Reputation: 4524
I want to generate a Uniq Number something like TMP-0001354, TMP will be always same only number will get change, which should not be get duplicate in table.
I want to a exp. code which should be in c#, I'll call that function at the time of inserting the record in table. SQL server database I am using
I am trying this I don't know will it work fine or not.
private string RandomNumberGenerator()
{
int maxSize = 8;
int minSize = 5;
char[] chars = new char[62];
string a;
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data);
size = maxSize;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size);
foreach (byte b in data)
{ result.Append(chars[b % (chars.Length - 1)]); }
return result.ToString();
}
Some one please help me.
Upvotes: 0
Views: 1447
Reputation: 113335
For generate uniq number use this (the number can start with 0):
string number_s = "TMP-" + RandomNumber(0, 9) + RandomNumber(0, 9) + RandomNumber(0, 9) + RandomNumber(0, 9) + RandomNumber(0, 9) + RandomNumber(0, 9) + RandomNumber(0, 9);
or this (is shorter, but will begin with 1):
string number_s = "TMP-" + RandomNumber(1000000, 9999999);
This is the code for RandomNumber
:
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public int RandomNumber(int min, int max)
{
lock (syncLock)
{ // synchronize
return random.Next(min, max);
}
}
It works nice for me. Hope that I helped you.
Upvotes: 2
Reputation: 10367
return string.Format("TMP-{0:d}", DateTime.Now.Millisecond);
also see this SO post:
Upvotes: 0
Reputation: 55
You might try System.Guid.NewGuid, which generates a global unique identifier (GUID).
Upvotes: 0
Reputation: 1791
System.Guid.NewGuid().ToString()
This generates a unique number. append the constant part to this guid.
Upvotes: 2
Reputation: 4327
You can use a mini hash, guid, you could also use the time year month day seconds miliseconds, or a timestamp.
there are many ways to make a unique ID
Upvotes: 0