tsJensen

A quest for software excellence...

Run Single Instance of Process Using Mutex

Recently I needed to assure that a process could not be started for a second time on the same machine. I had done this before with a mutex but rather than rummaging through old code on my own personal machine, I did the expedient thing and found this question on Stack Overflow.

I liked the answer as many others did and after a few minutes of tweaking came up with this useful adaptation. I share it here in part to help others but mostly to create a permanent “note to self” as this will surely come up again in the future.

private static void Main(string[] args)
{
  // assure only one instance running
  RunExclusively(() =>
  {
    // do your exclusive stuff
  });
}

static void RunExclusively(Action action)
{
  // global mutex to prevent multiple instances from being started
  // get application GUID as defined in AssemblyInfo.cs
  string appGuid = ((GuidAttribute)
           Assembly.GetExecutingAssembly()
           .GetCustomAttributes(typeof(GuidAttribute), false)
           .GetValue(0))
           .Value;

  // unique id for global mutex - Global prefix means it is global to the machine
  string mutexId = string.Format("Global\\{{{0}}}", appGuid);

  using (var mutex = new Mutex(false, mutexId))
  {
    // set security settings for mutex - allow everyone
    var allowEveryoneRule = new MutexAccessRule(
      new SecurityIdentifier(WellKnownSidType.WorldSid, null),
      MutexRights.FullControl, AccessControlType.Allow);
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);
    mutex.SetAccessControl(securitySettings);

    var hasHandle = false;
    try
    {
      try
      {
        // wait to acquire for up to five seconds
        if (!mutex.WaitOne(5000, exitContext: false))
        {
          throw new TimeoutException("Timeout waiting for exclusive access");
        }
      }
      catch (AbandonedMutexException)
      {
        // mutex abandoned in another process
        // it will still get acquired
        hasHandle = true;
      }
      action(); //execute work
    }
    finally
    {
      if (hasHandle) mutex.ReleaseMutex();
    }
  }
}

If you know of a better way or see any flaws in this one, please do share.

C# Basics: On the Importance of the Using Statement and IDisposable

The world of .NET programming is full of objects that implement the IDisposable interface. File, Font, DataContext, Stream, DbConnection, and many more—all implement the IDisposable interface. And for good reason. They touch the outside world and the outside world is messy, full of resource allocations that can only be used one at a time and must be explicitly returned to their owner to be used by another caller.

So in this 8th installment of C# Basics, let’s take a look at how best to use the IDisposable interface by simply using the using statement. The using statement is really just syntactic sugar but it helps you produce much more readable and reliable code.

using (var myobj = new MyDisposable())
{
  myobj.DoSomething();
}

You can even stack them like this:

using (var myobj = new MyDisposable())
using (var otherobj = new MyOtherDisposable())
{
  var x = myobj.DoSomething();
  otherobj.DoAnotherThing(x);
}

Of course, you could write your own resource cleanup explicitly, but it can start to look a bit messy and as lazy as we often are, the cleanup often gets forgotten.

var myobj = new MyDisposable();
var otherobj = new MyOtherDisposable();
try
{
  var x = myobj.DoSomething();
  otherobj.DoAnotherThing(x);
}
finally
{
  if (otherobj != null) otherobj.Dispose();
  if (myobj != null) myobj.Dispose();
}

Use the using statement where you can. It's not a one size fits all syntax sugar, but it is sweet where it fits.

C# Basics: const vs readonly vs static

In this 7th installment of C# Basics, I’m going to cover the differences between the modifiers const, readonly, and static, specifically in reference to class members where the developer wishes to use the fields or properties in client code that cannot change the value of that member.

To illustrate and discuss the differences between each modifier, I’ve put together a contrived set of classes with the least amount of code I can think to add in order to review and to examine the differences in the IL (intermediate language) taken from Ildasm.exe. (Visit this nice page to learn how to use Ildasm.exe from with Visual Studio.)

using System;

namespace ReadOnlyConstant
{
  public class MyConstOnly
  {
    // assigned at declaration and used at compile time only
    public const int Age = 20;
  }

  public class MyReadOnly
  {
    // can only be assigned in declaration or constructor
    public readonly int Age = 0;
    public MyReadOnly()
    {
      Age = 20;
    }
  }

  public static class MyStaticOnly
  {
    // can be assigned within class but "readonly" for client
    private static int _age = 20;
    public static int Age { get { return _age; } }
  }
}

The goal in each class above is to create a public field or member that can be read by client code but cannot be changed by client code. Looking through the IL produced by compiling this code can also be instructive even if you do not fully understand each and every IL instruction. Take a look here at these classes under the compiled covers and notice that the MyConstOnly class does not have a getter method to retrieve Age nor is it's value set in the .ctor but only noted by the compiler in the .field definition for use by the compiler later should client code use it. Then read through to the client code and see its IL code as well.

// =============== CLASS MEMBERS DECLARATION ===================

.class public auto ansi beforefieldinit ReadOnlyConstant.MyConstOnly
       extends [mscorlib]System.Object
{
  .field public static literal int32 Age = int32(0x00000014)
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method MyConstOnly::.ctor

} // end of class ReadOnlyConstant.MyConstOnly

.class public auto ansi beforefieldinit ReadOnlyConstant.MyReadOnly
       extends [mscorlib]System.Object
{
  .field public initonly int32 Age
  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       25 (0x19)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  ldc.i4.0
    IL_0002:  stfld      int32 ReadOnlyConstant.MyReadOnly::Age
    IL_0007:  ldarg.0
    IL_0008:  call       instance void [mscorlib]System.Object::.ctor()
    IL_000d:  nop
    IL_000e:  nop
    IL_000f:  ldarg.0
    IL_0010:  ldc.i4.s   20
    IL_0012:  stfld      int32 ReadOnlyConstant.MyReadOnly::Age
    IL_0017:  nop
    IL_0018:  ret
  } // end of method MyReadOnly::.ctor

} // end of class ReadOnlyConstant.MyReadOnly

.class public abstract auto ansi sealed beforefieldinit ReadOnlyConstant.MyStaticOnly
       extends [mscorlib]System.Object
{
  .field private static int32 _age
  .method public hidebysig specialname static 
          int32  get_Age() cil managed
  {
    // Code size       11 (0xb)
    .maxstack  1
    .locals init ([0] int32 CS$1$0000)
    IL_0000:  nop
    IL_0001:  ldsfld     int32 ReadOnlyConstant.MyStaticOnly::_age
    IL_0006:  stloc.0
    IL_0007:  br.s       IL_0009

    IL_0009:  ldloc.0
    IL_000a:  ret
  } // end of method MyStaticOnly::get_Age

  .method private hidebysig specialname rtspecialname static 
          void  .cctor() cil managed
  {
    // Code size       8 (0x8)
    .maxstack  8
    IL_0000:  ldc.i4.s   20
    IL_0002:  stsfld     int32 ReadOnlyConstant.MyStaticOnly::_age
    IL_0007:  ret
  } // end of method MyStaticOnly::.cctor

  .property int32 Age()
  {
    .get int32 ReadOnlyConstant.MyStaticOnly::get_Age()
  } // end of property MyStaticOnly::Age
} // end of class ReadOnlyConstant.MyStaticOnly

// =============================================================

You can read the MSDN full explanations of each modifier but here’s the basics:

const
Can only be assigned a value in declaration and can only be a value type or string. Use the const modifier when you KNOW the value won’t change. If you think it might change at a later date and your assembly is distributed as a compiled library, consider one of the other modifiers to assure that you don’t have a value you didn’t expect in your client code. (See use code sample below.)

readonly
Can assign a value at declaration or in the class constructor. It is important to note that if you use a reference type with modifiable members, your client code can still modify those members even if it cannot assign a value to the readonly reference. Note in the IL above that the initialization of the declared value occurs in the .ctor before the assignment in the .ctor, so if you are wondering which would be better, now you have some insight into that question.

static
Can assign the value of the private member anywhere within the class code. Note the initialization of the value in the static .ctor of the class. You could also assign the value in some other method later but with the public property implementing only a get, the client code cannot assign a value.

And here is the client code and it’s IL just below it. The most important point to note in the IL is that the client code is compiled with the const’s literal value, NOT a get to the class. This is why you must watch for the use of a const that could change with a new library. Make sure you compile your client code against that new library when you get it or you could be very sorry when the library is using one const compiled value and you’re using another.

namespace TestConsole
{
  class Program
  {
    static void Main(string[] args)
    {
      // compiler will replace with constant value
      // If the referenced assembly is changed to 40 and this is
      // not compiled again against that new assembly, the value
      // for mcoAge will still be 20. (See IL below.)
      int mcoAge = MyConstOnly.Age;

      MyReadOnly mro = new MyReadOnly();
      int mroAge = mro.Age;

      int msoAge = MyStaticOnly.Age;

      Console.WriteLine("{0} {1} {2}", mcoAge, mroAge, msoAge);
    }
  }
}

// output: 20 20 20

// and here is the IL with some of my own comments

// =============== CLASS MEMBERS DECLARATION ===================

.class private auto ansi beforefieldinit TestConsole.Program
       extends [mscorlib]System.Object
{
  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       53 (0x35)
    .maxstack  4
    .locals init ([0] int32 mcoAge,
             [1] class [ReadOnlyConstant]ReadOnlyConstant.MyReadOnly mro,
             [2] int32 mroAge,
             [3] int32 msoAge)
    IL_0000:  nop
    IL_0001:  ldc.i4.s   20   //NOTE: literal value assigned - no mention of MyConstOnly class
    IL_0003:  stloc.0
    IL_0004:  newobj     instance void [ReadOnlyConstant]ReadOnlyConstant.MyReadOnly::.ctor()
    IL_0009:  stloc.1
    IL_000a:  ldloc.1
    IL_000b:  ldfld      int32 [ReadOnlyConstant]ReadOnlyConstant.MyReadOnly::Age
    IL_0010:  stloc.2
    IL_0011:  call       int32 [ReadOnlyConstant]ReadOnlyConstant.MyStaticOnly::get_Age()
    IL_0016:  stloc.3
    IL_0017:  ldstr      "{0} {1} {2}"
    IL_001c:  ldloc.0
    IL_001d:  box        [mscorlib]System.Int32
    IL_0022:  ldloc.2
    IL_0023:  box        [mscorlib]System.Int32
    IL_0028:  ldloc.3
    IL_0029:  box        [mscorlib]System.Int32
    IL_002e:  call       void [mscorlib]System.Console::WriteLine(string,
                                                                  object,
                                                                  object,
                                                                  object)
    IL_0033:  nop
    IL_0034:  ret
  } // end of method Program::Main

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Program::.ctor

} // end of class TestConsole.Program

// =============================================================

C# Basics: Extension Methods and QDD vs TDD

In this sixth installment of C# Basics, I want to share a brief snippet of an extension method I’ve found useful that will introduce you to QDD as well. Quick and Dirty Design (QDD) is my name for having multiple tiny console application projects lying around in which I test little code snippets before putting them into something more serious. This is only necessary in projects in which TDD has not been used and no testing framework or tests are available for whatever reason.

But back to extension methods. From MSDN we learn:

“Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.”

As the MSDN article points out, the most common extension methods you may run into are the LINQ standard query operations. But don’t let that stop you from providing yourself with some very nice little extension methods like this one:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace IOTest
{
  class Program
  {
    static void Main(string[] args)
    {
      string phone1 = @"8015551212";
      string phone2 = @"(8a0d1d)d d5d5d5d-d1d2d1d2";

      if (phone1.StripNonNumeric() == phone2.StripNonNumeric())
        Console.WriteLine("true");
      else
        Console.WriteLine("false");

      Console.ReadLine();
    }
  }

  static class Ext
  {
    private static Regex nonNum = new Regex(@"[^0-9]");

    public static string StripNonNumeric(this string item)
    {
      return nonNum.Replace(item, string.Empty);
    }
  }
}

C# Basics: Symmetric Encryption with Rijndael

I often need to encrypt a string and then decrypt it. Sometimes its to move some value from one server to another without the benefit of SSL. So for the fifth installment of C# Basics, I’ll share the a generic version of a little encryption utility I’ve used many times and in many places.

Most Important: If you decide to use this code, be sure to change the key and vector text to something only you know. You might even want to use a hardware security module.

I like AES (formerly known as Rijndael, pronounced “rain-doll”) but you can pick your own algorithm. The code below will work with most of the .NET symmetric encryption algorithms.

using System;
using System.Security.Cryptography;
using System.Text;

namespace MyCrypt
{
  public static class Tokenizer
  {
    //create your own unique key and vector strings
    //maybe even lock them up and require a cert to get them out
    private const string keyText = @"The quick brown fox jumps";
    private const string vectorText = @"over the lazy dog.";
    private static byte[] key = null;
    private static byte[] vector = null;

    static Tokenizer()
    {
      key = GetMD5Hash(keyText);
      vector = GetMD5Hash(vectorText);
    }

    public static string Encrypt(string val)
    {
      if (string.IsNullOrWhiteSpace(val)) return null;
      RijndaelManaged rjm = new RijndaelManaged();
      rjm.KeySize = 128;
      rjm.BlockSize = 128;
      rjm.Key = key;
      rjm.IV = vector;
      byte[] input = Encoding.UTF8.GetBytes(val);
      byte[] output = rjm.CreateEncryptor()
        .TransformFinalBlock(input, 0, input.Length);
      string data = Convert.ToBase64String(output);
      return data;
    }

    public static string Decrypt(string val)
    {
      if (string.IsNullOrWhiteSpace(val)) return null;
      try
      {
        RijndaelManaged rjm = new RijndaelManaged();
        rjm.KeySize = 128;
        rjm.BlockSize = 128;
        rjm.Key = key;
        rjm.IV = vector;
        byte[] input = Convert.FromBase64String(val);
        byte[] output = rjm.CreateDecryptor()
          .TransformFinalBlock(input, 0, input.Length);
        string data = Encoding.UTF8.GetString(output);
        return data;
      }
      catch
      {
        return null;
      }
    }

    static byte[] GetMD5Hash(string data)
    {
      MD5 md5 = MD5CryptoServiceProvider.Create();
      return md5.ComputeHash(Encoding.UTF8.GetBytes(data));
    }
  }
}

C# Basics: If-Else If-Else vs Switch vs Dictionary<K,T> in Dealing with Multiple Choices

In this fourth installment of C# Basics, let’s take a look at how you handle multiple choice questions in your code. When you need to decide on a course of action based on the multiple possible values a variable may have, you have three essential choices.

  1. if | else if … | else
  2. switch
  3. Dictionary<K,T>

The code below shows you an example of each:

public class DownloadViewModel
{
  public Byte[] Contents { get; set; }
  public string FileName { get; set; }

  public string ContentType1
  {
    get
    {
      string ext = Path.GetExtension(FileName).ToLower();
      if (ext == ".pdf")
        return "application/pdf";
      else if (ext == ".txt")
        return "application/txt";
      else  
        return "application/octet-stream";
    }
  }

  public string ContentType2
  {
    get
    {
      switch (Path.GetExtension(FileName).ToLower())
      {
        case ".pdf":
          return "application/pdf";
        case ".txt":
          return "application/txt";
        default:
          return "application/octet-stream";
      }
    }
  }

  public string ContentType3
  {
    get
    {
      if (map.Count == 0) LoadMap();
      string val = string.Empty;
      if (!map.TryGetValue(Path.GetExtension(FileName).ToLower(), out val))
      {
        val = "application/octet-stream";
      }
      return val;
    }
  }

  private void LoadMap()
  {
    map.Add(".pdf", "application/pdf");
    map.Add(".txt", "application/txt");
    map.Add("*.*", "application/octet-stream");
  }

  private Dictionary<string, string> map = new Dictionary<string, string>();
}

So how do you pick which one to use? For me, the choice is easy. If I have only a few possible values that are not likely to change, I’ll use the if|else if|else construct. If I have a fair number (more than 3 and less than 16) and these values are not likely to change, I’ll use the switch statement. But if the values are likely to change or be data driven or if the number of values is greater than 15, I prefer to use a Dictionary.

Another highly valuable use of the Dictionary is when the values will kick off some action that may be lengthy or complicated. In that case, I prefer a Dictionary<T, ActionForT>. I can then retrieve the ActionForT and call the Execute method. Like this:

public class DownloadModel
{
  public Byte[] Contents { get; set; }
  public string FileName { get; set; }

  public string ContentType
  {
    get
    {
      string ext = Path.GetExtension(FileName).ToLower();
      if (ext == ".pdf")
        return "application/pdf";
      else if (ext == ".txt")
        return "application/txt";
      else  
        return "application/octet-stream";
    }
  }

  public void Save()
  {
    if (map.Count == 0) LoadMap();
    Action action = null;
    if (map.TryGetValue(Path.GetExtension(FileName).ToLower(), out action))
    {
      action(); //execute the action stored in our map
    }
    else
    {
      map["*.*"](); //execute the default action
    }
  }

  private void SavePdf()
  {
    throw new NotImplementedException();
  }

  private void SaveTxt()
  {
    throw new NotImplementedException();
  }

  private void SaveOther()
  {
    throw new NotImplementedException();
  }

  private void LoadMap()
  {
    map.Add(".pdf", new Action(SavePdf));
    map.Add(".txt", new Action(SaveTxt));
    map.Add("*.*", new Action(SaveOther));
  }

  private Dictionary<string, Action> map = new Dictionary<string, Action>();
}

C# Basics: Beware of Catch (Exception e)

In this third installment of C# Basics, let's take a look at exception handling. It is one the easiest things to do poorly in an application. In C# you can capture an error and do something with it as easily as this:

try
{
  //do something that may raise an exception
}
catch (Exception e)
{
  //do something with e--log it, modify a return value, etc.
  //if you want the caller of your code to have a crack at the same exception
  throw; //raise the exception again with throw; (almost NEVER throw e;)
}

But do try your best to NEVER catch the base Exception class. Be more specific, especially where you have to do something specific with a particular type of exception and allows others to rise up the call stack. Here’s just one example of being a bit more specific:

try
{
  //call a service that reads data from SQL Server
}
catch (SqlException se)
{
  if (se.Message.Contains("Timeout"))
  {
    //send a timeout log message to the DBA service
  }
  throw; //raise it up the stack to be handled by the caller
}

Of course, you can and ought to handle different exceptions differently where required. Here’s a brief example:

try
{
  //call a service that reads data from SQL Server
  //call another service that writes to a file
}
catch (SqlException se)
{
  if (se.Message.Contains("Timeout"))
  {
    //send a timeout log message to the DBA service
  }
  throw; //raise it up the stack to be handled by the caller
}
catch (IOException iox)
{
  //special handling or logging of IO exceptions
  Console.WriteLine(iox.Message);
}
catch (Exception e)
{
  //log a general exception and rethrow
  throw;
}

And don’t forget, you can create your own specialized exception classes. In fact, with Visual Studio you can use the code snippet for Exception. Just put your cursor in a C# file, outside of a class declaration, and start typing Exception and when you see the Intellisense prompt just hit TAB TAB. And you will have the following:

[Serializable]
public class MyException : Exception
{
	public MyException() { }
	public MyException(string message) : base(message) { }
	public MyException(string message, Exception inner) : base(message, inner) { }
	protected MyException(
	 System.Runtime.Serialization.SerializationInfo info,
	 System.Runtime.Serialization.StreamingContext context)
		: base(info, context) { }
}

Flesh out your own custom exception and raise and catch it just like a pro.

public void ShowExample(int count)
{
  if (count < 0) throw new MyException("Count cannot be less than zero.");
  // . . .
}

public void CallExample()
{
  try
  {
    ShowExample(-4);
  }
  catch (MyException me)
  {
    Console.WriteLine(me.Message);
  }
}

Of course, in the above example, you would more likely want to just throw a new ArgumentException. There is a very long list of commonly used exception classes in the .NET base class libraries. Spend some time on MSDN and get familiar with them. Here’s a brief but incomplete list of common exception classes you may want to catch or throw and then catch.

  • System.ArgumentException  
  • System.ArgumentNullException  
  • System.ArgumentOutOfRangeException  
  • System.ArithmeticException  
  • System.DivideByZeroException  
  • System.FormatException  
  • System.IndexOutOfRangeException  
  • System.InvalidOperationException  
  • System.IO.IOException  
  • System.IO.DirectoryNotFoundException  
  • System.IO.EndOfStreamException  
  • System.IO.FileLoadException  
  • System.IO.FileNotFoundException  
  • System.IO.PathTooLongException  
  • System.NotImplementedException  
  • System.NotSupportedException  
  • System.NullReferenceException  
  • System.OutOfMemoryException  
  • System.Security.SecurityException  
  • System.Security.VerificationException  
  • System.StackOverflowException  
  • System.Threading.SynchronizationLockException  
  • System.Threading.ThreadAbortException  
  • System.Threading.ThreadStateException  
  • System.TypeInitializationException  
  • System.UnauthorizedAccessException

C# Basics: The Conditional or Ternary Operator

For the second installment of C# Basics, let’s take a look at the conditional operator, sometimes known as the ternary operator. How many times have you written code like this:

if (a == b)
{
  x = y;
}
else
{
  x = z;
}

Probably never, at least not quite this simplistic or with such ancient style variable names, or one would hope anyway. But the example serves its purpose. Now use the conditional operator and convert that code to this:

x = (a == b) ? y : z;

You can read more about the conditional operator on MSDN here.