Lesson 1: Saving and Retrieving User Information

Lesson 1: Saving and Retrieving User Information

Web applications that require users to register information can retrieve that information whenever a particular user revisits the Web site. For example, a shopping Web site might record the user s shipping and billing information and then retrieve that information to fill in address fields whenever that user places a new order.

After this lesson, you will be able to

  • Explain how cookies make it possible to identify users and to store user information

  • Store simple or complex information on a user s computer through a cookie

  • Remove a cookie from a user s computer

  • Create a unique identifier for a user and store it on his or her computer

  • Use an XML file to store and retrieve information about a user based on that user s unique identifier

Estimated lesson time: 35 minutes

Identifying Web Application Users

Web applications can identify users by requiring them to enter a user name and password whenever they visit the Web site. Web applications can also identify users through information stored on their computers in the form of cookies. Cookies are small files that a Web application can write to the client s computer.

The advantage of using cookies is that the interaction happens invisibly to the user: users don t have to log on every time they visit your Web site; their information just appears automatically when needed.

The disadvantage of using cookies is that users can set their browsers not to accept cookies. Some users don t like the idea of Web sites storing information on their computers and possibly using that information to track their movements on the Internet. Therefore, you should always check to see whether a client accepts cookies before attempting to use them.

You can use two approaches when storing and retrieving user information through cookies:

  • Store all the user information as a cookie on the client s machine.

    This approach is useful when the user information is simple and is not required on the server for any other tasks.

  • Store an identification key on the client s machine, and then retrieve user information from a data source on the server using that identification key.

    This is the best approach for storing more extensive information.

The following sections describe how to save and retrieve user information using each of these approaches.

Storing User Information on the Client

To store a cookie on the client s machine, follow these steps:

  1. Check whether the client supports cookies by using the Browser object s Cookies property.

  2. If the client supports cookies, check whether the cookie already exists by using the Request object s Cookies collection.

  3. If the cookie does not already exist, create a new cookie object using the HttpCookie class.

  4. Set the cookie object s Value and Expiration properties.

  5. Add the cookie object to the Response object s Cookies collection.

The following Page_Load event procedure demonstrates the preceding steps by creating a cookie that tracks the last time a user viewed a Web page. The code checks whether the user accepts cookies and either adds a cookie if this is the user s first visit to the page or updates the cookie if the user has visited the page before.

Visual Basic .NET

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' (1) Check if browser accepts cookies. If Request.Browser.Cookies Then ' (2) If the cookie does not exist... If Request.Cookies("LastVisit") Is Nothing Then ' (3) Create the cookie. Dim cookLastVisit As New HttpCookie("LastVisit", _ DateTime.Now.ToString()) ' (4) Set the expiration to tommorrow. cookLastVisit.Expires = DateTime.Now.AddDays(1) ' (5) Add to cookies collection. Response.Cookies.Add(cookLastVisit) ' Display message. litMessage.Text = "This is your first visit." Else ' Get the cookie. Dim cookLastVisit As HttpCookie = Request.Cookies("LastVisit") ' Display a message showing time of last visit. litMessage.Text = "You last visited this page: " & _ cookLastVisit.Value ' Update the cookie on the client. Response.Cookies("LastVisit").Value = Now.ToString() Response.Cookies("LastVisit").Expires = DateTime.Now.AddDays(1) End If Else litMessage.Text = "Your browser does not accept cookies." End If End Sub

Visual C#

private void Page_Load(object sender, System.EventArgs e) { // (1) Check if browser accepts cookies. if (Request.Browser.Cookies) { // (2) If the cookie does not exist... if (Request.Cookies["LastVisit"] == null) { // (3) Create the cookie. HttpCookie cookLastVisit = new HttpCookie("LastVisit", DateTime.Now.ToString()); // (4) Set the expiration to tommorrow. cookLastVisit.Expires = DateTime.Now.AddDays(1); // (5) Add to cookies collection. Response.Cookies.Add(cookLastVisit); // Display message. litMessage.Text = "This is your first visit."; } else { // Get the cookie. HttpCookie cookLastVisit = Request.Cookies["LastVisit"]; // Display a message showing time of last visit. litMessage.Text = "You last visited this page: " + cookLastVisit.Value; // Update the cookie on the client. Response.Cookies["LastVisit"].Value = DateTime.Now.ToString(); Response.Cookies["LastVisit"].Expires = DateTime.Now.AddDays(1); } } else { litMessage.Text = "Your browser does not accept cookies."; } }

Facts About Cookies

Cookies are case sensitive. For example, LastVisit is not the same cookie as Lastvisit. The Expires property specifies when the client s machine can discard the cookie. By default, cookies expire when the user s session ends. Setting Expires to the DateTime.MaxValue means that the cookie never expires.

You can remove the cookie from the client s machine by resetting the Expires property to the current time. For example, the following code removes the LastVisit cookie from the client s machine:

Visual Basic .NET

Private Sub butRemoveCookie_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butRemoveCookie.Click ' Set cookie to expire immediately. Response.Cookies("LastVisit").Expires = DateTime.Now End Sub

Visual C#

private void butRemoveCookie_Click(object sender, System.EventArgs e) { // Set cookie to expire immediately. Response.Cookies["LastVisit"].Expires = DateTime.Now; }

Using Keys Within Cookies

You can save up to 4096 bytes of information in a single cookie, and you can identify information within a cookie using keys. For example, the following code saves the user s name and address information as a cookie with individual keys:

Visual Basic .NET

Private Sub butOK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butOK.Click ' Create a cookie. Dim cookUserInfo As New HttpCookie("UserInfo") ' Fill in the keys from the form data. cookUserInfo("FirstName") = txtFirstName.Text cookUserInfo("LastName") = txtLastName.Text cookUserInfo("Street") = txtStreet.Text cookUserInfo("City") = txtStreet.Text cookUserInfo("State") = drpState.SelectedItem.Value cookUserInfo("ZIP") = txtZIP.Text ' Set the expiration. cookUserInfo.Expires = DateTime.Now.AddDays(30) ' Add the cookie. Response.Cookies.Add(cookUserInfo) End Sub

Visual C#

private void butOK_Click(object sender, System.EventArgs e) { // Create a cookie. HttpCookie cookUserInfo = new HttpCookie("UserInfo"); // Fill in the keys from the form data. cookUserInfo["FirstName"] = txtFirstName.Text; cookUserInfo["LastName"] = txtLastName.Text; cookUserInfo["Street"] = txtStreet.Text; cookUserInfo["City"] = txtStreet.Text; cookUserInfo["State"] = drpState.SelectedItem.Value; cookUserInfo["ZIP"] = txtZIP.Text; // Set the expiration. cookUserInfo.Expires = DateTime.Now.AddDays(30); // Add the cookie. Response.Cookies.Add(cookUserInfo); }

To get the values from keys stored in a cookie, simply use the key s name, as shown in the following code:

Visual Basic .NET

Private Sub butGetData_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butGetData.Click ' Get the cookie. Dim cookUserInfo As HttpCookie = Request.Cookies("UserInfo") ' Fill in the fields. txtFirstName.Text = cookUserInfo("FirstName") txtLastName.Text = cookUserInfo("LastName") txtStreet.Text = cookUserInfo("Street") txtCity.Text = cookUserInfo("City") drpState.SelectedItem.Value = cookUserInfo("State") txtZIP.Text = cookUserInfo("ZIP") End Sub

Visual C#

private void butGetData_Click(object sender, System.EventArgs e) { // Get the cookie. HttpCookie cookUserInfo = Request.Cookies["UserInfo"]; // Fill in the fields. txtFirstName.Text = cookUserInfo["FirstName"]; txtLastName.Text = cookUserInfo["LastName"]; txtStreet.Text = cookUserInfo["Street"]; txtCity.Text = cookUserInfo["City"]; drpState.SelectedItem.Value = cookUserInfo["State"]; txtZIP.Text = cookUserInfo["ZIP"]; }

Storing User Information on the Server

To store user information on the server instead of on the client s machine, simply use cookies as an identification device to store and retrieve user information on the server. You can store user information on the server using a database, an XML file, or some other type of data store.

To store user information on the server, follow these steps:

  1. Create a unique key to identify the user.

  2. Save the unique key as a cookie on the user s computer.

  3. Create a file on the server to store user information.

  4. Save the user information on the server using the unique key as an index.

The follow sections describe these steps in greater detail.

Creating Unique Keys to Identify Users

The Microsoft .NET Framework provides the System.Guid namespace for creating globally unique identifiers (GUIDs). A GUID is a 128-bit integer that serves as a unique identifier across networks. You can use GUIDs as unique keys to identify all sorts of things, including users.

The following code creates a GUID and stores it as a cookie on the client s machine to later identify the user:

Visual Basic .NET

Private Sub butOK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butOK.Click ' Get the request cookie. Dim cookUserID As HttpCookie = Request.Cookies("UserID") ' If it doesn't exist, create it. If cookUserID Is Nothing Then ' Create a new cookie with a new GUID. cookUserID = New HttpCookie("UserID", _ System.Guid.NewGuid().ToString()) cookUserID.Name = "UserID" End If ' Set the expiration. cookUserID.Expires = DateTime.Now.AddDays(30) ' Add the cookie to the response. Response.Cookies.Add(cookUserID) ' Save the user info from the form data. SetUserInfo(cookUserID.Value) End Sub

Visual C#

private void butOK_Click(object sender, System.EventArgs e) { // Get the request cookie. HttpCookie cookUserID = Request.Cookies["UserID"]; // If it doesn't exist, create it. if (cookUserID == null) // Create a new cookie with a new GUID. cookUserID = new HttpCookie("UserID", System.Guid.NewGuid().ToString()); // Set the expiration. cookUserID.Expires = DateTime.Now.AddDays(30); // Add the cookie to the response. Response.Cookies.Add(cookUserID); // Save the user info from the form data. SetUserInfo(cookUserID.Value); }

Creating a File to Store User Information

Part of the point of storing user information is to be able to retrieve that information quickly the next time the user visits your Web application. Because these users are already identified by a unique key (the GUID created in the preceding section), it makes sense that you will want to access their data through a data set. Data sets provide the Find method to retrieve rows of data by unique keys.

Using a data set means that the file you create on the server must be either a database or an XML file. XML provides a way to record structured data to a file without the complexity or overhead of a database, so for something as simple as user name and address information you ll probably want to use XML.

To create an XML file to store user information, follow these steps:

  1. Create an XML file in Visual Studio containing test data for each of the data fields you want to record about the user.

  2. Generate an XML schema from the XML file. The XML schema enables the data set to refer to data in the XML file by name.

  3. Specify a key field within the XML schema. This will let you find records using that field with the data set s Find method.

  4. Read the XML schema and XML file into a data set.

The following sections describe these steps in more detail.

Creating an XML File

To create an XML file in Visual Studio, choose Add New Item from the Project menu and then select XML File from the Templates list.

XML files look a lot like HTML files; however, XML elements and attributes are case sensitive and use a strict syntax. You use <element> and </element> tags to identify the data elements in an XML file. The following sample shows an XML file for storing user name and address information:

<?xml version="1.0" standalone="yes"?> <USERS xmlns="http://tempuri.org/UserPrefs.xsd"> <USER> <FIRSTNAME>Joan</FIRSTNAME> <LASTNAME>Reddington</LASTNAME> <STREET>436 Atlantic Ave.</STREET> <CITY>Melbourne Beach</CITY> <STATE>FL</STATE> <ZIP>32401</ZIP> <ID>79844302-6d86-4520-ac64-c8c3240e21a9</ID> </USER> </USERS>

Creating an XML Schema

To use an XML file with a data set, you must first create an XML schema for the data set. An XML schema is a description of the data elements contained in the XML file. It provides the names of the elements and their types, indicates whether they are key fields, and provides other information.

To create an XML schema from an XML file, select Create Schema from the XML menu while the XML file is displayed in the Design view. Visual Studio creates a schema file describing the XML file, as shown in Figure 7-1.

figure 7-1 an xml schema

Figure 7-1. An XML schema

Specifying a Key Field

You add a primary key to the XML schema to enable searching. The schema shown in Figure 7-1 includes a key field that enables the data set to search for users by UserID.

To add a key field to the XML schema, follow these steps:

  1. Right-click the element to create a key, point to Add, and then select New Key from the shortcut menu. Visual Studio displays the Edit Key dialog box, as shown in Figure 7-2.

    figure 7-2 the edit key dialog box

    Figure 7-2. The Edit Key dialog box

  2. Select the Dataset Primary Key check box and click OK to make the element a primary key within the data set. This enables you to use the Dataset object s Find method to retrieve rows from the data set using values for the element.

Reading the XML into a Data Set

When you ve created an XML file and an XML schema, you can read those files into a data set using the ReadXmlSchema and ReadXml methods, respectively. The following code shows a helper function that returns a data set created from the UserInfo XML file:

Visual Basic .NET

Function GetUserData() As DataSet ' Set the path of the XML file and XML schema. Dim strPath As String = Server.MapPath(".") ' Declare a data set. Dim dsUsers As New DataSet() ' Apply the XML schema to the data set. dsUsers.ReadXmlSchema(strPath & "\UserInfo.xsd") ' Read the XML into the data set. dsUsers.ReadXml(strPath & "\UserInfo.xml") Return dsUsers End Function

Visual C#

private DataSet GetUserData() { // Set the path of the XML file and XML schema. string strPath = Server.MapPath("."); // Declare a data set. DataSet dsUsers = new DataSet(); // Apply the XML schema to the data set. dsUsers.ReadXmlSchema(strPath + "\\UserInfo.xsd"); // Read the XML into the data set. dsUsers.ReadXml(strPath + "\\UserInfo.xml"); return dsUsers; }

Saving User Information on the Server

To save user information on the server as an XML file, use the Dataset object s SaveXML method. The following SetUserInfo procedure uses the GetUserData procedure described in the preceding section to get a data set from the XML file and then uses the Find method to check whether the UserID exists within that data set. If the UserID is not found, SetUserInfo adds a row for the user before setting the values for the fields in that row from server controls on a Web form. Finally, SetUserInfo writes the whole data set back to the server.

Visual Basic .NET

Sub SetUserInfo(ByVal UserID As String) ' Set the path of the XML file and XML schema. Dim strPath As String = Server.MapPath(".") ' Get the User's data set. Dim dsUsers As DataSet = GetUserData() ' Find the row in the data set. Dim rowUser As DataRow = dsUsers.Tables("User").Rows.Find(UserID) ' If the row is not found, then create a new row. If rowUser Is Nothing Then rowUser = dsUsers.Tables("User").NewRow dsUsers.Tables("User").Rows.Add(rowUser) End If ' Save data from form fields. rowUser("FirstName") = txtFirstName.Text rowUser("LastName") = txtLastName.Text rowUser("Street") = txtStreet.Text rowUser("City") = txtCity.Text rowUser("State") = drpState.SelectedItem.Text rowUser("ZIP") = txtZIP.Text rowUser("ID") = UserID ' Write the XML from the data set. dsUsers.WriteXml(strPath & "\UserInfo.xml") End Sub

Visual C#

private void SetUserInfo(string UserID) { // Set the path of the XML file and XML schema. string strPath = Server.MapPath("."); // Get the User's data set. DataSet dsUsers = GetUserData(); // Find the row in the data set. DataRow rowUser = dsUsers.Tables["User"].Rows.Find(UserID); // If the row is not found, then create a new row. if (rowUser == null) { rowUser = dsUsers.Tables["User"].NewRow(); dsUsers.Tables["User"].Rows.Add(rowUser); } // Save data from form fields. rowUser["FirstName"] = txtFirstName.Text; rowUser["LastName"] = txtLastName.Text; rowUser["Street"] = txtStreet.Text; rowUser["City"] = txtCity.Text; rowUser["State"] = drpState.SelectedItem.Text; rowUser["ZIP"] = txtZIP.Text; rowUser["ID"] = UserID; // Write the XML from the data set. dsUsers.WriteXml(strPath + "\\UserInfo.xml"); }

Retrieving User Information from the Data Set

To retrieve user information from the XML file, use the GetUserData procedure to create a data set from the XML file, and then use the Find method to retrieve the row that corresponds to the UserID. The following GetUserInfo procedure retrieves user information from the data set and uses it to fill in server controls on a Web form:

Visual Basic .NET

Sub GetUserInfo(ByVal UserID As String) ' Get the User's data set. Dim dsUsers As Data.DataSet = GetUserData() ' Find the row in the data set. Dim rowUser As Data.DataRow = dsUsers.Tables("User").Rows.Find(UserID) ' If user wasn't found, exit. If rowUser Is Nothing Then Exit Sub ' Add data to form fields. txtFirstName.Text = rowUser.Item("FirstName") txtLastName.Text = rowUser.Item("LastName") txtStreet.Text = rowUser.Item("Street") txtCity.Text = rowUser.Item("City") drpState.SelectedItem.Text = rowUser.Item("State") txtZIP.Text = rowUser.Item("ZIP") End Sub

Visual C#

void GetUserInfo(string UserID) { // Get the User's data set. DataSet dsUsers = GetUserData(); // Find the row in the data set. DataRow rowUser = dsUsers.Tables["User"].Rows.Find(UserID); // If user wasn't found, exit. if (rowUser == null) return; // Add data to form fields. txtFirstName.Text = rowUser["FirstName"].ToString(); txtLastName.Text = rowUser["LastName"].ToString(); txtStreet.Text = rowUser["Street"].ToString(); txtCity.Text = rowUser["City"].ToString(); drpState.SelectedItem.Text = rowUser["State"].ToString(); txtZIP.Text = rowUser["ZIP"].ToString(); }



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net