January 31, 2013

Understanding Async Programming

It is easy to invoke Asynchronous methods in VS 2012 RC using “asyncfeature. To use “await” operator in method you have to modified your method with “async” modifier.

Using asynchronous methods instead of synchronous methods can provide benefits. Asynchronous makes UI applications more responsive because the UI thread that launches that operation can perform other work. Asynchronous also improves the scalability of server-based application by reducing the need for threads.

The work flow in asynchronous programming is very simple as compared with synchronous programming, when we modify method with “async” modifier then during method calling control reaches an “await” expression in async method, control returns to the caller and progress in the method is suspended till awaited task completes. When the task is complete, execution can resume in the method.

Checkout this example diagram took from MSDN blog.

The numbers in above diagram corresponds to following steps.
  1. An event handler calls and awaits the AccessTheWebAsync” async method.

  2. AccessTheWebAsync” creates an HttpClient instance and the calls  the GetStringAsnc method to the download the contents of website as a string.

  3. Something happens in GetStringAsync that suspends its progress. Perhaps it must wait for a website to download or some other blocking activity. To avoid blocking resources, GetStringAsync yields control to its caller, “AccessTheWebAsync”.

  4. BecausegetStringTask” hasn't been awaited yet, “AccessTheWebAsync” can continue with other work that doesn't depend on the final result from GetStringAsync. That work is represented by a call to the synchronous method “DoIndependentWork”.

  5. DoIndependentWork” is a synchronous method that does its work and returns to its caller. 

  6. AccessTheWebAsync” has run out of work that it can do without a result from “getStringTask.AccessTheWebAsync” next wants to calculate and return the length of the downloaded string, but the method can't calculate that value until the method has the string.

  7. GetStringAsync completes and produces a string result. The string result isn't returned by the call to GetStringAsync in the way that you might expect. (Remember that the method already returned a task in step 3.) Instead, the string result is stored in the task that represents the completion of the method, “getStringTask”. The await operator retrieves the result from “getStringTask”. The assignment statement assigns the retrieved result to “urlContents”.

  8. When “AccessTheWebAsync” has the string result, the method can calculate the length of the string. Then the work of “AccessTheWebAsync” is also complete, and the waiting event handler can resume. In the full example at the end of the topic, you can confirm that the event handler retrieves and prints the value of the length result. 
To better undestand what is actually is asynchronous programming, consider the difference between synchronous and asynchronous behavior.

synchronous method returns when its work is complete (step 5), but an async method returns a task value when its work is suspended (steps 3 and 6).

When the async method eventually completes its work, the task is marked as completed and the result, if any, is stored in the task. 

January 9, 2013

Select columns as rows from table

To select column as row from table in SQL Server, use this code

---------------------
SQL QUERY :
---------------------


SELECT     t.name AS table_name, 
           SCHEMA_NAME(schema_id) AS schema_name,
           c.name AS column_name
FROM       sys.tables AS t
INNER JOIN sys.columns c 
               ON t.OBJECT_ID = c.OBJECT_ID
WHERE      t.name = 'Test'
ORDER BY   schema_name, table_name;



-----------------------------------
SQL QUERY OUTPUT :
-----------------------------------


Test     dbo TestId
Test     dbo NameTitle
Test     dbo NormalValues


Simply Tricky Codes

Today I am sharing with some unique but popular codes which are still being ask in interviews for fresh graduates. First I want to give you the list of those codes. (This is final release, perhaps it would grow with passage of time and technology)
  1. Calculate Age from DOB
  2. Is string contains integer using Regular Expression
  3. Auto-Number generation of specific length
  4. Totally reverse the string
  5. Generate Year and Month
  6. Out Parameter
Calculate Age from DOB

C#.Net Code

static int CalculateAge(DateTime BirthDate)
{
    int YearsPassed = DateTime.Now.Year - BirthDate.Year;
    
    if (DateTime.Now.Month < BirthDate.Month || (DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day))
    {
        YearsPassed--;
    }

    return YearsPassed;
}

VB.NET Code

Private Shared Function CalculateAge(BirthDate As DateTime) As Integer
 Dim YearsPassed As Integer = DateTime.Now.Year - BirthDate.Year

 If DateTime.Now.Month < BirthDate.Month OrElse (DateTime.Now.Month = BirthDate.Month AndAlso DateTime.Now.Day < BirthDate.Day) Then
  YearsPassed -= 1
 End If

 Return YearsPassed
End Function

Is string contains integer using Regular Expression

C#.Net Code

string value = "abc123";
bool testValue = Regex.IsMatch(value, @"\d");

if (testValue)
{
    Console.WriteLine("Passed");
}
else
{
    Console.WriteLine("Failed");
}

VB.NET Code

Dim value As String = "abc123"
Dim testValue As Boolean = Regex.IsMatch(value, "\d")

If testValue Then
 Console.WriteLine("Passed")
Else
 Console.WriteLine("Failed")
End If

Auto-Number generation of specific length

C#.Net Code

string uniqueId = "000000";
int newNumber = Convert.ToInt32(uniqueId) + 1;
uniqueId = newNumber.ToString("000000");
Console.WriteLine(uniqueId);

VB.NET Code

Dim uniqueId As String = "000000"
Dim newNumber As Integer = Convert.ToInt32(uniqueId) + 1
uniqueId = newNumber.ToString("000000")
Console.WriteLine(uniqueId)

Totally reverse the string

C#.Net Code

var input = "hello world";
string output = "";

for (int i = input.Length - 1; i >= 0; i--)
{
    output += input[i];
}

Console.WriteLine(output);

VB.NET Code

Dim input = "hello world"
Dim output As String = ""

For i As Integer = input.Length - 1 To 0 Step -1
 output += input(i)
Next

Console.WriteLine(output)

Generate Year and Month

C#.Net Code

for (int i = DateTime.Now.Year; i >= 1990; i--)
{
    Console.WriteLine(i);
}

for (int i = 1; i <= 12; i++)
{
    Console.WriteLine(Convert.ToDateTime(i + "/1/2012").ToString("MMMM"));
}

VB.NET Code

For i As Integer = DateTime.Now.Year To 1990 Step -1
 Console.WriteLine(i)
Next

For i As Integer = 1 To 12
 Console.WriteLine(Convert.ToDateTime(i + "/1/2012").ToString("MMMM"))
Next

Out Parameter

C#.Net Code

var seq = new List<string> { "1", "Blah", "3" };
int temp = 0;
var nums =
    from item in seq
    let success = int.TryParse(item, out temp)
    orderby item
    select success ? temp : 0;
foreach (var num in nums)
{
    Console.WriteLine(num);
}

VB.NET Code

Dim seq = New List(Of String)() With { _
 "1", _
 "Blah", _
 "3" _
}
Dim temp As Integer = 0
Dim nums = _
 Let success = Integer.TryParse(item, temp) _
 Order By item
For Each num As var In nums
 Console.WriteLine(num)
Next

Get the different between two DateTime

You found a lot of code on internet related to DateTime difference in terms of Year, Months and Days and also for Hours, Minutes and Seconds. Here I am showing you my code which is very simple and easy to understand. 

----------------------C#.NET Code :----------------------


-------- METHOD ---------------------

static string GetDateTimeDurationFromDateDiff(DateTime startDate, DateTime endDate)
{
    #region Get Year, Month, Days

    string duration = string.Empty;
    int year = 0, month = 0, days = 0;

    var timeSpan = new TimeSpan();
    timeSpan = endDate.Subtract(startDate);
    year = (timeSpan.Days / 365);

    do
    {
        for (int i = 0; i <= 12; i++)
        {
            if (endDate.Subtract(startDate.AddYears(year).AddMonths(i)).Days > 0)
            {
                month = i;
            }
            else
            {
                break;
            }
        }

        if (month > 12)
        {
            year = year + 1;
        }
    }
    while (month > 12);

    days = endDate.Subtract(startDate.AddYears(year).AddMonths(month)).Days;

    if (year > 0)
    {
        duration += year.ToString() + "Year(s) ";
    }

    if (month > 0)
    {
        duration += month.ToString() + " Month(s) ";
    }
    if (days > 0)
    {
        duration += days.ToString() + " Day(s)";
    }

    #endregion

    #region Get Hours, Minutes, Seconds

    TimeSpan span = endDate.Subtract(startDate);
    duration +=
        " " + span.Hours + " hour(s) " + span.Minutes + " minute(s) " + span.Seconds + " second(s) ";

    #endregion

    return duration.Trim();            
}

-------- METHOD CALLING ---------

DateTime startDate = Convert.ToDateTime("08/01/2012 09:00:00 AM");
string getDuration = GetDateTimeDurationFromDateDiff(startDate, DateTime.Now);
Console.WriteLine(getDuration);

-------- OUTPUT ----------------------

5 month(s) 8 day(s) 6 hour(s) 36 minute(s) 17 second(s)

------------------------VB.NET Code :------------------------


-------- METHOD ---------------------

Private Shared Function GetDateTimeDurationFromDateDiff(startDate As DateTime, endDate As DateTime) As String
    '#Region "Get Year, Month, Days"

    Dim duration As String = String.Empty
    Dim year As Integer = 0, month As Integer = 0, days As Integer = 0

    Dim timeSpan = New TimeSpan()
    timeSpan = endDate.Subtract(startDate)
    year = (timeSpan.Days / 365)

    Do
        For i As Integer = 0 To 12
         If endDate.Subtract(startDate.AddYears(year).AddMonths(i)).Days > 0 Then
          month = i
         Else
          Exit For
         End If
        Next

        If month > 12 Then
         year = year + 1
        End If
    Loop While month > 12

    days = endDate.Subtract(startDate.AddYears(year).AddMonths(month)).Days

    If year > 0 Then
        duration += year.ToString() + "Year(s) "
    End If

    If month > 0 Then
        duration += month.ToString() + " Month(s) "
    End If
    If days > 0 Then
        duration += days.ToString() + " Day(s)"
    End If

    '#End Region

    '#Region "Get Hours, Minutes, Seconds"

    Dim span As TimeSpan = endDate.Subtract(startDate)
    duration += " " + span.Hours + " hour(s) " + span.Minutes + " minute(s) " + span.Seconds + " second(s) "

    '#End Region

    Return duration.Trim()
End Function

-------- METHOD CALLING ---------

Dim startDate As DateTime = Convert.ToDateTime("08/01/2012 09:00:00 AM")
Dim getDuration As String = GetDateTimeDurationFromDateDiff(startDate, DateTime.Now)
Console.WriteLine(getDuration)

-------- OUTPUT ----------------------

5 month(s) 8 day(s) 6 hour(s) 36 minute(s) 17 second(s)

Convert LINQ List To Datatable

Some times you need to convert LINQ query list to datatable in specific cases but there is none of any built-in function present in .net framework to convert it into datatable.

After using some built-in, I successfully able to convert LINQ list into datatable. Checkout my code.

------------
C#.NET :
------------

public static DataTable LINQToDataTable<T>(IEnumerable<T> linqList) 
{
    var dtReturn = new DataTable();
    PropertyInfo[] columnNameList = null;

    if (linqList == null) return dtReturn;

    foreach (T t in linqList) 
    {
        // Use reflection to get property names, to create table, Only first time, others will follow 
        if (columnNameList == null) 
        {
            columnNameList = ((Type)t.GetType()).GetProperties();

            foreach (PropertyInfo columnName in columnNameList) 
            {
                Type columnType = columnName.PropertyType;

                if ((columnType.IsGenericType) && (columnType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    columnType = columnType.GetGenericArguments()[0];
                }

                dtReturn.Columns.Add(new DataColumn(columnName.Name, columnType));
            }
        }

        DataRow dataRow = dtReturn.NewRow();

        foreach (PropertyInfo columnName in columnNameList)
        {
            dataRow[columnName.Name] = 
                columnName.GetValue(t, null) == null ? DBNull.Value : columnName.GetValue(t, null);
        }

        dtReturn.Rows.Add(dataRow);
    }

    return dtReturn;
}

------------
VB.NET :
------------

Public Shared Function LINQToDataTable(Of T)(linqList As IEnumerable(Of T)) As DataTable
 Dim dtReturn = New DataTable()
 Dim columnNameList As PropertyInfo() = Nothing

  If linqList Is Nothing Then
  Return dtReturn
 End If

  For Each t As T In linqList
  ' Use reflection to get property names, to create table, Only first time, others will follow 
  If columnNameList Is Nothing Then
   columnNameList = DirectCast(t.[GetType](), Type).GetProperties()

    For Each columnName As PropertyInfo In columnNameList
    Dim columnType As Type = columnName.PropertyType

     If (columnType.IsGenericType) AndAlso (columnType.GetGenericTypeDefinition() = GetType(Nullable(Of ))) Then
     columnType = columnType.GetGenericArguments()(0)
    End If

     dtReturn.Columns.Add(New DataColumn(columnName.Name, columnType))
   Next
  End If

   Dim dataRow As DataRow = dtReturn.NewRow()

   For Each columnName As PropertyInfo In columnNameList
   dataRow(columnName.Name) = If(columnName.GetValue(t, Nothing) Is Nothing, DBNull.Value, columnName.GetValue(t, Nothing))
  Next

   dtReturn.Rows.Add(dataRow)
 Next

  Return dtReturn
End Function

Handle Response.Statuscode=404

-------------------
DEFINITION :
-------------------

The 404 or Not Found error message is a HTTP Standard Response Code indicating that client was able to communicate with the server but the server could not find what was requested.


-----------------
SOLUTION :
-----------------

You can handle Error Code 404 in following ways.

There are three places in ASP.NET to define what happens to these unhandled errors.

  • In web.config file, Custom Error section. (Use it within <system.web>)
<customErrors mode="On" defaultRedirect="Error.htm">
       <error statusCode="500" redirect="Error500.htm">
       <error statusCode="401" redirect="Error401.htm" />
       <error statusCode="404" redirect="Error404.htm" />
      <error statusCode="403" redirect="Error403.htm" />
</customErrors>
  • In global.asax file, Application_Error method.
  • In code-behind file, Page_Error method.
The actual order to error handling is as follow.
  • In code-behind file
  • In global.asax file
  • In web.config file

January 3, 2013

Connection String Encryption Decryption in web.config / app.config file


To secure the data of any type is the critical issue now a days. There are plenty of method available on internet to secure your data from breaching / hacking. Developers around the world using different techniques to secure userId and Password of connection string. In this post I add another method to secure your connection string.

You can create a .dll file of that methods and use it where you want. Let suppose your connection string format in app.config or web.config as:

<connectionStrings>
    <add name="ConnectionString"
      connectionString="Data Source=MachineName\ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserId;Password=Password" providerName ="System.Data.SqlClient" />
</connectionStrings>

Use below mention encrpt function to convert plain connection string into encrypted form so your connection string becomes like:

<connectionStrings>
<add name="ConnectionString" 
  connectionString="7Os+mKN5qLvQWu9FfIhHrVPNWoPvz875oi+s9o7nvI529cFnim2U9AE9g9865ZF0L4Jaae+94dxM9enuRAskIWfW5kpWFUhfBAPYg1YQoV4ptgRH+qPiS+ByaA8CcxsSst0oCZWFN6ejg5+a2jhgHj2c1QWlI1KhZckultjWsUw=" 
  providerName ="System.Data.SqlClient" />    
</connectionStrings>

So whenever you call connection string from app.config or web.config file, first decrypt it using below mention function and then use it like:


------
C# :
------


var getConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var decryptConnection = DecryptConnection(getConnectionString);

using (SqlConnection connection = new SqlConnection(decryptConnection))
{
    // To some thing here
}

------------------
NameSpaces :
------------------

using System.Security.Cryptography;
using System.Configuration;
using System.Data.SqlClient;

------------------
Initialization : 
------------------

const string passphrase = "connection";

---------------
Encryption :
---------------

private static string EncryptConnection(string connectionString)
{
    byte[] results;
    var uTF8Encoding = new UTF8Encoding();
    var HashProvider = new MD5CryptoServiceProvider();
    byte[] TDESKey = HashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase));
    var tDESAlgorithm = new TripleDESCryptoServiceProvider();

    tDESAlgorithm.Key = TDESKey;
    tDESAlgorithm.Mode = CipherMode.ECB;
    tDESAlgorithm.Padding = PaddingMode.PKCS7;
    byte[] dataToEncrypt = uTF8Encoding.GetBytes(connectionString);

    try
    {
        ICryptoTransform Encryptor = tDESAlgorithm.CreateEncryptor();
        results = Encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
    }
    finally
    {
        tDESAlgorithm.Clear();
        HashProvider.Clear();
    }

    return Convert.ToBase64String(results);
}

---------------
Decryption :
---------------

private static string DecryptConnection(string connectionString)
{
    byte[] results;
    var uTF8Encoding = new UTF8Encoding();
    var hashProvider = new MD5CryptoServiceProvider();
    byte[] tDESKey = hashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase));
    var tDESAlgorithm = new TripleDESCryptoServiceProvider();

    tDESAlgorithm.Key = tDESKey;
    tDESAlgorithm.Mode = CipherMode.ECB;
    tDESAlgorithm.Padding = PaddingMode.PKCS7;
    byte[] dataToDecrypt = Convert.FromBase64String(connectionString);

    try
    {
        ICryptoTransform Decryptor = tDESAlgorithm.CreateDecryptor();
        results = Decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
    }
    finally
    {
        tDESAlgorithm.Clear();
        hashProvider.Clear();
    }

    return uTF8Encoding.GetString(results);
}
-------------
VB.Net :
-------------

Dim getConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim decryptConnection = DecryptConnection(getConnectionString)

Using connection As New SqlConnection(decryptConnection)
     ' Do some thing here
End Using

-----------------
Initialization :
--------------------

Imports System.Security.Cryptography
Imports System.Configuration
Imports System.Data.SqlClient


---------------
Encryption :
---------------


Private Shared Function EncryptConnection(connectionString As String) As String
 Dim results As Byte()
 Dim uTF8Encoding = New UTF8Encoding()
 Dim HashProvider = New MD5CryptoServiceProvider()
 Dim TDESKey As Byte() = HashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase))
 Dim tDESAlgorithm = New TripleDESCryptoServiceProvider()

 tDESAlgorithm.Key = TDESKey
 tDESAlgorithm.Mode = CipherMode.ECB
 tDESAlgorithm.Padding = PaddingMode.PKCS7
 Dim dataToEncrypt As Byte() = uTF8Encoding.GetBytes(connectionString)

 Try
  Dim Encryptor As ICryptoTransform = tDESAlgorithm.CreateEncryptor()
  results = Encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length)
 Finally
  tDESAlgorithm.Clear()
  HashProvider.Clear()
 End Try

 Return Convert.ToBase64String(results)
End Function



------------------
Dencryption :
------------------


Private Shared Function DecryptConnection(connectionString As String) As String
 Dim results As Byte()
 Dim uTF8Encoding = New UTF8Encoding()
 Dim hashProvider = New MD5CryptoServiceProvider()
 Dim tDESKey As Byte() = hashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase))
 Dim tDESAlgorithm = New TripleDESCryptoServiceProvider()

 tDESAlgorithm.Key = tDESKey
 tDESAlgorithm.Mode = CipherMode.ECB
 tDESAlgorithm.Padding = PaddingMode.PKCS7
 Dim dataToDecrypt As Byte() = Convert.FromBase64String(connectionString)

 Try
  Dim Decryptor As ICryptoTransform = tDESAlgorithm.CreateDecryptor()
  results = Decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length)
 Finally
  tDESAlgorithm.Clear()
  hashProvider.Clear()
 End Try

 Return uTF8Encoding.GetString(results)
End Function

January 2, 2013

A network-related or instance-specific error occurred while establishing a connection to SQL Server

This error comes when you are unable to pass correct credentials from application to connect with database. There are many different ways to connect your application with database server. Some times this error comes when you pass wrong userId and password to database or you are trying to access database server through LAN.

During trying to access database server through LAN, there are many things mess up.

  1. Wrong userId and password
  2. Ping interval breaking
  3. System is shutdown etc
To resolve this issue, make sure your following steps are in working condition correctly
  • Database Engine is configured correctly to accept remote connections
Make sure your database engine is configured to accept remote connections. To Enable remote connections do following things. 
  1. Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration
  2. Click on Surface Area Configuration for Services and Connections
  3. Select the instance that is having a problem > Database Engine > Remote Connections
  4. Enable local and remote connections
  5. Restart instance

  • SQL Server Service account
If you are not using a domain account as a service account and you are using NETWORK SERVICE, you may want to switch this first before proceeding.
  • SQL Server Instance
If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings in your application. Usually the format needed to specify the database server is machinename\instancename. Check your connection string as well
  • Firewall Exception
You may need to create an exception on the firewall for the SQL Server instance and port you are using:
  1. Start > Run > Firewall.cpl
  2. Click on exceptions tab
  3. Add the sqlservr.exe (typically located in C:\Program Files (x86)\Microsoft SQL Server\MSSQL.x\MSSQL\Binn, check your installs for the actual folder path), and port (default is 1433)
  4. Check your connection string as well
Also you may also need to create an exception in your firewall for SQL Browser.

Visual Studio 2008 Crystal Reports deployment

To deploy your application which are using crystal reports, you have to add another project in existing solution named Setup Project to deploy your application to server or client machine.

After adding project in your existing application,

  1. Right Click on Setup Project in the solution explorer
  2. Click Properties
  3. There is a button called "Prerequisites" click it in the list you will find "Crystal Reports Basic for Visual Studio 2008(x86, x64)
  4. Add it and click Apply --> OK
After doing that your project will now include the CRRedist Files. When you run the installation it will install them and everything works fine. 

On Business Objects official site, still I am unable to find .msm file for VS 2008 Crystal Report Basic One. One more thing do not confuse Crystal Reports 2008 runtime files with Visual Studio Runtime files, as this is totally different.  The version shipped with Visual Studio 2008 is "Crystal Reports 2008 Basic v.10.5

Deploy the Crystal Reports 2008 Basic Runtime

If you created reports using Visual Studio 2008 and Crystal Reports 2008 Basic (the one included with Visual Studio 2008) and you want to deploy your application on a server or client machine, you'll also need to deploy the CR runtime.  

Your first reaction might be to go to the Business Objects Website and download the CR 2008 runtime.


Well, that's the wrong runtime.  You don't need to download CR runtime from above mention link. That one belongs to the full version of CR 2008 (version 12).  The runtime you require to deploy is CR 2008 Basic One (version 10.5).

So where do you get the CR basic (10.5) runtime?  It's right on your machine:

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\CrystalReports10_5

January 1, 2013

Disable Enter Key for Submit form excluding multiline textbox

Disable Enter Key hit on submit form excluding TextBox is the hot question now a days. Peoples including me search a lot how to do this. One of my client ask me to disable enter key functionality on form because whenever he hit Enter Key it will allow him to submit form.

In order to complete this task, firstly I search the Enter Key code number which is 13. After that I used these
lines in Header section of page.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
    
    $(document).keypress(function(e) {
    if (e.which == 13 && e.target.tagName != 'TEXTAREA') {            
            return false;
        }
    });    
</script>

Here in above code I use "TEXTAREA", because Asp.Net TextBox having TextMode="MultiLine" will become type TextArea after rendering into HTML.

Using above jQuery code, it will disable enter key hitting on form but it allow multiline TextBox like Asp.net TextBox to hit enter key within it.