0

i'm new to asp.net, i'm writing a login & registration script for learning database application. But the script seems not work. it stills can add duplicated username. Here is the script

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class Registration : System.Web.UI.Page
{
    static string temp;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["earchConnectionString"].ConnectionString);
            con.Open();
            string cmdStr = "Select count(*) from [user] where UserName='" + TextBoxUN.Text + "'";

            SqlCommand userExist = new SqlCommand(cmdStr, con);
            int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());

            con.Close();
            if (temp == 1)
            {
                Response.Write("User Name Already Exist....<br /> Please Choose Another User Name.");
            }
        }

    }
    protected void Submit_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["earchConnectionString"].ConnectionString);
        con.Open();
        string insCmd = "Insert into [user] (UserName, Password, EmailAddress, FullName, level) values (@UserName,@Password,@EmailAddress, @FullName, @level)";
        SqlCommand insertUser = new SqlCommand(insCmd, con);
        insertUser.Parameters.AddWithValue("@UserName", TextBoxUN.Text);
        insertUser.Parameters.AddWithValue("@Password", TextBoxPass.Text);
        insertUser.Parameters.AddWithValue("@EmailAddress", TextBoxEA.Text);
        insertUser.Parameters.AddWithValue("@FullName", TextBoxFN.Text);
        insertUser.Parameters.AddWithValue("@level", level.SelectedValue.ToString());

        try
        {
            insertUser.ExecuteNonQuery();
            con.Close();
            //Response.Redirect("Login.aspx");
            Label1.Text = temp;
        }
        catch (Exception er)
        {
            Response.Write("Something wrong");
        }
        finally
        {
            //Any Special Action You Want To Add
        }

    }
}

Any can detect the problems?

thanks

2
  • 2
    You should really parameterize your first query - you are feeding user input directly into a sql query - en.wikipedia.org/wiki/SQL_injection Commented Oct 10, 2012 at 8:44
  • Yeah, definitely parameterize that query otherwise your application can be attacked using SQL Injection. See here for more help. Commented Oct 10, 2012 at 8:47

3 Answers 3

3

You should do the check whether the username exists inside your Button_Click, not inside Page_Load. Ideally both queries should be executed within the same SQL transaction. Also you should absolutely use parametrized query for the first one (the same way you are doing in the second query) in order to prevent SQL injection.

Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it :-). The only other suggestion I'd make is to add a unique index to the username column to make sure duplicates are not possible - and if there are already duplicates in the table, then the logic (count == 1) will continue to allow more duplicates.
2

Set primary key on the column UserName of the table user. So you don't have to check for the user existence in the database at the time of insertion, reducing an extra call to database. This way command.ExecuteNonQuery() won't allow you to insert duplicate users and throw exception and you can take necessary actions in the catch block of your code.

1 Comment

Hmm. I'd advise against using anything other than an auto-incrementing integral ID for primary key. Anything else is really a violation of single-reponsibility principal. Unique constraints/indexes are designed for this purpose and that's what should be used.
0
  1. Make an unique field for your user login in SQL Database.
  2. On account creation page on account creation button click event do it as following:

                try
                {
    
                    SqlCommand command = new SqlCommand("INSERT INTO Users(login,password) VALUES ('" + txtLogin.Text + "','" + txtPass.Text+ "');", con);
                    command.ExecuteNonQuery();
                    Response.Redirect("login.aspx");
                }
    
                catch (SqlException)
                {
                    lblWrongLogin.Text = "Username already exists.";
                }
    

Basically, when you try to write a duplicate login in SQL Database you get SQL exception, so you just catch it in your application and do whatever action you need (in most cases reload registration page).

P.S.: consider using some hashing algorithm like MD5 to hash passwords before putting them in database. Also dont forget to hash passwords client-side when logging in. P.P.S.: use SQL parameters for login, password and every other user-entered information to prevent SQL injection.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.