Pranay Rana: c#
Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Monday, November 2, 2020

Work Partitioning - Process large amount of records in C#

What is Work Partitioning ?

Work Partitioning means dividing big/large amount of work between workers. Which means if you have work which is going to take 100hrs to complete by one worker you divide it among multiple worker lets between 10 workers who work parallel , then work of 100hrs get complete in 10hrs. So work partitioning helps to complete works faster.

Once can apply work partitioning to process data faster by dividing work among set of machines (like in big data where large amount high volume data processed by set of machines located at on premise or at in cloud) or process incoming request by set of machines with help of Load Balancers. But in this post I am going to put information about partitioning work in Process/Application using Task Parallel library of C# language.

Below is code that make use of C# task parallel library and does the processing of lots of records, here is 1m records.

public List<TransFormedCustomer> GetProcessData()
{
    var processRecordCount = 10000;
    var retModels = new List<TransFormedCustomer>();
    var lotOfRecords = GetFakeData(); //example million records from datasource like database, web service, csv file

    int tasksCount = (lotOfRecords.Count / processRecordCount);
    if (lotOfRecords.Count % processRecordCount > 0)
        tasksCount++;

    var tasks = new Task<List<TransFormedCustomer>>[tasksCount];
    for (int i = 0; i < tasksCount; i++)
    {
        IEnumerable<Customer> datas;
        int skip = (processRecordCount * i);
        int take = processRecordCount;

        if (i == 0)
            datas = lotOfRecords.Take(take);
        else
            datas = lotOfRecords.Skip(skip).Take(take);

        tasks[i] = Task.Factory.StartNew((obj) => GetProccessedData(datas), Tuple.Create(skip, take));
#if DEBUG
        if (i == tasksCount - 1 && lotOfRecords.Count % 10000 != 0)
           take = lotOfRecords.Count % 10000;
        Console.WriteLine($"task no {i} started, reading from {skip} to {skip + take}");
#endif
    }
    try
    {
        Task.WaitAll(tasks);
    }
    catch
    {
        //left empty as logging errors in below foreach block
    }

    foreach (var task in tasks)
    {
        if (task.IsCanceled || task.IsFaulted)
        {
            var state = (Tuple<int, int>)task.AsyncState;
            Console.WriteLine($"taks failed to process data from {state.Item1} to {state.Item2}");
        }
        else
            retModels.AddRange(task.Result);
     }

    return retModels;
} 
Code works above works as follows
  1. It sets number number of records one task can process , here in code its 10000 set in "processRecordCount" variable. 
  2. Code get 1m records from the datasoruce, here "GetFake()" method(code listed at the end) returns 1m customers records 
  3. "taskCount" variable stores number of task need to process received records ("GetProccessedData(datas)"- method listed below) i.e. here its 100000/1000 = 10 number of task required to process records.
  4. In for loop with help of "Take" or "Skip" , each task get 10000 to process. 
  5. "Task.WaitAll()" wait for all task to finish work
  6. After work get finished by each task, processed records get added to "retModels" collection.
  7. If task to fail to process record then it logs information on console. 

Output

As shown in above image each thread does processing of 10000 records and each pick different set of records. 

Followings are advantages of work partitioning
  1. Very huge amount of data get processed faster as it gets process parallelly with help of tasks i.e. workers\
  2. It make use of multicore CPU i.e. computing efficiently as one task get processed by one core mostly   
Code used to support above function   

GetFakeData- method

Fake data produced by using Faker.Net "install-package Faker.Net"

private List<Customer> GetFakeData()
{
    var customers = new List<Customer>();
    for (int i = 0; i < 100000; i++)
    {
        customers.Add(
            new Customer()
            {
                FirstName = Faker.Name.First(),
                LastName = Faker.Name.Last(),
                EmailAddress = Faker.Internet.Email(),
                SSN = Faker.Identification.SocialSecurityNumber()
            }
            );
    }
    return customers;
}
GetProccessedData-Method
private List<TransFormedCustomer> GetProccessedData(IEnumerable<Customer> customers)
{
    var transFormedCustomers = new List<TransFormedCustomer>();
    foreach (var customer in customers)
    {
        //do processing on recevied data 
        //enrich data and add it to process collection 
        string formattedSSN = customer.SSN.Insert(5, "-").Insert(3, "-");
        string formattedName = customer.FirstName + ' ' + customer.LastName;
        string email = customer.EmailAddress;
        Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
        Match match = regex.Match(email);
        if (!match.Success)
            email = "dummy@dummy.com";
        var transFormedCustomer = new TransFormedCustomer()
        {
            Name = formattedName,
            SSN = formattedSSN,
            EmailAddress = email
        };

        transFormedCustomers.Add(transFormedCustomer);
    }
    return transFormedCustomers;
}
Customer & TransformCustomer Modal class
    public class Customer
    {
        public string EmailAddress { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string SSN { get; set; }
    }

    public class TransFormedCustomer
    {
        public string EmailAddress { get; set; }
        public string Name { get; set; }
        public string SSN { get; set; }
    }
 

Thursday, January 31, 2019

Self Host Angular and WebApi Using Owin

Full Source code at GitHub : OwinWebapiAngularHost

In development there are situations(organization restrictions, developing POC/Demo, there is need of control on server) where developer doesn't have Server application(IIS,Tomcat etc.), where developer got and deploy Web application. So to overcome these situation developer need environment which similar to Server application, basically issue can be resolved by having Self hosting application. Self hosting application allows to deploy web application and provide similar functionality as server application.
Question rises how to create self hosting application, answer is by making use of Owin like Framework. Below post is about how to create self hosting application with help of Owin framework which in turn allows to host Asp.Net WebApi and Angular application.

Creating Self Hosting application
To create self hosting application, developer can create either Console, WPF or Windows Form Application or Windows Service by choosing Console, WPF or Windows Form or WindowsService project type provided in visual studio.
For this post I am choosing Windows Service project as given in below image

Once click "ok button" it will create windows service application in visual studio. But when run application by pressing "F5" in visual studio it display message


To avoid error in development environment , do check for service running in user interactive check flag "UserInteractive". Below code shows how to do it

static class Program
{
        /// 
        /// The main entry point for the application.
        /// 
    static void Main(string[] args)
    {
        try
        {
            //flag check service running in user interactive mode i.e. debug mode 
            if (Environment.UserInteractive)
            {
                Service1 service1 = new Service1();
                service1.TestStartup(args); // start service in debug mode
                Console.WriteLine("Service Started at: http://localhost:8081/File/action");
                Console.ReadLine(); // stop service in debug mode
                service1.TestStop();
            }
            else
            {

                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[]
                {
                 new Service1()
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
        catch(Exception ex)
        {
           Console.WriteLine(ex);
           //log error 
           Console.ReadLine();
        }
    }
}


Once done add below code in service.cs file which is related to windows service application

public partial class Service1 : ServiceBase
{
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
       if (ConfigurationManager.AppSettings["baseAddress"] != null)
          baseAddress = ConfigurationManager.AppSettings["baseAddress"].ToString();
       server = WebApp.Start(baseAddress);
    }

    protected override void OnStop()
    {
        server.Dispose();
    }

    internal void TestStartup(string[] args)
    {
        this.OnStart(args);
    }

    internal void TestStop()
    {
        this.OnStop();
    }
    
    private IDisposable server;
    string baseAddress = "http://*:8081/";
} 
Line of code written in OnStart method of service file is most important code, "WebApp.Start()" this method start Owin web server at "8081" port by making use of settings provided in "OwinStartUp"(setup of this class discussed in detail below) class.

Installing Owin
After creating and setting Windows service, now it's time to install Owin framework which provide support for hosting web based application. Owing installation can be done via "Package Manager console (this console can be opened up from Visual studio menu Tools>>Nuget Package Manager >> Package Manager Console)" or by "Manage Nuget Packages(this is menu option comes by right clicking project in visual studio)".

//run below command in package manager console to install owin support
Install-package Microsoft.Owin.SelfHost
//or search package "Microsoft.Owin.SelfHost" in package management window  
This command installs following packages, one can view in package.json file of project or in references as dll.
  
  Microsoft.Owin
  Microsoft.Owin.Diagnostics
  Microsoft.Owin.Host.HttpListener
  Microsoft.Owin.Hosting
  Microsoft.Owin.SelfHost
  Owin

Installation of basic packages enable Owin in windows service application. To make use of Owin, developer needs to add settings which decide what type of application/files can be served by self hosted owin server application. Below is basic "OwinStartUp" class that used by "WebApp.Start()" method to start server.

//OwinStartUp.Cs
public class OwinStartUp
{
    public void Configuration(IAppBuilder app)
    {
#if DEBUG
        app.UseErrorPage();
#endif
        app.UseWelcomePage("/");
    }
}


Enable WebApi Hosting
To enable WebApi hosting in above created self hosted owin based application, Add below package

//run below command in package manager console to install WebApi support
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
//or search package "Microsoft.AspNet.WebApi.OwinSelfHost" in package management window  

This command installs following packages, one can view in package.json file of project or in references as dll.
  
  Microsoft.AspNet.WebApi.Client
  Microsoft.AspNet.WebApi.Core
  Microsoft.AspNet.WebApi.Owin
  Microsoft.AspNet.WebApi.OwinSelfHost
  Newtonsoft.Json

Once installation done, below line of code in start setting class enable support of WebApi hosting in application

public class OwinStartUp
{
    public void Configuration(IAppBuilder appBuilder)
    {
  // Configure Web API for self-host.
  //Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

  //removing support of xmlformatter
  HttpConfiguration config = new HttpConfiguration();
  config.Formatters.Remove(config.Formatters.XmlFormatter);

  //webapi route configuration
  config.Routes.MapHttpRoute(
   name: "DefaultApi",
   routeTemplate: "api/{controller}/{action}/{id}",
   defaults: new { id = RouteParameter.Optional }
  );

  config.MapHttpAttributeRoutes();

  //adding config for WebApi support
  appBuilder.UseWebApi(config);
    }
}

After adding support for WebApi, developer can add WebApi controller as given below.

public class TestController : ApiController
{
    [HttpGet]
    public string GetFileName()
    {
        return "Test";
    }
} 


Enable support for CORS
Above add support for WebApi, but it won't allows to access form other domain apart form hosted domain i.e. from Cross domain. Developer can resolve issue of CORS as below.

//run below command in package manager console to install Cors support
Install-Package Microsoft.Owin.Cors
//or search package "Microsoft.Owin.Cors" in package management window  

This command installs following packages, one can view in package.json file of project or in references as dll.
  
  Microsoft.Owin.Cors
  Microsoft.AspNet.Cors

Once installation done, below line of code enable CORS
  
public class OwinStartUp
{
    public void Configuration(IAppBuilder appBuilder)
    {
        //webapi code done before remain as is
  
        //Install-Package Microsoft.Owin.Cors
        appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    }
}

So now self host is ready with WebApi hosted in it.

Enabling Angular/Static file hosting
Enabling self host for angular is similar to enable self host for allowing browsing of static html files i.e. web site. Because angular is framework for creating single page application which access by accessing "index.html" file only.

Note:
For hosting angular application please perform prod build (by using angular cli command ng build --prod) of you application as it has prod generated code i.e. html page with javascript only. Guide for Angular deployment : https://angular.io/guide/deployment

To enable WebApi hosting in above created self hosted owin based application, Add below package

//run below command in package manager console to provide static website /angular app support
Install-Package Microsoft.Owin.StaticFiles
//or search package "Microsoft.Owin.StaticFiles" in package management window  

This command installs following packages, one can view in package.json file of project or in references as dll.
  
  Microsoft.Owin.FileSystems
  Microsoft.Owin.StaticFiles

Once installation done, below line of code in start setting class enable support of Static Web app/Angualr app hosting in application

public class OwinStartUp
{
    public void Configuration(IAppBuilder appBuilder)
    {
       //hosting static files i.e. angular
       //install-package Microsoft.Owin.SelfHost
       //install-package Microsoft.Owin.StaticFiles
       var options = new FileServerOptions();
       options.EnableDirectoryBrowsing = true;
       options.FileSystem = new PhysicalFileSystem("./app");
       options.StaticFileOptions.ServeUnknownFileTypes = true;
       appBuilder.UseFileServer(options);

      //code done for WebApi remain as is if you want webapi support 
   }
}

Below is full source code done in this excercise
    
    public class OwinStartUp
    {
        public void Configuration(IAppBuilder appBuilder)
        {

            //hosting static files i.e. angular
            //install-package Microsoft.Owin.SelfHost
            //install-package Microsoft.Owin.StaticFiles
            var options = new FileServerOptions();
            options.EnableDirectoryBrowsing = true;
            options.FileSystem = new PhysicalFileSystem("./app");
            options.StaticFileOptions.ServeUnknownFileTypes = true;
            appBuilder.UseFileServer(options);


            // Configure Web API for self-host.
            //Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
            HttpConfiguration config = new HttpConfiguration();
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.MapHttpAttributeRoutes();
            appBuilder.UseWebApi(config);

            //Install-Package Microsoft.Owin.Cors
            appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        }
    }

Full Source code at GitHub : OwinWebapiAngularHost

Saturday, January 19, 2019

Return Given Type from Generic method

In C#, Genetic method as below, which can return value of multiple types (i.e. below method can return value of any primitive types or reference types).
   public T GetValue<T>()
   {
  
   }
so one cannot return value directly from method. As T is template type & it can be any of type, so compiler doesn't allow direct conversation of return value to type T.
   public T GetValue<T>()
   {
     //Compilation error (line 13, col 10): Cannot implicitly convert type 'Customer' to 'T'
     return new Customer();
     //this error says that T is template type and it can be of any type (primitive or reference)
   }
Above will not work because Template type of Generic method get replaced at Runtime and Compiler of C# cannot able to figure out Generic type actual type at compile time. for example call to method is like as below
// call to method
GetValue<int>()

//then at runtime method will be like as below 
public int GetValue<int>()
{
 //assuming generic method return customer object only 
 return new Customer();
}

Solution 
As explained in detail problem with generic method is to return value of requested return type (i.e. Runtime type which replaces generic Template type T). So to solve problem return value to object type(as object is base class of all types in C# .net) and then convert it to generic template type. Below is code for that solves problem
public T GetValue<T>()
{
  Type typeParameterType = typeof(T);
    Type typeParameterType = typeof(T);
  if(typeParameterType.ToString()=="System.Int32")
    return (T)(object)1;
   if(typeParameterType.ToString()=="Customer")
    return (T)(object)new Customer()
}

But problem with above code is ,for every new return type value new condition required to be added in method i.e it requires to change method for every new return type and it violates Single responsibility principle.

This can easily be resolved by making use of C# in built method Convert.ChangeType, below is code for the same
  (T)Convert.ChangeType(1, typeParameterType)//here T is generic type

Below is code for getting value of column form DataRow object which is based on above discussion
  public static T GetColumnValue<T>(this DataRow dr, string columnName)
  {
     //get type of Template type T
     Type typeParameterType = typeof(T);
     //get type of Template type T, this works when requested type is nullable
     typeParameterType = Nullable.GetUnderlyingType(typeParameterType) ?? typeParameterType;

     //check value present or not , if not return default value of generic type
     return dr[columnName] != DBNull.Value
                ? (T)Convert.ChangeType(dr[columnName], typeParameterType)
                : default(T);
   } 
//use of this method in code 

datarow.GetColumnValue<int>("id");
datarow.GetColumnValue<int?>("orderid");
datarow.GetColumnValue<double>("amount");

so above is Generic method to get value of datacolumn of given type. Method get value of return type from template type T and then does conversation of datacolumn value using Convert.ChangeType.

Below is example of Factory Design pattern using same technique
public class CommandFactory
{       
    //only create object of type which implement ICommand
    public static T GetCommand<T>() where T:  ICommand
    {
      //it create object using Template type T and by making use of reflection
      //once create factory this way there is no need to open it again for modification
        Type type = typeof(T);
        Object obj = Activator.CreateInstance(type);
        return (T)obj;
    }
}

Read about this in detail here : Factory Design Pattern With Generics

Sunday, July 15, 2018

Parsing Number with NumberStyles

Parsing string value to number i.e. converting string representation of number into number type is one of the basic task and most of programming language provides support to perform it easily. But sometimes developer writes too much complex code to perform this (string to number parsing) task as not aware about the easy way provided by programming language.

Below is small tip about parsing string representation of number to number type with respect to C# language. C# language has below numeric types 
  • integer types (sbyte, short, int, long, byte, ushort, uint, ulong),  
  • non-integer (number with precision or floating) types (float, decimal) 
and to convert string value in one of the above listed numeric type, C# language provide two methods


Above two method allows to convert string representation of number to string. For Example

int number = int.Parse("1234");
//or
//int number = -1;
//bool isPased = int.TryParse("1234", out number);
Console.WriteLine(number);

But it fails (i.e. throws run-time exception) when you try input as below

int parsedNumber = int.Parse(" -1234 ");
int parsedNumber = int.Parse("(1234)");
int parsedNumber = int.Parse("$1234");
int parsedNumber = int.Parse("1,234");
int parsedNumber = int.Parse(" (1,234) ")

So above all tried input throws run-time exception , but solution to is make use of overload of Parse and TryParse which comes with NumberStyles as input. Below is screen shot of overload of Parse method

below is code make use of overload and avoid run-time exception.

//output: -1234
int parsedNumber = int.Parse("(1234)", NumberStyles.AllowParentheses);

// output: 1234
int parsedNumber = int.Parse("1,234", NumberStyles.AllowThousands);

// output: -1234
int parsedNumber = int.Parse(" -1234  ", NumberStyles.AllowTrailingWhite |
                                              NumberStyles.AllowLeadingWhite |
                                              NumberStyles.AllowLeadingSign);

// output: -1234
int parsedNumber = int.Parse(" (1,234) ", NumberStyles.AllowTrailingWhite |
                                          NumberStyles.AllowLeadingWhite |
                                     NumberStyles.AllowParentheses |
                                          NumberStyles.AllowThousands);

// allows currency symbol
// output: 1234
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
int parsedNumber4 = int.Parse("$1234", NumberStyles.Currency);

Different number allows different input values. As given in above code one can put logic OR between  different value of NumberStyles and allows combination to permit various input format.

Try out other values of NumberStyles listed at MSDN: https://msdn.microsoft.com/en-us/library/system.globalization.numberstyles(v=vs.110).aspx  

Tuesday, May 22, 2018

Factory Design Pattern With Generics

Factory Method design pattern is one of the highly used design pattern, which is used in project to centralize creation of similar family object in application. It's part of creation design patterns as it helps to create objects in application.



Why to Centralize Object creation with Facotry?

  1. To avoid object creation every where in application with New. 
  2. To create object at run-time which serves purpose, based on requirement (i.e. based on input parameters). 
Factory Pattern Implementation

Below is class diagram and code implementation of Factory pattern.

Below code, centralize creation of command objects with help of Factory design pattern. Code below works as below

  • Code below creates different command to perform task such as addemployee, editemployee etc.
  • It's scalable as if developer wants to add new command let's say deleteemployee then it require to create new DeleteEmployee command which inherits from ICommand as other commands do.
  • CommandFactory , its factory pattern base class which has method GetCommand to return requested command based on input string argument. Modification required in GetCommand method when new command need to be added in application.
  • Program is client class which make use of CommandFactory and execute returned command.

    class Program
    {
        static void Main(string[] args)
        {
            ICommand cmd = CommandFactory.GetCommand("AddEmployee");
            Console.WriteLine(cmd.GetType());
            Console.ReadLine();
        }
    }

    public class CommandFactory
    {
        public static ICommand GetCommand(string cmdName)
        {
            if(cmdName=="AddEmployee") 
            {
                return new AddEmployee();
            } 
     else if(cmdName=="EditEmployee") 
            {
                return new EdutEmployee();
            }

            return new NullCommand();
        }
    }

    public class NullCommand : ICommand
    {
        public bool CanExecute()
        {
             Console.WriteLine("Null command");
    return true;
        }

        public void Execute()
        {
           Console.WriteLine("Null command");
        }
    }

    public class AddEmployee : ICommand
    {
        public bool CanExecute()
        {
            //validation
   return true;
        }

        public void Execute()
        {
          //code to execute
        }
    }
 
    public class EditEmployee : ICommand
    {
        public bool CanExecute()
        {
            //validation
             return true;
        }

        public void Execute()
        {
          //code to execute
        }
    }

    public interface ICommand
    {
        bool CanExecute();
        void Execute();
    } 

Following are issues with above code
  1. One big issue with above code is , it's violate Open Close principle. Because whenever new command added in application, developer need to go to Command Factory and need to add if condition for creating it.
    For Example: when there is need of adding Delete command , developer need to open CommandFactory class and need to add if clause for that.
  2. CommandFactory, GetCommand takes string argument to create and return instance of command. If developer pass wrong string argument value it will end up with NullCommand object (which is based on Null object pattern).
    So its not type safe implementation.
  3. CommandFactory, GetCommand can only return ICommand. If developer added new property/method let's say xyz which is specific to command ex. AddEmployee, then developer cannot access it like addCommandObj.xyz as return Command is of type ICommand and it doesnt has that property. 
Generics Based Factory Pattern Implementation

Solution to problem listed above is make use of factory pattern using Generics. Below is diagram and code of implementation


    class Program
    {
        static void Main(string[] args)
        {
            ICommand cmd = CommandFactory.GetCommand<AddEmployee>();
            Console.WriteLine(cmd.GetType());
            AddEmployee addEmployeeCmd = CommandFactory.GetCommand<AddEmployee>();
            Console.WriteLine(addEmployeeCmd.NewEmployeeId);
            Console.ReadLine();
        }
    }

    public class CommandFactory
    {       
        //only create object of type which implement ICommand
        public static T GetCommand<T>() where T:  ICommand
        {
          //it create object using Template type T and by making use of reflection
          //once create factory this way there is no need to open it again for modification
            Type type = typeof(T);
            Object obj = Activator.CreateInstance(type);
            return (T)obj;
        }
    }

    public class EditCommand : ICommand
    {
        public bool CanExecute()
        {
            //validation
            return true;
        }

        public void Execute()
        {
            //code to execute 
        }
    }

    public class AddEmployee : ICommand
    {
        private int newEmployeeId;
        public int NewEmployeeId
        {
            get { return newEmployeeId; }
        }

        public bool CanExecute()
        {
            return true;
        }

        public void Execute()
        {
            //execute code to create employee
            this.newEmployeeId = 1;//created employeeid 
        }
    }

    public interface ICommand
    {
        bool CanExecute();
        void Execute();
    } 

Following are advantages (solutions for previous approach problem) of generics based implementation

  1. It doesn't violate open close principle as object get created using reflection and using Generics Template type T in CommandFacoty class - GetCommand method. Check CommandFacotry Class in above code.
  2. By making use of Generics, it makes CommandFactory strongly type and there is no need string as argument based on which GetCommand method creating object in previous implementation.
     public static T GetCommand<T>() where T:  ICommand 
    if you see signature of GetCommand now,  it force Template type T must implement ICommand interface and so that it only going to create object of types which implement ICommand.
  3. Now factory can return object of specific implemented type like AddEmployee
      AddEmployee addEmployeeCmd = CommandFactory.GetCommand<AddEmployee>();
    
    Above line of code in Program class Main method proves point that now factory can return implemented type that can also be convert to to parent type ICommand.
Wrapping up
Factory pattern is one of the highly used deign pattern which used in most of the application to create and centralize object creation. So when it written not strongly type based way can lead to problem. So it's better to implement it strongly type based way (Generics implementation) to avoid issues and it helps to stick your code with SOLID principle.


Sunday, December 3, 2017

Abort/Cancel Task

Below post is based on one of the question(Stop hanging synchronous method) I answered on StackOverflow, in which questioner wants to cancel task when its taking too long time to respond i.e. taking too much time in execution and returning result.  But when I tried to provide answer of that question I found there is no direct way to cancel task when its making call outside world i.e. making call to WebService or making call to Database to get data via third party library XenAPI in my case, which is hanging application and not allowing to proceed. To understand this have look to below code.

Var task = Task.Factory.StartNew(()=> CallWebServiceandGetData());

Above line of code creating task which is making call to webservice to get data. Now developer want to write code, such a way that if task take more than 10 second, task get cancel. But in TPL library there is no way to cancel task i.e. there is no direct method or there is no other way to make this task cancel.
So task.Cancel() or task.Abort() like method not exist in TPL. Below post is about how developer can really abort task.

Aborting thread vs Cancelling task

What is really difference between aborting thread and cancelling task.
Aborting thread – In System.Treading , which is library provided for threading prior to TPL library. (Just to note : old System.Threading is still part of.net framework but as TPL provide more control on Task( which is wrapper around thread) provide more control ). In this library to abort thread there is as method called Abort() is available. With help of this method developer can ask execution environment i.e. CLR to abort thread. Below is example code for the same

Thread newThread = new Thread(() => Console.WriteLine("Test"));
newThread.Start();
Thread.Sleep(1000);//sleeping main thread
newThread.Abort();

main thread aborting newly created thread.

Cancelling Task – In newer library TPL (System.Threading.Tasks) , there is no direct method on Task which cancel or abort underlying thread. But there is way to cancel task by using CancellationTokenSource class which allows you to pass CancellationToken as one of the input parameter when you create task. (more on this discussed below). Below is code for cancelling task

var source = new CancellationTokenSource();

CancellationToken token = source.Token;Task.Factory.StartNew(() => { 
 for(int i=0;i< 10000;i++)
 {
   Console.WriteLine(i);
   if (token.IsCancellationRequested)
    token.ThrowIfCancellationRequested();
 }
}, token);
source.CancelAfter(1000);

So above code make use of CancellationTokenSource and CancellationToken provided by it. In above code CancellationTokenSource calls method CancelAfter which set taskCancellation flag. This flag is watched inside delegate via IsCancellationRequested property on CancellationToken. And once it sees in for loop that IsCancellationRequested flag is true it calls ThrowIfCancellationRequested() method and cancels thread.

So in simple term abort thread allows developer to abort executing thread and CancellationToken in new TPL library does same thing, which is called cancelation of task. So basically newer(TPL) and older(Threading) have different way to cancel/abort thread.

But one of the major difference between Abort() thread and Cancel task is Abort() can leave application in inconsistent state ( on Abort()system immediately abort thread not allow to perform any operation to put application in consistent state ),  especially when doing file operation or doing create/update operation , so it better to take care when aborting thread or write code such way that application remain in consistent state. That is one of reason TPL come up with Cancellation mechanism, so those who write code can watch cancellation flag and if it gets true than they can write code to put application in consistence state.

Returning to problem of Cancelling task

By reading above section of “Cancellation Task” one can say there is provision to cancel task which in turn cancel thread also and put system in consistent state, so it’s better approach.  But if we now go to back to scenario where task is got created to fetch data from webService or DataBase which is taking too much long time. So code will be like as below with cancellation mechanism

var source = new CancellationTokenSource();
CancellationToken token = source.Token;
Task.Factory.StartNew(() => { 
    try
    {
        //below is third party library(XenAPI) method 
        HTTP_actions.put_import(…//parameter of method);
        //instead of this there can be database call to get data
        //which takes too much time 
    }
    catch (HTTP.CancelledException exception)
    {
    }
    //execution never comes here till above method get complete           
    if (token.IsCancellationRequested)
        token.ThrowIfCancellationRequested();
              
}, token);
source.CancelAfter(1000);

So in above scenario once call made to API method it never comes back, so control of execution will not return to application and so the code which checks cancellation never get executed till call returns. Which means Task not get cancelled even though after 1000 ms it cancellation flag set to true for cancellation of task.

Above scenario is based on Third party API so it might difficult to understand context. So for easy understanding have look to below code (just one change here , TaskCompletionSource is used to wrap underlying task)

static Task<string> DoWork(CancellationToken token)
        {
            var tcs = new TaskCompletionSource<string>();

            //comment this whole this is just used for testing 
            Task.Factory.StartNew(() =>
            {
                //Simulate work (usually from 3rd party code)
                for (int i = 0; i < 100000; i++)
                    Console.WriteLine("value" + i);

              //execution never comes here till above for loop or        
              //may be long execution /computation get completed           
               if (token.IsCancellationRequested)
                    token.ThrowIfCancellationRequested();

                Console.WriteLine("Task finished!");
            },token);
            tcs.SetResult("Completed");
            return tcs.Task;
        }
       public static void Main()
        {
            var source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            DoWork(token);
             source.CancelAfter(1000);
            Console.ReadLine();
        }

So in above code instead of third party code I replaced it with for loop (or consider long calculation task), now when execution going on application cannot get chance to read cancellation flag which is setup by main thread i.e. from main method. So application cannot able to cancel task till computation get over and control reach to point where cancellation flag check is done. In both of the scenario major problem is when log computation or long call is going on application cannot cancel task, Cancellation mechanism provided in TPL not work and there we need solution to cancel this task other way.

Solution code is
 
    class Program
    {
        //capture request running that , which need to be cancel in case
        // it take more time 
        static Thread threadToCancel = null;
        static async Task<string> DoWork()
        {
            var tcs = new TaskCompletionSource<string>();
            //comment this whole this is just used for testing 
            await Task.Factory.StartNew(() =>
            {
                //Capture the thread
                threadToCancel = Thread.CurrentThread;
                //Simulate work (usually from 3rd party code)
                for (int i = 0; i < 100000; i++)
                     Console.WriteLine("value" + i);
               Console.WriteLine("Task finished!");
            });
            tcs.SetResult("Completed");
            return tcs.Task.Result;
        }

        public static void Main()
        {
            var source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            DoWork();
            //another task check for cancellation flag
            //cancels long running task by calling thread abort method 
            Task.Factory.StartNew(() =>
            {
           //while true below is just for example , in real time 
           //you should replace this with either timer or by thread sleep
           //to save CPU time (or may be better solution other than that) 
           //it better to play around that 
                while (true)
                {
                    if (token.IsCancellationRequested && threadToCancel != null)
                    {
                        threadToCancel.Abort();//abort long running thread
                        Console.WriteLine("Thread aborted");
                        return;
                    }
                }
            });
            //here 1000 can be replace by miliseconds after which you want to 
            // abort thread which calling your long running method 
            source.CancelAfter(1000);
            Console.ReadLine();
        }
    }

Comment in code explains most of the things but let go in detail how it’s going to work. Following are changes in code
  1.  Async/await used to make DoWork method asynchronous
  2.  threadToCancel variable in code stores reference of the Tread of underlying Task by calling Thread.CurrentThread, this variable allows to cancel thread of Task
  3. One more Task got created in main which keep checking Cancellation flag which setup by source.CancelAfter(1000); after 1000 miliseconds 
  4. Task created in Main is running While loop with true, which keep check Cancellation flag true to not, once it gets true this task executes method threadToCancel.Abort(); to abort underlying thread of long running task
So Real magic part in code is reference of underlying thread is stored via Thread.CurrentThread. And separate task runs in main method abort long running task thread when cancellation flag set to true by CancellationSoruce.

Monday, November 27, 2017

TPL : Find Failed Task

TPL - Task paralle library is new libaray added by microsoft in .net framework 4.0. This libaray allows one to create task i.e Thread, which means multi threading application. Task created by this libarary allows greater control on task(thread) which is very diffcult with previous Threading library, one of them is exception handling specially when one use ThreadPool for doing work. Below post is about handling exception in TPL and about how to find which of task failed when multiple task excuted.

Exception Handling : Single Task (synchronous)

Exception handling is very easy when Task(thread) creaed by TPL. But to find out task failed or executed without exception one must need to use "Wait()" method or need use "Result" property. Below is example of same.

 try
 {
     //below throws divide by zero exception
     var task = Task.Factory.StartNew(() => { return 10 / 0;});
     task.Wait();//or use task.Result
     //or there may be multiple taks 
     // example
     // Task[] task = new Task[3](); 
     // task[1] = Task.Factory.StartNew(() => { return 10 / 0;});
     // task[2] = Task.Factory.StartNew(() => { return 10 / 0;});
     // task[3] = Task.Factory.StartNew(() => { return 10 / 0;}); 
     //Task.WaitAll(task); //for this multiple senario we need Aggregate exception.
 }
 catch (AggregateException ex)
 {
     Console.WriteLine(ex.InnerException.ToString());
 } 

above code throw DivideByZeroException. and same get printed as output of the above code. One thing to note here is it throws AggregateException exception, so one need to go to InnerException for getting exact exception message.AggregateException is need because in real time senario there might be running and if all throws exception than there need to be structure like AggregateException who stores excpetion of all task.

Exception Handling : Single Task (asynchronous)

Below is same code with asynchronous.

public static async void CallDivide()
{
  try
  {
     var task = Task.Factory.StartNew(() => Divide(0));
     await task;
  }
  catch (Exception ex)
  {
     Console.WriteLine(ex.ToString());
  }
}  

it will give output same as previous one. One thing to note here there is no need to use AggregateException as asynchronous as when task fails it exception get unwarped and get throw to captured context or on thread which is going to execute continuation. If there are multiple task than only first failed task exception get reported as asynchronous unwrap AggregateException and throw first one.

So there is not problem when you are execution one task and it fails , in that case you know which one failed. But actual problem occurs when you are executing multiple task and one of task fails, then there is no way which one failed.

Exception Handling : Multiple Task (synchronous)

To undestand this let go throgh below code

 public static void Main(string[] args)
 {
    List<int> lstInt = new List<int>(){1,11,4,3,0,7,0};
    List<Task<string>> tasks = new List<Task<string>>();
    foreach(int i in lstInt)
    {
        var task =Task.Factory.StartNew((obj)=> Divide(i),"Task " + i);
        tasks.Add(task);
    }
    try
    {
        Task.WaitAll(tasks.ToArray());
    }
    catch(AggregateException e)
    {
        for (int j = 0; j < e.InnerExceptions.Count; j++)
        {
            Console.WriteLine("\n--------------------\n{0}", e.InnerExceptions[j].Message);
        }
    }
    var failedTask = tasks.Where(t=> t.IsFaulted);
  }
        
  public static string Divide(int i)
  {
      var val = 10/i;
      Console.WriteLine(val);
      return "Value : " + i +" : " + val;
  }

Above code output is :

10
0
3
2
1

--------------------
Attempted to divide by zero
Attempted to divide by zero.

Exception Handling : Multiple Task (asynchronous)

Same output will be there when you try below asynchronous task based approch. But asynchronous only prints first failed task exception as asynchronous unwrap received AggregateException and report first one only.

public static async void CallDivide()
{
    List<Task<string>> tasks = new List<Task<string>>();
            try
            {
                List<int> lstInt = new List<int>() { 1, 11, 4, 3, 0, 7, 0 };
                
                foreach (int i in lstInt)
                {
                    var task = Task.Factory.StartNew((obj) => Divide(i), "Task " + i);
                    tasks.Add(task);
                }

                await Task.WhenAll(tasks.ToArray());
            }
            catch (Exception ex)
            {
                var exceptions = tasks.Where(t => t.Exception != null).Select(t => t.Exception);
                Console.WriteLine(ex.ToString());
            }
}
public static string Divide(int i)
{
    var val = 10 / i;
    Console.WriteLine(val);
    return "Value : " + i + " : " + val;
}

Above code output is :

10
0
3
2
1

--------------------
Attempted to divide by zero
 ///Attempted to divide by zero.- will not come in case of asynchronous

By the output you get to know one task failed, but you dont know which task failed or in simple term you dont know for which input my method failed when data coming from database or some external soruce(means right now we have static list of interger for example in real application this list of int is may be coming from via argument or via database).
Or imagine senario where you are querying multiple database via multiple task and one of the database query have problem and thro exception i.e. one of the task fails. In that senario you like to know which database failed.

Solution

Solution for this i.e. to find which task failed easy way is to attach "State" with task. When you attache State with Task you will get state value when you access property called "AsyncState". Below is line of code which shows how you can attach sate with task. To attach state one(developer) just need to pass one more argument after called function, which is "Task " + i in in this case.

var task = Task.Factory.StartNew((obj) => Divide(i), "Task " + i);
 
Below is full code how this solution works

Find Faild Task : Multiple Task (synchronous)

 static  void Main(string[] args)
        {
            Console.ReadLine();
            List<int> lstInt = new List<int>() { 1, 11, 4, 3, 0, 7, 8 };
            List<Task<string>> tasks = new List<Task<string>>();
            foreach (int i in lstInt)
            {
                var task = Task.Factory.StartNew((obj) => Divide(i), "Task with input " + i);
                tasks.Add(task);
            }
            try
            {
                Task.WaitAll(tasks.ToArray());
            }
            catch 
            {
                   var failedTask = tasks.Where(t => t.IsFaulted);
                   foreach (var t in failedTask)
                   {
                      Console.WriteLine(t.AsyncState.ToString());
                       Console.WriteLine(t.Exception.InnerException.ToString());
                   }
            }
            
            Console.ReadLine();
        } 

Find Faild Task : Multiple Task (asynchronous)

  public static async void CallDivide()
        {
            List<Task<string>> tasks = new List<Task<string>>();
            try
            {
                List<int> lstInt = new List<int>() { 1, 11, 4, 3, 0, 7, 8 };

                foreach (int i in lstInt)
                {
                    var task = Task.Factory.StartNew((obj) => Divide(i), "Task with input" + i);
                    tasks.Add(task);
                }

                await Task.WhenAll(tasks.ToArray());
            }
            catch 
            {
                var failedTask = tasks.Where(t => t.Exception != null);
                foreach (var t in failedTask)
                {
                    Console.WriteLine("Failed Task is : " + t.AsyncState.ToString());
                    Console.WriteLine("Failed Task Excetption is : " + t.Exception.InnerException.Message);
                };
            }
        } 

output of above code
10
0
2
1
1
3
Failed Task is : Task with input 0
Failed Task Excetption is : Attempted to divide by zero.

both of the way will give you same output. But if you see output caefully , you see Task with input 0 failed. Here i just attached input but in real time senario like when querying datase you can attach name of database or you can also give some meaning ful vaue in state or even you can pass object as state. But point here is you can get to know which task failed when you attach state with Task.

Tuesday, April 12, 2016

Diffence between list of user defined types

Below is discussion about finding out difference between two lists of elements.

Easiest way to find out difference between two list is make use of method Except, which is introduced with Linq feature in .Net framework 3.5.

Except method works as below



So when except method is applied on two List A and List B, it get list of all element which are present in list A only.

Let’s understand same by writing Code

List<int> a = new List<int>() { 2, 4, 7, 9, 4 };
List<int> b = new List<int>() { 8, 6, 7, 3, 4 };

var lst = a.Except(b);
foreach (var ele in lst)
{
    Console.WriteLine(ele);
}
Above code defines two list of integer, and apply Except method to find difference between them.

Output 
 


Output prints 2 & 9, which are the element in “List a” and not in “List b”. If one want to find out element which are present in “List b” and not in “List a”, than code will be like

var lst = b.Except(a);//pint output 8,6 & 3

Note:
Except method returns element of the collection which is on left side, it doesn’t get list of those element of the right side collection element which is not part of left side collection.

Except on User Defined typed List
Below is explain about how Except works when applied on user-defined data type, to understand this let’s defined employee class

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

After defining Employee class below code creates two list of Employee and applies Except method on it

List<Employee> lstA = new List<Employee>() { new Employee { ID = 1, Name = "Abc" }, 
                         new Employee { ID = 2, Name = "Pranay" },
                         new Employee { ID = 3, Name = "Hemang" }};
 List<Employee> lstB = new List<Employee>() { new Employee { ID = 4, Name = "Xyz" }, 
                         new Employee { ID = 2, Name = "Pranay" },
                         new Employee { ID = 5, Name = "Virendra" }};

var lst = lstB.Except(lstA);
foreach (var ele in lst)
{
     Console.WriteLine(ele.ID + " " + ele.Name);
}

Output 
 


So output print out all the element of list B, rather than printing elements which are not present in list A.
Problem here is when Except method applied on user-defined datatype it tries to compare references of object to find difference between lists.

Resolution
To resolve problem, there is need to use Except overload method which takes list as first input and Custom Equality Comparer as its second parameter for type. Custom Equality comparer helps to do comparison between object of list and returns difference between list.

public class EmployeeComparer : IEqualityComparer<Employee>
{
     bool IEqualityComparer<Employee>.Equals(Employee x, Employee y)
     {
        if (x == null || y == null)
            return false;

        return x.ID == y.ID;
     }

    int IEqualityComparer<Employee>.GetHashCode(Employee obj)
    {
       if (obj == null)
           return 0;

       return obj.ID.GetHashCode();
    }
}
Above code defines Custom Employee comparer which implements IEqualityComparer and does comparison of employee objects based on ID property defined in employee class.

Now when Except method applied on list as in below code,

List<Employee> lstA = new List<Employee>() { new Employee { ID = 1, Name = "Abc" }, 
                         new Employee { ID = 2, Name = "Pranay" },
                         new Employee { ID = 3, Name = "Hemang" }};

List<Employee> lstB = new List<Employee>() { new Employee { ID = 4, Name = "Xyz" }, 
                         new Employee { ID = 2, Name = "Pranay" },
                         new Employee { ID = 5, Name = "Virendra" }};

var lst = lstB.Except(lstA, new EmployeeComparer());
foreach (var ele in lst)
{
     Console.WriteLine(ele.ID + " " + ele.Name);
}
Output 
 


Output prints element of list B which are not present in List A of employee. So comparer makes it easy to find difference between two lists.

Sunday, March 20, 2016

Event Vs Deleagte

Post is explains basics of Events & Delegate and most importantly explains what is difference between both.
Both Event & Delegate is based on overserved pattern of GOF, which is based on giving notification of change in one thing (object) to all others who is interested in change. Below image is graphical interpretation of same.



Delegates
Delegate in C# is reference type, which hold reference to the function and invokes function when called with Invoke method. If one is coming from C++/C background, delegate is like pointer to function which points to function.
To understand delegate better way have look to below sample code.

    public class DelegateTest
    {
        public delegate void Print(string val);

        public DelegateTest()
        {
            Print p = new Print(PrintValue);
            p += new Print(PrintData);
            p.Invoke("Test");
        }

        private void PrintData(string s)
        {
            Console.WriteLine("PrintData" + s);
        }

        public void PrintValue(string s)
        {
            Console.WriteLine("PrintValue" + s);
        }
    }

When above class get invoked following output will get printed
PrintData Test
PrintValue Test

Key points in above code
  1. It defines delegate which can points to method with void return type and take string as input
  2. In constructor of type, it create reference object of delegate which points to method “PrintData” and “PrintValue”.
  3. Invoke method of delegate calls both methods one by one
Read more about Delegate : https://msdn.microsoft.com/en-in/library/900fyy8e(v=vs.71).aspx

Events
Event in C# is of type Delegate, which means that if one wants to use event than one must need to define delegate first. Event can have multiple event-handler functions which are of signature like delegate which get called when event raised by some event in application Simple Example is Button click on UI. Event is very useful to create notification.
To understand delegate better way have look to below sample code.

    public class EventTest
    {
        public delegate void Print(string val);
        public event Print PrintEvent;

        public EventTest()
        {
            this.PrintEvent +=  PrintData;
            this.PrintEvent += PrintValue;
        }

        public virtual void OnPrintEvent()
        {
            if (PrintEvent != null)
                PrintEvent("Test");
        }

        private void PrintData(string s)
        {
            Console.WriteLine("PrintData" + s);
        }

        public void PrintValue(string s)
        {
            Console.WriteLine("PrintValue" + s);
        }
    }

When above class object is created and then “OnPrintEvent” method invoked following output will get printed
PrintData Test
PrintValue Test

Key points in above code
  1. Its creates delegate which can point to method with return type void and take string as argument
  2. It defines Event which is of type defined delegate
  3. In Constructor, event holds two delegate i.e. Event handlers. It can also be written like
  4.           this.PrintEvent += new Print (PrintData);
              this.PrintEvent += new Print (PrintValue);
    
  5. OnPrintEvent method checks event is holding event handler function or not, if there is any event handler(s) it calls all event handlers.
Read more about Event : https://msdn.microsoft.com/en-in/library/8627sbea%28v=vs.71%29.aspx

Event VS Delegate
Both event and delegate does the same task, which is hold event handlers and call them when delegate/event invoked. So one always has question, what is need of Event in language C# when one can achieve same thing with Delegate.

Answer is Event is wrapper on Delegate type.

Problem With Delegate
Let’s understand this, using same class defined above which is “DelegateTest”.
    class Program
    {

        static void Main(string[] args)
        {
            Program p = new Program();
            DelegateTest delegateTest = new DelegateTest();
            delegateTest.p = new DelegateTest.Print(p.TestString);
            delegateTest.p = null;
        }

        public void TestString(string s)
        {
        }
    }
Above doe does following things
  1. It creates object of type DelegateTest
  2. Its assigns new delegate reference to delegate Print and override value assigned in constructor
  3. Its assigns “null” to Print delegate and removes all added function.

Problem with Delegate is that one can easily override delegate property and that lead to error or serious issue. That means one cannot use delegate as public property.

Solution with Event
To avoid above problem C# has Events, Which defines wrapper around delegate. (Below code make use of EventTest class defined above and as form above code PrintEvent is wrapper around Print delegate).
static void Main(string[] args)
        {
            Program p = new Program();
            EventTest eventTest = new EventTest();
            //eventTest.PrintEvent = null;//Not allowed in C#
            eventTest.PrintEvent += p.TestString;
        }

        public void TestString(string s)
        {
        }
Above does following things
  1. It defines object of type EventTest
  2. its assigns eventhandler to PrintEvent event of EventTest
One cannot do below things with Event
	eventTest.PrintEvent = null;//Not allowed in C#
	eventTest.PrintEvent = new PrintEvent()//Not allowed in C#

So Event type resolve problem of exposing delegate outside class by defining wrapper around delegate. Below image is presentation of Event & Delegate.



Another Difference between Event & Delegate is
  1. Event is very helpful to create Notification system. Same is not possible with delegate because delegate cannot be exposed as public.
  2. Delegate is very helpful to create call back function i.e can pass delegate as function argument, which is not possible with Event.
Conclusion
Event and Delegate are both follows Observer pattern. Difference between both is Event wraps Delegate type and which makes delegate not modifiable in terms of changing reference i.e. assign new object is not possible.

Tuesday, February 9, 2016

Reference type modification vs change of reference

Post is regarding misconception related to modifying reference type variable and assigning new reference object to reference type variable.

Let’s understand misconception by using code, below is customer class created to understand it.

Public class Customer 
{
 Public int ID{get; set;}
 Public string Name {get; set;}
}

Modification of Reference type
 
Customer cust = new Customer { ID = 1, Name = "abc" }; //defines new class 
Console.WriteLine("cust name : " + cust.Name);
cust.Name = "xyz"; //modifies value of name field and modifies cust variable
Console.WriteLine("modified cust name : " + cust.Name);

Above code creates new object of customer class and modifies it.

Customer cust1 = cust; //cust1 now has reference to cust
cust1.Name = "abc xyz"; // modification to Name field of cust1 modifies both cust1 and cust
Console.WriteLine("after cust1 modification name " );
Console.WriteLine("cust name : " + cust.Name);
Console.WriteLine("cust1 name : " + cust1.Name);

Output


Above code assigns reference of already created object cust to cust1. Because cust1 holding reference to same object as cust1 modification to cust1 also change cust. This means both cust and cust1 points only to one object.




Change of Reference i.e. Assigning new reference type object

But what happens when assigns null to cust variable

cust = null;
Console.WriteLine("after cust=null");
if (cust==null)
   Console.WriteLine("cust is null ");
Console.WriteLine("cust1 name : " + cust1.Name);

Ouput


Now most of developer thinks as cust is null than cust1 is also null. But this is not true because when you give new reference to cust , both cust and cust1 point to different location.



Assigning null cust variable is can also be as below

Customer cust = new Customer { ID =2 , Name =”customer abc”}

So when you assign new value to any reference its point to new memory location i.e. new object. Which also means that assigning new value to reference variable is doesn’t affect old reference variable.

What happens in case of method?

Now Consider scenario where developer pass reference variable to method

Modification of Reference type

Customer cust = new Customer { ID = 1, Name = "abc" }; //defines new class 
Console.WriteLine("cust name : " + cust.Name);
Program p = new Program();
p.ChangeCustomer(cust);
Console.WriteLine("modified cust name after call to changecustomer : " + cust.Name);

public void ChangeCustomer(Customer cust)
{
     cust.Name = "xyz"; //modifies value of name field and modifies cust variable
     Console.WriteLine("modified cust name in changecustomer : " + cust.Name);
}

Above code defines new customer object and pass customer object to method which does modification to object.

Method modifies customer name, so does it modifies customer object also. Output below prints modified customer name in method and same name after call returns to caller.

So this is similar to case discussed above.

Output 



Change of Reference i.e. Assigning new reference type object

Now consider below scenario

Customer cust = new Customer { ID = 1, Name = "abc" }; //defines new class 
Console.WriteLine("cust name : " + cust.Name);
Program p = new Program();
p.ChangeCustomer1(cust);
Console.WriteLine("modified cust name after call to changecustomer1 : " + cust.Name);

public void ChangeCustomer1(Customer cust)
{
    cust = new Customer { ID = 1, Name = "abc xyz" };
    Console.WriteLine("modified cust name in changecustomer1 : " + cust.Name);
}  

Above code defines new customer object and pass customer object to method which does modification to object.

Method in this code assigns new customer object to pass cust variable. So it print output as below



Output prints different name. Reason behind this is method doesn’t modify varible but it’s changing reference value it points by assigning new customer object.

So this is similar to case discussed above.

Solution to above is either return newly created object as below

public Customer ChangeCustomer1(Customer cust)
{
    cust = new Customer { ID = 1, Name = "abc xyz" };
    Console.WriteLine("modified cust name in changecustomer1 : " + cust.Name);
    return cust;
}

Or make use of ref with variable name

public void ChangeCustomer1(ref Customer cust)
{
    cust = new Customer { ID = 1, Name = "abc xyz" };
    Console.WriteLine("modified cust name in changecustomer1 : " + cust.Name);
}

Conclusion 

Above discussion it’s clear that modification to reference variable happens when you do change in original reference variable and assigning new object to variable does modify the reference i.e. memory location object points to.

Monday, September 7, 2015

Collection Interface In .NET

Introduction

.NET framework provides interfaces that implements by collections in language to provide functionality of iterating over objects in collection, adding and removing object from collection to randomly access object from collection.

As different interfaces provide different set of functionality most of the developers has problem when to use which interface to achieve functionality. The following post provides information about interfaces implemented by collection.

Interfaces

The following diagram is for relation between the interfaces.


Note:
  1. Class diagram are not having all the methods but contains important method that belongs to each collection interface.

  2. Collection interface is available in both generic and non-generic form, so in diagram obj type is object in nongeneric form and obj type is T(template type) in generic form.
Functionality Provided Read Count Add & Remove Index Based Read Index Based Add & Remove
IEnumerable
  1. Provide Read only Collection.
  2. Allow to read each object of collection in forward only mode.
Y N N N N
ICollection
  1. Allow to modify collection.
  2. Allow to get size of collection.
  3. Allow to Add and Remove object in/from collection.
Y
Inherited)
Y Y N N
IReadOnlyCollection
  1. Allow to read collection.
  2. Allow to get size of collection.
Y
(Inherited)
Y N N N
IList
  1. Allows to access collection by Index.
  2. Allow to Add and Remove object in/from collection by index.
Y
(Inherited)
Y
(Inherited)
Y
(Inherited)
Y Y
IReadOnlyList Allow to read collection by Index. Y
(Inherited)
Y
(Inherited)
N Y N

Note:
In above diagram (Inherited), the columns indicate that the features are inherited from parent and to find out from which parent one must look in the interface collection diagram.

So from above table three main interfaces functionality concluded in following way:

IEnumerable – interface provide minimum functionality which is Enumration.

ICollection – interface provide medium functionality which is getting size, adding, removing and clearing collection i.e. modification of collection. As it inherited from IEnumerable so includes functionality of IEnumerable.

IList – interface provide full functionality which is index base accessing of collection element, index base adding, index base removing from collection. As it inherited from ICollection it includes functionality of Enumerable and ICollection.

The following are some important things to know:
  1. IEnumerable interface under the hood make use of IEnumerator for providing reaonly and forward mode read.

  2. IReadOnly*** and IEnumerable are used for providing readonly collection. But difference is that IEnumerable allows collection to read in forward only mode where IReadOnly*** provide feature of Collection /List but only in readonly mode i.e. without modification feature like add & remove.

  3. IReadOnly is part of collection interface from framework 4.5.
Above table list down the features provided by each interface when collection gets converted to interface type or class implement interface to provide feature of collection.

Conclusion

It’s very important for developers to understand these interfaces because the rule says its always good to depend on interface rather than on the concrete type.

ContinueWith Vs await

TPL is new library introduced in C # 4.0 version to provide good control over thread, to make use of multicore CPU by mean of parallel execution on thread. Below discussion is not about TPL but its about ContinueWith function available on Task Class of TPL and await keyword introduced in C# 5.0 to support asynchronous calls.

ContinueWith - its method available on the task which allows executing code after task finished execution. In simple word it allows continuation.

Things to note here is ContinueWith also return one Task. That means you can attach ContinueWith on task return by this method.

Example :
public void ContinueWithOperation()
{
   Task<string> t = Task.Run(() => LongRunningOperation("Continuewith", 500));
   t.ContinueWith((t1) =>
   {
       Console.WriteLine(t1.Result);
   });
}

In above code new created task runs LongRunningOperation and once task execution completed ContinueWith execute operation on retuned task and print result of task.

ContinueWith operation thask get executed by default thread scheduler, one can also provide other scheduler for running task on it, this discussed in later in this article.

Note: below code is LongRunningOperation called by task. LongRunningOpertion here is just example in real program one cannot call long running operation on task, and if one want to call longrunning task than one need to pass TaskCreationOperation.LongRunning.

private string LongRunningOperation(string s, int sec)
{
  Thread.Sleep(sec);
  return s + " Completed";
}

await – its keyword that cause runtime to run operation on new task and cause executing thread to return and continue with execution (In most of the cases executing that is main thread of application). Once await operation get finished it returns to statement where is left of (i.e. returns to caller i.e. it returns according state saved) and start executing statements.

So await wait for newly created task to finish and ensures continuation once execution of waiting task is finished.

await keyword used with async to achieve asynchronous programming in C#. It’s called asynchronous programming because runtime capture state of program when it encounter await keyword (which is similar to yield in iterator) and restore state back once waited task finish so the continuation runs on correct context.

Example :

public async void AsyncOperation()
{
    string t = await Task.Run(() => LongRunningOperation("AsyncOperation", 1000));
    Console.WriteLine(t);
}

In above example new created task calls LongRunningOperation and execution left of once main thread encounter await keyword i.e. main thread return to caller of AsyncOpetion and execute further. Once LongRunningOpertaion completed than result of task get printed on console.

So here because state saved when await encountered flow returns on same context one operation on task executed.

Note: State is having detail about executioncontext/synchronizationcontext.

So form above its clear that both Task.ContinueWith and await Task wait for task to finish and allows continuation after task completion. But both works differently.

Difference between ContinueWith and await
  1. Saving Sate for And return on Execution context
    ContinueWith doesn’t save any kind of state, continuation operation attached using ContinueWith run on default thread scheduler in case not scheduler provided.

    await – on encounter of this keyword state get saved and once task on which await done get completed execution flow pick up saved state data and start execution statement after await. (Note: State is having detail about executioncontext/synchronizationcontext.)

  2. Posting Completed Task result on UI Control
    Below is example with ContinueWith and await to display completion task result on UI control.

    ContinueWith :

    Consider below code which display result of completed task on UI label.

    public void ContinueWithOperation()
           {
             CancellationTokenSource source = new CancellationTokenSource();
             source.CancelAfter(TimeSpan.FromSeconds(1));
             Task<string> t = Task.Run(() => LongRunningOperation("Continuewith", 500
    ));
    
                t.ContinueWith((t1) =>
                {
                    if (t1.IsCompleted && !t1.IsFaulted && !t1.IsCanceled)
                        UpdateUI(t1.Result);
                });
    }
    
    private void UpdateUI(string s)
           {
             label1.Text = s;
    }
    Note : LogRunningOperation is already given above.

    When above code is get executed below runtime exception occurs.



    This exception occurs because Continuation operation UpdateUI operation runs on different thread, in this case thread will be provided by default threadschedular which is ThreadPool and it doesn’t have any information about Synchronization context on which to run.

    To avoid exception, one must need to pass thread scheduler which pass data on UI SynchronizationContenxt. In below code TaskScheduler.FromCurrentSynchronizationContext() method pass UI related thread scheduler.

    t.ContinueWith((t1) =>
                {
                    if (t1.IsCompleted && !t1.IsFaulted && !t1.IsCanceled)
                        UpdateUI(t1.Result);
                }, TaskScheduler.FromCurrentSynchronizationContext());


    await :

    Consider below code which display result of completion on UI.

    public async void AsyncOperation()
    {
        try
        {
           string t = await Task.Run(() => LongRunningOperation("AsyncOperation",
                            10000));
           UpdateUI(t);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


    Code written with await doesn’t throw any exception when posting data to UI control, No special code required for await. This happens because as discussed in 1 point of difference , on encounter of await state data get saved which has information about SynchronizationContext.

    So if one need to post data on UI than await is good option because there is no need of extra care/code to post data on UI.


  3. Handling Exception and Cancellation
    Consider below example code for ContinueWith and await method for handing exception and cancelled task.

    ContinueWith

    Below is example code how the exception/cancellation handled using ContinueWith.

    public void ContinueWithOperationCancellation()
           {
                CancellationTokenSource source = new CancellationTokenSource();
                source.Cancel();
    
                Task<string> t = Task.Run(() =>
                    LongRunningOperationCancellation("Continuewith", 1500,
                        source.Token), source.Token);
    
                t.ContinueWith((t1) =>
                {
                    if (t1.Status == TaskStatus.RanToCompletion)
                        Console.WriteLine(t1.Result);
                    else if (t1.IsCanceled)
                        Console.WriteLine("Task cancelled");
                    else if (t.IsFaulted)
                    {
                        Console.WriteLine("Error: " + t.Exception.Message);
                    }
                });
    }

    In above code cancellation/exception in continuation handled with by using TaskStatus. Other way to do same thing by making use of TaskContinuationOptions.OnlyOnRanToCompletion

    t.ContinueWith(
        (antecedent) => {  },
         TaskContinuationOptions.OnlyOnRanToCompletion);

    await

    Below is example code how the exception/cancellation handled using await.

    public async void AsyncOperationCancellation()
           {
             try
             {
               CancellationTokenSource source = new CancellationTokenSource();
               source.Cancel();
               string t = await Task.Run(() =>
                   LongRunningOperationCancellation("AsyncOperation", 2000, source.Token),
                       source.Token);
                    Console.WriteLine(t);
             }
             catch (TaskCanceledException ex)
             {
                    Console.WriteLine(ex.Message);
             }
             catch (Exception ex)
             {
                    Console.WriteLine(ex.Message);
             }
    }


    Above code doesn’t make use of task status as continuewith, it makes use of try ..catch block to handle exception. To handle cancellation there is need of catch block with TaskCanceledException.

    So from above example my view is cancellation/exception handling is done very clean way when one use continuation.

    Below is code for LongRunningOperationCancellation method.

    private string LongRunningOperationCancellation(string s, int sec,CancellationToken ct)
           {
             ct.ThrowIfCancellationRequested();
             Thread.Sleep(sec);
             return s + " Completed";
    }


    Above three cases shows difference of coding between ContinueWith and await. But below one shows why await is better than ContinueWith.

  4. Complex flow
    Consider below function which used for calculation factorial of number

       public KeyValuePair<int, string> Factorial(int i)
            {
                KeyValuePair<int, string> kv;
                int fact = 1;
                for (int j = 1; j <= i; j++)
                    fact *= j;
                string s = "factorial no " + i.ToString() + ":" + fact.ToString();
                kv = new KeyValuePair<int, string>(i, s);
                return kv;
            }
    Above function calculate factorial of number and return KeyValuePair to caller to display calculation.

    Now problem statement is above function to calculate factorial of number 1 to 5.

    ContinueWith

    Below is code to calculate factorial of numbers between 1 to 5. Expectation from the code below is calculating factorial of number, display it in order and once it completed “Done” message will get printed on the console.

    public void ContinueWithFactorial()
           {
                for (int i = 1; i < 6; i++)
                {
                    int temp = i;
                    Task<KeyValuePair<int, string>> t = Task.Run(() => Factorial(temp));
                    t.ContinueWith((t1) =>
                    {
                        KeyValuePair<int, string> kv = t1.Result;
                        Console.WriteLine(kv.Value);
                    });
                }
                Console.WriteLine("Done");
    }


    Once code get executed one will find that “Done” message get printed immediately i.e. first than factorial of number get displayed on screen. One more problem is number factorial is not get displayed in order. Below is output of the code execution.



    So to resolve problem with above code , code need to be refactored like this

    public void FactContinueWithSeq(int i)
    {
                Task<KeyValuePair<int, string>> t = Task.Run(() => Factorial(i));
                var ct = t.ContinueWith(((t1) =>
                {
                    KeyValuePair<int, string> kv = t1.Result;
                    int seed = kv.Key;
                    if (seed < 6)
                    {
                        Console.WriteLine(kv.Value);
                        seed++;
                        FactContinueWithSeq(seed);
                    }
                    else
                    {
                        Console.WriteLine("Done");
                        return;
                    }
                }));
    }


    Above function will be called like this p.FactContinueWithSeq(1).

    In above code to maintain sequence, task need to be fired one by one. And for that once one task completes its execution Contuation on it with the help of ContinueWith method call function again. It’s like doing recursive calling to function.

    And to display “Done” message at the end need to check for the seed to function. Which checks seed value increases 6 or not.



    But now there is need for attaching continuation on completion of FactContinueWithSeq, to achieve this code need to be done as below.

    TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
            public Task<string> FactAsyncTask { get { return tcs.Task; } }
            public void FactContinueWithSeqAsync(int i)
            {
                Task<KeyValuePair<int, string>> t = Task.Run(() => Factorial(i));
                var ct = t.ContinueWith(((t1) =>
                {
                    KeyValuePair<int, string> kv = t1.Result;
                    int seed = kv.Key;
                    if (seed < 5)
                    {
                        Console.WriteLine(kv.Value);
                        seed++;
                        FactContinueWithSeqAsync(seed);
                    }
                    else
                    {
                        tcs.SetResult("Execution done");
                    }
                }));
            }

  5. Call to above function

    p.FactContinueWithSeqAsync(1);
                Task<string> t = p.FactAsyncTask;
                t.ContinueWith((t1)=> Console.WriteLine(t.Result));


    In above code TaskCompletionSource is used to achieve the code of providing continutation on completion of factorial calculation.

    So one need to do lot of code for providing expected result, which is calculating factorial in sequence, waiting on calculation and once calculation get completed “Done” message get printed on console.

    await

    Now same code with help of await can be done like this

    public async void AwaitWithFactorial()
    {
       for (int i = 1; i < 6; i++)
       {
           int temp = i;
           Task<KeyValuePair<int, string>> t = Task.Run(() => Factorial(temp));
           await t;
           Console.WriteLine(t.Result.Value);
          }
          Console.WriteLine("Done");
     
    }


    Above code is simple and clean there is no need of doing whole big refactoration which required when doing same thing with ContinueWith.

Summary

From above difference/comparison of ContinueWith vs await it clear that in many scenario using and await is very helpful.
But there is also scenario where more complex things not required with proper error/cancellation handling in that case continuewith is helpful. But this scenario is very rare.

It’s always good to go with simple, easy and clear solution, for this my suggestion is always go with await rather than ContinueWith.