0

I understand that many similar questions have been asked. I've looked through them and after several days, I still couldn't understand where I have gone wrong with my code. I'm a beginner, so please bear with me if I seemed a little silly.

Here is the problem I am facing. I am trying to create a simple asp.net registration page that will insert records into a database (on SQL server). I have five text boxes on my web form, namely

  • Username
  • Password
  • e-Mail
  • SecurityQuestion
  • SecurityAnswer and a submit button.

I have a class file that is written this way

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

public class Student 
{
private static string connStr = "server = localhost; initial catalog = DevelopTest; integrated security = true;";

public static void AddUser(string username, string password, string email, string question, string answer)
{
    string sqlStr = "INSERT INTO Student VALUES(@username, @pass, @email, @question, @answer, 1);"; 
    SqlConnection dbConn = new SqlConnection(connStr);
    SqlCommand sqlComd = new SqlCommand(sqlStr, dbConn);
    sqlComd.Parameters.AddWithValue("@username", username);
    sqlComd.Parameters.AddWithValue("@pass", password);
    sqlComd.Parameters.AddWithValue("@email", email);
    sqlComd.Parameters.AddWithValue("@question", question);
    sqlComd.Parameters.AddWithValue("@answer", answer);

    SqlTransaction tran = null;
    try
    {
        dbConn.Open();
        tran = dbConn.BeginTransaction();
        sqlComd.Transaction = tran; 
        sqlComd.ExecuteNonQuery();
        tran.Commit();
    }
    catch (SqlException e)
    {
        tran.Rollback();                        
    }
    finally
    {
        if (dbConn != null) { dbConn.Close(); }
    }


}

And then I have the button click written this way:

protected void btnRegister_Click(object sender, EventArgs e)
{
Student.AddUser(tbUsernameRegs.Text, tbPassRegs.Text, tbeMailRegs.Text, tbSecretQnsRegs.Text, tbSecretAnswRegs.Text);
}

When I click one the button though, I get a null object reference exception. I understand that null object reference means I have an uninitialised object, but I've been trying to spot the mistake for days already, and still couldn't figure out where I have gone wrong.

I hope could help me out on this. Thanks a lot.

Edit* Here's the stack trace.

[NullReferenceException: Object reference not set to an instance of an object.]
Student.AddUser(String username, String password, String email, String question, String answer) +290
Registration.btnRegister_Click(Object sender, EventArgs e) +94
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9752490
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +196
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
5
  • 2
    Do not store passwords in plain text. Commented Mar 19, 2014 at 16:33
  • What's the stack trace? What do you see in the debugger? Commented Mar 19, 2014 at 16:34
  • Did you see if your connection to database is setup before you do anything with it? Post stack trace as well for more help Commented Mar 19, 2014 at 16:38
  • You should also put some real validation in there to prevent injection attacks Commented Mar 19, 2014 at 16:39
  • I understand the various advice. At the moment though, I am trying to get it working before putting in the validations. Commented Mar 19, 2014 at 16:49

2 Answers 2

4

In the catch block you are calling

tran.Rollback();

without checking if tran is not null. And it might be if the connection attempt fails and no transaction was created here:

dbConn.Open();
tran = dbConn.BeginTransaction();

So add checking for null for tran variable:

catch (SqlException e)
{
    if (tran != null)
    {
        tran.Rollback();                        
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@user3438545, to what result?
Still the same :( I'm going to go bald soon.
@user3438545, stacktrace says error is on the line 290. What code is on this line?
0

Couple small things. You should be explicit about the columns you are inserting and should never assume they are going in proper order... qualify the insert...

insert into student ( UserName, Password, EMail, Question, Answer, FlagField )
   values ( @username, @pass, @email, @question, @answer, 1 )

What would happen if the table had columns as Password, Email, UserName, then the columns would not be properly paired up.

Sorry on the ToString() suggestion, brain-cramp. Anyhow, it is throwing error based on inbound parameter string although expected passed as NULL. You will need to validate them coming in, such as

if( username == null)
   username = "";
if( pass == null )
   pass = "";
etc...

THEN, apply your .Parameters.AddWithValue() call

3 Comments

I see. I've tried to pass strings as arguments into the Student.AddUser method, but still ran into error though.
" simplify this by simply adding .ToString() to each parm" - interesting recommendation. Do you expect null.ToString() to work without exceptions?
@user3438545, revised answer to explicitly test for == null.

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.