The session stores temporary application variables that need to be shared between different Web forms within an application. Because the server stores a separate instance of session data for each user connection, it is important to store information in the session selectively. As more data is stored into the session, its footprint grows, slowing down the performance of the Web server.
Any type of data object can be stored in the session by one Web form and accessed by another. The only limitation is that the object stored has a Serializable attribute. In Listing 7-10, you can modify the Business Facade layer that validates user login against Active Directory to take the returned User object and save it as session data. When the user enters their credentials and clicks the OK button, the user invokes the btnOK_Click method.
private void btnOK_Click(object sender, System.EventArgs e) { User objUser = new User(); objUser = UserManager.GetUser( txtEmailAddress.Text, txtPassword.Text ); Session.Add( "USER_OBJECT", objUser ); Response.Redirect( "IssueSummary.aspx", true ); return; }
This method invokes the GetUser method, passing the user's entered credentials. If the login is successful, the UserManager class returns a User object filled with various user details. This User object is stored into the session for later reference. At any time, another page can access the session and immediately access the user's profile.
Reading data saved to the application session is as easy as storing it. As Listing 7-11 outlines, the Page_Load method of any other Web form can create a new User object and assign it to a value pulled from the session. Then, the User object is used as needed (in this case, to display a greeting).
private void Page_Load(object sender, System.EventArgs e) { try { User objUser = (User)Session["USER_OBJECT"]; lblGreeting.Text = "Welcome to IssueTracker, " + objUser.Firstname; } catch( Exception x ) { } return; }