HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Abstract session value manager

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
managerabstractvaluesession

Problem

I've been working in C# for a while, but I'm just recently starting to force myself to use better abstracted and generic code. I recently encountered a situation where I was juggling a lot of session values on a page, so I made a wrapper class for the session to enable easy and safe get/sets of session values.

I'm not entirely sure if this is the best way to go about accomplishing what I want, but I would love some feedback on ways this code can be improved. I'm aware that it can currently only be used for string values, but I'm just using it right now for storing form values between multiple postbacks in a very complex page, so that's not a huge concern for me at the moment.

Base class

```
abstract public class SessionManager
{
public List PossibleKeys;

public string GetValue(HttpSessionState pSession, string pKey)
{
if (this.PossibleKeys.Contains(pKey))
return ((SessionManager)pSession[this.SessionKey]).Values[pKey].ToString();
else
return "";
}

public bool SetValue(HttpSessionState pSession, string pKey, string pValue)
{
if (this.PossibleKeys.Contains(pKey))
{
var tParameters = (SessionManager)pSession[this.SessionKey];
tParameters.Values[pKey] = pValue.Trim();
pSession[this.SessionKey] = tParameters;
return true;
}
return false;
}

abstract class Keys { }

private Dictionary Values { get; set; }
private string SessionKey { get; set; }
private static string DefaultKey = "parameters";

protected void Construct(HttpSessionState pSession, string pSessionKey = null)
{
if (pSessionKey.IsNullOrWhitespace())
this.SessionKey = SessionManager.DefaultKey;
else
this.SessionKey = pSessionKey.Trim();

this.Values = new Dictionary();
foreach (var tKey in this.PossibleKeys)
{
this.Values.Add(tKey, "");
}

SessionM

Solution

I don't get what your solution brings that something like this doesn't:

public class DataManager
{
    private HttpSessionState session
    public String MemberID
    {
        get {return session["MemberID"];}
        set {session["MemberID"] = value;}
    }
}


Managing the collections Keys and PossibleKeys in two places seems error-prone.
Your naming convention of prefixing everything with 'p' is unusual (in C#).

Code Snippets

public class DataManager
{
    private HttpSessionState session
    public String MemberID
    {
        get {return session["MemberID"];}
        set {session["MemberID"] = value;}
    }
}

Context

StackExchange Code Review Q#62070, answer score: 3

Revisions (0)

No revisions yet.