23
Working with Session and Application Objects

Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

  • View
    230

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Working with Session and Application Objects

Page 2: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Postback and Variables

• Variables declared in a web page including ADO.Net objects may be reinitialized and lose their values.

Page 3: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Persistence of Data between Page Postback

• We can store variables and ADO objects in Session or Application object.

Page 4: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Increase Counter by One. What is wrong?

Dim counter As Integer Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click counter = counter + 1

Response.Write(counter) End Sub

Page 5: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Save Counter in Session

int counter=0; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) Session["mYcounter"]=counter; else

counter = (int) (Session["mYcounter"]); protected void Button1_Click(object sender, EventArgs e) { counter += 1; Session["mYcounter"] = counter; Response.Write(counter); }

Note: Can we do this in the Page_Load event:

if (Page.IsPostBack) counter = (int) (Session["mYcounter"]);

Page 6: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

DataSet Example

• Create a web form with a Radiobuttonlist to choose rating and display customers with the selected rating in a data grid.

• RadioButtonList control:– Items property– SelectedValue property

Page 7: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

DataSet objDataSet = new DataSet(); DataView objDataView = new DataView(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer;"; OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSQL, objConn); objAdapter.Fill(objDataSet, "Customer"); Session["myDataset"] = objDataSet; } else objDataSet = (DataSet) Session["myDataset"]; } protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e) { objDataView = objDataSet.Tables["customer"].DefaultView; objDataView.RowFilter = "rating = '" + RadioButtonList1.SelectedItem.ToString() + "'"; GridView1.DataSource = objDataView; GridView1.DataBind(); }

Page 8: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Binding a ListBox and Display Two other Fields

DataSet objDataSet = new DataSet();protected void Page_Load(object sender, EventArgs e){ if (!Page.IsPostBack) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer;"; OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSQL, objConn); objAdapter.Fill(objDataSet, "Customer"); Session["myDataset"] = objDataSet; ListBox1.DataSource = objDataSet.Tables["Customer"]; ListBox1.DataTextField = "cid"; ListBox1.DataValueField = "Cname"; ListBox1.DataBind(); } else objDataSet = (DataSet)Session["myDataset"]; } protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) { TextBox1.Text = ListBox1.SelectedValue; TextBox2.Text = objDataSet.Tables["Customer"].Rows[ListBox1.SelectedIndex]["rating"].ToString(); }

Page 9: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

A page with CID Listbox to display customer data in textboxes and orders data in

GridView.• Use one adapter to create a dataset with

two tables.

• Create bound listbox and automatically select the first customer’s CID:– ListBox1.Items[0].Selected = true;

• GridView control is bound using Orders table’s view.

Page 10: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

protected void Page_Load(object sender, EventArgs e) {if (!Page.IsPostBack){string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb";OleDbConnection objConn = new OleDbConnection(strConn);string strSQL = "select * from customer;";OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSQL, objConn);objAdapter.Fill(objDataSet, "Customer");string strSQLOrders = "select * from orders";objAdapter.SelectCommand.CommandText = strSQLOrders;objAdapter.Fill(objDataSet, "Orders");Session["myDataset"] = objDataSet;ListBox1.DataSource = objDataSet.Tables["Customer"];ListBox1.DataTextField = "cid";ListBox1.DataValueField = "cid";ListBox1.DataBind();ListBox1.Items[0].Selected = true;TextBox1.Text = objDataSet.Tables["Customer"].Rows[ListBox1.SelectedIndex]["Cname"].ToString();TextBox2.Text = objDataSet.Tables["Customer"].Rows[ListBox1.SelectedIndex]["rating"].ToString();DataView ObjDataView= new DataView();ObjDataView = objDataSet.Tables["Orders"].DefaultView;ObjDataView.RowFilter = "CID='" + ListBox1.SelectedValue + "'"; GridView1.DataSource = ObjDataView;GridView1.DataBind();Session["myDataset"] = objDataSet;} else objDataSet = (DataSet)Session["myDataset"];}

Page 11: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Listbox SelectedIndexChanged event

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) {TextBox1.Text = objDataSet.Tables["Customer"].Rows[ListBox1.SelectedIndex]["Cname"].ToString();TextBox2.Text = objDataSet.Tables["Customer"].Rows[ListBox1.SelectedIndex]["rating"].ToString(); DataView ObjDataView = new DataView(); ObjDataView = objDataSet.Tables["Orders"].DefaultView; ObjDataView.RowFilter = "CID='" + ListBox1.SelectedValue + "'"; GridView1.DataSource = ObjDataView; GridView1.DataBind(); }

Page 12: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Share Variables between Pages

• First page: – Session[“CustName”]=“Smith”;

• Second page:– Response.Write("Welcome, " +

Session["CustName“].ToString();)

Page 13: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Global.asax File• The Global.asax file, also known as the

ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events.

• Application events:– Application_Start– Application_End

• Session events:– Session_Start– Session_End

Page 14: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Adding the Global.asax file:Project/Add/New item

Page 15: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Application_Start• Application_Start event gets triggered when the

first request for any resource in the application comes. Resource can be a page or an image in the application. When the very first request for a resource, say a web page, is made by a user “Application_Start” is triggered after which this event is not at all executed.

• If by any chance the server where the application is hosted is restarted then this event is fired once again i.e. when the very first request for any resource in the application is made after the server is reset.

Page 16: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Session_Start• Session start event is fired only when a new

session for a user starts. Once “Session_Start” for a user is fired then if the user makes subsequent request to any resource within the application this event is not at all triggered.

• This event can be used when you want to do something when the user visits you site/application for the first time or when his session starts.

Page 17: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Example: Create a variable to show current date and save it in Session

protected void Session_Start(object sender, EventArgs e) { string CurrentDay = "Today is " + System.DateTime.Now.DayOfWeek.ToString() + ", " + System.DateTime.Now.ToString(); Session["CurrentDay"] = CurrentDay; }

This variable can be accessed from any page:

Response.Write(Session["CurrentDay"].ToString());

Page 18: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

If a Dataset object is needed in many pages, it can be created and saved in the Session

protected void Session_Start(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string strSQL = "select * from customer;"; OleDbDataAdapter objAdapter = new OleDbDataAdapter(strSQL, objConn); DataSet objDataSet = new DataSet(); objAdapter.Fill(objDataSet, "Customer"); string strSQLOrders = "select * from orders"; objAdapter.SelectCommand.CommandText = strSQLOrders; objAdapter.Fill(objDataSet, "Orders"); Session["myDataset"] = objDataSet; }

Page 19: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

The saved dataset can be accessed from other page

protected void Page_Load(object sender, EventArgs e) { DataSet objDataSet = new DataSet(); objDataSet =(DataSet) Session["MyDataset"]; GridView1.DataSource = objDataSet; GridView1.DataMember = "Customer"; GridView1.DataBind(); }

Page 20: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Application/Session Demo

• When are Application and Session events triggered?

• Database: – WebLog table:

• StartEnd field• TimeStamp field

• Session.abandon();

• Application.Lock();

• Application.Unlock();

Page 21: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

Global.Asax fileprotected void Application_Start(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\WebLogDB.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string timeStamp = System.DateTime.Now.ToString(); string strSQLInsert; strSQLInsert = "Insert into WebLog values ('ApplicationStart','" + timeStamp + "')"; OleDbCommand objCommInsert= new OleDbCommand(strSQLInsert, objConn); objConn.Open(); objCommInsert.ExecuteNonQuery(); objConn.Close(); }protected void Session_Start(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\WebLogDB.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string timeStamp = System.DateTime.Now.ToString(); string strSQLInsert; strSQLInsert = "Insert into WebLog values ('SessionStart','" + timeStamp + "')"; OleDbCommand objCommInsert = new OleDbCommand(strSQLInsert, objConn); objConn.Open(); objCommInsert.ExecuteNonQuery(); objConn.Close(); }

Page 22: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

protected void Session_End(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\WebLogDB.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string timeStamp = System.DateTime.Now.ToString(); string strSQLInsert; strSQLInsert = "Insert into WebLog values ('SessionEnd','" + timeStamp + "')"; OleDbCommand objCommInsert = new OleDbCommand(strSQLInsert, objConn); objConn.Open(); objCommInsert.ExecuteNonQuery(); objConn.Close(); } protected void Application_End(object sender, EventArgs e) { string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\WebLogDB.accdb"; OleDbConnection objConn = new OleDbConnection(strConn); string timeStamp = System.DateTime.Now.ToString(); string strSQLInsert; strSQLInsert = "Insert into WebLog values ('ApplicationEnd','" + timeStamp + "')"; OleDbCommand objCommInsert = new OleDbCommand(strSQLInsert, objConn); objConn.Open(); objCommInsert.ExecuteNonQuery(); objConn.Close(); }

Page 23: Working with Session and Application Objects. Postback and Variables Variables declared in a web page including ADO.Net objects may be reinitialized and

string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\SalesDB2011.accdb"; string strSQL; OleDbDataReader objDataReader; protected void Application_Start(object sender, EventArgs e) { OleDbConnection objConn = new OleDbConnection(strConn); strSQL = "select VisitorCounter from VCounterTable where CounterDate = ("; strSQL = strSQL + "Select Max(CounterDate) from VCounterTable);"; OleDbCommand objComm=new OleDbCommand(strSQL, objConn); objConn.Open(); objDataReader = objComm.ExecuteReader(); objDataReader.Read(); Application["visitor"] = objDataReader["VisitorCounter"]; objConn.Close(); } protected void Session_Start(object sender, EventArgs e) { Application.Lock(); Application["visitor"] = (int) Application["visitor"] + 1; Session["visitor"] = Application["visitor"]; Application.UnLock(); } protected void Application_End(object sender, EventArgs e) { OleDbConnection objConn = new OleDbConnection(strConn); strSQL = "Insert Into VCounterTable Values (#" + (DateTime.Now.ToString()) + "#, " + Application["visitor"] + ");"; OleDbCommand objComm=new OleDbCommand(strSQL, objConn); objConn.Open(); objComm.ExecuteNonQuery(); objConn.Close(); }