0

I have the a function I took from this post which works great:

private string GenerateTransactionCode()
{
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    var result = new string(
        Enumerable.Repeat(chars, 8)
                  .Select(s => s[random.Next(s.Length)])
                  .ToArray());
    return result;
}

I would like to modify it so that instead of it being random, it picks the alpha numeric digits based on DateTime.UtcNow.Ticks. This way it will be non-repeating. I suppose the characters in the resulting TransactionCode might need to be increased depending on the length of the milliseconds? I would like the length of the resulting TransactionCode to be constant. Hopefully, no more than 8 Characters.

Example: If the ticks happened to be 135 (going to me more than that in real life) then the resulting code will be ACE or BDF depending if it's 0 based (I don't care if it is or not).

Community
  • 1
  • 1
capdragon
  • 14,565
  • 24
  • 107
  • 153
  • 5
    Ticks is not non-repeating... especially on multi-core; however, a simple interlocked counter would be... as would a database `IDENTITY`, and as would be a `Guid` (appropriately constructed, obviously) – Marc Gravell Apr 24 '12 at 13:40
  • 2
    I don't think you want to do this. Modern CPUs are more than capable of doing more than one thing in the resolution of the tick counter. See [here](http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/3a197913-7d01-415f-a7ff-ba8ff18dae52/) for more information. – David Schwartz Apr 24 '12 at 13:41
  • I think your example doesn't represent what you want, in that case only `A` through `J` would be used (unless `135` wasn't a decimal value). – C.Evenhuis Apr 24 '12 at 13:43
  • I was thinking if the ticks were 135 then it would pick it out from the array as such. 135 are the index values of BDF in the chars "array" – capdragon Apr 24 '12 at 13:46

1 Answers1

3

I imagine what you actually want is a real non-repeating transaction code, or GUID:

Guid g = Guid.NewGuid();
string txcode = Convert.ToBase64String(g.ToByteArray());

If you want to clean it up:

txcode = txcode.Replace("=","").Replace("+","").Replace("/","");

Example of generated output is OEndimZwsEKRAbAwnvzjoA but because of the replacement of + / and = the length can be slightly unpredictable.

You may prefer this format g.ToString("N") which gives something like 58d5381c878b484591568b086296fe8e and is guaranteed to be 32 characters long.

yamen
  • 15,390
  • 3
  • 42
  • 52