Thursday, January 29, 2015

DLL HELL in .NET

DLL HELL in .NET

DLL Hell is most frequent word during the interview session. Why it is and the reason of its occurrence.

In this article I’m going to share the reason of its occurrence and the resolution.

DLL HELL:

image 

After having a look in the above image you can understand that two application A and B are using the same shared assembly

.

Now few scenarios come in front of us during the production time.

1. I have two applications, A and B installed, both of them installed on my PC.
2. Both of these applications use shared assembly SharedApp.dll
3. Somehow, I have a latest version of SharedApp.dll and installed on my PC.

4. The latest SharedApp.dll overwrite the existing .dll, Which App A was also using earlier.

5. Now App B works fine while App A doesn’t work properly cause to the newly created SharedApp.dll.

In short a newer version of .dll is not compatible with Old app .Here SharedApp.dll is with new version which is not backward compatible with App A.

So, DLL HELL is a problem where one application will install a new version of the shared component that is not backward compatible with the version already on the machine, causing all the other existing applications that rely on the shared component to break. With .NET versioning we don’t have DLL HELL problem any more

Now the resolution of this is after introducing Versioning in .Net with shared assemblies. Which is placed in GAC (Global Assembly cache).Its path “C:\Windows\assembly” and the screen shot of GAC how it looks like depicted below in image.

GAC Image:

clip_image005

GAC contains strong named assemblies. Strong named assemblies in .NET have 4 pieces in its name as listed below.

1. Name of assembly
2. Version Number
3. Culture
4. Public Key Token

If you look into the images above, you can find that Microsoft.Interop.Security.AzRoles assembly has version 2.0.0.0.

Each .dll has its own version number which describes as like below:

clip_image006

image

Now recall the Dll Hell problem with newer face with versioning concept.

 

1. I have two applications, A and B installed, both of them installed on my PC.
2. Both of these applications use shared assembly SharedApp.dll having version 1.0.0.0.
3. Somehow, I have a latest version (2.0.0.0) of SharedApp.dll and install It into GAC.

4. So, in the GAC we now have 2 versions of SharedApp.dll

5. Now App A uses its old dll with version 1.0.0.0 and App B works perfectly with SharedApp.dll version 2.0.0.0.

In summarize words .Net .Dll versioning helped to resolve this DLL Hell problem.

Hope you enjoyed this demonstration.

To learn more about MVC please go to the following link.

MVC Articles

Thanks.
Keep coding and Stay Happy Smile

Monday, January 26, 2015

Database Table Encryption Using Symmetric Key in SQL Server 2008 R2

The purpose of this article is to provide security to a database column's value so that no one can understand what the actual value is.


understand


Scenario: Actually a few days ago I had the situation to add one more layer of security, like encryption and decryption of some keys (for example SaltKey or RSAKey), that were being used in my C# code base file. These keys were being used to encrypt and decrypt the username and password, however I don't want to make these keys public to anyone (for example SaltKey or RSAKey) , because anyone can read this easily using reflector if obfuscation is not applied to the C# code base file (.cs file). So I thought to put these keys into the database and put up all the columns values in encrypted mode and decrypt it since I needed the actual values of these keys.
I studied about this from various portals before implementing. In this article I'll also share some findings that may be helpful to you to create rudimentary queries.
There are many approaches to implement encryption but I've chosen column encryption of a database table. I just encrypted and decrypted the data placed in the table. This approach takes little time to do the required procedure than the other approach.
So let's start with encryption and decryption process executed with a Symmetric Key. I've created a database with the name DBEncrypt with a table “TestTable” that has three columns in it. Kindly look at the screenshot given below:


table


TestTable


If you notice in the image shown above there are three columns with some text value. My main objective is to encrypt those values and decrypt accordingly.
Create a master key, each database can have one master key and this master key used to protect the private keys of the certificates. After this we'll create a certificate to encrypt the data in the database and symmetric key (the symmetric key used by the sender and the receiver of a message, it's a common key used to encrypt and decrypt the message). We've created a symmetric key using the certificate (EncryptTestCert).

      1: CREATE MASTER KEY ENCRYPTION  
      2: BY PASSWORD = 'Support@123'
      3: 
      4: CREATE CERTIFICATE EncryptTestCert  
      5: WITH SUBJECT = 'SupportCert'
      6: 
      7: CREATE SYMMETRIC KEY TestTableKey  
      8: WITH ALGORITHM = TRIPLE_DES ENCRYPTION  
      9: BY CERTIFICATE EncryptTestCert. 

Now it's time to create another three columns that will keep encrypted data of these three columns (SaltKey, RSAKey and PrivateKey) of table respectively. I've also added one more Column SaltKeyEnCol2 as nvarchar(max). I will share the reason to create an extra column later in this document.

 

The code given below encrypts three columns (SaltKey, RSAKey and PrivateKey) values to the newly created

  1: ALTER TABLE TestTable  
  2: ADD SaltKeyEnCol VARBINARY(256),RSAKeyEnCol VARBINARY(256),PrivateKeyEnCol VARBINARY(256)  
  3: 
  4: ALTER TABLE TestTable  
  5: ADD SaltKeyEnCol2 nvarchar(max) 
  6: 

columns above with an alter commnad. Also note that we are using the same certificate(EncryptTestCert) to open the symmetric key and make it available for use. Kindly have a look at the syntax given below.


  1: OPEN SYMMETRIC KEY TestTableKey DECRYPTION   
  2: BY CERTIFICATE EncryptTestCert,   
  3: UPDATE TestTable   
  4: SET SaltKeyEnCol = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),SaltKey),RSAKeyEnCol = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),RSAKey),PrivateKeyEnCol = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),PrivateKey) 
  5: 
Kindly manually close the symmetric key otherwise it will remain open for the current session.
After the execution of the preceding query you can have a look and see the affects made into the database. Kindly have a look at the image given below:



affects made into database



If you notice in the image above, it only shows you <Binary data> in encrypted Columns. Which was a little tricky for me initially, after looking at these values I thought I made some mistake and the data doesn't look OK.



To cater this issue, I again created another column with the name “SaltKeyEnCol2” as I have shared this in the preceding in the document and is also shown below. It helped me to see the actual value.



  1. ALTER TABLE TestTable  
  2. ADD SaltKeyEnCol2 nvarchar(max)

Please execute the SQL query given below and see the effect.


  1. OPEN SYMMETRIC KEY TestTableKey DECRYPTION  
  2. BY CERTIFICATE EncryptTestCert  
  3. UPDATE TestTable SET SaltKeyEnCol2 = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),SaltKey)

The column SaltKeyEnCol2 has some encrypted value in SaltKeyEnCol2 as depicted below in the screen shot rather than the <Binary Data> value.



SaltKeyEnCol2



As we can see above, we've achived the encryption of the required columns. Now the turn is to decrypt the data placed in the encrypted columns. Kindly refer to the image given below with the outcome.



query



Kindly find in the following the complete database query script.

  1: CREATE MASTER KEY ENCRYPTION  
  2: BY PASSWORD = 'Support@123'  
  3:   
  4: CREATE CERTIFICATE EncryptTestCert  
  5: WITH SUBJECT = 'SupportCert'  
  6:   
  7: CREATE SYMMETRIC KEY TestTableKey  
  8: WITH ALGORITHM = TRIPLE_DES ENCRYPTION  
  9: BY CERTIFICATE EncryptTestCert  
 10:   
 11: ALTER TABLE TestTable  
 12: ADD SaltKeyEnCol VARBINARY(256),RSAKeyEnCol VARBINARY(256),PrivateKeyEnCol VARBINARY(256)  
 13:   
 14: ALTER TABLE TestTable  
 15: ADD SaltKeyEnCol3 nvarchar(max)  
 16: --drop COLUMN SaltKeyEnCol3   
 17:   
 18:   
 19: OPEN SYMMETRIC KEY TestTableKey DECRYPTION  
 20: BY CERTIFICATE EncryptTestCert  
 21: UPDATE TestTable SET SaltKeyEnCol3 = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),SaltKey)  
 22:   
 23:   
 24: OPEN SYMMETRIC KEY TestTableKey DECRYPTION  
 25: BY CERTIFICATE EncryptTestCert,  
 26: UPDATE TestTable  
 27: SET SaltKeyEnCol2 = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),SaltKey),RSAKeyEnCol = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),RSAKey),PrivateKeyEnCol = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),PrivateKey)  
 28:   
 29: CLOSE SYMMETRIC KEY TestTableKey;  
 30:   
 31: OPEN SYMMETRIC KEY TestTableKey DECRYPTION  
 32: BY CERTIFICATE EncryptTestCert  
 33: SELECT CONVERT(nvarchar(max),DECRYPTBYKEY(SaltKeyEnCol2)) AS DecryptSaltKeyEnCol FROM TestTable  
 34:   
 35: OPEN SYMMETRIC KEY TestTableKey DECRYPTION  
 36: BY CERTIFICATE EncryptTestCert  
 37: SELECT CONVERT(nvarchar(max),DECRYPTBYKEY(SaltKeyEnCol2)) AS DecryptSaltKeyEnCol,CONVERT(nvarchar(max),DECRYPTBYKEY(RSAKeyEnCol)) AS DecryptRSAKeyEnCol,  
 38: CONVERT(nvarchar(max),DECRYPTBYKEY(PrivateKeyEnCol)) AS DecryptPrivateKeyEnCol FROM TestTable  
 39:   
 40: CLOSE SYMMETRIC KEY TestTableKey 

I hope it will help you somewhere. I took the idea from: Introduction to SQL Server Encryption and Symmetric Key Encryption.
Thanks For reading this articleSmile

To learn more about MVC please go to the following link.

MVC Articles

Thanks.
Keep coding and Stay Happy Smile

Thursday, January 22, 2015

Commit and Rollback using TransactionScope in LINQ

Commit and Rollback using TransactionScope in LINQ

Ship

Hi Techies

There is a very good feature to achieve commit and roll back in LINQ using TransactionScope.

For an example you are having two table  named as Customer and customerDetails.

As I've declared two tables ,Let's create a scenario , Suppose you have updated some value in current context using db.SubmitChanges() for customer table whilst other hand any exception occurs for customerDetails table then it would be weird .

Our main target is to achieve roll back transactions if something goes wrong ,rather than saving uncompleted code.

The code segment given below:

  1: using (TransactionScope tscope = new TransactionScope())
  2: 
  3: {
  4: 
  5:     Customer customer = new Customer();
  6: 
  7:     db.Customer.InsertOnSubmit(customer);    // To insert into the Customer table
  8:     db.SubmitChanges();                     // inserted into database, but transaction not yet committed   
  9:     CustomerDetails objCustomerDetails = new CustomerDetails();  // Creating an object of CustomerDetails 
 10:     db.CustomerDetails.InsertOnSubmit(objCustomerDetails);        // queues up insert to Customer table
 11:     db.SubmitChanges();    // insert done in db but still not committed
 12:     
 13:     //To rollback explicitly from a transaction execute one of the following
 14:     Transaction.Current.Rollback();
 15:     tscope.Dispose();
 16: 
 17: // To commit the complete transaction
 18:     tscope.Complete();    // The inserted in above statement are committed to the db
 19: }

This is the optimum ways i found during last day .So sharing my thoughts.

To learn more about MVC please go to the following link.

MVC Articles

Thanks.
Keep coding and Stay Happy Smile

Wednesday, January 21, 2015

LINQ Let Keyword Using C#

LINQ Let Keyword Using C#

While exploring LINQ keywords, I encountered the Let keyword and thought to write something for .Net geeks. The Let keyword gives you the liberty to use its value for the next level. This is the beauty of this keyword, that you can utilize the value on the next statement, which helps you keep your code simpler and easier to understand.

images


Example for the LINQ Let Clause Using C# in ASP.Net

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5:  
  6: namespace LINQ_LetKeyword
  7: {
  8:  
  9:     class Employee
 10:     {
 11:         public string Name { get; set; }
 12:         public string EmpID { get; set; }
 13:         public int Salary { get; set; }
 14:  
 15:     }
 16:     class Program
 17:     {
 18:         static void Main(string[] args)
 19:         {
 20:             //Object Initialization for Employee class
 21:             List<Employee> objEmployee = new List<Employee>{
 22:                     new Employee{ Name="Sachin",EmpID="I001",Salary=800},
 23:                     new Employee{ Name="Vijay",EmpID="I002",Salary=400},
 24:                     new Employee{ Name="Ashish",EmpID="I003",Salary=250},
 25:                     new Employee{ Name="Syed",EmpID="I004",Salary=300},
 26:                     new Employee{ Name="Ravish",EmpID="I005",Salary=700},
 27:                 };          
 28:  
 29:             var objresult = from emp in objEmployee
 30:                             let totalSalary = objEmployee.Sum(sal => sal.Salary)
 31:                             let avgSalary = totalSalary / 5
 32:                             where avgSalary > emp.Salary
 33:                             select emp;
 34:             foreach (var emp in objresult)
 35:             {
 36:                 Console.WriteLine("Student: {0} {1}", emp.Name, emp.EmpID);
 37:  
 38:             }
 39:             Console.ReadLine();
 40:         }
 41:     }
 42: }
 43: 
 44: LINQ Query 
 45:  
 46: var objresult = from emp in objEmployee
 47:                             let totalSalary = objEmployee.Sum(sal =>  sal.Salary)
 48:                             let avgSalary = totalSalary / 5
 49:                             where avgSalary > emp.Salary
 50:                             select emp;

 


//output :
LinqLet.jpg
I've tried to use the very simplest way to describe the "Let" keyword. Yet I look forward to your advise on this, whether I could present it in a more convenient way and if so then how.
Cheers.


Please download the relevant code file from the link given below:


LINQ LET KEYWORD USING C#


To learn more about MVC please go to the following link.

MVC Articles

Thanks.
Keep coding and Stay Happy Smile