Search code examples
guidhashcodehash-code-uniqueness

How to generate a document ID or Report ID of 8 characters in .net


Can someone point me to the preferred method for generating a report or document ID? I have been looking at maybe using a guid that would be reduced down to a shorter length. We have an application that creates an ID for reports that is about 8 characters long. They appear to be using some type of hash code. Probably using a base 36 encoding scheme. But I cant seem to find a way to make the hash code come out to a length of 8 characters since people have to use them to refer to the documents. They would also be used in a disconnected environment, so you couldnt look up the next usable serialized number in the chain. Just wondering what some of you use in applications like this?


Solution

  • The .net Framwork provides RNGCryptoServiceProvider class which Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class is usually used to generate random numbers. Although I can use this class to generate unique number in some sense but it is also not collision less. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only. So, I used this class along with some character masking to generate unique key of fixed length.

    private string GetUniqueKey()
     {
     int maxSize  = 8 ;
     int minSize = 5 ;
     char[] chars = new char[62];
      string a;
      a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
     chars = a.ToCharArray();
     int size  = maxSize ;
      byte[] data = new byte[1];
     RNGCryptoServiceProvider  crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data) ;
     size =  maxSize ;
     data = new byte[size];
     crypto.GetNonZeroBytes(data);
     StringBuilder result = new StringBuilder(size) ;
     foreach(byte b in data )
     { result.Append(chars[__b % (chars.Length - )>); }
      <span class="code-keyword">return result.ToString();
      }
    

    http://www.codeproject.com/Articles/14403/Generating-Unique-Keys-in-Net