ASP.NET Sessions and OOPS

In this article we will try to understand how to make ASP.Net session objects Type Safe and override safety.

OOP

Object Oriented Programming - It just means reusability and making things more manageable.

All the architectures and technologies are just based on them or we can say derived from them.

ASP.NET Session

ASP.Net Session objects are basically used to store user-specific data, data which will be needed in more than one page related to a user.

Problem Statement

A company ABC organization is working on an E-Commerce website with around 5 developers. Each developer is working on one module.

  1. Problem 1

    Say Developer 1 is working on a Book sale module and Developer 2 on a Magazine sale module. Now there is a strong possibility that Developer 1 will for example create a session variable say TotalPrice to store the TotalPrice of books (which keeps on updating as the end user purchases new books), and even Developer 2 creates the session variable with the same name since both are unaware about the other person's code.
     
  2. Problem 2

    The Project Manager also wants to control the number of session variables used (because more session variables mean more memory consumed which results in lower performance.)

Solution

Make project architecture in such a way that for sessions there will be a central repository, if anybody wants to access or modify session values they go through that repository. For that create a Class SessionManager as follows:

public class ClsStateManagement
{

    public string UserId
    {

        get
        {

            if (HttpContext.Current.Session["UserId"] == null)

                return null;

            return HttpContext.Current.Session["UserId"].ToString();

        }

        set
        {

            HttpContext.Current.Session["UserId"] = value;

        }

    }

    public int TotalPrice
    {

        get
        {

            if (HttpContext.Current.Session["TotalPrice"] == null)

                return 0;
 
                    return int.Parse(HttpContext.Current.Session["TotalPrice"].ToString());

         }

 

         set

         {

 

             HttpContext.Current.Session["TotalPrice"] = value;
 
         }

     }
 

 }

We wrapped all session data and hid all the unnecessary things from the external world; that's called encapsulation.

Hope you enjoyed the article, make sure to leave some good comments.
 


Similar Articles
Just Compile LLP
Just Compile is an IT based firm based out of Mumbai. Application Development, Staffing, Training