0

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.

Rocky
  • 4,454
  • 14
  • 64
  • 119

5 Answers5

2
System.Guid.NewGuid().ToString()

This generates a unique number. append the constant part to this guid.

user1071979
  • 1,701
  • 2
  • 12
  • 25
  • 'TMP-' is just a constant prefix. If we add that prefix to a unique number the compound is unique. The question's main concern is avoiding duplicates rather than a rigid format. the identifier has 2 parts "TMP-" part and "unique number" part. That is how i perceived the question? If the unique number part is rigid w.r.t the number of digits then i do agree with you that GUID's format wont work here. – user1071979 Jul 27 '12 at 06:27
2

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.

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
0

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

JohnnBlade
  • 4,261
  • 1
  • 21
  • 22
0

You might try System.Guid.NewGuid, which generates a global unique identifier (GUID).

wintermute
  • 55
  • 1
  • 4
0
return string.Format("TMP-{0:d}", DateTime.Now.Millisecond);

also see this SO post:

Community
  • 1
  • 1
Ria
  • 10,237
  • 3
  • 33
  • 60