1

Here Scenario is HttpContext.Current.Session["value"].ToString() gives null value, even have already set session value when user login.

My webconfig

<sessionState timeout="40" mode="InProc"/>

My global.asax

   void Session_Start(object sender, EventArgs e) 
    {
       // Code that runs when a new session is started
       Session["EmployeeId"] = "";
       this.Session["DomainName"] = "";
    }

In my Defaultpage.asppx.cs

Emp_grade empgrd = new Emp_grade(); gives Object reference not set to an instance of an object

using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Configuration;

public partial class EmpGrade : System.Web.UI.Page
{

   //here am getting error(The type initializer for 'Emp_grade' threw an exception)
   // stack error message  Object reference not set to an instance of an object.
   Emp_grade empgrd = new Emp_grade(); 

   protected void Page_Load(object sender, EventArgs e)
    {
      logic code...
      Datatable dt= empgrd.EmpRecord();
    }
}

In my App_Code folder i have class file Emp_grade.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Web.SessionState;

public class Emp_grade  
{       
    public Emp_grade()
    {
        //TODO: Add constructor logic here
    }

    static string getConnection = HttpContext.Current.Session["DomainName"].ToString();
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[getConnection].ConnectionString);

     public DataTable EmpRecord()
    {
       logic code
    }
 }

My login page:

 protected void Page_Load(object sender, EventArgs e)
    { 
    //set some value
     Session["DomainName"] = domainname;
    }

ScreenShot(Debugging) enter image description here

Satinder singh
  • 10,100
  • 16
  • 60
  • 102

2 Answers2

2

You should probably refactor a bit. This:

static string getConnection = HttpContext.Current.Session["DomainName"].ToString(); 

is a static field with an initializer. It will run once, and keep whatever value it got until the application is restarted. And it will run at a time that is not very well defined, it is only guranteed that it will run sometime before it is first accessed.

This means that it may well run at a time when no HttpContext is present (like Dan Puzey wrote) which will cause an exception to be thrown. Any subsequent attempt to access it will (to the best of my knowledge) result in the same Exception being thrown.

But keep in mind that it is only fetched once, so even if the initializer were to succeed and find a value, that value will be used for all subsequent uses of getConnection. It will not be fetched anew for each different user.

To fix that, you could wrap it in an instance method:

private string GetDomainName()
{
    return HttpContext.Current.Session["DomainName"].ToString();
}
SqlConnection conn = null;

and then initialize conn in the constructor:

public Emp_grade()         
{         
    conn = new SqlConnection(ConfigurationManager.ConnectionStrings[GetDomainName()].ConnectionString);
}

Please also note the since this class is initializing and storing a SqlConnection (which is IDisposable), your class should also implement the IDisposable interface. For background information about implementing IDisposable, see for instance this answer.

EDIT: The screenshot shows that the HttpContext.Current.Session is returning null.

The reason is this line:

Emp_grade empgrd = new Emp_grade();

This is declaring an instance member in the Page class, with an initializer. The initializer is run very early in the request pipeline, so at the point when it runs the Session is not yet present in the context.

Change to:

Emp_grade empgrd = null;

protected void Page_Load(object sender, EventArgs e) 
{ 
  empgrd = new Emp_grade();
  Datatable dt = empgrd.EmpRecord(); 
} 
Community
  • 1
  • 1
user1429080
  • 9,086
  • 4
  • 31
  • 54
  • thanks for reply, but still same error **System.NullReferenceException: Object reference not set to an instance of an object.** at `return HttpContext.Current.Session["DomainName"].ToString();` – Satinder singh Aug 16 '12 at 11:04
  • @satindersingh Then you must figure out which object is null on that line. It could be that `HttpContext.Current` is null, or `HttpContext.Current.Session` is null or simply that there is nothing in the Session with the key `DomainName`. To find out which, put a break point on the line and then when the breakpoint is hit, hover your mouse over each in turn and see what the tooltip shows. Also check the call stack to see where the class is being newed up. – user1429080 Aug 16 '12 at 11:13
  • pls check the screenshot, have updated my question, hope its helps – Satinder singh Aug 16 '12 at 11:23
1

You're referencing .Session["DomainName"] in a constructor for a static field. That will potentially run before any of your other code does. Quite possibly it will run outside of any HttpContext at all, because chances are it'll run as the application initialised, before the first request is processed.

I suspect that making getConnection non-static will fix the problem.

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96
  • I also suspect that creating a SQL connection in every instance of Emp_grade is not an ideal solution. – Maarten Aug 16 '12 at 10:20
  • getConnection non-static will fix the problem gives error " A field initializer cannot reference the non-static field, method, or property 'Emp_grade.getConnection'" – Satinder singh Aug 16 '12 at 10:20
  • @satindersingh: You should move your initialisation to the constructor instead, then. – Dan Puzey Aug 16 '12 at 11:54