Advanced Asp.Net Concepts And Constructs

50 %
50 %
Information about Advanced Asp.Net Concepts And Constructs

Published on December 5, 2008

Author: mannysiddiqui



This presentation is about some of the advanced and often overlooked features offered by ASP.NET.

IIS and ASP.NET Integration – Deep Dive  HTTP Modules  HTTP Handlers  Virtual Path Provider  URL Rewriting  Response Filters  Configuration Runtime API 

Extending web servers by means of installing  some components  Internet Server API – ISAPI (Microsoft)  Netscape Server API – NSAPI (Netscape) IIS is an ISAPI compliant web server   Extension possible through ISAPI Filters and Extensions (both are Win 32 DLLs) Application Mapping in IIS maps the request to  an ISAPI Extension by mapping the request extension to a Win 32 DLL.

The integration b/w IIS and ASP.NET occurs through the  Application Mapping – ASP.NET is an ISAPI Extension!

IIS   Receives the request  Authenticates the request and attaches a security token (identity) to it.  For authenticated requests, it is the Windows identity of the user connecting to IIS (e.g. Domainusername)  For anonymous requests, it is your old friend IUSR_Machinename or whatever account is specified in IIS for anonymous requests.  Forwards the request along with the token to aspnet_isapi.dll

aspnet_isapi.dll   Since it’s a DLL, it will be mapped into the address space of the web server process which runs under the SYSTEM account! Not good!  That’s why it does not do much in terms of processing the request.  Forwards the request to the ASP.NET Worker Process.

Worker Process   Provides housing for the worker threads  Aspnet_wp.exe  IIS 5.0 and IIS 5.1  The process identity is determined by the <processModel> node in the machine.config file  W3wp.exe  IIS 6.0 – Worker Process Isolation Mode  The process identity is not determined by the <processModel> node; in-fact almost all of the settings defined by this node are ignored.  The process identity is determined by the Application Pool identity.  IIS 6.0 – IIS 5 Isolation Mode  Works like IIS 5

Identities   Process Identity – discussed earlier  Worker Thread Identity!  Why is it needed?  To answer that, think about what would happen if there is no thread identity?  What could be the thread identity?  The thread identity could be one of the following:  Identity of the Worker Process.  Identity passed by IIS to ASP.NET.  Identity specified in the <identity> node in the web.config.

Identities   Thread Identity  How is it determined which identity out of the three will be used?  Identity of the Worker Process  Impersonation is disabled <identity impersonate=“false”/> (the default setting)  Identity passed by IIS  Impersonation is enabled <identity impersonate=“true”/>  Identity specified in the <identity> node in the web.config  Impersonation is enabled and a specific identity has been specified in the web.config file <identity impersonate=“true” userName=“manny” password=“mannypwd”/>

A class that participates in the ASP.NET request  processing pipe-line (by virtue of registering for the events) Provides high level of componentization  ASP.NET implements some of its functionalities  using HTTP modules

Implements the IHttpModule interface 

Configure the module using web.config file  ASP.NET Modules 

Tips/Tricks   Modules are called for each and every request which is handled by ASP.NET for that application; no configuration to run the HTTP module for selective requests  Write custom if-then-else checks in the module code.  The events raised by HTTP modules and the HttpApplication class are captured in the Global.asax  Convention: ModuleName_EventName  Examples: Session_Start, Session_End, CustomModule_MyCustomEvent  That means the custom modules can also raise events and those events can be captured in the Global.asax file!

Tips/Tricks   Did you know that the events raised by modules can also be captured by other modules? How to do that? HttpApplication maintains the modules collection Module name from the config file Event raised by the Session module

Tips/Tricks   HTTP modules are called in the order in which the modules have been defined in the web.config file.  For example, WSS SharePoint hijacks the ASP.NET pipe- line by clearing all of the existing modules and installing a custom module as the very first module! WSS/MOSS module installed as the 1st module in the ASP.NET page processing pipeline

Tips/Tricks   ASP.NET framework changes its behavior slightly for the .asmx requests, which in turn affects the way HTTP modules behave.  Unhandled exception in an ASP.NET web page or an HttpHandler raises the Error event as usual.  Unhandled exception in an ASMX web service gets translated into a SOAP Fault! You would have to write SOAP Extension to deal with it.

Practical uses for HTTP modules   Application wide exception handling

Practical uses for HTTP modules   Referrer tracking

Practical uses for HTTP modules   URL Rewriting

Practical use of HTTP modules   Security  Force the user to change password @ the time of first login.  Force the user to accept the terms and conditions

A class that is the final destination for a request  that comes to ASP.NET Must implement the IHttpHandler interface  ASP.NET uses handlers for implementing most of  its functionality

Use the <httpHandlers> node to register any  handlers There are three ways of using a handler   For processing a custom request (e.g. handler for processing .rdnug files)  For processing requests to an already mapped ASP.NET extension (e.g. image.axd)  Similar to the 2nd option – Directly calling a handler without using any custom or commonly used ASP.NET extensions – generic handler!

Processing a custom request   Allows you to define your own custom extension  Requires changes to IIS! Not good for hosted applications.  Steps required  Implement the IHttpHandler interface on a class  Add a new Application Mapping for the new extension in order for the requests to be re-reroute to ASP.NET  Add the handler to the web.config file  Client syntax would be as follows  http://site/virtualdirectory/test.rdnug

Process an already mapped extension   Allow you to re-use an already mapped ASP.NET extension  No changes to the IIS meta-base; good for hosting environments. is already .axd  Steps required mapped to ASP.NET  Implement the IHttpHandler interface on a class  Add the handler to web.config file by using an already mapped ASP.NET extension  Client syntax would now refer to the path specified in the web.config file in order to invoke the handler  <a href=“image.axd?id=10”/>  Examples  Most common – handler for returning images  Return JavaScript from a common handler  Return CSS files from a common handler – allows to compress the CSS

Generic Handler   Similar to the previous approach but uses .ashx as the extension  It’s a convention to use generic handler instead of reusing any other ASP.NET extensions  Steps required  Implement the IHttpHandler interface on a class  Add the handler to the web.config file  Client syntax would be as follows  Mycustomhandler.ashx?querystring

Problem   ASP.NET processes files that live in the file system.  Adds a dependency! Not good. Solution   Need to abstract away the details of where the pages would be stored and retrieved  Opens up options for storing web site (and related resources) anywhere we want!

VirtualPathProvider to the rescue   New concept in ASP.NET 2.0  Extend a few base classes and override some methods  Part of System.Web.Hosting namespace  Supports  ASP.NET Pages (including master pages)  User controls  Standard web pages (e.g .htm) and images (e.g. .jpg)  Themes in the App_Theme folder  Does not support  The Global.asax file  Web.config files  Site map data used by the XmlSiteMapProvider  Directories that contain assemblies or generate assemblies: bin, App_Code, App_GlobalResources, any App_LocalResources

Implement a custom VirtualPathProvider   Derive a class from System.Web.Hosting.VirtualPathProvider  Must override the following methods  FileExists  public override bool FileExists(string virtualPath)  GetFile  public override VirtualFile GetFile(string virtualPath)  Must override the following methods (if the provider supports directories) – must support directories if supporting Themes  DirectoryExists  public override bool DirectoryExists(string virtualDir)  GetDirectory  public override VirtualDirectory GetDirectory(string virtualDir)  Need to derive classes that derive from the following  VirtualFile  VirtualDirectory  What about the file change notifications?  Easy with the file system based providers (can use FileSystemWatcher class for that purpose). What do to in extensible cases where provider knows where the files are stored?  Need to implement one of the following methods  GetCacheDependency  GetFileHash

Register with ASP.NET   Must be registered with ASP.NET compilation system before any page parsing or compilation occurs.  Normally registered in the Application_Start event in the global.asax file  Or can also be registered in the static AppInitialize method in a public class that lives in the App_Code folder.

Examples   WSS/SharePoint use this concept – SPVirtualPathProvider. The pages live in the WSS/SharePoint content database that ASP.NET has no knowledge about.  Serve web site out of a zip file!   Serve master page from a DLL  haring-Master-Pages-amongst-Applications-by- Embedding-it-in-a-Dll_2E00_.aspx

Problem   We all hate the cryptic URLs visible in the browser window?  What if we could reformat the above URL to look like as follows? Solution   Let the user go to the friendly URL (2nd URL above)  Intercept the incoming request and redirect (on the server) it to the actual URL (1st URL above)  Http Modules to rescue!

Response Filter is just that – an object that filters  the final response before it is sent to the client – note that everything else has already run before the filter is invoked. Anything written to the HttpResponse.Write  method will eventually go through the installed filter. The response filter must be a Stream object.  Added to the Response.Filter property 

Examples   Compress the final output before it is sent to the client  Search pages where some of the text need to be highlighted.  Returning formatted code files (C#, VB.NET, etc) from the server.  Remove white spaces from the final output  Make sure that the HTML output is XHTML compliant 

Gotcha   Filters are not called if the code calls HttpApplication.CompleteRequest  Avoid the following methods b/c they all call HttpApplication.CompleteRequest!  Server.Transfer  Response.End  Response.Redirect  Do use Server.Execute

Used for editing the configuration files @ design  time or runtime. WebConfigurationManager class   Preferred for web applications (Use ConfigurationManager class for Windows applications)  Supports changes to configuration @ design time  Use one of the Open methods to get the Configuration object (examples on next slide)

Configuration Class   Represents a configuration file applicable to a particular computer, application or resource. // Open current application’s (~) web.config file. Pass null for machine level web.config // Pass “/” for root web site’s web.config Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(quot;~quot;); // Open local machine.config file Configuration machineConfig = WebConfigurationManager.OpenMachineConfiguration();  Use GetSection or GetSectionGroup methods for getting access to the configuration sections or configuration section groups. ConfigurationSection class   Returned by the methods of the Configuration and WebConfigurationManager classes.  Cast to the strongly typed objects: HttpModulesSection, HttpHandlersSection, AuthenticationSection, CacheSection, PagesSection, CompilationSection, etc.  Not all sections can be changed; some are hidden @ run time.

 Code Example – Set authentication to Forms Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(quot;~quot;); ConfigurationSection configSection = webconfig.GetSection(quot;system.web/authenticationquot;); AuthenticationSection authSection = configSection as AuthenticationSection; Provided by .NET if (authSection != null) for manipulating config file sections { authSection.Mode = AuthenticationMode.Forms; webconfig.Save(); } Update the <authentication> Write changes to mode to Forms! the web.config file

Issues   Permissions  Need to have appropriate permissions in order to read from or write to the config file(s).  Need Read permission on the parent config files.  Application Domain Restarts  Whenever a setting is changed in the web.config file  May use external configuration files to avoid restarting the application domain for certain sections (configSource attribute)  Whether or not to restart the app domain on the  change of the  external file

Add a comment

Related presentations

Related pages

(Core C# Programming Constructs) (Advanced C# ... -

(Core C# Programming Constructs) (Advanced C# Programming ... Basic Concepts DECISION CONSTRUCTS ... Web Applications with ASP.NET 4.5 Web Applications ...
Read more

Chapter 4. Advanced C# -

Advanced C#. This chapter is ... we cover advanced C# topics that build on concepts explored in ... a general term that captures constructs such as C ...
Read more

ASP.NET with SQL Server Test - Upwork

SQL Server Programming Constructs ; ASP.NET Basics ; ASP.NET ... Advanced ASP.NET Concepts ; Advanced Topics ; Database Programming and Validation ; ADO ...
Read more

ASP.Net Syllabus: ipsr solutions ltd: Authorized Red Hat ...

Creating Conditional and Looping Constructs ... Web Programming Concepts ... Download, syllabus, ...
Read more

Migrating from PHP to ASP.NET -

... Learn about migrating from PHP to ASP.NET ... The upside to ASP.NET's support of OOP concepts means that ASP.NET ... advanced debugging ...
Read more

ASP.Net 4.0 Skills Test, ASP.Net 4.0 Skills Certification

The ASP.Net 4.0 Skills Test can be taken from any computer with an internet ... Advanced ASP.NET Concepts; Advanced Topics; ... SQL Server Programming ...
Read more

2. Microsoft AJAX Library Programming - Advanced ASP.NET ...

You are previewing Advanced ASP.NET AJAX ... It provides objects and programming constructs that we can ... so you’ll see many concepts and types ...
Read more

C# Advanced Topics: Take Your C# Skills to the Next Level ...

... bite-sized video tutorials on advanced C# constructs that ... Please confirm that you want to add C# Advanced Topics: Take Your C# ... ASP. NET, object ...
Read more