Asynchronous Programming with Async and Await in .NET

You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using Asynchronous Programming.

What is Asynchronous Programming?

Asynchronous programming is writing code that allows several things to happen at the same time without “blocking”, or waiting for other things to complete. This is different from synchronous programming, in which everything happens in the order it is written.

Let’s see example. Say I have a class called ContentManagement, which has both synchronous and asynchronous methods:

public class ContentManagement  
{
    public string GetContent()
    {
        Thread.Sleep(2000);
        return "content";
    }

    public int GetCount()
    {
        Thread.Sleep(5000);
        return 4;
    }

    public string GetName()
    {
        Thread.Sleep(3000);
        return "UZVAL";
    }

    public async Task<string> GetContentAsync()
    {
        await Task.Delay(2000);
        return "content";
    }

    public async Task<int> GetCountAsync()
    {
        await Task.Delay(5000);
        return 4;
    }

    public async Task<string> GetNameAsync()
    {
        await Task.Delay(3000);
        return "UZVAL";
    }
}

Now let’s write an MVC controller, like so:

public class HomeController : Controller  
{
    [HttpGet]
    public ActionResult Index()
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        ContentManagement service = new ContentManagement();
        var content = service.GetContent();
        var count = service.GetCount();
        var name = service.GetName();

        watch.Stop();
        ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
        return View("Index");
    }

    [HttpGet]
    public async Task<ActionResult> IndexAsync()
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        ContentManagement service = new ContentManagement();
        var contentTask = service.GetContentAsync();
        var countTask = service.GetCountAsync();
        var nameTask = service.GetNameAsync();

        var content = await contentTask;
        var count = await countTask;
        var name = await nameTask;
        watch.Stop();
        ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
        return View("IndexAsync");
    }
}

async : This tells the compiler that this method can run asynchronously.

await : This tells the compiler that we will ultimately need the result of the async method.

Notice what these two action methods are doing. In both cases, the action methods are calling the methods in the ContentManagement service, but in one they are doing it asynchronously.

On our Index view, we have an output : 

Time Elapsed : 10000 ms

On our IndexAsync view, we have an output : 

Time Elapsed : 5000 ms

Where did we get that number? The longest-running of the three tasks takes 5 seconds. By designing this to use async, we cut our total execution time in half! That’s a lot of speedup to be gained from writing a little extra code.

Potential Issues :

When we mark a method as async, the compiler generates a state machine in the background; this is extra code. If we write good, stable asynchronous code, the amount of time it takes to create this extra structure won’t impact us at all, since the benefits of running asynchronously outweigh the cost of building the state machine. However, if our async method doesn’t have an await, the method will run synchronously, and we will have spent extra time creating the state machine that we didn’t use.

There’s one other potential problem to be aware of. We cannot call an asynchronous method from a synchronous one. Because async and await should go together in all cases, we pretty much have to have async on all methods, all the way down. This is why we needed separate async methods in the ContentManagement class earlier.

List To DataTable and Vice Versa using C#

public class ObjectConverter
 {
     public DataTable ListToDataTable(List items)
     { 
          DataTable dataTable = new DataTable(typeof(T).Name);
          //Get all the properties
          PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public |         BindingFlags.Instance);
          foreach (PropertyInfo prop in Props)
          {
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name);
          }
          foreach (T item in items)
          {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
             {
               //inserting property values to datatable rows
               values[i] = Props[i].GetValue(item, null);
             }
            dataTable.Rows.Add(values);
          }
          return dataTable;
     }

     public static List DataTableToList(DataTable dt)
     {
       List lstdata = new List();
       foreach (DataRow row in dt.Rows)
        {
           T item = GetItem(row);
           lstdata.Add(item);
        }
        return lstdata;
      }

      private static T GetItem(DataRow dr)
      {
        Type temp = typeof(T);
        T obj = Activator.CreateInstance();

        foreach (DataColumn column in dr.Table.Columns)
        {
          foreach (PropertyInfo pro in temp.GetProperties())
          {
            if (pro.Name == column.ColumnName)
               pro.SetValue(obj, dr[column.ColumnName], null);
            else
               continue;
          }
        }
        return obj;
       }
 }
Calling : 
 ObjectConverter converter = new ObjectConverter();
 
 DataTable dtstudentDetails=new DataTable();
 dtstudentDetails = converter.ListToDataTable(lststudentDetails); 

 List lststudentDetails = new List(); 
 lststudentDetails = converter.DataTableToList(dtstudentDetails);

Object To XML and Vice Versa using C#

Sometimes in web applications we like to save or send our data as XML to the SQL databases.
It’s mostly done when there is a large chunk of data or we like to convert our entity model objects to XML.
It makes it easier to move data from web applications to SQL database and vice versa.
Here I’ll share a code snippet to convert C# object to XML and XML to object C#.

C# Object to XML:

To convert an object to XML, we’ll make use of XmlSerializer to serialize and XmlTextWriter to output the XML string.
Here is how the code looks like :

public static string GetXMLFromObject(object o)
{
    StringWriter sw = new StringWriter();
    XmlTextWriter tw = null;
    try
    {
        XmlSerializer serializer = new XmlSerializer(o.GetType());
        tw = new XmlTextWriter(sw);
        serializer.Serialize(tw, o);
    }
    catch (Exception ex)
    {
        //Handle Exception Code
    }
    finally
    {
        sw.Close();
        if (tw != null)
        {
            tw.Close();
        }
    }
    return sw.ToString();
}

XML to Object C# :

Similarly, to convert an XML string to object we make use of the XmlSerializer to deserialize and XmlTextReader to read the XML string.
Here is how the code to convert XML to objects looks like :

public static Object ObjectToXML(string xml, Type objectType)
{
    StringReader strReader = null;
    XmlSerializer serializer = null;
    XmlTextReader xmlReader = null;
    Object obj = null;
    try
    {
        strReader = new StringReader(xml);
        serializer = new XmlSerializer(objectType);
        xmlReader = new XmlTextReader(strReader);
        obj = serializer.Deserialize(xmlReader);
    }
    catch (Exception exp)
    {
        //Handle Exception Code
    }
    finally
    {
        if (xmlReader != null)
        {
            xmlReader.Close();
        }
        if (strReader != null)
        {
            strReader.Close();
        }
    }
    return obj;
}

Calling :

Employee emp = new Employee();
emp.FirstName = "Ujjwala Datta";
emp.LastName = "Kalluri";

string xml = GetXMLFromObject(emp);
<?xml version="1.0" encoding="utf-16" ?> 
- <Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FirstName>Ujjwala Datta</FirstName> 
  <LastName>Kalluri</LastName> 
  </Employee>

Object obj = ObjectToXML(xml,typeof(Employee));

Regenerating SessionID in ASP.NET

Creating New ASP.NET_SessionId & Attaching Old ASP.NET_SessionId Values to New ASP.NET_SessionId

public void RegenerateSessionId()

{
System.Web.SessionState.SessionIDManager manager = new System.Web.SessionState.SessionIDManager();
string oldId = manager.GetSessionID(System.Web.HttpContext.Current);

string newId = manager.CreateSessionID(System.Web.HttpContext.Current);

bool isAdd = false, isRedir = false;
manager.SaveSessionID(System.Web.HttpContext.Current, newId, out isRedir, out isAdd);

HttpApplication ctx = (HttpApplication)HttpContext.ApplicationInstance;
HttpModuleCollection mods = ctx.Modules;
System.Web.SessionState.SessionStateModule ssm = (SessionStateModule)mods.Get(“Session”);
System.Reflection.FieldInfo[] fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
SessionStateStoreProviderBase store = null;
System.Reflection.FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;
foreach (System.Reflection.FieldInfo field in fields)
{
if (field.Name.Equals(“_store”)) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
if (field.Name.Equals(“_rqId”)) rqIdField = field;
if (field.Name.Equals(“_rqLockId”)) rqLockIdField = field;
if (field.Name.Equals(“_rqSessionStateNotFound”)) rqStateNotFoundField = field;
}
object lockId = rqLockIdField.GetValue(ssm);
if ((lockId != null) && (oldId != null)) store.ReleaseItemExclusive(System.Web.HttpContext.Current, oldId, lockId);
rqStateNotFoundField.SetValue(ssm, true);
rqIdField.SetValue(ssm, newId);
}

UZVAL – Statistics – Total Hits-22,222, Total Visitors-6623, Total Posts – 93

Six years back I started posting certain postings in this blog for learning purpose.

Today it got 22,222 hits, Total Visitors-6623, Total Posts – 93.

During this tenure I had Learned a lot & Implemented my level best, Professionally & Personally.

Today i am feeling that i had completed one life cycle.

Heartful Thanks to My Well-Wishers who had given me good opportunities.

Now we all know lot of significant CHANGES (new versions, new libraries, new frameworks) evolved in .Net Stack.

Hope TOGETHER (Integrations & Collaborations) we learn and implement NEW needful CHANGES Professionally & Personally for a better life-style & society.

Sincerely,

Ujjwala Datta Kalluri.

uzval

If any Suggestion, please submit it below :

Getting MAC Address of Client Machine in C #

Usually MAC address is also used to keep track of the unique Identification, if IP Address are not static, Every then from same system it will generate different IP Address, so cannot be keep records for unique, unless it is Static IP.

But MAC is set in users hardware system it is easy to trace, it is also used in E-commerce website, even IRCTC uses MAC Address to traces the records to trace the number of new user per day.

A media access control address (MAC address), also called physical address, is a unique identifier assigned to network interfaces for communications on the physical network segment.

MAC addresses are used as a network address for most IEEE 802 network technologies, including Ethernet and WiFi. Logically, MAC addresses are used in the media access control protocol sublayer of the OSI reference model.
MAC addresses are most often assigned by the manufacturer of a network interface controller (NIC) and are stored in its hardware, such as the card’s read-only memory or some other firmware mechanism.

If assigned by the manufacturer, a MAC address usually encodes the manufacturer’s registered identification number and may be referred to as the burned-in address (BIA). It may also be known as an Ethernet hardware address (EHA), hardware address or physical address. This can be contrasted to a programmed address, where the host device issues commands to the NIC to use an arbitrary address.

How do I find out the MAC address of my computer? (Windows)
• Click the Start icon
• Click Control Panel
• Select Network and Internet
• Click Network and Sharing Centre
• Select Change Adapter Settings from the list on the left hand side
• You may have a separate icon for your Wireless connection, Ethernet (Wired) and a Virtual WiFi MiniPort. Each has its own MAC address.
• Right click on the connection you are trying to find the MAC address for and select Properties
• Hover your mouse over the text box underneath connect using . Your MAC address will appear in the tooltip and is made up of 12 characters e.g. 00:11:22:AA:66:DD
using System.Management;
using System.IO;

protected void Page_Load(object sender, EventArgs e)
{
string MacAddress = GetMACAddress();
}

public string GetMACAddress()
{
string macAddresses = “”;

foreach (System.Net.NetworkInformation.NetworkInterface nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}

Encryption and Decryption in C# – Data Encryption Standard (DES) Algorithm

In cryptography, Encryption is the process of encoding messages or information in such a way that only authorized parties can read it. It requires some secret information to transform the plain text to cipher text; it is usually referred as key.

Decryption is the process of converting encrypted data back into its original form, so it can be understood

There are many modern cryptographic methods used for encryption and decryption and it is classified in to two classes of key based algorithms.

1.     Symmetric Algorithm 

a.    Same key is used for both Encryption and Decryption. The key will be kept as secret.

b.     Symmetric Ciphers is divided into Stream and Block Ciphers.

i.      Stream Ciphers – It encrypts a single bit of plain text at a time.

ii.      Block Ciphers –    It takes number of bits and encrypts them as a single unit.

2.       Asymmetric Algorithm

a.       Different key is used for Encryption and Decryption. It is also called as public Key algorithm.

b.      Encryption key is public and the Decryption key will be kept as secret.

c.       By using this asymmetric algorithm, anyone can encrypt the message by using encryption key but the message can be decrypted only by using decryption key.

3.       Hybrid Encryption – Symmetric and Asymmetric algorithm are used together and it is called as Hybrid Encryption.

Algorithm Requirements:

1.       The Key will be kept secret and should be Random.

2.       It should not be possible to find the key even if the plain text and Cipher text are known.

 Types of Symmetric Encryption Algorithm:

1.       Data Encryption Standard (DES)

2.       Triple DES (3DES)

3.       Advanced Encryption Standard (AES)

Below is the example for encryption and decryption in C# using Triple DES algorithm.

using System.IO;
using System.Security;
using System.Security.Cryptography;
Public class Program
{
static void Main(string[] args)
{
var text = “This is Plain Text”;

var encryptedText = CryptoGraphyExample.EncryptPlainTextToCipherText(text);
var decryptedText = CryptoGraphyExample.DecryptCipherTextToPlainText(encryptedText);

Console.WriteLine(“Passed Text = ” + text);
Console.WriteLine(“EncryptedText = ” + encryptedText);
Console.WriteLine(“DecryptedText = ” + decryptedText);

Console.ReadLine();
}
}

public class CryptoGraphyExample
{
/// <summary>
/// This security key should be very complex and Random for encrypting the text. This playing vital role in encrypting the text.
/// </summary>
private const string _securityKey = “MyComplexPrivateKey”;

/// <summary>
/// This method is used to convert the plain text to Encrypted/Un-Readable Text format.
/// </summary>
/// <param name=”PlainText”>Plain Text to Encrypt before transferring over the network.</param>
/// <returns>Cipher Text</returns>
public static string EncryptPlainTextToCipherText(string PlainText)
{
//Getting the bytes of Input String.
byte[] toEncryptedArray = UTF8Encoding.UTF8.GetBytes(PlainText);

MD5CryptoServiceProvider objMD5CryptoService = new MD5CryptoServiceProvider();

//Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(_securityKey));

//De-allocatinng the memory after doing the Job.
objMD5CryptoService.Clear();

var objTripleDESCryptoService = new TripleDESCryptoServiceProvider();

//Assigning the Security key to the TripleDES Service Provider.
objTripleDESCryptoService.Key = securityKeyArray;

//Mode of the Crypto service is Electronic Code Book.
objTripleDESCryptoService.Mode = CipherMode.ECB;

//Padding Mode is PKCS7 if there is any extra byte is added.
objTripleDESCryptoService.Padding = PaddingMode.PKCS7;

var objCrytpoTransform = objTripleDESCryptoService.CreateEncryptor();

//Transform the bytes array to resultArray
byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptedArray, 0, toEncryptedArray.Length);

//Releasing the Memory Occupied by TripleDES Service Provider for Encryption.
objTripleDESCryptoService.Clear();

//Convert and return the encrypted data/byte into string format.
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

/// <summary>
/// This method is used to convert the Cipher/Encypted text to Plain Text.
/// </summary>
/// <param name=”CipherText”>Encrypted Text</param>
/// <returns>Plain/Decrypted Text</returns>
public static string DecryptCipherTextToPlainText(string CipherText)
{
byte[] toEncryptArray = Convert.FromBase64String(CipherText);

MD5CryptoServiceProvider objMD5CryptoService = new MD5CryptoServiceProvider();

//Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(_securityKey));

//De-allocatinng the memory after doing the Job.
objMD5CryptoService.Clear();

var objTripleDESCryptoService = new TripleDESCryptoServiceProvider();

//Assigning the Security key to the TripleDES Service Provider.
objTripleDESCryptoService.Key = securityKeyArray;

//Mode of the Crypto service is Electronic Code Book.
objTripleDESCryptoService.Mode = CipherMode.ECB;

//Padding Mode is PKCS7 if there is any extra byte is added.
objTripleDESCryptoService.Padding = PaddingMode.PKCS7;

var objCrytpoTransform = objTripleDESCryptoService.CreateDecryptor();

//Transform the bytes array to resultArray
byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

//Releasing the Memory Occupied by TripleDES Service Provider for Decryption.
objTripleDESCryptoService.Clear();

//Convert and return the decrypted data/byte into string format.
return UTF8Encoding.UTF8.GetString(resultArray);
}
}