Caveman's Blog

My commitment to learning.

Archive for the ‘ASP.Net’ Category

ASP.Net MapPath

Posted by cavemansblog on August 11, 2009

Writing code in  a web application with not access to HttpContext and still need to map to a folder in the website? No problem.. you can use the System.Web.Hosting.HostingEnvironment.MapPath function.


//This is how you would map if you had access to the HttpContext object

System.Web.HttpContext.Current.Server.MapPath("~/App_Data/data.xml");

//and here is how you would map if you do not have access to the HttpContext object

System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/data.xml");

Posted in ASP.Net, Sudheer Reddy Battula | Tagged: | Leave a Comment »

Encrypting the Web.Config configurations

Posted by cavemansblog on July 28, 2009

The web.config is a file that is not accessible to the user of a web application via a browser. The dotnet framework shields this file from all kinds of external intrusion. However someone having access to the physical file can steal sensitive information.

This vulnerability can be overcome by using aspnet_regiis, an in-build ASP.Net tool.  Following these simple steps, sections of the web.config can be encrypted (and/or decrypted) to secure the configuration settings:

Step 1: Encrypt connection Strings in the web.config. This command uses RSAProtectedConfigurationProvider (uses TripleDES and RSA encryption) for encrypting sections of the web.config file. This command has to be executed in a Visual Studio 2005/2008 command prompt window at the location where the web.config resides:

aspnet_regiis -pef connectionStrings .

Step 2: Adding users to the ACL of the key containers using the –pa parameter. Give access to the ASP.NET user:

aspnet_regiis -pa “NetFrameworkConfigurationKey” “ASPNET”

Step 3: Decrypt Connection Strings to clear text

aspnet_regiis -pdf connectionStrings .

The best part is that, the web application code does not have to change one bit after the encryption of web.config file. Following is a before and after view of the Connection Strings section of a web.config file:

Before:

<connectionStrings>
 <add name="MembershipConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\LOCALDB.MDF;Integrated Security=True;User Instance=True"
 providerName="System.Data.SqlClient" />
 </connectionStrings>

After:

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
 <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
 xmlns="http://www.w3.org/2001/04/xmlenc#">
 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
 <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
 <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
 <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
 <KeyName>Rsa Key</KeyName>
 </KeyInfo>
 <CipherData>
 <CipherValue>Qnp5eTaECH2wMwlRJjne61lKvEcRfZ3NDeCUhtw+wRKPmmY3Z3iZPBowIZwclU6gjdmY48/dhAEdUCLmzM5iEfHmPoyli+LMW5Yz1pQZM8I7iTFLLgeKux1CgUwP+bUtCpvP66Vu5wL5/veYSiR7kGzu/FgH+8vM6M3SYusHVGQ=</CipherValue>
 </CipherData>
 </EncryptedKey>
 </KeyInfo>
 <CipherData>
 <CipherValue>BPA8J8Vue27wc4COgJ2Pfk9XCe7umTNAKdTJ2WnsyIg/zpEpdL4H6zxE0b5DBFehWTARRAtxfJhNUz4mp+QZvBZ0Iod1utujiXP0+EiWZpY8v31s94lgFhE88cH/CoF/vZgHYyDfedBTtJtUyN1xpegxzHHy38IwDElXUhb3UHP3X3nRWPJ0AohYz8xZZRMzn8MEDJDWCoKErwtMpUbE08AEZHDQSU6ITSn5urNrgS+V2CYYwhY3t1VbA2b+mEQFxVin4bEvOl+O8HGl2kzPtq5rhN60FnbxjPyHwCeHvl8JOzjk/ND8go/w49N61eGrGOH2xFNFPw2mhGVkJD5Lm8nn7xeo30YSS+Ct9uGzLfs=</CipherValue>
 </CipherData>
 </EncryptedData>
 </connectionStrings></pre>

Tip: Here is how to secure appsettings

Encrypt appSettings: aspnet_regiis -pef sppSettings .

Decrypt appSettings: aspnet_regiis -pdf sppSettings .

References:
1. How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA
2. Encrypting configuration files using protected configuration

Posted in ASP.Net, Dotnet, Sudheer Reddy Battula | Tagged: , | 1 Comment »

Factoring the Web.Config

Posted by cavemansblog on June 4, 2009

Web.Config is a XML document file in a ASP.Net application that is used to store configuration settings related to the web application. The web.config file contains information about database configuration, control module loading, security configuration, session state configuration, Custom configuration and compilation settings. Each web application in ASP.Net inherits their base web.config from the machine’s web.config located in %SystemRoot%\Microsoft.Net\Framework\v#.#.#.#\CONFIG. The applications own web.config is physically located at the root of the web application and sub directories inherit the configuration setting unless they have their own web.config with in the respective sub-directories.

Usually as the application size grows, so does the number of settings and the size of the web.config file. The settings in config file become so many that it will be pretty tough to manage them and also hard to read. There is one less known optional string attribute called “ConfigSource” that specifies the name of the include file in which the associated configuration section is defined, if such a file exists. The configsource attribute was introduced in .NET Framework 2.0 to support external configuration files. This attribute can be added to any configuration section to specify a an external file for that section. Following is an example of a before and after scenario for using the configsource attribute. This example demonstrates how the database connection settings can be separated into an external config file:

Before:

<configuration>
    <configSections>
        <section name="ConnectionStrings" restartOnExternalChanges="false"/>
    </configSections>
    <connectionStrings>
        <add name=“Inventory” connectionString=“Database=MYINVENTORYDB;Server=<SERVER-NAME>;User ID=<USERNAME>;Password=<PASSWORD>;Trusted_Connection=False;” providerName=“System.Data.SqlClient”/>
    </connectionStrings>
.
.
<configuration>

After:

Following are two sections from the web.config and the dbsetting.config files. The dbsettings.config file has the database connection configuration information.

web.config

<configuration>
    <configSections>
        <section name="ConnectionStrings" restartOnExternalChanges="false"/>
    </configSections>
    <connectionStrings configSource="dbsettings.config">

      </connectionStrings>
.
.
<configuration>

dbsettings.config

<configuration>
    <connectionStrings>
        <add name=“Inventory” connectionString=“Database=MYINVENTORYDB;Server=<SERVER-NAME>;User ID=<USERNAME>;Password=<PASSWORD>;Trusted_Connection=False;” providerName=“System.Data.SqlClient”/>
    </connectionStrings>
</configuration>

Example 2

Here is another example of separating the database configuration settings into multiple files. These settings are for Enterprise Library External file configuration source for Application blocks. Following are the sections of the web.config and the entlib.config files into which the database Connection string configuration has been separated:

Web.Config

<enterpriseLibrary.ConfigurationSource selectedSource=“File Configuration Source”>
    <sources>
        <add name=“File Configuration Source” type=“Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=X.X.X.X, Culture=neutral, PublicKeyToken=null” filePath=“entlib.config”/>
    </sources>
</enterpriseLibrary.ConfigurationSource>

entlib.config

<configuration>
    <connectionStrings>
        <add name=“Inventory”connectionString=“Database=MYINVENTORYDB;Server=<SERVER-NAME>;User  ID=<USERNAME>;Password=<PASSWORD>;Trusted_Connection=False;” providerName=“System.Data.SqlClient”/>
    </connectionStrings>
</configuration>

The end result is that this feature of web.config file has been very useful to me so far in keeping the config files neat and simple to read. Also note that the restartOnExternalChanges property is set to false in the “section element for config sections” so that the application does not restart when a change to the external config file is made.

Tip: ConnectionStrings.com has nice list of connection strings for various databases.

References:

1. MSDN Online

http://www.nikhilk.net/Entry.aspx?id=158

Posted in ASP.Net, Dotnet, Sudheer Reddy Battula | Tagged: , , , , , | 1 Comment »

The Response.Redirect Menace

Posted by cavemansblog on February 13, 2008

You know how we all take things for granted and never bother to think of the caveats…. yep you know what I am talking about…. exactly… I ran into one such situation with Response.Redirect.

I have learnt that the Response.Redirect internally has to make a call to Response.End to force stop the execution of the current thread there by throwing a ThreadAbort exception [2].

The way this works is:

A call to HttpResponse.Redirect(string url) actually calls an overload HttpResponse.Redirect(string url, bool endResponse) with endResponse set to true. If endResponse is set to true, HttpResponse.Redirect will make a call to HttpResponse.End(). [1]

Microsoft recommends that we use the overloaded Response.Redirect(String url, bool endResponse) method that passes false so that a call to Thread.Abort() can be avoided by suppressing the call to Response.End. Is there a catch? Yes, the page will execute the code that follows Response.Redirect.

One solution I can think of to minimize the effort in execution of the code that follows the Response.Redirect is, actually code around the Response.Redirect

if(HaveToredirect == true)
{
  Response.Redirect(url, false); //as described in [1]
  HttpContext.ApplicationInstance.CompleteRequest();
  return;
}

Check for the IsRequestBeingRedirected property of the Response object and return if it is true, in all the page events as the first step. This way we can mimimize the execution time of the page.

if (Response.IsRequestBeingRedirected == true)
return;

This approach might be feasible in all scenarios though.

Also note that Server.Transfer calls Response.End interally.

References:

1. Response.Redirect(url) ThreadAbortException Solution
2. Microsoft Support Article.

Posted in ASP.Net, Sudheer Reddy Battula, ThreadAbort, Web Applications | Tagged: , | 1 Comment »

State Management in ASP.NET

Posted by coolgirlsblog on January 31, 2008

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
  • Server-side

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.

1) 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 information from cookies.

//to create a cookie variable
Response.Cookies["username"].Value=name;

//to access a cookie variable
Request.Cookies["username"].Value

2) 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.

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.

//to save informationViewState.Add(“shape”,”circle”);//to retrieve informationstring 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.

This is an article in its entirity has been posted on http://www.csharphelp.com/ by Eric Zheng. I am reposting this on my blog since it is very well written and is very useful.

Reference:
1. http://www.csharphelp.com/archives/archive207.html - Eric Zheng

Posted in ASP.Net, State Management | Tagged: , | 2 Comments »