Advanced Web Forms Mark Sapossnek CS 594 Computer
Advanced Web Forms Mark Sapossnek CS 594 Computer Science Department Metropolitan College Boston University
Prerequisites w This module assumes that you understand the fundamentals of n n n C# programming ADO. NET Introduction to ASP. NET and Web Forms
Learning Objectives w Assorted topics in ASP. NET w Developing web applications with ASP. NET
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
IIS w Internet Information Server n n n Microsoft’s web server Foundation for ASP. NET Runs in inetinfo. exe process l l n n Also FTP, NNTP, SMTP Shared resources Default location c: inetpubwwwroot Internet Services Manager l A Microsoft Management Console (MMC) snap-in
IIS Virtual Directories w Provides a level of indirection from URL to actual file locations on the server w For example, the file for the url: http: //my. Server/my. Application/foo. asp could be mapped to the physical location: d: my. Foldermy. App. Folderfoo. asp
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Create Controls Developing Web Forms
Web Applications w What is a Web Application? n All resources (files, pages, handlers, modules, executable code, etc. ) within a virtual directory and its subdirectories l l l n Configuration files Shared data (application variables) global. asax Scopes user sessions l l A session is a series of web page hits by a single user within a block of time Shared data (session variables)
Web Applications global. asax w Located at application root w Can define and initialize application variables and session variables n n Specify object to create with class, COM Prog. ID or COM Class. ID Be careful: use of shared objects can cause concurrency errors or blocking! <object id="items" runat="server“ scope=“application” class="System. Collections. Array. List" />
Web Applications global. asax w Can contain user-created code to handle application and session events (just like ASP) n n Application_On. Start, Application_On. End Session_On. Start, Session_On. End void Application_On. Start() { Application["start. Time"]=Date. Time. Now. To. String(); } void Session_On. Start() { Session["start. Time"]=Date. Time. Now. To. String(); }
Web Applications global. asax w Can use code-behind w Can contain application-level directives n n n <%@ Application Description=“This is my app…” %> <%@ Application Inherits=“My. Base. Class” %> <%@ Application Src=“Global. cs” %> l n n Visual Studio. NET uses this <%@ Import Namespace=“System. Collections” %> <%@ Assembly Name=“My. Assembly. dll” %>
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Configuration w Goal n Provide extensible configuration for admins & developers to hierarchically apply settings for an application w Solution n Store configuration data in XML text files l Format is readable and writable by people and machines
Configuration w Settings specified in configuration sections, e. g. n Security, Session. State, Compilation, Custom. Errors, Process. Model, HTTPHandlers, Globalization, App. Settings, Web. Services, Web. Controls, etc. w Configuration information stored in web. config It is just a file, no DLL registration, no Registry settings, no Metabase settings w <!-- web. config can have comments --> n
Configuration Hierarchy w Configuration files can be stored in application folders n Configuration system automatically detects changes w Hierarchical configuration architecture n Applies to the actual directory and all subdirectories Root Dir web. config Sub Dir 1 Sub Dir 2
Configuration web. config Sample <configuration> <configsections> <add names=“httpmodules“ type=“System. Web. Config. Http. Modules. Config. Handler“/> <add names=“session. State“ type=“. . . “/> </configsections> <http. Modules> <!--- http module subelements go here --> </http. Modules> <session. State> <!--- sessionstate subelements go here --> </session. State> </configuration>
Configuration Hierarchy w Standard machine-wide configuration file n n Provides standard set of configuration section handlers Is inherited by all Web Applications on the machine C: WINNTMicrosoft. NETFrameworkv 1. 0. 2914configmachine. config
Configuration User-defined Settings w Create web. config in appropriate folder <configuration> <app. Settings> <add key=“Cxn. String” value=“localhost; uid=sa; pwd=; Database=foo”/> </app. Settings> </configuration> w Retrieve settings at run-time string cxn. Str = Configuration. Settings. App. Settings["Cxn. String"];
Configuration Custom Configuration Handlers w Extend the set of section handlers with your own w Implement the interface: System. Web. Configuration. IConfiguration. Section. Handler w Add to web. config or machine. config
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Tracing w ASP. NET supports tracing n n n Easy way to include “debug” statements No more messy Response. Write() calls! Debug statements can be left in, but turned off w Great way to collect request details n n Server control tree Server variables, headers, cookies Form/Query string parameters Tracing provides a wealth of information about the page w Can be enabled at page- or application- level
Tracing Methods and Properties w Methods n n Trace. Write: Writes category and text to trace Trace. Warn: Writes category and text to trace in red w Properties n n Trace. Is. Enabled: True if tracing is turned on for the application or just that page Trace. Mode: Sort. By. Time, Sort. By. Category w Implemented in System. Web. Trace. Context class
Tracing Page-Level Tracing w To enable tracing for a single page: 1. Add trace directive at top of page l 2. Add trace calls throughout page l l 3. <%@ Page Trace=“True” %> Trace. Write(“My. App”, “Button Clicked”); Trace. Write(“My. App”, “Value: ” + value); Access page from browser
Tracing Application-Level Tracing w To enable tracing across multiple pages: 1. Create web. config file in application root <configuration> <trace enabled=“true” requestlimit=“ 10”/> </configuration> 1. 2. Hit one or more pages in the application Access tracing URL for the application http: //localhost/My. App/Trace. axd
Tracing Demo w Demo: Trace 1. aspx n Show information obtained from tracing
Tracing Into A Component w To add tracing to a component: n Import the Web namespace: using System. Web; n Enable tracing in your class constructor (optional): Http. Context. Current. Trace. Is. Enabled = true; n Write to trace: Http. Context. Current. Trace. Write(“category”, “msg”);
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
State Management The Problem w How/where to store data? w How can you pass data from page to page? w How do we get around HTTP statelessness?
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
State Management Client w Client-side state management means this: n n Client requests an initial page The server generates a HTTP/HTML response that is sent back to the client l n User looks at the response and makes a selection, causing another request to the server l n This response includes data (state) This second request contains the data that was sent in the first response The server receives and processes the data l Could be same server or different server
State Management Client w URL in a hyperlink (<a>) n n Query string Very visible to users l This can be good or bad w Hidden form elements n Like __VIEWSTATE w Cookies n n Limited to 4 K May be blocked by users
State Management Web Server (Middle-Tier) w Application variables n Shared by all sessions (users) w Session variables n n Still need to pass session id through the client ASP. NET State Service or database w Caching n Similar to application variables, but can be updated periodically or based upon dependencies
State Management Database w Application-level n Part of application database design w Session-level n n Custom session state management in database ASP. NET database session state support
State Management In ASP. NET w ASP. NET supports both Application-level and Session-level state management w Allows you to store state (data) in middle tier
State Management Application Variables w Application state is stored in an instance of Http. Application. State w Accessed from Page. Application property w Can lock Application object for concurrent use n Needed only when changing application variable w Again, use this wisely n n n Use in “read-mostly” style Initialize in global. asa Avoid serializing your pages
State Management Sessions w What is a session? n n Context in which a user communicates with a server over multiple HTTP requests Within the scope of an ASP. NET Application w HTTP is a stateless, sessionless protocol w ASP. NET adds the concept of “session” n n n Session identifier: 120 bit ASCII string Session events: Session_On. Start, Session_On. End Session variables: store data across multiple requests w ASP. NET improves upon ASP sessions
State Management Session Identifier w By default, session id stored in a cookie w Can optionally track session id in URL n New in ASP. NET w Requires no code changes to app n All relative links continue to work <configuration> <session. State cookieless=“true”/> </configuration>
State Management Session Variables w ASP stores session state in IIS process n n State is lost if IIS crashes Can’t use session state across machines w ASP. NET stores session state: n n n In process In another process: ASP State NT service In SQL Server database <sessionstate inproc="false" server=“Another. Server" port="42424" /> <sessionstate inproc="false" server=“Another. Server" port="42424" usesqlserver=“true” />
State Management Session Variables w “Live” objects are not stored in session state n Instead, ASP. NET serializes objects out between requests w ASP. NET approach provides: n n 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)
State Management Application & Session Variables w Demo: Application. And. Session. aspx
State Management Transfering Control Between Pages w Link to a page w Postback w Response. Redirect n n Causes HTTP redirect Tells browser to go to another URL w Server. Transfer n Like a redirect but entirely on one server w Server. Execute n n Execute one page from another then return control Both pages processed on same server
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Caching w Many sites spend considerable effort generating the same web pages over and over n For example, a product catalog changes overnight, but is accessed tens of thousands of times a day w Server-side caching can vastly improve performance and scalability w ASP. NET provides support for n n Page output caching Data caching
Caching Page Output Caching w Entire web page output (HTML) is cached w Must specify life of cached page (in seconds) <%@ Output. Cache Duration="60“ Vary. By. Param="none" %> w Can cache multiple versions of a page, by: n n GET/POST parameters; use Vary. By. Param HTTP header; use Vary. By. Header l n E. g. Accept-Language Browser type or custom string; use Vary. By. Custom
Caching Partial Page Output Caching w Can cache a portion of a page by placing it in a User Control w Can cache multiple versions of a User Control on a page, by property; use Vary. By. Control
Caching in the Browser w Don’t confuse server-side page output caching with how the browser and proxy servers cache the page w Use Response. Cache to specify HTTP cache headers n Contains a Http. Cache. Policy object
Caching Data Caching w Data cache is similar to application variables w Can cache objects, HTML fragments, etc. w Usage pattern: n n Try to retrieve data If null then create data and insert into cache Data. View Source = (Data. View)Cache["My. Data"]; if (Source == null) { Source = new Data. View(ds. Tables["Authors"]); Cache["My. Data"] = Source; // Save in cache }
Caching Data Caching w Cache object is stored on the Page and is an instance of System. Web. Caching. Cache
Caching Data Caching w Cache may be scavenged: when memory runs low it will be automatically reclaimed w Can specify data expiration: absolute time (e. g. midnight), relative (in 1 hour) w Cached data can be dependent upon a file or other cache item Cache. Insert("My. Data", Source, null, // Expire in 1 hour Date. Time. Now. Add. Hours(1), Time. Span. Zero); Cache. Insert("My. Data", Source, // Dependent on file new Cache. Dependency(Server. Map. Path("authors. xml")));
Caching Data Caching w Populating a data cache has an inherent race condition: if hit almost concurrently, multiple pages may try to populate the same cache w 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 w If it does matter, there are two solutions: n n Populate the cache in Application_On. Start Synchronize access to the cache
Caching Data Caching private static String cache. Synchronize = "my. Key"; Data. View Source = (Data. View)Cache["My. Data. Set"]; if (Source == null) { lock (cache. Synchronize) { Source = (Data. View)Cache["My. Data. Set"]; if (Source == null) { // Have to test again // Open database. . . Source = new Data. View(ds. Tables["Authors"]); Cache["My. Data. Set"] = Source; // Save in cache } } }
Caching Data Caching w ASP. NET page state maintenance is great, but __VIEWSTATE can get quite large w Why store constant data in __VIEWSTATE? n E. g. dropdowns listing countries, states, days of the week, months, product categories, SKUs, etc. w Instead, set Enable. View. State=false, cache that data on the server, and populate the control from the cache in Page_Load w Can cache data or even HTML n Use Control. Render() to obtain a control’s HTML
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Error Handling w. NET Common Language Runtime provides a unified exception architecture n n Runtime errors done using exceptions VB now supports try/catch/finally w ASP. NET also provides declarative application custom error handling n n Automatically redirect users to error page when unhandled exceptions occur Prevents ugly error messages from being sent to users
Error Handling Custom Error Pages w 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>
Error Handling Error Events w Can override Page. Handle. Error to deal with any unhandled exception on that page w Global application event raised if unhandled exception occurs n n n Provides access to current Request Provides access to Exception object See Http. Application. Error event
Error Handling Error Event w What do you actually do when an error occurs? n n Use new Event. Log class to write custom events to log when errors occur Use new Smtp. Mail class to send email to administrators
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, Event. Args E) { string Log. Name = "My. Custom. App. Log"; string Message = "Url " + Request. Path + " Error: " + this. Error. To. String() // Create event log if it doesn’t exist if (! Event. Log. Source. Exists(Log. Name)) { Event. Log. Create. Event. Source(Log. Name, Log. Name); } // Fire off to event log Event. Log = new Event. Log(); Log. Source = Log. Name; Log. Write. Entry(Message, Event. Log. Entry. Type. Error); } </script>
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, Event. Args E) { Mail. Message My. Message = new Mail. Message(); My. Message. To = "scottgu@microsoft. com"; My. Message. From = "My. App. Server"; My. Message. Subject = "Unhandled Error!!!"; My. Message. Body. Format = Mail. Format. Html; My. Message. Body = "<html><body><h 1>" + Request. Path + "</h 1>" + Me. Error. To. String() + "</body></html>"; Smtp. Mail. Send(My. Message); } </script>
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Deployment w XCOPY deployment n Components are placed in. bin folder w No DLL deployment, registration n Unless you’re using COM or other DLLs w No locked DLLs n n DLLs are “shadow copied” into a hidden folder. aspx files are automatically compiled l n n Not true for codebehind Update code (. aspx and assemblies) while server is running No need to stop/bounce the server
Deployment w Applications are isolated n Each can have their own version of components w Uninstall = delete /s *. *
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Availability w ASP. NET handles failures in user and system code w Detects and recovers from problems n Access violations, memory leaks, deadlocks w Supports pre-emptive cycling of apps n Time and request-based settings
Availability Process Model Recovery w ASP. NET runs code in an external worker process – aspnet_ewp. exe n Automatic AV/Crash Protection w It is also now possible to configure ASP. NET worker process to recover from: n Memory Leaks <processmodel memorylimit=“ 75” /> n Deadlocks <processmodel requestqueuelimit=“ 500” />
Availability Preemptive Recycling w ASP. NET optionally supports pre-emptive cycling of worker processes n Eliminates need for admins to “kick the server” once a week w Can be configured two ways: n Time based (reset every n minutes) <processmodel timeout=“ 60” /> n Request based (reset every n requests) <processmodel requestlimit=“ 10000” />
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Security w Reasons for Security n n Prevent access to areas of your Web server Record and store secure relevant user data w Security Configuration n <security> tag in web. config file w Authentication, Authorization, Impersonation w Code Access Security n n Are you the code you told me you are? Protect your server from bad code
Security Authentication w Who are you? w Server must authenticate client w Client should authenticate server n Kerberos does w Need a directory to store user accounts n NT: Security Accounts Manager l n Good for intranet usage up to about 40, 000 accounts Windows 2000: Active Directory l Good for intranet and Internet usage
Security IIS Authentication w Anonymous n A single W 2 K/NT account is used for all visitors w Basic authentication n n Standard, commonly supported Password sent in clear text w Digest authentication n Standard, but not yet common w Integrated Windows Authentication n n NTLM Kerberos (Windows 2000 only) w Client certificates n Mapped to W 2 K/NT account
Security ASP. NET Authentication w Passport module provided n Exposes passport profile API w Custom, forms-based authentication n Easy to use, with cookie token tracking Enables custom login screen (no popup dialogs) Supports custom credential checks against database, exchange, etc.
Security Authorization w Now that I know who you are, here’s what you are allowed to do w W 2 K/NT DACLs (Discretionary Access-Control List) n Grant and deny read/write/execute/etc. permission to users or groups of users w IIS also provides coarse-grained control n Read, write, run script, run executable, directory browsing, script access for virtual directories, directories and files
Security ASP. NET Authorization w ASP. NET supports authorization using either users or roles w Roles map users into logical groups n n Example: “User”, “Manager”, “VP”, etc. Provides nice developer/admin separation w Developers can perform runtime role checks in code n if (User. Is. In. Role(“Admin”) { }
Security Impersonation w w 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
Security Code Access Security w. NET Framework feature w Verify the code‘s identity and where it comes from w Specify operations the code is allowed to perform
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
HTTP Runtime w The low-level HTTP processing infrastructure n Logical replacement for ISAPI w Managed code; runs within an unmanaged host process w Aims for 100% availability n n Asynchronously processes all requests Multithreaded w Provides ability to replace/customize/extend the core product n n Eliminate “black box” magic with ASP/IIS Support other programming abstractions
HTTP Runtime w Provides built-in thread pool support n No private thread pool required w Provides full access to ASP. NET intrinsics n n Clean object-oriented class APIs No more obscure ISAPI programming w Built-in async execution support n Enables unwinding of worker threads during the execution of requests
HTTP Runtime w ASP. NET has a well-factored, layered architecture n n Developers can hook in at various levels Replace or modify built-in functionality w Http. Modules allow intercepting requests n n Similar to ISAPI filter Used for authentication, state, output caching w Http. Handlers allow low-level request handling n n n Object implements IHttp. Handler Activated to handle requests Pages and services built on top of IHttp. Handler w Add modules and handlers in web. config
HTTP Runtime w ASP. NET Web Forms and Web Services built entirely using the ASP. NET HTTP Runtime n n No “hidden” tricks or escapes You could build the same….
HTTP Runtime w HTTP module pipeline n n Managed classes Each module implements a specific interface l n For example: state management or security All requests are routed through the same pipeline w Request handler n n Managed classes Multiple request handlers for one application l But only one per URL
HTTP Runtime HTTP Handler Application HTTP Module Http Context HTTP Module ASP+ HTTP Runtime Host (IIS 5, IIS 4, IE) Managed code Native code
HTTP Runtime HTTPContext w Http. Context is an object that encapsulates all information about an individual Http Request within ASP+ n System. Web. Http. Context w Http. Handler and Http. Modules access to ASP. NET intrinsics via Http. Context n “Flowed” throughout request lifetime w Http. Handlers and Http. Modules can also “add” objects into Http. Context n Objects then flowed throughout request
HTTP Runtime System. Web. HTTPContext public class Http. Context { public Http. Request public Http. Response public Http. Server. Utility public Http. Application public Http. Session public IPrincipal public Cache public IDictionary } Request Response Server Application Session User Cache Items { { { { get; get; } } } } public IHttp. Handler public Exception public Date. Time Handler Error Time. Stamp { get; } public Object Get. Config(String name);
HTTP Runtime HTTPRequest/HTTPResponse w Http. Request/Http. Response objects have been significantly enhanced n n Http. Request: 25 new props, 3 methods Http. Response: 9 new props, 7 methods w Great new additions: n n n Text. Writer/Stream support Filter Stream support Write. File
HTTP Runtime Http. Handlers w Http. Handlers enable processing of individual Http URLs or groups of URL extensions within an app n Analogous to ISAPI Extensions w HTTPHandler examples n n ASP. NET Page Handler ASP. NET Service Handler Server-Side XSL Transformer Image Generator Service
HTTP Runtime Http. Handlers w Built as classes that implement the System. Web. IHttp. Handler interface public interface IHttp. Handler { public void Process. Request(Http. Context context); public bool Is. Reusable(); } w Process. Request() Method n Method that processes individual request w Is. Reusable() Method n Indicates whether pooling is supported
HTTP Runtime Http. Handler Registration 1. Compile and deploy. NET Library DLL within “bin” dir under application vroot 2. Register Http. Handler in web. config <configuration> <httphandlers> <add verb=“*” path=“foo. bar” type=“assembly#class”/> </httphandlers> </configuration> 3. Ensure that Http. Handler file extension is registered within IIS to xspisapi. dll n Hint: Copy/Paste “. aspx” registration entry
HTTP Runtime Http. Modules w Http. Modules enable developers to intercept, participate or modify each individual request into an application w Http. Module Examples: n n Output Cache Module Session State Module Personalization State Module Custom Security Module
HTTP Runtime Http. Modules w Built as classes that implement the System. Web. IHttp. Module interface public interface IHttp. Module { public String Module. Name { get; } public void Init(Http. Application application); public void Dispose(); }
HTTP Runtime Http. Modules w Http. Modules can use Init() method to sync any Http. Application n n Global Application Events Per Request Application Events w Global Application Events n n n Application_Start Application_End Application_Error
HTTP Runtime Per Request Application Events w Per Request Events (in order): n n n n n Application_Begin. Request Application_Authenticate. Request Application_Authorize. Request Application_Resolve. Request. Cache Application_Aquire. Request. State Application_Pre. Request. Handler. Execute Application_Post. Request. Handler. Execute Application_Release. Request. State Application_Update. Request. Cache Application_End. Request w Per Request Transmission Events: n n Application_Pre. Send. Request. Headers Application_Pre. Send. Request. Content
HTTP Runtime HTTP Module Registration 1. Compile and deploy. Net Library DLL within “bin” dir under app vroot 2. Register Http. Module in web. config <configuration> <httpmodules> <add type=“assembly#classname”/> </httpmodules> </configuration>
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Targeting Uplevel Clients w Goal: Pages render more richly to uplevel clients, but work well in downlevel clients too w Page developers can identify target client <%@ Page Client. Target="Uplevel" %> <%@ Page Client. Target="Downlevel" %> <%@ Page Client. Target="Auto" %>
Targeting Uplevel Clients Request. Browser w Provides more granular control of what is rendered to a given client w Exposes specific client capabilities if (Request. Browser. Frames == True) { // Use frames }
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Creating Controls w ASP. NET provides two ways to create your own server-side controls n User Controls: Essentially a mini. aspx file l n Formerly called a “Pagelet” Custom Controls: You derive a class from System. Web. UI. Control
Creating Controls User Controls w Provide a simple way for page developers to author controls n Stored in a. ascx file w Not just a server-side include w Enables full encapsulation n Supports nested controls Separate code namespace Separate code language w Can partition work across multiple developers w Great way to reuse work across multiple pages and applications
Creating Controls Registering User Controls w Registers user control for use on a page <%@ Register Tag. Prefix="Acme“ Tag. Name="Message" Src="pagelet 1. aspc" %>. . . <Acme: Message runat="server"/>
Creating Controls Exposing a User Control Object Model w User controls can expose object model to pages w Properties, fields, events, methods n Just make them public <script language=“C#" runat="server"> public string Color = "blue“; </script> <font color=<%=Color%>> This is a simple message pagelet </font>
Creating Controls Programmatic Use of User Controls w Page. Load. Control(string source) n Dynamically instantiates a user control w Get and customize an instance: foo = Page. Load. Control("foo. ascx"); foo. color = "red“; w Insert into the control hierarchy: my. Panel. Controls. Add(foo);
Creating Controls Custom Controls w A class that you create w Derived from System. Web. UI. Control using System; using System. Web. UI; public class My. Control : Control { protected override void Render(HTMLText. Writer w) { w. Write(“<h 1>Control output</h 1>”); } }
Creating Controls Custom Controls w w Must implement Render() method Can expose properties, methods and events Should maintain state Should handle postback data n Can generate client-side script to do postback w Should handle child controls n n Render them Handle events w Can expose and implement templates w Can handle data binding
Creating Controls Custom Controls vs. User Controls Custom 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
Agenda w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Developing Web Forms Using Notepad w Incredibly simple: just create. aspx file as a text file, edit, and hit the page w That’s how the demos in this module were done w Use tracing as a debugging aid
Developing Web Forms Using Visual Studio. NET w Create a new project n n Choose “Web Application” Specify URL of application
Developing Web Forms IBuy. Spy w http: //www. ibuyspy. com
Developing Web Forms Debugging w Basic Debugger ships with the SDK n n n Multi-language Single stack trace Breaks, watches, etc. w Visual Studio® Debugger n n Adds remote debugging support Supports managed/unmanaged debugging
Developing Web Forms Debugging 1. Create web. config file in application root <configuration> <compilation debugmode=“true”/> </configuration> 2. Attach using debugger 3. Set breakpoints 4. Hit page or service
Conclusion w w w w IIS Web Applications Configuration Tracing State Management Caching Error Handling w w w w Deployment Availability Security HTTP Runtime Targeting Uplevel Clients Creating Controls Developing Web Forms
Resources w Quick Start Tutorial http: //localhost/quickstart/ASPPlus/default. htm w ASP. NET Overview http: //msdn. microsoft. com/msdnmag/issues/0900/ASPPlus/A SPPlus. asp w Caching http: //msdn. microsoft. com/voices/asp 04262001. asp w Session state http: //msdn. microsoft. com/library/default. asp? URL=/libr ary/welcome/dsmsdn/asp 12282000. htm w Validation http: //msdn. microsoft. com/library/techart/aspplusvalid. htm w Tracing http: //msdn. microsoft. com/library/default. asp? URL=/libr ary/welcome/dsmsdn/asp 01252001. htm
- Slides: 113