We help IT Professionals succeed at work.

Checking if the Session object exists

purplesoup
purplesoup asked
on
I'm writing a component test of some asp.net code, and I want to make sure it runs if the session object doesn't exist.

I tried

if (Session != null) Session["xxx"] = foo;

but I am still getting a null reference exception - do I have to put it in a try/catch block or is there some way to actually check if the Session object exists?
Comment
Watch Question

Kiran SonawaneProject Lead
Top Expert 2011

Commented:
You need to check like this

if (Session["xxx"]  != null)
 Session["xxx"] = foo;
Kiran SonawaneProject Lead
Top Expert 2011

Commented:
 if (Session["xxx"] == null)
            {
              // Code if session null
            }
            else
            {
               // code if session not null
            }
purplesoupProgrammer

Author

Commented:
sonawanekiran - this is still giving me a NullReferenceException - when I check for Session["xxx"] I get the error.

Eyal - I put in a check

if (System.Web.HttpContext.Current.Session.Contents.Count != null)

but I'm still getting a NullReferenceException making the check.
Whenever you hit this error, back up a bit. You have to find out which object isn't set. The way to do that is to test each tier before proceeding, at least while debugging until you can figure out what's wrong and why. After that you don't always have to go overboard.

Example:

1. Check if Systemn.Web.HttpContext.Current is populated.
2. Check if the Session is populated.
3. Check the Contents.

See what I'm doing? Check each object before trying to dive into that object's properties.

You'd get the same situation if you checked myString.Length if myString were null.
purplesoupProgrammer

Author

Commented:
There is nothing wrong, I'm just trying to call the code from a unit test so the page isn't loaded normally, however I need some way to avoid the calls to Session, as it throws a NullReferenceException whenever I go near it.
Ha! You didn't mention that before! ;)

You can't do that. If you need to test web code, you need to structure your code in a way to support it and use a mock object to stand in for the context. Honestly, I started down that road and hit so many road blocks that I abandoned the idea of unit testing that portion of the code.
purplesoupProgrammer

Author

Commented:
Well I'll give this the points as it pointed me to the answer - the correct way to check - or the way that worked for me anyway was this

                if (HttpContext.Current != null)
                {
                      Session["xxx"] = foo;
                }