[SOLVED] System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null

Issue

I’m trying create and save the password both in salt and hash while I’m trying to insert user password in database. While I’m clicking the register button it’s shows the following error.

System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.

Below I’ve added my code of registration page.

public class GenerateHash
{
    public string CreateSalt(int SaltSize)
    {
        var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
        byte[] Salt = new byte[SaltSize];
        rng.GetBytes(Salt);
        return Convert.ToBase64String(Salt);
    }

    public string GenarateHash(string UserPassword, string salt)
    {
        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(UserPassword + salt);
        byte[] PasswordHash = new System.Security.Cryptography.SHA256Managed().ComputeHash(bytes);

        return Convert.ToBase64String(PasswordHash);
    }

    protected void Regist_Click(object sender, EventArgs e)
    {
        GenerateHash HashAndSalt = new GenerateHash();
        string GetSalt = HashAndSalt.CreateSalt(10);
        string hashString = HashAndSalt.GenarateHash(Password.Text, GetSalt);
        string username = UserName.Text;
        string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (MySqlConnection conn = new MySqlConnection(connectionString))
        {
            conn.Open();
            using (MySqlCommand cmd = new MySqlCommand("Insert into [User](UserName, PasswordHashed, Salt) values(" + "@UserName, @PasswordHashed, @Salt)", conn))
            {
                cmd.Parameters.AddWithValue("@UserName", username);
                cmd.Parameters.AddWithValue("@PasswordHashed", hashString);
                cmd.Parameters.AddWithValue("@Salt", GetSalt);
                cmd.ExecuteNonQuery();
            }
        }
        Response.Redirect("Login  .aspx");
    }
}

Solution

Check the connection string name in your web.config file and see if it matches the ConnectionString in your code.

For example:

<connectionStrings>
    <add name="connStr" connectionString="SERVER=localhost;DATABASE=saha;UID=root;PASSWORD=abc123;max pool size=50000000; Allow User Variables=True"/>
  </connectionStrings>

So in the above code change the name="connstr" to name="connectionString". I think that should resolve your issue.
Hope it helps.

Answered By – prkash

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published.