programming asp.net 2.0 krishna kumar academic developer evangelist microsoft corp....
TRANSCRIPT
Programming ASP.NET Programming ASP.NET 2.02.0Krishna KumarKrishna KumarAcademic Developer EvangelistAcademic Developer EvangelistMicrosoft Corp.Microsoft [email protected]@microsoft.com
AgendaAgenda
Introduction to Web DevelopmentIntroduction to Web Development
Module 1 – Architecture and Web Module 1 – Architecture and Web FormsForms
Module 2 – User Interface ElementsModule 2 – User Interface Elements
Module 3 – Data BindingModule 3 – Data Binding
Module 4 – State ManagementModule 4 – State Management
Module 5 – Membership and SecurityModule 5 – Membership and Security
Wrap UpWrap Up
Introduction to Web Introduction to Web DevelopmentDevelopment
Browser based ApplicationsBrowser based ApplicationsLittle or no client installLittle or no client install
Platform independentPlatform independent
Standards based – HTTP, [X]HTMLStandards based – HTTP, [X]HTML
Client Server ArchitectureClient Server ArchitectureConventionalConventional
ContemporaryContemporary
HTTPHTTPRequest (Verb, URI, Version, Headers, Request (Verb, URI, Version, Headers, Body)Body)
Response (Status Code, Headers, Body)Response (Status Code, Headers, Body)
Dynamic Web ContentDynamic Web Content
Dynamically generated HTML Dynamically generated HTML requires server hostrequires server host
An engine that exposes an API to emit An engine that exposes an API to emit contentcontent
Traditional hosts on Microsoft Traditional hosts on Microsoft platform include:platform include:
IIS with CGIIIS with CGI
IIS with ISAPIIIS with ISAPI
IIS with ASPIIS with ASP
IIS with ASP.NETIIS with ASP.NET
Module 1a – ASP.NET ArchitectureModule 1a – ASP.NET Architecture
Where does ASP.NET fit Where does ASP.NET fit in?in?
Hosting ASP.NET with IIS6Hosting ASP.NET with IIS6
Demo: Simple .aspx pageDemo: Simple .aspx page
Page CompilationPage Compilation
ASPX page is compiled upon first accessASPX page is compiled upon first accessTemporary ASP.NET filesTemporary ASP.NET files
ASPX is a classASPX is a classInherits from the Page classInherits from the Page classServer side script blocks are added to the class Server side script blocks are added to the class definition (member vars. & fns.)definition (member vars. & fns.)Interspersed script is added to a Render Interspersed script is added to a Render function (executable code)function (executable code)
You work with ASP.NET byYou work with ASP.NET byBuilding additional classesBuilding additional classesExtending Base classesExtending Base classesControlling class generation from .ASPX filesControlling class generation from .ASPX files
Back to the DEMOBack to the DEMO
Code BehindCode Behind
Pages support inheritance from custom Pages support inheritance from custom base classbase class
Base class specified with Inherits directiveBase class specified with Inherits directivePromotes separation of code from presentationPromotes separation of code from presentation
Three options for compiling code behind Three options for compiling code behind classclass
Demand compiled using the ‘codefile’ directive Demand compiled using the ‘codefile’ directive and src placed in the same directory as the and src placed in the same directory as the pagepageDemand compiled and src placed in a directory Demand compiled and src placed in a directory named ~/App_Code at the top level of the named ~/App_Code at the top level of the applicationapplicationPrecompiled and the assembly placed in a Precompiled and the assembly placed in a directory named ~/bin at the top level of the directory named ~/bin at the top level of the applicationapplication
Shadow Copy (~/bin assemblies) Shadow Copy (~/bin assemblies) DEMODEMO
Module 1b – Web Forms & ControlsModule 1b – Web Forms & Controls
Control Based Control Based programmingprogramming
Familiar Paradigm from desktop Familiar Paradigm from desktop application developmentapplication development
A program consists of a collection of controlsA program consists of a collection of controlsEach control knows how to render to the screenEach control knows how to render to the screenThe developer manipulates the state of these The developer manipulates the state of these controls and lets rendering happen implicitlycontrols and lets rendering happen implicitly
ASP.NET brings control based ASP.NET brings control based programming to web appsprogramming to web apps
Server side objects created to represent Server side objects created to represent elements of a pageelements of a pageEach server side object capable of rendering as Each server side object capable of rendering as HTMLHTMLLayered on top of HTTP’s Request/Response Layered on top of HTTP’s Request/Response modelmodelSome desktop paradigms work well – others Some desktop paradigms work well – others must be rethoughtmust be rethought
Demo: Control based .aspx pageDemo: Control based .aspx page
Server side controlsServer side controls
Server side controls:Server side controls:So called as they exist on the server and So called as they exist on the server and provide rendering to the client as HTMLprovide rendering to the client as HTML
Created using ‘runat=server’ attribute on Created using ‘runat=server’ attribute on traditional HTML elements in a .aspx pagetraditional HTML elements in a .aspx page
Can be referenced within server side code Can be referenced within server side code using IDusing ID
Implicitly added as member variables to the Implicitly added as member variables to the generated Page-derived class definitiongenerated Page-derived class definition
State ManagementState ManagementInitial GET request creates controls with default Initial GET request creates controls with default valuesvalues
Subsequent POST back requests create controls Subsequent POST back requests create controls and initialize them with values from the post and initialize them with values from the post bodybody
ViewState for non POSTable informationViewState for non POSTable information
Page LifecyclePage Lifecycle
Each request to a page results in a new Each request to a page results in a new instance of that classinstance of that class
Page goes through a lifecycle during requestPage goes through a lifecycle during request
Exposes events that you can handle to Exposes events that you can handle to interact with the page at various points interact with the page at various points during the requestduring the request
5 primary events called in sequence during a 5 primary events called in sequence during a page’s lifetimepage’s lifetime
Possible to subscribe to these events in 3 waysPossible to subscribe to these events in 3 waysDefining functions named Page_XXX with Defining functions named Page_XXX with AutoEventWireup set to TrueAutoEventWireup set to True
Explicitly subscribing a delegate to that eventExplicitly subscribing a delegate to that event
Overriding virtual function handlers in base classOverriding virtual function handlers in base class
Event SequenceEvent Sequence
Control EventsControl Events
Can handle control events in 2 ways:Can handle control events in 2 ways:Declarative Event SubscriptionDeclarative Event Subscription
Indicating your handler function with the Indicating your handler function with the OnEvent OnEvent attribute in the control’s tagattribute in the control’s tag
Explicit Event SubscriptionExplicit Event SubscriptionConstruct a new instance of the Construct a new instance of the eventHandler delegate and initialize it with eventHandler delegate and initialize it with you handler function pointeryou handler function pointer
Subscribe the delegate to the control’s eventSubscribe the delegate to the control’s event
Hint: If using VS2005, just double click Hint: If using VS2005, just double click the control to get the event handler the control to get the event handler setup automaticallysetup automatically
Detailed Event SequenceDetailed Event Sequence
User ControlsUser Controls
User controls provide a simple way of User controls provide a simple way of defining composite controlsdefining composite controls
You can take any .aspx page and turn it You can take any .aspx page and turn it into a ‘user control’into a ‘user control’
User controls are defined in .ascx pages User controls are defined in .ascx pages and use the @Control directive instead and use the @Control directive instead of @Pageof @Page
Using user controlsUsing user controlsClients reference user controls using the Clients reference user controls using the @Register directive specifying the .ascx @Register directive specifying the .ascx file in the Src attributefile in the Src attribute
DEMODEMO
SummarySummary
Prominence of Web DevelopmentProminence of Web Development
HTTP pipeline / architectureHTTP pipeline / architecture
ASP.NET architectureASP.NET architecture
Page CompilationPage Compilation
Demarcation between presentation Demarcation between presentation and processingand processing
Controls based programmingControls based programming
Page LifecyclePage Lifecycle
Event handlingEvent handling
Module 2 – User Interface ElementsModule 2 – User Interface Elements
MasterPages, Themes, Skins and MasterPages, Themes, Skins and NavigationNavigation
Master PagesMaster Pages
Application wide templatesApplication wide templates
Partitioned into two blocksPartitioned into two blocksBlocks of HTML and code that apply to all pagesBlocks of HTML and code that apply to all pages
Content blocks (Content blocks (ContentPlaceHolder ContentPlaceHolder ))
ContentPlaceHolder ContentPlaceHolder are sections that are filled in by are sections that are filled in by individual pages in the siteindividual pages in the site
Page designates the master via the Page designates the master via the MasterPageFileMasterPageFile property property
Designer and IDE supportedDesigner and IDE supported
Page before and after Master Page before and after Master PagePage
Demo: Master Page DemoDemo: Master Page Demo
Associating PagesAssociating Pages
Can have multiple Master Pages per siteCan have multiple Master Pages per siteAssociate each via MasterPageFile attributeAssociate each via MasterPageFile attributeTo change via code, must be done before or To change via code, must be done before or during Page.PreInitduring Page.PreInit
Can configure all pages in a site to use one Can configure all pages in a site to use one Master PageMaster Page
Pages element in Web.ConfigPages element in Web.Config
Will only apply to pages that use the correct Will only apply to pages that use the correct content content control declarationscontrol declarationsIndividual pages can overrideIndividual pages can override
Relative PathsRelative PathsUse the ASP.NET root path syntax (“~/<ref>”)Use the ASP.NET root path syntax (“~/<ref>”)ASP.NET will expand the URL to be correct ASP.NET will expand the URL to be correct relative from the local folder to the root of the relative from the local folder to the root of the applicationapplication
ThemesThemes
Theme: a great tool for consolidation Theme: a great tool for consolidation of UI elements (CSS, Images, of UI elements (CSS, Images, resources etc.)resources etc.)
A named set of stylesA named set of styles
Each theme has a folder inside Each theme has a folder inside app_themesapp_themes
*Each CSS file in the theme folder *Each CSS file in the theme folder embedded as a link in the rendered embedded as a link in the rendered page*page*
Applying a ThemeApplying a ThemeSet via ‘Theme’ attribute in the Page Set via ‘Theme’ attribute in the Page directivedirective
Theme DEMOTheme DEMO
SkinsSkins
Another way to customize stylesAnother way to customize styles‘‘CSS’ for ASP.NET Server side controlsCSS’ for ASP.NET Server side controls
.skin files are placed inside the named .skin files are placed inside the named Theme foldersTheme folders
Can have multiple skin files in a folderCan have multiple skin files in a folderTheme as a whole is applied by nameTheme as a whole is applied by name
A .skin file contains server side control A .skin file contains server side control declarations with default attributesdeclarations with default attributes
Default skins and ID’d skinsDefault skins and ID’d skinsBy default, .skin properties override local By default, .skin properties override local propertiesproperties
Use @Page 'StyleSheetTheme' for the inverseExempt controls or pages from themes with EnableTheming='false'
Skins DEMOSkins DEMO
NavigationNavigation
Three new controls targeted at site navigation
TreeViewHierarchical rendering with images and text
MenuBoth dynamic and static rendering supported
SiteMapPath'Breadcrumbs' control
All three controls can use SiteMapProvider
Default data source draws from web.sitemapSite map data (for page navigation) is kept in an XML file named “web.sitemap”
Demo: NavigationDemo: Navigation
How it all ties together…How it all ties together…
SiteMapDataSource uses the default SiteMapProvider
Defaults to XmlSiteMapProvider implementation which reads XML data from web.sitemap file
SummarySummary
Master pagesStandard implementation of templated pages
Designer / runtime support
Themes and skinsCollection of pluggable UI elements
Unify images, .css, and control declarations
New navigation controlsStandard implementations of Menu, Tree, and SiteMapPath
Flexible, provider driven (or data source driven)
UI is extremely customizable
Module 3 – Data BindingModule 3 – Data Binding
FundamentalsFundamentals
Data binding is a process of Data binding is a process of populating a control with data from a populating a control with data from a data sourcedata source
Controls that support data binding Controls that support data binding expose-expose-
A property called A property called DataSourceDataSource
A method called A method called DataBindDataBind
To bind data to a control, initialize its To bind data to a control, initialize its DataSource DataSource to a data source and invoke to a data source and invoke its its DataBind DataBind methodmethod
Page code can avoid looping over dataPage code can avoid looping over data
Data Source ControlsData Source Controls
Declarative Data BindingDeclarative Data Binding
Meant to reduce the amount of code written - Meant to reduce the amount of code written - data binding can now be accomplished with no data binding can now be accomplished with no codecode
Declare everything neededDeclare everything neededLet framework do heavy liftingLet framework do heavy lifting
Declarative data source controls to access data Declarative data source controls to access data sourcesource
Declare how to select, update, instert and/or deleteDeclare how to select, update, instert and/or deleteCan provide parametersCan provide parametersParameter sources declaratively chosenParameter sources declaratively chosen
Extensive designer supportExtensive designer supportIntegration with server explorerIntegration with server explorerStandard binding model easily customizedStandard binding model easily customized
New Data Bound ControlsNew Data Bound Controls
GridViewGridViewDisplays a row in a table for each row from data sourceDisplays a row in a table for each row from data sourceSupports automatic paging and sortingSupports automatic paging and sorting
RepeaterRepeaterDisplays multiple items for each row from data sourceDisplays multiple items for each row from data sourceData and layout defined via templatesData and layout defined via templates
DataListDataListDisplays one cell in table for each row from data sourceDisplays one cell in table for each row from data sourceData and layout defined via templatesData and layout defined via templates
DetailsViewDetailsViewDisplays one row from data sourceDisplays one row from data sourceLayout predefined in HTML tableLayout predefined in HTML table
FormsViewFormsViewDisplays one row from data sourceDisplays one row from data sourceData and layout defined via templatesData and layout defined via templates
Demo: Data BindingDemo: Data Binding
New Data Bound ControlsNew Data Bound Controls
ParametersParametersData source controls can accept parametersData source controls can accept parameters
Parameter sources are declarativeParameter sources are declarativeValues automatically readValues automatically readParameter types depend upon source of valueParameter types depend upon source of value
Parameter typesParameter typesControlParameterControlParameter
Value retrieved from the property of any server control on Value retrieved from the property of any server control on the pagethe page
CookieParameterCookieParameterValue retrieved from the cookie in requestValue retrieved from the cookie in request
FormParameterFormParameterValue retrieved from HTTP POST variableValue retrieved from HTTP POST variable
ProfileParameterProfileParameterValue retrieved from Client profile informationValue retrieved from Client profile information
QueryStringParameterQueryStringParameterValue retrieved from QueryStringValue retrieved from QueryString
SessionParameterSessionParameterValue retrieved from Client SessionValue retrieved from Client Session
Parameters – SqlDataSource - Parameters – SqlDataSource - TextText
Bound parameters can be used to populate Bound parameters can be used to populate any of the parameters in a data sourceany of the parameters in a data source
Parameters most common along with Parameters most common along with accompanying expressionaccompanying expression
TemplatesTemplates
Allows customization of databound controlsAllows customization of databound controlsCustomize layoutCustomize layout
Customize dataCustomize data
Customize layout by choosing markup in Customize layout by choosing markup in templatetemplate
Customize data by choosing data binding Customize data by choosing data binding expressionsexpressions
<%# Eval () %> for read only data<%# Eval () %> for read only data
<%# Bind () %> for editable data<%# Bind () %> for editable data
Different templates for viewing, editing, Different templates for viewing, editing, insertinginserting
Well known CWell known CommandName ommandName to switch modesto switch modes
TemplatesTemplates
Connection String StorageConnection String Storage
ConnectionStrings section in ConnectionStrings section in Web.ConfigWeb.Config
New <%$ %>syntax for retrieving config New <%$ %>syntax for retrieving config file valuesfile values
SummarySummaryMost controls in ASP.NET can have data bound to Most controls in ASP.NET can have data bound to themthemDeclarative model provides a higher order Declarative model provides a higher order framework for data bindingframework for data bindingDeclarative data sourcesDeclarative data sources
Reduce code, move data access code into frameworkReduce code, move data access code into framework
Data BindingData BindingImplicit with declarative data sources Implicit with declarative data sources
New rich data controlsNew rich data controlsSeveral new controls including the GridView and Several new controls including the GridView and DetailsViewDetailsView
ParametersParametersEach data source is completely customizable with Each data source is completely customizable with parametersparameters
TemplatesTemplatesNew DataBinding Syntax – <%# Eval() %> and <%# New DataBinding Syntax – <%# Eval() %> and <%# Bind() %>Bind() %>
Connection String storageConnection String storageNew storage location in web.configNew storage location in web.config
Module 4 – State ManagementModule 4 – State Management
Client stateClient state
Keeping track of client activity, as they move Keeping track of client activity, as they move between different physical pages in your ASP.NET between different physical pages in your ASP.NET applicationapplication
How to accumulate and maintain state between page How to accumulate and maintain state between page invocationsinvocations
Hard problem to solve since HTTP is a stateless protocolHard problem to solve since HTTP is a stateless protocol
Various ways of storing state on behalf of clientsVarious ways of storing state on behalf of clientsSessionSession
ProfilesProfiles
Session StateSession State
Session state is used to store individual data for a user Session state is used to store individual data for a user during application transactionduring application transaction
Session state is scoped by a single client session, and is tagged Session state is scoped by a single client session, and is tagged with a unique Session IDwith a unique Session ID
The session ID is transmitted between client and server using The session ID is transmitted between client and server using cookies (or mangled URLs if cookieless mode is enabled)cookies (or mangled URLs if cookieless mode is enabled)
Accessed through the Accessed through the Session Session property of the page, which property of the page, which references the current references the current HttpSession HttpSession object provided by the HTTP object provided by the HTTP runtimeruntime
Works regardless in both single page and multiple page Works regardless in both single page and multiple page programming modelsprogramming models
Demo: SessionDemo: Session
Improvements in session state in Improvements in session state in ASP.NETASP.NET
Several improvements to the way Several improvements to the way session state works in ASP.NET 2.0session state works in ASP.NET 2.0
Can avoid relying on cookies to track Can avoid relying on cookies to track clientsclients
Cookieless mode of ‘autodetect’Cookieless mode of ‘autodetect’
Can configure to survive process Can configure to survive process shutdownshutdown
Can configure to work across machines Can configure to work across machines in a web farmin a web farm
Fully extensible provider based modelFully extensible provider based model
Pluggable ID generatorPluggable ID generator
Autodetect cookieless Autodetect cookieless modemode
Session key maintained with Session key maintained with cookiescookies
Session key maintained with URL Session key maintained with URL ManglingMangling
ProfileProfile
Per-user data storage that is persistentPer-user data storage that is persistentProfile prover manages persistenceProfile prover manages persistence
Keys off of authenticated userKeys off of authenticated userOptionally supports anonymous usersOptionally supports anonymous users
Supports strongly typed property data – usage easier than Supports strongly typed property data – usage easier than SessionsSessions
Working with profiles:Working with profiles:Define the properties for the Profile inside web.configDefine the properties for the Profile inside web.config
The above properties are now available as properties on the The above properties are now available as properties on the Profile Profile property of the Pageproperty of the Page
Accessing profile Accessing profile informationinformation
Demo: ProfileDemo: Profile
Saving profile dataSaving profile data
Profile data is saved automaticallyProfile data is saved automaticallySaved after every page requestSaved after every page request
By default, a local SQL Server 2005 database file By default, a local SQL Server 2005 database file is generated (under App_Data) with ASP.NET is generated (under App_Data) with ASP.NET tables to store profile and membership tables to store profile and membership informationinformation
Migrating anonymous profile Migrating anonymous profile datadata
Transition from unauthenticated to Transition from unauthenticated to authenticated fires eventauthenticated fires event
Opportunity to transfer profile Opportunity to transfer profile information from anonymous user to information from anonymous user to authenticated userauthenticated user
SummarySummary
Client State ManagementClient State ManagementSessionsSessions
Session state is client-specific tied to Session state is client-specific tied to browser sessionbrowser session
ProfilesProfilesIs client-specific tied to authenticated userIs client-specific tied to authenticated user
Can be tied to anonymous userCan be tied to anonymous user
Module 5 – Membership and SecurityModule 5 – Membership and Security
OutlineOutline
SecuritySecurity
MembershipMembership
Security ControlsSecurity Controls
Membership ProviderMembership Provider
Role ProviderRole Provider
Security in ASP.NETSecurity in ASP.NET
ASP.NET provides security features in ASP.NET provides security features in addition to those provided by IISaddition to those provided by IIS
Oriented around client authenticationOriented around client authentication
Several method available for integrating Several method available for integrating authentication into your pagesauthentication into your pages
Managed through web.configManaged through web.config
Accessing authenticated client Accessing authenticated client informationinformation
The The User User property of the Page class property of the Page class provides access to current client provides access to current client informationinformation
Authentication and Authentication and AuthorizationAuthorization
Authentication ModesAuthentication ModesMode=NoneMode=None
Mode=WindowsMode=Windows
Mode=FormsMode=Forms
Authorizing clientsAuthorizing clientsAuthorization element used to describe which Authorization element used to describe which clients are granted accessclients are granted access
Supports sub elements allow and denySupports sub elements allow and denyUsers, roles, verbsUsers, roles, verbs
? represents anonymous? represents anonymous
* represents all clients* represents all clients
The first match found (allow or deny) The first match found (allow or deny) determines authorizationdetermines authorization
Windows AuthenticationWindows Authentication
Users credentials defined in active Users credentials defined in active directorydirectory
Leverage IIS to perform authenticationLeverage IIS to perform authenticationIIS challenges browser by sending a 401 status IIS challenges browser by sending a 401 status codecode
IIS forwards the username to ASP.NETIIS forwards the username to ASP.NET
Forms AuthenticationForms Authentication
Common approach for performing Common approach for performing application-level authenticationapplication-level authentication
Application manages storage of Application manages storage of credentialscredentials
Application handles authenticationApplication handles authentication
FormsAuthenticationFormsAuthentication class class
Credential Management and storageCredential Management and storage
Security ‘providers’ for common Security ‘providers’ for common taskstasks
Membership providersWorks with xxMembershipProvider to simplify common tasks in building security infrastructure
CreateUserDeleteUserChangePasswordValidateUser
Role providersxxRoleProvider implements common role-based authorization features
CreateRoleIsUserInRoleGetAllRolesGetRolesForUser
Several new controls generate large pieces of security UI
Example: Login controlExample: Login control
Building a login page now consists of:Building a login page now consists of:
How it works…How it works…
Where’s the data?Where’s the data?
Membership controlsMembership controls
Several new controls available that tap into the membership and role providers
<asp:Login ... />login authentication form
<asp:LoginView ... />alternate views based on identity
<asp:PasswordRecovery ... />password retrieval form (only with un-hashed passwords)
<asp:LoginStatus ... />Status and hyperlink to login/logout based on the state
<asp:LoginName ... />displays username for authenticated users
<asp:CreateUserWizard ... />form for entering new users
<asp:ChangePassword ... />form for changing password
Demo: Authentication ControlsDemo: Authentication Controls
Controls rely on providerControls rely on provider
Role based authorizationRole based authorization
Useful to develop pages by querying the Useful to develop pages by querying the current client’s role membershipcurrent client’s role membership
Avoids hard coded user names checksAvoids hard coded user names checks
Can be used interchangeably with windows Can be used interchangeably with windows group/user model through group/user model through IPrincipal.IsInRole()IPrincipal.IsInRole()
DEMODEMO
SummarySummary
IIS security sits on top of ASP.NET securityASP.NET provides a rich authentication frameworkASP.NET enables site level management of securityNew membership provider + security controls
Greatly simplifies building complex security UIs
Common infrastructure to 'do it right'
Pluggable
Integrated role support
© 2005 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.
Thank You.Thank You.
Please turn in the reviews!Please turn in the reviews!