asp.net programming - student workbook

Upload: vaibhavisawantmokal

Post on 10-Apr-2018

245 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 ASP.net Programming - Student Workbook

    1/96

    ASP.NET ProgrammingCustom Workshop

    Student Workbook

  • 8/8/2019 ASP.net Programming - Student Workbook

    2/96

    2

    Microsoft | Services

  • 8/8/2019 ASP.net Programming - Student Workbook

    3/96

    3

    Microsoft | Services

    TABLE OF CONTENT

    SLIDE 1: WORKSHOP AGENDA ................................................ 4

    SLIDE 169 - MODULE 1: INTRODUCTION TO ASP.NET .............. 8

    SLIDE 176 - MODULE 2: WEB PAGES, MASTER PAGES AND

    NAVIGATION ........................................................................ 11

    SLIDE 219 MODULE 3: SERVER CONTROLS .......................... 33

    SLIDE 233 MODULE 4: ADO.NET ......................................... 41

    SLIDE 256 MODULE 5: LINQ ................................................ 53

    SLIDE 265 MODULE 6: ASP.NET AJAX ................................. 58

    SLIDE 277 MODULE 7: ADDITIONAL TOPICS ....................... 65

  • 8/8/2019 ASP.net Programming - Student Workbook

    4/96

    4

    Microsoft | Services

    Slide 1: Workshop Agenda

    ASP.NET programming

    Custom Workshop

    Slide 2

    Introduction

    Meet your trainer

    About You:Name

    Title/Function/Area of Responsibility

    Programming Experience

    .NET Framework Experience

    Expectations for this Course

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    5/96

  • 8/8/2019 ASP.net Programming - Student Workbook

    6/96

    6

    Microsoft | Services

    Slide 5

    Course Outline

    Introduction to ASP.NET

    Web Pages, Master Pages and Navigation

    Server Controls

    ADO.NET

    LINQ

    AJAX

    Additional Topics (e.g. State management, Caching,Security, Performance Best Practices)

    Slide 6

    Setup

    Software

    Course Files

    Classroom Setup

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    7/96

    7

    Microsoft | Services

    Slide 7

    Questions?

  • 8/8/2019 ASP.net Programming - Student Workbook

    8/96

    8

    Microsoft | Services

    Slide 169 - Module 1: Introduction to ASP.NET

    Module 1:Introduction to

    ASP.NET

    Slide 170

    Overview

    ASP.NET high level overview

    ASP.NET Execution model

    Features

    Build a web site

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    9/96

    9

    Microsoft | Services

    Slide 171

    ASP.NET

    Base Class Library

    Common Language Specification

    Common Language Runtime

    ADO.NET: Data and XML

    Visual Studio

    ASP.NETWindows

    Forms

    Visual Basic

    C++ C# JScript

    Slide 172

    Execution Model

    Visual BasicSource code

    Compiler

    C++C#

    Compiler Compiler

    AssemblyIL Code

    AssemblyIL Code

    AssemblyIL Code

    Operating System Services

    Common Language Runtime

    JIT Compiler

    Native Code

    Managedcode

    UnmanagedComponent

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    10/96

    10

    Microsoft | Services

    Slide 173

    ASP .NET Request Processing

    . N E T

    C o

    d e

    Application

    Host (IIS)

    ASP.NETPage

    ASP.NET Runtime

    ASP.NETService

    HTTPHandler

    HTTP Module

    Global.asax

    HTTP Module

    HttpContext

    N a

    t i v e

    C o

    d e

    Module Per Request Events:

    BeginRequestAuthenticateRequestAuthorizeRequestResolveRequestCacheAcquireRequestStatePreRequestHandlerExecutePostRequestHandlerExecuteReleaseRequestStateUpdateRequestCacheEndRequest

    Slide 174

    Some examples of ASP.NET Features

    Simplified programming model

    Simplified deployment

    Better performance

    Caching

    Security

    Powerful controlsSimplified browser support

    Simplified configuration

    Code behind pages

    More powerful data access

    Web services

    Better session management

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    11/96

    11

    Microsoft | Services

    Slide 175

    Lab: Building web site

    Exercise 2: Creating a simple web site

    Slide 176 - Module 2: Web Pages, Master Pages and Navigation

    Module 2:

    Web Pages, MasterPages and Navigation

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    12/96

    12

    Microsoft | Services

    Slide 177

    Overview

    ASP.NET PagesMaster Pages

    Navigation

    Slide 178

    ASP.NET Pages

    Introduction

    Web Forms

    Run Time Compilation

    Page class

    Page events

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    13/96

    13

    Microsoft | Services

    Slide 179

    Introduction

    ASPX files

    Inherits from Page class

    Partial class (generated by you and ASP.NET whilecompiling)

    Contains Directives

    Located anywhere in the page

    @Assembly, @Control, @Import, @Implements, @Page,etc.

    Single form model

    Slide 180

    Web Forms

    Combines declarative tagsHTML, XML, WML, ASP directives, server controlsand static text with code

    Clean separation between code and tags

    Form1.aspx

    code

    Form1.aspx

    code

    Form1.cs

    single file separate files

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    14/96

    14

    Microsoft | Services

    Slide 181

    Web Forms (continue)

    The parsed file is representedas a tree of controlsThe Page is the root of the treeWeb form is declared by the runat =serverattribute

    Ensures that the form is executed at the server

    Static text (eg HTML withoutrunat =server ) isrepresented as a LiteralControl in the hierarchy

    Slide 182

    Runtime Compilation

    ASPX

    File

    Request

    ASPX

    EngineParse

    GendPage

    Class

    Generate

    Response

    Request

    Instantiate

    Response

    Code-behindclass

    Page

    DLLInstantiate, Process

    and Render

    Compile

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    15/96

    15

    Microsoft | Services

    Slide 183

    Page class

    Intrinsic Objects

    Application, Cache, Request, Response, Server,Session, etc.

    Worker properties

    ClientScript, Controls, ErrorPage, Form, Master,IsPostBack, MasterPageFile, PreviousPage, etc.

    Context properties

    Title, ClientQueryString, ClientTarget, etc.

    Metods

    DataBind, RenderControl, FindControl, LoadTemplateetc.

    Slide 184

    Page Events

    AbortTransaction - Occurs for ASP.NET pages marked to participate in an automatic transaction w hen atransaction aborts.

    CommitTransaction - Occurs for ASP.NET pages marked to participate in an automatic transaction w hen atransaction commits.

    DataBinding - Occurs when the DataBind method is called on the page to bind all the child controls to their respective data sources.

    Disposed - Occurs when the page is released from memory, which is the last stage of the page life cycle.

    Error - Occurs when an unhandled exception is thrown.

    Init - Occurs when the page is initialized, which is the first step in the page life cycle.

    InitComplete - Occurs when all child controls and the page have been initialized. Not availabl e in ASP.NET 1.x.

    Load - Occurs when the page loads up, after being initialized.LoadComplete - Occurs when the loading of the page is completed and server events have been raised. Notavailable in ASP.NET 1.x.

    PreInit - Occurs just before the initialization phase of the page begins. Not available in ASP.NET 1.x.

    PreLoad - Occurs just before the loading phase of the page begins. Not available in ASP.NET 1.x.

    PreRender - Occurs when the page is about to render.

    PreRenderComplet e- Occurs just before the pre-rendering phase begins. Not available in ASP.NET 1.x.

    SaveStateComplete - Occurs when the view state of the page has been saved to the persistence medium. Notavailable in ASP.NET 1.x.

    Unload - Occurs when the page is unloaded from memory but not yet disposed.

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    16/96

    16

    Microsoft | Services

    Slide 185

    Master Pages

    Introduction & Basics

    Defining a Master Page

    Applying a Master Page to the page and site

    Default Content

    Page.Master

    Tips & Tricks

    Slide 186

    Introduction

    Master Page

    Content Page

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    17/96

    17

    Microsoft | Services

    Slide 187

    Master Page Basics

    Masters define common content and placeholders()

    Content pages reference masters and fill placeholderswith content ()

    Site.master default.aspx http://.../default.aspx

    Slide 188

    Defining a Master Page

    ACME Inc.

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    18/96

    18

    Microsoft | Services

    Slide 189

    Applying a Master Page

    This content f i l ls the place holder "Main" defined in the master page

    Slide 190

    Applying a Master Page to a Site

    < / sys t em.web>

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    19/96

    19

    Microsoft | Services

    Slide 191

    Default Content

    ContentPlaceHolder controls can define content of their own ("default content")

    Default content is displayed ONLY if not overriddenby content page

    ...

    Thi s i s de fau l t con ten t t ha t w i l l appea r i n the absence o f ama tch ing Con ten t con t ro l i n a con ten t page

    Slide 192

    The Page.Master Property

    Retrieves reference to master page

    Instance of class derived fromSystem.Web.UI.MasterPage

    Null if page doesn't have a master

    Used to programmatically access content defined inthe master page

    Use FindControl for weak typing

    Use public property in master page for strong typing(preferred)

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    20/96

    20

    Microsoft | Services

    Slide 193

    Tips & Tricks

    Title of a page

    Nested master pages

    Exposing Master Properties

    You can change a master page dynamically

    PreInit event

    this.MasterPageFile

    Slide 194

    Lab: Master Pages

    Exercise 3: Creating and Using Master Pages

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    21/96

    21

    Microsoft | Services

    Slide 195

    Site Navigation

    Introduction

    Schema

    TreeView

    SiteMapDataSource

    SiteMapPath

    Site Map Providers & API

    Slide 196

    Site Navigation

    Navigation UIs are tedious to implement

    Especially if they rely on client-side script

    New controls simplify site navigation

    TreeView and Menu - Navigation UI

    SiteMapDataSource - XML site maps

    SiteMapPath - "Bread crumb" controls

    Public site map API provides foundation

    Provider-based for flexibility

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    22/96

    22

    Microsoft | Services

    Slide 197

    Site Navigation Schema

    Provider Layer

    Server Controls SiteMapDataSourceTreeView SiteMapPath

    Site NavigationAPI

    SiteMapNode SiteMapNode SiteMapNode SiteMap class

    XmlSiteMapProvider (SiteMapProvider)

    RelationalStoreweb.sitemap User Defined

    Menu

    Slide 198

    TreeView Controls

    Render hierarchical data as trees

    Expandable and collapsible branches

    Nodes are navigable, selectable, or static and caninclude check boxes

    Content defined by TreeNode objectsTreeNodes can be added declaratively,programmatically, or through data binding

    TreeNodes can also be demand-loaded

    Highly customizable UI

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    23/96

    23

    Microsoft | Services

    Slide 199

    Declaring a TreeView

  • 8/8/2019 ASP.net Programming - Student Workbook

    24/96

    24

    Microsoft | Services

    Slide 201

    SiteMapDataSource

    Data source control representing site mapsSite map = List of pages and URLs

    Nodes can include descriptive text

    Permits TreeViews and Menus to be populated withlinks through data binding

    Supports "security trimming"

    Specified nodes visible only to specified roles

    Provider-based for flexible data storage

    Slide 202

    XML Site Map

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    25/96

    25

    Microsoft | Services

    Slide 203

    TreeViews and Site Maps

    Web.sitemap

    Slide 204

    Changing the File Name

    < /p rov ide r s>

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    26/96

    26

    Microsoft | Services

    Slide 205

    Attributes

    Name Description

    description Description of node

    roles Role or roles for which this node is visible*

    title Title of this node

    url URL of this node

    *Multiple roles can be specified using comma- or semicolon-delimited lists

    Slide 206

    Security Trimming

    Visible only to Managersand CEOs

    Visible to everyone

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    27/96

    27

    Microsoft | Services

    Slide 207

    Enabling Security Trimming

    Slide 208

    SiteMapDataSource Properties

    Name Description

    SiteMapProvider Name of provider used to obtain site map data

    StartingNodeOffset Starting node identified by level (d efault = 0)

    StartingNodeUrl Starting node identified by URL

    S ta rt Fr om Cu rr en tN od e S pe ci fi es w he th er s ta rt in g n od e s ho ul d b e t he r oo t n od e(false) or the current node (true). Default = false

    Provider Provider used to obtain site map data

    ShowStartingNode Specifies whether to show the root node

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    28/96

    28

    Microsoft | Services

    Slide 209

    Hiding the Root Site Map Node

    Web.sitemap

    Slide 210

    SiteMapPath Controls

    "Bread crumbs" showing path to page

    By default, renders current node as static text

    By default, renders parent nodes as hyperlinks

    Highly customizable UI

    Nodes can be stylized and templatized

    Separators can be stylized and templatized

    Integrates with site map providers to acquire path info

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    29/96

    29

    Microsoft | Services

    Slide 211

    Using SiteMapPath

    Slide 212

    Key SiteMapPath Properties

    Name Description

    CurrentNodeStyle Style used to render the current node

    CurrentNo deTemplate HTML temp late used to ren der the current node

    NodeStyle

    NodeStyleTemplate

    PathSeparatorStyle Style used to render node separators

    PathSeparatorTemplate

    Style used to render non-current nodes

    HTML template used to render non-current nodes

    HTML template used to render node separators

    PathSeparator Text used for node separators (default = ">")

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    30/96

    30

    Microsoft | Services

    Slide 213

    Stylizing SiteMapPath

    < / I t emTempla te>

    Slide 214

    Site Map Providers

    Site maps are provider-based

    Provider interprets site map data and provides it toSiteMapDataSource controls

    Provider also tracks current position and provides it to

    SiteMapPath controlsASP.NET 2.0 ships with one provider

    XmlSiteMapProvider

    Use custom providers for other data stores

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    31/96

    31

    Microsoft | Services

    Slide 215

    Site Map API

    System.Web.SiteMap represents site mapsRootNode property identifies root node

    CurrentNode property identifies current node

    SiteMapNode represents nodes

    Interrogate properties of node

    Walk up, down, and sideways in the hierarchy

    The magic underlying SiteMapPath controls

    Great for customizing SiteMapPaths

    Slide 216

    Using the Site Map API

    / / Wr i t e t he t i t l e o f t he cu r ren t node to a Labe l con t ro lLabe l1 .Tex t = S i t eMap .Cur ren tNode .Ti t le ;

    // Write the path to the current node to a Label controlSi t eMapNode node = S i t eMap .Cur ren tNode ;S t r ingBui lde r bu i lde r = new S t r ingBui lde r (node .Ti t l e ) ;

    while (node.ParentNode != null) {node = node .Pa ren tNode ;bu i lde r. Inse r t (0 , " > " ) ;bu i lde r. Inse r t (0 , node .Ti t l e ) ;

    }

    Labe l1 .Tex t = bu i lde r.ToS t r ing ( ) ;

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    32/96

    32

    Microsoft | Services

    Slide 217

    SiteMap.ResolveSiteMap

    Fired by SiteMapPath controlsUsed to perform on-the-fly customization of pathsdisplayed by SiteMapPath controls

    Add nodes to site map for pages that don't appear in thesite map

    Change the properties of the current node

    Register handler in Application_Start

    Slide 218

    Lab: Navigation

    Exercise 4: Adding Site Navigation to a WebSite

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    33/96

    33

    Microsoft | Services

    Slide 219 Module 3: Server Controls

    Module 3:Server Controls

    Slide 220

    Overview

    ASP.NET Controls overview

    HTML Controls

    Web Controls

    Validation controls

    User Controls

    _____________________________________________________________________________________

    _____________________________________________________________________________________ _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    34/96

    34

    Microsoft | Services

  • 8/8/2019 ASP.net Programming - Student Workbook

    35/96

    35

    Microsoft | Services

    Slide 221

    ASP.NET Controls - Introduction

    Descend from System.Web.UI.Control class

    The class defines minimum set of functionalities, suchas:

    Properties: Controls, ID, Page, Parent, Visible, etc.

    Methods: DataBind, Dispose, Focus, FindControl,RenderControl, etc.

    Events: DataBinding, Disposed, Init, Load, PreRender,Unload

    Control State

    Slide 222

    HTML Controls

    All controls derived fromSystem.Web.UI.HtmlControls.HtmlControl

    Map directly to HTML elements supported by mostbrowsers

    Can run on client or server usingrunat=server

    Controls are lightweight and fast to load

    Support databinding

    void Page_Load(object sender, EventArgs e) {

    lastName.Value = Esposito;

    }

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    36/96

    36

    Microsoft | Services

    Slide 223

    HTML Controls - examples

    HtmlInputControlHtmlInputButtonBoxHtmlInputFile

    HtmlInputImage

    HtmlInputHidden

    HtmlInputRadioButton

    HtmlContainerControlHtmlAnchor

    HtmlForm

    HtmlSelect

    HtmlButton

    HtmlTable

    Slide 224

    Example: Uploading a file

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    37/96

    37

    Microsoft | Services

    Slide 225

    Web Controls

    Defined in System.Web.UI.WebControls

    WebControl is the base class

    Use runat=server

    More abstract in API design and richer in functionalitythan HTML controls

    On ASPX page, they use ASP namespace prefix

    Almost the same markup as HTML controls

    Slide 226

    Web Controls: examples

    Button

    CheckBox

    FileUpload

    HiddenField

    HyperLinkImage

    Panel

    TextBox

    Table

    Calendar

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    38/96

    38

    Microsoft | Services

    Slide 227

    Validation controls

    All vaidators on a page are grouped in the ValidatorscollectionPage.Validate() and control.Validate()

    Types of validators:

    CompareValidator

    CustomValidator

    RangeValidator

    RegularExpressionValidator

    RequiredFieldValidator

    Slide 228

    Validators (cont.)

    BaseValidator class

    Properties: ControlToValidate, ErrorMessage, ForeColor,ValidationGroup

    Examples:

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    39/96

    39

    Microsoft | Services

    Slide 229

    Validators: Examples (cont.)

    Slide 230

    User Controls

    Derives from System.Web.UI.UserControl class

    Web form saved to a distinct file with ASCX extention

    Easy to implement and reuse

    Build visually in Visual Studio

    Support @OutputCache to take advantage of outputcaching:

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    40/96

    40

    Microsoft | Services

    Slide 231

    An example

    Message.ascx

    Message.ascx.cspublic partial class Message : System.Web.UI.UserControl {

    public string ForeColor;public string Text;

    }

    ASPX file

    Slide 232

    Lab: Validation

    Exercise 5: Validate user input

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    41/96

    41

    Microsoft | Services

    Slide 233 Module 4: ADO.NET

    Module 4:ADO.NET

    Slide 234

    Overview

    Introduction

    Data Providers

    Data Containers

    Data Controls

    _____________________________________________________________________________________

    _____________________________________________________________________________________ _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    42/96

    42

    Microsoft | Services

  • 8/8/2019 ASP.net Programming - Student Workbook

    43/96

    43

    Microsoft | Services

    Slide 235

    ADO.NET Data Providers

    Principal components

    Main features

    Type of providers

    Main classes:

    SqlConnection

    SqlCommand

    SqlDataReader

    Connection String

    Slide 236

    Principal components

    Connection

    Transaction

    Command

    Parameter

    DataAdapter CommandBuilder

    DataReader

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    44/96

    44

    Microsoft | Services

    Slide 237

    Main features

    Disconnected data

    Connected data access

    Slide 238

    Types of providers

    Types of providers

    Managed ProvidersSystem.Data.SqlClientMicrosoft.SqlServerCe.Client

    OLE DB Providers

    ODBC drivers (System.Data.Odbc)

    Oracle (System.Data.OracleClient)

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    45/96

    45

    Microsoft | Services

    Slide 239

    SqlConnection

    string connString = SERVER=... ; DATABASE=... ; UID=. ..;PWD=...;SqlConnection conn = new SqlConnection(connString);conn.Open();...conn.Close(); //or conn.Dispose();

    Properties: ConnectionString, ConnectionTimeout, etc.

    Methods: BeginTransaction, Open, Close,CreateCommand

    Use try / catch / finally !

    Slide 240

    Connection String

    Contains keywords, for example: Application Name, Connection Timeout (15 sec default), Database,Password, Server, User ID

    Should be configurable for entire web site in one placeConfigurationManager.ConnectionStrings

    Web.config file:

    Should be protected

    Connection Pooling is enabled by default

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    46/96

    46

    Microsoft | Services

    Slide 241

    SqlCommand

    Properties:CommandText, CommandTimeout, CommandType, Connection,Transaction, etc.

    Methods:ExecuteNonQuery, ExecuteReader, ExecuteScalar, Cancel,CreateParameter, etc.

    Synchronously or asynchronously

    An example:using (SqlConnection conn = new SqlConnection(ConnStri ng)){

    SqlCommand cmd = new SqlCommand(sprocName, conn);cmd.CommandType = commandType.StoredProcedure;cmd.Connection.Open();cmd.ExecuteNonQuery();

    }

    Slide 242

    SqlDataReader

    Works like a cursor

    Reads one or more results generated by a command

    SqlCommand.ExecuteReader

    Can read multiple results set

    Very effective metodProperties:

    FieldCount, HasRows, IsClosed, Item, etc.

    Methods:

    Close, IsDbNull, NextResult, GetValues, Read, GetByte,GetChar, GetInt32, etc.

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    47/96

    47

    Microsoft | Services

    Slide 243

    SqlDataReader: an example

    An example:using (SqlConnection conn = new SqlConnection(connString) ) {

    string cmdText = SELECT * FROM customers;

    SqlCommand cmd = new SqlCommand(cmdText, conn);

    cmd.Connection.Open();

    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())

    CustomerList.Items.Add(reader[companyname].ToStri ng());

    reader.Close();

    }

    Slide 244

    ADO.NET Data Containers

    Data Adapters

    Data Sets

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    48/96

    48

    Microsoft | Services

    Slide 245

    Data Adapters

    Acts as a two-way bridge between a data source and theDataSet objectFills DataSet

    Submit DataSets data back to a data source

    SqlDataAdapter class

    Slide 246

    SqlDataAdapter

    Properties:

    DeleteCommand, SelectCommand, UpdateCommand

    AcceptChangesDuringFill, AcceptChangesDuringUpdate,TableMappings

    Methods:

    Fill, Update, GetFillParameters

    An example:DataSet ds = new DataSet() ;adapter.Fill(ds); Adapter.Fill (ds, MyTable);

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    49/96

    49

    Microsoft | Services

    Slide 247

    DataSet

    In-memory object with data retrieved through a query

    In-memory counterpart of a DBMS databasemay contain multiple tables (DataTable objects)

    may contain relationships

    may contain constraints between tables

    Filling a DataSet = filling a table in DataSet

    TableMappings maps a result set into a DataSet table

    Properties:EnforceConstraints, HasErrors, Relations, Tables

    Methods: AcceptChanges, Clear, Copy, GetChanges, GetXml, ReadXml,RejectChanges

    Slide 248

    DataSet Batch Update

    adapter.Update(ds, MyTable);

    Executes Insert, Update, Delete statement for eachmodified row

    ContinueUpdateOnError

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    50/96

  • 8/8/2019 ASP.net Programming - Student Workbook

    51/96

    51

    Microsoft | Services

    Slide 251

    Data Controls

    Binding Model

    Data-bound controls

    Data source components

    Slide 252

    Binding model

    Data-bound controls:

    List and iterative controls

    Implements DataBoundControl class

    Data-Binding Properties:

    DataSource, DataSourceIDDataMember

    DataTextField, DataTextFormatString, DataValueField

    DataKeyField

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    52/96

    52

    Microsoft | Services

    Slide 253

    Useful Data-bound controls

    List Controls:

    DropDownList

    CheckBoxList

    RadioButtonList

    ListBox

    BulletedList

    Iterative Controls

    Repeater

    DataList

    DataGrid

    Slide 254

    Data Source components

    SqlDataSource

    ObjectDataSource

    GridView

    DetailsView

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    53/96

    53

    Microsoft | Services

    Slide 255

    Lab: Data Access and Data Controls

    Exercise 6: Basic Data Access

    Exercise 7: Creating Master-Detail WebPages

    Exercise 8: Using the ListView Web Server Control

    Slide 256 Module 5: LINQ

    Module 5:LINQ

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    54/96

    54

    Microsoft | Services

    Slide 257

    Overview

    IntroductionExamples

    LINQ to XML

    LINQ to SQL

    LINQ to DataSet

    Slide 258

    LINQ: Introduction

    LINQ = Language Integrated Query

    Query, Set and Transform Operations for .NET

    Makes querying data a core programming concept

    Works with all types and shapes of data, for example:

    Relational databasesXML

    DataSets

    Even available for SharePoint 2010!

    Works with all .NET languages

    New VB and C# have integrated language support

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    55/96

    55

    Microsoft | Services

    Slide 259

    Some examples:

    Query expression:var contacts =

    from c in customerswhere c.City == Warszawa"select new { c.Name, c.Address };

    Lambda expression:var contacts =

    customers.Where(c => c.City == Warszawa").Select(c => new { c.Name, c.Address });

    Slide 260

    LINQ to XML

    Creating XML

    Constructors lend themselves to nesting

    Can use LINQ (over anything) to build XML

    Querying

    Use normal axes from XML infosetGet full power of query expressions over XML

    Select, where, group by, etc.

    Xml Namespaces

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    56/96

  • 8/8/2019 ASP.net Programming - Student Workbook

    57/96

    57

    Microsoft | Services

    Slide 263

    LINQ to DataSet

    Query expressions over in-memory data

    Works with untyped or typed DataSets

    If query returns some kind of DataRow: -

    Can yield results as a DataView

    ...and therefore databind to those results

    Slide 264

    Lab:LINQ

    Exercise 9: LINQ in Object Model

    Exercise 10: LinqDataSource andDetailsView controls

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    58/96

    58

    Microsoft | Services

    Slide 265 Module 6: ASP.NET AJAX

    Module 6:ASP.NET AJAX

    Slide 266

    Overview

    Introduction

    Visual Studio 2008 AJAX Support

    Developer scenarious

    Update Panel

    ASP.NET AJAX Control Toolkit

    Control Extenders

    _____________________________________________________________________________________

    _____________________________________________________________________________________ _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    59/96

    59

    Microsoft | Services

  • 8/8/2019 ASP.net Programming - Student Workbook

    60/96

    60

    Microsoft | Services

    Slide 267

    Introduction

    AJAX = Asynchronous JavaScript and XML

    clever use of DHTML + JavaScriptA framework for building richer, moreinteractive, more personalized webexperiencesExchange data and not pages with serverv1.0 works on ASP.NET 2.0 and VS 2005

    Shipped in Jan as separate downloadAll ASP.NET AJAX 1.0 features in .NET 3.5

    Slide 268

    Introduction (cont.)

    XMLHttpRequest

    Sends HTTP request synchronously or asynchronously

    Microsoft AJAX JavaScript library

    ASP.NET AJAX assembly: system.web.extensions

    JavaScript files are resource files in the assemblyDefines:

    Core framework clases (Sys.WebForms, Sys.Net, Sys.Services,Sys.Serialization, Sys)User-interface framework classes (Sys.UI)

    Script Manager and Script Manager Proxy controls

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    61/96

    61

    Microsoft | Services

    Slide 269

    Visual Studio 2008 AJAX Support

    JavaScript Intellisense

    Code intellisense for client-side JavaScript

    Integrated editor support for ASP.NET AJAX JS Library

    Intellisense against JSON enabled .asmx web services

    JavaScript Debugging

    Improved discoverability

    ASP.NET AJAX Extender Control Support

    Easy design-time to attach extenders

    Slide 270

    Page Developer Scenario

    .NET Framework 2.0

    Browser Application

    Rendered Page

    (HTML/CSS)

    ASP.NET Application

    ASPX Page

    Postback

    Updated Rendering

    Initial Rendering(UI + Behavior)

    protected void Handler(){}

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    62/96

    62

    Microsoft | Services

    Slide 271

    Page Developer Scenario with ASP.NET AJAX

    .NET Framework 2.0Microsoft AJAX Library

    Browser Application

    Rendered Page

    ASP.NET Application

    ASPX Page

    Async Postback

    Updated Rendering(only region in

    UpdatePanel)

    Initial Rendering(UI + Behavior) Some non-updatable content and controls...

    This content can be dynamically updated!

  • 8/8/2019 ASP.net Programming - Student Workbook

    63/96

    63

    Microsoft | Services

    Slide 273

    Showing Progress

    UpdateProgress control provides feedback on theprogress of partial-page rendering

  • 8/8/2019 ASP.net Programming - Student Workbook

    64/96

    64

    Microsoft | Services

    Slide 275

    Control Extenders

    Extend ASP.NET controls with ASP.NET AJAX clientbehaviorsEncapsulate both client and server behavior

    Same familiar programming model as ASP.NET server controls

  • 8/8/2019 ASP.net Programming - Student Workbook

    65/96

    65

    Microsoft | Services

    Slide 277 Module 7: Additional Topics

    Module 7:Additional Topics

    Slide 278

    Overview

    Error Handling

    State Management

    Security

    Membership and Role Managers

    Performance Best Practices

    _____________________________________________________________________________________

    _____________________________________________________________________________________ _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    66/96

    66

    Microsoft | Services

  • 8/8/2019 ASP.net Programming - Student Workbook

    67/96

    67

    Microsoft | Services

    Slide 279

    Error handling

    In code: try, catch, finally

    On Page level: Error eventOn Web Application Level:

    global.asax Application_Error eventServer.GetLastError() to obtain info about the error

    Web.config

    Custom error page

    Should be logged, e.g.:

    Event Log class (System.Diagnostics namespace)

    SQL table

    Slide 280

    Best Practices

    Do not reveal exception details to the client

    Use a global error handler to catch unhandledexceptions

    Monitor application exceptions.

    Consider using an application-specific event source

    Protect audit and log files

    Use try/finally on disposable resources

    Write code that avoids exceptions

    Set timeouts aggressively

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    68/96

  • 8/8/2019 ASP.net Programming - Student Workbook

    69/96

    69

    Microsoft | Services

    Slide 283

    Application

    Global setting for web application

    Thread safe

    Objects will stay permanently in memory

    // This operation is thread-safe Application[MyValue] = 1;

    Application.Lock();int val = (int) Application[MyValue];if (val < 10)

    Application[MyValue] = val + 1; Application.UnLock();

    Slide 284

    Session State

    For the same session made by a user

    Available accross multiple web pages

    Different State Client Managers: section in web.config

    InProc in memory of w3wp process (detault option)

    Off disabled

    SQLServer SQL Server table

    StateServer in memory of aspnet_state.exe process

    Session ID

    Session Cookies

    Cookless sessions Be careful: session hijacking!

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    70/96

    70

    Microsoft | Services

    Slide 285

    Session State: Best Practices

    Do not rely on client-side state management options.

    Protect your out-of-process state service.

    Protect SQL Server session state.

    Slide 286

    View State

    By default, maintained as a hidden feld added to thepage

    StateBag class

    Remember about security and performance!

    Can be disabled for a web page:

    Or controls:

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    71/96

    71

    Microsoft | Services

    Slide 287

    Caching

    Cache class

    Can be confgured to expire after a specifed number of seconds

    Globally visible class which works in current ApplicationDomain

    Dont work in web garden or web farm scenario

    Cache[MyData] = value;

    Slide 288

    Caching Web Pages and sections

    ASP.NET output caching

    Location of a cache

    Any, Client, None, DownStream, Server, ServerAndClient

    Can be used on page and custom control level

    Caching profiles

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    72/96

    72

    Microsoft | Services

    Slide 289

    Security

    ASP.NET Processing

    Authentication vs. AuthorizationAuthentication methods

    IIS Authentication and Authorization Process

    ASP.NET web site configuration

    Application pool account and permissions

    IIS Built-in accountsCode Access Security

    Global Assembly Cache

    Attack Methods

    Best Practices

    Slide 290

    ASP.NET Processing

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    73/96

    73

    Microsoft | Services

    Slide 291

    Authentication vs. Authorization

    Authentication is the process of identification andvalidation of a user's credentials.Authorization provides access controls for a user

    Slide 292

    IIS: Authentication and autorization process

    1. Is IP address permitted?

    2. Is user permitted?

    Valid credentials

    Account restrictionsTime, Lockout, Password expired, Privileges

    3. Does IIS allow access?

    4. Does NTFS allow access?

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    74/96

    74

    Microsoft | Services

    Slide 293

    Authentication methods

    Authentication methods in IISBasic

    Digest

    Integrated WindowsProtocols: NTLM or Kerberos

    Passport

    Anonymous

    Certificates

    Authentication is defined in web.config file

    Forms

    Windows

    Passport

    Slide 294

    Configuration Files and the .NET Framework

    The Web server has a Web.config file for ASP.NET Webapplication settings

    Each ASP.NET Web application also has its ownWeb.config file

    Within the Web.config file, you can control access toindividual pages or the entire Web site:

  • 8/8/2019 ASP.net Programming - Student Workbook

    75/96

    75

    Microsoft | Services

    Slide 295

    Web.config: some examples:

    Internet web site

  • 8/8/2019 ASP.net Programming - Student Workbook

    76/96

    76

    Microsoft | Services

    Slide 297

    Default permissions of the Application Pool account

    Access this computer from the network

    Deny logon locally

    Deny logon through

    Terminal Services

    Log on as a batch job

    Log on as a service

    Some NTFS permissions

    Slide 298

    IIS: Built-in accounts

    Account Description

    LocalSystemA built-in account that has a high level of access rightsAvoid assigning LocalSystem as an application poolidentity

    Network Service

    A built-in IIS account with low privilegesInteracts throughout the network with the computeraccountThe default application pool i dentity (recommended)

    Local Service

    A built-in IIS account with lowest privileges

    Connects anonymously over the networkUse for local Web applications only

    IIS_WPG An IIS group account, application pool identity accountsmust be a member of this group

    IUSR_computername An IIS account for anonymous IIS access

    IWAM_computernameAn IIS account for starting out-of-process applications inIIS 5.0 isolation mode

    ASPNETA built-in account for running Microsoft ASP.NET workerprocess in IIS 5.0 isolation mode

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    77/96

    77

    Microsoft | Services

    Slide 299

    Code Access Security

    Define what your code can do

    Fine-grained policyFine-grained permissions

    Multiple levels of trust

    Different apps in the same process can run at different trust levels

    Range of named trust levelsFulltrust: do anything the process can

    Hightrust: no unmanaged code, still have broad permissions

    Mediumtrust: recommended default

    Lowtrust: basic set of rights

    Minimaltrust: execute only

    in Web.config

    Slide 300

    Code Access Security: Best Practices

    Consider code access security for partial trustapplications.

    Choose a trust level that does not exceed your application's requirements.

    Create a custom trust policy if your application needs

    additional permissions.Use Medium trust in shared hosting environments.

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    78/96

    78

    Microsoft | Services

    Slide 301

    Global Assembly Cache

    Registry for .NET assemblies

    Add an assembly to the GAC:Generate a strong name, assembly: 1) name, 2) version, 3) 64 bitpublic key hash -sn.exe , 4) culture

    Add to the GAC -gacutil.exe , .NET Configuration x.x(MMC Snap-in)

    Viewing the contents of the GAC:gacutil /lstart explorer %windir%\assembly

    Security: all GACed assemblies (for ASP.NET apps):Run as Full Trust

    Are accessible to all ASP.NET apps

    Slide 302

    Attack methods

    Cross-site scripting - Untrusted user input is echoed to the page.

    Denial of service (DoS) - The attacker foods the network with fakerequests, overloading the system and blocking regular traffc

    Eavesdropping - The attacker uses a sniffer to read unencryptednetwork packets as they are transported on the network

    Hidden-feld tampering - The attacker compromises unchecked (andtrusted) hidden felds stuffed with sensitive dataOne-click - Malicious HTTP posts are sent via script

    Session hijacking - The attacker guesses or steals a valid sessionID and connects over another users session

    SQL injection - The attacker inserts malicious input that the codeblissfully concatenates to form dangerous SQL commands

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    79/96

    79

    Microsoft | Services

    Slide 303

    Security: Best Practices

    Use Run As...never log on as an Administrator

    Disable NetBIOS

    Do not put Web files on C:

    Use the highest level of authentication you can, based on theclients used

    Always encrypt sensitive information using SSL or IPSec

    Always use SSL when using basic authentication

    Do not issue a request for a certificate on a production server

    Never leave certificates on the server

    Use URL Scan

    Do not install the Resource Kit on a production server

    Slide 304

    Data Access: Best Practices

    Encrypt your connection strings.

    Use least-privileged accounts for database access.

    Use Windows authentication where possible.

    If you use Windows authentication, use a trusted service account.

    If you cannot use a domain account, consider mirrored accounts.

    When using SQL authentication, use strong passwords.When using SQL authentication, protect credentials over thenetwork.

    When using SQL authentication, protect credentials in configurationfiles.

    Validate untrusted input passed to your data access methods.

    When constructing SQL queries, use type safe SQL parameters.

    Avoid dynamic queries that accept user input.

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    80/96

    80

    Microsoft | Services

    Slide 305

    Sensitive Data: Best Practices

    Avoid plaintext passwords in configuration files.

    Use platform features to manage keys where possible

    Do not pass sensitive data from page to page

    Protect sensitive data over the wire

    Do not cache sensitive data

    Slide 306

    Parameter Manipulation: Best Practices

    Do not make security decisions based on parametersaccessible on the client-side

    Validate all input parameters

    Avoid storing sensitive data in ViewState

    Encrypt ViewState if it must contain sensitive data

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    81/96

    81

    Microsoft | Services

    Slide 307

    Membership and Role Management

    Membership service

    Login controls

    Role Management service

    FBA: Best Practices

    Slide 308

    Membership Service

    Service for managing users and credentials

    Declarative access via Web Site Admin Tool

    Programmatic access via Membership andMembershipUser classes

    Membership class provides base servicesMembershipUser class represents users and providesadditional services

    Provider-based for flexible data storage

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    82/96

    82

    Microsoft | Services

    Slide 309

    Membership Schema

    Membership API

    MembershipData

    OtherData Stores

    Controls

    Login LoginStatus LoginView

    Other MembershipProviders

    Membership Providers

    M em bership M em bershipUser

    SqlMembershipProvider

    SQLServer

    Other LoginControls

    AD/AzMan

    Windows Auth Provider

    Slide 310

    The Membership Class

    Provides static methods for performing keymembership tasks

    Creating and deleting users

    Retrieving information about users

    Generating random passwordsValidating logins

    Also includes read-only static properties for acquiringdata about provider settings

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    83/96

    83

    Microsoft | Services

    Slide 311

    Key Membership Methods

    Nam e Description

    C re ateU ser Ad ds a us er to th e m embership da ta s tore

    De le teUser R em o ves a us er from the m em bersh ip d ata sto re

    G en e rateP asswo rd G en er ates a ran do m p asswo rd of a specified length

    G etAllUsers R et rieves a c ollec tion o f M em bership User o bjectsrepresenting all currently registered users

    G e tU ser R etr ieves a M em bersh ipUse r o bject r epresentin g a u ser

    U p d at eUser U pd at es information f or a s pecified u ser

    Va lidate User Validates login s based on user n am es and passwo rds

    Slide 312

    The MembershipUser Class

    Represents individual users registered in themembership data store

    Includes numerous properties for getting and settinguser info

    Includes methods for retrieving, changing, andresetting passwordsReturned by Membership methods such as GetUser and CreateUser

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

    _____________________________________________________________________________________

  • 8/8/2019 ASP.net Programming - Student Workbook

    84/96

    84

    Microsoft | Services

    Slide 313

    Key MembershipUser Properties

    Name Description

    C om m ent S to rag e f or u ser-d efined d ata

    C re a tio nDate Da te us er w as ad ded to th e m em ber ship d a ta