Sunday, December 22, 2013

Caller Information in C# 5.0

Getting Caller Information using Caller Info attributes is initially introduced with .NET Framework 4.5. It can be real handy if you want to write a module for tracing, debugging etc.

Following are the Caller Info Attributes which are defined in System.Runtime.CompilerServices namespace.

Let’s see a very simple example.
using System;
using System.Runtime.CompilerServices;
 
namespace CallerInfoDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            TraceMessage("Caller Info Attributes...");
        } 

        static void TraceMessage(string message = "",
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
        {
            Console.WriteLine("Message: " + message);
            Console.WriteLine("Member name: " + memberName);
            Console.WriteLine("Source file path: " + sourceFilePath);
            Console.WriteLine("Source line number: " + sourceLineNumber);
        }
    }
}
Please note the optional parameters which are marked with Caller Info Attributes in the TraceMessage method.

This will print the following output.
Picture1
Output
Please check the following post to get to know about a scenario where Caller Information can be used very effectively.
    INotifyPropertyChanged Without Hardcoding the Property Name

Download the sample from my SkyDrive.

 
Happy Coding.

Regards,
Jaliya

Wednesday, December 18, 2013

Visual C# Technical Guru - November 2013

Became the Visual C# Technical Guru for the month of November, 2013. And this is my Hat-trick Gold Medal. Dear C#, Thank you so much for keeping me up and running.

The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Picture1
Visual C# Technical Guru - November 2013
Happy Coding.

Regards,
Jaliya

Tuesday, December 17, 2013

Action, Func<TResult> and Predicate<T> Delegate

I am pretty you all must have seen these delegates when writing code. IntelliSense shows methods that accepts Actions, Func<TResult> and some accepts Predicate<T>. So what are these? Let’s find out.

Let’s go by a simple example. I have following “Employee” class and it has a helper method which will return me a list of Employees.
public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthday { get; set; }
    public int Age { get; set; }
 
    public static List<Employee> GetEmployeees()
    {
        return new List<Employee>()
        {
            new Employee()
            {
                FirstName = "Jaliya",
                LastName = "Udagedara",
                Birthday =  Convert.ToDateTime("1986-09-11")
            },
            new Employee()
            {
                FirstName = "Gary",
                LastName = "Smith",
                Birthday = Convert.ToDateTime("1988-03-20")
            }
        };
    }
}
In my Main method I am getting these list of type employees into a variable.
List<Employee> employees = Employee.GetEmployeees();

Action

Action series of delegates are pointers to methods which takes zero, one or more input parameters, and does not return anything.

Let’s consider List<T>.ForEach Method, which accepts a Action of type T. For my list of type Employee, it accepts a Action of type Employee.

Untitled
Action
So let’s create a Action now. I have the following method which will calculate the age of the employee when the employee is passed in.
static void CalculateAge(Employee emp)
{
    emp.Age = DateTime.Now.Year - emp.Birthday.Year;
}
So I can create a Action, pointing to above method.
Action<Employee> empAction = new Action<Employee>(CalculateAge); 

employees.ForEach(empAction); 

foreach (Employee e in employees)
{
   Console.WriteLine(e.Age);
}

This will print me the calculated age for each employee. With the use of Lambda Expressions, I can eliminate writing a separate method for calculating the age and put it straight this way.
employees.ForEach(e => e.Age = DateTime.Now.Year - e.Birthday.Year);

Func<TResult>

Func<TResult> series of delegates are pointers to methods which takes zero, one or more input parameters, and returns a value of the type specified by the TResult parameter.

For this let’s consider Enumerable.First<TSource> Method, which has a overloading method which accepts a Func.

Untitled
Func
In my scenario this particular method accepts Func which accepts a Employee and returns a bool value. For this let’s create a method which I am going to point my Func to. Following method accepts a employee and checks whether his/her FirstName is equal to “Jaliya” and returns true or false.
static bool NameIsEqual(Employee emp)
{
    return emp.FirstName == "Jaliya";
}
Now I can create a Func and get the first employee which satisfies the condition on Func.
Func<Employee, bool> myFunc = new Func<Employee, bool>(NameIsEqual); 

Console.WriteLine(employees.First(myFunc).FirstName);
Again with the use of Lambda Expressions, I can make my code simple.
Console.WriteLine(employees.First(e => e.FirstName == "Jaliya").FirstName);

Predicate<T>

Predicate<T> represents a method that defines a set of criteria and determines whether the specified object meets those criteria.

For this let’s consider List<T>.Find Method which accepts a Predicate.

Untitled
Predicate
In here it’s a Predicate of type Employee. So let’s create a method which accepts a Employee and check whether he/she is born in “1986”. If yes it will return true or else false.
static bool BornInNinteenEightySix(Employee emp)
{
    return emp.Birthday.Year == 1986;
}
Now I am creating a Predicate pointing to above method.
Predicate<Employee> predicate = new Predicate<Employee>(BornInNinteenEightySix); 

Console.WriteLine(employees.Find(predicate).FirstName);
Again with the use of Lambda Expressions, I can simplify the code.
Console.WriteLine(employees.Find(e => e.Birthday.Year == 1986).FirstName);

Func Vs. Predicate<T>

Now you must be wondering what is the difference between Func and Predicate. Basically those are the same, but there is a one significant difference.

Predicate can only be used point to methods which will return bool. If the pointing method returning something other than a bool value, you can’t use predict. For that, you can use Func. Let’s take a look at following method.
static string MyMethod(int i)
{
    return "You entered: " + i;
}
The method accepts a integer value and returns a string. I can create the following Func and use it to call the above method.
Func<int, string> myFunc = new Func<int, string>(MyMethod); 

Console.WriteLine(myFunc(3));
This will compile and print the desired output. But if you try to create a Predicate for this, you can’t.

I am uploading the sample to my SkyDrive. Do play around!.


Happy Coding.

Regards,
Jaliya

Tuesday, December 10, 2013

INotifyPropertyChanged Without Hardcoding the Property Name

If you are doing WPF or Silverlight using MVVM pattern, I am pretty sure your ViewModel is implementing INotifyPropertyChanged. Basically what INotifyPropertyChanged does is it notifies it’s clients when the value of a property (which a client is listening in) has changed.

Let’s go by an example. I have created a very simple WPF Aplictaion and I have the following Employee View Model which implements INotifyPropertyChanged. There are two properties which are the FirstName and the LastName which raises NotifyPropertyChanged() when values of the properties are changed.
public class EmployeeViewModel:INotifyPropertyChanged
{
   private string firstName;
   public string FirstName
   {
       get
       {
           return firstName;
       }
       set
       {
           firstName = value;
           NotifyPropertyChanged("FirstName");
       }
   }
 
   private string lastName;
   public string LastName
   {
       get
       {
           return lastName;
       }
       set
       {
           lastName = value;
           NotifyPropertyChanged("LastName");
       }
   } 

   public event PropertyChangedEventHandler PropertyChanged;
   private void NotifyPropertyChanged(string propertyName)
   {
       if (PropertyChanged != null)
       {
           PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
       }
   }
}
As you can see here, in the Setter of every property I am calling NotifyPropertyChanged passing the property name hard coded. And this is the part where my code looks ugly and there were hundreds of times I wanted to stop property name from hard coding. But for now lets keep it going this way. 

In my MainWindow.xaml I have following Stack Panel. I have two text boxes which are bound to FirstName and LastName properties of EmployeeViewModel. I have a button which will trigger a value change in the FirstName and LastName properties.
<StackPanel>
    <TextBox Text="{Binding FirstName}"></TextBox>
    <TextBox Text="{Binding LastName}"></TextBox>
    <Button Content="Button" Click="Button_Click"/>
</StackPanel>
In the MainWindow.xaml.cs I have the following code. I am setting up the current DataContext to EmployeeViewModel.
public partial class MainWindow : Window
{
    EmployeeViewModel employee = new EmployeeViewModel()
    {
        FirstName = "Jaliya",
        LastName = "Udagedara"
    }; 

    public MainWindow()
    {
        InitializeComponent();
        DataContext = employee;
    }
 
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        employee.FirstName = "John";
        employee.LastName = "Smith";
    }
}
If I run this simple application I am getting the expected result. Which is initially text boxes will be filled with values “Jaliya” and “Udagedara”. Once I click on the button property values will be changed to "John" and "Smith" and will be reflected in the text boxes. To make this happen in my EmployeeViewModel, in the property Setters I have hardcoded property names. So when ever the property values get changed, they will say "hey, I am FirstName property and my value just got changed!".  My requirement now is, the property should not specifically pass it's property name when it raises NotifyPropertyChanged().

With the C# 5 or with .NET Framework 4.5 and above there is a nice feature which comes handy in these kind of scenartios. You can use Caller Information feature which will provide Caller Info attributes and using these you can obtain information about the caller to a method. So let me modify the code above as follows.
public class EmployeeViewModel:INotifyPropertyChanged
{
    private string firstName;
    public string FirstName
    {
        get
        {
            return firstName;
        }
        set
        {
            firstName = value;
            NotifyPropertyChanged();
        }
    }
 
    private string lastName;
    public string LastName
    {
        get
        {
            return lastName;
        }
        set
        {
            lastName = value;
            NotifyPropertyChanged();
        }
    }
 
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
If you can see here, I haven’t hard coded the Property Name when raising NotifyPropertyChanged() method. The compiler will fill in the information for me. If I debug and check the value of variable "propertyName", I can see the name of the property which is triggering the NotifyPropertyChanged().

Hope this helps. Please find the sample project in my SkyDrive.


Happy Coding.

Regards,
Jaliya