Friday, 1 April 2016

FileSystemWatcher Class

private int ReadLinesCount = 0;
public static void RunWatcher()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = "c:\folder";   
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;   
    watcher.Filter = "*.txt";    
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.EnableRaisingEvents = true;

}

private static void OnChanged(object source, FileSystemEventArgs e)
{
      int totalLines - File.ReadLines(path).Count();
      int newLinesCount = totalLines - ReadLinesCount;
      File.ReadLines(path).Skip(ReadLinesCount).Take(newLinesCount );
      ReadLinesCount = totalLines;
}
using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{

    public static void Main()
    {
    Run();

    }

    [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if(args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = args[1];
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch text files.
        watcher.Filter = "*.txt";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
}

Sunday, 21 February 2016

Delegates & its 5 Modern Flavors (Func, Action, Predicate, Converter, Comparison)

Introduction

Delegate is a very powerful feature available in the .NET Framework. In this article, we will explore delegate & its new features which are being introduced in the framework. I will be using Visual Studio 2013 for coding sample code, assuming that you do have basic knowledge of .NET C# code.
I will be explaining the following flavors in this articles:
  1. Func
  2. Action
  3. Predicate
  4. Converter
  5. Comparison
I would like to get feedback on this article. Please feel to share your comments or you can also email me at shettyashwin@outlook.com. If you like this article, please don't forget to rate it.

Background

As part of the Interview panel, I have been asked to interview a lot of candidates for the opening we had. At the time of interview when questions were asked on delegates & its features, very few candidates were able to answer this question. Even one of my team members was surprised when I optimized his code & started using action delegate. Hence, I decided to write this article which shares some details on delegates & some of its features.

What are Delegates?

If I can put it into simple words, Delegate is a pointer to a method. Delegate can be passed as a parameter to a method. We can change the method implementation dynamically at run-time, only thing we need to follow doing so would be to maintain the parameter type & return type.
For example: If I declare delegate with return type int & two parameters as string and int respectively, all the references which are set using this delegate should follow this signature.
internal class Program
   {
       protected delegate int tempFunctionPointer(string strParameter, int intParamater);

       public static void Main()
       {
           DelegateSample tempObj = new DelegateSample();
           tempFunctionPointer funcPointer = tempObj.FirstTestFunction;
           funcPointer("hello", 1);
           Console.ReadKey();
           funcPointer = tempObj.SecondTestFunction;
           funcPointer("hello", 1);
           Console.ReadKey();
       }
   }

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

   public class XEmployee
   {
       public string Name { get; set; }
       public int Age { get; set; }

       public bool IsExEmployee {
           get { return true; }
       }
   }

  public class DelegateSample
   {
       public int FirstTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("First Test Function Execution");
           Console.WriteLine(strParameter);
           return intParamater;
       }

       public int SecondTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("Second Test Function Execution");
           Console.WriteLine(strParameter);
           return intParamater;
       }

       public void ThirdTestFunction(string strParameter, int intParamater)
       {
           Console.WriteLine("Third Test Function Execution");
           Console.WriteLine(strParameter);
       }

       public bool FourthTestFunction(Employee employee)
       {
           return employee.Age < 27;
       }

       public XEmployee FifthTestFunction(Employee employee)
       {
           return new XEmployee() {Name = employee.Name, Age = employee.Age};
       }

       public int SixTestFunction(Employee strParameter1, Employee strParamater2)
       {
           return strParameter1.Name.CompareTo(strParamater2.Name);
       }
   }
Delegates can be executed synchronous or asynchronously. Code sample mentioned above is an example of synchronous processing. To make it an Asynchronous process, we need to use BeginInvoke method.
funcPointer.BeginInvoke("Hello", 1, null, null); 
First two parameters are the inputs for the function. 3rd parameter can be set for getting call back after execution of process. Detailed explanation of making Asynchronous call is available here.

When Do I Use Delegate?

Looking at the sample above, a lot of us might think this can be also achieved using Interface or abstract class, then why do we need delegate.
Delegate can be used in the following scenarios:
  1. If you don’t want to pass your interface or abstract class dependence to internal class or layers.
  2. If the code doesn't need access to any other attributes or method of the class from which logic needs to be processed.
  3. Event driven implementation needs to be done.

Different Flavors of Delegate

As .NET Framework evolved over a period of time, new flavors have been added to keep implementation simple & optimized. By default, you get all the features & functionality with flavors which you get with delegate. Let’s have a look at Func delegate.

Func<TParameter, TOutput>

Func is logically similar to base delegate implementation. The difference is in the way we declare. At the time of declaration, we need to provide the signature parameter & its return type.
Func<string, int, int> tempFuncPointer;
First two parameters are the method input parameters. 3rd parameter (always the last parameter) is the out parameter which should be the output return type of the method.
Func<string, int, int> tempFuncPointer = tempObj.FirstTestFunction;
int value = tempFuncPointer("hello", 3);
Console.ReadKey();
Func is always used when you have return object or type from method. If you have void method, you should be using Action.

Action<TParameter>

Action is used when we do not have any return type from method. Method with void signature is being used with Action delegate.
Action<string, int> tempActionPointer; 
Similar to Func delegate, the first two parameters are the method input parameters. Since we do not have return object or type, all the parameters are considered as input parameters.
Action<string, int> tempActionPointer = tempObj.ThirdTestFunction;
tempActionPointer("hello", 4);
Console.ReadKey();  

Predicate<in T>

Predicate is a function pointer for method which returns boolean value. They are commonly used for iterating a collection or to verify if the value does already exist. Declaration for the same looks like this:
Predicate<Employee> tempPredicatePointer;  
For sample, I have created an Array which holds a list of Employees. Predicate is used to get employee below age of 27:
Predicate<Employee> tempPredicatePointer = tempObj.FourthTestFunction;
Employee[] lstEmployee = (new Employee[]
{
   new Employee(){ Name = "Ashwin", Age = 31},
   new Employee(){ Name = "Akil", Age = 25},
   new Employee(){ Name = "Amit", Age = 28},
   new Employee(){ Name = "Ajay", Age = 29},
});

Employee tempEmployee = Array.Find(lstEmployee, tempPredicatePointer);
Console.WriteLine("Person below 27 age :" + tempEmployee.Name);
Console.ReadKey();

<pre lang="cs">//Code block which gets executed while iteration 
public bool FourthTestFunction(Employee employee)
{
   return employee.Age < 27;
}  

Converter<TInput, TOutput>

Convertor delegate is used when you need to migrate / convert one collection into another by using some algorithm. Object A gets converted into Object B.
Converter<Employee, XEmployee> tempConvertorPointer 
                = new Converter<Employee, XEmployee>(tempObj.FifthTestFunction); 
For sample, I have created XEmployee entity. All the Employees in the collection get migrated to XEmployee Entity.
 Employee[] lstEmployee = (new Employee[]
            {
                new Employee(){ Name = "Ashwin", Age = 31},
                new Employee(){ Name = "Akil", Age = 25},
                new Employee(){ Name = "Amit", Age = 28},
                new Employee(){ Name = "Ajay", Age = 29},
            });

Converter<Employee, XEmployee> tempConvertorPointer 
                = new Converter<Employee, XEmployee>(tempObj.FifthTestFunction);

XEmployee[] xEmployee = Array.ConvertAll(lstEmployee, tempConvertorPointer);
Console.ReadKey(); 

//Code block which get executed while iteration 
 public XEmployee FifthTestFunction(Employee employee)
 {
    return new XEmployee() {Name = employee.Name, Age = employee.Age};
 } 

Comparison<T>

Comparison delegate is used to sort or order the data inside a collection. It takes two parameters as generic input type and return type should always be int. This is how we can declare Comparison delegate.
Comparison<string> tempComparison = new Comparison<string>(tempObj.SixTestFunction); 
In this sample, Employee Name is used to Sort the order. All the entity inside the collection will be processed using SixthTestFunction which contains the logic for processing / sorting the data as per our requirement.
Comparison<Employee> tempComparisonPointer
                = new Comparison<Employee>(tempObj.SixTestFunction);
            Array.Sort(lstEmployee, tempComparisonPointer);
            Console.ReadKey();

 public int SixTestFunction(Employee strParameter1, Employee strParamater2)
        {
            return strParameter1.Name.CompareTo(strParamater2.Name);
        }

Points of Interest

Using the new delegates, we can achieve better level of abstraction & performance can also been gained by avoiding unnecessary iteration or conversion logic. All three delegates (PredicateConverterComparison) do have optimized internal logic for iteration.

References

IEnumerable VS IQueryable

In LINQ to query data from database and collections, we use IEnumerable and IQueryable for data manipulation. IEnumerable is inherited by IQueryable, Hence IQueryable has all the features of IEnumerable and except this, it has its own features. Both have its own importance to query data and data manipulation. Let’s see both the fetures and take the advantage of both the fetures to boost your LINQ Query performance.

IEnumerable

  1. IEnumerable exists in System.Collections Namespace.
  2. IEnumerable can move forward only over a collection, it can’t move backward and between the items.
  3. IEnumerable is best to query data from in-memory collections like List, Array etc.
  4. While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.
  5. IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
  6. IEnumerable supports deferred execution.
  7. IEnumerable doesn’t supports custom query.
  8. IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
  9. Extension methods supports by IEnumerable takes functional objects.

IEnumerable Example

  1. MyDataContext dc = new MyDataContext ();
  2. IEnumerable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
  3. list = list.Take<Employee>(10);

Generated SQL statements of above query will be :

  1. SELECT [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
  2. WHERE [t0].[EmpName] LIKE @p0
Notice that in this query "top 10" is missing since IEnumerable filters records on client side

IQueryable

  1. IQueryable exists in System.Linq Namespace.
  2. IQueryable can move forward only over a collection, it can’t move backward and between the items.
  3. IQueryable is best to query data from out-memory (like remote database, service) collections.
  4. While query data from database, IQueryable execute select query on server side with all filters.
  5. IQueryable is suitable for LINQ to SQL queries.
  6. IQueryable supports deferred execution.
  7. IQueryable supports custom query using CreateQuery and Execute methods.
  8. IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
  9. Extension methods supports by IQueryable takes expression objects means expression tree.

IQueryable Example

  1. MyDataContext dc = new MyDataContext ();
  2. IQueryable<Employee> list = dc.Employees.Where(p => p.Name.StartsWith("S"));
  3. list = list.Take<Employee>(10);

Generated SQL statements of above query will be :

  1. SELECT TOP 10 [t0].[EmpID], [t0].[EmpName], [t0].[Salary] FROM [Employee] AS [t0]
  2. WHERE [t0].[EmpName] LIKE @p0
Notice that in this query "top 10" is exist since IQueryable executes query in SQL server with all filters.
Summary
In this article I try to explain the difference between IEnumerable and IQueryable. I hope after reading this article you will be able to boost your LINQ query performance. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

What should you required to learn machine learning

  To learn machine learning, you will need to acquire a combination of technical skills and domain knowledge. Here are some of the things yo...