Unique Id Generation !!!

A short while I was engaged in a little project where I had to interact with a third party service provider who required a (30 length) unique id as part of the transaction. I am little dumb and am used to GUIDs for a long time when it comes to unique ids. But GUIDs are more than 30 in length. I was trying out some stupid ways like stripping out the trail part of the GUID to make 30 length unique but my intuition wasn’t convinced about the tricks I was working out.

Finally, Sriram helped me with it. I am sharing his code for the benefit of others.

string GenerateUniqueId(int length)
   string asciiChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
   char[] chars = asciiChars.ToCharArray();
   byte[] randombytes = new byte[length];

   RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
   StringBuilder result = new StringBuilder(length);

   foreach (byte b in randombytes)
      result.Append(chars[b % asciiChars.Length]);

   return result.ToString();

Thanks Sriram.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s