Search code examples
c#asp.netwebformssession-variablesasp.net-4.0

How to get a return value when a given session variable is or isn't null


I use the following dedicated class to manage session variables in my applications (ignore misspelled names; that's intentional):

This first code block is for usage. You can see the class it is calling on, at the next code block

//'importing' the class for current project
using SeSn = Debug_Tests.Seseions.SeSn;

// creating an object (usually with name related to currentProject)
public static SeSn.CreatCurrentSesionVariablsStructNamed CurSesVarStruct = new Seseions.SeSn.CreatCurrentSesionVariablsStructNamed();

// the long name helps me in this little 'chaos'

This is an instance of a struct, that is 'grouping' or 'tying' all my globals into one bundle. Whenever I may need to store my global variables, I will assign the values into the appropriate-struct-variable that CurSesVarStruct has to offer.

Then all I need is to access session variables once, only to extract the "Variable-collection" -object, ... as it is actually a session variable that I keep its name constant - _CurrentSesionGlobals.

In short, it's the struct that is stored in the session as one of the session variables - data type = object, or you could say a clone of the struct to be saved between sessions.

Since I have that and can use it with _CurrentSesionGlobals, I could just access any value I need from session through the following, for example:

Assign the struct before storing it in Session:

CurSesVarStruct.SelectedUercustid = custID;

Then the next method - ExtrctSesnVar() below, allows me to use for example:

Extract a variable that was saved in last session:

custID = ExtractSesnVar().SelectedUercustid;

So SelectedUercustid is actually one of the struct members.

The Question/Problem

Performing extraction of _CurrentSesionGlobals out of the session variables.

public static SeSn.CreatCurrentSesionVariablsStructNamed ExtrctSesnVar()
{
    var CurrAppGlobals = SeSn.GetValueAS.ACloneOfTheStructObj("_CurrentSesionGlobals");
    return (SeSn.CreatCurrentSesionVariablsStructNamed)CurrAppGlobals;
  //the question is refereing this location.
}

How can I have a return value for a null result, or a condition that will first ask if the object / a given Session Variable, that I am trying to extract isn't null, or does not exist?

Currently there's an exception error while I am trying to get the value of a non-existing session variable.

The next code block is a class that I add into the solution, as a helper to every website application. It's actually a namespace, so the class that is responsible to handle session variables is Sesn:

namespace Seseions {
    public class Sesn {
        public static bool isNotEmpty() {
            return HttpContext.Current.Session.Keys.Count > 0;
        }
        public struct CreatCurrentSesionVariablsStructNamed {

            // some of commonly used variables- still testing options..

            public int ManagerCustID;
            public int SelectedUercustid;
            public int recordID;
            public int SelectedMonth;
            public int SelectedChosenWorker;
            public int SelectedYear ;

            
            public string SelectedTable;
            public string SelectedColumn;
            public string SqlSelectCommandLastQuery;
            public string TableOfUsersReference;
            public List<string> Fontlist { get; set; }

        }

        // converts and extract values of session variables

        public class GetValueAS {
            public static CreatCurrentSesionVariablsStructNamed ACloneOfTheStructObj(string currntProjectSesVarStructName) {
                if(HttpContext.Current.Session[currntProjectSesVarStructName] != null) {
                    return (CreatCurrentSesionVariablsStructNamed)HttpContext.Current.Session[currntProjectSesVarStructName]; 
            }

            public static int _Int(string SesParameterValToReturn) {
                return Convert.ToInt32(HttpContext.Current.Session[SesParameterValToReturn]);
            }

            public static string _String(string SesParameterValToReturn) {
                return Convert.ToString(HttpContext.Current.Session[SesParameterValToReturn]);
            }
            public static DataSet _DataSet(string SesParameterValToReturn) {
                return (DataSet)HttpContext.Current.Session[SesParameterValToReturn];
            }
            public static DataTable _DataTable(string SesParameterValToReturn) {
                return (DataTable)HttpContext.Current.Session[SesParameterValToReturn];
            }
            public static bool _Bool(string SeSnVarToCheckOn) {
                if (HttpContext.Current.Session[SeSnVarToCheckOn] == null)
                    return false;
                return (bool)HttpContext.Current.Session[SeSnVarToCheckOn];
            }
        }

        // an easy way to access and mange session variables actions
      public enum Act {
          Add, Remove, Replace
      }

      public static void Modify(Act action, string New_SesnVarName= null, object NewP_Value=null, string Currnt_Ses_SesnVarName=null) {
          switch (action) {
              case Act.Remove:
                  if (isNotEmpty()) {
                      HttpContext.Current.Session.Remove(CurSes_ParamName);
                  }
                  break;
              case Act.Replace:
                  HttpContext.Current.Session.Remove(CurSes_ParamName);
                  HttpContext.Current.Session.Add(New_SesnVarName, NewP_Value);
                  break;

              case Act.Add:
                  HttpContext.Current.Session.Add(NewQs_SesnVarName, NewP_Value);
                  break;
            }
        }
    }
}

Solution

  • Just don't do this.

    • critical: do not put Session (user) related data in static variables. It is not thread-safe.
    • best practice: try to avoid static in ASP.NET for everything else too.
    • best practice: do not use structs for anything but small, immutable and identity-less types

    It seems you are over-engineering this. All you need (for now) is to use some constants for the strings:

    public static class SessionKeys
    {
       public const string ManagerCustID = "ManagerCustID";
       ...
    }
    

    and then you can start focusing on code that adds value to your app.