Tuesday, 29 November 2011

Partial methods

I like to compare partial methods with abstract methods for easy understanding. Both method types don't declare body, but one exception is abstract methods needs to be implemented, but not partial methods need not be.


Consider below example

    public partial class MyPartial
    {
        partial void Add(int a, int b, ref int result);
    }

    public abstract class MyAbstract
    {
        public abstract int Add(int a, int b);
    }

    public partial class MyPartial
    {
        partial void Add(int a, int b, ref int result)
        {
            result = a + b;
        }
    }

    public abstract class MyImplementedAbstract : MyAbstract
    {
        public override int Add(int a, int b)
        {
            return a + b;
        }
    }

    Some glaring facts
    1. Partial method cannot return, but can take ref.
    2. Partial method cannot have access modifier, by default it is Private.
    3. If Partial methods are not declared, compiler ignores it.

    So where are these getting used

    1. Only scenario, i can think of is 'developing code generators'.

Wednesday, 23 November 2011

Hello World - Raven DB

I assume you have started Raven DB server @ localhost:8080.

class Program
{
        class Company
        {
            public string Id { get; set; }
            public string Name { get; set; }
            public string Location { get; set; }
        }

        class Employee
        {
            public string Id { get; set; }
            public string Name { get; set; }
            public string Location { get; set; }
        }


        // Demo the Store & SaveChanges
        static void Save()
        {
            using (var documentStore = new DocumentStore())
            {
                documentStore.Url = "http://localhost:8080/";
                documentStore.Initialize();
               
                using (var session = documentStore.OpenSession())
                {
                    session.Store(new Company { Location = "Bengaluru", Name = "MIC" });
                    session.Store(new Company { Location = "Virginia", Name = "TD" });

                    session.Store(new Employee { Location = "Bengaluru", Name = "Suresh Babu" });
                    session.Store(new Employee { Location = "Virginia", Name = "David Walker" });

                    session.SaveChanges();
                }
            }
        }

        static void Query()
        {
            using (var documentStore = new DocumentStore())
            {
                documentStore.Url = "http://localhost:8080/";
                documentStore.Initialize();

                using (var session = documentStore.OpenSession())
                {
                    var companyResults = session.Query().ToArray();
                    var employeeResults = session.Query().ToArray();

                    foreach (var result in companyResults)
                    {
                        Console.WriteLine("Company Name : {0}, Location : {1}, ID : {2}", result.Name, result.Location, result.Id);
                    }

                    foreach (var result in employeeResults)
                    {
                        Console.WriteLine("Employee Name : {0}, Location : {1}, ID : {2}", result.Name, result.Location, result.Id);
                    }
                }
            }
        }

        static void Load()
        {
            using (var documentStore = new DocumentStore())
            {
                documentStore.Url = "http://localhost:8080/";
                documentStore.Initialize();

                using (var session = documentStore.OpenSession())
                {
                    var companyResult = session.Load("companies/1");
                    var employeeResult = session.Load("employees/1");

                    Console.WriteLine("Company Name : {0}, Location : {1}, ID : {2}",
                                        companyResult.Name, companyResult.Location, companyResult.Id);
                    Console.WriteLine("Employee Name : {0}, Location : {1}, ID : {2}",
                                        employeeResult.Name, employeeResult.Location, employeeResult.Id);

                    companyResult = session.Load("companies/2");
                    employeeResult = session.Load("employees/2");

                    Console.WriteLine("Company Name : {0}, Location : {1}, ID : {2}",
                                        companyResult.Name, companyResult.Location, companyResult.Id);
                    Console.WriteLine("Employee Name : {0}, Location : {1}, ID : {2}",
                                        employeeResult.Name, employeeResult.Location, employeeResult.Id);
                }
            }
        }

        static void LuceneQuery()
        {
            using (var documentStore = new DocumentStore())
            {
                documentStore.Url = "http://localhost:8080/";
                documentStore.Initialize();

                using (var session = documentStore.OpenSession())
                {
                    var companyResults = session.Advanced.LuceneQuery("CompanyLocationIndex")
                                            .Where("Location:Virginia").ToArray();
                    var employeeResults = session.Advanced.LuceneQuery("EmployeeNameIndex")
                                            .Where("Name:\"David Walker\"")
                                            .WaitForNonStaleResults()
                                            .ToArray();

                    foreach (var result in companyResults)
                    {
                        Console.WriteLine("Company Name : {0}, Location : {1}, ID : {2}", result.Name, result.Location, result.Id);
                    }

                    foreach (var result in employeeResults)
                    {
                        Console.WriteLine("Employee Name : {0}, Location : {1}, ID : {2}", result.Name, result.Location, result.Id);
                    }
                }
            }
        }

        static void CreateIndex()
        {
            using (var documentStore = new DocumentStore())
            {
                documentStore.Url = "http://localhost:8080/";
                documentStore.Initialize();

                documentStore.DatabaseCommands.PutIndex("EmployeeNameIndex",
                            new IndexDefinitionBuilder
                            {
                                Map = employees => from employee in employees
                                                   select new { employee.Name }
                            }
                            );

                documentStore.DatabaseCommands.PutIndex("CompanyLocationIndex",
                            new IndexDefinitionBuilder
                            {
                                Map = companies => from company in companies
                                                   select new { company.Location }
                            }
                            );
            }
        }

        static void Main(string[] args)
        {
            Save();
            Query();
            Load();
            CreateIndex();
            LuceneQuery();
        }
    }


'Unknown' or 'NotFound' enum values

As per Jon Skeet's opinion, we should get away with 'Unknown' or 'NotFound' enum values and move towards nullable type, certainly it makes sense to me.


public enum UserStatus
        {
            Enabled,
            Disabled,
            DosUser
        }

        static UserStatus? GetUserStatus(int i)
        {
            return (i.Equals(0) ? UserStatus.Disabled : (UserStatus?) null);
        }

        static void Main(string[] args)
        {
            UserStatus? userStatus1 = GetUserStatus(0);
            UserStatus? userStatus2 = GetUserStatus(1);

            Console.WriteLine(userStatus1.HasValue );
            Console.WriteLine(userStatus2.HasValue);
        }

Monday, 21 November 2011

Access Point Names(APN)

This is just for my reference
This article explains what is APN,  basically it is gateway to external networks for a mobile device. Those external network could be internet or private network.

So how can i figure my APN settings(my HTC HD2 win6.5)


settings - all settings - connections - connections


Wednesday, 16 November 2011

Better ways to validate using Func

public class Movie
    {
        public string Title { get; set; }

        public int ReleaseYear { get; set; }

        public int Length { get; set; }
    }

    public static class MovieValidator
    {
        public static bool IsValid1(Movie movie)
        {
            if (movie.Title.IsNullOrWhiteSpace()) return false;

            if (movie.ReleaseYear < 1900) return false;

            if (movie.Length <= 0) return false;

            return true;
        }

        public static bool IsValid2(Movie movie)
        {
            Func[] rules =
                                {
                                    m => m.Title.IsNotNullOrWhiteSpace(),
                                    m => m.Length > 0,
                                    m => m.ReleaseYear > 1900
                                };

            return rules.All(rule => rule(movie));
        }

        public static bool IsNullOrWhiteSpace(this string value)
        {
            return string.IsNullOrEmpty(value) || value.Length.Equals(0);
        }

        public static bool IsNotNullOrWhiteSpace(this string value)
        {
            return !value.IsNullOrWhiteSpace();
        }
    }

Named Parameters, Extension methods and Fluent API's

Let's see how above three techniques help us to write a better code

    public interface ITask
    {
    }

    public class CopyFile : ITask
    {
    }

    public class ScheduledTask
    {
        public ScheduledTask(ITask task, TimeSpan runEvery, TimeSpan expiresOn)
        {
            this.Task = task;
            this.RunEvery = runEvery;
            this.ExpiresOn = expiresOn;
        }

        public ITask Task { get; set; }

        public TimeSpan RunEvery { get; set; }

        public TimeSpan ExpiresOn { get; set; }
    }

    public static class Worker
    {
        public void DoWork()
        {
            //var task = new ScheduledTask(new CopyFile(),
            //                    runEvery : new TimeSpan(0,0,5),
            //                    expiresOn : new TimeSpan(0,0,5));

             var task = new ScheduledTask(new CopyFile(),
                                runEvery : 2.Minutes(),
                                expiresOn : 3.Days());

             var completed = 2.Minutes().Ago();
        }

        public static TimeSpan Minutes(this int value)
        {
            return new TimeSpan(0, 0, value, 0);
        }

        public static TimeSpan Days(this int value)
        {
            return new TimeSpan(value, 0, 0, 0, 0);
        }

        public static DateTime Ago(this TimeSpan value)
        {
            return DateTime.Now - value;
        }
    }

Get list of all countries

        public static List GetCountryList()
        {
            //create a new Generic list to hold the country names returned
            List cultureList = new List();

            //create an array of CultureInfo to hold all the cultures found, these include the users local cluture, and all the
            //cultures installed with the .Net Framework
            CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);

            //loop through all the cultures found
            foreach (CultureInfo culture in cultures)
            {
                if(CultureInfo.InvariantCulture.Equals(culture))
                {
                    continue;
                }
                //pass the current culture's Locale ID (http://msdn.microsoft.com/en-us/library/0h88fahh.aspx)
                //to the RegionInfo contructor to gain access to the information for that culture
                RegionInfo region = new RegionInfo(culture.LCID);

                //make sure out generic list doesnt already
                //contain this country
                if (!(cultureList.Contains(region.DisplayName)))
                    //not there so add the EnglishName (http://msdn.microsoft.com/en-us/library/system.globalization.regioninfo.englishname.aspx)
                    //value to our generic list
                    cultureList.Add(region.TwoLetterISORegionName);
            }
            return cultureList;
        }

Tuesday, 15 November 2011

operator, implicit, explicit

'operator' keyword is used to overload a built-in operator or user defined conversions[straight from msdn].

A simple example.....

public class Money
    {
        public Money():this(0, "GBP")
        {
        }

        public Money(double value):this(value, "GBP")
        { }

        public Money(double value, string currency)
        {
            this.Value = value;
            this.Currency = currency;
        }

        public double Value { get; set; }

        public string Currency { get; set; }

        public override string ToString()
        {
            return Value.ToString() + Currency;
        }

        public static Money operator +(Money arg1, Money arg2)
        {
            if (arg1.Currency.Equals(arg2.Currency))
            {
                return new Money(arg1.Value + arg2.Value, arg1.Currency);
            }

            return null;
        }

        public static Money operator -(Money arg1, Money arg2)
        {
            if (arg1.Currency.Equals(arg2.Currency))
            {
                return new Money(arg1.Value - arg2.Value, arg1.Currency);
            }

            return null;
        }

        public static explicit operator double(Money money)
        {
            return money.Value;
        }

        public static implicit operator Money(double value)
        {
            return new Money(value);
        }
    }
------------------------------------------------

static void Main(string[] args)
{
            Money money1 = new Money(10.50);
            Money money2 = new Money(21.50);
            Money money3 = 23.50;

            Console.WriteLine((money1 + 10.50).ToString());
            Console.WriteLine((money1 + money2).ToString());
            Console.WriteLine((money2 - money1).ToString());
            Console.WriteLine((double)money1);
            Console.WriteLine(money3);
}

outputs

21GBP
32GBP
11GBP
10.5
23.5GBP
Press any key to continue . . .

Access Modifiers

1. So these are - Private, Protected, Internal, ProtectedInternal and Public.
2. Class/Struct can have Internal(default)/Public.
3. Struct members (nested class & structs etc) can have - Private(default), Internal and Public.
4. Class members (nested class & structs etc) can have - Private(default), Protected, Internal, ProtectedInternal and Public.
5. Default Access modifier for class constructor is - protected.
6. Friend assemblies - InternalsVisibleToAttribute.
7. Derived classes cannot have greater accessibility than their base types. In other words, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.
8. Destructors cannot have accessibility modifiers.

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/