Friday, 13 September 2013

IComparable<> inheritance in SortedDictionary

[Test]
public void Test()
{
  var dic = new SortedDictionary<BaseClass, string>();
  dic.Add(new BaseClass(){Number = 1}, "");
  dic.Add(new ExtendClass(){Text = "One"}, "");
 
  Assert.True(dic.ContainsKey(new BaseClass() { Number = 1 }));
  Assert.False(dic.ContainsKey(new BaseClass() { Number = 2 }));
  Assert.True(dic.ContainsKey(new ExtendClass() { Text = "One" }));
  Assert.False(dic.ContainsKey(new ExtendClass() { Text = "Two" }));
}
 
public class BaseClass : IComparable<BaseClass>
{
  public int Number { get; set; }
 
  public virtual int CompareTo(BaseClass other)
  {        
    return Number.CompareTo(other.Number);
  }
}
 
public class ExtendClass : BaseClass, IComparable<ExtendClass>
{
  public string Text { get; set; }
 
  public override int CompareTo(BaseClass other)
  {
    var other2 = other as ExtendClass;
    return other2 == null ? base.CompareTo(other) : CompareTo(other2);
  }
 
  public int CompareTo(ExtendClass other)
  {        
    return Text.CompareTo(other.Text);
  }
}

Tuesday, 10 September 2013

Exception handling in multithreaded C#

try
{
  Parallel.Invoke(
    () =>
    {
      Console.WriteLine("Starting Job 1..");
      Thread.Sleep(3*1000);
      Console.WriteLine("Starting Job 1.. SUCCESS");
    },
    () =>
    {
      Console.WriteLine("Starting Job 2..");
      throw new Exception("Job 2 Failed");
    }
  );
}
catch (AggregateException ex)
{
  Console.WriteLine(ex);
  foreach (var innerEx in ex.InnerExceptions)
  {
    Console.WriteLine(innerEx);
  }        
}

How to find PID of Windows Service

sc queryex <servicename>