Thursday, November 26, 2015

Multicast Delegates in C#

In today's article we will be discussing multicast delegates in C# with example.

Multicast Delegates

As we discussed last week about delegates here, a delegate points to a function. We saw an example of a delegate pointing to a function and how we can use it. However, when using delegates we are not limited to pointing the delegate instance to only one method. With one delegate call, we can invoke multiple methods. The multicast delegate keeps a list of assigned delegates and calls them one by one when invoked.

multicast delegates in C#
Multicast Delegates in C#


Let's look at an example.
Suppose, we have an Employee class like this:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime PositionChangeDate { get; set; }
    public decimal Salary { get; set;}
}

And here is the multicast delegate for employee promotion:

public delegate void CustomDel(Employee employee);
static void Main(string[] args)
{
       var employees = new List<Employee>()
       {
             new Employee(){Id = 1, Name = "Abhi", Salary = 10},
             new Employee(){Id = 2, Name = "John", Salary = 20}
        };

        CustomDel SalaryRaiseDel, PositionDateDel, 
                  EmployeePromoteMulticastDelegate;
        SalaryRaiseDel = new CustomDel(EmployeeSalaryRaise);
        PositionDateDel = new CustomDel(PostionDateUpdate);
      
        //multiple delegates assigned
        EmployeePromoteMulticastDelegate = PositionDateDel 
                                         + SalaryRaiseDel;

        foreach (var emp in employees)
        {
            EmployeePromoteMulticastDelegate(emp);
            {
                Console.WriteLine("Id = " + emp.Id);
                Console.WriteLine("Name = " + emp.Name);
                Console.WriteLine("Salary = " + emp.Salary);
            }
        }

        Console.ReadLine();
   }
    

//set position change date to current time
private static void PostionDateUpdate(Employee employee)
{
     employee.PositionChangeDate = DateTime.Now;
}

//raise employee salary by 10%
private static void EmployeeSalaryRaise(Employee employee)
{
     employee.Salary += employee.Salary + employee.Salary 
          * (decimal) 0.1;
}

So here I created a multicast delegate called EmployeePromoteMulticastDelegate. This delegate is assigned 2 other delegates viz. SalaryRaiseDel & PositionDateDel. So when we call the EmployeePromoteMulticastDelegate with Employee parameter, it calls EmployeeSalaryRaise() and PostionDateUpdate() methods. So with one call we were able to call 2 methods.

Any delegate when assigned multiple methods to invoke becomes multicast delegate. There is no special syntax for multicast delegates.

Conclusion

Multicast delegates are a powerful feature of C# and are used to apply publish subscribe pattern. By invoking an event, we can call multiple methods who have subscribed to the event.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, November 19, 2015

Delegates in C#

In today's blog post, we will be discussing delegates in C#.

Delegates

Simply put, a delegate is a type safe function pointer. It defines the signature of the method that can be used. The delegate can point to any method as long as the signature of the method is the same. The signature here includes the parameter types and return types.

delegates in C#

Let's take a look at a simple example of delegates and see how they can be useful. Let's have our favorite Employee class like this:

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
}
Suppose, we want to find out all the employees who can be promoted. So we might write our code something like this:

static bool IsEmployeePromotable(Employee employee) 
{
   if (DateTime.Now.Year - employee.StartDate.Year > 5)
         return true;

    return false;
}

static void Main(string[] args)
{
    var employees = new List<Employee>()
    {
        new Employee(){Id = 1, Name = "Abhi", StartDate = new DateTime(2010,1,1)},
        new Employee(){Id = 2, Name = "John", StartDate = new DateTime(2005,1,1)}
    };

   foreach (var emp in employees) 
   {
        if (IsEmployeePromotable(emp))
       {
          Console.WriteLine("Id = " + emp.Id);
          Console.WriteLine("Name = " + emp.Name);
       }
   }
    Console.ReadLine();
}

So here the program prints all the employees who has more than 5 years of experience in the company. So this looks fine and short.
Suppose, we have some more requirements that want to change the promotion criteria. This will lead us to change the existing code. For any new criteria to be added we will have to change the existing code again and again.  Delegates can help us here as we can inject the promotion criteria on the fly. Let's see how we can do that using delegates:

public delegate bool PromotableEmployee(Employee employee);
static void Main(string[] args)
{
    var employees = new List<Employee>()
    {
        new Employee(){Id = 1, Name = "Abhi", StartDate = new DateTime(2010,1,1)},
        new Employee(){Id = 2, Name = "John", StartDate = new DateTime(2005,1,1)}
    };
    PromotableEmployee IsEmployeePromotable = new PromotableEmployee(IsEmployeeFiveYearsOld);
    foreach (var emp in employees) 
    {
        if (IsEmployeePromotable(emp))
        {
            Console.WriteLine("Id = " + emp.Id);
            Console.WriteLine("Name = " + emp.Name);
        }
    }
    Console.ReadLine();
}

static bool IsEmployeeFiveYearsOld(Employee employee)
{
    if (DateTime.Now.Year - employee.StartDate.Year > 5)
        return true;
    return false;
}

So here I created a delegate type called PromotableEmployee. This type can have any method assigned to it as long as it conforms to the signature. We have this method called IsEmployeeFiveYearsOld() which conforms to the signature. When we created the delegate instance called IsEmployeePromotable which uses IsEmployeeFiveYearsOld() method. And then we use the delegate instance in our program. When we create the delegate instance, we can assign any method to it as long as it conforms to the signature. That's the power of the delegates. 
So I can create any new PromotionCriteria and add it to the code base. Then we can inject that method on the fly.

Conclusion

Delegates are powerful feature of C# and have improved a lot over different versions of C#. I will be discussing multicast delegates in the next post which will show how delegates can be more useful to us.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, November 12, 2015

Async Await in C#

In today's blog post, I will be talking about how to do asynchronous programming in C# using async await keywords.

ASYNC AWAIT

Earlier (before C# 5), writing asynchronous code used to be difficult and bug-prone. With C# 5 came async await which made writing asynchronous code lot easier.


Async Await C#



Let's take a look at a simple example of how to do this.
In order to demonstrate this, I created a small web form application which looks like this:


Web Form .NET Async Await C#


The code behind looks like this:


public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    var result = SlowMehtod("Abhi");
    label1.Text = result;
}

private string SlowMehtod(string str)
{
    Thread.Sleep(2000);
    return "Welcome " + str;
}



So when I click the button, it updates the label1 text to "Welcome Abhi". However, as you can see I added a Thread Sleep statement to add a delay of 2 seconds. The reason why I did this is to make the method slow (who does that!). In your code, you might have some method which accesses resource over the web or some database or due to some other reason, its slow. I just simulated the slow behavior. So when I click the button, my form freezes for 2 seconds and then it shows "Welcome Abhi".

If we are blocking the UI thread, we are basically freezing the application and making the user experience not pleasant. The user might think that application is frozen and might just kill the process. So we should avoid blocking the UI thread.

By wring asynchronous code, we can put the slow method to execute in parallel. Let's take a look at how we can do that here:

private void button1_Click(object sender, EventArgs e)
{
    CallSlowMethodAsync("Jain");
    label1.Text = "Waiting...";
}

private async void CallSlowMethodAsync(string str)
{
    var result = await SlowMehtodAsync("Jain");
    label1.Text = result;
}

private Task<string> SlowMehtodAsync(string str)
{
    return Task.Factory.StartNew(() => SlowMehtod(str));
}

private string SlowMehtod(string str)
{
    Thread.Sleep(2000);
    return "Welcome " + str;
}

For writing async code, we simply created a new method with async keyword. Inside async method, there is await which marks the method that will be executed in parallel. The await calls the SlowMethodAsync which return a Task<string>.  By convention the name of the async method ends with an "Async" suffix. The return type of async method can be:

  1. Task<TResult> - if method is returning something of type TResult.
  2. Task - if method has no return statement or empty return statement.
  3. Void - if it's async event event handler.

So now when I run this application, and I click the button, the label text changes to "Waiting..." right away. Then after 2 seconds, it updates to "Welcome Jain". During the time the SlowMethod() is running, the UI doesn't freeze anymore as it's running asynchronously :)

Web Form .NET Async Await C#


Conclusion

C# 5 makes it very easy to write asynchronous code and we should use this feature when we have any slow running code threatening our user experience ;)

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


Thursday, November 5, 2015

JavaScript Generators

In today's blog post I will be discussing what JavaScript generators are and how they can be useful. Generators are part of ES6 and are truly a game changer.

Generators

Usually when we execute any functions, they run till the end (or first return statement). We cannot pause them in between and do something else.
The ES6 generators are special types of functions which can be paused. We can pause them, re-run them, pause them again and re-run them and so on.

Javascript Generators


A "function*" is used to represent a generator function and "yield" keyword marks the pauses in the generator. Let's take a look at an example:

function *foo() {
    yield 'a';
    yield 'b';
    yield 'c';
}

In order to use it, we simply call the next() function on the generator like this:

var func = foo();
console.log(func.next());  // Object {value: "a", done: false}

This return the first yield value i.e. 'a'. Next time, we call func.next(), we get this:

console.log(func.next());  // Object {value: "b", done: false}

So you can see how the function execution gets paused on each yield. And how it re-runs on each next() call.
If we execute it more, we get:

console.log(func.next()); // Object {value: "c", done: false}

console.log(func.next()); 
// Object {value: undefined, done: true}

So once it reaches the end of the generator function, we get the value as undefined and done as true. Once a generator function is done, it will keep returning the same values of undefined and true, no matter how many times we call the next() function on it afterwards.

Now, let's take a look at how we can do two-way communication using generators. Whatever we pass in the yield as argument, we get it back as the Object's value.

function *foo(a) {
    var b = 3 * (yield (a + 2));
    console.log(b);                         //24
    var c = yield (b / 2);
    console.log(c);                         //13
    return (a + b + c);
}
var func = foo(6);
console.log(func.next());   // Object {value: 8, done: false}
console.log(func.next(8));  // Object {value: 12, done: false}
console.log(func.next(13)); // Object {value: 43, done: false}


And if we want to pass anything to the generator function, we pass it as argument to the next() call.
So in the example above when we call foo() function, we pass 6 as argument. That's the value of "a". Then we call func.next() - that returns (6+2=) 8 as the value. The generator is paused at the first yield. Then we call func.next() second time with argument of 8. So the value of b is assigned as (8*3=) 24. So we passed in the value 8 into the generator function and that gets used inside the function.
Then, we called func.next() with argument 13 and that gets assigned to c. Then the last value is returned as  (6+24+13=) 43.

Why useful?

So the reason why these pausable functions can be useful is for asynchronous programming. We can do "yield" followed by asynchronous call. This will fetch the result of that asynchronous call. And whenever we are ready for the next call, we can simply call the next() function and get the result of the next asynchronous call. We can also pass in any arguments we like to the next() call which can be used in the asynchronous request we are making. 

function * () {
    var a = yield async1();
    var b = yield async2(a),
    var c = yield async3(b);
    console.log(a, b, c);
};


Conclusion

JavaScript Generators are a great way to write asynchronous code. We will have to write more and more of asynchronous code as the time progresses. Nesting asynchronous calls and callbacks makes our code look dirty and difficult to debug. With generators, not only the code will look better but will also be easier to debug.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)