I'm integrating/testing with a remote web service and even though it's the "QA" endpoint, it still enforces a unique email address on every call.
I can think of DateTime.Now.Ticks
(e.g. 634970372342724417) and Guid.NewGuid()
, but neither of those can be coalesced into an email with max. 20 chars (or can they?).
I suppose it's not that hard to write out to a file a number that contains the last number used and then use [email protected], [email protected], etc...
but if I can avoid persisting state I always do.
Does anyone have a trick or an algorithm that gives something of a short length "guid" that is unique to a reasonably long time period (say a year) that I could use for my email addresses of max length 20 chars with (max length of guid) = 14 = 20 - length of "@x.com"?
p = randperm(1e10, 10);
If you assume that you will not generate two e-mail addresses at the same 'tick', then you can indeed use the ticks to generate an e-mail address.
However, if ticks is a 64-bit number, and you write out that number, you will end up with more than 20 characters.
The trick is to encode your 64-bit number using a different scheme. Assume that you can use the 26 characters from the western alphabet + 10 digits. This makes 36 possible characters. If you take 5 bits, you can represent 32 characters. That should be enough. Take the 64-bits and divide them in groups of 5 bits (64 /5 is about 13 groups). Translate every 5 bits to one character. That way you end up with 13 characters, and you can still add a character in front of it).
long ticks = DateTime.Now.Ticks;
byte[] bytes = BitConverter.GetBytes(ticks);
string id = Convert.ToBase64String(bytes)
.Replace('+', '_')
.Replace('/', '-')
.TrimEnd('=');
Console.WriteLine (id);
Yields:
Gq1rNzbezwg
If you get the following digits from your date-time, you should be able to make it work... Soemthing like:
DateTime.Now.ToString("yyMMddHHmmssff");
which is 16 characters, leaving 4 for some other prefix as you need.
So, Feb 21, 2013, at approximately 10:21 would be "130321102142" and the next one would be "130321102169", etc...
Have a look at http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx for more details on datetime formatting.
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