-1

I am using this code to generate unique code

public static string CreateRandomPassword()  
    {
        string _allowedChars = "1234567899999";
        Random randNum = new Random((int)DateTime.Now.Ticks); 
        char[] chars = new char[5];


        for (int i = 0; i < 5; i++)
        {
            chars[i] = _allowedChars[randNum.Next(_allowedChars.Length)];
            //No need to over complicate this, passing an integer value to Random.Next will "Return a nonnegative random number less than the specified maximum."
        }
        return new string(chars);

And this to use to send entry to sql table . ids is the text box in which i am entering how many unique code is to be generate

protected void Button1_Click(object sender, EventArgs e)
    {
        var sand = CreateRandomPassword();
        int num; 
        if ( int.TryParse(ids.Text,out num))
        {
            for (int i = 1; i <= num; i++)
            {

                string strcon = ConfigurationManager.ConnectionStrings["slxserv"].ToString();
                using (SqlConnection con = new SqlConnection(strcon))

                using (SqlCommand cmd = new SqlCommand("INSERT INTO passwords (password) VALUES (@password) "))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@password",sand);

                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }

        } 

Please help me when i am trying to generate more than one unique code it send the data to sql with same code multiple times . i am doing anything wrong please let me know . or it is possible to do with sql procedure also please let me know

  • There are a lot of problems with this code - you create only a *single* password, calling `cmd.Parameters.AddWithValue("@password",sand);` in a loop actually adds *new* parameters, opening/closing the connection inside the loop simply wastes CPU. The wors problem though is `CreateRandomPassword` itself. First, .NET already has a method to generate strong passwords, as shown [here](http://stackoverflow.com/questions/54991/generating-random-passwords). Second, the password is very, very weak with 9s more frequent than the other numbers – Panagiotis Kanavos Apr 06 '16 at 09:02
  • Check out the accepted answer to [this post.](http://stackoverflow.com/questions/4558403/how-can-i-generate-random-strings-in-tsql) – Zohar Peled Apr 06 '16 at 09:08

1 Answers1

2

You create the password naming it "sand" and then in a for loop, you send the same password "num" times. Can you please try this:

    int num; 
    if ( int.TryParse(ids.Text,out num))
    {
        for (int i = 1; i <= num; i++)
        {
           var sand = CreateRandomPassword();
Nuh Metin Güler
  • 1,075
  • 8
  • 9