Click to See Complete Forum and Search --> : accessing session state from a web control?


dmeikle
April 26th, 2005, 09:24 AM
I'd like to build a custom login control for dot net using c#. Once the person submits their login and password information successfully, the control hits the database, grabs their information, and can throw a loginsuccess or loginfail event. after this in the codebehind page, the loginsuccess event will redirect to a member area, or the loginfail will redirect to a fail message.

I normally like to load an instance of a member object with all their information into session. i'd like to do the same here, so i can access user parameters without hitting the database each time...plus at the very least I'd need to store the memberid...

how do I access the session object to store values there? Or is there some other way I'm not aware of? I know about roles configured in the webconfig file, but this is still slightly different.

cheers
David

mmetzger
April 26th, 2005, 10:47 AM
Basically, to add something to the Session object, you just do it as:


Session[objname] = objvalue;


The biggest trick is handling null values when a session times out (I've had bad luck with that in the past) and making sure to cast the object correctly when reading a session object.

For example, if you have an ArrayList in Session, do the following:



ArrayList al;
al = (ArrayList) Session["myarraylist"];
if (al == null)
{
al = new ArrayList();
// Commence to reload data from db)
Session["myarraylist"] = al;
}

// perform normal operations as code now is present regardless.


The Cache object works similarly, but is global across all sessions.
[/code]

cmiskow
April 26th, 2005, 12:08 PM
You can access the Session the same way in a custom control that you do in a Page.

dmeikle
April 27th, 2005, 05:15 AM
mmm...see...? It was right in front of me the whole time.... :rolleyes:

I was trying:

this.*wait for intellisense popup*

... hmmm. not a base class of this object....

thanks for the tip. the code sample was a huge bonus too, mmetzger.

cheers.