Monday 9 May 2016

Encrypt Web config's section for ASP.NET Website

Hi guys, Welcome back, i was reading how to make website more secure, while studding i found, we can encrypt the sections of web.configs. i thought it is an interesting topic to do some R&D on. i started to work on it and now i am able to encrypt sections of web.config file.

Lets start to encrypt the web.config sections, i am encrypting to connectionString section in this article.

Steps to do a simple demo:

1. Create a new Website
2. add connectionstring element into it and connect to any DB.
3. open "Developer Command Prompt for Visual Studio" as administrator privilege.
4. change directory of command prompt to specific version of .net in which your website is as for this example i have created website in 4.5 version:

so i have changed the command directory to

C:\Windows\Microsoft.NET\Framework\v4.0.30319

5. add the following section into web.config under configuration tag:

<configProtectedData defaultProvider="SampleProvider">
<providers>
  <add name="SampleProvider" 
    type="System.Configuration.RsaProtectedConfigurationProvider, 
          System.Configuration, Version=2.0.0.0, Culture=neutral, 
          PublicKeyToken=b03f5f7f11d50a3a,
         processorArchitecture=MSIL"
    keyContainerName="SampleKeys" 
    useMachineContainer="true" />
</providers>
6. Now in command prompt run the following command

aspnet_regiis -pef "connectionStrings" "E:\New folder\WebApplication2\WebApplication2"

7. now check your web.config file, you will find the connectionString section is changed to some identical format as given below:

<connectionStrings configProtectionProvider="SampleProvider">
<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>BHvfwKGyvl2xYIxhRwvNLSwHzLgwBCSgMSSjEGiLK5zb9+K2u2WRgOSpMcjcIuJZCBThW5Ob+cOFZLdhHgPN5PAnDi0cTmoT+mk4fgPoJn2FMaND1+wcxjWtzunK9ipjnSWjNqZtbmbcj7LYppR2EOTwHAWCgZFTPIoqRV01Now=</CipherValue>
      </CipherData>
    </EncryptedKey>
  </KeyInfo>
  <CipherData>
    <CipherValue>wunR4sanau6/KBtTDqpP/KSaI5BA9Tj7AqywCHkHgQlNEdHEUHN7W0qfGR2soJ9cb7KMU2J6mDGMd08MzHvbln66RynDiQus+CrrX4Xzer2xZmqEZiEC+DmEWmVtvhZ+UjeTR1KE5CRH4W5IM8MKCMMdAKm9szqwNhMjobIsXbiulPG38qIkUHmhknyNaA34VzBthPFotSedpm4+zK1svUBjf+mE7BqksPBXCQk2SPaFsQ8uv89Mesuxkkx5zMmJZxVPkqseo/mOfcU5DyF8GbzHMHihpVe3Uc4pWPDAMu9yvj7wsW9S62z8TCb7UUeKnys6Nf0bug0v8k8BMRi6RBzBbACOtmByLot6AhtVKf+VDoUzkNSusXMWckZnD44gpV3SFNIQWMFLWK9bCZN76TqmsoeUzEJMuCuBpT+YpTA5gePD3uouUw==</CipherValue>
  </CipherData>
</EncryptedData>

that's all..Now no body will come to know what is the DB server what is the DB name and what are the creds.

And another Good thing, do are not supposed make any changes in connecting to DB from code. connect it as we do normally, no extra efforts are needed.

BBYE for Now.. will come back with any new article. till then Happy Coding...!!!!

Wednesday 20 April 2016

Dapper with MVC Application C# ASP.NET Example

Hi Guys, Hope you are enjoying coding...!!!! :) 

As i mentioned in my last post, i will come back with one of ORM.  so today i will try to explore about the new and second very fast ORM i.e. Dapper. 

Dapper is an open source, lightweight micro-ORM that simplifies data access while ensuring that your application is high-performant.

The following are the key features of Dapper:


  1. Speed and fast in performance.
  2. Operating directly to IDBConnection class that provides smoothness and running query directly to the database instead of passing data using various objects as we do in EF and ADO.NET.
  3. Static Object Binding.
  4. Dynamic Object Binding.
  5. Object Mapper.
  6. Multiple Query Support.
  7. Support for Stored Procedure.
  8. Bulk Data insert functionality.
  9. Dapper also allows fetching multiple data based on multiple inputs.
  10. Dapper allow to store bulk data at once.

Okay, lets have quick working example of DAPPER:

1. Create a Simple MVC website. 

2. Now install the Dapper from Nuget into your website. you can use "Install-Package Dapper" with package manager to install the Dapper.

Create a new Interface as below:

public interface IUserRepository
    {
        List<User> GetAll();
        User Find(int id);
        User Add(User user);
        User Update(User user);
        void Remove(int id);
        User GetUserInformatiom(int id);
    }


Now create new service Class or you can repository class as below:

  public class UserRepository : IUserRepository
    {
        private IDbConnection _db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
        public List<User> GetAll()
        {
            return this._db.Query<User>("SELECT * FROM UserDetails").ToList();
            //return null;
        }
    }

I have created the example to get the users only, you can do as you want.

Now you can call this repository method in controller:

 public ActionResult Index()
        {
            var model = _repository.GetAll();
            return View();
        }

Summary : 

Dapper.NET is extremely easy to use and offers a high degree of flexibility with regard to how data is accessed and mapped to any business object. It also has the advantage of not requiring a cumbersome XML (or similar) definition file to set it up.

Happy Coding.. 



Thursday 11 February 2016

ORM in C#

ORM, stands for Object Relation Mapping is a way to map your relational database to logical objects in the programming language which comes to an advantage to reduce the lines of code to implement a business process and provides some sort of persistency to the objects.

Based on abstraction, ORM manages the mapping details between a set of objects and underlying relational databases, XML repositories or other data sources and sinks, while simultaneously hiding the often changing details of related interfaces from developers and the code they create.

Types of ORMs available: (From Wiki)

  1. Base One Foundation Component Library, free or commercial 
  2. Castle ActiveRecord, ActiveRecord for .NET, open source 
  3. DatabaseObjects .NET, open source 
  4. DataObjects.NET, commercial 
  5. Dapper, open source 
  6. ECO, commercial but free use for up to 12 classes 
  7. Entity Framework, included in .NET Framework 3.5 SP1 and above 
  8. EntitySpaces, was commercial, now free 
  9. iBATIS, free open source, maintained by ASF but now inactive. 
  10. LINQ to SQL, included in .NET Framework 3.5 
  11. Neo, open source but now inactive. 
  12. NHibernate, open source 
  13. nHydrate, open source 
  14. Persistor.NET, free or commercial 
  15. Quick Objects, free or commercial 
  16. SubSonic, open source but now inactive 
  17. XPO, commercial 

ORM hides and encapsulates change in the data source itself, so that when data sources or their APIs change, only ORM needs to change to keep up—not the applications that use ORM to insulate themselves from this kind of effort. 


This capacity lets developers take advantage of new classes as they become available and also makes it easy to extend ORM-based applications. In many cases, ORM changes can incorporate new technology and capability without requiring changes to the code for related applications. 

Which ORM you should use depends on the answers of below questions, as yourself before going to use any of ORM,

  1. What database providers you want the ORM to support ? SQL Server,MySQL, Oracle, etc.
  2. Do you need model-first or db-first support ?
  3. What is my performance criteria [memory, processing] ?
  4. Are you going to use it in web-app or a desktop-app ?
  5. Do you have distributed clients in your application ?

NHibernate is more mature, feature rich, with a more advanced community and not likely to be discontinued when MS decides to break compatibility again. Entity Framework is more mainstream and is supported out-of-the-box. You will find more beginner books for EF, more advanced books for NH.


I will explain majorly used ORMs in my next posts. be in touch.. :)

Thanks for reading.....