I have a client which REQUIRES me to generate completely unique ids which NEVER, EVER, duplicate.
He won't accept the fact that Guid.NewGuid()
will statistically not repeat until the end of days https://stackoverflow.com/a/1705027/937131.
So I'm taking this as a challenge and tried to make a method which generates an ID which will never repeat a.k.a. a NONCE.
My general thought was that if I can incorporate a time portion at the end of every Guid, this should work.
Any ideas as to how this can be improved?
namespace JensB.Tools
{
public class RandomGenerator
{
public string GetNOnce()
{
string unique = Guid.NewGuid().ToString();
unique = unique.Replace("-", "");
long unixTimestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
string timeString = ToBase62(unixTimestamp);
unique = unique + timeString;
return unique;
}
private string ToBase62(long input)
{
string baseChars = ALPHANUMERIC_ALT;
string r = string.Empty;
int targetBase = baseChars.Length;
do
{
r = string.Format("{0}{1}",
baseChars[(int)(input % targetBase)],
r);
input /= targetBase;
} while (input > 0);
return r;
}
private static string ALPHANUMERIC_ALT =
"23456789" +
"abcdefghjkmnpqrstuvwxyz";
}
}