Skip to main content

Professional ASP .Net page 6

· Session Management In ASP .Net

There are two things to consider regarding the Session in the ASP .Net:

1) Web Farm Support: When an ASP .Net application is deployed on more than one web server, user's session can be maintained out-of-process using Windows NT Services (in separate memory from ASP .Net) and in SQL Server. In both cases all the web servers can be configured to share a common Session store. So, as users get routed to different servers, each server is able to access that user's Session data.

2) Cookieless Mode: To use Session state the client and web server need to share a key that the client can present to identify its Session data on subsequent requests. ASP .Net (like ASP) shared this key with the client through an HTTP cookie. When some user do not accept the HTTP cookies, in that case ASP .Net sends the client Session ID with the URL, and when client sends a request it also attach that Session ID with the requesting URL to server. Server can extract that ID from the URL to identify the user's Session data.

· For a class instance to be stored in out-of-process Session state, the class must be marked with the [Serializable] attribute.

· Unlike Session, however, Application does not support the concept of storing data separate from the ASP .Net process. Instead, Application stores its data in process with ASP .Net. If the ASP .Net process is recycled Application data is lost.

· Since Application is accessible in a multi-user environment, it is likely to happen that two or more user intend to update the same Application variable value at the same time. To prevent you have to Lock and Unlock mechanism.

Application.Lock()

Application("HitCounter") = 1

Application.UnLock()

If you do not explicitly call UnLock, ASP .Net will call it when the application completes the request, the request times out or an un-handled error occurs.

· Cache – Managing Transient State

Cache works same as Application with more added features. Items stored in the cache can be dependent on the other items. When those other item is changed the dependent items become invalid and removed from the Cache. The Cache supports allow us to run code when items are removed from the Cache. Unlike Application, Cache automatically Lock-UnLock for concurrency control implicitly. Cache also manages resource load. The Cache supports two methods of inserting items:

1) Implicit: Same as Application:

Cache("Name") = "John"

2) Explicit: Using the Insert method, it allows us to set up special relationship such as dependencies:

Cache.Insert("Name", "John", Nothing)

The Cache also supports an Add method. The Add method behaves similar to Insert, with the exception that it will only add them item to the Cache if it does not already exist – whereas the Insert method will always add the item into the Cache, even if it already exists.

Items in the Cache can be invalidated on File-Based, Key-Based or Time-Based criteria. In case of File-Based expiration when a file is changed in the Cache, all the dependent items to that file also become invalid. In case of Key-Based expiration, if a master key is becomes invalid, all the child keys also become invalid. In Time-Based expiration you can create dependencies on time values. You can set the time (duration) of an item to be invalid with expiration of that time period.

Cache.Insert ("UserData", ObjDataSet, Nothing,

DateTime.Now.AddMinutes(60), TimeSpan.Zero)

Cache additionally supports a callback capability. The callback allows you to run your code when as item is removed from the cache, giving you the opportunity to add it back.

· An HTTP module is the equivalent of IIS's ISAPI filter concept. An HTTP module gives us an opportunity to work with the request before it is serviced by an ASP .Net page or web service or custom HTTP Handler, and again before the response is sent to the client.

· ASP .Net application events are multi-cast events. This means that we can have both an HTTP module and global.asax respond to the same event. ASP .Net supports 18 applications events, and also allows you to add your own custom events.

· Some Commonly Used Application Events

1) Application_OnBeginRequest: This event is raised on each request that ASP .Net handles. We can use this event to execute code before any process for the request occurs.

2) Application_OnEndRequest: Once the request is complete, this is the last event raised that allows us to affect the application response before we send the HTTP headers and body.

3) Application_OnStart

4) Application_OnEnd

5) Session_OnStart

6) Session_OnEnd

7) Application_Error: This event is raised whenever an unhandled application error occurs. This event allows us to catch all unhandled exceptions for the entire application.

8) Application_OnDisposed: This event is raised when the ASP .Net application is eventually shut down and CLR removes the application from memory.

· By default ASP .Net enables response buffering – this simply means the server will not begin sending data to the requestor until all the data is ready. However, if buffering is disabled, the response can be sent as data becomes available.

· Writing Error To Windows Event Log

Import System.Diagnostics

Public Sub Application_Error (Sender As Object, E As

EventArgs)

Dim LogName As String = "Web_Errors"

Dim Message As String

Message = Server.GetLastError.ToString

' Create event log if it does not exist

If (Not EventLog.SourceExists(LogName)) Then

EventLog.CreateEventSource(LogName, LogName)

End If

Dim Log As New EventLog

Log.Source = LogName

Log.WriteEntry (Message, EventLogEntryType.Error)

End Sub

· Using Static Variables To Store Application Level Data

The Classname attribute of the Application directive in the global.asax allows you to control the name of the class generated for your global.asax code when it is compiled. You can define a static type variable in the global.asax class and can use it through the class name.

<%@ Application Classname="CommerceApplicaton" %>

<Script runat="server">

Public Shared Discount As Interger = 10

</Script>

Now you can use it as:

Dim TempDis As Integer

TempDis = CommerceApplication.Discount

· Using Your Own Base Class For global.asax

The Inherits attribute of the global.asax application directive allows you to name a .Net class that global.asax will use as the base class for all compiled instances of global.asax. To use Inherits, you first need to create your own custom class that inherits from the HttpApplication class. After that you can inherit it in global.asax as:

<%@ Application Inherits = "MyClass" %>

· Mapping File Extensions To ASP .Net

For example, instead of using the extension .aspx for ASP .Net pages we decided to use the extension .wrox. To do this:

1) First, we must create the following new entry in the Web.Config or Machine.Config files

<configuration>

<system.web>

<httpHandlers>

<add verb="*" path="*.wrox" type =

"System.Web.UI.PageHandlerFactory.System.Web" />

</httpHandlers>

</system.web>

</configuration>

2) Second, we must configure IIS to send requests with the extension .wrox to ASP .Net by mapping our custom extensions into ISAPI extensions. ISAPI is a low-level API that lets custom application plug into IIS. ASP .Net uses an ISAPI named aspnet_isapi.dll. The ASP .Net ISAPI simply takes the entire request from IIS and hands it to ASP .Net. If you want ASP .Net to handle .wrox extension, you need to map it onto the aspnet_isapi.dll so that IIS sends the request to ASP .Net.

· Asynchronous Application Events

ASP .Net code is executed in an ASP .Net worker process, not in the IIS process. Within this worker process, threads are used to execute code. ASP .Net creates and manages a ThreadPool, increasing and decreasing the number of threads as required throughout the life of the application. This is in contrast to ASP, which used a fixed number of threads. In some cases, application code such as network I/O can potentially stall threads in the ASP .Net process. This is because the ASP .Net thread has to wait (it is blocked) until this slow operation is complete. When a thread is blocked, it cannot be used to service requests. Coding the event to be asynchronous will free the ASP .Net worker thread to service other requests until the code executed on the asynchronous thread completes.

· In the classic ASP all application configuration information is stored in a binary repository called the Internet Information Services (IIS) metabase. While the ASP .Net uses a simple but powerful XML-based configuration system. ASP .Net configuration system supports two type of configuration file:

1) Server Configuration: Server configuration information is stored in a machine.config, which represents the default settings used by all ASP .Net web application. A single machine.config file is installed for each version of ASP .Net installed.

2) Application Configuration: Application configuration information is stored in a web.config file, which represents the settings for an individual ASP .Net application. web.config overrides the settings in machine.config.

Settings in IIS metabase via the IIS MMC, do not effect your ASP .Net applications. ASP .Net configuration setting changes are immediate and do not require the web server to be restart to apply the changes. When a change is detected in either machine.config or web.config file (by listening for file change notification events provided by the operating system), it automatically applied. All web.config application configuration files inherit from machine.config, any configuration section handlers declared in machine.config are automatically available within web.condig.

· Common Configuration Settings

· <system.web>

<httpRuntime

executionTimeout="90"

maxRequestLength="4096"

minFreeThreads="8"

appRequestQueueLimit="100" />

</system.web>

· <system.web>

<pages buffer="true"

enableSessionState="true"
enableViewState="true"

smartNavigation="false"

pageBaseType="System.Web.UI.Page" />

</system.web>

· The application settings section <appSettings/>, allows you to store you custom application specific configuration details in the web.config.

<configuration>

<appSettings>

<add key="DSN"

value="server=sqll;uid=cust;pwd=net/>

</appSettings>

</configuration>

Now you can use it in your page as:

Dim Dsn As String =

ConfigurationSettings.AppSettings("DSN")

· <system.web>

<sessionState

mode="InProc | SQLServer | StateServer | Off"

sqlConnectionString=". . ."

cookieless="false"

timeout="20" />

</system.web>

Individual applications can be configured to support either cookie or cookieless statesm, but not both.

· Tracing: You can enable page tracing by adding a directive to the top of the ASP .Net page:

<%@ Page Trace="true" %>

You can enable application level tracing in web.config:

<system.web>

<trace

enabled="true"

requestLimit="10"

pageOutput="false"

traceMode="SortByTime | SortByCategory"

localOnly="true" />

</system.web>

When tracing is not enabled, tracing elements (such as Trace.Write()) are ignored and do not affect the performance of the application.

· When an unhandled exception is occurs, ASP .Net displays a detailed error page. You can control this via configuration settings:

<system.web>

<customErrors mode="Off" defaultRedirect =

"/defaultError.aspx>

</system.web>

Off: ASP .Net will always use ASP .Net rich error page.

On: ASP .Net will use user-defined error page.

RemoteOnly: ASP .Net error page will be shown to local user only. Remote user will be redirected to page set in defaultRedirect attribute.

You can also send users to a custom error page depending upon the type of error that occurred. For example, in case of 404 Not Found.

<customErrors . . .>

<error statusCode="404" redirect="/FileNotFound.htm">

</customErrors>

· Internationalization And Encoding: The settings defined within <globalization> allow us to configure the culture and encoding options.

<system.web>

<globalization

requestEncoding="utf-8"

responseEncoding="utf-8"

culture="en-GB" (For British English)

/>

</system.web>

· Compilation Options: The settings defined in the <compilation> section of machine.config allow you to control various compilation features like default language, debug options and this is where you can also add additional CLR compilers, such as COBOL or Perl. You can also name the assemblies here that ASP .Net will link to when compiling ASP .Net application files.

<system.web>

<compilation debug="false" explicit="true"

defaultLanguage="vb">

<compilers>

<compiler language="C#;cs;csharp"

extension=".cs" />

</compilers>

<assemblies>

<add | remove assembly="System"/>

</assemblies>

</compilation>

</system.web>

You can use <remove> tag of <assemblies> element to remove an assembly, which is referenced in machine.config and you do not need it in your application compilation process. You can remove it in web.config for your application.

· HTTP Handlers: ASP .Net builds upon an extensible architecture known simply as the HTTP runtime. The runtime is responsible for handling requests and sending responses. A request is assigned to ASP .Net from IIS. ASP .Net then examines entries in the <httpHandlers> secion, based on the extension (such as .aspx) of the request to determine which handler the request should be routed to. You can also implement your custom handlers that can process your specific request. For this first you have to create your own HTTP Handler class which implements IHTTPHandelr interface. Now you can build an assembly using this handler class and add a entry of the handler into the configuration file as:

<system.web>

<httpHandlers>

<add verb="*" path="*.wrox"

type="Simple.MyHandler,

Simple (this is assembly name) />

</httpHandlers>

</system.web>

After that you also have to map the extension (.wrox) into

IIS. Now all request having extensions .wrox is handled and processed by this handler.

· HTTP Modules: Whereas HTTP Handlers allow you to map a request to a specific class to handle the request, HTTP Modules act as filters that you can apply before the handler sees the request or after the handler is done with the request. ASP .Net makes use of modules for cookieless session state, output caching and several security-related features.

· Configuring The ASP .Net Worker Process: Unlike ASP, ASP .Net runs in a separate process from IIS. The process known as aspnet_wp.exe. ASP .Net used IIS only to receive requests and to send responses (as a request/response broker). IIS is not involved in executing any ASP .Net code. The <processModel> section of machine.config is used to configure ASP .Net process management. These settings can only be made in machine.config as they apply to all ASP .Net applications on that machine. The ASP .Net worker process runs in a special windows account, aspnet. ASP .Net supports multiple worker processes on the same machine. This feature is known as web garden. Web garden mode is only supported on multi-processor servers.

<system.web>

<processModel

enable="true"

timeout="Infinite"

idleTimeout="Infinite"

requestLimit="Infinite"

requestQueueLimit="5000"

memoryLimit="60" (% of the total memory)

webGarden="false"

logLevel="All | None | Errors"

maxWorkerThreads="25"

maxIOThreads="25"

serverErrorMessageFile="path" />

</system.web>

· Specifying The Location: Using the <location> element, you can specify application-specific settings in machine.config. Settings define under this element only apply to that particular application or virtual directory or a particular file (may be a web.config or a .aspx). You can think of it as putting a application-specific web.config file into machine.config.

· Locking Down Configuration Settings: You can limit the configuration settings, which can be overridden by down level configuration files. For example you can set a setting in the machine.config file, which is not overridable in the web.config file. You can do this by two ways:

1) Locking Down Via <location>: When you define an element <location> in the machine.config file you can set whether the settings defined under it is orverridable in web.config file or not using allowOverride attribute.

2) Locking Down Via Configuration Section Handler: You can use the optional allowDefinition attribute on the configuration section handler to restrict the web.config file to override the particular section.

allowDefinition="MachineOnly"

· Authentication

The process of discovering the individual identity of users, and making them prove that they are whom they say they are.

· Authorization

The process of determining if a particular user is entitled to access the resource they have requested.

· Impersonation

The process whereby the resources can be accessed under a different identity, usually the context of a remote user. Windows defines special accounts for the anonymous users. IIS and ASP .Net uses these account to allow anonymous access. When impersonation is turned off, ASP .Net makes all access to resources under the context of a special ASP .Net process account. When the impersonation is on, ASP .Net executes every resource under the account of a specified user that is authenticated by IIS when the request is made.

· Authentication Process

When IIS first received a request it checks for user's IP address or domain permission. If it is permitted, then it checks whether the anonymous access is enabled or not. If the anonymous access is enabled then IIS execute the request under the IIS anonymous account and send it to ASP .Net for further processing. If the anonymous access is not permitted the user is transferred to windows. Windows authenticate user via windows security rule. If succeed, the user is transferred to ASP .Net for further processing. ASP .Net also perform some security checks before sending the resources to user.

· By default impersonation is enabled in IIS (the request is made under the context of the IIS anonymous account, default is IUSR_machinename) and is disable in ASP .Net (the request is made under the context of the ASP .Net process account).

· The <authorization> section settings in web.config are automatically applied to any directory in which you place the web.config. But this is not a case with <authentication> section settings. To apply these settings, you must place web.config file the root folder of a web site.

· Types Of Authentication

1) Windows: The initial authentication is performed by IIS through Basic, Digest or Integrated windows authentication. The requested resources are then accessed under the context of this account.

2) Forms-Based: Unauthenticated requests are automatically redirected to a login page through HTTP client-side redirection. If the application authenticates the request, the system issues a cookie to client. The client browser then sends the cookie with all subsequent requests to access the resources.

3) Passport: It uses the Microsoft passport authentication web services.

· Setting Up Windows Authentication

Simply specify this authentication mode and then turn on impersonation within the <identity> element in the web.config. Now each user will access resources under the context of the account that they logged into IIS with.

<system.web>

<authentication mode="Windows" />

<identity impersonate="true">

</system.web>

· The <deny> elements precedence over <allow> elements, so that you can allow a Windows account group using <allow roles="x"/>, But deny specific users that are within that account group using <deny users="y"/>. The <allow> element should always be located before the <deny> element.

<authorization>

<allow roles="MyDomainName\SalesDept"

users="MyDomainName\billjones,

MyMachineName\marthasmith" />

<deny users="*" />

</authorization>

· Specifying HTTP Access Types

<allow verb="GET" users="*" />

<allow verb="POST" users="marthasmith" />

<deny verb="POST" users="*" />

In this case only user marthasmith will able to send POST requests to the application. All the other users will only able to send GET requests.

· You can use the <location> element in the web.config file to control the access permission on a specific sub folder or a file.

<location path="mypage.aspx> (only apply to this file)

<system.web>

<authorization>

. . .

</authorization>

<system.web>

</location>

· Running Under Another Specific Account

You can instruct ASP .Net to access resources under a specific account, rather than the user account that was authenticated by IIS or the special ASP .Net process account (which is normally used when impersonation is not enabled).

<system.web>

<identity impersonate="true">

userName="MyUserName"

password="MyPassword" />

</system.web>

· If you are accessing the application from the local machine or a machine on the same domain and Integrated Windows authentication is enabled in Internet Services Manager (the default), your browser will send your current windows logon details in response to the logon challenge from the web server.

· Passport Authentication

In case of passport authentication, you use an authentication web service provided by the Microsoft. To enable passport authentication for your site you have to register yourself to the service. Passport authentication is a single-authentication process for all the passport enabled web sites. It means user has to authenticate himself only one time, and all the subsequent redirects to the passport enabled sites do not need an authentication process to be done again. If a user is request a resource on your web site and he is not authenticated yet, he will be redirected to the passport serves login page. After authenticated there, it will be redirected again to your server. On all subsequent requests to your web site or any other passport enabled web site user can present his encrypted ticket in form of a cookie, issued by the passport service.

· Form-Based Authentication

It is also known as cookie-based authentication. The request is received by IIS, which checks that the IP address and domain of the user are permitted. IIS also authenticates the user if anonymous access is disabled, although in this scenario you will almost always allow anonymous access because the access control is being performed by ASP .Net. Once IIS authenticated the user, it passes it to ASP .Net. ASP .Net check whether the user is already authenticated or not (by looking at authentication cookie in the request header). If the user is already authenticated, ASP .Net checks whether the user is permitted for the requested resource or not. If the user is not yet authenticated it will be redirected to a login page. User has to present his credentials here, and if ASP .Net authenticate him, it will issue him a authentication cookie for subsequent requests.

· Setting Up Forms-Based Authentication In Web.Config

<authentication mode="Forms">

<forms name="cookie-name"

path="/"

loginurl="url"

protection="All | None | Encryption"

timeout="number-of-minutes"

requireSSL="false"

slidingExpiration="true" >

<credentials passwordFormat="Clear|SHA1|MD5" >

<user name="-" password="-" />

. . .

</credentials>

</forms>

</authentication>

· Authenticate User

When a user enters its credentials into the login form it can be authenticated against the user list provides in the web.config.

If FormsAuthentication.Authenticate ("user-

name","password") Then

FormsAuthentication.RedirectFromLoginPage("user-

name", False)

' Redirecting to the original requested page, False '

' in the parameter means the cookies will not be ' '

' persisted between session.

End If

You can expire a cookie immediately on demand as:

FormsAuthentication.SignOut()

· Authorization process in forms-based authentication is same, as we have used in the windows-based authentication. ASP .Net overrides the windows authentication mode and settings. It means if windows accounts do exist for the users who are trying to log on through forms-based authentication, they are not used when the user logs in via forms-based authentication. All access will be performed under the context of the ASP .Net process account, which must have access to the resource.

· Getting The User Information

StrUserName = User.Identity.Name

BlnAuthenticated = User.Identity.IsAuthenticated

StrAuthType = User.Identity.AuthenticationType

If windows authentication was used, its possible to tell which windows account group the current user is a member of.

BlnResult = User.IsInRole("MyDomainName\SalesDept")

In windows authentication mode, you can use WindowsIdentity object to get more specific information about the user. The Identity property returns an Identity object, and you cast this to a WindowsIdentity object. To do this you need to import System.Security.Principal name-space.

Dim ObjIdentity = CType(User.Identity, WindowsIdentity)

' Get the current WindowsIdentity object for this user

' This contains more specific information

Dim ObjWinIdentity = ObjIdentity.GetCurrent()

· Encrypting The Password

StrHash =

FormsAuthentication.HashPasswordForStoringInConfigFile

("Password", "SHA1 | MD5")

· Authentication Against A Different Source

Instead mentioning the users, who can access the application, in web.config (hard-coding), you can use a XML based file or SQL Server database to authenticate them. First you have to set <authorization> element in the web.config as "?", it means that anyone who has been authenticated can access the pages, because the default machine.config file allows all users to access all resources unless you override this in an application.

<authorization>

<deny users="?"/>

</authorization>

1) XML User List Document: The following XML document is used to authenticate the user. In this the elements are the name of user and in between the elements we have placed the password for the user.

<?xml version="1.0" ?>

<userlist>

<billjones>test</billjones>

<marthasmith>test1</marthasmith>

</userlist>

Now when the button "Login" is pressed by the user the following code is executed in response.

Dim ObjXMLDoc As New XmlDocumnet()

ObjXmlDoc.Load("XML File Name To Load")

' Create a NodeList collection of all matching child nodes

' There should be only one for the user

Dim ColUser As XmlNodeList

ColUser = ObjXMLDoc.GetElementsByTagname("Name Of User")

' See if any matching user name found in the collection

If ColUser.Count > 0 Then

' Check if the value of the element (the child #text

' node) is equal to the password entered by the user

If StrPwd = ColUser(0).FirstChild().Value Then

' Set the authentication value true

End If

End If

2) Authentication Against Database: Simply take the users credential and fire a SQL query, which checks the credential against the values (user-name and password) stored in the database. If it succeed make the authentication value true.

In both cases described above when the authentication process is succeed, you can tell ASP .Net that you have validated the user's credentials and that they should be authenticated and receive the appropriate cookie so that they can access your application. Do it as:

FormsAuthentication.RedirectFromLoginPage("user-

name",false)

You can also use the encrypted password both in XML document and database. To do this, first encrypt the user password (using FormsAuthentication's method) and store them in the XML document or in database. Then in login process get the password value entered by the user, encrypt it again and check this hashed value against the

Comments

Popular posts from this blog

Top Open Source Web-Based Project Management Software

This is an user contributed article. Project management software is not just for managing software based project. It can be used for variety of other tasks too. The web-based software must provide tools for planning, organizing and managing resources to achieve project goals and objectives. A web-based project management software can be accessed through an intranet or WAN / LAN using a web browser. You don't have to install any other software on the system. The software can be easy of use with access control features (multi-user). I use project management software for all of our projects (for e.g. building a new cluster farm) for issue / bug-tracking, calender, gantt charts, email notification and much more. Obviously I'm not the only user, the following open source software is used by some of the biggest research organizations and companies world wild. For example, NASA's Jet Propulsion Laboratory uses track software or open source project such as lighttpd / phpbb use re

My organization went through the approval process of supporting the .NET Framework 2.0 in production. Do we need to go through the same process all...

My organization went through the approval process of supporting the .NET Framework 2.0 in production. Do we need to go through the same process all over again for the .NET Framework 3.0? Do I need to do any application compatibility testing for my .NET Framework 2.0 applications? Because the .NET Framework 3.0 only adds new components to the .NET Framework 2.0 without changing any of the components released in the .NET Framework 2.0, the applications you've built on the .NET Framework 2.0 will not be affected. You don’t need to do any additional testing for your .NET Framework 2.0 applications when you install the .NET Framework 3.0.

Google products for your Nokia phone

Stay connected with Gmail, Search, Maps and other Google products. Check products are available for your Nokia phone Featured Free Products Search - Find the information you need quickly and easily Maps - Locate nearby businesses and get driving directions Gmail - Stay connected with Gmail on the go YouTube - Watch videos from anywhere Sync - Synchronize your contacts with Google