Monday, April 24, 2017

Session is Null with SQL Server Session Mode

The Problem

Session variable works fine with InProc Session Mode but is null when you switch the Session Mode to SQLServer mode. 
You may see the following exception.
"Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode." 

Make sure you check the inner exception to see which class needs to be changed to Serializable.

Review all the data you have stored in Session variables to verify the data is serializable.  .NET knows how to automatically serialize the simple built in types like string, enum, integer, etc. Any classes you create are NOT serializable by default. Fortunately, you can make your classes serializable with a simple class attribute of [Serializable] like this.

public class Address
       public int      nStreetNum;
       public string strStreetName;

public class Customer
      public string strFirstName;
      public string strLastName;
      public Address Addr;  // The Address class must be serializable.

      public Customer(string FirstName, string LastName, Address theAddr)
          strFirstName = FirstName;
          strLastName = LastName;
          Addr = theAddr;

Your class must meet these requirements to be serializable:

  • Your class must have the Serializable attribute
  • Any classes it derives from must have the Serializable attribute.
  • All class member variables must be serializable types.  For example, the Address type used for Customer Addr member variable must also be serializable.

Visit if you need custom software development.

Saturday, April 8, 2017

Get Session Variable and Check for Null

Accessing a Session variable that hasn't been created causes a null exception.   You can use the C# null-coalescing(??) or 'as' operators to simplify and avoid a null exception.

First two examples yield the same result;
myClassObj will receive the myClassObj stored in the Session variable if it exists; otherwise null.

With ?? Operator

   MyClass myClassObj = (MyClass)Session["mySessionName"] ?? null;

With as Operator

   MyClass  myClassObj = Session["mySessionName"] as MyClass 

With Both Operators

   string strMyClass = Session["mSessionName"] as string ?? "";