Sie sind auf Seite 1von 96

ASP.

NET Programming
Custom Workshop

Student Workbook
2
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

3
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

4
Microsoft | Services
Slide 3

Facilities

Class Hours Phones

Transport Computers

Rest Rooms Smoking

Meals Recycling

Slide 4

Workshop Overview

Workshop’s content:
Presentation
Demos
Labs
Dev team lab (we create a web site together)

Bring your laptop? Unless you plan to record


electronic notes, please turn it off.
Please silence your phone!

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

5
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

6
Microsoft | Services
Slide 7

Questions?

7
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
Microsoft | Services
Slide 171

ASP.NET

® ®
Visual Basic C++ C# JScript …

Common Language Specification

Windows

Visual Studio
ASP.NET
Forms

ADO.NET: Data and XML

Base Class Library

Common Language Runtime

Slide 172

Execution Model

Source code
Visual Basic C# C++

Unmanaged
Compiler Compiler Compiler
Component

Managed Assembly Assembly Assembly


code IL Code IL Code IL Code

Common Language Runtime

JIT Compiler

Native Code

Operating System Services

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

9
Microsoft | Services
Slide 173

ASP .NET Request Processing

Module Per Request Events:


ASP.NET ASP.NET HTTP
BeginRequest Page Service Handler
AuthenticateRequest
AuthorizeRequest
ResolveRequestCache
Application
AcquireRequestState
PreRequestHandlerExecute
<handler executes here> HTTP Module
PostRequestHandlerExecute
ReleaseRequestState
UpdateRequestCache HTTP Module
EndRequest

HttpContext
Global.asax

.NET Code
ASP.NET Runtime

Native Code
Host (IIS)

Slide 174

Some examples of ASP.NET Features

Simplified programming model


Simplified deployment
Better performance
Caching
Security
Powerful controls
Simplified browser support
Simplified configuration
Code behind pages
More powerful data access
Web services
Better session management

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

10
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, Master
Pages and Navigation

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

11
Microsoft | Services
Slide 177

Overview

ASP.NET Pages
Master Pages
Navigation

Slide 178

♦ ASP.NET Pages

Introduction
Web Forms
Run Time Compilation
Page class
Page events

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

12
Microsoft | Services
Slide 179

Introduction

ASPX files
Inherits from Page class
Partial class (generated by you and ASP.NET while
compiling)
Contains Directives
Located anywhere in the page
@Assembly, @Control, @Import, @Implements, @Page,
etc.
<%@ Directive_Name attribute=”value”
[attribute=”value”.. . ] %>
Single form model

Slide 180

Web Forms

Combines declarative tags


HTML, XML, WML, ASP directives, server controls
and static text with code
Clean separation between code and tags
single file separate files

code

<tags> <tags> code

Form1.aspx Form1.aspx Form1.cs

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

13
Microsoft | Services
Slide 181

Web Forms (continue)

The parsed file is represented


as a tree of controls
The Page is the root of the tree
Web form is declared by the runat=“server”
attribute
Ensures that the form is executed at the server
<form runat="server">
</form>
Static text (eg HTML without runat=“server” ) is
represented as a “LiteralControl” in the hierarchy

Slide 182

Runtime Compilation

ASPX Generate
Parse Code-
Engine behind
class

Gen’d
Request ASPX Page
File Class
Instantiate

Request Compile

Response Page
DLL
Response Instantiate, Process
and Render

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

14
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, LoadTemplate
etc.

Slide 184

Page Events

AbortTransaction - Occurs for ASP.NET pages marked to participate in an automatic transaction when a
transaction aborts.
CommitTransaction - Occurs for ASP.NET pages marked to participate in an automatic transaction when a
transaction 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 available 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. Not
available 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.
PreRenderComplete - 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. Not
available in ASP.NET 1.x.
Unload - Occurs when the page is unloaded from memory but not yet disposed.

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

15
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

16
Microsoft | Services
Slide 187

Master Page Basics

Masters define common content and placeholders


(<asp:ContentPlaceHolder>)
Content pages reference masters and fill placeholders
with content (<asp:Content>)

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

<%@ Master %> <%@ Page MasterPage-


File="Site.master" %>

<asp:Content
<asp:ContentPlaceHolder ContentPlaceHolderID=
ID="Main" "Main" RunAt="server" />
RunAt="server" />

</asp:Content>

Slide 188

Defining a Master Page

<%@ Master %>

<html>
<body>
<!-- Banner shown on all pages that use this master -->
<table width="100%">
<tr>
<td bgcolor="darkblue" align="center">
<span style="font-size: 36pt; color: white">ACME Inc.</span>
</td>
</tr>
</table>

<!-- Placeholder for content below banner -->


<asp:ContentPlaceHolder ID="Main" RunAt="server" />
</body>
</html>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

17
Microsoft | Services
Slide 189

Applying a Master Page

<%@ Page MasterPageFile="~/Site.master" %>

<asp:Content ContentPlaceHolderID="Main" RunAt="server">


This content fills the place holder "Main" defined in the master page
</asp:Content>

Slide 190

Applying a Master Page to a Site

<configuration>
<system.web>
<pages masterPageFile="~/Site.master" />
</system.web>
</configuration>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

18
Microsoft | Services
Slide 191

Default Content

ContentPlaceHolder controls can define content of


their own ("default content")
Default content is displayed ONLY if not overridden
by content page

<%@ Master %>


...
<asp:ContentPlaceHolder ID="Main" RunAt="server">
This is default content that will appear in the absence of a
matching Content control in a content page
<asp:ContentPlaceHolder>

Slide 192

The Page.Master Property

Retrieves reference to master page


Instance of class derived from
System.Web.UI.MasterPage
Null if page doesn't have a master
Used to programmatically access content defined in
the master page
Use FindControl for weak typing
Use public property in master page for strong typing
(preferred)

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

19
Microsoft | Services
Slide 193

Tips & Tricks

Title of a page
<@Page MasterPageFile=”simple. master” Ti tle=”Hel l o,
master” %>
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

20
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

21
Microsoft | Services
Slide 197

Site Navigation Schema

Server Controls
M enu TreeView SiteM apPath SiteM apDataSource

Site Navigation
SiteM apNode SiteM apNode SiteM apNode SiteM ap class
API

XmlSiteM apProvider (SiteM apProvider)

Provider Layer

Relational
web.sitemap User Defined
Store

Slide 198

TreeView Controls

Render hierarchical data as trees


Expandable and collapsible branches
Nodes are navigable, selectable, or static and can
include check boxes
Content defined by TreeNode objects
TreeNodes can be added declaratively,
programmatically, or through data binding
TreeNodes can also be demand-loaded
Highly customizable UI

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

22
Microsoft | Services
Slide 199

Declaring a TreeView

<asp:TreeView RunAt="server>
<Nodes>
<asp:TreeNode Text="Training" RunAt="server">
<asp:TreeNode Text="Programming .NET" RunAt="server"
Navigateurl="Classes.aspx?id=1" />
<asp:TreeNode Text="Programming ASP.NET" RunAt="server"
NavigateUrl="Classes.aspx?id=2" />
<asp:TreeNode Text="Programming Web Services" RunAt="server"
NavigateUrl="Classes.aspx?id=3" />
</asp:TreeNode>
<asp:TreeNode Text="Consulting" RunAt="server"
NavigateUrl="Consulting.aspx" />
<asp:TreeNode Text="Debugging" RunAt="server"
NavigateUrl="Debugging.aspx" />
</Nodes>
</asp:TreeView>

Slide 200

Key TreeView Properties

Name Description

ExpandDepth Specifies the TreeView's initial expand depth

ShowExpandCollapse Specifies whether expand/collapse indicators are shown

LevelStyles Specifies appearance of nodes by level

NodeStyle Specifies default appearance of nodes

RootNodeStyle Specifies appearance of root nodes

LeafNodeStyle Specifies appearance of leaf nodes

SelectedNodeStyle Specifies appearance of selected nodes

HoverNodeStyle Specifies appearance of nodes when cursor hovers overhead

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

23
Microsoft | Services
Slide 201

SiteMapDataSource

Data source control representing site maps


Site map = List of pages and URLs
Nodes can include descriptive text
Permits TreeViews and Menus to be populated with
links through data binding
Supports "security trimming"
Specified nodes visible only to specified roles
Provider-based for flexible data storage

Slide 202

XML Site Map

<siteMap>
<siteMapNode title="Home" description="" url="default.aspx">
<siteMapNode title="Training" url="Training.aspx"
description="Training for .NET developers">
<siteMapNode title="Programming .NET" url="Classes.aspx?id=1"
description="All about the .NET Framework" />
<siteMapNode title="Programming ASP.NET" url="Classes.aspx?id=2"
description="All about ASP.NET" />
<siteMapNode title="Programming Web Services" url="Classes.aspx?id=3"
description="All about Web services" />
</siteMapNode>
<siteMapNode title="Consulting" url="Consulting.aspx"
description="Consulting for .NET projects" />
<siteMapNode title="Debugging" url="Debugging.aspx"
description="Help when you need it the most" />
</siteMapNode>
</siteMap>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

24
Microsoft | Services
Slide 203

TreeViews and Site Maps

<asp:SiteMapDataSource ID="SiteMap" RunAt="server" />


<asp:TreeView DataSourceID="SiteMap" RunAt="server" />

Web.sitemap

<siteMap>
<siteMapNode title="Home" description="" url="default.aspx">
<siteMapNode title="Training" url="Training.aspx"
description="Training for .NET developers">
<siteMapNode title="Programming .NET" url="Classes.aspx?id=1"
description="All about the .NET Framework" />
<siteMapNode title="Programming ASP.NET" url="Classes.aspx?id=2"
description="All about ASP.NET" />
<siteMapNode title="Programming Web Services" url="Classes.aspx?id=3"
description="All about Web services" />
</siteMapNode>
<siteMapNode title="Consulting" url="Consulting.aspx"
description="Consulting for .NET projects" />
<siteMapNode title="Debugging" url="Debugging.aspx"
description="Help when you need it the most" />
</siteMapNode>
</siteMap>

Slide 204

Changing the File Name

<configuration>
<system.web>
<siteMap>
<providers>
<remove name="AspNetXmlSiteMapProvider" />
<add name="AspNetXmlSiteMapProvider"
type="System.Web.XmlSiteMapProvider, System.Web, ..."
siteMapFile="Acme.sitemap" />
</providers>
</siteMap>
</system.web>
</configuration>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

25
Microsoft | Services
Slide 205

<siteMapNode> 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 to everyone

<siteMap>
<siteMapNode title="Home" description="" url="default.aspx">
<siteMapNode title="Announcements" url="Announcements.aspx"
description="Information for all employees" roles="*" />
<siteMapNode title="Salaries" url="Salaries.aspx"
description="Salary data" roles="Managers,CEOs" />
<siteMapNode>
</siteMap>

Visible only to Managers


and CEOs

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

26
Microsoft | Services
Slide 207

Enabling Security Trimming

<configuration>
<system.web>
<siteMap>
<providers>
<remove name="AspNetXmlSiteMapProvider" />
<add name="AspNetXmlSiteMapProvider"
type="System.Web.XmlSiteMapProvider, System.Web, ..."
securityTrimmingEnabled="true"
siteMapFile="web.sitemap" />
</providers>
</siteMap>
</system.web>
</configuration>

Slide 208

SiteMapDataSource Properties

Name Description

Provider Provider used to obtain site map data

SiteMapProvider Name of provider used to obtain site map data

ShowStartingNode Specifies whether to show the root node

StartFromCurrentNode Specifies whether starting node should be the root node


(false) or the current node (true). Default = false

StartingNodeOffset Starting node identified by level (default = 0)

StartingNodeUrl Starting node identified by URL

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

27
Microsoft | Services
Slide 209

Hiding the Root Site Map Node

<asp:SiteMapDataSource ID="SiteMap" ShowStartingNode="false"


RunAt="server" />
<asp:TreeView DataSourceID="SiteMap" RunAt="server" />

Web.sitemap
< s i teMap>
< s i teMapNode t itle="Home" description="" u rl="default.aspx">
< s i teMapNode t itle="Training" u rl="Training.aspx"
d e scription="Training for . NET d evelopers">
< s iteMapNode t itle="Programming . NET" u rl="Classes.aspx?id=1"
d e scription="All a bout t he . NET F ramework" / >
< s iteMapNode t itle="Programming A SP.NET" url="Classes.aspx?id=2"
d e scription="All a bout A SP.NET" / >
< s iteMapNode t itle="Programming W eb S ervices" u rl="Classes.aspx?id=3"
d e scription="All a bout W eb s ervices" / >
< / s iteMapNode>
< s i teMapNode t itle="Consulting" u rl="Consulting.aspx"
d e scription="Consulting f or . NET p rojects" / >
< s i teMapNode t itle="Debugging" u rl="Debugging.aspx"
d e scription="Help w hen you n eed i t t he m ost" / >
< / s iteMapNode>
< / s iteMap>

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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

28
Microsoft | Services
Slide 211

Using SiteMapPath

<asp:SiteMapPath RunAt="server" />

Slide 212

Key SiteMapPath Properties

Name Description

CurrentNodeStyle Style used to render the current node

CurrentNodeTemplate HTML template used to render the current node

NodeStyle Style used to render non-current nodes

NodeStyleTemplate HTML template used to render non-current nodes

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

PathSeparatorStyle Style used to render node separators

PathSeparatorTemplate HTML template used to render node separators

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

29
Microsoft | Services
Slide 213

Stylizing SiteMapPath

<asp:SiteMapPath Font-Name="Verdana" Font-Size="10pt" RunAt="server">


<CurrentNodeStyle Height="24px" BackColor="Yellow" Font-Bold="true" />
<NodeStyle Height="24px" />
<PathSeparatorTemplate>
<ItemTemplate>
<asp:Image ImageUrl="~/images/arrow.gif" RunAt="server" />
</ItemTemplate>
</PathSeparatorTemplate>
</asp:SiteMapPath>

Slide 214

Site Map Providers

Site maps are provider-based


Provider interprets site map data and provides it to
SiteMapDataSource controls
Provider also tracks current position and provides it to
SiteMapPath controls
ASP.NET 2.0 ships with one provider
XmlSiteMapProvider
Use custom providers for other data stores

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

30
Microsoft | Services
Slide 215

Site Map API

System.Web.SiteMap represents site maps


RootNode 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

// Write the title of the current node to a Label control


Label1.Text = SiteMap.CurrentNode.Title;

// Write the path to the current node to a Label control


SiteMapNode node = SiteMap.CurrentNode;
StringBuilder builder = new StringBuilder (node.Title);

while (node.ParentNode != null) {


node = node.ParentNode;
builder.Insert (0, " > ");
builder.Insert (0, node.Title);
}

Label1.Text = builder.ToString ();

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

31
Microsoft | Services
Slide 217

SiteMap.ResolveSiteMap

Fired by SiteMapPath controls


Used to perform on-the-fly customization of paths
displayed by SiteMapPath controls
Add nodes to site map for pages that don't appear in the
site map
Change the properties of the current node
Register handler in Application_Start

Slide 218

Lab: Navigation

Exercise 4: Adding Site Navigation to a Web


Site

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

32
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
33
Microsoft | Services
34
Microsoft | Services
Slide 221

 ASP.NET Controls - Introduction

Descend from System.Web.UI.Control class


The class defines minimum set of functionalities, such
as:
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 from


System.Web.UI.HtmlControls.HtmlControl
Map directly to HTML elements supported by most
browsers
Can run on client or server using
runat=server
Controls are lightweight and fast to load
Support databinding
<input runat=”server” id=”lastName” type=”text” />
void Page_Load(object sender, EventArgs e) {
lastName.Value = “Esposito”;
}
<input name=”myName” id=”myName” type=”text” value=”Esposito” />

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

35
Microsoft | Services
Slide 223

HTML Controls - examples

HtmlInputControl
HtmlInputButton
BoxHtmlInputFile
HtmlInputImage
HtmlInputHidden
HtmlInputRadioButton

HtmlContainerControl
HtmlAnchor
HtmlForm
HtmlSelect
HtmlButton
HtmlTable

Slide 224

Example: Uploading a file

<form runat=”server” enctype=”multipart/form-data”>


<input runat=”server” type=”file” id=”upLoader” >
<input runat=”server” id=”UploadButton” type=”submit”
value=”Upload” onserverclick=”UploadButton_Click” />
</form>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

36
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 functionality
than 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
HyperLink
Image
Panel
TextBox
Table
Calendar

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

37
Microsoft | Services
Slide 227

Validation controls

All vaidators on a page are grouped in the Validators


collection
Page.Validate() and control.Validate()
Types of validators:
CompareValidator
CustomValidator
RangeValidator
RegularExpressionValidator
RequiredFieldValidator

Slide 228

Validators (cont.)

BaseValidator class
Properties: ControlToValidate, ErrorMessage, ForeColor,
ValidationGroup
Examples:

<asp:CompareValidator runat=”server” id=”ageValidator”


ControlToValidate=”ageTextBox”
ValueToCompare=”18”
Operator=”GreaterThanEqual ”
Type=”Integer”
ErrorMessage=”Must specify an age greater than 17. ”
/>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

38
Microsoft | Services
Slide 229

Validators: Examples (cont.)

<asp:RegularExpressionValidator runat=”server” id=”emailValidator”


ControlToValidate=”email”
ValidationExpression=”[a-zA-Z_0-9.-]+\@[a-zA-Z_0-9. -]+\.\w+”
ErrorMessage=”Mustbea valid email address.”
/>

<asp:RangeValidator runat=”server” id=”hiredDateValidator”


ControlToValidate=”hired”
MinimumValue=”2000-1-4”
MaximumValue=”9999-12-31”
Type=”Date”
ErrorMessage=”Must be a date after <b>Jan 1, 1999</b>. ”
/>

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 output
caching:
<% @OutputCacheDuration=”60” VaryByParam=”None” %>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

39
Microsoft | Services
Slide 231

An example

Message.ascx
<%@ Control Language=”C#” CodeFile=”Message.ascx.cs”
Inherits=”Message” %>
Message.ascx.cs
public partial class Message : System.Web.UI.UserControl {
public string ForeColor;
public string Text;
}
ASPX file
<%@ Page Language=”C#” CodeFile=”Test.aspx.cs” Inherits=”TestUserCtl ” %>
<%@ Register Src=”Message.ascx” TagName=”Message” TagPrefix=”x” %>
<html><body><form id=”form1” runat=”server”>
<x:Message ID=”Message1” runat=”server” />
</form></body></html>

Slide 232

Lab: Validation

Exercise 5: Validate user input

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

40
Microsoft | Services
Slide 233 – Module 4: ADO.NET

Module 4:
ADO.NET

Slide 234

Overview

Introduction
Data Providers
Data Containers
Data Controls

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
41
Microsoft | Services
42
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

43
Microsoft | Services
Slide 237

Main features

Disconnected data
Connected data access

Slide 238

Types of providers

Types of providers
Managed Providers
•System.Data.SqlClient
•Microsoft.SqlServerCe.Client
OLE DB Providers
ODBC drivers (System.Data.Odbc)
Oracle (System.Data.OracleClient)

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

44
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 place
ConfigurationManager.ConnectionStrings
Web.config file:
<connectionStrings>
<add name=”NWind” connectionString=”... ”
providerName=”System.Data.SqlClient” />
</connectionStrings>

Should be protected
Connection Pooling is enabled by default

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

45
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 metod
Properties:
FieldCount, HasRows, IsClosed, Item, etc.
Methods:
Close, IsDbNull, NextResult, GetValues, Read, GetByte,
GetChar, GetInt32, etc.

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

46
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

47
Microsoft | Services
Slide 245

Data Adapters

Acts as a two-way bridge between a data source and the


DataSet object
Fills DataSet
Submit DataSet’s 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”);

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

48
Microsoft | Services
Slide 247

DataSet

In-memory object with data retrieved through a query


In-memory counterpart of a DBMS database
may 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 each
modified row
ContinueUpdateOnError

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

49
Microsoft | Services
Slide 249

Command Builder

Quick way to generate commands


An example:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = “SELECT employeeid, lastname FROM
Employees”;
cmd.Connection = conn;
adapter.SelectCommand = cmd;
SqlCommandBuilderbuilder = new SqlCommandBui lder(adapter);
And use them in SqlDataAdapter

Slide 250

Useful containers

In System.Data namespace:
DataSet
DataTable
DataRow
DataColumn
DataView
DataRelation

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

50
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, DataSourceID
DataMember
DataTextField, DataTextFormatString, DataValueField
DataKeyField

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

51
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

52
Microsoft | Services
Slide 255

Lab: Data Access and Data Controls

Exercise 6: Basic Data Access


Exercise 7: Creating Master-Detail Web
Pages
Exercise 8: Using the ListView Web Server
Control

Slide 256 – Module 5: LINQ

Module 5:
LINQ

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

53
Microsoft | Services
Slide 257

Overview

Introduction
Examples
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 databases
XML
DataSets
Even available for SharePoint 2010!
Works with all .NET languages
New VB and C# have integrated language support

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

54
Microsoft | Services
Slide 259

Some examples:

Query expression:
var contacts =
from c in customers
where 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 infoset
Get full power of query expressions over XML
Select, where, group by, etc.
Xml Namespaces

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

55
Microsoft | Services
Slide 261

LINQ to SQL

DataContext is the central class


Use code-gen for ORM
SQL is only submitted when needed
Parent-child relationships are respected
Control of deferred loading
Can insert/update/delete
Transactionally, with concurrency checks

Slide 262

LINQ to SQL (cont.)

from c in Application db.Customers.Add(


db.Customers c1);
where c.City == c2.City = “Seattle";
"London" db.Customers.Rem
select ove(c3);
c.CompanyName
LINQ Objects SubmitChanges()
Query

LINQ to SQL

DML or Stored
SQL Rows Procedures
Query

SELECT INSERT INTO Customers…


CompanyName UPDATE Customers …
FROM Cust DELETE FROM Customers
WHERE City = …
'London' SQL Server

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

56
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 and
DetailsView controls

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

57
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
58
Microsoft | Services
59
Microsoft | Services
Slide 267

Introduction

AJAX = Asynchronous JavaScript and XML


clever use of DHTML + JavaScript
A framework for building richer, more
interactive, more personalized web
experiences
Exchange data and not pages with server
v1.0 works on ASP.NET 2.0 and VS 2005
Shipped in Jan as separate download
All 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 assembly
Defines:
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

60
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

Browser “Application” ASP.NET Application

Rendered Page Initial Rendering ASPX Page

(HTML/CSS) (UI + Behavior) <asp:Button runat=“server”


Text=“Submit”
OnClick=“Handler” />

Postback
protected void Handler()
{}
Updated Rendering

.NET Framework 2.0

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

61
Microsoft | Services
Slide 271

Page Developer Scenario with ASP.NET AJAX

Browser “Application” ASP.NET Application

Rendered Page Initial Rendering ASPX Page

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

<asp:UpdatePanel id=“u1” runat=“server”>


<ContentTemplate>
This content can be dynamically updated!
<asp:label id="Lablel1” runat=“server”/>
<asp:button id=“button1” text=“Submit”
runat=“server”/>
<ContentTemplate>
</asp:UpdatePanel>

Async Postback More non-updatable content and controls...

Updated Rendering
(only region in protected void Handler()
{}
UpdatePanel)

Microsoft AJAX Library .NET Framework 2.0

Supporting Scripts

Slide 272

UpdatePanel control

<asp:UpdatePanel> control
Easily define “updatable” regions of a page
Server roundtrips become asynchronous
ASP.NET AJAX handles all the infrastructure
Supports Triggers that allow other controls to fire the
Postback
<asp:UpdatePanel id=“updatepanel1” runat=“server”>
<ContentTemplate>

<!-- This content will be dynamically updated! -->


<asp:Calendar id=“calndr1” runat=“server”/>

<ContentTemplate>
</asp:UpdatePanel>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

62
Microsoft | Services
Slide 273

Showing Progress

UpdateProgress control provides feedback on the


progress of partial-page rendering

<asp:UpdateProgress ID="UpdateProgress1“
runat="server">
<ProgressTemplate>
Please Wait ...
</ProgressTemplate>
</asp:UpdateProgress>

Slide 274

ASP.NET AJAX Control Toolkit

Separate download from core ASP.NET AJAX


Library of free ASP.NET AJAX enabled controls
Download from http://ajax.asp.net

Developed using a collaborative source model


All source freely available with modification license
Both Microsoft & non-Microsoft developers can
contribute

Around 40 controls today

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

63
Microsoft | Services
Slide 275

Control Extenders

Extend ASP.NET controls with ASP.NET AJAX client


behaviors
Encapsulate both client and server behavior
Same familiar programming model as ASP.NET server
controls<asp:AutoCompleteExtender

Slide 276

Lab: ASP.NET AJAX

Exercise 11: Creating a Web Site with


ASP.NET AJAX
Exercise 12: ASP.NET AJAX Extender
Controls

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

64
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
65
Microsoft | Services
66
Microsoft | Services
Slide 279

♦Error handling

In code: try, catch, finally


On Page level: Error event
On Web Application Level:
global.asax
Application_Error event
Server.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 unhandled
exceptions
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

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

67
Microsoft | Services
Slide 281

♦State Management

Introduction
Application
Session state
View State
Caching

Slide 282

State Management: Important Classes

Cache - Implements an automatic scavenging mechanism,


and periodically clears less frequently used contents
HttpApplicationState - Created when the frst request hits
the Web server, and released when the application shuts
down (ad hoc property Application)
HttpContex - Spans the entire lifetime of the individual
request
HttpSessionState - Created when the user makes the frst
request, and lasts until the user closes the session (ad hoc
property Session)
ViewState - Represents the calling context of each page
being generated

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

68
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:
<sessionState> 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!

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

69
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 the


page
StateBag class
Remember about security and performance!
Can be disabled for a web page:
<%@Page EnableVi ewState=”false” %>
Or controls:
<asp:datagrid runat=”server” EnableViewState=”false”>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

70
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 Application
Domain
Don’t work in web garden or web farm scenario

Cache[“MyData”] = value;

Slide 288

Caching Web Pages and sections

ASP.NET output caching


<%@ OutputCache Duration=”30” VaryByParam=”None” %>
Location of a cache
Any, Client, None, DownStream, Server, ServerAndClient
Can be used on page and custom control level
Caching profiles

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

71
Microsoft | Services
Slide 289

♦Security

ASP.NET Processing
Authentication vs. Authorization
Authentication methods
IIS Authentication and Authorization Process
ASP.NET web site configuration
Application pool account and permissions
IIS Built-in accounts
Code Access Security
Global Assembly Cache
Attack Methods
Best Practices

Slide 290

ASP.NET Processing

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

72
Microsoft | Services
Slide 291

Authentication vs. Authorization

Authentication is the process of identification and


validation 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 restrictions
Time, Lockout, Password expired, Privileges
3. Does IIS allow access?
4. Does NTFS allow access?

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

73
Microsoft | Services
Slide 293

Authentication methods

Authentication methods in IIS


Basic
Digest
Integrated Windows
Protocols: 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 Web


application settings
Each ASP.NET Web application also has its own
Web.config file
Within the Web.config file, you can control access to
individual pages or the entire Web site:
<location path=“default.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

74
Microsoft | Services
Slide 295

Web.config: some examples:

Internet web site


<authentication mode="Forms"/>
<forms name="login“ loginUrl="login.aspx" />
<authorization>
<deny users="?"/>
</authorization>

Intranet web site


<authentication mode="Windows"/>
<authorization>
<allow users ="*" />
</authorization>

Slide 296

Security context of thread vs User Principal

Application Pool identity:


NETWORK SERVICE (default)
It is configurable
Usually switched to a domain account
Impresonation
<impersonation enabled=”true” />
ASP.NET user principal
HttpContext.User
Thread.CurrentPrincipal

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

75
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
 A built-inaccount that has a high level of access rights
LocalSystem  Avoid assigning LocalSystem as an application pool
identity
 A built-in
IIS account with low privileges
 Interacts
throughout the network with the computer
Network Service account
 The default application pool identity (recommended)

 A built-inIIS account with lowest privileges


Local Service  Connects anonymously over the network
 Use for local Web applications only

 AnIIS group account, application pool identity accounts


IIS_WPG must be a member of this group
 An IIS account for anonymous IIS access
IUSR_computername
 An IIS account for starting out-of-process applications in
IWAM_computername IIS 5.0 isolation mode
 A built-in
account for running Microsoft ASP.NET worker
ASPNET process in IIS 5.0 isolation mode

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

76
Microsoft | Services
Slide 299

Code Access Security

Define what your code can do…


Fine-grained policy
Fine-grained permissions
Multiple levels of trust
Different apps in the same process can run at different trust levels
Range of named trust levels
Full trust: do anything the process can
High trust: no unmanaged code, still have broad permissions
Medium trust: recommended default
Low trust: basic set of rights
Minimal trust: execute only
in Web.config<trust level =”Medium” originUrl =”” />

Slide 300

Code Access Security: Best Practices

Consider code access security for partial trust


applications.
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.

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

77
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 bit
public 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 /l
start explorer %windir%\assembly

Security: all GAC’ed 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 fake
requests, overloading the system and blocking regular traffc
Eavesdropping - The attacker uses a sniffer to read unencrypted
network packets as they are transported on the network
Hidden-feld tampering - The attacker compromises unchecked (and
trusted) hidden felds stuffed with sensitive data
One-click - Malicious HTTP posts are sent via script
Session hijacking - The attacker guesses or steals a valid session
ID and connects over another user’s session
SQL injection - The attacker inserts malicious input that the code
blissfully concatenates to form dangerous SQL commands

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

78
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 the
clients 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 the
network.
When using SQL authentication, protect credentials in configuration
files.
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.

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

79
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 parameters


accessible on the client-side
Validate all input parameters
Avoid storing sensitive data in ViewState
Encrypt ViewState if it must contain sensitive data

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

80
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 and
MembershipUser classes
Membership class provides base services
MembershipUser class represents users and provides
additional services
Provider-based for flexible data storage

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

81
Microsoft | Services
Slide 309

Membership Schema

Controls

Other Login
Login LoginStatus LoginView Controls

Membership API

Membership MembershipUser

Membership Providers

Windows Auth Provider Other Membership


SqlMembershipProvider Providers

Membership
Data

Other
SQL Server AD/AzMan
Data Stores

Slide 310

The Membership Class

Provides static methods for performing key


membership tasks
Creating and deleting users
Retrieving information about users
Generating random passwords
Validating logins
Also includes read-only static properties for acquiring
data about provider settings

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

82
Microsoft | Services
Slide 311

Key Membership Methods

Name Description

CreateUser Adds a user to the membership data store

DeleteUser Removes a user from the membership data store

GeneratePassword Generates a random password of a specified length

GetAllUsers Retrieves a collection of MembershipUser objects


representing all currently registered users

GetUser Retrieves a MembershipUser object representing a user

UpdateUser Updates information for a specified user

ValidateUser Validates logins based on user names and passwords

Slide 312

The MembershipUser Class

Represents individual users registered in the


membership data store
Includes numerous properties for getting and setting
user info
Includes methods for retrieving, changing, and
resetting passwords
Returned by Membership methods such as GetUser
and CreateUser

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

83
Microsoft | Services
Slide 313

Key MembershipUser Properties

Name Description

Comment Storage for user-defined data

CreationDate Date user was added to the membership data store

Email User's e-mail address

LastLoginDate Date user last logged in successfully

LastPasswordChangedDate Date user's password was last changed

UserId Unique user ID generated by membership provider

UserName User's registered user name

Slide 314

Membership Providers

Membership is provider-based
Provider provides interface between membership
service and physical data store
ASP.NET ships with one provider
SqlMembershipProvider (SQL Server or SQL Server
Express)
Use custom providers for other data stores

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

84
Microsoft | Services
Slide 315

Provider Configuration

Membership providers support a number of


configuration settings
How should passwords be stored (cleartext, hashed,
encrypted)?
Should password recovery be enabled?
Must each user have a unique e-mail address?
Exposed as properties of provider class
Initialized from CONFIG files

Slide 316

Changing Provider Settings

<membership>
<providers>
<remove name="AspNetSqlProvider" />
<add name="AspNetSqlProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, ..."
connectionStringName="RemoteSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
description="Stores and retrieves membership data ..."
/>
</providers>
</membership>

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

85
Microsoft | Services
Slide 317

Login Controls

Control Description

ChangePassword UI for changing passwords

CreateUserWizard UI for creating new user accounts

Login UI for entering and validating user names and passwords

LoginName Displays authenticated user names

LoginStatus UI for logging in and logging out

LoginView Displays different views based on login status and roles

PasswordRecovery UI for recovering forgotten passwords

Slide 318

The Login Control

Standard UI for logging in users


Integrates with membership service
Calls ValidateUser automatically
No-code validation and logins
Also works without membership service
Incorporates RequiredFieldValidators
Highly customizable UI and behavior

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

86
Microsoft | Services
Slide 319

Role Management Service

Role-based security in a box


Declarative access via Web Site Admin Tool
Programmatic access via Roles class
Roles class contains static methods for creating
roles, adding users to roles, etc.
Maps users to roles on each request
Replaces Application_AuthenticateRequest
Provider-based for flexible data storage

Slide 320

Role Management Schema

Controls
Other Login
Login LoginStatus LoginView Controls

Roles API
Roles

Role Providers

SqlRoleProvider Other Role Providers

Roles Data

Other
SQL Server AuthMan
Data Stores

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

87
Microsoft | Services
Slide 321

The Roles Class

Gateway to the Role Management API


Provides static methods for performing key role
management tasks
Creating and deleting roles
Adding users to roles
Removing users from roles and more
Also includes read-only static properties for
acquiring data about provider settings

Slide 322

Key Roles Methods

Name Description

AddUserToRole Adds a user to a role

CreateRole Creates a new role

DeleteRole Deletes an existing role

GetRolesForUser Gets a collection of roles to which a user belongs

GetUsersInRole Gets a collection of users belonging to a specified role

IsUserInRole Indicates whether a user belongs to a specified role

RemoveUserFromRole Removes a user from the specified role

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

88
Microsoft | Services
Slide 323

Role Management Providers

Role management is provider-based


ASP.NET 2.0 ships with two providers
SqlRoleProvider (SQL Server)
WindowsTokenRoleProvider (Windows)
Use custom providers for other data stores

Slide 324

FBA: Best Practices

Use membership providers instead of custom authentication.


Use SSL to protect credentials and authentication cookies.
If you cannot use SSL, consider reducing session lifetime.
Validate user login information.
Do not store passwords directly in the user store.
Enforce strong passwords.
Protect access to your credential store.
Do not persist authentication cookies.
Restrict authentication tickets to HTTPS connections.
Consider partitioning your site to restricted areas and public areas.
Use unique cookie names and paths.

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

89
Microsoft | Services
Slide 325

Lab: Using FBA

Exercise 13: Membership and User Login

Slide 326

Performance Best Practices

Don’t deploy Debug Builds


Use Bath Compilation
Use Output caching
Limit Viewstate usage
Reduce temporary strings
Limit Data access and display
Disable session state if you do not use it
Optimize page loads
Smart state management

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

90
Microsoft | Services
Slide 327

Don’t deploy Debug Build

Deploying a debug build in production impacts


performance
For debug builds
 Pages are not batch compiled
 Extra temporary files are generated
 Compilation takes longer
 Requests do not timeout

Slide 328

Don’t deploy Debug Build (cont.)

To get a release build set <compilation debug=“false” />


in web.config

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

91
Microsoft | Services
Slide 329

Ensure Batch Compilation

Batch compilation is the process by which ASP.NET


compiles all pages within a directory to a single
assembly file which has performance benefits
Certain scenarios lead to creation of multiple assemblies
and should be avoided
 Pages that use different languages (C#,VB, etc.) should be placed in
the different directories
 Updates to pages should be followed by restarting the application

WebApplication
Page1.
aspx
Page2.
aspx Batch Compilation WebApplication.dll
Page3.
aspx

Slide 330

Use Output caching

Output caching is the process by which you identify and


cache parts of a page that are relatively static
How to identify parts that can be cached?
 Relatively static, does not change frequently
 Used frequently
 Expensive to create

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

92
Microsoft | Services
Slide 331

Limit Viewstate Usage

Viewstate is the technique used to persist state changes


of controls across page postbacks
By default it is saved using a hidden form field named
“__VIEWSTATE”
Disable view state if you do not need it
Minimize the number of objects you store in view state
Use tracing to check view state size

Slide 332

Reduce Temporary Strings

Temporary string objects increase the load on the garbage


collector and impact performance
Avoid operations like concatenation, split, etc. that create
temporary string objects
Use StringBuilder if you need a temporary buffer

String

String Concatenation
String Concatenation Is Bad

String Concatenation Is

Final String

Temporary Strings

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

93
Microsoft | Services
Slide 333

Limit Data Access and Display

Accessing and displaying large amounts of data can


increase the load on the application as well as the client
leading to bad user experience
Use a DataReader where possible
Prevent users from requesting too much data
 Allow filtering
 Use paging
 Load on demand
 Limit returned number of rows from SQL Server tables

Slide 334

Disable session state if you do not use it

Session state is used to store and retrieve user specific


data for the duration of the session
Session state impacts performance and should be
disabled where possible
Session state can be disabled at different levels
 Machine Level: Disabled for all applications on the
machine
 Application Level: Disabled for the entire application
 Page Level: Disabled for the page

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

94
Microsoft | Services
Slide 335

Optimize Page Loads

Slow page load time leads to bad user experience


Limit expensive initialization operations to the first time
the page is loaded
Use Page.IsPostback to avoid repeating expensive
initialization operations

Slide 336

Smart State Management

State management enables persistence of information


Information can be persisted between page postbacks,
for the duration of the session or the life of the
application
State can be stored on the client or on the server
Use client-based state management where possible
Consider serialization costs for server-based state
management

_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________
_____________________________________________________________________________________

95
Microsoft | Services
Slide 337

HTTP Modules

Avoid long-running and blocking calls in pipeline code


Consider asynchronous events

96
Microsoft | Services

Das könnte Ihnen auch gefallen