I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Showing posts with label Web.config. Show all posts
Showing posts with label Web.config. Show all posts

Connection String Encryption in Web.config using C#

Almost all ASP.NET web sites connect database and one of the best practices in ASP.NET is to store your database connection string outside your source code typically in web configuration file (web.config). This gives you benefit of changing your database related information such as the server name, user id or password without any modification or compilation of your source code. To provide additional security of important connection string information you should always encrypt your connection string in web.config file.

ASP.NET 2.0 allow you to encrypt and decrypt your connection string in web.config. In the following tutorial, I will show you how you can encrypt and decrypt connection strings in C# using .NET Framework built in classes available in System.Configuration and System.Web.Configuration namespaces.

To test the following code you should have your connection string in web.config file as following code shows:

<configuration>
<connectionStrings>
<add name="MyConnectionString"
connectionString="Server=TestServer; Database=TestDB; UID=test; PWD=test"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

Here is the C# code to encrypt and decrypt connection string. Make sure you have reference of System.Configuration and System.Web.Configuration available to test this code.
Encryption

try
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
config.Save();
}
}
catch (Exception ex)
{ }

Decryption

try
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}
catch (Exception ex)
{ }

Download Source Code Download Source Code

Creating Custom Configuration Sections in ASP.NET

Almost all ASP.NET Web Applications require some sort of configuration settings to be stored in the web.config files. These settings can be application settings, database connection strings, user authentication settings, page specific settings and so on. ASP.NET also provides very powerful Configuration API to work with configuration settings defined in web.config files. The Configuration API not only allows us to read/write settings in configuration files with ease but also allow us to define our own custom configuration sections in web.config. These custom sections are very useful in large web applications where you have a lot of application settings to store in the configuration file. In this tutorial, I will show you how to create and use custom configuration sections in ASP.NET.

I am sure many of you are using the following appSettings section of web.config to define your application specific settings.

<appSettings>
   <add key="DefaultLanguage" value="English-US"/>
   <add key="WebsiteTitle" value="Microsoft Corporation"/> 
   <add key="MaximumTransactionLimit" value="100000"/>
</appSettings>

However, in large projects you end up having an endless list of key/value pairs in your web.config file. This makes life little difficult as you have to make sure when you are reading these values you are typing the spellings of all keys correctly e.g. DefautlLanguage is not same as DefaultLanguage. You also need to do lot of type casting when you are reading all types of values such as numbers, Booleans, dates, etc.

To solve these problems, ASP.NET allows us to create a custom configuration section in web.config. A custom configuration section can be defined in the element in web.config. You need to specify the name of the section and the class name that is responsible for serialization and de-serialization of attributes of custom configuration section into class properties. Following is an example of custom configuration section defined for a typical ecommerce web application.

<configuration>
<configSections>
      <section name="ShoppingCartSettings" type="ShoppingCartSection"/>
   </configSections>

   ...
   ...
</configuration>

Please keep in mind that the value given for the type attribute above is the fully qualified name of the class. If the class is in App_Code folder of your project, you can simply use its name as used in the above example. If the class is in another assembly (.dll) then you need to use"Namespace.ClassName, AssemblyName" as the value of the type attribute. Once you have defined the custom configuration section you can use it in web.config file anywhere inside root configuration element as shown in the following code.

<configuration>
<system.web>
</system.web>
...
<ShoppingCartSettings
defaultCurrency="USD"
maxItemsInCart="10"
paypalCheckoutEnabled="true" />

</configuration>

You can define any number of properties in the ShoppingCartSettings section but keep in mind that these properties need to be defined in the class named ShoppingCartSection as mentioned above in the type attribute. ShoppingCartSection class will be a simple C# class inherited from the System.Configuration.ConfigurationSection class. To define this class, add the reference of System.Configuration in your project and import the namespace on the top of the file with using statement.

using System.Configuration;
public class ShoppingCartSection : ConfigurationSection
{
...
...
}

The ShoppingCartSection class represents the root ShoppingCartSettings element of the custom configuration section defined in web.config file. Next you need to define the properties of the class as shown in the following code.

public class ShoppingCartSection : ConfigurationSection
{
[ConfigurationProperty("defaultCurrency", IsRequired = true, DefaultValue="USD")]
[StringValidator(MinLength=1, MaxLength=100)]

public string DefaultCurrency
{
get { return (string)this["defaultCurrency"]; }
set { this["defaultCurrency"] = value; }
}
[ConfigurationProperty("maxItemsInCart", IsRequired = true, DefaultValue = "5")]
[IntegerValidator(MinValue=1, MaxValue=10)]

public int MaxItemsInCart
{
get { return Convert.ToInt32(this["maxItemsInCart"]); }
set { this["maxItemsInCart"] = value; }
}
[ConfigurationProperty("paypalCheckoutEnabled", IsRequired = false, DefaultValue = false)]
public bool PaypalCheckoutEnabled
{
get { return Convert.ToBoolean(this["paypalCheckoutEnabled"]); }
set { this["paypalCheckoutEnabled"] = value; }
}
}

Notice how the class properties MaxItemsInCart, DefaultCurrency etc. are mapped with the attributes defined in custom configuration element in web.config using the ConfigurationProperty attribute declaration on top of the properties. The ConfigurationProperty attribute is also using some other parameters such as DefaultValue and IsRequired. The DefaultValue parameter specifies the default value of the property if it is not defined in the web.config. The IsRequired parameter specified whether the attribute defined in web.config is required or optional. I have also used the StringValidator and IntegerValidator attributes in the above code to show you how to validate the values specified in the web.config.
To read the custom configuration section data in your web pages you can use the static GetSection method of ConfigurationManager class as shown below:

ShoppingCartSection settings =
ConfigurationManager.GetSection("ShoppingCartSettings") as ShoppingCartSection;

Label1.Text = "Default Currency: " + settings.DefaultCurrency;
Label2.Text = "Max Allowed Items in Shopping Cart: " + settings.MaxItemsInCart.ToString();
Label3.Text = "Paypal Checkout Enable: " + settings.PaypalCheckoutEnabled.ToString();