Thursday, April 3, 2008

Singleton Session Manager

A long while back I found a post on CodeProject that wrapped session management into a facade pattern. At the time, I was fighting Session overload from developers who were moving from the classic asp world to .Net. I wanted an easy, centralized, type-safe way to manage sessions.

Preferably, I would have done away with sessions, but every time I thought I had figured out a way to do so, some situation arose that required the use of a session variable. So finally I bit the bullet and agreed but with some stipulations.

The following code was my stipulation. All session information had to go through this class.

[Serializable()]
class SiteContext
{

private const string SITE_CONTEXT = "ApplicationContext";

private SiteContext()
{

}

#region SiteContext Properties
public static SiteContext Current
{
get
{
SiteContext context;
if(HttpContext.Current.Session[SITE_CONTEXT] == null)
{
context = new SiteContext();
HttpContext.Current.Session[SITE_CONTEXT] = context;
}
else
{
context = (SiteContext)HttpContext.Current.Session[SITE_CONTEXT];
}

return context;
}
}

#endregion

#region SiteContext Fields

private int m_StartMonth;
public int StartMonth
{
get { return m_StartMonth;}
set { m_StartMonth = value;}
}

#endregion
}


Then in my code I could do this...

SiteContext.Current.StartMonth = 1 //Adds a value to session state

and

int Month = SiteContext.Current.StartMonth //Retrieves the value from session state

Nothing too fancy here, but it works great for centralizing session variables.

I would love to give the original poster credit for this code, but I couldn't find it. If anyone knows please send me the original post and I'll be glad to include it.

Wednesday, March 26, 2008

Subscribing to Events in Master Pages

There has been a lot written on communicating between master pages and user controls and some of it I actually understood. However, I never could get one solution to work for me so I ended up taking the approaches of a few and then making up the rest. What I ended up with was a workable solution.

My problem:
I have a master page with a list of projects and a button to view those projects. I have a nested master page within the main master page, then a page, and finally a user control.

I need to capture the event in my user control when the button on the main master page has been clicked.

Solution:
What I ended up doing was creating an interface called ISiteMaster. In this interface I define the event I want to subscribe to.

public interface ISiteMaster
{
event CommandEventHandler ViewProjects;
}

I implement the interface from the main master page. In the button event on my master page I then raise this event.
On the user control I then subscribe to this event and assign it to a method.

So now when I click the button on my master page it gets captured in the user control and voila!, the method on my user control is called.