0

I have created a web application for online testing.

The website is running perfectly fine on my local machine but giving an error on remote server.

protected void Page_Load(object sender, EventArgs e)
{

            arrSessionALL_questions = Session["arrALL_questions"] as int[];
            arrSessionQuestion_ID = Session["arrayOfQuestionID"] as int[];
            arrSessionCorrectAns = Session["arrayOfCorrectAns"] as string[];
            arrSessionCorrectAnsMarks = Session["arrayOfCorrectAnsMarks"] as int[];
            arrSessionAns_ID = Session["arrayOfAnsID"] as string[];
            arrSessionAttempted_ID = Session["arrayOfAttemptedID"] as int[];
            arrSessionMarkQuestion_ID = Session["arrMarkQuestion_ID"] as int[];
            arrSessionLeft_ID = Session["arrayOfLeftID"] as int[];
            arrSessionTotalMarks = Session["arrTotalMarks"] as int[];
}

protected void ButtonNext_Click(object sender, EventArgs e)
{


    PanelTimer.Visible = true;
    PanelQuestNum.Visible = false;

    try
    {       

    if (arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] != 0)
    {


        if (Convert.ToInt32(Session["QuestionCounter"]) < arrSessionALL_questions.Length)
        {
            //Session["QuestionCounter"] = Convert.ToInt32(Session["QuestionCounter"]) + 1;
            LabelStudentName.Text = arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])].ToString();
            correctAns = arrSessionCorrectAns[Convert.ToInt32(Session["QuestionCounter"])].ToString();
            correctMarks = Convert.ToInt32(arrSessionCorrectAnsMarks[Convert.ToInt32(Session["QuestionCounter"])]);
            PanelQ.Visible = true;
            ButtonSTART.Visible = false;
            ButtonMark.Visible = true;


            PanelTimer.Visible = true;
            PanelQuestNum.Visible = false;


            if (RadioButtonListAns.SelectedIndex >= 0)
            {

                arrAns_ID[Convert.ToInt32(Session["QuestionCounter"])] = RadioButtonListAns.SelectedItem.ToString();
                Session["arrayOfAnsID"] = arrAns_ID;
                arrSessionAns_ID = Session["arrayOfAnsID"] as string[];


                if (arrSessionAns_ID[Convert.ToInt32(Session["QuestionCounter"])] == correctAns)
                {
                    studentMarks = correctMarks;
                    attempt_correct_wrong = "correct";
                }
                else
                {
                    studentMarks = 0;
                    attempt_correct_wrong = "wrong";
                }


                con.Open();
                SqlDataAdapter adp = new SqlDataAdapter("select * from Student_Analysis where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con);
                DataSet ds = new DataSet();
                adp.Fill(ds, "Student_Analysis");
                int count = ds.Tables[0].Rows.Count;
                if (count > 0)
                {
                    con.Close();

                    con1.Open();
                    SqlCommand cmd = new SqlCommand("UPDATE Student_Analysis set studentAns='" + arrSessionAns_ID[Convert.ToInt32(Session["QuestionCounter"])] + "',studentMarks='" + studentMarks + "',attemp_correct_wrong='" + attempt_correct_wrong + "' where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con1);
                    cmd.ExecuteNonQuery();
                    con1.Close();
                }
                else
                {

                    con.Close();

                    con1.Open();
                    SqlCommand cmd = new SqlCommand("insert into Student_Analysis values('" + date + "','" + studentId.ToString() + "','" + studentName + "','" + username.ToString() + "','" + papername + "','" + Convert.ToInt32(LabelStudentName.Text) + "','" + arrSessionAns_ID[Convert.ToInt32(Session["QuestionCounter"])] + "','" + correctAns + "','" + studentMarks + "','" + correctMarks + "','" + attempt_correct_wrong + "')", con1);
                    cmd.ExecuteNonQuery();
                    con1.Close();
                }

}

            else
            {
                arrAns_ID[Convert.ToInt32(Session["QuestionCounter"])] = "NULL";
                Session["arrayOfAnsID"] = arrAns_ID;
                arrSessionAns_ID = Session["arrayOfAnsID"] as string[];


                studentMarks = 0;
                attempt_correct_wrong = "Not attempted";



                con.Open();
                SqlDataAdapter adp = new SqlDataAdapter("select * from Student_Analysis where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con);
                DataSet ds = new DataSet();
                adp.Fill(ds, "Student_Analysis");
                int count = ds.Tables[0].Rows.Count;
                if (count > 0)
                {
                    con.Close();

                    con1.Open();
                    SqlCommand cmd = new SqlCommand("UPDATE Student_Analysis set studentAns='" + "NULL" + "',studentMarks='" + studentMarks + "',attemp_correct_wrong='" + attempt_correct_wrong + "' where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con1);
                    cmd.ExecuteNonQuery();
                    con1.Close();
                }
                else
                {

                    con.Close();

                    con1.Open();
                    SqlCommand cmd = new SqlCommand("insert into Student_Analysis values('" + date + "','" + studentId.ToString() + "','" + studentName + "','" + username.ToString() + "','" + papername + "','" + Convert.ToInt32(LabelStudentName.Text) + "','" + "NULL" + "','" + correctAns + "','" + studentMarks + "','" + correctMarks + "','" + attempt_correct_wrong + "')", con1);
                    cmd.ExecuteNonQuery();
                    con1.Close();
                }
            }


            if (Convert.ToInt32(Session["QuestionCounter"]) < arrSessionALL_questions.Length - 1)
            {
                Session["QuestionCounter"] = Convert.ToInt32(Session["QuestionCounter"]) + 1;
                loadQuestion();
                ButtonMark.Visible = true;


                //Checking if question has been marked
                con.Open();
                SqlDataAdapter adp = new SqlDataAdapter("select * from StudentMarkedQuestions where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND markedQuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con);
                DataSet ds = new DataSet();
                adp.Fill(ds, "Student_Analysis");
                int count = ds.Tables[0].Rows.Count;
                if (count > 0)
                {
                    ButtonMark.Visible = false;
                    ButtonUnMark.Visible = true;

}

                else
                {
                    ButtonMark.Visible = true;
                    ButtonUnMark.Visible = false;
                }
                //Checking if question has been marked
            }
            else
            {
                LabelStudentName.Text = "End of questions!!";
                PanelQ.Visible = true;
                ButtonSTART.Visible = false;
                ButtonFinish.Visible = true;
                ButtonNext.Visible = true;
                ButtonPrevious.Visible = true;

            }


        }
        else
        {
            LabelStudentName.Text = "End of questions!!";
            PanelQ.Visible = true;
            ButtonSTART.Visible = false;

            ButtonFinish.Visible = true;
            ButtonMark.Visible = false;
            ButtonPrevious.Visible = false;
            ButtonNext.Visible = false;
            ButtonUnMark.Visible = false;

        }
    }


    }   //try ends     
    catch(Exception ex)
    {

       Response.Write(ex.Message);          
    }
}

public void loadQuestion()
{
    if (arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] != 0)
    {


        con1.Open();
        SqlDataAdapter adp1 = new SqlDataAdapter("select * from QuestionInsert where(QuestionNum='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "')", con1);
        DataSet ds1 = new DataSet();
        adp1.Fill(ds1);
        LabelQuestion.Text = (Convert.ToInt32(Session["QuestionCounter"]) + 1) + ".  " + ds1.Tables[0].Rows[0][7].ToString();
        con1.Close();


        RadioButtonListAns.Items.Clear();
        con2.Open();
        string strQuery = "select * from QuestionInsert where(QuestionNum='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "')";
        SqlDataAdapter da = new SqlDataAdapter(strQuery, con2);
        DataTable dt = new DataTable();
        da.Fill(dt);
        con2.Close();
        RadioButtonListAns.Items.Insert(0, new ListItem(dt.Rows[0]["Option1"].ToString(), dt.Rows[0]["Option1"].ToString()));
        RadioButtonListAns.Items.Insert(1, new ListItem(dt.Rows[0]["Option2"].ToString(), dt.Rows[0]["Option2"].ToString()));
        RadioButtonListAns.Items.Insert(2, new ListItem(dt.Rows[0]["Option3"].ToString(), dt.Rows[0]["Option3"].ToString()));
        RadioButtonListAns.Items.Insert(3, new ListItem(dt.Rows[0]["Option4"].ToString(), dt.Rows[0]["Option4"].ToString()));
        RadioButtonListAns.Items.Insert(4, new ListItem(dt.Rows[0]["Option5"].ToString(), dt.Rows[0]["Option5"].ToString()));



        //Selects radiobutton if answer found in database
        con3.Open();
        SqlDataAdapter adp = new SqlDataAdapter("select * from Student_Analysis where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con3);
        DataSet ds = new DataSet();
        adp.Fill(ds, "Student_Analysis");
        int count = ds.Tables[0].Rows.Count;
        if (count > 0)
        {
            con3.Close();

            string ans = ds.Tables[0].Rows[0][6].ToString();
            if (RadioButtonListAns.Items.FindByText(ans) != null)
            {
                RadioButtonListAns.Items.FindByText(ans).Selected = true;
            }
        }
        con3.Close();
        //Selects radiobutton if answer found in database
    }

}

This is the code that I have applied, I have given the code from Page Load and ButtonNext_Click() event.

While starting the test, it loads two questions but then if you will click on next button again, it is giving me this error:

 [NullReferenceException: Object reference not set to an instance of an object.]
       StudentTestingPage.ButtonNext_Click(Object sender, EventArgs e) +2018
       System.EventHandler.Invoke(Object sender, EventArgs e) +0
       System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553178
       System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
       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

I tried everything that I know and searched about everything on internet but still unable to fix it. I have checked all the variables and arrays that can be set to null, the code is running fine on local machine. I have used SQL Server as database.

15
  • 1
    @Hanumendra - Just checked it gives null reference exception on the ButtonNext_Click() method Commented Sep 11, 2013 at 11:04
  • 1
    Holy cow that got closed quickly. I was in the middle of writing an answer. While the question has issues, this is clearly someone lacking a few basic debugging skills - maybe they don't know how to ask what they're looking for yet. Oh well. Commented Sep 11, 2013 at 11:05
  • 1
    @hanumendra: The clue is in the stack trace. You are calling a method or getting/setting a property on something that is null in the handler for ButtonNext. Look at your ButtonNext_Click() method and try to see what objects might be null. Commented Sep 11, 2013 at 11:05
  • 1
    @NeilBarnwell The problem is that this question isn't formulated nearly well enough to be useful to anyone else, and the OP hasn't put the information into the question that we need to solve their problem. Sure, we could use our psychic debugging powers, but that's not what Stack Overflow is meant for. Commented Sep 11, 2013 at 11:06
  • 2
    @NeilBarnwell Its called [on hold] for a reason, if it improves it will be reopened Commented Sep 11, 2013 at 11:15

1 Answer 1

1

The clue is in the stack trace. You are calling a method or getting/setting a property on something that is null in the handler for ButtonNext.

Look at your ButtonNext_Click() method and try to see what objects might be null.

If you can't replicate locally, then consider building a DEBUG build and deploying that. That should give you the actual line number throwing the exception in the stack trace.

However

This code has many serious issues. If you work on improving the overall quality of the code, simple things like NullReferenceException become easier to locate and resolve.

  1. Method length You need to cut your frankly MASSIVE ButtonNext_Click() method into many, small (maybe even less than 10 lines) descriptively-named methods. If you have ReSharper learn how to use it. If you don't, buy it and learn how to use it. However even Visual Studio has "Extract Method" these days - USE IT. In particular the contents of if/else blocks might be good candidates.
  2. SQL Injection You are being very naughty - concatenating SQL strings is a BAD IDEA. Instead, parameterise your SQL strings. Better still, use Entity Framework (comes free in the .NET framework) or something like Dapper.
  3. Don't use "NULL". Use null and note the important difference.

One last thing - you shouldn't see the Yellow Screen of Death, really. You should always turn it off in production in your web.config:

<customErrors mode="RemoteOnly" ... />
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Neil, Thanks a lot, I have fixed the issue with your help. You are really a nice human being
You're very welcome. Care to share exactly what the issue was, and why it was different in your production site than it was locally?

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.