Click here to Skip to main content
12,503,591 members (55,807 online)
Click here to Skip to main content
Add your own
alternative version

Stats

11.4K views
211 downloads
15 bookmarked
Posted

Session Manager Utility for asp.Net

, 6 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.

Introduction

In my last post http://www.codeproject.com/Tips/790387/Session-in-ASP-NET-MVC

I explained how to use single session for asp.Net MVC projects. Single session is obviously the best practice. But some time we many need to use multiple sessions in our project. So let’s check a utility class for our session management.

Background

The aim would be to make a

- Utility class which will be able to full fill our session based requirement. Like adding, removing, replacing, retrieving .. etc. sessions.

- Session enlistments, so that we will be able to say at a glance what number of sessions is been used in our project, and using which keys they are been stored.

Using the code

First we will try to enlist each individual the session’s keys/names using a enum. This enum will help use in later cores.

internal enum SessionEnum
{
    LogOn,
    Permission,
    LogInName,
    LogInTime
}

Now lest see the SessionManager which manage our sessions.

As you can see we can make an object of this class by providing the previously discussed SessionEnum or not. And it is important to know.

  •  If you want to use the methods declared inside the #region session, you obviously have to provide a SessionEnum, or an error would be shown. Because they works for a particular session key only.

Rest of the methods works with some basic session management requirements like (see the public/internal methods.)

internal class SessionManager
{
    private readonly HttpSessionState _session;
    private readonly SessionEnum? _sessionKey;
    private string SessionName
    {
        get
        {
            if (_sessionKey == null)
            {
                throw new NullReferenceException("No sessionKey provided at the constructor");
            }
            return _sessionKey.ToString();
        }
    }

    internal SessionManager()
    {
        _session = HttpContext.Current.Session;
    }

    internal SessionManager(SessionEnum sessionKey) : this()
    {
        _sessionKey = sessionKey;
    }

    #region Depends on SessionKey provied using constructor
    internal bool DoesKeyExist()
    {
        if (!HasAnySessions())
        {
            return false;
        }
        bool exist = false;
        for (int i = 0; i < _session.Count; i++)
        {
            exist = _session.Keys[i] == SessionName;
            if (exist)
            {
                break;
            }
        }
        return exist;
    }

    internal bool IsNull()
    {
        return _session[SessionName] == null;
    }

    internal void SetNull()
    {
        _session[SessionName] = null;
    }

    internal TSource Get<TSource>()
    {
        return (TSource) _session[SessionName];
    }

    internal void Add<TSource>(TSource model)
    {
        _session.Add(SessionName, model);
    }

    internal void Replace<TSource>(TSource model)
    {
        _session[SessionName] = model;
    }

    internal void Remove()
    {
        _session.Remove(SessionName);
    }
    #endregion


    internal string GetSessionId()
    {
        return _session.SessionID;
    }

    internal bool HasAnySessions()
    {
        return _session.Count > 0;
    }

    internal void RemoveAll()
    {
        _session.RemoveAll();
    }

    internal void AbandonSessions()
    {
        _session.Abandon();
    }
}

Some of the uses,

/*Adding sessions*/
new SessionManager(SessionEnum.LogOn).Add(new UserSessionModel(){LogInName = "scott", LogInTime = DateTime.Now});
new SessionManager(SessionEnum.LogInName).Add("scott");
new SessionManager(SessionEnum.LogInTime).Add(DateTime.Now);

/*Session id*/
string sessionId = new SessionManager().GetSessionId();

/*HasAnySessions*/
bool hasSession = new SessionManager().HasAnySessions();

/*DoesKeyExist*/
bool hasLogOnKey = new SessionManager(SessionEnum.LogOn).DoesKeyExist();                //true
bool hasPermissionKey = new SessionManager(SessionEnum.Permission).DoesKeyExist();      //false as it is not added yet

/*IsNull*/
bool isLogOnSessionNull = new SessionManager(SessionEnum.LogOn).IsNull();               //false
bool isPermissionSessionNull = new SessionManager(SessionEnum.Permission).IsNull();     //true as it is not added yet

/*Replace*/
new SessionManager(SessionEnum.LogOn).Replace(new UserSessionModel() { LogInName = "scottRocks", LogInTime = DateTime.Now.AddDays(-2) });

/*Get*/
var user = new SessionManager(SessionEnum.LogOn).Get<UserSessionModel>();   //success

/*Remove*/
new SessionManager(SessionEnum.LogOn).Remove();
user = new SessionManager(SessionEnum.LogOn).Get<UserSessionModel>();       //null


var manager = new SessionManager();

/*Remove All*/
manager.RemoveAll();
hasSession = new SessionManager().HasAnySessions();

/*Abandon Session*/
manager.AbandonSessions();
hasSession = new SessionManager().HasAnySessions();

Make the flexibility little titer

our above class works fine. But if you want to add some restrictions. Which is important if you are working with multiple session objects in project.

1. Avoid using a key to be added, more than once.

2. Get a session means, it need to be present still now with specifing type. Being null is not acceotabke.

3. Remove a session means, Being null is not acceotabke.

4. If onece created a session with a specific type of objec using specific key, it can only hold that type of object for life cyle.

means you know exectly what is going on with the sessions, and its going on as we wanted to be.

 

To do so, reedit the utility class by replacing  some of the methods from above. Which may look like mines,

internal TSource Get<TSource>()
{
	if (IsNull())
	{
		throw new Exception(String.Format("The session with key '{0}' is null", SessionName));
	}
	return (TSource) _session[SessionName];
}

internal void Add<TSource>(TSource model)
{
	if (DoesKeyExist())
	{
		throw new Exception(String.Format("The session key '{0}' is already been used, try using another key",
			SessionName));
	}
	_session.Add(SessionName, model);
}

internal void Replace<TSource>(TSource model)
{
	if (!DoesKeyExist())
	{
		throw new Exception(String.Format("The session key '{0}' is not been used yet", SessionName));
	}

	if (!IsNull() && (model.GetType() != _session[SessionName].GetType()))
	{
		throw new Exception(
			String.Format("The old data type of session key '{0}' is not matching with the new data type",
				SessionName));
	}
	_session[SessionName] = model;
}

internal void Remove()
{
	if (!DoesKeyExist())
	{
		throw new Exception(
			String.Format("The session with the key '{0}' is already been removed, or not used yet", SessionName));
	}
	_session.Remove(SessionName);
}

Limitations

1. I have tested the code on asp.net web forms, web service, and mvc

2. If you want user session model need to be more typed, try to avoid Base-child relational models on the replace method. Because the comparison of may vary at some points

model.GetType() != _session[SessionName].GetType()

3. Try to use it inside the First Server Communication Layer only, rather than at logic or data layers.

 

Find the Visual Studio 2010 project solution at the attachment.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DiponRoy
Bangladesh Bangladesh
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralThank you! Pin
dimas197119-May-15 4:42
memberdimas197119-May-15 4:42 
GeneralRe: Thank you! Pin
DiponRoy19-May-15 23:59
memberDiponRoy19-May-15 23:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160919.1 | Last Updated 7 Jul 2014
Article Copyright 2014 by DiponRoy
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid