Monday, January 11, 2010

01/11

 

Asp.Net State Management

  • ViewState
  • Application :hold unchanged value of application level
  • Cache : not frequently change value of application level
  • Session : per user level
  • Cookie (Client side)

 

Using Cache:

 

Code :

 

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
carsGridView.DataSource = (DataTable)Cache["AppDataTable"];
carsGridView.DataBind();
}
}

protected void btnAddCar_Click(object sender, EventArgs e)
{
// Update the Inventory table
// and call RefreshGrid().
InventoryDAL dal = new InventoryDAL();
dal.OpenConnection(@"Data Source=(local)\SQLEXPRESS;" +
"Initial Catalog=AutoLot;Integrated Security=True");
dal.InsertAuto(int.Parse(txtCarID.Text), txtCarColor.Text,
txtCarMake.Text, txtCarPetName.Text);
dal.CloseConnection();
RefreshGrid();
}

 

private void RefreshGrid()
{
InventoryDAL dal = new InventoryDAL();
dal.OpenConnection(@"Data Source=(local)\SQLEXPRESS;" +
"Initial Catalog=AutoLot;Integrated Security=True");

DataTable theCars = dal.GetAllInventory();
dal.CloseConnection();
carsGridView.DataSource = theCars;
carsGridView.DataBind();

}

 

 

 

Now, to test the use of the cache, begin by running the current program (Ctrl+F5) and copy the URL appearing in the browser to your clipboard. Next, launch a second instance of Internet Explorer (using the Start button) and paste the URL into this instance. At this point you should have
two instances of your web browser, both viewing Default.aspx and showing identical data.

In one instance of the browser, add a new automobile entry. Obviously, this results in an updated GridView viewable from the browser that initiated the postback. In the second browser instance, click the Refresh button (F5). You should not see the new item, given that the Page_Load event handler is reading directly from the cache. (If you did see the value, the 15 seconds had already expired. Either type faster or increase the amount of time the DataTable will remain in the cache.) Wait a few seconds and click the Refresh button from the second browser
instance one more time. Now you should see the new item, given that the DataTable in the cache has expired and the CacheItemRemovedCallback delegate target method has automatically updated the cached DataTable.

0 Comments:

Post a Comment

<< Home