I used to use RNGCryptoServiceProvider
to generate string-based Order ID's, but, there were 4 instances where ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@$%^*()_-
would generate an already-existing Order ID.
And it got me thinking...
Why can't we just use something like:
<html>
...
<p>@GenerateOrderId()</p>
...
</html>
and:
public string GenerateOrderId()
{
return "OID" +
DateTime.Now.Year + DateTime.Now.Month +
DateTime.Now.Day +
DateTime.Now.Hour +
DateTime.Now.Minute +
DateTime.Now.Second +
DateTime.Now.Millisecond;
}
I've been told that it's a bad idea, but without any explanation, or reason, it's still stuck in my head. ... The reason I'd like to use this, is because it will always be unique.
This uses the DateTime. Now. Ticks property, which is “the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001”. It will therefore always be unique, unless the id is generated in a threaded scenario.
It tends to be between 0.5 and 15 milliseconds. As a result, repeated calls to the Now property in a short time interval, such as in a loop, may return the same value.
DateTime. UtcNow is the time according to the Coordinated Universal Time standard and is the same across timezones. This means that DateTime. UtcNow has the same value in the GMT +2 timezone and in the GMT -7 timezone and all other timezones.
timestamp is a data type that exposes automatically generated binary numbers, which are guaranteed to be unique within a database.
Computers work at nanosecond speeds. You would be guaranteed to generate a duplicate order ID almost immediately.
Your best bet would be to use a GUID [MSDN-C#] [MSDN-SQL] (a.k.a. UNIQUEIDENTIFIER
in the SQL world).
It won't always be unique.
If the same process is carried out during the same millisecond, then it will be identical.
As @Bill has stated, you should use a GUID for a unique string.
Never call the Now
getter that many times. "Now" may change while you're adding the strings. You could say DateTime.Now.ToString("yyyyMMddHHmmssfff")
or similar, but it's much better to use Guid.NewGuid()
for this.
If you just want a globally unique identifier and aren't bothered about the format, why don't you just use a GUID?
http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx
using System;
class Sample
{
public static void Main()
{
Guid g = Guid.NewGuid();
Console.WriteLine(g);
}
}
It even has a type in T-SQL (which you may well be using given that you're using ASP.NET)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With