Lecture 16 - ASP - NET (Part 3)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

C# 6 and the .NET 4.

6 Framework

Chapter 33: ASP.NET State


Management Techniques
HTTP is stateless
HTTP is stateless
using System;

public partial class _Default : System.Web.UI.Page


{
private string dataStr = "Yugo";
protected void Page_Load(object sender, EventArgs e){}
protected void btnSetData_Click(object sender, EventArgs e)
{
dataStr = txtData.Text;
}
protected void btnGetData_Click(object sender, EventArgs e)
{
lblData.Text = dataStr;
}
}
HTTP is stateless
So how about this. It still “remembers” the “Something”. This is a
facility from ASP.NET called “View State”.

This proves that the server


“forgets” about your request (it
create new page object every time
you make a request).
ASP.NET State Management
Techniques
• Use ASP.NET view state.
• Use ASP.NET control state.
• Define application-level data.
• Use the cache object.
• Define session-level data.
• Define cookie data.
Understanding the Role of ASP.NET
View State
• The role of ASP.NET View State
– Do not need to manually scrape out and repopulate the values
in the HTML widgets
– ASP.NET runtime automatically embeds a hidden form field
(named __VIEWSTATE)
– The data assigned to this field is a Base64-encoded string that
contains a set of name/value pairs representing the values of
each GUI widget on the page at hand
– The Page base class's Init event handler is in charge of reading
the incoming values in the __VIEWSTATE field to populate the
appropriate member variables in the derived class
– Just before the outgoing response is emitted back to the
requesting browser, the __VIEWSTATE data is used to
repopulate the form's widgets.
Demonstrating View State
Demonstrating View State
The Role of the Global.asax File
• To interact with the web application as a
whole
– An ASP.NET application may choose to include an
optional Global.asax file via the WebSite
– Global.asax script is dynamically generated as a
class deriving from the System.Web.
HttpApplication base class
he Role of the Global.asax File
<%@ Application Language="C#" %>
<script RunAt="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>
The HttpApplication Base Class
Understanding the Application/Session
Distinction
Members of the HttpApplicationState
Type
Update the Application_Start Method
You can now access these anywhere
protected void btnShowCarOnSale_Click(object sender, EventArgs arg)
{
lblCurrCarOnSale.Text = string.Format("Sale on {0}'s today!",
(string)Application["CurrentCarOnSale"]);
}
Modifying Application Data
private void CleanAppData()
{
// Remove a single item via string name.
Application.Remove("SomeItemIDontNeed");

// Destroy all application data!


Application.RemoveAll();
}
Safely access related application data
Application.Lock();
Application["SalesPersonOfTheMonth"] = "Maxine";
Application["CurrentBonusedEmployee"] = Application["SalesPersonOfTheMonth"];
Application.UnLock();

If you have a situation where a set of application-level variables must be


updated as a unit, you risk the possibility of data corruption since it is
technically possible that an application-level data point may be changed while
another user is attempting to access it!
Understanding the Application Cache
• Application Cache
– A second and more flexible way to handle application-
wide data.
– The values within the HttpApplicationState object
remain in memory as long as your web application is
alive.
– If you want to maintain a piece of application data
only for a specific period of time
• System.Web.Caching.Cache object
– Accessed via Context.Cache property
– Allows you to define objects that are accessible by all
users from all pages for a fixed amount of time
Example of use of Cache
// Define a static-level Cache member variable.
static Cache _theCache;

void Application_Start(Object sender, EventArgs e)


{
// First assign the static "theCache" variable.
_theCache = Context.Cache;

// When the application starts up,


// read the current records in the
// Inventory table of the AutoLot DB.
var theCars = new InventoryRepo().GetAll();

// Now store DataTable in the cache.


_theCache.Insert("CarList",
theCars,
null,
DateTime.Now.AddSeconds(15),
Cache.NoSlidingExpiration,
CacheItemPriority.Default,
UpdateCarInventory);
}
Maintaining Session Data
• A session is little more than a given user's ongoing interaction with
a web application, which is represented via a unique
HttpSessionState object
• To maintain stateful information for a particular user, you can use
the Session property in your web page class or in Global.asax
• The classic example of the need to maintain per-user data is an
online shopping cart.
• When a new user joins to your web application, the .NET runtime
automatically assigns the user a unique session ID, which is used to
identify that user.
• Each session ID identifies a custom instance of the HttpSessionState
type to hold user-specific data
• Inserting or retrieving session data is syntactically identical to
manipulating application data
Add a new class to App_Code
public class UserShoppingCart
{
public string DesiredCar { get; set; }
public string DesiredCarColor { get; set; }
public float DownPayment { get; set; }
public bool IsLeasing { get; set; }
public DateTime DateOfPickUp { get; set; }

public override string ToString()


{
return string.Format("Car: {0}<br>Color: {1}<br>$ Down: {2}<br>Lease: {3}<br>Pick-
up Date: {4}", DesiredCar, DesiredCarColor, DownPayment, IsLeasing,
DateOfPickUp.ToShortDateString());
}
}
On session start create new object
void Session_Start(object sender, EventArgs e)
{
Session["UserShoppingCartInfo"] = new UserShoppingCart();

}
Designing the GUI
Save the session data
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Set current user prefs.
var cart = (UserShoppingCart)Session["UserShoppingCartInfo"];
cart.DateOfPickUp = myCalendar.SelectedDate;
cart.DesiredCar = txtCarMake.Text;
cart.DesiredCarColor = txtCarColor.Text;
cart.DownPayment = float.Parse(txtDownPayment.Text);
cart.IsLeasing = chkIsLeasing.Checked;
lblUserInfo.Text = cart.ToString();
Session["UserShoppingCartInfo"] = cart;
}
Access it in the checkout page
References
Troelsen, A. & Japikse, P., 2015. C# 6 and the
.NET 4.6 Framework. 7th ed. Apress.

You might also like