Friday, 18 May 2012

LINQ Zip Operator

The Zip operator was added in Framework 4.0. It enumerates two sequences in step (like a zipper), returning a sequence based on applying a function over each element pair.
The extension method signature is:
   1: public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(
   2:                                     this IEnumerable<TFirst> first,
   3:                                     IEnumerable<TSecond> second,
   4:                                     Func<TFirst, TSecond, TResult> resultSelector)
Zip cycles through two sequences using deferred execution. The items at the same index are paired and each pair is transformed using a function that is usually provided as a lambda expression. The sequence stops as soon as one of the sequences exhausts its elements; ideally, the sequences are identical in length or you can say in other word continues until all of the items in either sequence have been processed. If one sequence has more elements than the other, the extra elements are not projected into the new sequence. The merging happens in the func function. It takes two arguments (the element from first source, and the element from the second source) and lets you return a combined type.

Example:
   1: using System;
   2: using System.Linq;
   3:  
   4: namespace ZIP_OPERATOR_DEMP
   5: {
   6:   class Program
   7:   {
   8:     static void Main(string[] args)
   9:     {
  10:       //Initialize two lists of integer with same sequence.
  11:       int[] integers1 = new int[] { 1, 2, 3, 4, 5 };
  12:       int[] integers2 = new int[] { 10, 20, 30, 40, 50 };
  13:  
  14:       //Now apply zip operator on it.
  15:       var sumsZip = integers1.Zip(integers2, (i, j) => i + j);
  16:  
  17:       Console.WriteLine("Output of zip of two interger series.");
  18:       Console.WriteLine("=====================================");
  19:  
  20:       //Get the out of Zip operation.
  21:       foreach (var sum in sumsZip)
  22:       { Console.WriteLine(sum); }
  23:  
  24:       Console.WriteLine("\n");
  25:  
  26:       //Initialize two lists with different sequence and different datatypes.
  27:       int[] integers3 = new int[] { 1, 2, 3, 4, 5 };
  28:       char[] characters = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
  29:       var items = characters.Zip(integers3, (c, i) => string.Format("{0}{1}", c, i));
  30:  
  31:       Console.WriteLine("Output of zip of two different datatype series.");
  32:       Console.WriteLine("===============================================");
  33:  
  34:       //Get the out of Zip operation.
  35:       foreach (var item in items)
  36:       { Console.WriteLine(item); }
  37:  
  38:       Console.WriteLine("\n");
  39:  
  40:       //Now we zip more then two list with one by one basis.
  41:       //So final output will be full address line for each element.
  42:       var bldgNum = new string[] {"A5", "A2", "A1" };
  43:       var flatNum = new int[] {104, 109, 25, 200 };
  44:       var streetNm = new string[] {"Baker Street", "Cross Street", "Hu Street" };
  45:       var city = new string[] { "CO", "WA", "AU", "CA" };
  46:  
  47:       Console.WriteLine("Output of multiple zip operation multiple series.");
  48:       Console.WriteLine("=================================================");
  49:  
  50:       //Zip all the partiall address to full address.
  51:       var address = bldgNum.Zip(flatNum, (bl, fl) => bl + ", " + fl.ToString())
  52:                            .Zip(streetNm, (fl, st) => fl + " , " + st)
  53:                            .Zip(city, (st, ct) => st + ", " + ct);
  54:  
  55:       foreach (var addr in address)
  56:         Console.WriteLine(addr);
  57:  
  58:       Console.ReadLine();
  59:     }
  60:   }
  61: }
Output:
clip_image002 
Explanation:

For the first example we'll zip together two sequences containing the same number of elements, where each sequence contains the same data type. In the code below you can see that the Zip operator is used as an extension method of the first array. The second array is passed to the first parameter. The second argument specifies the projection function that is used to generate the items in the resultant collection. In this case each pair of values is summed.
In the second example we add an array of characters so that we can demonstrate combining sequences of differing types. Here a character and an integer from the source arrays are combined with string.Format to generate a string. Note also that the list of characters is longer than the integer sequence. The final item, "F", is dropped from the results. 

Conclusion:

We can use this "ZIP" linq operator where we want some action to perform on same or different data types sequences but operator consider only "Source" & "Destination" index match else ignore other element in sequence.
For more details you can refer MSDN.

Friday, 4 May 2012

Drag and Drop Listbox

Glad to announce that “Drag and Drop Listbox” for Dynamics CRM 2011 was successfully placed at Dynamics Marketplace.

Give it a whirl.http://dynamics.pinpoint.microsoft.com/en-IN/applications/drag-and-drop-listbox-12884936087

Tuesday, 1 May 2012

Introduction to 'async' and 'await' keywords in C# 5.0


As a developer, I often do File Operations like writing and reading to and from a file, performing file Uploads and Downloads to and from a file server and so on. In such scenarios, if the size of the file is huge and if number of files to be uploaded and downloaded are more than what can be managed by the application, I go in for Asynchronous programming using BeginInvoke() method of the delegate. In this case, it is necessary for me to implement complex threading mechanisms which can at times make my code complex and a difficult to maintain.

However, when I came across the new features in.NET Framework 4.5 and C# 5.0, I found a simple solution. The developer community has been provided with a new simplified approach for Asynchronous programming which can make a developer’s life simpler. Following are the new Keywords introduced:

async: This modifier indicates the method is now asynchronous. The benefit of using this keyword is that it provides a simpler way to perform potentially long-running operations without blocking the callers thread. The caller of this 'async' method can resume its work without waiting for this asynchronous method to finish its job. This reduces developer’s efforts for writing an additional code. The method with 'async' modifier has at least one await.This method now runs synchronously until the first await expression written in it.

await: Typically, when a developer writes some code to perform an asynchronous operations using threads, then he/she has to explicitly write necessary code to perform wait operations to complete a task. In asynchronous methods, every operation which is getting performed is called a Task. Here the task is also known as an ongoing work or work to perform.

The ‘await’ keyword is applied on the task in an asynchronous method and suspends the execution of the method, until the awaited task is not completed. During this time, the control is returned back to the caller of this asynchronous method.

You must keep in mind that the keyword ‘async’ is applied on the method which is decorated with the ‘async’ keyword. The most important behavior of the await keyword is it does not block the thread on which it is executing. What it does it that it signals to the compiler to continue with other async methods, till the task is in an await state. Once the task is completed, it resumes back where it left off from.

Let's take an example to understand it.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("Step1: Please enter a number"));
            string userInput = Console.ReadLine();

            Console.WriteLine("--------- Ex1: Synchronous Call: ---------");
            CallSync(userInput);
            Console.WriteLine(string.Format("Ex1 - Step3: Synchronous call finished"));

            Console.WriteLine("--------- Ex2: Asynchronous Call: ---------");
            CallAsync(userInput);
            Console.WriteLine(string.Format("Ex2 - Step3: Asynchronous call finished"));
            Console.WriteLine(string.Format("Ex2 - Step4: Other operations can now be done"));

            Console.ReadLine();
        }

        #region Synchronous Call

        public static void CallSync(string userInput)
        {
            long result = SyncFactorial(ulong.Parse(userInput));

            Console.WriteLine(string.Format("Ex1 - Step2: Factorial is {0}",
                                                           result.ToString()));
        }

        public static long SyncFactorial(ulong number)
        {
            long result = 1;

            for (long i = 1; i <= number; i++)
            {
                // Simulated a time consuming operation
                Thread.Sleep(1000);
                result *= i;
            }

            return result;
        }

        #endregion      

        #region Asynchronous Call

        public static async void CallAsync(string userInput)
        {
            long result = await AsyncFactorial(long.Parse(userInput));

            Console.WriteLine(string.Format("Ex2 - Step2: Factorial is {0}",
                                                          result.ToString()));
        }

        public static async Task<long> AsyncFactorial (long number)
        {
            Task<long> resultFactorial = TaskEx.Run(() =>
            {
                long result = 1;
                for (long i = 1; i <= number; i++)
                {
                    // Simulated a time consuming operation
                    Thread.Sleep(1000);
                    result *= i;
                }

                return result;
            });

            return await resultFactorial;
        }

        #endregion
    }

Explanation : As shown in above example I have wrote a two methods.

1)  First is "SyncFactorial" this is coded like traditional way and I have added some sleep of a second so method can take more time to execute and we can easily understand how execution is done.

2) Second is "AsyncFactorial" this is coded in a such a fashion that code will run on separate thread with use of 'Async' and if you see same code is there what we have written in "SyncFactorial" but the only difference is - we have created that as Task to perform it as asyncronous and I have added 'await' statement for resultFactorial and second at method calling "AsyncFactorial" So when function is call at time Task is created and run on different thread and caller is free now to execute further line of code and when task completed its task then it will start from await statement in our case it will be await for result and main thread continues with Console.WriteLine statement.

Now let's see execution sequence of the program.

Step1: Please enter a number : 5
--------- Ex1: Synchronous Call: ---------
Ex1 - Step2: Factorial is 120
Ex1 - Step3: Synchronous call finished
--------- Ex2: Asynchronous Call: ---------
Ex2 - Step3: Asynchronous call finished
Ex2 - Step4: Other operations can now be done
Ex2 - Step2: Factorial is 120

We can archive this functionality with some more amount of code using threading but using 'Async' and 'Await' it is very easy to code asynchronous.

Conclusion: The new keywords 'async' and 'await' introduced in C# 5.0 helps developers to make their asynchronous programming logic less complex and more manageable.