8.ASP.net Basics

download 8.ASP.net Basics

of 141

Transcript of 8.ASP.net Basics

  • 8/12/2019 8.ASP.net Basics

    1/141

    ASP.NET Architecture,ASP.NET Web Controls and

    HTML Controls

    Svetlin NakovTelerik Corporation

    www.telerik.com

    http://www.telerik.com/http://www.telerik.com/
  • 8/12/2019 8.ASP.net Basics

    2/141

    Table of Contents

    1. Introduction to ASP.NETASP.NET Benefits

    2. ASP.NET Architecture Overview

    Separation of Presentation from Logic3. ASP.NET Base Components

    Web Forms

    Web Controls

    2

  • 8/12/2019 8.ASP.net Basics

    3/141

    Table of Contents (2)

    4. ASP.NET Execution ModelApplication Life Cycle

    Page Life Cycle

    6. Creating ASP.NET forms7. Code-behind

    8. Directives

    3

  • 8/12/2019 8.ASP.net Basics

    4/141

    Table of Contents

    9. Controls Class Hierarchy

    10. HTML Server Controls

    11. Web Server Controls

    Basic Web ControlsValidation Controls

    List Controls

    Rich Controls

    12. Web Server Control Life Cycle

    13. HTML Escaping 4

  • 8/12/2019 8.ASP.net Basics

    5/141

    Introduction to ASP.NET

  • 8/12/2019 8.ASP.net Basics

    6/141

    ASP.NET BenefitsSeparate presentation from code

    Object-oriented approach

    Component-based development

    Event-driven architectureCode compilation

    Extensible architecture

    Built-in state management

    Many others (data binding, validation, masterpages, etc.)

    6

  • 8/12/2019 8.ASP.net Basics

    7/141

    ASP.NET Overview

  • 8/12/2019 8.ASP.net Basics

    8/141

    ASP.NET Execution

    ASP.NET applications are executed via a sequenceof HTTP requests and HTTP responses

    Client Web browser request ASPX pages

    The Web server executes the ASPX page andproduce XHTML + CSS + JavaScript

    8

  • 8/12/2019 8.ASP.net Basics

    9/141

    ASP.NET Architecture

    Windows Server

    Internet Information Server (IIS) ISAPI Filters (aspnet_isapi.dll)

    ASP.NET runtime (aspnet_wp.dll / w3wp.dll)

    XML-based

    configuration

    HttpApplication Cache

    HttpModules

    Session state Authentication

    HttpHandlers

    ASP.NET pages ASP.NET Web services

    Html Controls AJAX

    Web controls User controls

  • 8/12/2019 8.ASP.net Basics

    10/141

    ASP.NET: How it Works?Traditional Web pages (static HTML)

    Consist of static HTML, images, styles, etc.

    Execute code on the client side

    Simple operationsASP.NET Web Forms

    Execute code on the server side

    Database access

    Dynamic pages

    Higher security level10

  • 8/12/2019 8.ASP.net Basics

    11/141

    Separate Visualizationfrom Business Logic

    Traditional Web development keep HTML andprogramming code in one file (PHP, ASP, ) Hard to read, understand and maintain

    Hard to test and debugASP.NET splits the Web pages into two parts:

    .aspx file containing HTML for visualization

    "Code behind " files (.cs for C#) containingpresentation logic for particular page

    11

  • 8/12/2019 8.ASP.net Basics

    12/141

    Separate Visualizationfrom Business Logic (2)

    Class generated from the.aspx file does not derivesdirectly from Page class

    Derives from class definedin the "code behind", whereit 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

  • 8/12/2019 8.ASP.net Basics

    13/141

    Your First ASP.NETApplication Sumator

    Steps to create a simple ASP.NET Webapplication:

    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 logicto calculate the sum of the values in thetext fields

    5. Display the results in the label13

  • 8/12/2019 8.ASP.net Basics

    14/141

    ASP.NET SumatorLive Demo

  • 8/12/2019 8.ASP.net Basics

    15/141

    ASP.NET Base Components

  • 8/12/2019 8.ASP.net Basics

    16/141

    ASP.NET Base ComponentsWeb Forms deliver ASP.NET user interface

    Web Control the smallest part we can use inour Web application (e.g. text box)

    "Code behind " contains the server-side code

    Web.config contains ASP.NET applicationconfiguration

    Machine.config contains configuration forall applications on the ASP.NET server

    Global.asax class containing application

    level event handlers 16

  • 8/12/2019 8.ASP.net Basics

    17/141

    ASP.NET Web Controls

    ASP.NET Web controls are the smallestcomponent part

    Deliver fast and easy component-orienteddevelopment process

    HTML abstraction, but finally everything isHTML

    17

  • 8/12/2019 8.ASP.net Basics

    18/141

    Web.configMain settings and configuration file for

    ASP.NETText based XML documentDefines:

    Connection strings to any DB used by appThe default language for child pagesWhether debugging is allowed

    18

    Minimal Web.config should look like this

  • 8/12/2019 8.ASP.net Basics

    19/141

    Machine.config

    Text based XML documentContains settings that apply to an entirecomputer

    19

  • 8/12/2019 8.ASP.net Basics

    20/141

    Global.asax

    Also known as ASP.NET application file

    Located in the Web application root folder

    Exposes application and session level events

    Application_StartApplication_End

    Session_Start

    Session_End

    20

  • 8/12/2019 8.ASP.net Basics

    21/141

    Look Inside Web.config,Machine.config, Global.asax

    Live Demo

  • 8/12/2019 8.ASP.net Basics

    22/141

    ASP.NET Execution Model

  • 8/12/2019 8.ASP.net Basics

    23/141

    ASP.NET Execution ModelFirst call to particular page

    23

  • 8/12/2019 8.ASP.net Basics

    24/141

    ASP.NET Execution Model (2)Any other call after the first

    24

  • 8/12/2019 8.ASP.net Basics

    25/141

    ASP.NET Application Lifecycle

    1. IIS receives the HTTP request

    2. IIS using ISAPI sends the request toaspnet_wp.exe

    3. ASP.NET receives request for the first time4. Basic ASP.NET objects are created for every

    request (e.g. Request , Response , etc.)

    5. Request is associated with theHttpApplication object

    6. HttpApplication process the request25

  • 8/12/2019 8.ASP.net Basics

    26/141

    ASP.NET Lifecycle EventsPreInit

    InitInitCompletePreLoad

    LoadLoadCompletePreRenderPreRenderCompleteSaveStateComplete

    Unload 26

  • 8/12/2019 8.ASP.net Basics

    27/141

    ASP.NET Lifecycle Events (2)PreInit

    Create or recreate controls, set the master page or theme

    InitInitComplete

    PreLoadLoadLoadComplete

    PreRenderPreRenderCompleteSaveStateComplete

    Unload 27

  • 8/12/2019 8.ASP.net Basics

    28/141

    ASP.NET Lifecycle Events (3)PreInit

    InitAll controls are initializedUse it to set some control properties

    InitCompletePreLoadLoadLoadCompletePreRenderPreRenderCompleteSaveStateComplete

    Unload 28

  • 8/12/2019 8.ASP.net Basics

    29/141

    ASP.NET Lifecycle Events (4)PreInitInitInitComplete

    Use it when you need all the control initialization done

    PreLoadLoadLoadComplete

    PreRenderPreRenderCompleteSaveStateComplete

    Unload 29

  • 8/12/2019 8.ASP.net Basics

    30/141

    ASP.NET Lifecycle Events (5)PreInit

    InitInitCompletePreLoad

    Some processing before Load eventAfter this the Page object loads the view-state

    LoadLoadCompletePreRenderPreRenderCompleteSaveStateComplete

    Unload 30

  • 8/12/2019 8.ASP.net Basics

    31/141

    ASP.NET Lifecycle Events (6)PreInitInitInitCompletePreLoad

    LoadHere we do common processing (e.g. bind controls)

    LoadComplete

    PreRenderPreRenderCompleteSaveStateComplete

    Unload 31

  • 8/12/2019 8.ASP.net Basics

    32/141

    ASP.NET Lifecycle Events (7)PreInit

    InitInitCompletePreLoad

    LoadLoadCompletePreRender

    Executed after data bindingMake some final changes over controls

    PreRenderCompleteSaveStateCompleteUnload 32

  • 8/12/2019 8.ASP.net Basics

    33/141

    ASP.NET Lifecycle Events (8)PreInit

    InitInitCompletePreLoad

    LoadLoadCompletePreRender

    PreRenderCompleteHappens right before the page content is renderedSaveStateCompleteUnload

    33

  • 8/12/2019 8.ASP.net Basics

    34/141

    ASP.NET Lifecycle Events (9)PreInitInitInitCompletePreLoad

    LoadLoadCompletePreRender

    PreRenderCompleteSaveStateComplete

    Any changes over the page content are ignored

    Unload 34

  • 8/12/2019 8.ASP.net Basics

    35/141

    ASP.NET Lifecycle Events (10)PreInitInitInitCompletePreLoad

    LoadLoadCompletePreRender

    PreRenderCompleteSaveStateCompleteUnload

    Page is unloaded from memory 35

  • 8/12/2019 8.ASP.net Basics

    36/141

    ASP.NET ApplicationLifecycleLive Demo

  • 8/12/2019 8.ASP.net Basics

    37/141

    Creating ASP.NET Forms

  • 8/12/2019 8.ASP.net Basics

    38/141

    What is a Web FormASP.NET Web Form is a programmable Web

    page ( .aspx file)Acts as a user interface (UI) of an ASP.NETapplication

    Consists of HTML, code and controls which areexecuted on a web server

    The user sees the result in the form of HTMLgenerated by the web server

    The code and controls which describe the webform dont leave the server

    38

  • 8/12/2019 8.ASP.net Basics

    39/141

    Creating a Web Form

    The functionality of the Web form is definedby using three layers of attributes

    39

    My First WebForm

  • 8/12/2019 8.ASP.net Basics

    40/141

    Creating a Web Form (2)

    Page attributes define global functionality

    40

    My First WebForm

  • 8/12/2019 8.ASP.net Basics

    41/141

    Creating a Web Form (3)

    body tags define the appearance of a web pageMS_POSITIONING: FlowLayout , GridLayout

    41

    My First WebForm

  • 8/12/2019 8.ASP.net Basics

    42/141

    Creating a Web Form (4)

    form attributes define how the groups ofcontrols are going to be processed

    42

    My First WebForm

  • 8/12/2019 8.ASP.net Basics

    43/141

    The Tag

    Defines how the controls are going to beprocessed

    In a Web form there can be several tags

    Only one server-side tag

    43

    HTML version

    ASP.NET version (only 1)

    f

  • 8/12/2019 8.ASP.net Basics

    44/141

    Attributes

    id form identifier

    method - specifies the method of sendinginformation back to the server

    GET in the URLPOST 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

  • 8/12/2019 8.ASP.net Basics

    45/141

    Example: WebFormTest.aspx

    45

    WebFormTest

    HTML and controls go here

  • 8/12/2019 8.ASP.net Basics

    46/141

    Creating ASP.NET FormsLive Demo

  • 8/12/2019 8.ASP.net Basics

    47/141

    Coding Methods

    W i i C d

  • 8/12/2019 8.ASP.net Basics

    48/141

    Writing Code

    Writing code in an ASP.NET Web form is donein three ways:

    Mixed code methodThe code is in the same file as the web content,mixed with the HTML code

    This method is not recommended as the sourcecode is hard to read and maintain

    Inline code method

    Code-behind method

    48

    W i i C d (2)

  • 8/12/2019 8.ASP.net Basics

    49/141

    Writing Code (2)

    Writing code in an ASP.NET web form is donein three ways:

    Mixed code method

    Inline code methodThe code is separated in a SCRIPT section in thesame file

    Code-behind method

    49

    W i i C d (3)

  • 8/12/2019 8.ASP.net Basics

    50/141

    Writing Code (3)

    Writing code in an ASP.NET web form is donein three ways:

    Mixed code method

    Inline code method

    Code-behind methodThe code is in the code-behind page a separatefile from the HTML content

    When using Visual Studio .NET this is the defaultmethod

    50

    E l I li C d M h d

  • 8/12/2019 8.ASP.net Basics

    51/141

    Example: Inline Code Method

    51

    private void btn_Click(object sender,

    System.EventArgs e){

    ...}

  • 8/12/2019 8.ASP.net Basics

    52/141

    Code-Behind

    C d b hi d M d l

  • 8/12/2019 8.ASP.net Basics

    53/141

    Code-behind Model

    A separate compiled file containing theprogram logic of the page

    Each web page has its own code-behind page

    Has the same name as the web page to whichit is attached

    The file extension is .aspx.cs

    The two files are built into one when theapplication is started

    53

    H D C d b hi d W k?

  • 8/12/2019 8.ASP.net Basics

    54/141

    How Does Code-behind Work?To associate an .aspx page to its code-behindclass the @Page directive is usedVS.NET adds three attributes to the @Page directive:

    Inherits allows the .aspx page to derivefrom the code-behind classCodebehind used internally by Visual Studio

    .NET to associate the filesSrc contains the name of the code-behindpage

    Used if the application is not precompiled54

    @P g Di ti E l

  • 8/12/2019 8.ASP.net Basics

    55/141

    @Page Directive Example

    55

    JIT C il ti

  • 8/12/2019 8.ASP.net Basics

    56/141

    JIT Compilation

    The Code-behind page can be eitherprecompiled or just-in-time (JIT) Compiled

    JIT compilation

    A compilation at first requestSet by the Src attribute of the @Page directive

    VS.NET doesnt add it by default

    56

    P il ti

  • 8/12/2019 8.ASP.net Basics

    57/141

    Precompilation

    PrecompilationAvoids the delay at first request

    Simplifies the deployment of the webapplication

    The source code of the code-behind class is notnecessary

    57

  • 8/12/2019 8.ASP.net Basics

    58/141

    Directives

    Directives

  • 8/12/2019 8.ASP.net Basics

    59/141

    DirectivesProvide control over many options affecting the

    compilation and execution of the web formImportant directives:

    @Page main directive of the page

    @Import imports a namespace into the@Assembly attaches an assembly to the formwhen it is compiled

    @OutputCache controls the ability of the formsto use cache

    @Register registers a user control to be used

    in a web form 59

    The @Page Directive

  • 8/12/2019 8.ASP.net Basics

    60/141

    The @Page Directive

    Defines a form specific ( .aspx file) attributesused by the parser and the compiler ofASP.NET

    Important attributes:AutoEventWireup

    Culture a culture used when the page isgenerated

    UICulture a culture used for the visualizationof data

    60

    The @Page Directive (2)

  • 8/12/2019 8.ASP.net Basics

    61/141

    The @Page Directive (2)

    Important attributes:Debug whether the page is compiled withdebug symbols in it

    EnableSessionState whether a session issupported

    EnableViewState whether to use "viewstate or not

    ErrorPage a page to which to redirect in caseof unhandled exception

    61

    The @Page Directive (3)

  • 8/12/2019 8.ASP.net Basics

    62/141

    The @Page Directive (3)Important attributes:

    Language states the program language usedto script the pageCodebehind points to the code-behind filewhere the page logics is storedSmart-Navigation improves user experienceover post backs

    Persists element focus and scroll position

    Avoids flickers

    Supported by IE 5.5 or later

    Shouldnt use it - problematic 62

  • 8/12/2019 8.ASP.net Basics

    63/141

    Using the @Page DirectiveLive Demo

    What is ASP.NET

  • 8/12/2019 8.ASP.net Basics

    64/141

    What is ASP.NETServer Control?

    ASP.NET server controlsThe smallest ASP.NET Component

    Wrap an HTML UI element, or more complex UI

    Component-oriented programming modelExecuted and rendered at the server side

    Example of ASP.NET server controls:

    64

    What is ASP.NET

  • 8/12/2019 8.ASP.net Basics

    65/141

    W at s S .Server Control ?(2)

    Mandatory properties for all server controls:runat="server"

    ID=""

    Programming model based on eventsEach user interaction causes and event

    Programmer decides which events to handle

    Browser-specific HTML is generatedControls deliver appropriate HTML dependingon browser type

    65

  • 8/12/2019 8.ASP.net Basics

    66/141

    Controls Class Hierarchy

    Controls Class Hierarchy

  • 8/12/2019 8.ASP.net Basics

    67/141

    Controls Class Hierarchy

    System.Web.UI.ControlBase for all controls

    Properties ID , Page , ViewState , Context ,ClientID , Controls

    Methods Render(HtmlTextWriter writer)

    67

    Controls Class Hierarchy (2)

  • 8/12/2019 8.ASP.net Basics

    68/141

    Controls Class Hierarchy (2)System.Web.UI.HtmlControls.HtmlControl

    68

    Controls Class Hierarchy (3)

  • 8/12/2019 8.ASP.net Basics

    69/141

    Controls Class Hierarchy (3)System.Web.UI.WebControls.WebControl

    System.Web.UI.TemplateControl

    69

  • 8/12/2019 8.ASP.net Basics

    70/141

    HTML Server Controls

    HTML Server Controls

  • 8/12/2019 8.ASP.net Basics

    71/141

    HTML Server Controls

    HTML server controls are very simple extension ofControl classLook like traditional HTML

    Defined by runat ="server"

    Simple HTML seems like text on the server

    If an HTML element is converted to HTML servercontrol, a server side object is associated with it

    Valid only inside a Web form tag:

    71

    HTML Server Control Example

  • 8/12/2019 8.ASP.net Basics

    72/141

    HTML Server Control Example

    72

    void ButtonSubmit_Click(Object sender, EventArgs e){Response.Write("Value:"+TextField.Value+"");

    }

    HTML Server Controls

  • 8/12/2019 8.ASP.net Basics

    73/141

    HTML Server ControlsLive Demo

    HTML Server Control Classes

  • 8/12/2019 8.ASP.net Basics

    74/141

    HTML Server Control Classes

    HtmlForm

    HtmlInputText

    HtmlButton

    HtmlAnchor HtmlSelect

    HtmlTable , HtmlTableCell , HtmlTableRow HtmlImage

    ...74

    HTML Server Control Classes (2)

  • 8/12/2019 8.ASP.net Basics

    75/141

    HTML Server Control Classes (2)

    HtmlGenericControl

    Used for all other HTML elements

    75

  • 8/12/2019 8.ASP.net Basics

    76/141

  • 8/12/2019 8.ASP.net Basics

    77/141

    HTML Generic ControlsLive Demo

  • 8/12/2019 8.ASP.net Basics

    78/141

    Web Server Controls

    Web Server Controls

  • 8/12/2019 8.ASP.net Basics

    79/141

    Web Server Controls

    Web server controls are server UI controls thatabstract the common HTML elements

    Have own lifecycle and functionality

    Come with .NET FrameworkLocated in System.Web.UI.WebControls namespace, inherit from the WebControl class

    HTML AbstractionRendered HTML tags are quite different fromthe design-time markup

    79

    Web Server Controls Features

  • 8/12/2019 8.ASP.net Basics

    80/141

    Web Server Controls Features

    Rich functionality

    Type-safe programming capabilities

    Automatic Web browser detection

    AutoPostBackSumbit when the focus is lost

    Support for themes

    80

    Web Server Controls - Syntax

  • 8/12/2019 8.ASP.net Basics

    81/141

    Web Server Controls Syntax

    81

    tag_prefixdetermines uniquenamespace for the

    web control

    The name ofthe control

    Attributes are

    properties of theWeb control

    Mandatoryattribute

    runat="server"

    Web Server Control Example

  • 8/12/2019 8.ASP.net Basics

    82/141

    Web Server Control Example

    82

    protected void ButtonSubmit_Click(

    object sender, EventArgs e){

    this.LabelResult.Text ="You entered: " + this.TextBoxInput.Text;this.LabelResult.Visible = true;

    }

  • 8/12/2019 8.ASP.net Basics

    83/141

    Web Server ControlsLive Demo

    System.Web.UI.bC l bC l

  • 8/12/2019 8.ASP.net Basics

    84/141

    WebControls.WebControlThe WebControl class defines properties,events and methods for all Web controls

    Control the appearance

    BackColorForeColor

    BorderWidth

    BorderStyleBorderColor

    84

    System.Web.UI.W bC l W bC l (2)

  • 8/12/2019 8.ASP.net Basics

    85/141

    WebControls.WebControl (2)

    Control the behaviorEnabled

    Visible

    TabIndexToolTip

    Not all controls support all these propertiesSee the documentation for details

    85

  • 8/12/2019 8.ASP.net Basics

    86/141

    Web Server ControlsBasic Web Controls

    Basic Web Controls HTML

  • 8/12/2019 8.ASP.net Basics

    87/141

    Basic Web Controls: TextBox

  • 8/12/2019 8.ASP.net Basics

    88/141

    Creates single-line or multiline text-box

    Lets the user to enter textProperties

    Text

    TextMode SingleLine , MultiLine , Password

    MaxLength

    ReadOnlyAutoPostBack

    Events

    TextChanged combined with AutoPostBack 88

    Basic Web Controls: Label

  • 8/12/2019 8.ASP.net Basics

    89/141

    Display static text in a block

    Allows programmatically to manipulate it

    Properties

    Text

    AssociatedControlID on click focus goes to thespecified control

    EventsTextChanged combined with AutoPostBack

    89

    CAUTION: the Text is NOT HTML encodedbefore it is displayed in the Label control.

    This make it possible to embed scriptwithin HTML tags in the text.

    Basic Web Controls: Literal

  • 8/12/2019 8.ASP.net Basics

    90/141

    Display static text

    Allows programmatically to manipulate itUnlike the Label control, Literal does not letyou apply styles to its content

    PropertiesText

    Renders the Text property value directly

    90

    CAUTION: the Text is NOT HTML encodedbefore it is displayed in the Literal

    control. This make it possible to embed

    script within HTML tags in the text.

    Basic Web Controls Buttons

  • 8/12/2019 8.ASP.net Basics

    91/141

    Implement IButtonControl

    PropertiesText button's title

    CommandName pass a command

    CommandArgument pass command arguments

    PostBackUrl posts back to specified page

    CausesValidation perform validation or notValidationGroup which validation group to bevalidated

    91

    Basic Web Controls Buttons (2)

  • 8/12/2019 8.ASP.net Basics

    92/141

    ( )

    EventsClick

    Command

    CommandName and CommandArgument are passedto code behind

    92

    Basic Web Controls Buttons (3)

  • 8/12/2019 8.ASP.net Basics

    93/141

    ( )

    Different button typesButton

    Creates a push button

    Submit button by default

    Different button typesImageButton

    Display an image that responds on mouse click ImageURL URL to displayed image

    Both Click and Command events are raised 93

    Basic Web Controls Buttons (4)

  • 8/12/2019 8.ASP.net Basics

    94/141

    ( )

    Different button typesCommand Button

    Has command name associated ( CommandName property)

    Programmatically determine which button isclicked in Command event handles

    Used in templated controls, e.g. GridView

    94

    Basic Web Controls Buttons (5)

  • 8/12/2019 8.ASP.net Basics

    95/141

    Different button typesLinkButton

    Same functionality as Button

    Renders as hyperlinkUse Hyperlink if you want to link to anotherpage

    Renders JavaScript on the client browser

    95

    Buttons Example

  • 8/12/2019 8.ASP.net Basics

    96/141

    96

    Untitled Page


    Buttons Example (2)

  • 8/12/2019 8.ASP.net Basics

    97/141

    97



  • 8/12/2019 8.ASP.net Basics

    98/141

    98

    ButtonsLive Demo

    Basic Web Controls Panel

  • 8/12/2019 8.ASP.net Basics

    99/141

    The Panel controlContainer for other controls

    Rendered as

    Useful for:Displaying and hiding groups of controls

    Generating and inserting controls at runtime

    99

    Basic Web Controls Panel(2)

  • 8/12/2019 8.ASP.net Basics

    100/141

    ( )Properties

    ScrollBars Modify visibility and position of scroll bars

    Wrap

    Value indicating whether the content wrapswithin the panel

    GroupingText

    Caption for the group of controls that iscontained in panel control

    DefaultButton

    Button to be pressed by default (Enter) 100

  • 8/12/2019 8.ASP.net Basics

    101/141

    PanelsLive Demo

    Basic Web Controls PlaceHolder

  • 8/12/2019 8.ASP.net Basics

    102/141

    PlaceHolderThe PlaceHolder control

    Reserves a space in the page control hierarchyUsed to add controls to the page at runtime

    Does not produce any visible outputControls

    Use it to add, insert or remove controls fromPlaceHolder Control

    102

    Basic Web Controls CheckBox

  • 8/12/2019 8.ASP.net Basics

    103/141

    Select between checked / unchecked

    PropertiesChecked

    Text Control caption

    AutoPostBack

    Automatically posts back the page when controlstate is changed

    103

    Basic Web Controls CheckBox (2)

  • 8/12/2019 8.ASP.net Basics

    104/141

    CausesValidation Whether validation is performed

    ValidationGroup Which validation group to be validated

    EventsCheckChanged

    104

    Basic Web Controls RadioButton

  • 8/12/2019 8.ASP.net Basics

    105/141

    RadioButton

    Creates a radio button on the Web Forms pageProperties

    Text

    GroupName Allow a mutually exclusive selection from thegroup

    105

  • 8/12/2019 8.ASP.net Basics

    106/141

    Validation ControlsPerforming Control Validation

    Validation Controls

  • 8/12/2019 8.ASP.net Basics

    107/141

    The ASP.NET Web forms validation controlsValidate the values that are entered into othercontrols of the page

    Two modes of validationClient-side validation

    Server-side validation

    Validation is performed at page submit

    107

    Validation Controls (2)

  • 8/12/2019 8.ASP.net Basics

    108/141

    Most important validation controls:RequiredFieldValidator

    RangeValidator

    CompareValidator

    RegularExpressionValidator

    CustomValidator

    ValidationSummary

    108

  • 8/12/2019 8.ASP.net Basics

    109/141

    Validation ControlsLive Demo

  • 8/12/2019 8.ASP.net Basics

    110/141

    List ControlsDisplaying Lists of Items

    List Controls

  • 8/12/2019 8.ASP.net Basics

    111/141

    List Web controlsDisplay 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

    List Controls (2)

  • 8/12/2019 8.ASP.net Basics

    112/141

    ListBox

    CheckBoxList

    RadioButtonList

    RepeaterDataList

    GridView

    DropDownList

    112

  • 8/12/2019 8.ASP.net Basics

    113/141

    List ControlsLive Demo

  • 8/12/2019 8.ASP.net Basics

    114/141

    Web Server ControlsRich Controls

    Rich Controls

  • 8/12/2019 8.ASP.net Basics

    115/141

    Task-specific controls

    Built with multiple HTML elements

    Rich functionality

    Examples:Calendar

    AdRotator

    115

  • 8/12/2019 8.ASP.net Basics

    116/141

    Web Server

    Controls Lifecycle

    Phases

  • 8/12/2019 8.ASP.net Basics

    117/141

    Init

    ViewStateLoadSend Postback Change Notification

    Handle Postback eventsPreRenderSave StateRenderDisposeUnload

    117

    Phases - Initialize

  • 8/12/2019 8.ASP.net Basics

    118/141

    Control initialize settings needed duringincoming web request

    Init event ( OnInit method)

    118

    Phases Load View State

  • 8/12/2019 8.ASP.net Basics

    119/141

    At the end of this phase ViewState property is

    automatically populatedOverride LoadViewState method tocustomize state restoration

    LoadViewState method

    119

    Phases Load

  • 8/12/2019 8.ASP.net Basics

    120/141

    Perform actions common to all requests

    Server controls in the tree are created andinitialized

    Control state from previous round trip isrestored including client side data

    Load event ( OnLoad method)

    120

    Phases Send PostbackChange Notification

  • 8/12/2019 8.ASP.net Basics

    121/141

    Change NotificationRaise change events in response to statechanges between previous and currentpostbacks

    RaisePostDataChangedEvent method

    IPostBackDataHandler should beimplemented

    121

    Phases HandlePostback Events

  • 8/12/2019 8.ASP.net Basics

    122/141

    ostbac ve tsHandle client-side events caused postback

    Raise appropriate events on the server

    RaisePostBackEvent method

    IPostBackEventHandler should beimplemented

    122

    Phases PreRender

  • 8/12/2019 8.ASP.net Basics

    123/141

    Perform any updates before the control is

    renderedChanges made in this phase can be saved

    PreRender event ( OnPreRender method)

    123

    Phases Save State

  • 8/12/2019 8.ASP.net Basics

    124/141

    ViewState property is persisted

    Send to the client and back as a hidden fieldSaveViewState method

    124

    Phases Render

  • 8/12/2019 8.ASP.net Basics

    125/141

    Generates the output which will be send to the

    clientAny changes to controls state made here arelost

    Render() method

    125

    Phases Dispose

  • 8/12/2019 8.ASP.net Basics

    126/141

    Final clean up

    Expensive resources should be releasedDispose() method

    126

    Phases Unload

  • 8/12/2019 8.ASP.net Basics

    127/141

    Final clean up

    Usually clean up is performed in previousphase so this event is not handled

    UnLoad event ( OnUnLoad() method)

    127

  • 8/12/2019 8.ASP.net Basics

    128/141

    ControlsLifecycle

    Live Demo

  • 8/12/2019 8.ASP.net Basics

    129/141

    HTML Escaping

    What is HTML Escaping?

  • 8/12/2019 8.ASP.net Basics

    130/141

    HTML escaping is the act of replacing special

    characters with their HTML entitiesEscaped characters are interpreted as characterdata instead of mark up

    Typical characters to escape start / end of HTML tag

    & start of character entity reference

    ' , " text in single / double quotes

    130

    Character EncodingE h h ld b d HTML i

  • 8/12/2019 8.ASP.net Basics

    131/141

    Each character could be presented as HTML entityescaping sequence

    Numeric character references:' ' is , or ;

    Named HTML entities:' ' is

    '' is >

    '& ' is &

    " (double quote) is "131

    XSS Attack

  • 8/12/2019 8.ASP.net Basics

    132/141

    Cross-site scripting (XSS) is a common security

    vulnerability in Web applicationsWeb application is let to display a JavaScriptcode 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 inputPerform HTML escaping when displaying textdata in a Web control

    132

    What Offers ASP.NET?

  • 8/12/2019 8.ASP.net Basics

    133/141

    ValidateRequest attribute of Page directive

    Checks all input data against a hard-coded listof potentially dangerous values

    The default is true

    Using it could harm the normal work on someapplications

    E.g. a user posts JavaScript code in a forum

    Escaping is better way to handle the problem!

    133

    What Offers ASP.NET ? (2)Htt S Utilit Ht lE d

  • 8/12/2019 8.ASP.net Basics

    134/141

    HttpServerUtility.HtmlEncode

    HTML encodes a string and returns the encodedstring

    Page.Server is instance of HttpServerUtility

    The following script

    Output:

    Web browser renders the following:

    134

    The image tag:

    The image tag:

  • 8/12/2019 8.ASP.net Basics

    135/141

    HTML EscapingLive Demo

    ASP.NET Architecture

  • 8/12/2019 8.ASP.net Basics

    136/141

    Questions?

    Exercises

  • 8/12/2019 8.ASP.net Basics

    137/141

    1. Start Visual Studio 2010 and make new Web Site.

    Look at the files generated and tell what's purposeof each file. Explain "code behind" model. Print"Hell ASP.NET" from code behind and from UI.Show automatic generated files in executingdirectory using Assembly.GetExecutingPath() .

    2. Create a Web page which saves empty file inProgramFiles directory. Configure directory securityso IIS process to be able to write in there.

    3. Catch all the events in page lifecycle usingappropriate method or event handler.

    137

    Exercises (2)

  • 8/12/2019 8.ASP.net Basics

    138/141

    4. Do some kind of tracing of these events.

    5. Create an HTML form that posts the contents of atextarea field to a server and the server prints it inanother field. Dont use code-behind.

    6. Create an ASP.NET web form which posts thecontents of a textarea field to a server and theserver prints it in another field.

    7. Use the src attribute of the @Page directive tocreate a page that doesnt need to be precompiled .

    138

    ExercisesU i g th HTML t l t d

  • 8/12/2019 8.ASP.net Basics

    139/141

    1. Using the HTML server controls create a random

    number generator Web application. It should havetwo input fields defining a range (e.g. [10..20]) and abutton 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. Onbutton click show the entered in the first textboxtext in other textbox control and label control. Entersome potentially dangerous text. Fix issues relatedto HTML escaping the application should acceptHTML tags and display them correctly.

    139

    Exercisesf f f

  • 8/12/2019 8.ASP.net Basics

    140/141

    4. Make a simple Web form for registration of students

    and courses. The form should accept first name, lastname, 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 ofthe entered information as formatted HTML. usedynamically generated tags ( ,

    , ).

    5. Implement the "Tic-tac-toe" game using Web servercontrols. The user should play against the computerwhich should implement some kind of intelligence.

    140

    Exercises

  • 8/12/2019 8.ASP.net Basics

    141/141

    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 withdecimal numbers. Validation is essential!