Tuesday, 15 November 2011

Private nested class

Why?
1. Framework, implements IEnumerable pattern as nested class. Of course these type of class has no other purpose other than parent class needs.

class MyUselessList : IEnumerable {
// ...
private List internalList;
private class UselessListEnumerator : IEnumerator {
private MyUselessList obj;
public UselessListEnumerator(MyUselessList o) {
obj
= o;
}
private int currentIndex = -1;
public int Current {
get
{ return obj.internalList[currentIndex]; }
}
public bool MoveNext() {
return ++currentIndex < obj.internalList.Count;
}
}
public IEnumerator GetEnumerator() {
return new UselessListEnumerator(this);
}
}
2. A fully lazy implementation for Singleton pattern(http://suresh-anothernetprogrammer.blogspot.com/2011/11/singleton.html)

3. to continue:):):)

Thursday, 10 November 2011

Idea1 - Avoid Switch/If conditions

While developing a web service, i came across a scenario where i need to create a Factory pattern to instantiate a Response class based on the Request string.

For example, if the Request is 'AuthenticateUserRequest', i need to create 'AuthenticateUserResponse'.

So i started writing an switch case like below

switch(requestName)
{
case "AuthenticateUserRequest":
return new AuthenticateUserResponse();
}

soon the method grows big, and i wanted to avoid this.

so i declared an dictionary with key value pair, with key being the request name and value being the response being the corresponding response class.

so it becomes

Dictionary responses = new Dictionary
{
{"AuthenticateUserRequest", new AuthenticateUserResponse()},
{"CreateOrderRequest", new CreateOrderResponse() }
};

-----
return responses[requestName].value.Clone();

Tuesday, 8 November 2011

Singleton Pattern

What is beforefieldinit?

1. All classes with static constructors will NOT be marked as 'beforefieldinit'
2. When a class is marked as 'beforefieldinit', then type initialization may be eager or lazy. So what i mean by this is

EAGER
using System;

class Test
{
public static string x = EchoAndReturn ("In type initializer");

public static string EchoAndReturn (string s)
{
Console.WriteLine (s);
return s;
}
}

class Driver
{
public static void Main()
{
Console.WriteLine("Starting Main");
// Invoke a static method on Test
Test.EchoAndReturn("Echo!");
Console.WriteLine("After echo");
// Reference a static field in Test
string y = Test.x;
// Use the value just to avoid compiler cleverness
if (y != null)
{
Console.WriteLine("After field access");
}
}
}

OUTPUT
In type initializer
Starting Main
Echo!
After echo
After field access
--------------------------------------------------
LAZY
Starting Main
Echo!
After echo
In type initializer
After field access

3. If the class 'Test' have static constructor, then only below output is possible
Main
In type initializer
Echo!
After echo
After field access

So what we understand from above points, when we have static constructor - then the type initializers called when instance/static members or functions are called on that type. If not, we can't guarantee, as type initializer might be eager or lazy.
---------------------------------------------------------------------------------
So 'readonly' fields can be initialized while declaring or in constructor, so 'static readonly' are initialized during declaration or static constructor. it also tells, reference can't be changed - means only one reference.

So

public sealed class Singleton
{
public static readonly Singleton instance = new Singleton();

static Singleton()
{
}

Singleton()
{
}
}

and

public sealed class Singleton
{
public static readonly Singleton instance;

static Singleton()
{
instance = new Singleton();
}

Singleton()
{
}
}
------------------------------------------------------
and full lazy initialization

public sealed class Singleton
{
private Singleton()
{
}

public static Singleton Instance
{
get
{
return NestedSingleton._instance;
}
}

private class NestedSingleton
{
static NestedSingleton()
{ }

public static readonly Singleton _instance = new Singleton();
}
}

So why fully lazy initialization?
because static constructor called when static fields are initializes(bit uncontrolled), so for expensive constructor operation + better control, lazy loading is perfect

Double Checked Locking

All these years, i believed double checked locking is the best solution for Singleton pattern over simple thread safe code using 'lock'.

So what is double checked loading

static Instance instance = null;

if(instance is not null)
{
lock(key)
{
if(instance is not null)
{
instance = new Instance();
}
}
}

return instance;


So why this is not advised

1. Some compiler creates statements as such, the value is initialized even before the constructor completes. So instance may not be null, even before 'new Instance()' completes, hence we get into issues.
2. To solve this make instance as volatile.

http://en.wikipedia.org/wiki/Double-checked_locking
http://www.yoda.arachsys.com/csharp/singleton.html

Thank god, i stand corrected now

So what is volatile - Historically it means the decorated variable can be modified by OS, threads etc, and disallows compiler from making optimizations
for example -

class Test
{
    static int foo;

    static void Main()
    {
        //new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start();

        while (foo != 255) ; //this might be optimized to while(true); because
                             //foo is not updated anywhere -  but it might have been
                             //by other system or threads etc. 
        Console.WriteLine("OK");
    }
}
 
in C#,it means any writes is immediately flushed into memory(from Thread's Cache),
and when read it is always read from memory instead of cache.
 
http://en.wikipedia.org/wiki/Volatile_variable
http://stackoverflow.com/questions/133270/how-to-illustrate-usage-of-volatile-keyword-in-c-sharp
http://msdn.microsoft.com/en-us/library/x13ttww7%28v=vs.71%29.aspx  

UAC in Windows 2003

This is just for my reference

If we face UAC errors in windows 2003 machine

http://social.msdn.microsoft.com/Forums/en/windowssecurity/thread/40dd94a9-2b52-4f60-a3fc-653ddf4bc306

UAC - Important settings

Admin Approval Mode for the Built-in Administrator account: Enabled (if UAC needed). Disabled means – full privilege.
Switch to the secure desktop when prompting for elevation: Enabled, can’t select anything in background.

Run all administrators in Admin Approval Mode: Enabled (if UAC needed). Disabled means – full privilege.

Only elevate executable that are signed and validated: Disabled (as it expects exe’s to have PKI certificates).

Detect application installations and prompt for elevation: Enabled, so installation will be prompt for elevation.

Friday, 4 November 2011

Installing SQL Server 2008 R2 Management Studio Express on 64bit machines

This is for my reference - http://tchmiel.wordpress.com/2010/07/01/installing-sql-server-2008-r2-management-studio-express-on-windows-7-64bit-sharepoint-development-box/