Top Banner
ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230
26

ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

Dec 26, 2015

Download

Documents

Barrie Terry
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

ASP.NETPart 3

Instructor: Charles Moen

CSCI/CINF 4230

Page 2: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

State Management

(Continued from last week)

Page 3: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

3

State Management

Storing the data that your web application needs

The problems• Thousands of users can be using the same web application at the same time,

so we need to be concerned about having sufficient memory and keeping track of each user’s data

• All users of your web application communicate with it over a stateless HTTP connection

Five choices• View state• Query string• Cookies• Session state• Application state

ASP.NET (MacDonald)

Page 4: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

4

Session Tracking in ASP.NET

Storing the data in a session object• Stored in memory on the server

• Tracked by the server by using a unique identifier

Scope• Global for your entire application for the current user

• Can be stored between visits by setting the Expires property

Lifetime• Times out due to inactivity after a preset amount of time, usually 20 minutes

• Lost if the user closes and restarts the browser

• May be lost if the user opens the page in another browser window

• Session.Abandon() can end the session

Typical use• Storing items in a shopping cart

ASP.NET (MacDonald)

Page 5: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

5

Session Example

Two pages that use a session for the user’s favorite color

ASP.NET (MacDonald)

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <asp:Label ID="favoriteColorLabel" runat="server" Text="Favorite color:"></asp:Label> &nbsp;<asp:TextBox ID="favoriteColorTextBox" runat="server"></asp:TextBox> <br /> <br /> <asp:Button ID="submitButton" runat="server" onclick="submitButton_Click" Text="Submit" /> <br /> <br /> <a href="SecondPage.aspx">SecondPage.aspx</a> </div> </form></body></html>

Page 6: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

6

Session Example

Two pages that use a session for the user’s favorite color

ASP.NET (MacDonald)

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <asp:Label ID="favoriteColorLabel" runat="server"></asp:Label> <br /> <br /> <a href="Default.aspx">Default.aspx</a> </div> </form></body></html>

Page 7: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

7

Session ExampleASP.NET (MacDonald)

public partial class _Default : System.Web.UI.Page { protected void submitButton_Click(object sender, EventArgs e) { string colorName = favoriteColorTextBox.Text; if (colorName != "") { Color favColor = new Color(colorName); Session["FavoriteColor"] = favColor; } }}

public partial class SecondPage : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { Color favColor = (Color)Session["FavoriteColor"]; if (favColor != null) { favoriteColorLabel.Text = "Favorite color = " + favColor.Name; } else { favoriteColorLabel.Text = "No favorite color"; } }}

public class Color{ private string name; public string Name { get { return name; } set { name = value; } }

public Color(string name) { Name = name; }}

Page 8: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

8

C# PropertiesASP.NET (MacDonald, Mayo)

public class Color{ private string name; public string Name { get { return name; } set { name = value; } } public Color(string name) { Name = name; }}

Properties are similar to member variables in a class Easier to use and easier to code

public class Color{ private string name; public string getName() { return name; } public void setName(string value) { name = value; } public Color(string name) { this.name = name; }}

Color favColor = new Color("red");Console.WriteLine(favColor.getName());

Traditional encapsulation with a member variable Encapsulating state with a property

Color favColor = new Color("red");Console.WriteLine(favColor.Name);

Getters and setters are shorter

Page 9: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

ADO.NET

Page 10: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

10

ADO.NET

The .NET technology for interacting with a database

• A set of classes that are part of the .NET Framework

Two models of data access

• Connected – direct data access

• Disconnected – fetch the data and store it in memory

Not the same as “data binding” in ASP.NET, which is binding a control to a data source

ASP.NET (MacDonald, Walther)

Page 11: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

11

Three-Tier Architecture

A type of client-server architecture

ASP.NET (MacDonald, Gittleman)

PresentationTier

LogicTier

DataTier

ADO.NET

Page 12: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

12

Role of the Database

Relational database• The most common way to store data for a web application

• Organizes data into tables, and each row in a table is called a record

• Each record must have a field called the primary key, which uniquely identifies the record

• A relationship between two tables can be created by storing the primary key of one table as a foreign key in another table

• Database Management System (DBMS) is the program that organizes, stores, and manages the data, e.g. MS Access, MS SQL Server, Oracle, MySQL

Most important web sites use data stored in a database• Amazon.com – stores products, customers, orders

• Continental Airlines – stores flight schedules, reservations, frequent flyer miles

• Google – stores web page URLs, links, and keywords

• www.uhcl.edu

ASP.NET (MacDonald)

Page 13: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

13

Microsoft Access

Relational DBMS• Microsoft product

• Bundled in some versions of MS Office

• Can be used for small web applications

• Available at UHCL

The databases that we use in this class are created by MS Access

• All the tables are stored in a single file named db.mdb

• You will need to use MS Access to create the tables for your project

• The db.mdb file can be downloaded or uploaded by FTP in binary mode

• For the homework project, consider putting your db.mdb file in a directory named “App_Data” stored in your app directory inside the “pages” directory

ASP.NET

Page 14: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

14

Microsoft Access Example

Categories table• Two fields, id and category

• The primary key is “id”

ASP.NET

Page 15: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

15

Microsoft Access Example

MenuItems table• Five fields, id, item, description, price, and category

• The primary key is “id”

• The “category” field is a foreign key from Categories

ASP.NET

Page 16: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

16

SQL

SQL is used for all database interaction through ADO.NET

SQL (Structured Query Language)

• Standard language for interacting with relational databases

• Four commonly used commands

SELECT – retrieves a record

UPDATE – modifies an existing record

INSERT – adds a new record

DELETE – deletes an existing record

ASP.NET (MacDonald)

Page 17: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

17

SQL Examples

ASP.NET (MacDonald)

select id, categoryfrom Categories;

Select all the records from the Categories table

select *from MenuItemswhere category = 2;

Select only the salad records from the MenuItems table

Page 18: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

18

ADO.NET Classes

Three types of classes are used in ADO.NET

Connection

• Classes that encapsulate a connection to a database

Command

• Classes that are used to execute a command against a database

DataReader

• Classes that encapsulate the data retrieved from a database

ASP.NET (MacDonald, Walther)

Page 19: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

19

Implementations of ADO.NET Classes

The Connection, Command, and DataReader classes for particular DBMSs are separated into different namespaces

System.Data.SqlClient• MS SQL Server 7.0 or higher

System.Data.OleDb• Using an OLEDB driver; OleDbConnection, OleDbCommand, OleDbDataReader

System.Data.Odbc• Using an ODBC driver

System.Data.OracleClient• Oracle 8i or higher

ASP.NET (MacDonald, Walther)

Page 20: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

20

Direct Data Access

Steps to query the database with direct data access1. Create Connection, Command, and DataReader objects

2. Retrieve information from the database with the DataReader object and add it to a page

3. Close the connection

4. Send the page to the user agent as HTML

ASP.NET (MacDonald)

using System.Data;using System.Data.OleDb;

In your C# code, import the correct ADO.NET namespaces

Page 21: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

21

Deli Menu DemoASP.NET (MacDonald)

Use ASP.NET and Visual Studio 2008 to build a web application to display the results of a menu search by category using a DropDownList

Page 22: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

22

Demo web.configASP.NET (MacDonald)

<?xml version="1.0"?><configuration>

<connectionStrings> <add name="Deli" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|/db.mdb"/></connectionStrings>

<configuration>

Define the connection string in the web.config file so that it is available throughout your application

NOTE: This is a partial file.

Points to the App_Data folder inside your web application directory

The alias that you can use in your code

Page 23: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

23

Demo Default.aspx.csASP.NET (MacDonald)

using System;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Data.OleDb;using System.Web.Configuration;

public partial class _Default : System.Web.UI.Page { private string connectionString = WebConfigurationManager.ConnectionStrings["Deli"].ConnectionString;

Use the alias defined in web.config

Page 24: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

24

Demo Page_LoadASP.NET (MacDonald)

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string selectSql = "SELECT id, category FROM Categories "; OleDbConnection conn = new OleDbConnection(connectionString); OleDbCommand cmd = new OleDbCommand(selectSql, conn); try { conn.Open(); OleDbDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { ListItem newItem = new ListItem(); newItem.Text = reader["category"].ToString(); newItem.Value = reader["id"].ToString(); categoriesDropDownList.Items.Add(newItem); } reader.Close(); } catch (Exception error) { resultsLabel.Text = "ERROR: " + error.Message; } finally { conn.Close(); } } }

When the page loads, query the Categories table.

For each record in the results, add a list item to the DropDownList

Page 25: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

25

DemocategoriesDropDownList_SelectedIndexChanged

ASP.NET (MacDonald)

protected void categoriesDropDownList_SelectedIndexChanged(object sender, EventArgs e) { if (IsPostBack) { string selectSql = "select * from MenuItems where category = " + categoriesDropDownList.SelectedValue; OleDbConnection conn = new OleDbConnection(connectionString); OleDbCommand cmd = new OleDbCommand(selectSql, conn); OleDbDataReader reader; using (conn) { conn.Open(); reader = cmd.ExecuteReader(); StringBuilder sb = new StringBuilder(); sb.Append("<table border=\"1\" cellpadding=\"5\" width=\"640px\">"); while (reader.Read()) { sb.Append("<tr>"); sb.Append("<td width=\"100px\">"); sb.Append(reader["item"].ToString()); sb.Append("</td>"); sb.Append("<td>"); sb.Append(reader["description"].ToString()); sb.Append("</td>"); sb.Append("<td>"); sb.Append(reader["price"].ToString()); sb.Append("</td>"); sb.Append("</tr>"); } sb.Append("</table>"); resultsLabel.Text = sb.ToString(); } }}

When the DropDownList selection changes, query the MenuItems table

For each record that has a category value equal to the value of the list selection, add the record to the table as a row

Page 26: ASP.NET Part 3 Instructor: Charles Moen CSCI/CINF 4230.

26

References

Ding, Wei, “ASP.NET” UHCL lecture slides, 2008.

Gittleman, Art, Computing with C# and the .NET Framework. Jones and Bartlett Publishers, 2003.

Lu, Dennis and Doug Rothaus, Microsoft (2002). “Best Practices for Using ADO.NET”. [Online]. Available: http://msdn.microsoft.com/en-us/library/ms971481.aspx

MacDonald, Matthew, Beginning ASP.NET 3.5 in C# 2008: From Novice to Professional, Second Edition. Apress, 2007.

Walther, Stephen. ASP.NET 3.5 Unleashed. SAMS, 2008.

W3Schools Online Web Tutorials. “ASP.NET”. [Online]. Available: http://www.w3schools.com/aspnet/default.asp