Monday, August 29, 2011

encrypt connection string example

In this article I will show you a super simple and secure way to encrypt your connection string in your web application. This is how you do it.

How to encrypt the connection string directly on the deployed server?

1>Place this inside the <configuration> section of your web.config.

      <add name="myProvider"
           type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,processorArchitecture=MSIL"
           useMachineContainer="true" />

2>Save the bolded text below in a file named encrypt.bat
(Note the extension of the file is .bat )

SET PATH=%windir%\Microsoft.NET\Framework\v2.0.50727

aspnet_regiis -pc "MyKey" 
aspnet_regiis -pa "MyKey" "NT AUTHORITY\NETWORK SERVICE"
aspnet_regiis -pa "MyKey" "ASPNET"
aspnet_regiis -pef "connectionStrings" "." -prov "MyProvider"


3>Where ever the web.config of your web application resides, put the encrypt.bat in the same folder.

4>Execute encrypt.bat.

Now if you open your config file, the connection strings section would look something like this

  <connectionStrings configProtectionProvider=" MyProvider">
    <EncryptedData Type=""
      <EncryptionMethod Algorithm="" />
      <KeyInfo xmlns="">
        <EncryptedKey xmlns="">
          <EncryptionMethod Algorithm="" />
          <KeyInfo xmlns="">
            <KeyName>Rsa Key</KeyName>

There! You are good to go!

What If you need to replace the web.config later some time?

Run this on command prompt
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pz "MyKey"

This will remove the machine key "MyKey" that was created at
 C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys

Then go ahead and run encrypt.bat

Further reading
Walkthrough: Creating and Exporting an RSA Key Container:

Thursday, August 25, 2011

ASP.NET Caching Tutorial (with examples)

There are two kinds of caching in

1>Page output caching:  What this does is it stores  the HTML output from the previous request and keeps serving the same output for subsequent requests until the stored cache times out.
Consider the example below, suppose you have a page that presents data from a database. The data it pulls from the database only changes once every few hours. In a case like this if you enable output caching with an expiry of 10  mins, you will hit the database only once in 10 mins.  If there are a large number of users, this will dramatically reduce the load on the database. The only downside to this is, the user could see outdated data for up to 10 mins.

Example: Adding this to the top of your will preserve this page for 600 seconds (10 mins)
<%@ OutputCache Duration="600" VaryByParam="None" %>

2>Application data caching: This is meant for storing data at an application level. It differs from application variables in the sense that application caching is usually meant for large amounts of data that needs to be periodically refreshed.

Example of application caching:

In the example below I will show you how to load a datatable into cache. This cache is set to expire at midnight everynight. Every time the cache gets destroyed due to expiry or underuse, it gets reloaded.

//Declare a variable of the delegate type CacheItemRemovedCallback
CacheItemRemovedCallback cacheRemovedDelg;

//Add the datatable ds.Tables["Vendor"] to cache

“Vendor”,                      //1
ds.Tables["Vendor"],           //2
null,                          //3
DateTime.Today.AddDays(1),     //4
Cache.NoSlidingExpiration,     //5
cacheRemovedDelg               //7

What the numbers above mean is expalined below

1> Key (Name)  assigned to the cache item
2> Data to be added to the cache
3> Anything that the cache depends on
4> This cache will expire at midnight
5> Set to no sliding expiration ( If instead a sliding expiration say for eg 20mins is set,then the the cache will expire after 20 mins after it was loaded )
6> The cache item that will not get removed due to shortage of memory
7> This delegate points to the function to be called when the cache is destroyed for any reason (Will not be called when cache is removed due to an application restart)

If you want to reload the application cache when it gets removed do this

Add this line of code to the Page_Load()  event handler.

cacheRemovedDelg = new CacheItemRemovedCallback(OnCacheRemoved);

Then declare this method on that page

private void OnCacheRemoved(string key, Object value, CacheItemRemovedReason reason)
     if (reason.ToString() == "Expired" || reason.ToString() == "Underused")
         // Reload cache in here

Modify IIS settings

The default app pool worker process is killed after 20 mins of inactivity. With that all the cache variables disappear. So my recommendation is to create your own app pool. Then raise the worker process shut down after an idle time (default 20 mins) and the recycle worker process (default 1740 mins) to  something that works for you . 

Check out this link for more on IIS settings

Further Reading
ASP.NET Caching:

Monday, August 22, 2011

C# : Difference between Array and Arraylist

Arrays are strongly typed.

 That is all the elements have to be of the same type. For example an array of integers has to have all integers.  It cannot have a mix of integers and strings.
An arraylist is NOT strongly typed.

You can have a  combination of built in types  (int,string etc) in your arraylist.
Cannot be dynamically resized.

(Note :Array.Resize() doesnot actually resize the existing array. It infact creates a new array with the required length and copies values from the old array to new array. Using the Resize is more memory intensive than AddRange() in arraylist)
Can be dynamically resized using the method Arraylist.AddRange()
int[] myIntArray = new int[2]

ArrayList leaderNames = new ArrayList();


Wednesday, August 10, 2011

How to consume a WCF service (WCF Client)

In this article I will show you how to consume (call) a WCF service. For  this example I will be consuming a service that was created in the  article Even if you haven't gone through this article, don't worry about it. You can consume any service in the same way as shown below.
Consuming a service involves basic steps

  • Adding a service reference
  • Creating an instance of the client
  • Calling the web methods of the instance

Follow the example below for details

1>Create a console application as shown below, call it ConsumeService

2>Add a Service Reference to http://localhost:8000/DilbertService (note that this service should be running)

3>Double click on ServicReference1 on the right 

4>Locate the name of the client. You will use this name "DilbertFunctionsClient" in the next step.

5>Copy this into the program.cs code page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsumeService.ServiceReference1;

namespace ConsumeService
    class Program
        static void Main(string[] args)
            DilbertFunctionsClient client = new DilbertFunctionsClient();

6>At this stage this is how your application would look like

7>Run the app to see the output of client.Add(1,2)  

Monday, August 8, 2011

How to use WCF test client

WCF test client is a user friendly tool that with which you can easily test a WCF service. It comes with Visual studio 2008 and above. It can be typically found at

 "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\WcfTestClient.exe".
"C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\WcfTestClient.exe"

In this article I will show you how to use WCF test client. Consider that you are trying to test a local WCF service "http://localhost:8000/DilbertService" .(To see how to create a service, check out This service provides you with two methods, 
1>HelloWorld(): Which just says Hello World when invoked
2>Add(): Which adds two input numbers.

This is how you would test the service

1>Open the WCF test client

2>File->Add Service

3>Enter url of the service to be tested  "http://localhost:8000/DilbertService"

4>Double click "Hello World"

5>Click on invoke to see the return value.

6>Similarly the "Add" function can also be tested.

Saturday, August 6, 2011

Introduction to WCF (Windows Communication Foundation Tutorial)

What is WCF?

In simple terms WCF can be thought of as the next generation of webservices. In true sense however, WCF is actually a replacement for both webservices and remoting.

The image below shows you a real life scenario where a WCF service is used to authorize a user access to a website within the LAN of a corporation. This WCF service has a method that takes the logged in user's LAN ID as an input parameter and returns a boolean value which is true if the user's designation is Manager or above. And it returns false if the user's designation is below that of a manager.

In this article I will show you a quick and easy way to build a WCF service and a WCF client that accesses that service.

Building a WCF Service

 Building a WCF service mainly involves 3 steps

  • Defining the service contract : This defines the signatures of all the methods provided by the service
  • Implementing the service contract: This code implements the methods defined in the service contract.
  • Hosting the service

A WCF service can be hosted in four different ways
1>As a console application
2>As a website in IIS
3>As a Windows service
4>As a Windows Activation Service

In the example below I have built the WCF service a console application. In this example,  defining and implementing the service is super simple. Hosting the service is the only part that will take slightly longer to understand.

To build a WCF service as a console application, this is what you would do

1>Create a console application project and call it SimpleService

2> Add a reference to System.ServiceModel

3>Once you do that it will appear in your references folder

4> Add a new Class file to the project where you would define your service contract. What this means is that this code defines the signatures of the methods that this service will expose. Name the class file as DefineServiceContract.cs

5>Paste the code below in that page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace DotnetAnalysis
    public interface IDilbertFunctions
        /* Here you define the service contract.
           In other words, this is where you specify
           what functions (web methods) your service will provide

        string HelloWorld();

        double Add(double x, double y);

6>Add another class file called ImplementServiceContract.cs .In this page you have to implement the methods defined in your service contract. Paste the code below do do that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotnetAnalysis
    class DilbertFunctions : IDilbertFunctions

        //This is the class where you implement the web methods defined in the service contract.

        public string HelloWorld()

            return "Hello World";

        public double Add(double a, double b)
            double sum = (a + b);
            return sum;

7>Host the service by pasting the code below to the program.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace DotnetAnalysis
    class Program
        static void Main(string[] args)

            //This is where you host the service

            Uri baseAddress = new Uri("http://localhost:8000/DilbertService");//"DilbertService can be replaced with any name you want.

            ServiceHost selfHost = new ServiceHost(typeof(DilbertFunctions), baseAddress);//DilbertFunctions is the name of the class that implements the web methods

            selfHost.AddServiceEndpoint(typeof(IDilbertFunctions), new WSHttpBinding(), "DilbertFunctions");//IDilbertFunctions is the name of the interface that defines the service contract

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;

            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");

            // Close the ServiceHostBase to shutdown the service.


8> At this stage this is how your application looks like (click on the image to expand it)

9>Run the service by pressing ctrl+f5 . After which you will see a screen as shown below

10> Now if you paste this url http://localhost:8000/DilbertService  into internet explorer, you should be able to see this

Further Reading:

How to test this service using WCF test client

How to consume this service by creating a WCF client

Windows Communication Foundation .net 4.0: