Today I wanted to generate short unique IDs in C#.  I stumbled upon an article here that helps you shorten GUID’s, here is the link: http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx.  I still thought that the IDs this generated were a bit lengthy and ugly for what I was looking for.  What I decided to use instead was the number of server ticks  to generate a URL friendly code / key that isn’t as long as a GUID or as obvious as a database auto-incremented record ID.  In any case, here’s the approach that I took.

        static string uniqueCode()
        {
            string characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#";
            string ticks = DateTime.UtcNow.Ticks.ToString();
            var code = "";
            for (var i = 0; i < characters.Length; i += 2)
            {
                if ((i + 2) <= ticks.Length)
                {
                    var number = int.Parse(ticks.Substring(i, 2));
                    if (number > characters.Length - 1)
                    {
                        var one = double.Parse(number.ToString().Substring(0, 1));
                        var two = double.Parse(number.ToString().Substring(1, 1));
                        code += characters[Convert.ToInt32(one)];
                        code += characters[Convert.ToInt32(two)];
                    }
                    else
                        code += characters[number];
                }
            }
            return code;
        }

This code will generate a unique code / key based on universal time stamp ticks.  Thanks to Chris Newman for pointing out the DateTime.UtcNow.  Originally I had used DateTime.Now to generate the ticks which in a clustered infrastructure could’ve caused problems.  This code can be cleaned up or implemented in any way that you want, feel free to use and edit it.  This code was created because I wanted something simpler than a GUID and something that was still URL friendly for my applications, I’m sure there are other countless methods available, I just hope this one helps some of you.   :-)

Advertisement