Translate

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 asp.net 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.



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



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


cls
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"


pause


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="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>IAA6fBJIxQFSe2hoy+vEGxeY80uZmNDVrIJ/bTMMYA6VErTLvvNRSZwdKdrrAHcXSngI/GABuTUG1+kjuMx0QMdXSF+xbu7byTwwnhmeCxc0CGdnqlemKyz2XAHlYH1b9TyhEQD+CDScN0T6nn28j+LCNOdmYzAoC1Rymnj6Rws=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>ZuHH8MoSkuc7x+tyZb75pmBrepHFQLIgC56d9bbrsiavqdnaUJ71y+2Gq5Kw51Jv5RxTSOxCRSk1UBqOy872L+IzkzlKKlWjD9Ib83Y9GrTV3nzBV5iVbe91lh/ScQ9gVZtjTwYgPEn7vv6ss/ooNjm6mkAkotXp4wLMTCVlxDswZfou9zJuM7uXDQrwtiwzIITUB/5eeIO84k3m9rfSVsfaDBCcXBuGxYgB9uvtjN/tjGALohxeDWfzioylTY/iJweRmuWZleOj8VPCeHh5OWJnV0/+EVkzuWIWScD20QJmTdLq0ij9IsX4SS0m1du3t8xrDy5y58xZZJ8dEP4uNhs/qYoYN0avcVE8H5EEXG2G4WU/SpIMfKjXXp8Yrl4ETxCOftIPagQi4ERSZKEL0dCKhd0LNm8kxtLXSSoXXT7j5npCvCrSzq5FBKbfCYcJpapa+P/Kw5NtiMcHsv5UuF9kvL0udjzoG8ibgEXdLYogfylvWIqkFO0Wqi/xlbCoRlrIqa/DEFSMa0dSiKBECy6z5Bv49FlWhffB54YqMMUTOqeDPieCAvs9f9PWIf2xLYE9c4IXXaVJ+6P5iCGoDja/SDxQlXaDn03KvDQmEdvjriVie1FuOSZ1JExw/xsy</CipherValue>
      </CipherData>
    </EncryptedData>
  </connectionStrings>



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:
http://msdn.microsoft.com/en-us/library/2w117ede(v=VS.100).aspx

Thursday, August 25, 2011

ASP.NET Caching Tutorial (with examples)



There are two kinds of caching in asp.net

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 asp.net 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

Cache.Add
(
“Vendor”,                      //1
ds.Tables["Vendor"],           //2
null,                          //3
DateTime.Today.AddDays(1),     //4
Cache.NoSlidingExpiration,     //5
CacheItemPriority.NotRemovable,//6
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
http://www.windowsnetworking.com/articles_tutorials/working-application-pools-internet-information-server.html


Further Reading
ASP.NET Caching:
http://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx

Monday, August 22, 2011

C# : Difference between Array and Arraylist



System.Array
System.Collections.ArrayList
1
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.
2
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()
3.
Eg
int[] myIntArray = new int[2]
myIntArray[0]=10;
myIntArray[1]=20;


Eg
ArrayList leaderNames = new ArrayList();

 leaderNames.Add("Obama");
 leaderNames.Add(5);



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 http://dotnetanalysis.blogspot.com/2011/08/introduction-to-wcf-windows.html. 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();
            Console.WriteLine(client.Add(1,2));
            client.Close();
            Console.ReadLine();
        }
    }
}


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".
OR
"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 http://dotnetanalysis.blogspot.com/2011/08/introduction-to-wcf-windows.html). 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
{
    [ServiceContract]
    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
        */

        [OperationContract]
        string HelloWorld();

        [OperationContract]
        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;
            selfHost.Description.Behaviors.Add(smb);

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

            // Close the ServiceHostBase to shutdown the service.
            selfHost.Close();


        
        }
    }
}

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
http://dotnetanalysis.blogspot.com/2011/08/how-to-use-wcf-test-client.html

How to consume this service by creating a WCF client
http://dotnetanalysis.blogspot.com/2011/08/how-to-consume-wcf-service-wcf-client.html



Windows Communication Foundation .net 4.0: