Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Números.
Advertisements

PDAs Accept Context-Free Languages
1 Introduction to Web Application Implement JavaScript in HTML.
EuroCondens SGB E.
Worksheets.
Developing Web Applications
Copyright © 2003 Pearson Education, Inc. Slide 7-1 Created by Cheryl M. Hughes The Web Wizards Guide to XML by Cheryl M. Hughes.
Addition and Subtraction Equations
Unit 02. ASP.NET Introduction HTML & Server controls Postbacks Page Lifecycle.
Add Governors Discretionary (1G) Grants Chapter 6.
CALENDAR.
CHAPTER 18 The Ankle and Lower Leg
The 5S numbers game..
A Fractional Order (Proportional and Derivative) Motion Controller Design for A Class of Second-order Systems Center for Self-Organizing Intelligent.
The basics for simulations
1 IMDS Tutorial Integrated Microarray Database System.
Svetlin Nakov Telerik Corporation
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
Dynamic Access Control the file server, reimagined Presented by Mark on twitter 1 contents copyright 2013 Mark Minasi.
Copyright © [2002]. Roger L. Costello. All Rights Reserved. 1 XML Schemas Reference Manual Roger L. Costello XML Technologies Course.
Progressive Aerobic Cardiovascular Endurance Run
MaK_Full ahead loaded 1 Alarm Page Directory (F11)
Master Pages, User Controls, Site Maps, Localization Svetlin Nakov Telerik Corporation
Essentials for Design JavaScript Level One Michael Brooks
2011 WINNISQUAM COMMUNITY SURVEY YOUTH RISK BEHAVIOR GRADES 9-12 STUDENTS=1021.
Before Between After.
2011 FRANKLIN COMMUNITY SURVEY YOUTH RISK BEHAVIOR GRADES 9-12 STUDENTS=332.
1 Non Deterministic Automata. 2 Alphabet = Nondeterministic Finite Accepter (NFA)
Static Equilibrium; Elasticity and Fracture
Chapter 12 Working with Forms Principles of Web Design, 4 th Edition.
Chapter 11 Creating Framed Layouts Principles of Web Design, 4 th Edition.
1.step PMIT start + initial project data input Concept Concept.
A Data Warehouse Mining Tool Stephen Turner Chris Frala
1 Non Deterministic Automata. 2 Alphabet = Nondeterministic Finite Accepter (NFA)
Introduction Embedded Universal Tools and Online Features 2.
Schutzvermerk nach DIN 34 beachten 05/04/15 Seite 1 Training EPAM and CANopen Basic Solution: Password * * Level 1 Level 2 * Level 3 Password2 IP-Adr.
Current Popular IT I Pertemuan 3 Matakuliah: T0403/Current Popular IT I Tahun: 2008.
Asp.NET Core Server Controls. Slide 2 Lecture Overview Understanding the types of ASP.NET controls HTML controls ASP.NET (Web) controls.
Anatomy of an ASP.NET Page. Slide 2 My Version of the Big Picture (1) ASP Worker (Engine) Your application Runs Server Other applications User 1User 2.
1 Chapter 12 Working With Access 2000 on the Internet.
Web Development Using ASP.NET CA – 240 Kashif Jalal Welcome to week – 3-1 of…
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
Joe Hummel, PhD Dept of Mathematics and Computer Science Lake Forest College Lecture 8: WebForms — Web-based.
Telerik Software Academy ASP.NET Web Forms.
ASP.Net, Web Forms and Web Controls 1 Outline Introduction Simple HTTP Transaction System Architecture Creating and Running a Simple Web Form Example Web.
Introduction to.Net and ASP.Net Course Introduction Build Your Own ASP.Net Website: Chapter 1 Microsoft ASP.Net Walkthrough: Creating a Basic Web Forms.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
Architecture Of ASP.NET. What is ASP?  Server-side scripting technology.  Files containing HTML and scripting code.  Access via HTTP requests.  Scripting.
Joe Hummel, PhD Dept of Mathematics and Computer Science Lake Forest College
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
Web Programming: Client/Server Applications Server sends the web pages to the client. –built into Visual Studio for development purposes Client displays.
© Minder Chen, ASP.NET 2.0: Introduction - 1 ASP.NET 2.0 Minder Chen, Ph.D. Framework Base Class Library ADO.NET: Data & XML.
ASP.NET Controls. Slide 2 Lecture Overview Identify the types of controls supported by ASP.NET and the differences between them.
Tutorial 121 Creating a New Web Forms Page You will find that creating Web Forms is similar to creating traditional Windows applications in Visual Basic.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
Murach’s ASP.NET 4.0/VB, C1© 2006, Mike Murach & Associates, Inc.Slide 1.
Overview of Previous Lesson(s) Over View  SDI programs  The Application Wizard can generate single-document interface (SDI) applications that work.
Introducing ASP.NET 2.0. Internet Technologies WWW Architecture Web Server Client Server Request Response Network HTTP TCP/IP PC/Mac/Unix + Browser (IE,
Anatomy of an ASP.NET Page. Slide 2 Compiling an ASP.NET Page An ASP.NET page is compiled when it is rendered for the first time A page is compiled to.
Module 4: Creating a Microsoft ASP.NET Web Form. Overview Creating Web Forms Using Server Controls.
ASP.NET 4 Unleashed Chapter 1. .aspx page: contains C# script and HTML code including tags. Listing 1.1 FirstPage.aspx.
ASP.NET (Active Server Page) SNU OOPSLA Lab. October 2005.
Asp.NET Core Server Controls. Slide 2 Lecture Overview Understanding the types of ASP.NET controls HTML controls ASP.NET (Web) controls.
Overview of Previous Lesson(s) Over View  ASP is a technology that enables scripts in web pages to be executed by an Internet server.  ASP.NET is a.
Svetlin Nakov Telerik Corporation
Introduction to ASP.NET development. Background ASP released in 1996 ASP supported for a minimum 10 years from Windows 8 release ASP.Net 1.0 released.
ASP.NET Forms.
Anatomy of an ASP.NET Page
Web Development Using ASP .NET
ASP.NET Imran Rashid CTO at ManiWeber Technologies.
Presentation transcript:

Svetlin Nakov Telerik Corporation

1. Introduction to ASP.NET  ASP.NET Benefits 2. ASP.NET Architecture Overview  Separation of Presentation from Logic 3. ASP.NET Base Components  Web Forms  Web Controls 2

4. ASP.NET Execution Model  Application Life Cycle  Page Life Cycle 6. Creating ASP.NET forms 7. Code-behind 8. Directives 3

9. Controls Class Hierarchy 10. HTML Server Controls 11. Web Server Controls  Basic Web Controls  Validation Controls  List Controls  Rich Controls 12. Web Server Control Life Cycle 13. HTML Escaping 4

 Separate presentation from code  Object-oriented approach  Component-based development  Event-driven architecture  Code compilation  Extensible architecture  Built-in state management  Many others (data binding, validation, master pages, etc.) 6

 ASP.NET applications are executed via a sequence of HTTP requests and HTTP responses  Client Web browser request ASPX pages  The Web server executes the ASPX page and produce XHTML + CSS + JavaScript 8

Windows Server Internet Information Server (IIS) ISAPI Filters (aspnet_isapi.dll) ASP.NET runtime (aspnet_wp.dll / w3wp.dll) XML-basedconfiguration HttpApplication Cache HttpModules Session state Authentication … Session state Authentication … HttpHandlers ASP.NET pages ASP.NET Web services … Html Controls AJAX Web controls User controls …

 Traditional Web pages (static HTML)  Consist of static HTML, images, styles, etc.  Execute code on the client side  Simple operations  ASP.NET Web Forms  Execute code on the server side  Database access  Dynamic pages  Higher security level 10

 Traditional Web development keep HTML and programming code in one file (PHP, ASP, …)  Hard to read, understand and maintain  Hard to test and debug  ASP.NET splits the Web pages into two parts: .aspx file containing HTML for visualization  "Code behind" files (.cs for C#) containing presentation logic for particular page 11

 Class generated from the.aspx file does not derives directly from Page class  Derives from class defined in the "code behind", where it is easy to add methods, event handlers, etc.  Using "code behind" separates the presentation logic from UI visualization 12 System.Web.UI.Page TestForm.aspx.cs TestForm.aspx

 Steps to create a simple ASP.NET Web application: 1.Start Visual Studio 2.Create “New Web Site” 3.Add two text fields, a button and a label 4.Handle Button.Click and implement logic to calculate the sum of the values in the text fields 5.Display the results in the label 13

Live Demo

 Web Forms – deliver ASP.NET user interface  Web Control – the smallest part we can use in our Web application (e.g. text box)  "Code behind" – contains the server-side code  Web.config – contains ASP.NET application configuration  Machine.config – contains configuration for all applications on the ASP.NET server  Global.asax – class containing application level event handlers 16

 ASP.NET Web controls are the smallest component part  Deliver fast and easy component-oriented development process  HTML abstraction, but finally everything is HTML 17 <asp:button runat="server" ID="btn" <asp:button runat="server" ID="btn" Text="Click me!" OnClick="btn_Click" /> Text="Click me!" OnClick="btn_Click" /></form>

 Main settings and configuration file for ASP.NET  Text based XML document  Defines:  Connection strings to any DB used by app  The default language for child pages  Whether debugging is allowed 18 <configuration> </configuration> Minimal Web.config should look like this

 Text based XML document  Contains settings that apply to an entire computer 19

 Also known as ASP.NET application file  Located in the Web application root folder  Exposes application and session level events  Application_Start  Application_End  Session_Start  Session_End  … 20

Live Demo

 First call to particular page 23

 Any other call after the first 24

1. IIS receives the HTTP request 2. IIS using ISAPI sends the request to aspnet_wp.exe 3. ASP.NET receives request for the first time 4. Basic ASP.NET objects are created for every request (e.g. Request, Response, etc.) 5. Request is associated with the HttpApplication object 6. HttpApplication process the request 25

 PreInit  Init  InitComplete  PreLoad  Load  LoadComplete  PreRender  PreRenderComplete  SaveStateComplete  Unload 26

 PreInit  Create or recreate controls, set the master page or theme  Init  InitComplete  PreLoad  Load  LoadComplete  PreRender  PreRenderComplete  SaveStateComplete  Unload 27

 PreInit  Init  All controls are initialized  Use it to set some control properties  InitComplete  PreLoad  Load  LoadComplete  PreRender  PreRenderComplete  SaveStateComplete  Unload 28

 PreInit  Init  InitComplete  Use it when you need all the control initialization done  PreLoad  Load  LoadComplete  PreRender  PreRenderComplete  SaveStateComplete  Unload 29

 PreInit  Init  InitComplete  PreLoad  Some processing before Load event  After this the Page object loads the view-state  Load  LoadComplete  PreRender  PreRenderComplete  SaveStateComplete  Unload 30

 PreInit  Init  InitComplete  PreLoad  Load  Here we do common processing (e.g. bind controls)  LoadComplete  PreRender  PreRenderComplete  SaveStateComplete  Unload 31

 PreInit  Init  InitComplete  PreLoad  Load  LoadComplete  PreRender  Executed after data binding  Make some final changes over controls  PreRenderComplete  SaveStateComplete  Unload 32

 PreInit  Init  InitComplete  PreLoad  Load  LoadComplete  PreRender  PreRenderComplete  Happens right before the page content is rendered  SaveStateComplete  Unload 33

 PreInit  Init  InitComplete  PreLoad  Load  LoadComplete  PreRender  PreRenderComplete  SaveStateComplete  Any changes over the page content are ignored  Unload 34

 PreInit  Init  InitComplete  PreLoad  Load  LoadComplete  PreRender  PreRenderComplete  SaveStateComplete  Unload  Page is unloaded from memory 35

Live Demo

 ASP.NET Web Form is a programmable Web page (.aspx file)  Acts as a user interface (UI) of an ASP.NET application  Consists of HTML, code and controls which are executed on a web server  The user sees the result in the form of HTML generated by the web server  The code and controls which describe the web form don’t leave the server 38

 The functionality of the Web form is defined by using three layers of attributes 39 Page Language="c#" Codebehind="TestWebForm.aspx.cs" Codebehind="TestWebForm.aspx.cs" Inherits="MyFirstWebApplication.WebForm"%> Inherits="MyFirstWebApplication.WebForm"%><html> My First WebForm My First WebForm </body></html>

 Page attributes define global functionality 40 Page Language="c#" Codebehind="TestWebForm.aspx.cs" Codebehind="TestWebForm.aspx.cs" Inherits="MyFirstWebApplication.WebForm"%> Inherits="MyFirstWebApplication.WebForm"%><html> My First WebForm My First WebForm </body></html>

 body tags define the appearance of a web page  MS_POSITIONING : FlowLayout, GridLayout 41 Page Language="c#" Codebehind="TestWebForm.aspx.cs" Codebehind="TestWebForm.aspx.cs" Inherits="MyFirstWebApplication.WebForm"%> Inherits="MyFirstWebApplication.WebForm"%><html> My First WebForm My First WebForm </body></html>

 form attributes define how the groups of controls are going to be processed 42 Page Language="c#" Codebehind="TestWebForm.aspx.cs" Codebehind="TestWebForm.aspx.cs" Inherits="MyFirstWebApplication.WebForm"%> Inherits="MyFirstWebApplication.WebForm"%><html> My First WebForm My First WebForm </body></html>

 Defines how the controls are going to be processed  In a Web form there can be several tags  Only one server-side tag 43 HTML version … … <form>…</form><form>…</form> ASP.NET version (only 1) … … <form>…</form><form>…</form>

 id – form identifier  method - specifies the method of sending information back to the server  GET – in the URL  POST – within the body of the HTTP request  runat - tells the parser that the tag is not an HTML element but an ASP.NET server control 44

45 <html><head> WebFormTest WebFormTest <meta name="GENERATOR" Content= <meta name="GENERATOR" Content= "Microsoft Visual Studio 7.0"> "Microsoft Visual Studio 7.0"> <meta name="vs_targetSchema" content= <meta name="vs_targetSchema" content= " " HTML and controls go here HTML and controls go here </body></html>

Live Demo

 Writing code in an ASP.NET Web form is done in three ways:  Mixed code method  The code is in the same file as the web content, mixed with the HTML code  This method is not recommended as the source code is hard to read and maintain  Inline code method  Code-behind method 48

 Writing code in an ASP.NET web form is done in three ways:  Mixed code method  Inline code method  The code is separated in a SCRIPT section in the same file  Code-behind method 49

 Writing code in an ASP.NET web form is done in three ways:  Mixed code method  Inline code method  Code-behind method  The code is in the code-behind page – a separate file from the HTML content  When using Visual Studio.NET this is the default method 50

51 </html> private void btn_Click(object sender, private void btn_Click(object sender, System.EventArgs e) System.EventArgs e) { }</script>

 A separate compiled file containing the program logic of the page  Each web page has its own code-behind page  Has the same name as the web page to which it is attached  The file extension is.aspx.cs  The two files are built into one when the application is started 53

 To associate an.aspx page to its code-behind class directive is used  VS.NET adds three attributes to directive:  Inherits – allows the.aspx page to derive from the code-behind class  Codebehind – used internally by Visual Studio.NET to associate the files  Src – contains the name of the code-behind page  Used if the application is not precompiled 54

55 Page Language="c#" Inherits="MyProject.WebFormTest"Codebehind="WebFormTest.aspx.cs" Src="WebFormTest.aspx.cs" %>

 The Code-behind page can be either precompiled or just-in-time (JIT) Compiled  JIT compilation  A compilation at first request  Set by the Src attribute of directive  VS.NET doesn’t add it by default 56

 Precompilation  Avoids the delay at first request  Simplifies the deployment of the web application  The source code of the code-behind class is not necessary 57

 Provide control over many options affecting the compilation and execution of the web form  Important directives: – main directive of the page – imports a namespace into the – attaches an assembly to the form when it is compiled – controls the ability of the forms to use cache – registers a user control to be used in a web form 59

 Defines a form specific (.aspx file) attributes used by the parser and the compiler of ASP.NET  Important attributes:  AutoEventWireup  Culture – a culture used when the page is generated  UICulture – a culture used for the visualization of data 60

 Important attributes:  Debug – whether the page is compiled with debug symbols in it  EnableSessionState – whether a session is supported  EnableViewState – whether to use "view state“ or not  ErrorPage – a page to which to redirect in case of unhandled exception 61

 Important attributes:  Language – states the program language used to script the page  Codebehind – points to the code-behind file where the page logics is stored  Smart-Navigation – improves user experience over post backs  Persists element focus and scroll position  Avoids flickers  Supported by IE 5.5 or later  Shouldn’t use it - problematic 62

Live Demo

 ASP.NET server controls  The smallest ASP.NET Component  Wrap an HTML UI element, or more complex UI  Component-oriented programming model  Executed and rendered at the server side  Example of ASP.NET server controls:       … 64

 Mandatory properties for all server controls:  runat="server"  ID="…"  Programming model based on events  Each user interaction causes and event  Programmer decides which events to handle  Browser-specific HTML is generated  Controls deliver appropriate HTML depending on browser type 65

 System.Web.UI.Control  Base for all controls  Properties – ID, Page, ViewState, Context, ClientID, Controls  Methods – Render(HtmlTextWriter writer) 67

 System.Web.UI.HtmlControls.HtmlControl 68

 System.Web.UI.WebControls.WebControl  System.Web.UI.TemplateControl 69

 HTML server controls are very simple extension of Control class  Look like traditional HTML  Defined by runat ="server"  Simple HTML seems like text on the server  If an HTML element is converted to HTML server control, a server side object is associated with it  Valid only inside a Web form tag: 71 … …

72 void ButtonSubmit_Click(Object sender, EventArgs e){ void ButtonSubmit_Click(Object sender, EventArgs e){ Response.Write("Value: "+TextField.Value+" "); Response.Write("Value: "+TextField.Value+" "); }</script><html><head> HTML Server Controls HTML Server Controls </head><body> <input id="ButtonSubmit" runat="server" value="Submit" <input id="ButtonSubmit" runat="server" value="Submit" onserverclick="ButtonSubmit_Click" type="button"/> onserverclick="ButtonSubmit_Click" type="button"/> </body></html>

Live Demo

 HtmlForm – …  HtmlForm – …  HtmlInputText –  HtmlInputText –  HtmlButton –  HtmlButton –  HtmlAnchor – …  HtmlAnchor – …  HtmlSelect –  HtmlSelect –  HtmlTable, HtmlTableCell, HtmlTableRow – …  HtmlTable, HtmlTableCell, HtmlTableRow – …  HtmlImage –  HtmlImage – ... 74

 HtmlGenericControl  Used for all other HTML elements    … 75

76 void Page_Load(Object sender, EventArgs e) { void Page_Load(Object sender, EventArgs e) { this.MetaInfo.Attributes["name"] = "description"; this.MetaInfo.Attributes["name"] = "description"; this.MetaInfo.Attributes["content"] = "The page was this.MetaInfo.Attributes["content"] = "The page was generated on: " + DateTime.Now.ToString(); generated on: " + DateTime.Now.ToString();}</script><html><head> </head><body> … … </body></html>

Live Demo

 Web server controls are server UI controls that abstract the common HTML elements  Have own lifecycle and functionality  Come with.NET Framework  Located in System.Web.UI.WebControls namespace, inherit from the WebControl class  HTML Abstraction  Rendered HTML tags are quite different from the design-time markup 79

 Rich functionality  Type-safe programming capabilities  Automatic Web browser detection  AutoPostBack  Sumbit when the focus is lost  Support for themes 80

81 tag_prefix determines unique namespace for the web control The name of the control Attributes are properties of the Web control Mandatory attribute runat="server"

82 <asp:Label ID="LabelResult" runat="server" <asp:Label ID="LabelResult" runat="server" Text="" Visible="false" /> Text="" Visible="false" /> <asp:Button ID="ButtonSubmit" runat="server" <asp:Button ID="ButtonSubmit" runat="server" Text="Submit" OnClick="ButtonSubmit_Click" /> Text="Submit" OnClick="ButtonSubmit_Click" /></form>… protected void ButtonSubmit_Click( object sender, EventArgs e) object sender, EventArgs e){ this.LabelResult.Text = this.LabelResult.Text = "You entered: " + this.TextBoxInput.Text; "You entered: " + this.TextBoxInput.Text; this.LabelResult.Visible = true; this.LabelResult.Visible = true;}

Live Demo

 The WebControl class defines properties, events and methods for all Web controls  Control the appearance  BackColor  ForeColor  BorderWidth  BorderStyle  BorderColor 84

 Control the behavior  Enabled  Visible  TabIndex  ToolTip  …  Not all controls support all these properties  See the documentation for details 85

Basic Web Controls

<asp:button> <asp:checkbox> <asp:hyperlink> <asp:image> <asp:imagebutton> <asp:linkButton> <asp:label><span>…</span> <asp:listbox> <asp:panel><div>…</div> <asp:radiobutton> <asp:table><table>…</table> <asp:textbox>

 Creates single-line or multiline text-box  Lets the user to enter text  Properties  Text  TextMode  SingleLine, MultiLine, Password  MaxLength  ReadOnly  AutoPostBack  Events  TextChanged – combined with AutoPostBack 88

 Display static text in a block  Allows programmatically to manipulate it  Properties  Text  AssociatedControlID – on click focus goes to the specified control  Events  TextChanged – combined with AutoPostBack 89 CAUTION: the Text is NOT HTML encoded before it is displayed in the Label control. This make it possible to embed script within HTML tags in the text.

 Display static text  Allows programmatically to manipulate it  Unlike the Label control, Literal does not let you apply styles to its content  Properties  Text  Renders the Text property value directly 90 CAUTION: the Text is NOT HTML encoded before it is displayed in the Literal control. This make it possible to embed script within HTML tags in the text.

 Implement IButtonControl  Properties  Text – button's title  CommandName – pass a command  CommandArgument – pass command arguments  PostBackUrl – posts back to specified page  CausesValidation – perform validation or not  ValidationGroup – which validation group to be validated 91

 Events  Click  Command  CommandName and CommandArgument are passed to code behind 92

 Different button types  Button  Creates a push button  Submit button by default  Different button types  ImageButton  Display an image that responds on mouse click  ImageURL – URL to displayed image  Both Click and Command events are raised 93

 Different button types  Command Button  Has command name associated ( CommandName property)  Programmatically determine which button is clicked in Command event handles  Used in templated controls, e.g. GridView 94

 Different button types  LinkButton  Same functionality as Button  Renders as hyperlink  Use Hyperlink if you want to link to another page  Renders JavaScript on the client browser 95

96 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" Transitional//EN" " " Untitled Page Untitled Page </head><body> <asp:Button ID="ButtonEx" <asp:Button ID="ButtonEx" CommandName="ButtonEx" CommandName="ButtonEx" runat="server" runat="server" OnClick="OnBtnClick" OnClick="OnBtnClick" OnCommand="OnCommand" OnCommand="OnCommand" Text="Normal Button"/> Text="Normal Button"/>

97 <asp:LinkButton ID="LinkButtonEx" <asp:LinkButton ID="LinkButtonEx" runat="server" runat="server" OnClick="OnBtnClick" OnClick="OnBtnClick" Text="Link Button" Text="Link Button" CommandName="LinkButtonEx" CommandName="LinkButtonEx" OnCommand="OnCommand"/> OnCommand="OnCommand"/> <asp:ImageButton ID="ImageButtonEx" <asp:ImageButton ID="ImageButtonEx" runat="server" runat="server" CommandName="ImageButtonEx" CommandName="ImageButtonEx" ImageUrl="~/images/DotNet_Logo_Small.gif" ImageUrl="~/images/DotNet_Logo_Small.gif" OnCommand="OnCommand" OnCommand="OnCommand" OnClick="OnBtnClick"/> OnClick="OnBtnClick"/> <asp:Label ID="LabelMessage" runat="server" <asp:Label ID="LabelMessage" runat="server" Text=""/> Text=""/> </body></html>

98 Live Demo

 The Panel control  Container for other controls  Rendered as  Rendered as  Useful for:  Displaying and hiding groups of controls  Generating and inserting controls at runtime 99

 Properties  ScrollBars  Modify visibility and position of scroll bars  Wrap  Value indicating whether the content wraps within the panel  GroupingText  Caption for the group of controls that is contained in panel control  DefaultButton  Button to be pressed by default (Enter) 100

Live Demo

 The PlaceHolder control  Reserves a space in the page control hierarchy  Used to add controls to the page at runtime  Does not produce any visible output  Controls  Use it to add, insert or remove controls from PlaceHolder Control 102

 Select between checked / unchecked  Properties  Checked  Text  Control caption  AutoPostBack  Automatically posts back the page when control state is changed 103

 CausesValidation  Whether validation is performed  ValidationGroup  Which validation group to be validated  Events  CheckChanged 104

 Creates a radio button on the Web Forms page  Properties  Text  GroupName  Allow a mutually exclusive selection from the group 105

Performing Control Validation

 The ASP.NET Web forms validation controls  Validate the values that are entered into other controls of the page  Two modes of validation  Client-side validation  Server-side validation  Validation is performed at page submit 107

 Most important validation controls:  RequiredFieldValidator  RangeValidator  CompareValidator  RegularExpressionValidator  CustomValidator  ValidationSummary 108

Live Demo

Displaying Lists of Items

 List Web controls  Display list of items, e.g. table of rows  Support binding to a collection  Display rows of data in templated format  Expose DataSourceID, DataSource, DataMember properties  Bind to collection that support IEnumerable, ICollection or IListSource 111

 ListBox  CheckBoxList  RadioButtonList  Repeater  DataList  GridView  DropDownList 112

Live Demo

Rich Controls

 Task-specific controls  Built with multiple HTML elements  Rich functionality  Examples:  Calendar  AdRotator 115

 Init  ViewState  Load  Send Postback Change Notification  Handle Postback events  PreRender  Save State  Render  Dispose  Unload 117

 Control initialize settings needed during incoming web request  Init event ( OnInit method) 118

 At the end of this phase ViewState property is automatically populated  Override LoadViewState method to customize state restoration  LoadViewState method 119

 Perform actions common to all requests  Server controls in the tree are created and initialized  Control state from previous round trip is restored including client – side data  Load event ( OnLoad method) 120

 Raise change events in response to state changes between previous and current postbacks  RaisePostDataChangedEvent method  IPostBackDataHandler should be implemented 121

 Handle client-side events caused postback  Raise appropriate events on the server  RaisePostBackEvent method  IPostBackEventHandler should be implemented 122

 Perform any updates before the control is rendered  Changes made in this phase can be saved  PreRender event ( OnPreRender method) 123

 ViewState property is persisted  Send to the client and back as a hidden field  SaveViewState method 124

 Generates the output which will be send to the client  Any changes to controls state made here are lost  Render() method 125

 Final clean up  Expensive resources should be released  Dispose() method 126

 Final clean up  Usually clean up is performed in previous phase so this event is not handled  UnLoad event ( OnUnLoad() method) 127

Live Demo

 HTML escaping is the act of replacing special characters with their HTML entities  Escaped characters are interpreted as character data instead of mark up  Typical characters to escape  – start / end of HTML tag  & – start of character entity reference  ', " – text in single / double quotes  … 130

 Each character could be presented as HTML entity escaping sequence  Numeric character references:  ' λ ' is λ, &#x03BB ; or &#X03bb ;  Named HTML entities:  ' λ ' is λ  ' < ' is <  ' > ' is >  ' & ' is &  " (double quote) is " 131

 Cross-site scripting (XSS) is a common security vulnerability in Web applications  Web application is let to display a JavaScript code that is executed at the client's browser  Crackers could take control over sessions, cookies, passwords, and other private data  How to prevent from XSS?  ALWAYS validate the user input  Perform HTML escaping when displaying text data in a Web control 132

 ValidateRequest attribute of Page directive  Checks all input data against a hard-coded list of potentially dangerous values  The default is true  Using it could harm the normal work on some applications  E.g. a user posts JavaScript code in a forum  Escaping is better way to handle the problem! 133

 HttpServerUtility.HtmlEncode  HTML encodes a string and returns the encoded string  Page.Server is instance of HttpServerUtility The following script The following scriptOutput: Web browser renders the following: 134 <%response.write(Server.HTMLEncode( "The image tag: "))%> "The image tag: "))%> The image tag: <img> The image tag: The image tag:

Live Demo

Questions?

1. Start Visual Studio 2010 and make new Web Site. Look at the files generated and tell what's purpose of each file. Explain "code – behind" model. Print "Hell ASP.NET" from code – behind and from UI. Show automatic generated files in executing directory using Assembly.GetExecutingPath(). 2. Create a Web page which saves empty file in ProgramFiles directory. Configure directory security so IIS process to be able to write in there. 3. Catch all the events in page lifecycle using appropriate method or event handler. 137

4. Do some kind of tracing of these events. 5. Create an HTML form that posts the contents of a textarea field to a server and the server prints it in another field. Don’t use code-behind. 6. Create an ASP.NET web form which posts the contents of a textarea field to a server and the server prints it in another field. 7. Use the src attribute of directive to create a page that doesn’t need to be precompiled. 138

1. Using the HTML server controls create a random number generator Web application. It should have two input fields defining a range (e.g. [10..20]) and a button to generate a random number in the range. 2. Re-implement the same using Web server controls. 3. Define a Web form with text box and button. On button click show the entered in the first textbox text in other textbox control and label control. Enter some potentially dangerous text. Fix issues related to HTML escaping – the application should accept HTML tags and display them correctly. 139

4. Make a simple Web form for registration of students and courses. The form should accept first name, last name, faculty number, university (drop-down list), specialty (drop-down list) and a list of courses (multi- select list). Use the appropriate Web server controls. After registration you should display summary of the entered information as formatted HTML. use dynamically generated tags (,, …). 5. Implement the "Tic-tac-toe" game using Web server controls. The user should play against the computer which should implement some kind of intelligence. 140

6. Make a simple Web Calculator. The calculator should support the operations like addition, subtraction, m 6. Make a simple Web Calculator. The calculator should support the operations like addition, subtraction, multiplication, division, square root and module. Also the calculator should be able to work with decimal numbers. Validation is essential! 141