Tuesday, 13 December 2011

SQL - Parse array of guid's Xml

drop PROCEDURE ParseList
go

CREATE PROCEDURE ParseList @list xml AS
   BEGIN
        DECLARE @Ids TABLE(Id uniqueidentifier)
        INSERT INTO @Ids
        SELECT T.Ids.value('.', 'uniqueidentifier') FROM @list.nodes('/ArrayOfGuid/guid') AS T(Ids)
        SELECT * FROM @Ids
    END
GO

EXEC ParseList
N'
        699f9527-1f9d-4a00-937b-a7637b0a8c03
        f766e5fb-27a7-4171-bf0c-c0e093baed27
        c22b2aa6-541e-495f-b315-233c0ed0e7a7
        ccf83d1e-5809-4214-a5a9-416ce22e62ca
     
'
go

Tuesday, 6 December 2011

GetHashCode

We basically use hash functions for Data integrity, faster look up etc.
Imagine doing a 'foreach' to look up an item in a hundred of thousands of List, it will certainly hamper the performance. One alternative is to use hashes to create something called _buckets_ of List. Essentially, it means List[] instead of List. Eric's article explains this, and he lists down all the guidelines for using GetHashCode, and i try to summarize below

1. Equal items should have equal hash.

Class Employee
{
      Public int Name { get; set; }
}

Employee suresh1 = new Employee { Name = "Suresh" };
Employee suresh2 = new Employee { Name = "Suresh" };

Ideally suresh1.GetHashCode() == suresh2.GetHashCode()
[Normally this is not the case, because String.GetHashCode will return different hash for same value, but the point here is we need to modify the GetHashCode()]

if this didn't return same value, ContainsKey will fail due to look up on different bucket than it is originally stored.

2. GetHashCode on a type should be based on its immutable fields or it's value should never change, if possible. At least it should not change while it is contained on a data structure based on hashing like Dictionary/HashSet/HashTable etc.

3. Should never throw exception.

4. Should be really fast.

5. Logically related records are physically stored together, but randomly. If we are going to store clustered data in a same bucket, it will affect performance as other buckets will never be used. So this needs to be random.

6. It is often suggested to use Big prime numbers while calculating Prime numbers instead of XOR.

int hash = 13;
hash = (hash * 7) + field1.GetHashCode();
hash = (hash * 7) + field2.GethashCode();
...
return hash;
 

7. Hash Collision - If two items have same hash code, it means they are equal(Rule 1), but not always. Hence we need to override equals() or  IEqualityComparer

Some useful stuffs

http://blogs.msdn.com/b/ericlippert/archive/2010/03/22/socks-birthdays-and-hash-collisions.aspx
http://msdn.microsoft.com/en-us/library/ms379571%28VS.80%29.aspx#datastructures20_2_topic5
http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c
http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode#263416
http://stackoverflow.com/questions/638761/c-gethashcode-override-of-object-containing-generic-array/639098#639098

Readonly vs Thread safe

Interesting article from Eric, basically we should not assume read only operations unless documented. In above article, read only operation mutates the structure for performance.

Friday, 2 December 2011

Primitive Types, Value Types and Reference Types

Just for my reference, good article

Signalling Threads

I am just trying to summarize what i learned over a period of time regarding Thread Signalling.

To put it in simple words, a thread might signal about something that might be of interest to other threads. For example, an Order Thread(OT) might signal that it created order in the database, so the Email Thread(ET) can pull certain details like total, email etc to mail _Confirmation_ to the customer. Also a Report Thread(RT) might be interested(to create something called _Order Total Today_). I am not going to discuss why this needs to be done asynchronously(then there is no point in creating this article :)).

In .Net there are various ways in which we can do thread signalling, but we can broadly categorize this into two types

1. Thread signalling within the process
2. Thread signalling across the process's

AutoResetEvent and ManualResetEvent belongs to Category 1
EventWaitHandle, Semaphore and Mutex belongs to Category 2

We take a moment to understand Thread Signalling and Thread Synchronization. Thread Synchronization, allows serialized access to a shared resource. So lock, Monitor, ReadWriterLock, ReadWriterLockSlim and Interlocked are such examples. We can even use Thread Synchronization for signalling(in fact they internally have to do some kind of signalling, but Thread signalling classes provides better API's). But having said that Thread Signalling is a kind of Thread Synchronization, in my Order example threads signal for synchronized access to database(in case of ET & RT).

wrt Thread Signalling, when a thread signals - it means 'I am done'. We can say a thread's flowchart will look like Wait->Lock->Act->Signal. So all signalling classes will helps us do the _last step_ depending upon the scenario.

EventWaitHandle - Threads can rely on WaitOne() to wait for any signals. Thread should call Set() to signal that it is done. So if more than one thread called WaitOne(), will all they be able to proceed further? Yes, in case of ManualResetEvent, No incase of AutoResetEvent. If we don't want all the threads to proceed, we need to call Reset()(which is called automatically for AutoResetEvent).

What else is the difference between Manual & Auto(copied)

It's like the difference between a tollbooth and a door. The ManualResetEvent is the door, which needs to be closed (reset). The AutoResetEvent is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.

Note : Signaled State - threads can proceed further
           Non-signaled State - threads are blocked

EventWaitHandle, Semaphore and Mutex - all can create 'named wait handles' hence it can be accessed across process. If we want to open 'named wait handles', we need to call 'OpenExisting()'

Semaphore(from Wikipedia) - 

Suppose a library has 10 identical study rooms, intended to be used by one student at a time. To prevent disputes, students must request a room from the front counter if they wish to make use of a study room. When a student has finished using a room, the student must return to the counter and indicate that one room has become free. If no rooms are free, students wait at the counter until someone relinquishes a room.
The librarian at the front desk does not keep track of which room is occupied, only the number of free rooms available. When a student requests a room, the librarian decreases this number. When a student releases a room, the librarian increases this number. Once access to a room is granted, the room can be used for as long as desired, and so it is not possible to book rooms ahead of time.

So here we can set initial count(no of rooms free) & maximum rooms using 'new Semaphore(0, 10)'. Students can request for a room using WaitOne() and vacate using ReleaseOne(). So 'new Semaphore(0, 10)', means 10 students will be allocated rooms immediately, but more than that only depending upon on room vacation.

Mutex - Similar to any thread synchronization techniques like lock/monitor etc. WaitOne() & ReleaseMutex() are used correspondingly. Important point is 'AbandonedMutexException'. When thread aborts or killed abruptly without releasing the Mutex, further threads calling 'WaitOne()' will experience this exception. So it is better ti have try catch for this kind of exception when dealing with Mutex.

Before i close, i want to touch on 'immutability', this is an important concept on thread synchronization. Immutable class means, it's state cannot be changed once created. This allow us to just share reference of the object across threads without worry as threads can't change the state of the object.

Hope this if of some use.

Thursday, 1 December 2011

Mutex - Good pattern?

Just for my reference

http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567#229567

This below link for creating a single instance application(referencing it to 'ReleaseMutex' method should force the garbage collector to leave it alone)
http://stackoverflow.com/questions/777744/how-can-i-check-for-a-running-process-per-user-session

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/

Friday, 21 October 2011

Static Reflection

Here is my example on static reflection(i have used INotifyPropertyChanged, but a simple code as i don't pass around the interface)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.ComponentModel;

namespace StaticReflection
{
public class Customer : INotifyPropertyChanged
{
private string employer = String.Empty;
private string mobile = String.Empty;

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}

public string Employer
{
get { return this.employer; }
set
{
if (value != this.employer)
{
this.employer = value;
NotifyPropertyChanged(this.PropertyName(c => c.Employer));
}
}
}

public string Mobile
{
get { return this.mobile; }

set
{
if (value != this.mobile)
{
this.mobile = value;
NotifyPropertyChanged(this.PropertyName(c => c.Mobile));
}
}
}
}

public static class CustomerExtensions
{
public static string PropertyName(this Customer target, Expression<Func<Customer, object>> expression)
{
return new PropertySpecifier<Customer>(expression).PropertyName;
}
}

public class PropertySpecifier<T>
{
//http://joelabrahamsson.com/entry/getting-property-and-method-names-using-static-reflection-in-c-sharp - Use this article to build a accomplished! PropertySpecifier function
public PropertySpecifier(Expression<Func<T, object>> expression)
{
if (expression == null) return;

if (expression.Body is MemberExpression)
{
this.PropertyName = (expression.Body as MemberExpression).Member.Name;
}
}

public string PropertyName
{
get;
set;
}
}
}

Wednesday, 28 September 2011

Create PDB always

For my reference
http://blogs.msdn.com/b/yash/archive/2007/10/12/pdb-files-what-are-they-and-how-to-generate-them.aspx

Project > Properties > Build > Advanced > Output > Debug Info
Always create PDB

Tuesday, 13 September 2011

Events vs Delegates

This rather confused me for a long time, but found a great article
http://blog.monstuff.com/archives/000040.html

Briefly

Events & Interfaces, Events Invocation, Event Signature and Event accessors

1. Events are ALWAYS multi-cast.
2. Events can be done away with delegates, but it is similar to exposing a Public member field than a Property.
3. Helps encapsulation - So interfaces don't support fields, but events - We can't declare delegate fields in Interface.

interface Temp
{
event EventHandler notify;
EventHandler eventHandler;
}


4. Only defined class can raise the event, but fields(delegates) can be raised outside of the class.
5. Standard signature of (sender, eventargs) - we can use EventHandler.
6. Event accessors - have add and remove - may be used for logging?

So my two cents with an example

public class MoneyWithdrawnEvent : EventArgs
{
public decimal Amount { get; set; }

public MoneyWithdrawnEvent(decimal amount)
{
this.Amount = amount;
}
}

public class BankService
{
public delegate void Notify(EventArgs e);
public event Notify amountWithdrawn;

public void Withdraw(decimal amount)
{
//Business
amountWithdrawn(new MoneyWithdrawnEvent(amount));
}
}

public class ATMService
{
IServiceFactory factory;

public ATMService(IServiceFactory factory)
{
}

public void Withdraw(decimal amount)
{
BankService service = factory.Create();

BankService.Notify notifyUser = new BankService.Notify(this.AlertUser);

notifyUser(new MoneyWithdrawnEvent(amount)); //This is wrong, as we don't the state(outcome) of the transaction, and
// allows this kind of business errors where alert before
// withdrawing money.
//service.amountWithdrawn(); 1. You can't invoke event, so it will be the responsiblity
// of bank to raise the money withdrawn.
service.Withdraw(amount);
}

private void AlertUser(EventArgs alert)
{
}
}

public interface IServiceFactory
{
BankService Create();
}

How to enable Hibernate

This is just for reference

start>run>"powercfg.exe /hibernate on"

Thursday, 14 July 2011

Create PFX with the Asymmetric keys genereated during CSR phase

This will not work with CNG(KSP)

Steps 1

1. When we create key/pair, store the KeyContainerName.
2. Sign CSR with created keys and get the certificate(one of CER/DER/PEM/CRT) format.
3. Open the certificate using x509certificate2 class, create CspParameter class. Assign the KeyContainerName to CspParamater class.
4. Create RsaCryptoProvider class using CspParamater, and assign it to PrivateKey of x509certificate2.
5. Using Export(pfx, password) option.
6. Clear RsaCryptoProvider using PersistCsp = false, and Clear().

Note
1. If you don't pass valid KeyContainerName, default will be created. But assigning to PrivateKey property will throw exception about Key mismatch(after all they are strongly related).
2. Clear the KeyContainer for better security purposes.

Sample code to get u started.

CspParameters p = new CspParameters();

p.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0";
p.ProviderType = 1;
p.KeyContainerName = "your container name";
p.KeyNumber = (int)AT_KEYEXCHANGE;

RSACryptoServiceProvider csp = new RSACryptoServiceProvider(p);

X509Certificate2 cer = new X509Certificate2("sss.cer");

cer.PrivateKey = csp;

byte[] bytes = cer.Export(X509ContentType.Pfx, "12345");

FileStream stream = new FileStream("CASigned.pfx", FileMode.CreateNew);

stream.Write(bytes, 0, bytes.Length);

stream.Close();

X509Certificate2 c1 = new X509Certificate2("CASigned.pfx", "12345");

bool value = c1.HasPrivateKey;

Wednesday, 13 July 2011

Certificate file types

Two types of encoding used in certificate

1. DER(Distinguished Encoding Rule) - DER encoded certificate.
2. PEM - Base64 encoded certificate - starts with BEGIN CERTIFICATE and ends with END CERTIFICATE.

Above can also used and extensions.

Common extensions
-----------------

1. CRT - Most common among *nix systems
2. CER - alternate form of .CRT (Microsoft Convention)

The only time CRT and CER can safely be interchanged is when the encoding type can be identical. (ie PEM encoded CRT = PEM encoded CER)

Monday, 4 July 2011

Respecting windows UAC while using LsaOpenPolicy

Please use POLICY_VIEW_LOCAL_INFORMATION = 1;

so your code will become

LsaOpenPolicy(SystemName, ref LSA_OBJECT_ATTRIBUTES,
(int)POLICY_VIEW_LOCAL_INFORMATION, out IntPtr)

Friday, 10 June 2011

Wix force install new msi

msiexec caches the installer, hence if you want to force executing new installer pls use

msiexec /fc installer.msi

This might be useful, because while developing you might have set installation conditions wrong, which might fire during un-installation as well, hence might block from doing so.

like




Above condition happens no matter what whether you are trying to install or uninstall.