Skip to main content

Posts

Showing posts from July, 2014

Use RNGCryptoServiceProvider to generate unique key

The implementation of RNGCryptoServiceProvider can generate cryptographically strong sequence of random values. Using this class, we can generate arbitrary length of random string. These strings can be used as unique keys if the length is long. Here is the function:         public static string GenerateUniqueKey(int length)         {             const string AvailableCharacters = " ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ";             char [] key = new char [length];             byte [] randomData = new byte [length];             using ( RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ())             {                 rng.GetBytes(randomData);             }             for ( int i = 0; i < key.Length; i++)             {                 int pos = randomData[i] % AvailableCharacters.Length;                 key[i] = AvailableCharacters[pos];             }             return new string (key);         }

Convert traditional connection string to entity framework connection string using EntityConnectionStringBuilder

I have a traditional ADO.NET connection string like this: Initial Catalog=QuartermasterMain_Dev;Data Source=localhost;UID=sa;password=Pass@word1 I would like to re-use this connection string in Entity framework, so I need to convert it to entity connection string. Assume I have an entity class called "QuartermasterMainEntities" We can use EntityConnectionStringBuilder class to construct an entity connection string from traditional connection string.     public partial class QuartermasterMainEntities : DbContext     {         public QuartermasterMainEntities(string strConnectionString)             : base ((new EntityConnectionStringBuilder ()                 {                     Metadata = " res://*/QuartermasterEntities.csdl|res://*/QuartermasterEntities.ssdl|res://*/QuartermasterEntities.msl ",                     Provider = " System.Data.SqlClient ",                     ProviderConnectionString = strConnectionString                 }).Connectio