locked
Object reference not set to an instance of an object RRS feed

  • Question

  • User-1066344940 posted

    I am getting a weird error all of the sudden, and no matter how I change my code, the error is happening on the same line(157). It is telling me; "Object reference  not set to an instance of  an object". I tried to set a break on my page load event, so that I can step through all of my calls and functions, but it is not breaking?! I am getting the user on page load, and then getting their zipcode, whicvh I pass to a method. Here is my code, does anyone see anything wrong? the errors are provided. The funny thing is, this is working in test. I even copied the code from test to dev(this code here) and I am getting this error.

    protected void Page_Load(object sender, EventArgs e)
            {
    
                pnlMaintenance.Visible = false;
                GetDateModified();
                if (!IsPostBack)
                {
                    Users user = new Users();//check the users access level against the users table
                    user.GetUser();
                    if (user.AccessLevel == "A")
                    {
                        pnlMaintenance.Visible = true;
                    }
                    else
                    {
                        user.AccessLevel = "U";
                        pnlMaintenance.Visible = false;
                    }
                    Session["accessLevel"] = user.AccessLevel;
                    lblEmpId.Text = user.EmployeeId;
                    if (lblEmpId.Text != "")
                    {
                       
                        String sqlCmd = //my query;
    
                        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["prodConnectionString"].ConnectionString);
                        SqlCommand cmd = new SqlCommand(sqlCmd, conn);
                        cmd.CommandType = CommandType.Text;
    
                        try
                        {
                            conn.Open();
                            SqlDataReader rdr = cmd.ExecuteReader();
                             string zip = "";
                            rdr.Read();
                            if (rdr == null || !rdr.HasRows)
                            {
                                System.Web.HttpContext.Current.Response.Redirect("http://www.somepage.org/");// if user is not in AD, send to somepage.org
                            }
                            else
                                
                                zip = rdr["ZIP"].ToString();//when I set a break on the catch, the execution jumps from here, down to the last line, hdnLongitude = ConvertTo......
                            
                        }
                        catch (SqlException ex)
                        {
                            Console.Write(ex.Message);
                        }
                        finally
                        {
                            conn.Close();
                            
                        }
    lblLatlng.Text = GeocodeAddress(zip);
    LocationResult workcoordinates = new LocationResult();
    workcoordinates.GetCoordinates(lblLatlng.Text);
    hdnLatitude.Value = Convert.ToString(workcoordinates.Latitude);
    hdnLongitude.Value = Convert.ToString(workcoordinates.Longitude); //it jumps to here and I get the error.
      }//end if
    //when i change the code to this, by moving the code block up into the else statement, I still get an error on line 157, but now it says that my finally is not set to an instance of an object??
    protected void Page_Load(object sender, EventArgs e)
            {
    
                pnlMaintenance.Visible = false;
                GetDateModified();
                if (!IsPostBack)
                {
                    Users user = new Users();//check the users access level against the users table
                    user.GetUser();
                    if (user.AccessLevel == "A")
                    {
                        pnlMaintenance.Visible = true;
                    }
                    else
                    {
                        user.AccessLevel = "U";
                        pnlMaintenance.Visible = false;
                    }
                    Session["accessLevel"] = user.AccessLevel;
                    lblEmpId.Text = user.EmployeeId;
                    if (lblEmpId.Text != "")
                    {
                       
                        String sqlCmd = //my query;
    
                        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["prodConnectionString"].ConnectionString);
                        SqlCommand cmd = new SqlCommand(sqlCmd, conn);
                        cmd.CommandType = CommandType.Text;
    
                        try
                        {
                            conn.Open();
                            SqlDataReader rdr = cmd.ExecuteReader();
                             string zip = "";
                            rdr.Read();
                            if (rdr == null || !rdr.HasRows)
                            {
                                System.Web.HttpContext.Current.Response.Redirect("http://www.somepage.org/");// if user is not in AD, send to somepage.org
                            }
                            else
                                
                            zip = rdr["ZIP"].ToString();
                            lblLatlng.Text = GeocodeAddress(zip);
                            LocationResult workcoordinates = new LocationResult();
                            workcoordinates.GetCoordinates(lblLatlng.Text);
                            hdnLatitude.Value = Convert.ToString(workcoordinates.Latitude);
                            hdnLongitude.Value = Convert.ToString(workcoordinates.Longitude);
    
                        }
                        catch (SqlException ex)
                        {
                            Console.Write(ex.Message);
                        }
                        finally
                        {
                            conn.Close();
                            
                        }
                        
                    }//end if
    
    
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "GetMap", "<script language='javascript'> document.addEventListener('DOMContentLoaded', GetMap, false); </script>");//load default map
                }
    Line 155:                        Console.Write(ex.Message);
    Line 156:                    }
    Line 157:                    finally   //error here now
    Line 158:                    {
    Line 159:                        conn.Close();
     
    

    I am stumped. My app wont break on page load either so I can step through it, it only breaks on the catch.



    Saturday, June 8, 2013 9:31 AM

Answers

  • User281315223 posted

    I believe there is an issue if an error occurs within the try-block that will cause a null reference to be thrown within your finally block. 

    You may want to consider revising your existing code and instead of manually instantiating an instance of your connection, consider using a much safer "using" statement, which will handle properly closing and disposing of your SqlConnection object : 

    protected void Page_Load(object sender, EventArgs e)
    {
            pnlMaintenance.Visible = false;
            GetDateModified();
            if (!IsPostBack)
            {
                Users user = new Users();//check the users access level against the users table
                user.GetUser();
                if (user.AccessLevel == "A")
                {
                    pnlMaintenance.Visible = true;
                }
                else
                {
                    user.AccessLevel = "U";
                    pnlMaintenance.Visible = false;
                }
                Session["accessLevel"] = user.AccessLevel;
                lblEmpId.Text = user.EmployeeId;
    
                //Changed this to use the safer String.IsNullOrEmpty() method
                if (!String.IsNullOrEmpty(lblEmpId.Text))
                {
                    String sqlCmd = //my query;
    
                    //Added a using statement to handle your connection (you won't have to dispose of it
                    //manually
                    using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["prodConnectionString"].ConnectionString)
                    {
                        SqlCommand cmd = new SqlCommand(sqlCmd, conn);
                        cmd.CommandType = CommandType.Text;
    
                        try
                        {
                            conn.Open();
                            SqlDataReader rdr = cmd.ExecuteReader();
                            string zip = "";
                            rdr.Read();
                            if (rdr == null || !rdr.HasRows)
                            {
                                //Handle your redirect
                                System.Web.HttpContext.Current.Response.Redirect("http://www.somepage.org/");
                            }
                            else
                            {
                                zip = rdr["ZIP"].ToString();
                                lblLatlng.Text = GeocodeAddress(zip);
                                LocationResult workcoordinates = new LocationResult();
                                workcoordinates.GetCoordinates(lblLatlng.Text);
                                hdnLatitude.Value = Convert.ToString(workcoordinates.Latitude);
                                hdnLongitude.Value = Convert.ToString(workcoordinates.Longitude);
                            }
                        }
                        catch (SqlException ex)
                        {
                            Console.Write(ex.Message);
                        }   
                    }
                } 
                //Loading your default map
                Page.ClientScript.RegisterStartupScript(this.GetType(), "GetMap", "<script language='javascript'> document.addEventListener('DOMContentLoaded', GetMap, false); </script>");
            }
    }
    

    If you are still encountering errors, I would highly recommend placing a breakpoint within this code to determine where this could possibly be failing at. I would make sure to check inside the actual SqlConnection block itself and take a look at the Inner Message within the details of an Exception if one occurs.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 8, 2013 9:48 AM

All replies

  • User281315223 posted

    I believe there is an issue if an error occurs within the try-block that will cause a null reference to be thrown within your finally block. 

    You may want to consider revising your existing code and instead of manually instantiating an instance of your connection, consider using a much safer "using" statement, which will handle properly closing and disposing of your SqlConnection object : 

    protected void Page_Load(object sender, EventArgs e)
    {
            pnlMaintenance.Visible = false;
            GetDateModified();
            if (!IsPostBack)
            {
                Users user = new Users();//check the users access level against the users table
                user.GetUser();
                if (user.AccessLevel == "A")
                {
                    pnlMaintenance.Visible = true;
                }
                else
                {
                    user.AccessLevel = "U";
                    pnlMaintenance.Visible = false;
                }
                Session["accessLevel"] = user.AccessLevel;
                lblEmpId.Text = user.EmployeeId;
    
                //Changed this to use the safer String.IsNullOrEmpty() method
                if (!String.IsNullOrEmpty(lblEmpId.Text))
                {
                    String sqlCmd = //my query;
    
                    //Added a using statement to handle your connection (you won't have to dispose of it
                    //manually
                    using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["prodConnectionString"].ConnectionString)
                    {
                        SqlCommand cmd = new SqlCommand(sqlCmd, conn);
                        cmd.CommandType = CommandType.Text;
    
                        try
                        {
                            conn.Open();
                            SqlDataReader rdr = cmd.ExecuteReader();
                            string zip = "";
                            rdr.Read();
                            if (rdr == null || !rdr.HasRows)
                            {
                                //Handle your redirect
                                System.Web.HttpContext.Current.Response.Redirect("http://www.somepage.org/");
                            }
                            else
                            {
                                zip = rdr["ZIP"].ToString();
                                lblLatlng.Text = GeocodeAddress(zip);
                                LocationResult workcoordinates = new LocationResult();
                                workcoordinates.GetCoordinates(lblLatlng.Text);
                                hdnLatitude.Value = Convert.ToString(workcoordinates.Latitude);
                                hdnLongitude.Value = Convert.ToString(workcoordinates.Longitude);
                            }
                        }
                        catch (SqlException ex)
                        {
                            Console.Write(ex.Message);
                        }   
                    }
                } 
                //Loading your default map
                Page.ClientScript.RegisterStartupScript(this.GetType(), "GetMap", "<script language='javascript'> document.addEventListener('DOMContentLoaded', GetMap, false); </script>");
            }
    }
    

    If you are still encountering errors, I would highly recommend placing a breakpoint within this code to determine where this could possibly be failing at. I would make sure to check inside the actual SqlConnection block itself and take a look at the Inner Message within the details of an Exception if one occurs.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 8, 2013 9:48 AM
  • User-1716253493 posted
    When getting session check first it's exist. If (Session["accessLevel"]!=null) {...}
    Saturday, June 8, 2013 10:06 AM
  • User465171450 posted

    You can't use Console.Write in a web application. This is for console applications and desktop apps. Try using the trace log. Enable tracing in your web.config by <trace enabled="true" /> in the <system.web> section. Then you can access the trace log by browsing to your app and viewing the trace.axd page (this is a page created by the trace handler). You can output to the trace using Trace.Write() and Trace.Warn(). By default, it only holds the first 10 pages after recompile but that can be changed. It could very well be that your catch is causing this error.

    Saturday, June 8, 2013 10:10 AM
  • User-1066344940 posted

    I'm getting errors here:

     SqlCommand cmd = new SqlCommand(sqlCmd, conn);
                        cmd.CommandType = CommandType.Text;

    and here:

    conn.Open();
    SqlDataReader rdr = cmd.ExecuteReader()

    the errors are on the:

    SqlCommand cmd

    cmd

    conn

    cmd

    Invalid initializer member declaration.

    ',' expected

    the name conn does not exist in the current context

    the name cmd does not exist in the current context

    Can you check your syntax? thanks allot.

    Saturday, June 8, 2013 2:31 PM
  • User-1066344940 posted

    Adding this  <trace enabled="true" /> to my<system.web> caused an error, are you sure you have the right tag??

    Saturday, June 8, 2013 2:35 PM
  • User-1066344940 posted

    I placed this syntax and can view the trace log now:

    <trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/>

    I view it by navigating too my apps root. Thanks.

    Saturday, June 8, 2013 3:17 PM
  • User-1066344940 posted

    Hi Rion,

    I did everything you told me to. I used this code:

    //using to handle Dispose
                        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["prodConnectionString"].ConnectionString))
                        {
                            SqlCommand cmd = new SqlCommand(sqlCmd, conn);
                            cmd.CommandType = CommandType.Text;
                            conn.Open();
    
                            try
                            {
                               
                                SqlDataReader rdr = cmd.ExecuteReader();
                                rdr.Read();
                                if (rdr == null || !rdr.HasRows)
                                {
                                    //Handle redirect
                                    System.Web.HttpContext.Current.Response.Redirect("http://www.somesite.org/");
                                }
                                else
                                {
                                    zip = rdr["ZIP"].ToString();
    
                                }
                            }
                            catch (SqlException)
                            {
                                Trace.Warn("An error occured");
                            }
                            lblLatlng.Text = GeocodeAddress(zip);
                            LocationResult workcoordinates = new LocationResult();
                            workcoordinates.GetCoordinates(lblLatlng.Text);
                            hdnLatitude.Value = Convert.ToString(workcoordinates.Latitude);
                            hdnLongitude.Value = Convert.ToString(workcoordinates.Longitude);
                        }
                    }

    My rdr is cumming up null, and if I set the break after the if statement:

    if (rdr == null || !rdr.HasRows)
     {  /I set the break here to check if the rdr is null and it is. also, conn and cmd are null

    I step through the rest and it hits the Redirect, and it hits the statement inside of the else statement:

    zip = rdr["ZIP"].ToString();

    Also, I have a watch set on both conn, and cmd, and they have values, I see my SqlCmd query, and the conn connection object. I step over again and it jumps over the Catch and starts running here:

    lblLatlng.Text = GeocodeAddress(zip);





    Saturday, June 8, 2013 4:04 PM
  • User-1066344940 posted

    Hi Rion,

    I took your advice and wrappped my sql in a using statement, The problem was a missing ')' after the  using:

    using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["prodConnectionString"].ConnectionString)) //was missing this closing paren

    I also had some old assemblies that my app was poointing too. I got rid of the .pdb files, rebuild my project, and the issue is resolved now. Thanks for the advice.

    Monday, June 10, 2013 12:55 PM