[ASP.net] refactoring session does make code simple and clean.

Source: Internet
Author: User
Tags httpcontext tostring
Asp.net|session

As the authors say, we often use many code similar to the following to detect objects stored in the session in ASP.net to prevent loss of variables stored after the session expires:
Int32 Nuserid =-1;
if (null!= session["UserID"]) {
if (session["UserID"] is Int32) {
if (0 < session["UserID"]) {
Nuserid = (Int32) session["UserID"]
}
}
}
if (-1 = nuserid)
{
throw new ApplicationException ("Unexpected Situation:userid invalid.");
}

This.dosomething (Nuserid);
Such code can be found all over the globe.

Then, using his package to do refactoring, it does make the code clean a lot of simplicity!
After his encapsulation, the code above is just a word:

This.dosomething (Ccurrentsession.userid)

His class is actually very simple, as follows:


Using System;
Using System.Web;

/**////--------------------------------------------------------------------
///developed by M. Van Eijkel- Aug
///[E]: marcelvaneijkel@gmail.com
///[W]: www.vaneijkel.com

Namespace Vaneijkel.web
{
   /**////<summary>
   ///Wrapper Class for the Session object.
   ///It centralizes the logic for retrieving and validation to session information.
   ///by using a approach like this to improve the protection and encapsulation of existing code.   ///It offers a simple, low-risk, easy manageable way to improve existing.
   ///therfore, I call it webrefactoring.
   ///</summary>
    public class Currentsession
    {
    constants#region Constants
    Private Const String Smandatory_session_key _not_found_msg = "Session variable excepted but does not exist." Key={0} ";
    Private Const String smandatory_session_value_invalid_null = "None NULL session VALUE excepted. Key={0} ";

Private Const Int32 Nuserid_unkown =-1;
Private Const Int32 Nuserid_minimum = 1;
Private Const String Suserid_invalid = "INVALID userid:{0}. UserID should be larger than:{1}";
#endregion

Userid#region UserID
/**////<summary>
Returns the UserID as a Int32 instead of an object.
This is way you'll get the compiler protection and intelligence support you need.
</summary>
public static Int32 UserID
{
Get
{
Return (Int32) GetValueOrDefault (Ekeys.userid, Nuserid_unkown);
}
Set
{
if (nuserid_minimum >= value)
{
throw new ApplicationException (String.Format (suserid_invalid, Value, Nuserid_minimum));
}
SetValue (Ekeys.userid, value);
}
}
#endregion

Private:getvalueordefault (Ekeys EKey, Object odefaultvalue) #region Private:getvalueordefault (Ekeys EKey, Object Odefa Ultvalue)
/**////<summary>
Gets the value from the Session object.
</summary>
<param name= the "EKey" > The session key to get the value for.</param>
<param name= "Odefaultvalue" >the default value to use if no valid value stored.</param>
<returns>when The value is null or the key does not exist,
The specified default value is returned.
Otherwise, the value is returned</returns>
Private static Object GetValueOrDefault (Ekeys EKey, Object Odefaultvalue)
{
Get the value
Object ovalue = GetValue (EKey);

Value not found or null?
if (null = = Ovalue)
{
Return default value
return odefaultvalue;
}

     //everything Oke:return Session value
      return Ovalue;
   }
    #endregion
    private:getmandatoryvalue (Ekeys eKey) #region Private: Getmandatoryvalue (Ekeys eKey)
   /**////<summary>
   ///Returns the Session value for a session-key that must exist.
   ///If The key does not exist a applicationexception is thrown.
   ///</summary>
   ///<param name= "EKey" > The Session-key to Return to the Session-value for. </param>
   ///<returns> A none-null value.</returns>
    Private static Object Getmandatoryvalue (Ekeys eKey)
    {
     //get The value
      object ovalue = GetValue (EKey);

     //key not found or value null?
      if (null = ovalue)
      {
        //throw ApplicationException because its application logic error (none CLR)
  & nbsp;     throw new ApplicationException (String.Format (smandatory_session_key_not_found_msg, Ekey.tostring ()));
     }

     //everything Oke:return value
      return ovalue
   }
    #endregion
    private:getvalue (Ekeys eKey) #region Private:getvalue (Ekeys eKey)
   /**////<summary>
   ///Gets the session Value from the specified key.
   ///</summary>
   ///<param name= "EKey" >the key to get the value F Rom</param>
   ///<returns>the Session value for the specified session key.
   ///If The key does not exist and Null is returned.
   ///</returns>
    private static Object GetValue (Ekeys eKey)
    {
      return httpcontext.current.items[ekey.tostring ()];
   }
    #endregion

Private Setmandatoryvalue (Ekeys EKey, Object ovalue) #region private Setmandatoryvalue (Ekeys EKey, Object Ovalue)
private static void Setmandatoryvalue (Ekeys eKey, Object ovalue)
{
if (null = = Ovalue)
{
throw new ApplicationException (String.Format (Smandatory_session_value_invalid_null, ekey.tostring ()));
}
}
#endregion
Private SetValue (Ekeys EKey, Object ovalue) #region private SetValue (Ekeys EKey, Object Ovalue)
/**////<summary>
Stores the specified session-value to the specified session-key.
</summary>
<param name= "EKey" >the key for the ' value to ' store in the session.</param>
<param name= "Ovalue" >the value to store in the session</param>
private static void SetValue (Ekeys eKey, Object ovalue)
{
Httpcontext.current.items[ekey.tostring ()] = Ovalue;
}
#endregion

/**////<summary>
An enum for the
</summary>
Private Enum Ekeys
{
Userid
}
}
}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.