How to write a method to generate random/unique string, then how to call the method?

VAer 756 Reputation points
2021-01-17T04:39:39.903+00:00

I will create a button and let user to generate a unique string for his/her own record.

How should I write the method and how to call it?

Thanks.

        private void buttonInsertString_Click(object sender, EventArgs e)
        {
//When user clicks the button, the program will generate a unique string for his/her own record.


                using (OdbcConnection Cn = new OdbcConnection(GlobalVariables.DatabaseConnectionString))
                {
                    OdbcCommand cmd = new OdbcCommand("INSERT into TableUser (GeneratedUniqueString) Values ('" + ..... + "')  WHERE Username ='" + Environment.UserName + "'", Cn);

                    //if the connection is not already open - then open it
                    if (Cn.State != ConnectionState.Open)
                    {
                        Cn.Open();
                    }

                    cmd.ExecuteNonQuery();

                }


        }


        public static void GenerateRandomUniqueString()
        {
//How to write a method to gerate a unique string (lowcase a-z letter only; lenth: 5)? Unique means: the generated string cannot be the one already in Database TableUser field GeneratedUniqueString. So there should be two steps: 1) generate a random 5 character string, lower case letter only; 2) check if the string is in database, if yes, regenerate a random string until it is not in the database.


        }
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,827 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,235 questions
0 comments No comments
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,571 Reputation points
    2021-01-18T05:31:58.1+00:00

    Try to use GUID:

    string uniqueString =  System.Guid.NewGuid().ToString();  
    

    You don't even have to use a method.

    In addition, it is best not to splice SQL like this, but use parameters:

    cmd.CommandText = "SELECT * FROM t1 WHERE id = ?";  
    cmd.Parameters.Add("@id", OdbcType.Int).Value = 4;  
    

    Update:
    The full name of GUID is globally unique identifier,
    Its length and format are fixed, 32 hex digits grouped into chunks of 8-4-4-4-12, for example:

    dfa8492b-4a88-4ec3-b675-b50bd78a9876  
    

    This means that it has 2^128 numbers, which is a huge number, more than the stars in the universe have been observed, so the probability of getting two numbers from it and it happens to be the same is infinitely close to 0, which can meet the requirements for random numbers in most cases.

    But the probability of repetition is not 0 after all. If you are still worried about repetition, you can add a verification to determine whether it already exists. Or add another GUID or timestamp at the end, which still does not guarantee that the probability is 0, but it will make the rate continue to shrink.

    Update2:
    Depending on your requirements, using RNGCryptoServiceProvider may be a good idea:

            public static string RandomString(int length)  
            {  
                string valid = "abcdefghijklmnopqrstuvwxyz";  
                StringBuilder sb = new StringBuilder();  
                using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())  
                {  
                    byte[] uintBuffer = new byte[sizeof(uint)];  
      
                    while (length-- > 0)  
                    {  
                        rng.GetBytes(uintBuffer);  
                        uint num = BitConverter.ToUInt32(uintBuffer, 0);  
                        sb.Append(valid[(int)(num % (uint)valid.Length)]);  
                    }  
                }  
                return sb.ToString();  
            }  
    

    But you still need to consider the possibility of duplication and deal with it.

    Update3:
    I think it is better not to change the RandomString method.
    Please try something like this:

           static void Main(string[] args)  
            {  
                string connString = @"Driver={Microsoft Access Driver (*.mdb)};Dbq=D:\test\db\test.mdb;";  
                using (OdbcConnection Cn = new OdbcConnection(connString))  
                {  
                    using (OdbcCommand cmd = new OdbcCommand())  
                    {  
                        if (Cn.State != ConnectionState.Open)  
                        {  
                            Cn.Open();  
                        }  
                        string randomString = getUniStr();  
                       
                        cmd.CommandText = "insert into TableUser .....";  
                        cmd.Parameters.AddWithValue("", OdbcType.VarChar).Value = randomString;  
                        cmd.ExecuteNonQuery();  
                    }  
                }  
                Console.WriteLine("Press any key to continue...");  
                Console.ReadLine();  
            }  
            public static string getUniStr()   
            {  
                string connString = @"Driver={Microsoft Access Driver (*.mdb)};Dbq=D:\test\db\test.mdb;";  
                using (OdbcConnection Cn = new OdbcConnection(connString))  
                {  
                    using (OdbcCommand cmd = new OdbcCommand())  
                    {  
                        if (Cn.State != ConnectionState.Open)  
                        {  
                            Cn.Open();  
                        }  
                        int count;  
                        string randomString = RandomString(5);  
                        do  
                        {  
                            cmd.Connection = Cn;  
                            cmd.CommandText = "select count(*) from table2 where ID=?";  
                            //If there is only one line in the code block, the braces can be omitted.  
                            if (cmd.Parameters.Contains("ID"))  
                                cmd.Parameters["ID"].Value = randomString;  
                            else  
                                cmd.Parameters.AddWithValue("ID", OdbcType.VarChar).Value = randomString;  
                            count = int.Parse(cmd.ExecuteScalar().ToString());  
                            if (count != 0)  
                                randomString = RandomString(5);  
                        }  
                        while (count == 1);  
                        return randomString;  
                    }  
                }  
            }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful