Wednesday, November 19, 2008

FIX: How to resolve Security Exception (ASP.NET)?

SUMMARY

This article will show you how to fix the security exception which occurs when you attempt to deploy an ASP.NET application such as forums, blogs etc.

SYMPTOMS

Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application’s trust level in the configuration file.

Exception: System.Security.SecurityException: Request ఫెల్డ్

CAUSE

The above error occurs since the domain is not placed under its own application pool on the IIS and also due to lack of proper trust level in the machine.config file on the server.

Back to the top

RESOLUTION

(1) Create an application pool for the appropriate domain using Internet Information Services (IIS). Login to the remote desktop and open IIS Manager. Expand the tree Application Pools. Right click and select New | Application Pool and give the required particulars.

(2) The next step is to place the domain under the newly created application pool. In order to perform this action, expand the tree labeled Web Sites and then Default Web Site under it. Select your domain name, right click on it and choose Properties menu item. Select the drop down box labeled Application pool and choose the newly created application pool name.

Note: You can automatically perform the above mentioned steps using certain popular hosting control panels if you have installed them on the server.

(3) Add the following lines of code to machine.config file. This file can be located under the folder - Root Drive Name:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG













(A) You should require administrative rights to the server and access to remote desktop to resolve the above issue. You should contact your hosting service provider if you don’t have access to the server.

(B) Replace yourdomain.com with the appropriate domain name in which the problem is occurring.

Warning: Incorrect modification of machine.config file will cause problems to the ASP.NET service on the server.

Thursday, August 14, 2008

In-process Mode

In-process mode simply means using ASP.NET session state in a similar manner to classic ASP session state. That is, session state is managed in process and if the process is re-cycled, state is lost. Given the new settings that ASP.NET provides, you might wonder why you would ever use this mode. The reasoning is quite simple: performance. The performance of session state, e.g. the time it takes to read from and write to the session state dictionary, will be much faster when the memory read to and from is in process, as cross-process calls add overhead when data is marshaled back and forth or possibly read from SQL Server.

In-process mode is the default setting for ASP.NET. When this setting is used, the only other session config.web settings used are cookieless and timeout.

If we call SessionState.aspx, set a session state value, and stop and start the ASP.NET process (iisreset), the value set before the process was cycled will be lost.

Session configuration

Config.web
There are two types of configuration files: a machine configuration file and an application configuration file, both named config.web. The two are identical, except that the machine configuration file applies settings to all applications but the application configuration files are either restrictive or expansive on an application-by-application basis.
In Beta 1, the machine config.web file is in the WinNT\Microsoft.NET\Framework\v1.0.2204 directory, while the optional application configuration files exist in the application's directory. Application config.web files are optional in the sense that if an application config.web file doesn't exist, the machine config.web settings are used instead. ASP.NET session state settings can be made in the machine config.web file and overridden in a particular application's config.web file.
Note: Changes made to config.web are applied immediately, unlike classic ASP, where the server has to be stopped and started for settings to take affect.

Session configuration
Below is a sample config.web file used to configure the session state settings for an ASP.NET application:

configuration
sessionstate mode="inproc" cookieless="false" timeout="20" sqlconnectionstring="data source=127.0.0.1;user id=user id;password=password" server="127.0.0.1" port="42424" /
/configuration

The settings above are used to configure ASP.NET session state. Let's look at each in more detail and cover the various uses afterward.

Mode.
The mode setting supports three options: inproc, sqlserver, and stateserver. As stated earlier, ASP.NET supports two modes: in process and out of process. There are also two options for out-of-process state management: memory based (stateserver), and SQL Server based (sqlserver). We'll discuss implementing these options shortly.

Cookieless. The cookieless option for ASP.NET is configured with this simple Boolean setting.

Timeout. This option controls the length of time a session is considered valid. The session timeout is a sliding value; on each request the timeout period is set to the current time plus the timeout value

Sqlconnectionstring. The sqlconnectionstring identifies the database connection string that names the database used for mode sqlserver.

Server. In the out-of-process mode stateserver, it names the server that is running the required Windows NT service: ASPState.

Port. The port setting, which accompanies the server setting, identifies the port number that corresponds to the server setting for mode stateserver.

ASP.NET Session State

ASP maintains session state by providing the client with a unique key assigned to the user when the session begins. This key is stored in an HTTP cookie that the client sends to the server on each request. The server can then read the key from the cookie and re-inflate the server session state.

Problems with ASP Session State
ASP developers know session state as a great feature, but one that is somewhat limited. These limitations include:
Process dependent.
ASP session state exists in the process that hosts ASP; thus the actions that affect the process also affect session state. When the process is recycled or fails, session state is lost.
Server farm limitations.
As users move from server to server in a Web server farm, their session state does not follow them. ASP session state is machine specific. Each ASP server provides its own session state, and unless the user returns to the same server, the session state is inaccessible. While network IP level routing solutions can solve such problems, by ensuring that client IPs are routed to the originating server, some ISPs choose to use a proxy load-balancing solution for their clients. Most infamous of these is AOL. Solutions such as AOL's prevent network level routing of requests to servers because the IP addresses for the requestor cannot be guaranteed to be unique.
Cookie dependent.
Clients that don't accept HTTP cookies can't take advantage of session state. Some clients believe that cookies compromise security and/or privacy and thus disable them, which disables session state on the server.

These are several of the problem sets that were taken into consideration in the design of ASP.NET session state.

ASP.NET Session State

ASP.NET session state solves all of the above problems associated with classic ASP session state:
Process independent.
ASP.NET session state is able to run in a separate process from the ASP.NET host process. If session state is in a separate process, the ASP.NET process can come and go while the session state process remains available. Of course, you can still use session state in process similar to classic ASP, too.
Support for server farm configurations.
By moving to an out-of-process model, ASP.NET also solves the server farm problem. The new out-of-process model allows all servers in the farm to share a session state process. You can implement this by changing the ASP.NET configuration to point to a common server.
Cookie independent.
Although solutions to the problem of cookieless state management do exist for classic ASP, they're not trivial to implement. ASP.NET, on the other hand, reduces the complexities of cookieless session state to a simple configuration setting.
Let's look at each of these features in more detail, including how the settings are configured.



2. Server-side state management:

Information will be stored on the server, it has higher security but it can use more web server resources.

A. Aplication object
The Application object provides a mechanism for storing data that is accessible to all code running within the Web application, The ideal data to insert into application state variables is data that is shared by multiple sessions and does not change often.. And just because it is visible to the entire application, you need to used Lock and UnLock pair to avoid having conflit value.
[c#]
Application.Lock();
Application[“mydata”]=”mydata”;
Application.UnLock();


B. Session object
Session object can be used for storing session-specific information that needs to be maintained between server round trips and between requests for pages. Session object is per-client basis, which means different clients generate different session object.The ideal data to store in session-state variables is short-lived, sensitive data that is specific to an individual session.

Each active ASP.NET session is identified and tracked using a 120-bit SessionID string containing URL-legal ASCII characters. SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide, and SessionID’s randomness makes it harder to guess the session ID of an existing session.SessionIDs are communicated across client-server requests either by an HTTP cookie or a modified URL, depending on how you set the application's configuration settings. So how to set the session setting in application configuration? Ok, let’s go further to look at it.
Every web application must have a configuration file named web.config, it is a XML-Based file, there is a section name ‘sessionState’, the following is an example:


cookieless’ option can be ‘true’ or ‘false’. When it is ‘false’(default value), ASP.NET will use HTTP cookie to identify users. When it is ‘true’, ASP.NET will randomly generate a unique number and put it just right ahead of the requested file, this number is used to identify users, you can see it on the address bar of IE:
http://localhost/Management/(2yzakzez3eqxut45ukyzq3qp)/Default.aspx

Ok, it is further enough, let is go back to session object.
[c#]
//to store information
Session[“myname”]=”Mike”;
//to retrieve information
myname=Session[“myname”];


C. Database
Database enables you to store large amount of information pertaining to state in your Web application. Sometimes users continually query the database by using the unique ID, you can save it in the database for use across multiple request for the pages in your site.

Summary
ASP.NET has more functions and utilities than ASP to enable you to manage page state more efficient and effective. Choosing among the options will depand upon your application, you have to think about the following before making any choose:
How much information do you need to store?
Does the client accept persistent or in-memory cookies?
Do you want to store the information on the client or server?
Is the information sensitive?
What kind of performance experience are you expecting from your pages?


Client-side state management summary

Method Use when


Cookies You need to store small amounts of information on the client and security is not
an issue.

View state You need to store small amounts of information for a page that will post back to
itself. Use of the ViewState property does supply semi-secure functionality.

Hidden fields You need to store small amounts of information for a page that will post back to
itself or another page, and security is not an issue.
Note You can use a hidden field only on pages that are submitted to the server.

Query string You are transferring small amounts of information from one page to another and
security is not an issue.
Note You can use query strings only if you are requesting the same page, or another page via a link.

Server-side state management summary
Method Use when
Application state object You are storing infrequently changed, application-scope information
that is used by many users, and security is not an issue. Do not store
large quantities of information in an application state object.

Session state object You are storing short-lived information that is specific to an individual
session, and security is an issue. Do not store large quantities of
information in a session state object. Be aware that a session state object
will be created and maintained for the lifetime of every session in your
application. In applications hosting many users, this can occupy
significant server resources and affect scalability.

Database support You are storing large amounts of information, managing transactions, or
the information must survive application and session restarts. Data mining
is a concern, and security is an issue.

Developing ASP.NET programme is really funny, once you jump into it, you can feel the power of it. Next time let us talk about another topic: Cache. Enjoy .Net!!

1.Client-side state management :

There is no information maintained on the server between round trips. Information will be stored in the page or on the client’s computer.
A. Cookies.
A cookie is a small amount of data stored either in a text file on the client's file system or in-memory in the client browser session. Cookies are mainly used for tracking data settings. Let’s take an example: say we want to customize a welcome web page, when the user request the default web page, the application first to detect if the user has logined before, we can retrieve the user informatin from cookies:
[c#]
if (Request.Cookies[“username”]!=null)
lbMessage.text=”Dear “+Request.Cookies[“username”].Value+”, Welcome shopping here!”;
else
lbMessage.text=”Welcome shopping here!”;


If you want to store client’s information, you can use the following code:
[c#]
Response.Cookies[“username’].Value=username;
So next time when the user request the web page, you can easily recongnize the user again.

B. Hidden Field
A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP Form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you would like to store directly in the page. Hidden field stores a single variable in its value property and must be explicitly added it to the page.
ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.
[c#]
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assign a value to
Hidden fieldHidden1.Value=”this is a test”;
//to retrieve a value
string str=Hidden1.Value;

Note: Keep in mind, in order to use hidden field, you have to use HTTP-Post method to post web page. Although its name is ‘Hidden’, its value is not hidden, you can see its value through ‘view source’ function.

C. View State
Each control on a Web Forms page, including the page itself, has a ViewState property, it is a built-in struture for automatic retention of page and control state, which means you don’t need to do anything about getting back the data of controls after posting page to the server.
Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.
[c#]
//to save information
ViewState.Add(“shape”,”circle”);
//to retrieve information
string shapes=ViewState[“shape”];


Note: Unlike Hidden Field, the values in ViewState are invisible when ‘view source’, they are compressed and encoded.

D. Query Strings
Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.
A URL with query strings may look like this:
http://www.examples.com/list.aspx?categoryid=1&productid=101
When list.aspx is being requested, the category and product information can be obtained by using the following codes:
[c#]
string categoryid, productid;
categoryid=Request.Params[“categoryid”];
productid=Request.Params[“productid”];


Note: you can only use HTTP-Get method to post the web page, or you will never get the value from query strings.

StateManagement in ASP.NET

Web form pages are HTTP-Based, they are stateless, which means they don’t know whether the requests are all from the same client, and pages are destroyed and recreated with each round trip to the server, therefore information will be lost, therefore state management is really an issue in developing web applications.

We could easily solve these problems in ASP with cookie, query string, application, session and so on. Now in ASP.NET, we still can use these functions, but they are richer and more powerful, so let’s dive into it.

Mainly there are two different ways to manage web page’s state: Client-side and Server-side.