Presentation is loading. Please wait.

Presentation is loading. Please wait.

ASP.NET Tutorial Michele Leroux Bustamante

Similar presentations


Presentation on theme: "ASP.NET Tutorial Michele Leroux Bustamante"— Presentation transcript:

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

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

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

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

5 Creating a New Web Application
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

7 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! Copyright Michele Leroux Bustamante. All rights reserved.

8 Reviewing the HTML You can rename the Web form class
WebForm1 -> defaultForm Page language=“C#” Codebehind=“default.cs” AutoEventWireup=“false” Inherits=“MyWebApp.WebForm1” %> namespace .cs file containing code for this page class Page language=“vb” Codebehind=“default.vb” AutoEventWireup=“false” Inherits=“MyWebApp.WebForm1” %> namespace .vb file containing code for this page class Copyright Michele Leroux Bustamante. All rights reserved.

9 Designing Web Pages Navigating the Visual Studio IDE HTML designer
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

10 Web Form Architecture Combines declarative tags… …with code
Web Services Tutorial Updated 04/07/2003 Web Form Architecture Combines declarative tags… HTML, XML, WML, static text …with code Clean separation between code & tags <tags> <tags> code code Form1.aspx Form1.aspx Form1.vb/.cs Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

11 Page Design Toolbox Controls Drag & Drop to Design View
Web Services Tutorial Updated 04/07/2003 Page Design Toolbox Controls HTML Controls ASP.NET Server Controls Drag & Drop to Design View Review HTML in HTML View Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

12 HTML Controls Drag and drop from toolbox into the HTML designer
Web Services Tutorial Updated 04/07/2003 HTML Controls Drag and drop from toolbox into the HTML designer Automatically generates HTML Select controls in designer, edit in Properties window <form id=“form1” method=“post” runat=“server> <INPUT id=“Button1” type=“button” value="Button" name="Button1" runat="server“> <INPUT id=“Text1” type=“text” value="Button" </form> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

13 Web Services Tutorial Updated 04/07/2003 DOCUMENT Properties Use the Properties window to set DOCUMENT properties Converted to HTML automatically Examples: bgcolor Inherits pageLayout showGrid title Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

14 Document Outline Window
Web Services Tutorial Updated 04/07/2003 Document Outline Window HTML Outline Hierarchical view of HTML code Select items to find location in HTML Delete items easily Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

15 Document Outline Window
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

16 Client Side Script Project Properties JavaScript or VBScript
Web Services Tutorial Updated 04/07/2003 Client Side Script Project Properties JavaScript or VBScript Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

17 .ASPX Syntax A simple page is just static text & HTML
Web Services Tutorial Updated 04/07/2003 .ASPX Syntax A simple page is just static text & HTML Any HTML page can be renamed .ASPX Pages may also contain: Directives: directive %> Server controls: <tag runat=server> Code blocks: <script runat=server> Data bind expressions: <%# expression %> Server side comments: <%-- --%> Render code: <%= %> and <% %> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

18 Page Script <script language="C#" runat="server">
Web Services Tutorial Updated 04/07/2003 Page Script <script language="C#" runat="server"> void Page_Load() { // add items to the listbox lst.Items.Add(" lst.Items.Add(" } </script> <form id="PageScript" method="post" runat="server"> <SELECT id="lst" style="Z-INDEX: 101; LEFT: 37px; WIDTH: 416px; POSITION: absolute; TOP: 60px; HEIGHT: 164px" size="10" runat="server" name="lst"> <OPTION>Item1</OPTION> <OPTION>Item2</OPTION> </SELECT> </form> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

19 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 Copyright Michele Leroux Bustamante. All rights reserved.

20 Page Events Page Events Page_Init – Fired when page is initialized
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

21 Page Load Event Load event is fired on every request
Web Services Tutorial Updated 04/07/2003 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” } Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

22 Web Services Tutorial Updated 04/07/2003 Run As Server Control HTML controls must be run as server controls for events to be handled in Codebehind module Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

23 Codebehind - runat=“server”
Web Services Tutorial Updated 04/07/2003 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: <input id=“txtFirstName” type=“text” runat=“server”> string strFirstName; strFirstName = txtFirstName.Text; Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

24 Events ASP.NET Control Events HTML View Codebehind
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 Copyright Michele Leroux Bustamante. All rights reserved.

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

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

27 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 <form id=“form1” method=“post” runat=“server> <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:Button id=“Button1" runat="server"></asp:Button> </form> Copyright Michele Leroux Bustamante. All rights reserved.

28 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 Copyright Michele Leroux Bustamante. All rights reserved.

29 HttpRequest Object Page.Request property Use it to access:
Web Services Tutorial Updated 04/07/2003 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! Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

30 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 Copyright Michele Leroux Bustamante. All rights reserved.

31 ASP.NET Application Files
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

32 ASP.NET Application Files
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

33 Global.asax Inherits HttpApplication
Web Services Tutorial Updated 04/07/2003 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 <script> tags Object creation <object> tags Application Codebehind="Global.asax.vb" Inherits="ViewState.Global" %> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

34 Application.BeginRequest Application.EndRequest
Web Services Tutorial Updated 04/07/2003 Global.asax Can handle application and HttpModule events For example, SessionStateModule Application.Start Session.Start Application.BeginRequest Application.EndRequest Session.End Application.End Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

36 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 *.aspx Page Object Codebehind Copyright Michele Leroux Bustamante. All rights reserved.

37 *.ASPX Files Defaults to Codebehind Can modify @ Page directive
Web Services Tutorial Updated 04/07/2003 *.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) Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

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

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

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

42 Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

43 Control Events Posted form parameters indicate:
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

45 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&TextBox1=goodbye&Button1=Select&DropDownList1=Item+4&ListBox1=Item+3 Copyright Michele Leroux Bustamante. All rights reserved.

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

47 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; Copyright Michele Leroux Bustamante. All rights reserved.

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

49 HTML Output ASP.NET generates HTML output Hidden <input>
Web Services Tutorial Updated 04/07/2003 HTML Output ASP.NET generates HTML output Automatic management of browser output Hidden <input> __VIEWSTATE field stores persisted page and control data between round trips <body MS_POSITIONING="FlowLayout"> <form name="Form1" method="post" action="WebForm1.aspx" id="Form1"> <input type="hidden" name="__VIEWSTATE" value="dDwxNDI1MDc1NTU1Ozs+BikBQY0EO1e4Kf6Hy4QBNSYWNZM=" /> .... Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

50 HTML Output Client Script
Web Services Tutorial Updated 04/07/2003 HTML Output Client Script Emitted with HTML output as client-side script block ASP.NET validation controls emit client script <body MS_POSITIONING="FlowLayout"> <form name="Form1" method="post" action="WebForm1.aspx" language="javascript" onsubmit="ValidatorOnSubmit();" id="Form1"> <input type="hidden" name="__VIEWSTATE" value="dDwxNDI1MDc1NTU1Ozs+BikBQY0EO1e4Kf6Hy4QBNSYWNZM=" /> <script language="javascript" src="/aspnet_client/system_web/1_0_3705_288/WebUIValidation.js"></script> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

52 HTML vs. Server Controls
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

53 HTML vs. Server Controls
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

54 WebControls Namespace
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

55 Web Server Controls Some Shared Properties:
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

56 Button Can be a submit button or command button
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

57 ImageButton, Image ImageButton is similar to Button
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

58 Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

59 TextBox TextMode Property TextChanged Event
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

60 List Controls Similar to Windows Forms controls
Web Services Tutorial Updated 04/07/2003 List Controls Similar to Windows Forms controls Support Data Binding (covered later) Base Class WebControls.ListControl DropDownList ListBox CheckBoxList RadioButtonList Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

61 Validation Controls Validation controls inherit BaseValidator
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

62 Web Services Tutorial Updated 04/07/2003 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) Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

63 Validation Controls Text appears if validation fails
Web Services Tutorial Updated 04/07/2003 Validation Controls Text appears if validation fails Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

64 Validation Controls RequiredFieldValidator RangeValidator
Web Services Tutorial Updated 04/07/2003 Validation Controls RequiredFieldValidator RangeValidator RegularExpressionValidator CustomValidator CompareValidator ValidationSummary Can create custom validation controls Inherit BaseValidator Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

65 Common Properties ControlToValidate – which input control to validate
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

67 RangeValidator Specify a data type to compare
Web Services Tutorial Updated 04/07/2003 RangeValidator Specify a data type to compare Specify a maximum and minimum Validation succeeds if input data is empty Use RequiredFieldValidator to enforce value Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

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

70 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 Copyright Michele Leroux Bustamante. All rights reserved.

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

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

73 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 Copyright Michele Leroux Bustamante. All rights reserved.

74 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) Copyright Michele Leroux Bustamante. All rights reserved.

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

76 State Management Application State Session State View State
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

77 HttpApplicationState
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

79 Application StaticObjects
Web Services Tutorial Updated 04/07/2003 Application StaticObjects Generate object with scope via global.asax Instantiated when application is started Access via Application.StaticObjects Use Lock(), UnLock() to protect state Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

80 Application StaticObjects
Web Services Tutorial Updated 04/07/2003 Application StaticObjects // in global.asax <object id=“appobj" scope="application" class="StateManagement.UrlInfo" runat="server"/> // setting value when application is loaded Application.Lock(); UrlInfo obj = (UrlInfo)Application.StaticObjects[“appobj"]; obj.Url=" obj.Title="IDesign Associates"; Application.UnLock(); Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

81 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 Copyright Michele Leroux Bustamante. All rights reserved.

82 HttpSessionState Exposed through intrinsic Session object
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

84 Session StaticObjects
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

85 Session StaticObjects
// in global.asax <object id=“sessionobj" scope="application" class="StateManagement.UrlInfo" runat="server"/> // setting value when application is loaded UrlInfo obj = (UrlInfo)Application.Session.StaticObjects[“sessionobj"]; obj.Url=" obj.Title="IDesign Associates"; Copyright Michele Leroux Bustamante. All rights reserved.

86 Session Configuration
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

87 Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

88 ViewState EnableViewState=true EnableViewState=false
Web Services Tutorial Updated 04/07/2003 ViewState EnableViewState=true EnableViewState=false Page EnableViewState=“True” … %> <input type="hidden" name="__VIEWSTATE" value="dDwyMTIzNzU4NjczO3Q8O2w8aTwxPjs+O2w8dDw7bDxpPDM+Oz47bDx0PHQ8O3A8bDxpPDA+O2k8MT47aTwyPjs+O2w8cDxDb2xvciBbQWxpY2VCbHVlXTtDb2xvciBbQWxpY2VCbHVlXT47cDxDb2xvciBbQXF1YV07Q29sb3IgW0FxdWFdPjtwPENvbG9yIFtBcXVhbWFyaW5lXTtDb2xvciBbQXF1YW1hcmluZV0+Oz4+Oz47Oz47Pj47Pj47PkZfIFK00pyBR1IaAbVIeLcMIvyz" /> Page EnableViewState=“False” … %> <input type="hidden" name="__VIEWSTATE" value="dDwyMTIzNzU4NjczOzs+e1hHXUI/yYEBrzVT8KuMABh8T7A=" /> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

89 Web Services Tutorial Updated 04/07/2003 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"]; Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

91 Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

92 Web Services Tutorial Updated 04/07/2003 Data Provider Objects ADO.NET Classes supporting interaction with database providers Categories of classes: Connection Command DataReader DataSet DataAdapter DataView Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

93 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 Copyright Michele Leroux Bustamante. All rights reserved.

94 Connection Object OleDbConnecton or SqlConnection
Web Services Tutorial Updated 04/07/2003 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() Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

96 Connection String Examples
Web Services Tutorial Updated 04/07/2003 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” Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

97 Command Object OleDbCommand or SqlCommand
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

98 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 Copyright Michele Leroux Bustamante. All rights reserved.

99 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(); Copyright Michele Leroux Bustamante. All rights reserved.

100 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 Copyright Michele Leroux Bustamante. All rights reserved.

101 DataReader Object OleDbDataReader or SqlDataReader
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

102 DataReader Object Iterating through a DataReader
Web Services Tutorial Updated 04/07/2003 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); } Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

103 DataReader Object Assigning a DataReader to the DataGrid.DataSource
Web Services Tutorial Updated 04/07/2003 DataReader Object Assigning a DataReader to the DataGrid.DataSource SqlDataReader reader = objSQLCommand.ExecuteReader(); dagMain.DataSource = reader; dagMain.DataBind(); Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

104 DataSet Object In-memory representation of XML or datasource
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

105 DataSet Object System.Data.DataSet ds = new System.Data.DataSet();
Web Services Tutorial Updated 04/07/2003 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 } Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

106 DataAdapter Object OleDbDataAdapter or SqlDataAdapter
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

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

109 Common Binding Properties
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

110 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(); Copyright Michele Leroux Bustamante. All rights reserved.

111 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(); Copyright Michele Leroux Bustamante. All rights reserved.

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

113 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(); Copyright Michele Leroux Bustamante. All rights reserved.

114 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(); Copyright Michele Leroux Bustamante. All rights reserved.

115 DataGrid Appearance Header and Footer Row Appearance
Web Services Tutorial Updated 04/07/2003 DataGrid Appearance Header and Footer FooterStyle, ShowFooter HeaderStyle, ShowHeader Row Appearance ItemStyle SelectedItemStyle AlternatingItemStyle Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

116 DataGrid Paging AllowPaging PageSize defaults to 10 PagerStyle
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 Copyright Michele Leroux Bustamante. All rights reserved.

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

118 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(); } Copyright Michele Leroux Bustamante. All rights reserved.

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

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

121 Web Services Tutorial Updated 04/07/2003 DataGrid Commands Can add button columns for selection, edit/update/cancel, or delete Should handle events for each button action Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

122 DataGrid Commands Web Services Tutorial Updated 04/07/2003
Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

123 DataGrid Commands Events provided for each command:
Web Services Tutorial Updated 04/07/2003 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}<br>“, cells[0].Text, cells[1].Text, cells[2].Text)); } Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

124 DataGrid Commands ItemCommand Event is invoked for all commands
Web Services Tutorial Updated 04/07/2003 DataGrid Commands ItemCommand Event is invoked for all commands Invoked prior to individual commands Can check command name using static members Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

125 Web Services Tutorial Updated 04/07/2003 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 } Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

126 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 Copyright Michele Leroux Bustamante. All rights reserved.

127 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 Copyright Michele Leroux Bustamante. All rights reserved.

128 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 Regular Item Template Alternating Item with different background color Separator Template Edit Item with TextBox in place of Labels Copyright Michele Leroux Bustamante. All rights reserved.

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

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

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

132 Binding Data Bind control to data source
Web Services Tutorial Updated 04/07/2003 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(); <FooterTemplate> Last Updated: <asp:Label id="labLastUpdated" runat="server" BackColor="Transparent"><%# DateTime.Now %></asp:Label> </FooterTemplate> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

133 Binding Data Example binding to specific fields in the data source
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

134 Binding Data <ItemTemplate><TABLE>
Web Services Tutorial Updated 04/07/2003 Binding Data <ItemTemplate><TABLE> <TR><TD><asp:Label id=labProductName runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "productName") %>'> </asp:Label><BR> <asp:Label id=labFilename runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "thumbNailImage") %>'> </asp:Label></TD> <TD align="right"> <asp:Image id=img runat="server" ImageAlign="Right" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "thumbNailImage","images/{0}") %>'> </asp:Image></TD> </TR></TABLE> </ItemTemplate> <SeparatorTemplate><HR width="100%" color="#6633ff" SIZE="1"></SeparatorTemplate> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

136 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 Copyright Michele Leroux Bustamante. All rights reserved.

137 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 Copyright Michele Leroux Bustamante. All rights reserved.

138 DataBind() Method Page.DataBind() Control.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 Copyright Michele Leroux Bustamante. All rights reserved.

139 Data Binding Expressions
Web Services Tutorial Updated 04/07/2003 Data Binding Expressions Placed between <%# … %> Used to bind control properties Used anywhere in the page <tagprefix:tagname property="<%# data-binding expression %> runat="server" /> or literal text <%# data-binding expression %> <asp:Label runat="server" Width="212px"> <%# ListBox1.SelectedItem.Text %> </asp:Label> <%# m_SomeValue %> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

140 Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

141 DataBinder.Eval Convert “Amount” field to string:
Web Services Tutorial Updated 04/07/2003 DataBinder.Eval Convert “Amount” field to string: Format “thumbNailImage” field with path: <%# DataBinder.Eval(Container.DataItem, “Amount”) %> <asp:Image id=img runat="server" ImageAlign="Right" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "thumbNailImage","images/{0}") %>'> </asp:Image></TD> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

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

143 Web User Controls Reusable Web form interface
Web Services Tutorial Updated 04/07/2003 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) Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

144 Creating Web User Controls
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

145 Using Web User Controls
Web Services Tutorial Updated 04/07/2003 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 Register TagPrefix="uc1" TagName="Login" Src="Login.ascx" %> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

146 Using Web User Controls
Web Services Tutorial Updated 04/07/2003 Using Web User Controls Adds control declaration to HTML Must be contained within <form> tag for events to work! <form id="Form1" method="post" runat="server"> <uc1:Login id="ucLogin" runat="server"></uc1:Login> </form> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

147 Web User Controls Features
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

148 Fragment Caching Web User Controls can be cached
@ OutputCache Directive Placed inside *.ascx file OutputCache Duration="30" VaryByParam="none" %> Copyright Michele Leroux Bustamante. All rights reserved.

149 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 } Copyright Michele Leroux Bustamante. All rights reserved.

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

151 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) Copyright Michele Leroux Bustamante. All rights reserved.

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

153 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 Copyright Michele Leroux Bustamante. All rights reserved.

154 Web Control Base Classes
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

155 HtmlTextWriter Render method provides access to the HtmlTextWriter
Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

156 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(); } Copyright Michele Leroux Bustamante. All rights reserved.

157 HtmlTextWriter Resulting HTML output:
<img alt=“Flower Image" src=“flower.jpg” myattribute=“custom attribute info” /> Copyright Michele Leroux Bustamante. All rights reserved.

158 Web Services Tutorial Updated 04/07/2003 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 Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

159 Render Method protected override void Render(HtmlTextWriter output) {
Web Services Tutorial Updated 04/07/2003 Render Method protected override void Render(HtmlTextWriter output) { output.AddAttribute(HtmlTextWriterAttribute.Alt, "Encoding, \"Required\"", true); output.AddAttribute(HtmlTextWriterAttribute.Src, “ , true); output.AddAttribute("myattribute", "No "encoding " required", false); output.RenderBeginTag(HtmlTextWriterTag.Img); output.RenderEndTag(); output.WriteLine(); } <img alt="Encoding, "Required"" src=" myattribute="No "encoding " required" /> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

160 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 Register TagPrefix="cc1" Namespace="OrderImage" Assembly="OrderImage" %> Copyright Michele Leroux Bustamante. All rights reserved.

161 Using Web Server Controls
Web Services Tutorial Updated 04/07/2003 Using Web Server Controls Adds control declaration to HTML <form id="Form1" method="post" runat="server"> <cc1:WebCustomControl1 id="WebCustomControl11" runat="server"></cc1:WebCustomControl1> </form> Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

162 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 Copyright Michele Leroux Bustamante. All rights reserved.

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

164 Web Services Tutorial Updated 04/07/2003 Composite Controls Create HTML literals, also added to Controls collection protected override void CreateChildControls() { this.Controls.Add(new LiteralControl("<center>")); Label label1 = new Label(); label1.Text = "Click the button below."; this.Controls.Add(label1); this.Controls.Add(new LiteralControl("</center>")); this.Controls.Add(new LiteralControl("<br>")); Button btn = new Button(); btn.Text = "Click Me"; btn.Width=new Unit("50%"); btn.Click += new EventHandler(this.OnClick); this.Controls.Add(btn); } Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.

165 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); } Copyright Michele Leroux Bustamante. All rights reserved.

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

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

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

169 References .NET Dashboard Web Services Tutorial Site
Updated 04/07/2003 References .NET Dashboard A growing list of articles and code Web Services Tutorial Site Tutorial session code samples Additional references Copyright Michele Leroux Bustamante. All rights reserved. Copyright Michele Leroux Bustamante. All rights reserved.


Download ppt "ASP.NET Tutorial Michele Leroux Bustamante"

Similar presentations


Ads by Google