Presentation is loading. Please wait.

Presentation is loading. Please wait.

ASP.NET Tutorial Michele Leroux Bustamante Get accompanying code samples from the following site:

Similar presentations


Presentation on theme: "ASP.NET Tutorial Michele Leroux Bustamante Get accompanying code samples from the following site:"— Presentation transcript:

1 ASP.NET Tutorial Michele Leroux Bustamante Get accompanying code samples from the following site: IDesign Site: Newsletter Site: Personal Site:

2 2 Copyright Michele Leroux Bustamante. All rights reserved. Part I: Fundamentals  My First ASP.NET Application  Page Processing & HTML Output  ASP.NET Server Controls  State Management

3 3 Copyright Michele Leroux Bustamante. All rights reserved. Part II: Advanced Techniques  Crash Course in ADO.NET  ASP.NET Database Server Controls  DataBinding  Web User Controls  Custom Web Server Controls

4 4 Copyright Michele Leroux Bustamante. All rights reserved. Part I: Fundamentals  My First ASP.NET Application  Page Processing & HTML Output  ASP.NET Server Controls  State Management

5 5 Copyright Michele Leroux Bustamante. All rights reserved. Creating a New Web Application  From VS.NET, create a new VB.NET or C# Web Application  By default, files are created beneath localhost, in a project subdirectory

6 6 Copyright Michele Leroux Bustamante. All rights reserved. Creating a New Web Application  Project Files Created in \Inetpub\wwwroot\MyWebApp

7 7 Copyright Michele Leroux Bustamante. All rights reserved. Testing Your New Application  Compile and run from VS.NET, or…  Compile, then, in your Web browser, type the URL: Did you get a blank page? Good!  Rename the web form file to default.aspx  Both the.cs/.vb file and.aspx file will be renamed  Do this from Solution Explorer!

8 8 Copyright Michele Leroux Bustamante. All rights reserved. Reviewing the HTML  You can rename the Web form class  WebForm1 -> defaultForm.cs file containing code for this page namespace class.vb file containing code for this page namespace class

9 9 Copyright Michele Leroux Bustamante. All rights reserved. Designing Web Pages  Navigating the Visual Studio IDE  HTML designer  Where you will drag and drop Web controls  HTML code  Edit the generated HTML directly  Codebehind  Separate business logic from user interface  Page and Control events can be handled in codebehind file

10 10 Copyright Michele Leroux Bustamante. All rights reserved. Web Form Architecture  Combines declarative tags…  HTML, XML, WML, static text  …with code  Clean separation between code & tags Form1.aspx code Form1.aspx code Form1.vb/.cs

11 11 Copyright Michele Leroux Bustamante. All rights reserved. Page Design  Toolbox Controls  HTML Controls  ASP.NET Server Controls  Drag & Drop to Design View  Review HTML in HTML View

12 12 Copyright Michele Leroux Bustamante. All rights reserved. HTML Controls  Drag and drop from toolbox into the HTML designer  Automatically generates HTML  Select controls in designer, editin Properties window

13 13 Copyright Michele Leroux Bustamante. All rights reserved. DOCUMENT Properties  Use the Properties window to set DOCUMENT properties  Converted to HTML automatically  Examples:  bgcolor  Inherits  pageLayout  showGrid  title

14 14 Copyright Michele Leroux Bustamante. All rights reserved. Document Outline Window  HTML Outline  Hierarchical view of HTML code  Select items to find location in HTML  Delete items easily

15 15 Copyright Michele Leroux Bustamante. All rights reserved. Document Outline Window  Script Outline  Visible in HTML View  List of events for each "named" HTML control  Use “id” attribute  Can double-click to create event handlers

16 16 Copyright Michele Leroux Bustamante. All rights reserved. Client Side Script  Project Properties  JavaScript or VBScript

17 17 Copyright Michele Leroux Bustamante. All rights reserved..ASPX Syntax  A simple page is just static text & HTML  Any HTML page can be renamed.ASPX  Pages may also contain:  Directives:  Server controls:  Code blocks:  Data bind expressions:  Server side comments:  Render code: and

18 18 Copyright Michele Leroux Bustamante. All rights reserved. Page Script void Page_Load() { // add items to the listbox lst.Items.Add("http://www.dotnetdashboard.net"); lst.Items.Add("http://www.idesign.net"); } Item1 Item2

19 19 Copyright Michele Leroux Bustamante. All rights reserved. Page Class  All ASP.NET pages are compiled into a “stateless” class (object)  Page class provides access to:  Properties to access ASP.NET server objects  Application, Cache, Request, Response, Server, Session  Properties describing page state  EnableViewState, IsPostBack, IsValid  Events that interact with round trip state  Load, Unload, PreRender, DataBinding

20 20 Copyright Michele Leroux Bustamante. All rights reserved. Page Events  Page Events  Page_Init – Fired when page is initialized  Page_Load – Fired when page is loaded  Control_Event – Fired if a control event is triggered  Page_Unload – Fired when page is unloaded from memory

21 21 Copyright Michele Leroux Bustamante. All rights reserved. Page Load Event  Load event is fired on every request  Should ALWAYS use Page.IsPostBack property to execute conditional logic public void Page_Load(object s, EventArgs e) { if (!Page.IsPostBack) //executes only on initial page load Message.Text = “initial value” }

22 22 Copyright Michele Leroux Bustamante. All rights reserved. Run As Server Control HTML controls must be run as server controls for events to be handled in Codebehind module

23 23 Copyright Michele Leroux Bustamante. All rights reserved. Codebehind - runat=“server”  HTML Controls can be processed on the server:  When the Form is submitted to the page, we can get it’s value like this: string strFirstName; strFirstName = txtFirstName.Text;

24 24 Copyright Michele Leroux Bustamante. All rights reserved. Events  ASP.NET Control Events  HTML View  HTML control events can be handled in script within the HTML page  Codebehind  Can handle events for ASP Server controls  And, HTML controls run on the server

25 25 Copyright Michele Leroux Bustamante. All rights reserved. Only HTML controls listed here (if they have an id) Client-Side Events

26 26 Copyright Michele Leroux Bustamante. All rights reserved. Selected HTML control List of valid events Client-Side Events

27 27 Copyright Michele Leroux Bustamante. All rights reserved. ASP.NET Controls  Drag and drop from toolbox into the HTML designer  Automatically generates definition  Placed between form tags in HTML  Select controls in designer, edit properties in Properties window

28 28 Copyright Michele Leroux Bustamante. All rights reserved. Codebehind Module  Write code to respond to page and control events  Use codebehind control members to manipulate properties of controls  Code is compiled into the application assembly  Beneath \bin directory

29 29 Copyright Michele Leroux Bustamante. All rights reserved. HttpRequest Object  Page.Request property  Use it to access:  Form parameters  QueryString parameters  Request headers and content  NOTE: You can save the contents of the HttpRequest by using the SaveAs() method!

30 30 Copyright Michele Leroux Bustamante. All rights reserved. HttpResponse Object  Use Page.Response property to access:  Output stream  Output cache  Send data back to the browser  BufferOutput property  Set to true, response is not sent until buffer is flushed  Set to false, Response.Write statements are flushed to client

31 31 Copyright Michele Leroux Bustamante. All rights reserved. ASP.NET Application Files  VS.NET creates default set of ASP.NET project files .csproj or.vbproj  Your project file, stores list of project files settings .webinfo  Project file indicating the URL for the Web application based on IIS path (edit if project is moved) .sln  Solution file, can load more than one project  VS.NET will load the solution

32 32 Copyright Michele Leroux Bustamante. All rights reserved. ASP.NET Application Files  Web.config  Can customize application configuration settings  Can override Machine.config settings  Global.asax  Represents the HttpApplication object  Can write code for application-level events  *.aspx  Default Web forms is WebForm1.aspx  Inherits the Page class  Can add more pages, and rename them as desired  Must select 1 to be the “startup” page

33 33 Copyright Michele Leroux Bustamante. All rights reserved. Global.asax  Inherits HttpApplication  Provides access to the application instance during an HTTP request Application directive links to codebehind  Like.aspx files,.asax can include:  Server side tags  Object creation tags Application Codebehind="Global.asax.vb" Inherits="ViewState.Global" %>

34 34 Copyright Michele Leroux Bustamante. All rights reserved. Global.asax  Can handle application and HttpModule events  For example, SessionStateModule Session.Start Application.Start Application.EndRequest Application.BeginRequest Session.End Application.End

35 35 Copyright Michele Leroux Bustamante. All rights reserved. Part I: Fundamentals  My First ASP.NET Application  Page Processing & HTML Output  ASP.NET Server Controls  State Management

36 36 Copyright Michele Leroux Bustamante. All rights reserved. Page Class  Page class is dynamically compiled by ASP.NET  Requests are handled by instance  HTML is written to the response stream by the page Page Object *.aspx Codebehind

37 37 Copyright Michele Leroux Bustamante. All rights reserved. *.ASPX Files  Defaults to Codebehind  Can Page directive  Benefits of Codebehind  Intermediate Language (IL) compiler can catch errors  *.ASPX are JIT compiled, users see uncaught errors  Clean separation of business logic and user interface presentation with a preserved event-driven model  Event validation controls perform client-side work, no need for in-page scripting (most of the time)

38 38 Copyright Michele Leroux Bustamante. All rights reserved. Codebehind  Codebehind inherits System.Web.UI.Page  Can handle Page events of interest Page.Load Page.Init Page.PreRender Page_DataBinding Page.Unload

39 39 Copyright Michele Leroux Bustamante. All rights reserved. Page Events

40 40 Copyright Michele Leroux Bustamante. All rights reserved. The Round Trip Controls HTTP Request Page Object HTTP Response Render Control HTML Render Page and Control HTML

41 41 Copyright Michele Leroux Bustamante. All rights reserved. The Round Trip HTTP Request Fire Events Render HTML Codebehind Source.aspx Page Class IL JIT Compiler Populate Members Create Page Object HTTP Response Page Object

42 42 Copyright Michele Leroux Bustamante. All rights reserved. Page Processing  Page/Control events get executed on the server during page processing  First, the Page.Load event for requested page  Followed by:  Other page events  Other “cached” control events

43 43 Copyright Michele Leroux Bustamante. All rights reserved. Control Events  Posted form parameters indicate:  Which control initiated HTTP POST  Selected control values  ASP.NET determines which events to fire  Based on changes in control values  Based on initiator of POST  Some controls can trigger a POST  Button click, Textbox change, Listbox select

44 44 Copyright Michele Leroux Bustamante. All rights reserved. HTTP POST: Button Click  Example:  Enter a new TextBox value  Select from a DropDownList or ListBox  Click a Button

45 45 Copyright Michele Leroux Bustamante. All rights reserved. HTTP POST: Button Click POST /ASPNETVB/ViewState/WebForm1.aspx HTTP/1.1 Cache-Control: no-cache Connection: Keep-Alive Content-Length: 135 Content-Type: application/x-www-form-urlencoded Accept:...; Accept-Encoding: gzip, deflate Accept-Language: en-us Cookie:.ASPXAUTH=...; ASP.NET_SessionId=ns53k155dbrbid21tccazt2e Host: localhost Referer: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0;.NET CLR ) __VIEWSTATE=dDwxMTIxMTQ1NzU1Ozs%2BAXQdcFai%2F004j3lupIyx0ltGA4U%3D&TextBo x1=goodbye&Button1=Select&DropDownList1=Item+4&ListBox1=Item+3

46 46 Copyright Michele Leroux Bustamante. All rights reserved. HTTP POST: Button Click  Form parameters indicate user entries:  TextBox1=goodbye  Button1=Select  DropDownList1=Item 4  ListBox1=Item 3 __VIEWSTATE=dDwxMTIxMTQ1NzU1Ozs%2BAXQdcFai%2F004j3lupIyx0ltGA4U%3D&TextBo x1=goodbye&Button1=Select&DropDownList1=Item+4&ListBox1=Item+3

47 47 Copyright Michele Leroux Bustamante. All rights reserved. Accessing Form Parameters  Page members are recreated on the round-trip  If view state is enabled  Control names in codebehind match.aspx identifiers // Control Members protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.DropDownList DropDownList1; // Code to access member values s = TextBox1.Text; s = DropDownList1.SelectedItem.Text;

48 48 Copyright Michele Leroux Bustamante. All rights reserved. Accessing Form Parameters  Request.Form property contains name/value pairs  Regardless of view state s = Request.Form[“TextBox1”]; s = Request.Form[“DropDownList1”];

49 49 Copyright Michele Leroux Bustamante. All rights reserved. HTML Output  ASP.NET generates HTML output  Automatic management of browser output  Hidden  __VIEWSTATE field stores persisted page and control data between round trips....

50 50 Copyright Michele Leroux Bustamante. All rights reserved. HTML Output  Client Script  Emitted with HTML output as client-side script block  ASP.NET validation controls emit client script

51 51 Copyright Michele Leroux Bustamante. All rights reserved. Part I: Fundamentals  My First ASP.NET Application  Page Processing & HTML Output  ASP.NET Server Controls  State Management

52 52 Copyright Michele Leroux Bustamante. All rights reserved. HTML vs. Server Controls  HTML Controls  Follow DHTML object model  Fewer Properties, Methods, Events  Valuable when no server interaction, or client side events are also necessary

53 53 Copyright Michele Leroux Bustamante. All rights reserved. HTML vs. Server Controls  ASP.NET Server Controls  Similar to Windows Forms object model  More functionality:  DataGrid, DataList, Calendar  Different syntax  Requires JIT compilation  First page load is affected  Are always run on the server  Round trips can be managed

54 54 Copyright Michele Leroux Bustamante. All rights reserved. WebControls Namespace  System.Web.UI.WebControls  Contains classes for creating Web server controls  Base Class WebControl  Contains common members for all Web server controls  BackColor, ForeColor, Font, Height, Width etc.  Web server controls render their own HTML  Page class is the container for controls  Controls render their own HTML as Page is rendered

55 55 Copyright Michele Leroux Bustamante. All rights reserved. Web Server Controls  Some Shared Properties:  AutoPostBack – should events be posted or cached?  EnableViewState – property persistence  CssClass – style sheet class  Tooltip – “title” attribute of HTML element  Visible / Enabled

56 56 Copyright Michele Leroux Bustamante. All rights reserved. Button  Can be a submit button or command button  Default is submit button  Handle the Click event  Set CommandName, CommandArgument property  Handle Click or Command event  Both events are fired on submit  Command event receives CommandEventArgs

57 57 Copyright Michele Leroux Bustamante. All rights reserved. ImageButton, Image  ImageButton is similar to Button  Handle Click or Command events  Displays an image  Properties: ImageAlign, ImageUrl, AlternateText  Image displays an image  No postback events  Properties: ImageAlign, ImageUrl, AlternateText

58 58 Copyright Michele Leroux Bustamante. All rights reserved. LinkButton, HyperLink  LinkButton creates a hyperlink with Button functionality  Handle Click or Command events  HyperLink creates a hyperlink  Link directly to another page, no postback  Can display text or image  Properties: Text, ImageUrl, NavigateUrl, Target

59 59 Copyright Michele Leroux Bustamante. All rights reserved. TextBox  TextMode Property  SingleLine, MultiLine, Password  TextChanged Event  Triggers server post if the AutoPostBack property is true  Otherwise, event is cached until post occurs  Event will still be triggered, not guaranteed in what order compared to other control server events

60 60 Copyright Michele Leroux Bustamante. All rights reserved. List Controls  Similar to Windows Forms controls  Support Data Binding (covered later)  Base Class WebControls.ListControl  DropDownList  ListBox  CheckBoxList  RadioButtonList

61 61 Copyright Michele Leroux Bustamante. All rights reserved. Validation Controls  Validation controls inherit BaseValidator  Which inherits Label  Which inherits WebControl  Validate associated input control  Can apply multiple validation controls to a single control  Support client-side validation  Deliver JavaScript to the client (no coding necessary!)  Avoid round trip for validation

62 62 Copyright Michele Leroux Bustamante. All rights reserved. Validation Controls  Place control on the form where error messages should appear  Error message will be displayed if validation fails  Can be validated on client or server (defaults to client validation)

63 63 Copyright Michele Leroux Bustamante. All rights reserved. Validation Controls  Text appears if validation fails

64 64 Copyright Michele Leroux Bustamante. All rights reserved. Validation Controls  RequiredFieldValidator  RangeValidator  RegularExpressionValidator  CustomValidator  CompareValidator  ValidationSummary  Can create custom validation controls  Inherit BaseValidator

65 65 Copyright Michele Leroux Bustamante. All rights reserved. Common Properties  ControlToValidate – which input control to validate  EnableClientScript – controls client/server validation  ErrorMessage – message to display in ValidationSummary control or in this control  Text – overrides display in this control, use * if using ValidationSummary control

66 66 Copyright Michele Leroux Bustamante. All rights reserved. RequiredFieldValidator  Validates the specified control for user input  Compares input value to IntialValue property

67 67 Copyright Michele Leroux Bustamante. All rights reserved. RangeValidator  Specify a data type to compare  Specify a maximum and minimum  Validation succeeds if input data is empty  Use RequiredFieldValidator to enforce value

68 68 Copyright Michele Leroux Bustamante. All rights reserved. RegularExpressionValidator  Matches input against a pattern  , Phone Numbers, SSN  Set ValidationExpression property  Dialog box supports predefined choices  Can create custom expression

69 69 Copyright Michele Leroux Bustamante. All rights reserved. RegularExpressionValidator  Client validation uses JScript  Server uses RegEx  Validation succeeds if input data is empty

70 70 Copyright Michele Leroux Bustamante. All rights reserved. CompareValidator  Compare the validated control input value with another control’s input value  ControlToValidate, ControlToCompare properties  Compare to a static value  ValueToCompare, Type properties  Use Operator property to indicate method of comparison  Measure equality  Perform data type checks

71 71 Copyright Michele Leroux Bustamante. All rights reserved. CustomValidator  User-defined validation for input  For client validation specify ClientValidationFunction  For server validation, handle ServerValidate event

72 72 Copyright Michele Leroux Bustamante. All rights reserved. ValidationSummary  ErrorMessage property values will be listed in summary control  Text property displays in control

73 73 Copyright Michele Leroux Bustamante. All rights reserved. Server-Side Validation  Server validation always performed  Page.Validate initiates validation  By default, validation happens after Page.Load event, before individual control events  Invoked by ASP.NET

74 74 Copyright Michele Leroux Bustamante. All rights reserved. Server-Side Validation  Page.Validate method must be explicitly called prior to checking Page.IsValid property during Page.Load  Can override failed validation by correcting problem and re-validating (call Page.Validate)

75 75 Copyright Michele Leroux Bustamante. All rights reserved. Part I: Fundamentals  My First ASP.NET Application  Page Processing & HTML Output  ASP.NET Server Controls  State Management

76 76 Copyright Michele Leroux Bustamante. All rights reserved. State Management  Application State  Data for an entire application  Limited use for frequently used, static data  Session State  Isolates data for a specific user  Default session timeout is 20 minutes, can be configured  View State  Persistence of page and control properties

77 77 Copyright Michele Leroux Bustamante. All rights reserved. HttpApplicationState  Exposed through intrinsic Application object  HttpApplication.Application  HttpContext.Application  Page.Application  Stores Key/Value Pairs  Add any type of object to the collection  Access using standard collection syntax, by name or index value

78 78 Copyright Michele Leroux Bustamante. All rights reserved. Application Values  HttpApplication.StaticObjects Collection  Stores object with application scope created using the tag // setting values Application.Add(“dbconnect", "Provider=SQLOLEDB.1;…”); or Application[“dbconnect”] = "Provider=SQLOLEDB.1;…”; // getting values String s = (String)Application[“dbconnect"];

79 79 Copyright Michele Leroux Bustamante. All rights reserved. Application StaticObjects  Generate object with scope via global.asax  Instantiated when application is started  Access via Application.StaticObjects  Use Lock(), UnLock() to protect state

80 80 Copyright Michele Leroux Bustamante. All rights reserved. Application StaticObjects // in global.asax // setting value when application is loaded Application.Lock(); UrlInfo obj = (UrlInfo)Application.StaticObjects[“appobj"]; obj.Url="http://www.idesign.net"; obj.Title="IDesign Associates"; Application.UnLock();

81 81 Copyright Michele Leroux Bustamante. All rights reserved. HttpApplicationState  Limitations  Application state information is cleared when application is restarted  Not shared across multiple servers (web farms)  Uses memory resources  Only thread safe objects should be saved  Locking can cause scalability issues

82 82 Copyright Michele Leroux Bustamante. All rights reserved. HttpSessionState  Exposed through intrinsic Session object  HttpApplication.Session  HttpContext.Session  Page.Session  Stores Key/Value Pairs  Add any type of object to the collection  Access using standard collection syntax, by name or index value

83 83 Copyright Michele Leroux Bustamante. All rights reserved. Session Values  HttpSessionState.StaticObjects Collection  Stores object with session scope created using the tag // setting values Application.Session.Add(“name",”Joe Smith”); or Application.Session[“name“] = ”Joe Smith”; // getting values String s = (String)Application.Session[“name"];

84 84 Copyright Michele Leroux Bustamante. All rights reserved. Session StaticObjects  Generate object with scope via global.asax  Instantiated when each session is started  One object for each active session  Access via Session.StaticObjects

85 85 Copyright Michele Leroux Bustamante. All rights reserved. Session StaticObjects // in global.asax // setting value when application is loaded UrlInfo obj = (UrlInfo)Application.Session.StaticObjects[“sessionobj"]; obj.Url="http://www.idesign.net"; obj.Title="IDesign Associates";

86 86 Copyright Michele Leroux Bustamante. All rights reserved. Session Configuration  Machine.config  By default enables session state  Can override in Web.config  EnableSessionState  Attribute of Page directive  Set to False for pages that don’t require a session object  Delays creation of session object  Can’t use Session object from pages that have this disabled

87 87 Copyright Michele Leroux Bustamante. All rights reserved. ViewState  Used to persist ASP.NET server control state between round trips  Implemented with a hidden field in client HTML  Can be disabled per page or control

88 88 Copyright Michele Leroux Bustamante. All rights reserved. ViewState  EnableViewState=true  EnableViewState=false

89 89 Copyright Michele Leroux Bustamante. All rights reserved. ViewState  You can save custom state information from page to page using ViewState // setting values this.ViewState[“customerid"] = “12345"; // getting values String s = (String)ViewState[“customerid"];

90 90 Copyright Michele Leroux Bustamante. All rights reserved. Part II: Advanced Techniques  Crash Course in ADO.NET  ASP.NET Database Server Controls  DataBinding  Web User Controls  Custom Web Server Controls

91 91 Copyright Michele Leroux Bustamante. All rights reserved. ADO.NET Data Providers  Set of classes interacting with a specific type of datasource  Optimized access  Provided with.NET  SQL Server Provider  OLE DB Provider  Other providers can be downloaded from Microsoft  I.e.,.NET Data Provider for Oracle

92 92 Copyright Michele Leroux Bustamante. All rights reserved. Data Provider Objects  ADO.NET Classes supporting interaction with database providers  Categories of classes:  Connection  Command  DataReader  DataSet  DataAdapter  DataView

93 93 Copyright Michele Leroux Bustamante. All rights reserved. Data Access – Basic Steps  Create and Open Connection  Create Command object with SQL query statements or Stored Procedure name  Execute command and retrieve data  Manually iterate through dataset results OR  Bind dataset results directly to Web controls

94 94 Copyright Michele Leroux Bustamante. All rights reserved. Connection Object  OleDbConnecton or SqlConnection  Implements IDbConnection  Establish and terminate data source connection  Properties initialized by constructor  ConnectionString  Database  DataSource  Must be explicitly closed  Call Close() or Dispose()

95 95 Copyright Michele Leroux Bustamante. All rights reserved. Connection Object SqlConnection objSQLConnection = new SqlConnection("Data Source=.; Initial Catalog=pubs; UID=sa; PWD="); objSQLConnection.Open(); // do work objSQLConnection.Close()

96 96 Copyright Michele Leroux Bustamante. All rights reserved. Connection String Examples  Connection string is database-specific  SQL Server Example:  Microsoft Access (*.mdb) Example:  DSN Example: "Data Source=.; Initial Catalog=pubs; UID=sa; PWD=" "server=localhost; database=pubs; uid=sa” “PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source=[path]authors.mdb” “DSN=myDSN”

97 97 Copyright Michele Leroux Bustamante. All rights reserved. Command Object  OleDbCommand or SqlCommand  Implements IDbCommand  Execute SQL statements or Stored Procedures against datasource  Requires a valid Connection be opened prior to execution  Connection property

98 98 Copyright Michele Leroux Bustamante. All rights reserved. Command Object  Commands are executed to return data  ExecuteNonQuery()  ExecuteReader()  ExecuteScalar()  ExecuteXmlReader() – SqlCommand only  CommandType indicates how command should execute against an open connection  SQL query is default setting

99 99 Copyright Michele Leroux Bustamante. All rights reserved. ExecuteReader()  Returns IDbReader object  SqlCommand returns SqlDataReader  OleDbCommand returns OleDbDataReader SqlCommand objSQLCommand; string strSQL = "select * from authors"; objSQLCommand = new SqlCommand(strSQL, objSQLConnection); SqlDataReader reader = objSQLCommand.ExecuteReader();

100 100 Copyright Michele Leroux Bustamante. All rights reserved. Sample SQL Queries SELECT list of fields FROM table name SELECT * FROM Titles SELECT Title, [Year Published], ISBN FROM Titles SELECT Titles.Title, Titles.[Year Published], Titles.ISBN, Publishers.Name FROM Titles SELECT list of fields FROM table name WHERE condition SELECT * FROM Titles WHERE [Title] = ‘some title’ SELECT * FROM Titles WHERE [Year Published] > 1990 SELECT list of fields FROM table name WHERE condition ORDER BY field SELECT * FROM Titles WHERE [Year Published] = 1990 ORDER BY Title

101 101 Copyright Michele Leroux Bustamante. All rights reserved. DataReader Object  OleDbDataReader or SqlDataReader  Implements IDbReader  Read-only and forward-only access to a set of rows from the datasource  Lightweight, high-performance access  Reads only 1 record at a time  Cannot be cached on the server

102 102 Copyright Michele Leroux Bustamante. All rights reserved. DataReader Object  Iterating through a DataReader SqlDataReader reader = objSQLCommand.ExecuteReader(); while (reader.Read()) { // Example: get values from the first field string s = (string)reader.GetValue(0); }

103 103 Copyright Michele Leroux Bustamante. All rights reserved. DataReader Object  Assigning a DataReader to the DataGrid.DataSource SqlDataReader reader = objSQLCommand.ExecuteReader(); dagMain.DataSource = reader; dagMain.DataBind();

104 104 Copyright Michele Leroux Bustamante. All rights reserved. DataSet Object  In-memory representation of XML or datasource  Disconnected, remotable  Not tied to a provider  Manipulation of relational data  Tables, Rows, Columns, Constraints, Relationships

105 105 Copyright Michele Leroux Bustamante. All rights reserved. DataSet Object System.Data.DataSet ds = new System.Data.DataSet(); SqlDataAdapter da = new SqlDataAdapter(objSQLCommand); int n = da.Fill(ds); foreach (DataTable tbl in ds.Tables) { foreach (DataRow tr in tbl.Rows) { foreach (object o in tr.ItemArray) // access to fields }

106 106 Copyright Michele Leroux Bustamante. All rights reserved. DataAdapter Object  OleDbDataAdapter or SqlDataAdapter  Implements IDbDataAdapter  IDbDataAdapter inherits IDataAdapter  Bridge between DataSet and data source  Can update the data source using specified SQL commands  Can generates a DataSet or DataTable  Use Fill() method from prior examples

107 107 Copyright Michele Leroux Bustamante. All rights reserved. Part II: Advanced Techniques  Crash Course in ADO.NET  ASP.NET Database Server Controls  DataBinding  Web User Controls  Custom Web Server Controls

108 108 Copyright Michele Leroux Bustamante. All rights reserved. Core Databound Controls  ListControl (Base)  DropDownList  ListBox  CheckBoxList  RadioButtonList  DataGrid  DataList  Repeater

109 109 Copyright Michele Leroux Bustamante. All rights reserved. Common Binding Properties  DataSource – source of data binding  DataValueField – field from data source that provides the value of each item  DataTextField – field from data source to display  DataMember – indicates a member from a multi-member DataSource (i.e., multiple tables in a DataSet)  DataTextFormatString – format string to be used on data bound to the control

110 110 Copyright Michele Leroux Bustamante. All rights reserved. Bound List Controls  Bind to an array  Specify DataSource  Issue DataBind() for the control or page string[] colors = System.Enum.GetNames(typeof(System.Drawing.KnownColor)); this.ListBox1.DataSource=colors; this.DataBind();

111 111 Copyright Michele Leroux Bustamante. All rights reserved. Bound List Controls  Bind to an XML file  Specify DataSource, DataTextField, and DataValueField (optional)  Issue DataBind() for control or page System.Data.DataSet ds = new DataSet("cultures"); string sPath = this.MapPath(""); StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}\\cultures.xml", sPath); ds.ReadXml(sb.ToString()); lstCultures.DataSource=ds; lstCultures.DataValueField = "value"; lstCultures.DataTextField = "descrip"; lstCultures.DataBind();

112 112 Copyright Michele Leroux Bustamante. All rights reserved. Bound List Controls  Bind to a particular column  Specify DataSource, DataTextField, and DataValueField (optional)  Issue DataBind() for control or page

113 113 Copyright Michele Leroux Bustamante. All rights reserved. Bound List Controls SqlConnection objSQLConnection = new SqlConnection("Data Source=.; Initial Catalog=pubs; UID=sa; PWD="); SqlCommand objSQLCommand; string strSQL = "select * from authors"; objSQLConnection.Open(); objSQLCommand = new SqlCommand(strSQL, objSQLConnection); System.Data.DataSet ds = new System.Data.DataSet(); SqlDataAdapter da = new SqlDataAdapter(objSQLCommand); int n = da.Fill(ds); ddl.DataSource=ds; ddl.DataTextField="au_fname"; ddl.DataValueField="au_fname"; ddl.DataBind();

114 114 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Control  Bind to a data source  Specify DataSource  Issue DataBind() for the control or page  AutoGenerateColumns is true by default  Set to false if specifying columns to bind System.Data.DataSet ds = new DataSet("cultures"); string sPath = this.MapPath(""); StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0}\\cultures.xml", sPath); ds.ReadXml(sb.ToString()); this.DataGrid1.DataSource=ds; this.DataGrid1.DataBind();

115 115 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Appearance  Header and Footer  FooterStyle, ShowFooter  HeaderStyle, ShowHeader  Row Appearance  ItemStyle  SelectedItemStyle  AlternatingItemStyle

116 116 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Paging  AllowPaging  Enables paging, disabled by default  PageSize defaults to 10  PagerStyle  Set properties of the paging area  Custom paging also supported  Optimize process for large datasets  Greater control over paging process

117 117 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Paging

118 118 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Paging  PageIndexChanged Event  Handle this to complete implementation for paging  DataGridPageChangedEventArgs provides access to selected page index  Bound data is lost on round-trip  Must rebind data source after setting the page index private void dagMain_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) { dagMain.CurrentPageIndex = e.NewPageIndex ; dagMain.DataBind(); }

119 119 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Columns  Can indicate specific columns and fields to bind to  Can format, sort, alter column header

120 120 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Columns

121 121 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Commands  Can add button columns for selection, edit/update/cancel, or delete  Should handle events for each button action

122 122 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Commands

123 123 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Commands  Events provided for each command:  CancelCommand, DeleteCommand, EditCommand, UpdateCommand, SelectIndexCommand private void OnSelectedIndexChanged(object sender, System.EventArgs e) { // SelectedItem has been set when this event is triggered TableCellCollection cells = DataGrid1.SelectedItem.Cells; Response.Write(String.Format(“Selected row contains:{0},{1},{2} “, cells[0].Text, cells[1].Text, cells[2].Text)); }

124 124 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Commands  ItemCommand Event is invoked for all commands  Invoked prior to individual commands  Can check command name using static members

125 125 Copyright Michele Leroux Bustamante. All rights reserved. DataGrid Commands private void OnItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { if (e.CommandName == DataGrid.SelectCommandName) { // Cell information is available from the // DataGridCommandEventArgs string s = e.Item.Cells[0].Text; // at this time, selectedIndex is -1, // so if accessing the SelectedItem // in this handler, must set SelectedIndex first DataGrid1.SelectedIndex = e.Item.ItemIndex; s = DataGrid1.SelectedItem.Cells[0].Text; // s holds productId }

126 126 Copyright Michele Leroux Bustamante. All rights reserved. DataList Control  Initialize similar to DataGrid  Set DataSource and issue DataBind() command  Handle command events  Must define templates for rows and columns  Using VS.NET editor  Using HTML directly  Programmatically  Does not support automatic paging or sorting  Use DataGrid for these features

127 127 Copyright Michele Leroux Bustamante. All rights reserved. Editing DataList Templates  VS.NET design environment supports editing templates for header, footer, items and separators Right-click on control and select from Edit Template menu options

128 128 Copyright Michele Leroux Bustamante. All rights reserved. Templates  Draw HTML or ASP.NET controls from the ToolBox into template regions  Can edit style such as background color and font Header and Footer Templates Separator Template Regular Item Template Alternating Item with different background color Edit Item with TextBox in place of Labels

129 129 Copyright Michele Leroux Bustamante. All rights reserved. Part II: Advanced Techniques  Crash Course in ADO.NET  ASP.NET Database Server Controls  DataBinding  Web User Controls  Custom Web Server Controls

130 130 Copyright Michele Leroux Bustamante. All rights reserved. Binding Data  Bind elements of each row using DataBindings dialog  Accessible from the Properties window  Alternative to editing HTML directly

131 131 Copyright Michele Leroux Bustamante. All rights reserved. Binding Data List of bindable properties Custom binding expression

132 132 Copyright Michele Leroux Bustamante. All rights reserved. Binding Data  Bind control to data source  Data bindings added to HTML view via DataBindings dialog, or manually OleDbDataReader rdr = cmd.ExecuteReader(); this.DataList1.DataSource = rdr; this.DataList1.DataBind(); Last Updated:

133 133 Copyright Michele Leroux Bustamante. All rights reserved. Binding Data  Example binding to specific fields in the data source  DataSource property must be set before DataBind() issued, and field names must be correct

134 134 Copyright Michele Leroux Bustamante. All rights reserved. Binding Data

135 135 Copyright Michele Leroux Bustamante. All rights reserved. DataList Appearance  Can arrange HTML output per row  Further customizable using DataRepeater control

136 136 Copyright Michele Leroux Bustamante. All rights reserved. Data Binding  Process of tying UI elements to a datastore such as a DataSet  ASP.NET provides server-side data binding  Removes issues of browser compatibility  Binds and renders data on the server  Outputs browser-independent HTML

137 137 Copyright Michele Leroux Bustamante. All rights reserved. DataSource Binding  Most ASP.NET server controls support data binding  Properties Window  Set DataBindings for control  Provides a list of properties that are bindable for the selected control

138 138 Copyright Michele Leroux Bustamante. All rights reserved. DataBind() Method  Page.DataBind()  Can perform data binding at the page level  Binds all controls on the page  Control.DataBind()  Instance method binds only that control  Binding forces the evaluation of data- binding expressions  Renders values to HTML output  DataBinding() event is triggered when binding occurs for the page

139 139 Copyright Michele Leroux Bustamante. All rights reserved. Data Binding Expressions  Placed between  Used to bind control properties  Used anywhere in the page runat="server" /> or literal text

140 140 Copyright Michele Leroux Bustamante. All rights reserved. DataBinder.Eval  Evaluates and formats the result of late-bound data-binding expressions  Uses late-binding and reflection  Carries overhead, but assists with data type casting  Can be useful for single-line formatting

141 141 Copyright Michele Leroux Bustamante. All rights reserved. DataBinder.Eval  Convert “Amount” field to string:  Format “thumbNailImage” field with path:

142 142 Copyright Michele Leroux Bustamante. All rights reserved. Part II: Advanced Techniques  Crash Course in ADO.NET  ASP.NET Database Server Controls  DataBinding  Web User Controls  Custom Web Server Controls

143 143 Copyright Michele Leroux Bustamante. All rights reserved. Web User Controls  Reusable Web form interface  Only within the same project  Designed just like Web forms  Drag & drop Web controls, write event handlers, etc.  Unlike custom Web server controls (covered later)

144 144 Copyright Michele Leroux Bustamante. All rights reserved. Creating Web User Controls  Add a Web User Control to the project  *.ascx file is added to project  Design as you would a Web page

145 145 Copyright Michele Leroux Bustamante. All rights reserved. Using Web User Controls  From Solution Explorer, drag & drop the.ascx file to an open Web form  Register to HTML  Source file, tag prefix & tag name

146 146 Copyright Michele Leroux Bustamante. All rights reserved. Using Web User Controls  Adds control declaration to HTML  Must be contained within tag for events to work!

147 147 Copyright Michele Leroux Bustamante. All rights reserved. Web User Controls Features  Compiled dynamically at runtime  Can’t be added to the Toolbox  Supports properties!  No Properties Window support  Easy to design using HTML Designer  Can combine Web user controls from multiple languages on a page  Support for fragment caching

148 148 Copyright Michele Leroux Bustamante. All rights reserved. Fragment Caching  Web User Controls can be cached OutputCache Directive  Placed inside *.ascx file

149 149 Copyright Michele Leroux Bustamante. All rights reserved. Fragment Caching  PartialCachingAttribute  Placed in codebehind file, as an attribute to the Web user control class  Attribute constructor supports supplying only Duration value [PartialCaching(30)] public abstract class Login : System.Web.UI.UserControl { // control definition }

150 150 Copyright Michele Leroux Bustamante. All rights reserved. Part II: Advanced Techniques  Crash Course in ADO.NET  ASP.NET Database Server Controls  DataBinding  Web User Controls  Custom Web Server Controls

151 151 Copyright Michele Leroux Bustamante. All rights reserved. Custom Web Server Controls  Great for code re-use, maintenance and specialization  Assembly deployment model  Completely reusable binary component  Can leverage.NET versioning  Single copy shared by multiple projects  Can be deployed to the Global Assembly Cache (GAC)

152 152 Copyright Michele Leroux Bustamante. All rights reserved. Web Control Library  New Web Control Library project  Project generates one Web control class by default, can define more classes

153 153 Copyright Michele Leroux Bustamante. All rights reserved. Web Control Base Classes  System.Web.UI.Control  Base class to Page object & all Web server controls (some through WebControl)  Properties Provided  ID  EnableViewState  Visible

154 154 Copyright Michele Leroux Bustamante. All rights reserved. Web Control Base Classes  System.Web.UI.WebControls.WebControl  Derived from Control  Base class to Web server controls  Default base class for a new Web Control Library  Properties Provided  BackColor, BorderStyle, CssClass, Enabled, Font, Visible, Width

155 155 Copyright Michele Leroux Bustamante. All rights reserved. HtmlTextWriter  Render method provides access to the HtmlTextWriter  Provides methods to write HTML tags and content to the output stream  AddAttribute, RenderBeginTag, RenderEndTag  Write, WriteLine  Static constants  SelfClosingEndTag, SingleQuoteChar, SpaceChar

156 156 Copyright Michele Leroux Bustamante. All rights reserved. HtmlTextWriter  HtmlTextWriter rendering code: protected override void Render(HtmlTextWriter output) { output.AddAttribute(HtmlTextWriterAttribute.Alt, “Flower Image”, true); output.AddAttribute(HtmlTextWriterAttribute.Src, “flower.jpg”, true); output.AddAttribute("myattribute", “custom attribute info”, false); output.RenderBeginTag(HtmlTextWriterTag.Img); output.RenderEndTag(); output.WriteLine(); }

157 157 Copyright Michele Leroux Bustamante. All rights reserved. HtmlTextWriter  Resulting HTML output:

158 158 Copyright Michele Leroux Bustamante. All rights reserved. Render Method  Provides access to the HtmlTextWriter to send output to the Web form  Provides methods to write HTML tags and content to the output stream

159 159 Copyright Michele Leroux Bustamante. All rights reserved. Render Method protected override void Render(HtmlTextWriter output) { output.AddAttribute(HtmlTextWriterAttribute.Alt, "Encoding, \"Required\"", true); output.AddAttribute(HtmlTextWriterAttribute.Src, “http://localhost//ASPNETCS//MLBWebControlClient//peaches_sm.jpg”, true); output.AddAttribute("myattribute", "No "encoding " required", false); output.RenderBeginTag(HtmlTextWriterTag.Img); output.RenderEndTag(); output.WriteLine(); }

160 160 Copyright Michele Leroux Bustamante. All rights reserved. Using Web Server Controls  From the Tools menu, select Customize Toolbox…  Browser for your Web server control DLL  Select the control, it will be added to the toolbox  Drag & drop the control to the Web form  Register to HTML  Source file, tag prefix & tag name

161 161 Copyright Michele Leroux Bustamante. All rights reserved. Using Web Server Controls  Adds control declaration to HTML

162 162 Copyright Michele Leroux Bustamante. All rights reserved. Composite Controls  Implement INamingContainer  No methods or properties  Ensures unique namespace for child controls in Page hierarchy  Override Control.CreateChildControls()  Add child controls to Controls collection  Creates a composite control

163 163 Copyright Michele Leroux Bustamante. All rights reserved. Composite Controls  Add to the Controls collection of the WebControl or Control class  Create Web server controls, set their properties, including style and position

164 164 Copyright Michele Leroux Bustamante. All rights reserved. Composite Controls  Create HTML literals, also added to Controls collection protected override void CreateChildControls() { this.Controls.Add(new LiteralControl(" ")); Label label1 = new Label(); label1.Text = "Click the button below."; this.Controls.Add(label1); this.Controls.Add(new LiteralControl(" ")); Button btn = new Button(); btn.Text = "Click Me"; btn.Width=new Unit("50%"); btn.Click += new EventHandler(this.OnClick); this.Controls.Add(btn); }

165 165 Copyright Michele Leroux Bustamante. All rights reserved. Composite Controls  Overriding Control.Render()  For composite controls, call base class Render()  Child controls will render themselves  Add custom rendering code if desired protected override void Render(HtmlTextWriter output) { // do nothing, allow rendering by composite controls base.Render(output); }

166 166 Copyright Michele Leroux Bustamante. All rights reserved. Presentation Details  Library & Control Name  Displayed in Customize Toolbox dialog  Custom Icon  System.Drawing.ToolboxBitmapAttribute  Applied to the control class  Specify filename or resource item

167 167 Copyright Michele Leroux Bustamante. All rights reserved. Presentation Details

168 168 Copyright Michele Leroux Bustamante. All rights reserved. Presentation Details [ToolboxBitmap("toolbox.ico")] [DefaultProperty(“Description"), ToolboxData(" ")] public class ImageInfo : System.Web.UI.WebControls.WebControl, INamingContainer { // Control definition }

169 169 Copyright Michele Leroux Bustamante. All rights reserved. References .NET Dashboard   A growing list of articles and code  Web Services Tutorial Site   Tutorial session code samples  Additional references


Download ppt "ASP.NET Tutorial Michele Leroux Bustamante Get accompanying code samples from the following site:"

Similar presentations


Ads by Google