0

My primary problem is, that I have a code, which is full of method calls to set/get session variables which makes the source hard to read. I am searching for a better/simpler/more elegant solution. I tried operator overload in classes, wrapper classes, implicit type conversion, but I run into problems with all of them.

I would like to handle session variables like regular variables. After reading a lot of articles, I came up with the following solution which I'd like to make even simpler:

public class SV_string
{
    private string key = ""; //to hold the session variable key

    public SV_string(string key)
    {
        this.key = key; // I set the key through the constructor
    }
    public string val // I use this to avoid using setter/getter functions
    {
        get
        {
            return (string)System.Web.HttpContext.Current.Session[key];
        }
        set
        {
            System.Web.HttpContext.Current.Session[key] = value;
        }
    }
}

I use the same key as the variable name:

public static SV_string UserID = new SV_string("UserID"); 

UserID.val = "Admin"; //Now the value assignment is quite simple
string user = UserID.val; //Getting the data is quite simple too

UserID = "Admin"; //but it would be even simpler

So is there any way to get the desired behaviour?

Thanks in advance!

5
  • 1
    Don't think there's going to be a way to do this - and I'm not sure you should want to do this, either, since it's going to be unintuitive to any C# developer. You might be better off using a method instead (UserID.SetValue("Admin")). Commented Oct 10, 2016 at 11:29
  • This is just the facade design pattern. Seems perfectly fine to me. Commented Oct 10, 2016 at 11:30
  • Your naming is terrible BTW Commented Oct 10, 2016 at 11:31
  • Ant P: Using methods is just a way I want to avoid. The source code I got is full of method calls and looks terrible. Commented Oct 11, 2016 at 9:25
  • yildizm80: What do you mean "your naming is terrible"? Commented Oct 11, 2016 at 9:25

3 Answers 3

1

You can create the following Session Wrapper and just add your methods/properties/members to it

public static class EasySession
{
    public static string UserId
    {
        get
        {
            return Get<string>();
        }
        set
        {
            Set(value);
        }
    }

    public static string OtherVariableA
    {
        get
        {
            return Get<string>();
        }
        set
        {
            Set(value);
        }
    }

    public static <datatype> OtherVariableB
    {
        get
        {
            return Get<datatype>();
        }
        set
        {
            Set(value);
        }
    }


    static  void Set<T>(T value, [CallerMemberName] string key = "")
    {
            System.Web.HttpContext.Current.Session[key] = value;
    }

    static  T Get<T>([CallerMemberName] string key = "")
    {
        return (T)System.Web.HttpContext.Current.Session[key];
    }
}

You will then use it as follow

EasySession.UserId = "Admin"

Better yet. If you are using C# 6.0 then you can add the following to your namespaces

using System;
using static xxx.EasySession;

This will then allow you to just call

UserId = "Admin"

Here is how it works

[CallerMemberName] will get the name of what is calling Get or Set In this case it will then bassically be "UserId eg Set("UserId","Admin")

Then it will go and just do the following System.Web.HttpContext.Current.Session["UserId"] = "Admin";

(Ref:https://msdn.microsoft.com/en-us/magazine/dn879355.aspx)

Sign up to request clarification or add additional context in comments.

4 Comments

It seems to be a good solution except one thing. I forgot to mention that I have a lof of session variables. If I understand well, I have to write set/get for every variable, which is a lot of work and code. (And I'd like to avoid that).
Yeah that may take a while to basically move all the variables, but your only going to do it once and later add more variables. But I understand you don't want to waste time, maybe do a test and see if it works. This code above is just a sample of what I actually currently use and there I only have about 10 Session Variables
I have about 1500 session variables in 6 separate sofwares. I'll give it a try and maybe write a script that generates all the code.
yikes :) that's a lot of session variables, must be quite a big software your building
0

Just use a property to wrap your session variable in.
There's no need for other parts of your code to know that its implementation, uses a Session variable or what key name it is stored in:

public string  UserId
{
    get 
    {
        return (string)System.Web.HttpContext.Current.Session["UserId"];
    }
    set
   {
       System.Web.HttpContext.Current.Session["UserId"] = value;
   }
}

3 Comments

Considering the question is about session context, the assumptions that session context is available is rather inherent to the question.
The problem is that he's obviously trying to encapsulate this logic in a type so he can effectively treat it as a pseudo-language-feature elsewhere (which is not actually going to be possible) - using a property that backs directly onto the session for each instance of this doesn't achieve the goal. The OP has asked for a very specific thing but there are really no valid answers because it isn't possible (or advisable).
FWIW I'm not suggesting it's not an appropriate way of handling session storage, just that it doesn't provide the very specific semantics that the OP is trying to achieve (i.e. the question doesn't really make sense).
0

I would suggest to create an interface with operations (no properties), and one concrete implementation of that interface that actually accesses those variables as session variables in the HTTP context; but also another mocked implementation that you can use in your unit tests; as HTTP context is not available in those cases.

So in your code you program against those interfaces, and the concrete implementation is injected at run-time. When the site is starting, it's the concrete implementation that uses Session; from tests, it's the mocked implementation.

The reason to use operations instead of properties would be to explicitly tell the user that you are not merely accessing normal properties, but session variables, that might have important side effects.

Warning: avoid to use static!!! This will cause undesirable side effects, like shared data between different users.

3 Comments

This is the proper way of handling the OP's scenario but doesn't do what he's actually asking for (which is impossible).
I just wanted to reply to "I would like to handle session variables like regular variables.", and give another better approach; instead of merely answering the question.
I moved this comment to my original post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.