Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science Department

Similar presentations


Presentation on theme: "Computer Science Department"— Presentation transcript:

1 Computer Science Department
Advanced Web Forms Mark Sapossnek CS 594 Computer Science Department Metropolitan College Boston University

2 Prerequisites This module assumes that you understand the fundamentals of C# programming ADO.NET Introduction to ASP.NET and Web Forms This session picks up where the previous ASP.NET/Web Forms session left off.

3 Learning Objectives Assorted topics in ASP.NET
Developing web applications with ASP.NET

4 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

5 IIS Internet Information Server Microsoft’s web server
Foundation for ASP.NET Runs in inetinfo.exe process Also FTP, NNTP, SMTP Shared resources Default location c:\inetpub\wwwroot Internet Services Manager A Microsoft Management Console (MMC) snap-in

6 IIS Virtual Directories
Provides a level of indirection from URL to actual file locations on the server For example, the file for the url: could be mapped to the physical location: d:\myFolder\myAppFolder\foo.asp

7 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Create Controls Developing Web Forms

8 Web Applications What is a Web Application?
All resources (files, pages, handlers, modules, executable code, etc.) within a virtual directory and its subdirectories Configuration files Shared data (application variables) global.asax Scopes user sessions A session is a series of web page hits by a single user within a block of time Shared data (session variables)

9 Web Applications global.asax
Located at application root Can define and initialize application variables and session variables Specify object to create with class, COM ProgID or COM ClassID Be careful: use of shared objects can cause concurrency errors or blocking! <object id="items" runat="server“ scope=“application” class="System.Collections.ArrayList" />

10 Web Applications global.asax
Can contain user-created code to handle application and session events (just like ASP) Application_OnStart, Application_OnEnd Session_OnStart, Session_OnEnd void Application_OnStart() { Application["startTime"]=DateTime.Now.ToString(); } void Session_OnStart() { Session["startTime"]=DateTime.Now.ToString();

11 Web Applications global.asax
Can use code-behind Can contain application-level directives Application Description=“This is my app…” %> Application Inherits=“MyBaseClass” %> Application Src=“Global.cs” %> Visual Studio.NET uses this Import Namespace=“System.Collections” %> Assembly Name=“MyAssembly.dll” %>

12 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

13 Configuration Goal Solution
Provide extensible configuration for admins & developers to hierarchically apply settings for an application Solution Store configuration data in XML text files Format is readable and writable by people and machines

14 Configuration Settings specified in configuration sections, e.g.
Security, SessionState, Compilation, CustomErrors, ProcessModel, HTTPHandlers, Globalization, AppSettings, WebServices, WebControls, etc. Configuration information stored in web.config It is just a file, no DLL registration, no Registry settings, no Metabase settings <!-- web.config can have comments -->

15 Configuration Configuration Hierarchy
Configuration files can be stored in application folders Configuration system automatically detects changes Hierarchical configuration architecture Applies to the actual directory and all subdirectories Root Dir Sub Dir1 Dir2 web.config

16 Configuration web.config Sample
<configuration> <configsections> <add names=“httpmodules“ type=“System.Web.Config.HttpModulesConfigHandler“/> <add names=“sessionState“ type=“...“/> </configsections> <httpModules> <!--- http module subelements go here --> </httpModules> <sessionState> <!--- sessionstate subelements go here --> </sessionState> </configuration>

17 Configuration Configuration Hierarchy
Standard machine-wide configuration file Provides standard set of configuration section handlers Is inherited by all Web Applications on the machine C:\WINNT\Microsoft.NET\Framework\v \config\machine.config

18 Configuration User-defined Settings
Create web.config in appropriate folder <configuration> <appSettings> <add key=“CxnString” value=“localhost;uid=sa;pwd=;Database=foo”/> </appSettings> </configuration> Retrieve settings at run-time string cxnStr = ConfigurationSettings .AppSettings["CxnString"];

19 Configuration Custom Configuration Handlers
Extend the set of section handlers with your own Implement the interface: System.Web.Configuration.IConfigurationSectionHandler Add to web.config or machine.config

20 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

21 Tracing ASP.NET supports tracing Great way to collect request details
Easy way to include “debug” statements No more messy Response.Write() calls! Debug statements can be left in, but turned off Great way to collect request details Server control tree Server variables, headers, cookies Form/Query string parameters Tracing provides a wealth of information about the page Can be enabled at page- or application- level

22 Tracing Methods and Properties
Trace.Write: Writes category and text to trace Trace.Warn: Writes category and text to trace in red Properties Trace.IsEnabled: True if tracing is turned on for the application or just that page Trace.Mode: SortByTime, SortByCategory Implemented in System.Web.TraceContext class

23 Tracing Page-Level Tracing
To enable tracing for a single page: Add trace directive at top of page Page Trace=“True” %> Add trace calls throughout page Trace.Write(“MyApp”, “Button Clicked”); Trace.Write(“MyApp”, “Value: ” + value); Access page from browser

24 Tracing Application-Level Tracing
To enable tracing across multiple pages: Create web.config file in application root Hit one or more pages in the application Access tracing URL for the application <configuration> <trace enabled=“true” requestlimit=“10”/> </configuration>

25 Tracing Tracing Demo Demo: Trace1.aspx
Show information obtained from tracing

26 Tracing Tracing Into A Component
To add tracing to a component: Import the Web namespace: using System.Web; Enable tracing in your class constructor (optional): HttpContext.Current.Trace.IsEnabled = true; Write to trace: HttpContext.Current.Trace.Write(“category”,“msg”);

27 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

28 State Management The Problem
How/where to store data? How can you pass data from page to page? How do we get around HTTP statelessness?

29 State Management Three-Tier Architecture
Client Store the data on one or more of the physical tiers Web Servers Data can be per-user permanent, per-user (session) or per-application Database

30 State Management Client
Client-side state management means this: Client requests an initial page The server generates a HTTP/HTML response that is sent back to the client This response includes data (state) User looks at the response and makes a selection, causing another request to the server This second request contains the data that was sent in the first response The server receives and processes the data Could be same server or different server

31 State Management Client
URL in a hyperlink (<a>) Query string Very visible to users This can be good or bad Hidden form elements Like __VIEWSTATE Cookies Limited to 4K May be blocked by users

32 State Management Web Server (Middle-Tier)
Application variables Shared by all sessions (users) Session variables Still need to pass session id through the client ASP.NET State Service or database Caching Similar to application variables, but can be updated periodically or based upon dependencies

33 State Management Database
Application-level Part of application database design Session-level Custom session state management in database ASP.NET database session state support

34 State Management In ASP.NET
ASP.NET supports both Application-level and Session-level state management Allows you to store state (data) in middle tier

35 State Management Application Variables
Application state is stored in an instance of HttpApplicationState Accessed from Page.Application property Can lock Application object for concurrent use Needed only when changing application variable Again, use this wisely Use in “read-mostly” style Initialize in global.asa Avoid serializing your pages

36 State Management Sessions
What is a session? Context in which a user communicates with a server over multiple HTTP requests Within the scope of an ASP.NET Application HTTP is a stateless, sessionless protocol ASP.NET adds the concept of “session” Session identifier: 120 bit ASCII string Session events: Session_OnStart, Session_OnEnd Session variables: store data across multiple requests ASP.NET improves upon ASP sessions

37 State Management Session Identifier
By default, session id stored in a cookie Can optionally track session id in URL New in ASP.NET Requires no code changes to app All relative links continue to work <configuration> <sessionState cookieless=“true”/> </configuration>

38 State Management Session Variables
ASP stores session state in IIS process State is lost if IIS crashes Can’t use session state across machines ASP.NET stores session state: In process In another process: ASP State NT service In SQL Server database KEY MESSAGE: Session variables are enhanced SLIDE SCRIPT: Used to store state information for a user. For example, a shopping basket. Can use cookies, or be cookieless. In the case of cookieless, every URL output by the ASP is modified automatically to contain a session ID. There’s a service called “ASP State” that listens for requests for state information. By setting up one machine as the “State Server”, and pointing all the other boxes at it, session state can be shared across a web farm. SLIDE TRANSISTION: Let’s look at this in action. ADDITIONAL INFORMATION FOR PRESENTER: <sessionstate inproc="false" server=“AnotherServer" port="42424" /> <sessionstate inproc="false" server=“AnotherServer" port="42424" usesqlserver=“true” />

39 State Management Session Variables
“Live” objects are are not stored in session state Instead, ASP.NET serializes objects out between requests ASP.NET approach provides: Ability to recover from application crashes Ability to recover from IIS crash/restart Can partition an application across multiple machines (called a Web Farm) Can partition an application across multiple processes (called a Web Garden)

40 State Management Application & Session Variables
Demo: ApplicationAndSession.aspx

41 State Management Transfering Control Between Pages
Link to a page Postback Response.Redirect Causes HTTP redirect Tells browser to go to another URL Server.Transfer Like a redirect but entirely on one server Server.Execute Execute one page from another then return control Both pages processed on same server

42 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

43 Caching Many sites spend considerable effort generating the same web pages over and over For example, a product catalog changes overnight, but is accessed tens of thousands of times a day Server-side caching can vastly improve performance and scalability ASP.NET provides support for Page output caching Data caching

44 Caching Page Output Caching
Entire web page output (HTML) is cached Must specify life of cached page (in seconds) Can cache multiple versions of a page, by: GET/POST parameters; use VaryByParam HTTP header; use VaryByHeader E.g. Accept-Language Browser type or custom string; use VaryByCustom OutputCache Duration="60“ VaryByParam="none" %>

45 Caching Partial Page Output Caching
Can cache a portion of a page by placing it in a User Control Can cache multiple versions of a User Control on a page, by property; use VaryByControl

46 Caching Caching in the Browser
Don’t confuse server-side page output caching with how the browser and proxy servers cache the page Use Response.Cache to specify HTTP cache headers Contains a HttpCachePolicy object

47 Caching Data Caching Data cache is similar to application variables
Can cache objects, HTML fragments, etc. Usage pattern: Try to retrieve data If null then create data and insert into cache DataView Source = (DataView)Cache["MyData"]; if (Source == null) { Source = new DataView(ds.Tables["Authors"]); Cache["MyData"] = Source; // Save in cache }

48 Caching Data Caching Cache object is stored on the Page and is an instance of System.Web.Caching.Cache

49 Caching Data Caching Cache may be scavenged: when memory runs low it will be automatically reclaimed Can specify data expiration: absolute time (e.g. midnight), relative (in 1 hour) Cached data can be dependent upon a file or other cache item Cache.Insert("MyData", Source, null, // Expire in 1 hour DateTime.Now.AddHours(1), TimeSpan.Zero); Cache.Insert("MyData", Source, // Dependent on file new CacheDependency(Server.MapPath("authors.xml")));

50 Caching Data Caching Populating a data cache has an inherent race condition: if hit almost concurrently, multiple pages may try to populate the same cache This probably doesn’t matter at all; it’s only significant if the cost to create the data is prohibitive or if there are side effects If it does matter, there are two solutions: Populate the cache in Application_OnStart Synchronize access to the cache

51 Caching Data Caching private static String cacheSynchronize = "myKey";
DataView Source = (DataView)Cache["MyDataSet"]; if (Source == null) { lock (cacheSynchronize) { Source = (DataView)Cache["MyDataSet"]; if (Source == null) { // Have to test again // Open database ... Source = new DataView(ds.Tables["Authors"]); Cache["MyDataSet"] = Source; // Save in cache }

52 Caching Data Caching ASP.NET page state maintenance is great, but __VIEWSTATE can get quite large Why store constant data in __VIEWSTATE? E.g. dropdowns listing countries, states, days of the week, months, product categories, SKUs, etc. Instead, set EnableViewState=false, cache that data on the server, and populate the control from the cache in Page_Load Can cache data or even HTML Use Control.Render() to obtain a control’s HTML

53 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

54 Error Handling .NET Common Language Runtime provides a unified exception architecture Runtime errors done using exceptions VB now supports try/catch/finally ASP.NET also provides declarative application custom error handling Automatically redirect users to error page when unhandled exceptions occur Prevents ugly error messages from being sent to users

55 Error Handling Custom Error Pages
Can specify error pages for specific HTTP status codes in web.config <configuration> <customerrors mode=“remoteonly” defaultredirect=“error.htm”> <error statuscode=“404” redirect=“adminmessage.htm”/> <error statuscode=“403” redirect=“noaccessallowed.htm”/> </customerrors> </configuration>

56 Error Handling Error Events
Can override Page.HandleError to deal with any unhandled exception on that page Global application event raised if unhandled exception occurs Provides access to current Request Provides access to Exception object See HttpApplication.Error event

57 Error Handling Error Event
What do you actually do when an error occurs? Use new EventLog class to write custom events to log when errors occur Use new SmtpMail class to send to administrators

58 Error Handling Writing to Event Log
Import Namespace="System.Diagnostics" %> Assembly name="System.Diagnostics" %> <script language="C#" runat=server> public void Application_Error(object Sender, EventArgs E) { string LogName = "MyCustomAppLog"; string Message = "Url " + Request.Path + " Error: " + this.Error.ToString() // Create event log if it doesn’t exist if (! EventLog.SourceExists(LogName)) { EventLog.CreateEventSource(LogName, LogName); } // Fire off to event log EventLog Log = new EventLog(); Log.Source = LogName; Log.WriteEntry(Message, EventLogEntryType.Error); </script>

59 Error Handling Sending SMTP Mail
Import Namespace="System.Web.Util" %> Assembly name="System.Diagnostics" %> <script language="C#" runat=server> public void Application_Error(object Sender, EventArgs E) { MailMessage MyMessage = new MailMessage(); MyMessage.To = MyMessage.From = "MyAppServer"; MyMessage.Subject = "Unhandled Error!!!"; MyMessage.BodyFormat = MailFormat.Html; MyMessage.Body = "<html><body><h1>" + Request.Path + "</h1>" + Me.Error.ToString() + "</body></html>"; SmtpMail.Send(MyMessage); } </script>

60 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

61 Deployment XCOPY deployment No DLL deployment, registration
Components are placed in .\bin folder No DLL deployment, registration Unless you’re using COM or other DLLs No locked DLLs DLLs are “shadow copied” into a hidden folder .aspx files are automatically compiled Not true for codebehind Update code (.aspx and assemblies) while server is running No need to stop/bounce the server

62 Deployment Applications are isolated Uninstall = delete /s *.*
Each can have their own version of components Uninstall = delete /s *.*

63 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

64 Availability ASP.NET handles failures in user and system code
Detects and recovers from problems Access violations, memory leaks, deadlocks Supports pre-emptive cycling of apps Time and request-based settings

65 Availability Process Model Recovery
ASP.NET runs code in an external worker process – aspnet_ewp.exe Automatic AV/Crash Protection It is also now possible to configure ASP.NET worker process to recover from: Memory Leaks <processmodel memorylimit=“75” /> Deadlocks <processmodel requestqueuelimit=“500” />

66 Availability Preemptive Recycling
ASP.NET optionally supports pre-emptive cycling of worker processes Eliminates need for admins to “kick the server” once a week Can be configured two ways: Time based (reset every n minutes) <processmodel timeout=“60” /> Request based (reset every n requests) <processmodel requestlimit=“10000” />

67 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

68 Security Reasons for Security Security Configuration
Prevent access to areas of your Web server Record and store secure relevant user data Security Configuration <security> tag in web.config file Authentication, Authorization, Impersonation Code Access Security Are you the code you told me you are? Protect your server from bad code

69 Security Authentication
Who are you? Server must authenticate client Client should authenticate server Kerberos does Need a directory to store user accounts NT: Security Accounts Manager Good for intranet usage up to about 40,000 accounts Windows 2000: Active Directory Good for intranet and Internet usage

70 Security IIS Authentication
Anonymous A single W2K/NT account is used for all visitors Basic authentication Standard, commonly supported Password sent in clear text Digest authentication Standard, but not yet common Integrated Windows Authentication NTLM Kerberos (Windows 2000 only) Client certificates Mapped to W2K/NT account

71 Security ASP.NET Authentication
Passport module provided Exposes passport profile API Custom, forms-based authentication Easy to use, with cookie token tracking Enables custom login screen (no popup dialogs) Supports custom credential checks against database, exchange, etc.

72 Security Authorization
Now that I know who you are, here’s what you are allowed to do W2K/NT DACLs (Discretionary Access-Control List) Grant and deny read/write/execute/etc. permission to users or groups of users IIS also provides coarse-grained control Read, write, run script, run executable, directory browsing, script access for virtual directories, directories and files

73 Security ASP.NET Authorization
ASP.NET supports authorization using either users or roles Roles map users into logical groups Example: “User”, “Manager”, “VP”, etc. Provides nice developer/admin separation Developers can perform runtime role checks in code if (User.IsInRole(“Admin”) { }

74 Security Impersonation
IIS authenticates the “user” A token is passed to the ASP.NET application ASP.NET impersonates the given token Access is permitted according to NTFS settings

75 Security Code Access Security
.NET Framework feature Verify the code‘s identity and where it comes from Specify operations the code is allowed to perform

76 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

77 HTTP Runtime The low-level HTTP processing infrastructure
Logical replacement for ISAPI Managed code; runs within an unmanaged host process Aims for 100% availability Asynchronously processes all requests Multithreaded Provides ability to replace/customize/extend the core product Eliminate “black box” magic with ASP/IIS Support other programming abstractions

78 HTTP Runtime Provides built-in thread pool support
No private thread pool required Provides full access to ASP.NET intrinsics Clean object-oriented class APIs No more obscure ISAPI programming Built-in async execution support Enables unwinding of worker threads during the execution of requests

79 HTTP Runtime ASP.NET has a well-factored, layered architecture
Developers can hook in at various levels Replace or modify built-in functionality HttpModules allow intercepting requests Similar to ISAPI filter Used for authentication, state, output caching HttpHandlers allow low-level request handling Object implements IHttpHandler Activated to handle requests Pages and services built on top of IHttpHandler Add modules and handlers in web.config

80 HTTP Runtime ASP.NET Web Forms and Web Services built entirely using the ASP.NET HTTP Runtime No “hidden” tricks or escapes You could build the same….

81 HTTP Runtime HTTP module pipeline Request handler Managed classes
Each module implements a specific interface For example: state management or security All requests are routed through the same pipeline Request handler Multiple request handlers for one application But only one per URL

82 HTTP Runtime Http Context HTTP Handler HTTP Handler HTTP Handler
Application HTTP Module Http Context HTTP Module HTTP Module Managed code ASP+ HTTP Runtime Native code Host (IIS 5, IIS 4, IE)

83 HTTP Runtime HTTPContext
HttpContext is an object that encapsulates all information about an individual Http Request within ASP+ System.Web.HttpContext HttpHandler and HttpModules access to ASP.NET intrinsics via HttpContext “Flowed” throughout request lifetime HttpHandlers and HttpModules can also “add” objects into HttpContext Objects then flowed throughout request

84 HTTP Runtime System.Web.HTTPContext
public class HttpContext { public HttpRequest Request { get; } public HttpResponse Response { get; } public HttpServerUtility Server { get; } public HttpApplication Application { get; } public HttpSession Session { get; } public IPrincipal User { get; } public Cache Cache { get; } public IDictionary Items { get; } public IHttpHandler Handler { get; } public Exception Error { get; } public DateTime TimeStamp { get; } public Object GetConfig(String name); }

85 HTTP Runtime HTTPRequest/HTTPResponse
HttpRequest/HttpResponse objects have been significantly enhanced HttpRequest: 25 new props, 3 methods HttpResponse: 9 new props, 7 methods Great new additions: TextWriter/Stream support Filter Stream support WriteFile

86 HTTP Runtime HttpHandlers
HttpHandlers enable processing of individual Http URLs or groups of URL extensions within an app Analogous to ISAPI Extensions HTTPHandler examples ASP.NET Page Handler ASP.NET Service Handler Server-Side XSL Transformer Image Generator Service

87 HTTP Runtime HttpHandlers
Built as classes that implement the System.Web.IHttpHandler interface ProcessRequest() Method Method that processes individual request IsReusable() Method Indicates whether pooling is supported public interface IHttpHandler { public void ProcessRequest(HttpContext context); public bool IsReusable(); }

88 HTTP Runtime HttpHandler Registration
Compile and deploy .NET Library DLL within “bin” dir under application vroot Register HttpHandler in web.config Ensure that HttpHandler file extension is registered within IIS to xspisapi.dll Hint: Copy/Paste “.aspx” registration entry <configuration> <httphandlers> <add verb=“*” path=“foo.bar” type=“assembly#class”/> </httphandlers> </configuration>

89 HTTP Runtime HttpModules
HttpModules enable developers to intercept, participate or modify each individual request into an application HttpModule Examples: Output Cache Module Session State Module Personalization State Module Custom Security Module

90 HTTP Runtime HttpModules
Built as classes that implement the System.Web.IHttpModule interface public interface IHttpModule { public String ModuleName { get; } public void Init(HttpApplication application); public void Dispose(); }

91 HTTP Runtime HttpModules
HttpModules can use Init() method to sync any HttpApplication Global Application Events Per Request Application Events Application_Start Application_End Application_Error

92 HTTP Runtime Per Request Application Events
Per Request Events (in order): Application_BeginRequest Application_AuthenticateRequest Application_AuthorizeRequest Application_ResolveRequestCache Application_AquireRequestState Application_PreRequestHandlerExecute Application_PostRequestHandlerExecute Application_ReleaseRequestState Application_UpdateRequestCache Application_EndRequest Per Request Transmission Events: Application_PreSendRequestHeaders Application_PreSendRequestContent

93 HTTP Runtime HTTP Module Registration
Compile and deploy .Net Library DLL within “bin” dir under app vroot Register HttpModule in web.config <configuration> <httpmodules> <add type=“assembly#classname”/> </httpmodules> </configuration>

94 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

95 Targeting Uplevel Clients
Goal: Pages render more richly to uplevel clients, but work well in downlevel clients too Page developers can identify target client Page ClientTarget="Uplevel" %> Page ClientTarget="Downlevel" %> Page ClientTarget="Auto" %>

96 Targeting Uplevel Clients Request.Browser
Provides more granular control of what is rendered to a given client Exposes specific client capabilities if (Request.Browser.Frames == True) { // Use frames }

97 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

98 Creating Controls ASP.NET provides two ways to create your own server-side controls User Controls: Essentially a mini .aspx file Formerly called a “Pagelet” Custom Controls: You derive a class from System.Web.UI.Control

99 Creating Controls User Controls
Provide a simple way for page developers to author controls Stored in a .ascx file Not just a server-side include Enables full encapsulation Supports nested controls Separate code namespace Separate code language Can partition work across multiple developers Great way to reuse work across multiple pages and applications

100 Creating Controls Registering User Controls
Registers user control for use on a page Register TagPrefix="Acme“ TagName="Message" Src="pagelet1.aspc" %> ... <Acme:Message runat="server"/>

101 Creating Controls Exposing a User Control Object Model
User controls can expose object model to pages Properties, fields, events, methods Just make them public <script language=“C#" runat="server"> public string Color = "blue“; </script> <font color=<%=Color%>> This is a simple message pagelet </font>

102 Creating Controls Programmatic Use of User Controls
Page.LoadControl(string source) Dynamically instantiates a user control Get and customize an instance: foo = Page.LoadControl("foo.ascx"); foo.color = "red“; Insert into the control hierarchy: myPanel.Controls.Add(foo);

103 Creating Controls Custom Controls
A class that you create Derived from System.Web.UI.Control using System; using System.Web; using System.Web.UI; public class MyControl : Control { protected override void Render(HTMLTextWriter w) { w.Write(“<h1>Control output</h1>”); }

104 Creating Controls Custom Controls
Must implement Render() method Can expose properties, methods and events Should maintain state Should handle postback data Can generate client-side script to do postback Should handle child controls Render them Handle events Can expose and implement templates Can handle data binding

105 Creating Controls Custom Controls vs. User Controls
Good for application-specific UI Good for reuse, encapsulate common UI Easy to build Can be more complex to build Less flexibility, performance, designer support Total flexibility, better performance, and designer support No template support Can support templates

106 Agenda IIS Web Applications Configuration Tracing State Management
Caching Error Handling Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms

107 Developing Web Forms Using Notepad
Incredibly simple: just create .aspx file as a text file, edit, and hit the page That’s how the demos in this module were done Use tracing as a debugging aid

108 Developing Web Forms Using Visual Studio.NET
Create a new project Choose “Web Application” Specify URL of application

109 Developing Web Forms IBuySpy

110 Developing Web Forms Debugging
Basic Debugger ships with the SDK Multi-language Single stack trace Breaks, watches, etc. Visual Studio® Debugger Adds remote debugging support Supports managed/unmanaged debugging

111 Developing Web Forms Debugging
Create web.config file in application root Attach using debugger Set breakpoints Hit page or service <configuration> <compilation debugmode=“true”/> </configuration>

112 Conclusion Deployment IIS Availability Web Applications Security
HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms IIS Web Applications Configuration Tracing State Management Caching Error Handling

113 Resources Quick Start Tutorial ASP.NET Overview Caching Session state Validation Tracing


Download ppt "Computer Science Department"

Similar presentations


Ads by Google