November 10, 2015

SQL SERVER 2016 FEATURES

SQL Server 2016 introduces the new statement because it is very confusing when you need to check an object either it is present or not.

Previously when we need to check the Store procedure either it is exists or not we use following long lengthy syntax:


IF OBJECTPROPERTY(object_id('dbo.sp_GenerateReport'), N'IsProcedure') = 1
DROP PROCEDURE [dbo].[sp_GenerateReport]
GO

Now in the latest version of SQL Server, they reduce the long lengthy statements into one line for Store procedure, function and tables. They named the statement as 'DIE' => DROP IF EXISTS


DROP FUNCTION IF EXISTS fn_CalculateSum
DROP PROCEDURE IF EXISTS sp_GenerateReport
DROP TABLE IF EXISTS Subscriber

See that!!! this is so simple to remember and use in your daily routine queries.

Cheers

October 29, 2015

BENEFITS OF AYAT UL KURSI

1. Recite while Leaving Your House, And 70,000 Angels Will Protect You from All sides.

2. Recite On Entering Your Home, And Poverty Won't Enter Your Home.

3. Recite After Wuzu, And It Raises You 70 Times In Allah's Rank.

4. Recite Before Sleeping And 1 Angel Will Protect You The Whole Night.

5. Recite After Fard Salah And The Only Thing That Is Separating You From Paradise Is Death.

If you pass this on Its Sadqa-e-Jaria (meaning you on getting rewarded for it, every time someone one acts upon it even when you have died, up until the day of judgement).

October 26, 2015

SOME GOLDEN WORDS OF PROPHET MUHAMMAD (صلى الله عليه وآله وسلم)

1. RESPECT 3 PEOPLE
    a. TEACHER
    b. PARENTS
    c. ELDERLY

2. HAVE 3 THINGS IN YOU
    a. HONESTY
    b. FAITH
    c. GOOD DEEDS

3. FREE YOURSELF FROM 3 THINGS
    a. ARROGANCE (THINKING OTHERS AS BELOW YOU AND DENYING THE TRUTH)
    b. CHEATING
    c. DEBT

4. HAVE CONTROL OVER 3 THINGS
    a. TONGUE
    b. ANGER
    c. SOUL (SELF DESIRES)

5. SAVE YOURSELF FROM 3 THINGS
    a. BAD DEEDS
    b. BACKBITING
    c. JEALOUSY

6. OBTAIN 3 THINGS
    a. KNOWLEDGE
    b. MANNERS
    c. PIETY

7. KEEP 3 THINGS PURE
    a. BODY
    b. CLOTHES
    c. THOUGHTS

8. REMEMBER 3 THINGS
    a. DEATH
    b. FAVOR (OTHERS HELPING)
    c. ADVICE

August 28, 2015

Custom Transpose In SQL Server

When we are playing with the database queries in order to create store procedure, triggers or job...we sometimes need to pass the comma separated string of integer values into the IN clause of SQL query.

Took the example from School where case is that we need to get the list of different Students based on StudentID provided in the procedure as a comma separated string.

DECLARE @StudentIdList AS VARCHAR(8000) = '1,10,15,18,22,45,99'

So when we try to get the Student List based on this parameter using the IN clause as:

SELECT StudentID, StudentName, RollNumber, Age
FROM   Student
WHERE  StudentID IN (@StudentIdList)

What happend!! when we try to run the above query. It will return the error on the IN parameter and mesage is mentioning that Cannot able to convert varchar to bigint....(something like that)

So how do we solve the problem???

Here comes the powerful transpose concept. Here we will create a function which will convert the comma separated string into the table structure where each value will be place into the rows.

CREATE FUNCTION [dbo].[ParamsToTable]
(
    @ParameterString VARCHAR(8000)
)
RETURNS @TblParam TABLE(IdString VARCHAR(10))
AS
BEGIN
    DECLARE @SingleValue VARCHAR(10)

    WHILE LEN(@ParameterString) > 0
    BEGIN
        SET @SingleValue = LEFT(@ParameterString, ISNULL(NULLIF(CHARINDEX(',', @ParameterString) -1, -1), LEN(@ParameterString)))
        SET @ParameterString = SUBSTRING(@ParameterString, ISNULL(NULLIF(CHARINDEX(',', @ParameterString), 0), LEN(@ParameterString)) + 1, LEN(@ParameterString))
     
        INSERT INTO @TblParam VALUES (@SingleValue)
    END
RETURN
END

Use the above created function in your sql query in order to generate the desire result as:

SELECT StudentID, StudentName, RollNumber, Age
FROM   Student
WHERE  StudentID IN (SELECT * FROM ParamsToTable(@StudentIdList))

The reason to put the query block into the function is that by doing this we can use it on several places where we need such type of activity to perform.

Let me know if you have any query over this implementation.

Cheers

August 26, 2015

Recursion In LINQ

A method which called itself is called "Recursive". These methods are extensively used in daily programming practices. We use it to solve the complex problems or puzzles we face in code. Using recursion add needless complication in other programs.

Before jump into the LINQ world, let me tell you the method definition and implementation. The method should contain the reference variable parameter. It checks a condition near the top of its method body, as many recursive algorithms do.

So if you see the same method signature repeated many times in the call stack, you have a recursive method.

Back to topic, so how the we can acheive the recursion in LINQ query. It is good here to follow the example and write a LINQ query according to it.

Suppose I have list Candy. And each candy have different flavors while some flavor may extend to their child flavors. We need to calculate the 'Total Count' of candy flavors. How do we acheive this?

Diagram of this case is like this tree:


Candy --> Flavor1
Candy --> Flavor2 --> SubFlavor1 --> One, Two
Candy --> Flavor2 --> 
Candy --> Flavor2 --> SubFlavor1 --> Three --> Four, Six

SOLUTION:

We will use 'SelectMany' in order to calculate the 'Total Flavors' count. When we use 'SelectMany', it collapses many elements into a single collection. The code logic will be:


var flavorCount = candyList.SelectMany(sm => sm.Flavors).Count(); // C#

Dim flavorCount = candyList.SelectMany(Function(sm) sm.Flavors).Count() ' VB.NET

You see that!!! this is very simple in LINQ in order to count the 'Total Flavor'. Here I used 'SelectMany' in order to get the count. 

Let me know if have any queries left.

Cheers

July 30, 2015

Updates In Visual Studio 2015

In the month of July, 2015... a major release annoucement being made for VS 2015 and .Net Framework 4.6. This post is intent to share with you the great updates which are available in this version.

1. ASP.NET Tooling Improvements:
    a. JSON Editor
    b. HTML Editor Updates
    c. JavaScript Editor Improvements
    d. ReactJS Editor Support
    e. Support for JavaScript package managers like Grunt, Gulp and Task Runners

2. ASP.NET 4.6 Runtime Improvements
    a. HTTP/2 Support
    b. Support for the .Net Compiler Platform
    c. Async Model Binding For Web Forms

3. ASP.NET 5

4. Entity Framework
    a. Entity Framework 6.x
    b. Entity Framework 7

This the summary of updates came in this release. In order to read these updates in detail please visit the blog of Scott Guthrie:

June 23, 2015

ERROR: MSDTC on server 'SomeServerName' is unavailable.

This exception is rise when you use 'TransactionScope' in your LINQ to SQL or LINQ to Entity logic where updating the database with multiple tables at once. Exception is belongs to 'System.Data.SqlClient.SqlException'. Exception is raised because of 'Distributed Transaction Coordinator' which not enabled or running on your server/machine.

SOLUTION:

We have three different types of methods available in order to fix the exception:

1. Check the firewall settings:

In Run, type firewall.cpl.
Click Exceptions Tab.
Click Add Program.
Browse for Msdtc.exe (normally found under C:\Windows\System32).
Click Add Port.
In the Add A Port window, give a name in the Name field.
Give 135 in the Port Number Field.
Select TCP.
Click OK.

2. Start via Services

Method A:
   
You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES
Find the service called 'Distributed Transaction Coordinator'.
RIGHT CLICK (on it and select) > Start.

Method B:

Type services.msc in the run command box
Select “Services” manager; Hit Enter
Select the service “Distributed Transaction Coordinator
Right on the service and choose “Start

3. Use this for windows Server 2008 r2

Click Start, click Run, type dcomcnfg and then click OK to open Component Services.
In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, click to expand Distributed Transaction Coordinator and then click Local DTC.
Right click Local DTC and click Properties to display the Local DTC Properties dialog box.
Click the Security tab.
Check mark "Network DTC Access" checkbox.
Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes.
Click Apply, OK.


VERIFICATION:

We can check that either the 'Distributed Transaction Coordinator' is enabled or not. In LINQ to Entity, we use 'TransactionScope.Complete();' line at the end of transaction. Run the application using breakpoint and you can check that either this line is parsed successfully or raise error/exception. 

If it is parsed then it means 'Distributed Transaction Coordinator' is enabled successfully and if it is not try the other method mentioned above in the post.

Let me know if you face any exception after implementing the suggested methods.

Cheers

January 7, 2015

WCF Project Templates in Visual Studio

Article is copying from my publish article at experts-exchange.com

Project templates provide the class structure and definition of service contracts, data contracts and other important features in Visual Studio for Windows Communication Foundation. Using these predefined template helps you to write a service with minimal code interaction and it will lead you to build more advanced services for your projects.

There are four different types of templates present in Visual Studio. The first two are the most commonly used to build, test and deploy SOA architectural applications.

1. WCF Service Library: 

The WCF Service Library project (C#) consists of three files; IService1.cs, Service1.cs and App.config. The WCF Service Library project (VB.Net) is consists of three files; IService1.vb, Service1.vb and App.config.

This type of project is suitable when we are focused on building the services first and deployment later.

  • IService File: This is the interface where the WCF service attributes are applied. In this file you place the definitions of data contract methods/operations.
  • Service File: This file is inherited from IService interface file and includes the implementations of defined interface's data contract methods/operations. 
  • Application Configuration File: In this file, you place the definitions of secure HTTP binding, endpoints of services and other important features.


2. WCF Service Application:
The WCF Service Application project (C#) is consists of four files; IService1.cs, Service1.svc, Service1.svc.cs and Web.config. The WCF Service Application project (VB.Net) is consists of four files; IService1.vb, Service1.svc, Service1.svc.vb and Web.config.

This type of project template creates a web site to be deployed to a virtual directory and hosts a service in that website.

  • Service Contract File (IService): The service contract interface file where you place the definitions of data contract operations.
  • Service Host File (Service1.svc) and Service Implemnetation File (Service1.svc.cs): This file is inherited from the service contract file and implements the data contract operations.
  • Web Configuration File: In this file, you place the definitions of secure HTTP binding, endpoints of services and other important features.

3. WCF Workflow Service Application:
The workflow (WF) service application can be accessed like a web service. It defines distinguish templates for XAML and other imperative programming models. We can create sequential and state machine workfow projects using these templates.


4. Syndication Service Application:
This type of project template provides the syndication functionality in an application in which you can easily work with feeds in ATOM, RSS and other custom formats as a WCF service. These are allowed you to read and create them and also expose them on service endpoints.

Now hopefully, you'll understand the different project templates in WCF which will be create as per the demand and the requirement.

January 6, 2015

Encryption - Decryption using AES Algorithm

Article is copying from my publish article at experts-exchange.com

You can find plenty of algorithms on the Internet that provide the Encryption - Decryption functionality. One of them is the AES algorithm. AES stands for "Advanced Encryption Standard".

The Advanced Encryption Standard was established by US National Institute of Standards and Technology in 2001. It was based; on the work of two Belgian cryptographers, Joan Daemen and Vincent Rijmen, who submitted the proposal to NIST during the selection process.

In the AES algorithm, there is a terminology we use called 'Cipher Mode'. There are different types Cipher Modes present in the algorithm. Based on your specific needs and requirements you can select the Cipher Modes. Let's have a look at what these are and how they differentiate from other cipher modes.

1. Electronic Code Book Mode: This mode doesn't require any feedback to be applied. You pass the plain text/data using this and and get the resulted Cipher data from it directly. The main disadvantage is that this mode will return the same cipher data on passing the same type of plain text in loop; if you pass 'Hello, World!' three times in this mode then it will return same cipher data in each iteration. That is why this mode is considered as 'Vulnerable' and not recommended for use.

2. Cipher Block Chaining Mode: This mode is required to add the feeback to modify the pre-encrypted data; with the feedback it will make each cipher data different from previous result. This mode is commonly used to secure applications.

3. Cipher Feedback Mode: This mode works like a Stream Cipher where data being processed can be shorter values rather than a larger block. In this mode, instead of passing the data to AES, it gets the XORed value that is generated from AES engine on the basis of previous message history. Here only XOR function is applied to the data and returns the smaller widths of data as compared to block size.

4. Output Feedback Mode: This mode is quite similar with Cipher Feedback Mode, but does not use the Stream Cipher due to the weakness when the data width that doesn't match the blocksize of encryption algorithm.

5. Counter Mode: This mode is also very common and used in to secure an application where count value of blocksized is maintained and encrypted using XOR. 

I'm going to use the C# Console Application in order to test AES algorithm different approaches. In this post I'm going to define two techniques of AES algorithm in order to Encrypt - Decrypt data.

1. First Technique: Using Aes Class which is inherited from SymmetricAlgorithm

Main Method:


const string original = "Here is some data to encrypt!";
Console.WriteLine("Data to encypt/decrypt: " + original + "\n");

Console.WriteLine("New Technique");

// Create a new instance of the Aes class. This generates a new key and initialization vector (IV)
using (var aes = Aes.Create())
{
    if (aes == null) return;
    // Encrypt the string to an array of bytes
    var encrypted = AesMode.NewEncryptMethod(original, aes.Key, aes.IV);

    // Decrypt the bytes to a string 
    var decrypted = AesMode.NewDecryptMethod(encrypted, aes.Key, aes.IV);

    //Display the encrypted data and the decrypted data
    Console.WriteLine("Encrypted: {0}", Convert.ToBase64String(encrypted));
    Console.WriteLine("Decrypted: {0}", decrypted);
}

Classes Used:


public static byte[] NewEncryptMethod(string plainText, byte[] key, byte[] iv)
{
    // Check arguments. 
    if (plainText == null || plainText.Length <= 0)
        throw new ArgumentNullException("plainText");
    if (key == null || key.Length <= 0)
        throw new ArgumentNullException("key");
    if (iv == null || iv.Length <= 0)
        throw new ArgumentNullException("key");
    byte[] encrypted = { };

    // Create an Aes object with the specified key and IV
    using (var aes = Aes.Create())
    {
        if (aes == null) return encrypted;
        aes.Key = key;
        aes.IV = iv;

        // Create a decrytor to perform the stream transform.
        var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

        // Create the streams used for encryption. 
        using (var msEncrypt = new MemoryStream())
        {
            using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                using (var swEncrypt = new StreamWriter(csEncrypt))
                {
                    //Write all data to the stream.
                    swEncrypt.Write(plainText);
                }

                encrypted = msEncrypt.ToArray();
            }
        }
    }

    // Return the encrypted bytes from the memory stream. 
    return encrypted;
}

public static string NewDecryptMethod(byte[] cipherText, byte[] key, byte[] iv)
{
    // Check arguments. 
    if (cipherText == null || cipherText.Length <= 0)
        throw new ArgumentNullException("cipherText");
    if (key == null || key.Length <= 0)
        throw new ArgumentNullException("key");
    if (iv == null || iv.Length <= 0)
        throw new ArgumentNullException("key");

    // Declare the string used to hold 
    // the decrypted text. 
    string plainText;

    // Create an Aes object 
    // with the specified key and IV. 
    using (var aes = Aes.Create())
    {
        if (aes == null) return null;
        aes.Key = key;
        aes.IV = iv;

        // Create a decrytor to perform the stream transform.
        var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

        // Create the streams used for decryption. 
        using (var msDecrypt = new MemoryStream(cipherText))
        {
            using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (var srDecrypt = new StreamReader(csDecrypt))
                {
                    // Read the decrypted bytes from the decrypting stream and place them in a string
                    plainText = srDecrypt.ReadToEnd();
                }
            }
        }
    }

    return plainText;
}

2. Second Technique: Using Cipher Mode "ECB" and a priavate key


Main Method:


const string original = "Here is some data to encrypt!";
Console.WriteLine("Data to encypt/decrypt: " + original + "\n");

Console.WriteLine("\nOld Technique");

var encryptData = AesMode.OldEncryptMethod(original);
var decryptData = AesMode.OldDecryptMethod(encryptData);

//Display the encrypted data and the decrypted data
Console.WriteLine("Encrypted: {0}", encryptData);
Console.WriteLine("Decrypted: {0}", decryptData);

Classes Used:

// A key used to encode and later decode the data
private const string PrivateKey = "@pRiVaTeKeY123";

/// <summary>
/// OldEncryptMethod
/// </summary>
/// <param name="plainData">Contains plain data to encrypt</param>
/// <returns>Encrypt Data</returns>
public static string OldEncryptMethod(string plainData)
{
    byte[] result;
    var utf8Encoding = new UTF8Encoding();
    var hashProvider = new MD5CryptoServiceProvider();
    var tDesKey = hashProvider.ComputeHash(utf8Encoding.GetBytes(PrivateKey));
    var tDesAlgorithm = new TripleDESCryptoServiceProvider
    {
        Key = tDesKey,
        Mode = CipherMode.ECB,
        Padding = PaddingMode.PKCS7
    };

    var dataToEncrypt = utf8Encoding.GetBytes(plainData);

    try
    {
        var encryptor = tDesAlgorithm.CreateEncryptor();
        result = encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
    }
    finally
    {
        tDesAlgorithm.Clear();
        hashProvider.Clear();
    }

    return Convert.ToBase64String(result);
}

/// <summary>
/// OldDecryptMethod
/// </summary>
/// <param name="encryptData">Contains encrypt data to decrypt</param>
/// <returns>Decrypt Data</returns>
public static string OldDecryptMethod(string encryptData)
{
    byte[] results;
    var utf8Encoding = new UTF8Encoding();
    var hashProvider = new MD5CryptoServiceProvider();
    var tDesKey = hashProvider.ComputeHash(utf8Encoding.GetBytes(PrivateKey));
    var tDesAlgorithm = new TripleDESCryptoServiceProvider
    {
        Key = tDesKey,
        Mode = CipherMode.ECB,
        Padding = PaddingMode.PKCS7
    };

    var dataToDecrypt = Convert.FromBase64String(encryptData);

    try
    {
        var decryptor = tDesAlgorithm.CreateDecryptor();
        results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
    }
    finally
    {
        tDesAlgorithm.Clear();
        hashProvider.Clear();
    }

    return utf8Encoding.GetString(results);
}

Hope it helps you to perform your action in fast pace. Stay tuned!