I\'m working on an app that sends raw data to zebra printer and print out barcodes. And since every item has its own unique barcode, I need to define a variable that automat
Start with a twelve digit number, ie: 111111111111
to get your new 'random' unique number take the previous number and add 1.
although not random, it will guarantee uniqueness.
You can simply use:
var temp = Guid.NewGuid().ToString().Replace("-", string.Empty);
var barcode = Regex.Replace(temp,"[a-zA-Z]", string.Empty).Substring(0, 12);
How many times do you generate a new barcode per day, hour, minute?
You could use a technique like the auto versioning of Visual Studio works.
public static class UniqueId
{
static private int _InternalCounter = 0;
static public string Get()
{
var now = DateTime.Now;
var days = (int)(now - new DateTime(2000, 1, 1)).TotalDays;
var seconds = (int)(now - DateTime.Today).TotalSeconds;
var counter = _InternalCounter++ % 100;
return days.ToString("00000") + seconds.ToString("00000") + counter.ToString("00");
}
With this approach you'll get an overflow at the 15. October 2273, but i think this can be solved by your follower. ;-)
If you need to create more than hundred unique IDs per second you can change the last two line into:
var counter = _InternalCounter++ % 1000;
return days.ToString("0000") + seconds.ToString("00000") + counter.ToString("000");
Now you'll have thousand unique IDs per second, but the days will already overflow at 18. May 2027. If this is too short, you can get additional ten years if you set the start date to 2010 by this line:
var days = (int)(now - new DateTime(2010, 1, 1)).TotalDays;
Using an RNG and a hash do:
10 - stream out 12 digits
20 - check if value is in hash
30 - if it's goto 40 else goto 10
40 - push value into hash
50 - return new 12 digit number
60 - goto 10