1 / 84

ASP.NET and ADO.NET Minder Chen, Ph.D. Associate Professor of Decision Sciences and MIS

ASP.NET and ADO.NET Minder Chen, Ph.D. Associate Professor of Decision Sciences and MIS School of Management George Mason University Fairfax, VA 22030 Email: mchen@gmu.edu 703-993-1788. ASP  ASP.NET ADO  ADO.NET VB  VB.NET Java  C# (J#). Outline.

moeshe
Download Presentation

ASP.NET and ADO.NET Minder Chen, Ph.D. Associate Professor of Decision Sciences and MIS

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ASP.NET and ADO.NET Minder Chen, Ph.D. Associate Professor of Decision Sciences and MIS School of Management George Mason University Fairfax, VA 22030 Email: mchen@gmu.edu 703-993-1788 ASP  ASP.NET ADO  ADO.NET VB  VB.NET Java  C# (J#)

  2. Outline • Introduction to ASP.NET in the Context of .NET Framework • Web Programming: ASP.NET • Web server control and Event-Driven programming • Postback and ViewState • Code-behind • Database Programming: ADO.NET • DataReader • DataSet and DataGrid • Topics to be covered in ASP.NET • Curriculum Design: Where does ASP.NET and ADO.NET fit in? • References: Online resources and books

  3. ASP.NET in the Context of .NET Framework VB C++ C# JScript J# Visual Studio.NET Common Language Specification ASP.NET Web Forms Web Services Mobile Internet Toolkit Windows Forms ADO.NET and XML Base Class Library Common Language Runtime Operating System

  4. Web Programming with ASP.NET • Attractive features in ASP.NET • Setup ASP.NET Environments • Web Forms • Postback and ViewState • Code-Behind • ASP.NET Execution Models • Web Form Controls • HTML Controls (form elements) • HTML Server Controls • Web Server Controls • User Controls

  5. ASP.NET Features • Event-driven programming • HTML Server Controls or Web Server Controls • Postback and ViewState • Separation of user interface (UI) and code • Code-behind • Scalability • Cache object • Server-farm support • Page Caching • State maintenance • ViewState, Cookie, Session, Application, Cache • Cookie-less session support • Visual Studio .NET development tool • Just drag and drop to create controls • Server Explorer for database & server object creations

  6. Setting Up the Development Environment • Visual Studio .NET: Windows XP Professional, Windows NT, Windows 2000 with IIS installed first. • ASP.NET Web Matrix: • ASP.NET Web Matrix is supported on Windows 2000 (Professional and Server editions) and Windows XP (Home, Professional) operating systems.  • You must have IE 5.5 or greater and the .NET Framework installed. • Can be downloaded for free from http://www.asp.net/webmatrix/ • Set up your own Internet Information Server (IIS) on a Windows NT Server or 2000 Server • Install IIS with WWW Service and FTP service • Set up ftp accounts for students • Install .NET Framework SDK • Use Web Hosting Providers Supporting ASP.NET, such as Brinkster.com (free)

  7. Hello1.asp (First Generation Technology) <html><body> <h1>Hello Old ASP!</h1> Current Time: <% Response.Write(Now()) %> <form> Enter your name: <input type="text" name="userName"> <input type="Submit" value="Enter"> </form></body></html> • The limitation of classic ASP is that the render block has to be placed where you want the output to appear. It is impossible to separate executable code from the HTML code itself. This makes the web page difficult to understand and difficult to maintain. • A form without an action attribute submits form data to itself and the form will be refreshed to its default status.

  8. Hello3.aspx

  9. ASP.NET Web Form Composition Compiler Directive <%@ Page language="VB" %> <html> <head> <%-- Script block --%> <script language="VB" runat="server"> Private x as String = "Developed by Minder Chen" Sub Page_Load(Src As Object, e As EventArgs) If Name.Text = "" Then Message.Text= "" Else Message.Text = "Hi " & Name.Text End If End Sub Sub Show_Author(Src As Object, e As EventArgs) DataBind( ) ' Bind data binding expressions End Sub </script> </head> HTML tags Server-Side Comment Code Block

  10. Continued… Output Directive Render Block Static Text <body> Current time: <%= Date.Now() %> <form runat="server" ID="Form1"> Enter your name: <asp:textbox id="Name" runat="server" /> <input type="submit" value="Enter your name"><p> <asp:label id="Message" runat="server" /><br> <input type="button" OnServerClick ="Show_author" value="Who is the author?" runat="server"> <br> <b> <%# "Message:" & x %> </b></form></body></html> Server Control Tags Server-side event procedure Data Binding Expression

  11. Add New Project Items • Choose Web Form • Enter Hello.aspx as item name

  12. pageLayout property • FlowLayout • GridLayout

  13. pageLayout • pageLayout • FlowLayout • GridLayout

  14. Hello.aspx <html> <script language="VB" runat="server"> Sub EnterBtn_Click(Src As Object, e As EventArgs) Message.Text = "Hi " & Name.Text & ", welcome to ASP.NET!" End Sub </script> <body> <form runat="server"> Enter your name: <asp:textbox id="Name" runat=server/> <asp:button text="Enter" OnClick="EnterBtn_Click" runat="server" /> <p> <asp:label id="Message" runat=server/> </form> </body> </html> Design time Run time

  15. Web Server Controls <html> <script language="VB" runat="server"> Sub EnterBtn_Click(Src As Object, e As EventArgs) Message.Text = "Hi " & Name.Text& _ ", welcome to ASP.NET!" End Sub </script> <body> <form runat="server"> Enter your name: <asp:textbox id="Name" runat=server/> <asp:button text="Enter" OnClick="EnterBtn_Click" runat="server"/> <asp:label id="Message" runat=server/> </form></body></html> Use id attribute to assign an unique identifier to each control in order to refer to it in your program.

  16. Design vs. HTML Mode

  17. Run and Test Your ASP.NET Program • Right mouse click the Hello.aspx at Solution Explorer • Choose Set as Start Page • Choose Start to run the program. • After testing the generated page in the browser. Close the browser to go back to the editing mode. You need to close the browser in order to modify your code again!

  18. ASP.NET Pages: Part Declarative, Part Code • Combines declarative tags (HTML, ASPX directives, server controls tags, and static text) with code in a single file or in separate files. • Unlike ASP, good separation provided between code and tags.  single file separate files (“code-behind”) code code <tags> <tags> Form1.aspx Form1.aspx Form1.aspx.vb

  19. Hello2.aspx Runtime Minder

  20. Design View and HTML View

  21. Code Behind

  22. Events Handlers in Hello2.aspx.vb (Code Behind) Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Put user code to initialize the page here If Not Page.IsPostBack Then Label1.Text = "First Time " Else Label1.Text = "Post back " End If Label1.Text &= "<br>Load event of Page" End Sub Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click LabelName.Text &= "Hello " & TextBox1.Text & "!" Label1.Text &= "<br>Click event of Button1" End Sub Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles TextBox1.TextChanged Label1.Text &= "<br>TextChanged event of TextBox1" End Sub

  23. Page/Control Event Execution PostBack First Request Page DLL is loaded, control hierarchy initialized They may be triggered on PostBack Page_Load Textbox1_Changed 1. Change Events Button1_Click 2. Action Events Page_PreRender Control hierarchy (Dynamically generated HTML page) is rendered Page_Unload Page is disposed

  24. ViewState and PostBack Hello2.aspx.vb If Not IsPostBack Then Label1.Text="First Time" Else Label1.Text="Post Back" End If First Request Response __VIEWSTATE = "dDwt…" <Input id="TextBox1"> Post back to the same page __VIEWSTATE = "dDwt…" Textbox1.Text = "Minder Chen" Response Default value __VIEWSTATE = "dDwt…" <Input id="TextBox1" value="Minder Chen" …> Hello2.aspx <asp:textbox id="TextBox1" runat="server"/> <asp:button id="Button1" runat="server" /> Minder Chen States of a page is maintained via the ViewState between the Postback

  25. ASP.NET Execution Model Class Hello Private Sub Page_Load(…) End Sub End Class Hello.aspx.vb Client Server First request Postback Output Cache

  26. State Management • HTTP protocol and Web Forms pages are stateless. • Pages are destroyed and recreated with each round trip to the server. • State management is to maintain state and page information over multiple requests for the same or different pages • State Management Mechanism • QueryString (hyperlink or form data via Get method) • Form elements including hidden field (Post method) • Cookie (per client machine and last longer) • Session (for each visitor during a visit): Support Cookie-less Sessions • Application (per Web application) • ViewState (Postback of the same page ) • Cache (Per Web application)

  27. ADO.NET • ADO.NET Object Model • Using ADO.NET with ASP.NET • DataReader • DataSet and DataGrid: A Powerful Combination • Browsing • Sorting • Filtering • Selection • Pagination • In-place Editing (Data Maintenance)

  28. ADO.NET Object Model ADO.Net Data Consumers Data Provider 2 Window Forms Data Provider 1 (Managed Component) DataSet DataAdapter Web Forms Connection Command SQL statement (Insert, Update, Delete) SQL Select Statement Web Services Mobile Forms Classes Console App. DataReader Records

  29. Data Objects Object Description Connection Establishes a connection to a specific data source.   Command Executes a command at a data source. Exposes Parameters and can enlist a Transaction from a Connection.   DataReader Reads a forward-only, read-only stream of data from a data source.   DataAdapter Populates (fills) a DataSet and resolves updates with the data source.  

  30. DataReader: Direct Access to Database • Select • Stored procedure Client Application Read DataReader Command Windows Form Connection Write Command • Insert • Update • Delete • Stored procedure Web Form Database

  31. Cursor of a "Record Set" Initial position of cursor If current cursor position is here, then the execution of dr.read() returns False. Dim dr As OleDbDataReader dr = catCMD.ExecuteReader() Column index 0 1 2 Num Name Price Column name Current cursor position dr.read() moves the cursor to the next row and return True if the next row exists. Record set dr.getDecimal("Price") is illegal!

  32. Connection String • Create a new data connection from the Server Explorer • Drag the newly created Data Connection onto a web form to create a connection. An icon of the connection will be displayed under the form. • Select this connection icon. Double click on Connection String Property to select the actual connection string's value. Copy it and paste it to your program.

  33. Data Link Properties

  34. CategoryList.aspx

  35. CategoryList.aspx.vb Imports System.Data.OleDb Public Class CategoryList Inherits System.Web.UI.Page Protected WithEvents Button1 As System.Web.UI.WebControls.Button Protected WithEvents Label1 As System.Web.UI.WebControls.Label Protected WithEvents Label2 As System.Web.UI.WebControls.Label #Region " Web Form Designer Generated Code " ' … #End Region Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then Dim conn As OleDbConnection Dim cmd As OleDbCommand Dim dr As OleDbDataReader

  36. Continued… Try conn = New _ OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & Server.MapPath("Northwind.mdb")) conn.Open() cmd = New OleDbCommand("select * from categories", conn) cmd.CommandType = CommandType.Text dr = cmd.ExecuteReader() While dr.Read() Label1.Text &= dr.GetInt32(0) & "--" _ & dr.GetString(1) & "--" _ & dr.GetString(2) & "<br>" End While Catch ex As Exception Label1.Text = "Database error!" & "<br>" & ex.Message Finally dr.Close() conn.Close() End Try End If End Sub End Class Format the dynamically generated HTML page

  37. DataSet • Containers for data; know nothing about getting data from database • Disconnected and in-memory cache of database or XML data. • Mobile applications using smart devices such as Pocket PCs • Trade-off between performance and memory resources usage. • Dataset is full integrated with XML Data.

  38. ADO.NET and ASP.NET .ASPX Page DataReader Command Database Connection DataAdapter .ASPX Page DataTable DataSet Data-Bound Control DataView

  39. Data Access with ADO.NET and DataGrid SqlDataAdapter1.Fill(dsCategory1) DataGrid1.DataBind() Web Form (.ASPX) Dataset Database Data Adapter Connection DataGrid1 SqlDataAdapter1.Update(dsCategory1)

  40. Using ADO.NET and DataGrid: Coding It Manually

  41. CategoryManual.aspx <%@ Import namespace="System.Data.OleDb" %> <%@ Import namespace="System.Data" %> <%@ Page Language="vb" %> <HTML><HEAD><title>CategoryManual</title> <script runat="server"> Sub Page_Load( ByVal sender As System.Object, ByVal e As System.EventArgs) Dim conn As OleDbConnection conn = New _ OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & Server.MapPath("Northwind.mdb") ) Dim ds As DataSet = New DataSet() Dim da As OleDbDataAdapter = New _ OleDbDataAdapter("select * from Categories", conn) da.Fill(ds, "Categories") Construct a new DataAdapter da based on the SelectCommand against the Connection conn Fill a DataTable "Categories" in the DataSet ds using the DataAdapter da

  42. Continued… ' Use a DataView as a DataSource Dim dv as New DataView() dv = ds.Tables("Categories").DefaultView DataGrid1.DataSource = dv DataGrid1.DataBind() End Sub </script> </HEAD> <body><H1>Category List</H1> <form id="Form1" method="post" runat="server"> <asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid> </form></body></HTML> No need to open and close the Connection associated with a DataAdapter. • Set DataMember property to a DataTable when the DataSource is a DataSet • DataGrid1.DataSource = ds • DataGrid1.DataMember = "Categories" • DataGrid1.DataBind()

  43. Formatting, Paging, and Sorting

  44. Create ProductSort.aspx

  45. Create Connection and DataAdapter from a Table or View • Drag and drop a database table from the Server Explorer to the web form! Drag and drop

  46. Configure Data Adapter

  47. Create a Dataset: DsProduct

  48. Create and Set Up a DataGrid Control

  49. Page_Load Event Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' DataGrid1 View State can retain data during PostBack If Not IsPostBack Then OleDbDataAdapter1.Fill(DsProduct1) DataGrid1.DataBind() End If End Sub

More Related