среда, 28 апреля 2010 г.

вторник, 27 апреля 2010 г.

Итераторы, yield.

Что может быть лучше хорошего примера?
По ссылке ниже на примерах показано использование итераторов. Просто и понятно.

Использование итераторов (Руководство по программированию в C#)

понедельник, 26 апреля 2010 г.

GC, Filalize, IDisposable

first GC. Collect() - Finalization Queue -> F-reachable Queue -> Finalize() - > delete on second GC. Collect().

IDisposable: try/finally => using => call Dispose() for using object.

Статья о GC.


Есть три причины, вызывающих запуск процесса сборки мусора:

  1. При очередном выделении памяти GC замечает, что превышен размер нулевого поколения.
  2. Приложение самостоятельно вызывает метод GC.Collect().
  3. Нехватка памяти в ОС.

Patterns & practices – Microsoft Enterprise Library

Patterns & practices – Microsoft Enterprise Library
http://entlib.codeplex.com/

The Microsoft Enterprise Library is a collection of reusable software components (application blocks) designed to assist software developers with common enterprise development challenges. Application blocks are provided as source code plus documentation that can be used "as is," extended, or modified by developers to use on complex, enterprise-level line-of-business development projects.

четверг, 22 апреля 2010 г.

Паттерны проектирования

Обзор паттернов проектирования
http://citforum.ru/SE/project/pattern/

Шаблоны проектирования

Generic Constraint Meaning in Life

Generic Constraint Meaning in Life
where T : struct Тип параметра должен быть System.ValueType в цепочке наследования.

where T : class The type parameter must not have System.ValueType in its chain of inheritance (e.g., must be a reference type).

where T : new() default constructor.
This is The type parameter must have a very helpful if your generic type must create an instance of the type parameter,
as you cannot assume the format of custom constructors. Note that this constraint must be listed last on a multiconstrained type.

where T : NameOfBaseClass derived from the class specified The type parameter must be by NameOfBaseClass.

where T : NameOfInterface The type parameter must implement the interface specified by NameOfInterface.
Multiple interfaces can be separated as a comma-delimited list.
When constraints are applied using the where keyword, the constraint list is placed after the generic type’s base class and interface list.
By way of a few concrete examples, consider the following constraints of a generic class named MyGenericClass:
/ MyGenericClass derives from Object, while
// contained items must have a default ctor.

public class MyGenericClass where T : new()
{...}

// MyGenericClass derives from Object, while
// contained items must be a class implementing IDrawable
// and support a default ctor.

public class MyGenericClass where T : class, IDrawable, new()
{...}

// MyGenericClass derives from MyBase and implements ISomeInterface,
// while the contained items must be structures.

public class MyGenericClass : MyBase, ISomeInterface where T : struct
{...}

On a related note, if you are building a generic type that specifies multiple type parameters,
you can specify a unique set of constraints for each:

// must have a default ctor, while must
// implement the generic IComparable interface.

public class MyGenericClass where K : new() where T : IComparable
{...}

среда, 21 апреля 2010 г.

Полезности аля NUnit и ReSharper

NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit.
http://www.nunit.org/

Developer Productivity Tool for Microsoft Visual Studio

http://www.jetbrains.com/resharper/

понедельник, 19 апреля 2010 г.

MS SQL , Current DateTime

Варианты получения текущей даты-времени:

SELECT CURRENT_TIMESTAMP
GO

SELECT {fn NOW()}
GO

SELECT GETDATE()
GO

вторник, 13 апреля 2010 г.

Акцессоры по-умолчанию

Interface - public (иное невозможно)
Enum - public (иное невозможно)
Struct - private ( возможны public, internal)
Class - internal
Field - private
Method - private
Property - private
Конструктор - public
_________________________
Всегда указывайте акцессор! Это хороший стиль.

Простая и безопасная реализация многопоточности в Windows Forms

Простая и безопасная реализация многопоточности в Windows Forms

Использовать стоит код, приведенный в третьей части статьи.
А во второй части, кстати, код не рабочий. Не работает остановка рабочего потока с использованием out параметров в методе отображения прогресса. Постоянно теряется значение. Но если сделать метку Cancel не bool, а object, то в таком случае код будет работать.
Собственно это замечание и указано в конце второй части статьи о многопоточности, и третья часть как раз есть реализация этой идеи.

пятница, 9 апреля 2010 г.

Pex and Moles - Isolation and White box Unit Testing for .NET

Pex and Moles - Isolation and White box Unit Testing for .NET

Инструмент для Visual Studio 2010, позволяющий автоматизировать процесс создания тестов по шаблонам типа Isolation и White box.

Isolation testing - базируется на принципе того, что каждый тест не должен влиять на другие, то есть должен быть изолированным.
White box testing - структурное тестирование, заключающееся в проверке внутренней структуры элементов системы.

Один экземпляр приложения

namespace SyncServiceController
{
static class Program
{
[STAThread]
static void Main()
{
bool onlyInstance;

Mutex mtx = new Mutex(true, "SyncServiceController", out onlyInstance);

if (onlyInstance)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}

}
}

Visual Studio, Web, Intellisence not work

Столкнулся с проблемой, когда открыв в Visual Studio Web-проект обнаружил, что на странице ASPX не работает Intellisence. Теги серверных контролов подсвечиваются с ошибкой валидации. Причем проект сам рабочий, но момент как для разработчика не очень приятный.

Ответ был найден на портале http://forums.asp.net
"В QUOTING FROM THE BLOG OF From Mikhail Arkipov (AND NOT THE SAME GOES FOR VS 2008)

I blogged earlier that in VS 2005 we switched from using static XML schemas to automatically generating them using reflection on Web controls. XML schemas are generated on demand as you open pages in your Web site. They contain information about ASP.NET controls, custom and user controls. You can find generated files cacheВ in

C:\Documents and Settings\[Username]\Application Data\Microsoft\VisualStudio\8.0\ReflectedSchemas

So, the first thing you want to do if you see dreaded "'asp' is an unrecognized tag prefix or device filter" error is to close all VS instances and then delete the folder contents. Restart VS, open your Web site and we will generate schemas again."

То есть вам в случае подобных сбоев следует очистить содержимое папок
ReflectedSchemas
ReflectedTypeLibs
которые располагаются
1. WindowsXP: C:\Documents and Settings\[Username]\Application Data\Microsoft\VisualStudio\[#.#]
2. Windows7: C:\Users\[Username]\AppData\Roaming\Microsoft\VisualStudio\[#.#]

вторник, 6 апреля 2010 г.

Windows Service and StartPath

Путь к стартовой папке Windows Service:

private string StartPath
{
get
{
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
}
}