Checking for a null session is a serious matter
While using Infragistics NetAdvantage for ASP.NET I noticed a bug while working with the UltraGauge (WebGauge) control. It turns out that if you disable session state for the page that this control is on or for the entire web application as I had done for performance reasons, you get a nasty error:
"Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration."
It turns out that the logic in Infragistic's source code was not that bad, it tested if the page was null, that we weren't in design mode, and then used this little snippet of code which was throwing the exception:
"if (this.Page.Session != null) {…"
This may seem like a sane check, and for the life of me it took a while to figure out what the problem was… turns out that if you call the get { } accessor in the Page's Session property, it in turn calls a method, get_Session(), which throws this exception upon not having access to session or a proper provider/handler. While I lodged a bug with Infragistics to put in a fix for this control, I went ahead and searched for a solution myself.
Inheritance is a wonderful thing, and so are virtual properties
The SAFE way to check whether or not it is valid to use session, regardless if you are on a page, control, static class, etc, is to use HttpContext.Current.Session. For example:
if (HttpContext.Current.Session != null)
{
// do stuff
}
Therefore, we needed to override the Page's default behavior to add a "safe" get for the Session property:
public override HttpSessionState Session
{
get
{
if (HttpContext.Current.Session == null)
return null;
else
return base.Session;
}
}
By putting this code in my Page's code-behind, I was able allow the WebGauge control to safely check if Session was null through the Page's Session property without this operation throwing an exception. I was also able to circumvent the need for a re-compile or further code changes should I ever want to re-enable session state in my application or even for that page.
Update
Dear Infragistics Customer,
The following WebGauge issue that you reported has been addressed in a hotfix release:
BR29520 – Exception throw when using the WebGauge with FileSystem deployment, and SessionState turned off for the website.
Incident(s):
WeG73
Hotfix Version(s):
7.2.20072.1072 CLR 2.0, 7.3.20073.1046 CLR 2.0, 8.1.20081.2001 CLR 2.0, 8.1.20081.2001 CLR 3.5


3 Responses Leave a comment
Thank you for the tips. Now i know how to do it.
Excellent post..Keep them coming
Thanks for sharing.
This is what I’ve been looking for! Thank you so much for sharing this!