Thursday, 14 May 2009

C# Indexer example

public class SampleIndexer
{
private readonly Dictionary<string,Dictionary<string, string>> list = new Dictionary<string,Dictionary<string, string>>();

public SampleIndexer()
{
list.Add("One",new Dictionary<string, string>());
list.Add("Two", new Dictionary<string, string>());
}

public void Add(string name, string key, string value)
{
list[name].Add(key,value);
}

public Dictionary<string,string> this[string name]
{
get
{
return list[name];
}
}

public string this[string name, string key]
{
get
{
return list[name][key];
}
}
}

[TestFixture]
public class TestIndexer{

[Test]
public void Test()
{
SampleIndexer indexer = new SampleIndexer();
indexer.Add("One","key1","value1");
indexer.Add("Two","key2","value2");

Console.WriteLine(indexer["One"]["key1"]);
}
}

C# String.Format("{0}", "formatting string")

Good summary of the String.Format("{0}", "formatting string")

C# Latch implementation

This is a c# Latch implementation for multithreaded applications (equivalent to java CountDownLatch).

It’s used in a situation when you have a one thread waiting for a number of other threads to finish.

The Test below also uses a Semaphore to run only a specific number of child threads at one time.

public class Latch
{
private readonly object locker = new object();
private int count;

public Latch(int noThreads)
{
lock (locker)
{
count = noThreads;
}
}

public void Await()
{
lock (locker)
{
while (count > 0)
{
Monitor.Wait(locker);
}
}
}

public void CountDown()
{
lock (locker)
{
if (--count <= 0)
{
Monitor.PulseAll(locker);
}
}
}

public int GetCount()
{
lock (locker)
{
return count;
}
}
}

[TestFixture]
public class TestLatch
{
static Latch latch = new Latch(5);
private Random random = new Random();
static Semaphore semaphore = new Semaphore(3,3);

public void Test()
{
for(int i=0;i<5;i++)
{
new Thread(RunIt).Start();
}
Console.WriteLine("Waiting for all threads to finish..");
latch.Await();
Console.WriteLine("All Threads completed.");
}

public void RunIt()
{
semaphore.WaitOne();
int waitTime = random.Next(5000);
Console.WriteLine("Running job {0}", waitTime);
Thread.Sleep(waitTime);
Console.WriteLine("Completed.");
semaphore.Release();
latch.CountDown();
}
}

Wednesday, 6 May 2009

ClickOnce Expired Certification Solution

RenewCert is a solution to Microsoft VS2005 ClickOnce deployment certification problem when it expires after one year. More info about the problem can be found on Microsoft website http://support.microsoft.com/kb/925521