Friday, January 27, 2012

Encrypt or Decrypt Connection Strings in web.config


Introduction

In this article I will explain how to encrypt or decrypt connection Strings in web.config file using asp.net.

Description

In Previous posts I explained lot of articles regarding Asp.net, Gridview, SQL Server, Ajax, JavaScript etc. In many of articles I used connection Strings section in web.config file to store database connection. The connection Strings section contains sensitive information of database connections including username and password of database. Is it secured to store the sensitive information of database connections in plain text files called web.config and machine.config files?
 
If we are using applications in our internal servers with security then it’s ok if we deploy our applications in shared host environment then we have chance to arise security problems to avoid these problems asp.net 2.0 provided built in protected configuration model functionality to encrypt or decrypt few sections of web.config file those are
 
RSAProtectedConfigurationProvider: This is default provider and uses the RSA public key encryption algorithm to encrypt and decrypt data.
 
DataProtectionConfgurationProvider: This provider uses windows data protection application programming interface to encrypt and decrypt the data.
 
The encrypting and decrypting of connection strings in web.config file will do by using aspnet_regiis.exe command line tool and code behind.

First Method

First we will do encryption and decryption using aspnet_regiis.exe command line tool in file system website
 
To implement encryption and decryption first create one new website using visual studio. 
 
After that open web.config file in application and add sample db connection in connectionStringssection like this 
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=RahulMittal;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
After add dbconnection in connectionString check the below steps to encrypt or decrypt the connection string in web.config.
 
1. 1) Go to Start >> All Programs >> Microsoft visual studio 2008 >> Visual Studio Tools >> Visual Studio 2008 Command Prompt (Note: if you’re using windows 7 right click on command prompt and select Run as administrator)
 
2. 2) after open command prompt type the following command aspnet_regiis.exe -pef "connectionStrings" "C:\VisualStudio2008\Authorization"
 
Here –pef indicates that the application is built as File System website. Second argumentconnectionStrings indicates that name of the configuration section needs to be encrypted. The Third argument is the physical path of the folder where the web.config file is located.
 
3. 3) after enter the command click enters if everything goes well we will get success message like “Encrypting configuration section… Succeeded!”
 
Now open your application and check connectionStrings in web.config file that would be like this
<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>ZNUbIEnOwlZzC8qbzHj5F2GS9gLYSkWCIgCJGkrgZAX8A+8oEIssyohhxUKvAubD3jizFc5IjbLGt7HNXhoFhXNTUPYz2y6tdKJDVgDmtCgVf8Z2C990zoMRBJG+VXhmgnlo1vtHYhGx8x/bBzE1prT1+xDpep98vHF22d+LrVI=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>tODWlPD0Q/B/mP14GQ/5tUxcjmhHcy9a0oPunV5osNrMQRztgi2h5V6sxJOEh+NC+G9gQNkv1huXf1s7eoZRRLy5/LDtLXzzqMUOqLSlJUs9igChvi33c9XG4rwGF15Tpn4N34bpQBt94n0rpSkQ18V9HCPzii+UO64PlA+ykDeQhc9aQr4gO3mCfUzmY2S9gsXzRbzdq0oCWBDvx8UkX2uDxaysVHC9Fo7u6IrlpU0+hOdK95Y3/A==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
Here we don’t want to write any code to decrypt the encrypted connectionString in our application because .NET automatically decrypts it. If we want to use the connection string just call it like normal way
string strconnection = ConfigurationManager.AppSettings["dbconnection"].ToString();
Now if we want to decrypt connectionStrings section in web.config use the following commandaspnet_regiis.exe -pdf "connectionStrings" "C:\VisualStudio2008\Authorization"
 
After command execute we will get message like “Decrypting configuration section… Succeeded!”

Now check your connctionStrings section in your web.config file you will see decrypted connection string.
 
Till now we learned how to encrypt and decrypt connectionStrings section in File system website. If I want to encrypt connection string in IIS based site like i.e. Deployed website for that we need to use the following commands
 
Encrypt connectionStrings in web.config of IIS based site
 
aspnet_regiis.exe -pe "connectionStrings" -app "/SampleWebSite"
Here –pe indicates that the application is built as IIS based site. Second argument connectionStrings is the name of configuration section needs to be encrypted. The Third argument -app indicates virtual directory and last argument is the name of virtual directory where application is deployed.
 
Decrypt connectionStrings in web.config of IIS based site
 
aspnet_regiis.exe -pd "connectionStrings" -app "/SampleWebSite"
Till now we learned how to encrypt and decrypt connectionStrings section in web.config file using aspnet_regiis.exe command line tool now I will explain code behind method to encrypt and decrypt the connection string section in web.config.
 
Second Method: In second method I will use RSAProtectedConfigurationProvider and DataProtectionConfgurationProvider to encrypt and decrypt connectionStrings in web.config using asp.net.
 
First open Default.aspx page and write the following code
<html xmlns="http://www.w3.org/1999/xhtml">
<head  runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1"  runat="server">
<div>
<asp:Button id="btnEncrypt" runat="server" Text="Encrypt" onclick="btnEncrypt_Click" />
<asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" onclick="btnDecrypt_Click" />
</div>
</form>
</body>
</html>
After that open code behind page and add the following namespace references
using System;
using System.Configuration;
using System.Web.Configuration;
After add namespaces write the following code in code behind

C# code

string provider = "RSAProtectedConfigurationProvider";
string section = "connectionStrings";
protected void Page_Load(object sender, EventArgs e)
{
 
}
protected void btnEncrypt_Click(object sender, EventArgs e)
{
   Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = confg.GetSection(section);
   if (configSect != null)
   {
      configSect.SectionInformation.ProtectSection(provider);
      confg.Save();
   }
}
 
protected void btnDecrypt_Click(object sender, EventArgs e)
{
   Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = config.GetSection(section);
   if (configSect.SectionInformation.IsProtected)
   {
      configSect.SectionInformation.UnprotectSection();
      config.Save();
   }
}

VB.NET

Imports System.Web.Configuration
Partial Class _Default
   Inherits System.Web.UI.Page
   Private provider As String = "RSAProtectedConfigurationProvider"
   Private section As String = "connectionStrings"
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
   End Sub
   Protected Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
      Dim confgSect As ConfigurationSection = confg.GetSection(section)
      If confgSect IsNot Nothing Then
         confgSect.SectionInformation.ProtectSection(provider)
         confg.Save()
      End If
   End Sub
   Protected Sub btnDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
      Dim confgSect As ConfigurationSection = config.GetSection(section)
      If confgSect.SectionInformation.IsProtected Then
         confgSect.SectionInformation.UnprotectSection()
         config.Save()
      End If
   End Sub
End Class
 
After that open web.config file in application and add sample db connection in connectionStrings section like this 
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=RahulMittal;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
Now run your application and check your web.config file after click on Encrypt button that would be like this 
<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>WagJ9DDjWTNc1nmYVNQXaQqXalQzXaiCHAOtUJvTWBRZiuT6UK1fBElM80PnL6dC5Umb8qvfHdkSMgoMW9CJzwOTZ0zTy17JBGZqRQmlfW2G9LacoWIil0UrxjhgmJmRXhwXHFpdGwEVl7AoQGVlJGabXuChutaTxmfGOoUbCr0=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>qry5qnr3qxOgyoNPeP7OKEiHpr/PPTsaeQ2mYUsSK7cg4Kkl9uPO4RyUXgBIkgCTsjbObqLlyndcSBnYyek6bxG/IBL82G1R5J1ci8i1eyt8kIDqouzYOx5vtouErld4z1L+7WGf9Wg37QAH5RiiEfkCHndJJq3dTqjxnnXZSno6NgbxSXDfqzwE/eKDVhGV3oaTQSfjVmO8e5a9wvREYeeyasDhojx8J2mdy7/Q9rEIpv98RTiRxA==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings> 
If we want to implement encryption and decryption with “DataProtectionConfigurationProvider” just replace “RSAProtectedConfigurationProvider” with “DataProtectionConfigurationProvider” and use same code.

What is DataContract and ServiceContract?

Data represented by creating DataContract which expose the
data which will be transefered /consumend from the serive
to its clients.

**Operations which is the functions provided by this
service.

To write an operation on WCF,you have to write it as an
interface,This interface contains the "Signature" of the
methods tagged by ServiceContract attribute,and all methods
signature will be impelemtned on this interface tagged with
OperationContract attribute.

and to implement these serivce contract you have to create
a class which implement the interface and the actual
implementation will be on that class.


Code Below show How to create a Service Contract:


[ServiceContract]
Public Interface IEmpOperations
{
[OperationContract]
Decimal Get EmpSal(int EmpId);

}

Class MyEmp: IEmpOperations
{
Decimal Get EmpSal()
{
// Implementation of this method.
}
}

Monday, January 23, 2012

Agile Terminology


What is Scrum?

Scrum is an agile approach to software development. Rather than a full process or methodology, it is a framework. So instead of providing complete, detailed descriptions of how everything is to be done on the project, much is left up to the software development team. This is done because the team will know best how to solve the problem they are presented. This is why, for example, a sprint planning meeting is described in terms of the desired outcome (a commitment to set of features to be developed in the next sprint) instead of a set of Entry criteria, Task definitions, Validation criteria, and Exit criteria (ETVX) as would be provided in most methodologies.
Scrum relies on a self-organizing, cross-functional team. The scrum team is self-organizing in that there is no overall team leader who decides which person will do which task or how a problem will be solved. Those are issues that are decided by the team as a whole. The team is cross-functional so that everyone necessary to take a feature from idea to implementation is involved.
These agile development teams are supported by two specific individuals: a ScrumMaster and a product owner. The ScrumMaster can be thought of as a coach for the team, helping team members use the Scrum framework to perform at their highest level. The product owner represents the business, customers or users and guides the team toward building the right product.
Scrum projects make progress in a series of sprints, which are timeboxed iterations no more than a month long. At the start of a sprint, team members commit to delivering some number of features that were listed on the project's product backlog. At the end of the sprint, these features are done--they are coded, tested, and integrated into the evolving product or system. At the end of the sprint a sprint review is conducted during which the team demonstrates the new functionality to the product owner and other interested stakeholders who provide feedback that could influence the next sprint.

Roles

Scrum Team
Product Owner, ScrumMaster and Team
Product Owner
The person responsible for maintaining the Product Backlog by representing the interests of the stakeholders.
ScrumMaster
The person responsible for the Scrum process, making sure it is used correctly and maximizing its benefits.
Team
A cross-functional group of people responsible for managing itself to develop the product.

Artifacts

Sprint burn down chart
Daily progress for a Sprint over the sprint’s length.
Product backlog
A prioritized list of high level requirements.
Sprint backlog
A prioritized list of tasks to be completed during the sprint.

Saturday, January 14, 2012

SQL Query to get Second Highest Salary of the Employee


SELECT min(salary) AS high5 FROM employee WHERE salary IN(SELECT DISTINCT TOP 5 salary FROM orders ORDER BY salary DESC)

Diffrence Between session.clear() and session.abandon()


Session.Abandon() destroys the session and the Session_OnEnd event is triggered.
Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.  

Wednesday, January 4, 2012

How to find Duplicates row in a SQL Table


Here's a handy query for finding duplicates in a table. Suppose you want to find all email addresses in a table that exist more than once:
SELECT email, 
 COUNT(email) AS NumOccurrences
FROM users
GROUP BY email
HAVING ( COUNT(email) > 1 )
You could also use this technique to find rows that occur exactly once:
SELECT email
FROM users
GROUP BY email
HAVING ( COUNT(email) = 1 )

Tuesday, January 3, 2012

Jquery Selector Editor

Difference between user defined function and stored procedure


Procedure may return none or more values
Function must always return one value either a scalar value or a table

Procedure have input,output parameters
Functions have only input parameters
Stored procedures are called independently by EXEC command 

 Functions are called from within SQL statement.
Functions can be called from procedure

Procedures cannot be called from function

Exception can be handled in Procedure by try-catch block
but try-catch block cannot be used in a function.(error-handling)
Transaction management possible in procedure

but not in function.

Advantages of User Defined Functions
Before SQL 2000, User Defined Functions (UDFs), were not available. Stored Procedures were often used in their place. When advantages or disadvantages of User Defined Functions are discussed, the comparison is usually to Stored Procedures.
One of the advantages of User Defined Functions over Stored Procedures, is the fact that a UDF can be used in a Select, Where, or Case statement. They also can be used to create joins. In addition, User Defined Functions are simpler to invoke than Stored Procedures from inside another SQL statement.

Disadvantages of User Defined Functions
User Defined Functions cannot be used to modify base table information. The DML statements INSERT, UPDATE, and DELETE cannot be used on base tables. Another disadvantage is that SQL functions that return non-deterministic values are not allowed to be called from inside User Defined Functions. GETDATE is an example of a non-deterministic function. Every time the function is called, a different value is returned. Therefore, GETDATE cannot be called from inside a UDF you create.

Types of User Defined Functions
There are three different types of User Defined Functions. Each type refers to the data being returned by the function. Scalar functions return a single value. In Line Table functions return a single table variable that was created by a select statement. The final UDF is a Multi-statement Table Function. This function returns a table variable whose structure was created by hand, similar to a Create Table statement. It is useful when complex data manipulation inside the function is required.

Scalar UDFs
Our first User Defined Function will accept a date time, and return only the date portion. Scalar functions return a value. From inside Query Analyzer, enter:
 
CREATE FUNCTION dbo.DateOnly(@InDateTime datetime)
RETURNS varchar(10)
AS
BEGIN
        DECLARE @MyOutput varchar(10)
        SET @MyOutput = CONVERT(varchar(10),@InDateTime,101)
        RETURN @MyOutput
END
To call our function, execute: SELECT dbo.DateOnly(GETDATE())
Notice the User Defined Function must be prefaced with the owner name, DBO in this case. In addition, GETDATE can be used as the input parameter, but could not be used inside the function itself. Other built in SQL functions that cannot be used inside a User Defined Function include: RAND, NEWID, @@CONNCECTIONS, @@TIMETICKS, and @@PACK_SENT. Any built in function that is non-deterministic.
The statement begins by supplying a function name and input parameter list. In this case, a date time value will be passed in. The next line defines the type of data the UDF will return. Between the BEGIN and END block is the statement code. Declaring the output variable was for clarity only. This function should be shortened to:
 
CREATE FUNCTION testDateOnly(@InDateTime datetime)
RETURNS varchar(10)
AS
BEGIN
        RETURN CONVERT(varchar(10),@InDateTime,101)   
END
Inline Table UDFs
These User Defined Functions return a table variable that was created by a single select statement. Almost like a simply constructed non-updatable view, but having the benefit of accepting input parameters.
This next function looks all the employees in the pubs database that start with a letter that is passed in as a parameter. In Query Analyzer, enter and run:
 
USE pubs
GO
 
CREATE FUNCTION dbo.LookByFName(@FirstLetter char(1))
RETURNS TABLE
AS
RETURN SELECT *
FROM employee
WHERE LEFT(fname, 1) =  @FirstLetter
To use the new function, enter:
SELECT * FROM dbo.LookByFName('A')
All the rows having a first name starting with A were returned. The return is a Table Variable, not to be confused with a temporary table. Table variables are new in SQL 2000. They are a special data type whose scope is limited to the process that declared it. Table variables are stated to have performance benefits over temporary tables. None of my personal testing has found this result though.
Multi Statement UDFs
Multi Statement User Defined Functions are very similar to Stored Procedures. They both allow complex logic to take place inside the function. There are a number of restrictions unique to functions though. The Multi Statement UDF will always return a table variable–and only one table variable. There is no way to return multiple result sets. In addition, a User Defined Function cannot call a Stored Procedure from inside itself. They also cannot execute dynamic SQL. Remember also, that UDFs cannot use non-deterministic built in functions. So GETDATE and RAND cannot be used. Error handling is restricted. RAISERROR and @@ERROR are invalid from inside User Defined Functions. Like other programming languages, the purpose of a User Defined Function is to create a stand-alone code module to be reused over and over by the global application.
For a Multi Statement test, we will create a modified version of the LookByFName function. This new function will accept the same input parameter. But rather than return a table from a simple select, a specific table will be created, and data in it will be manipulated prior to the return:
CREATE FUNCTION dbo.multi_test(@FirstLetter char(1))
RETURNS @Result TABLE
        (
        fname varchar(20),
        hire_date datetime,
        on_probation char(1)
        )
AS
BEGIN
        INSERT INTO @Result
               (fname, hire_date)
               SELECT fname, hire_date
               FROM employee
               WHERE LEFT(fname, 1) =  @FirstLetter
        
        UPDATE @Result
        SET on_probation = 'N'
        
        UPDATE @Result
        SET on_probation = 'Y'
        WHERE hire_date < '01/01/1991'
        
        RETURN
END
To use the new function, execute:
SELECT * FROM dbo.multi_test('A')
With the new Multi Statement Function, we can manipulate data like a Stored Procedure, but use it in statement areas like a View.
For example, only specific columns can be returned.
SELECT fname FROM dbo.multi_test('A')
The function can also be joined like a view:
SELECT e.lname, f.fname
FROM employee e INNER JOIN dbo.multi_test('A') f ON e.fname = f.fname
 
Conclusion
User Defined Functions offer an excellent way to work with code snippets. The main requirement is that the function be self-contained. Not being able to use non-deterministic built in functions is a problem, but if it can be worked around, UDFs will provide you with a programming plus.
 
Happy Programming !!