Tuesday, February 11, 2014

Named parameters revisited in .Net 4.5

As most of you are aware that there are lot of language and compiler changes has happened with recent release of .Net, but all the issues will not arise until and unless you are recompiling your code. Once you recompile your code, these changes will be introduced regardless of which framework you target.

Today I am writing about one of these breaking changes happened in .Net 4.5. 
With earlier framework, named and optional parameter concept was introduced and unfortunately it was implemented incorrectly. In essence, there was a issue with the evaluation order of named parameter and will occur only when you are using methods as an argument. 

Let's have a look at this snippet taken from MSDN:

Expected output: A C B
Output in Visual Studio 2010: C B A
Output in Visual Studio 2012/2013: A C B

Hope by this time, you are convinced about this incorrectness.  Please note, here issue is with named parameters and has nothing to do with optional parameters. This issue is with the Visual Studio 2010 compiler which is giving the unexpected results.

Reason: Incorrect results are because named parameters are evaluated before the positional arguments. For both named and positional evaluation must be from left to right. This was the bug in VS 2010 and is addressed in VS 2012.

This is unlikely to cause a problem in your code until and unless you are calling methods in your argument list.
Suggestion: Avoid calling methods in argument list if order of execution is important for your application.

Note: ref and out parameters may also suffer from side effects due to this change.

Saturday, February 8, 2014

INotifyPropertyChanged revisited with .Net Framework 4.5

Prior to this post, I have already discussed few ways of handling INotifyPropertyChanged interface. Now you might be thinking what's next ?

Well, today I'll talk about much better and cleaner way of handling this interface, which is type-safe as well as less error prone. Till now, as a common practice, we were passing a property name as a parameter of our RaisedPropertyChanged method, which unfortunately has some demerits. 
Let's say, what if user changed the name of the property and forgot to change the parameter passed inside RaisedPropertyChanged method. Now you might say that we can get rid of this by using Reflection. Even I agree with that but again it comes with an additional associated cost. So, what's the solution now???

Enough of worries, this issue has been addressed in .Net 4.5, in which developer can get rid of this parameter passing approach. Impressed?

An attribute titled CallerMemberName relieves us from all the worries because now this attribute will retrieve method and property name for us. Let's have a look at the code now:

You will notice that the attribute is applied with the parameters supplied for RaisedPropertyChanged method. So, now the implementation of our property will be lot simpler as:

Now user is not forced to pass parameter to this RaisedPropertyChanged ,method. Hope you enjoyed learning this new feature.

Saturday, February 1, 2014

C# 6.0 with Visual Studio 2014

Today while surfing internet, I came across a very interesting interview snippet from Anders Hejlsberg and Charles Torre, in which they talked about the future version of C#, which will be 6.0. I hope most of you are aware that .Net version shipped with Visual Studio 2013 was the minor release with numbers as 4.5.1, which was just an upgrade of version 4.5. It is expected that all the major changes will be part of .Net 5.0 which will be shipped with Visual Studio 2014.

Another nice thing which came out is, C# 6.0 will be based on the new compiler Roslyn, which is written in C# itself rather than C++.

We can also expect some of the very cool features of C# 6.0 as:

  • Primary Constructors
  • Readonly auto properties
  • Static type using statements
  • Property expressions
  • Method expressions
  • Params for enumerables
  • Monadic null checking
  • Constructor type parameter inference
  • Inline declarations for out params

All the probable features of C# 6.0 will make life of developers bit more easier. The glimpse of all these features were provided at New Developers Conference recently held in London.

Well, so keep waiting till everything become reality ;)


Wednesday, January 29, 2014

Microsoft soon to rename SkyDrive to OneDrive

Most of us might be aware that Microsoft is going to rename it's one of the cloud storage service SkyDrive soon due to disputes with one of the UK firm named British Sky Broadcasting Group. You can find this official announcement at blog by Ryan Gavin.

Saturday, January 25, 2014

Safest way to use EventHandlers in multi-threaded environment

Nowadays MVVM is one of the most common architectural structure and hope most of us working on WPF, Silverlight, Windows Phone or Windows Store apps might have come across this. When talking about MVVM, the first thing which strikes in mind is INotifyPropertyChanged interface. The usual and most common practice of implementing INotifyPropertyChanged is:

public class ViewModelBase : INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        protected void RaisePropertyChanged(string prop)
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));

What do you think about the above code? In first sight, it looks correct, but is it really perfect or thread safe? Well, here answer is NO. One very minor thing is missing in above code which can lead your application to crash in multi-threaded environment.

If you will inspect the above snippet closely, you will notice that the way event is handled here is the culprit. In multi-threaded scenarios, above code can create lot of chaos. Well, enough of suspense. To figure out this hidden culprit, let's take an easy and small snippet.

if (PropertyChanged != null)
         PropertyChanged(this, null);

Now, dig the code line-by-line. In above 2 line snippet:
  • First line executes on thread #1: if(PropertyChanged ! = null) 
  • At this point, PropertyChanged has an event attached to it. So, first line will return true.
  • Meanwhile, on thread #2, the object that has it's event handler attached to PropertyChanged removes it from PropertyChanged.
  • But thread #1 already did it's null check, so it moves on to next statement.
  • On thread #1, next line executes: PropertyChanged(this, null);
  • But the PropertyChanged event no longer has any associated event handlers attached to it, so it throws a NullReferenceException
Hope by this time, you understood the issue with above sort of code. Now question is, how to resolve this issue???

No worries. It's very simple and can be resolved by introducing a temporary variable as shown below:

EventHandler temporaryVariable = PropertyChanged;
if (temporaryVariable != null)
           temporaryVariable(this, null);

After doing the above changes, once the null check is happened, instead of calling PropertyChanged(this, null), thread #1 will call temporaryVariable(this, null); The temporaryVariable is keeping track of all the event handlers that were attached to PropertyChanged, so that statement won't throw a NullReferenceException.

In computer science terms, above problem is called Race condition. Hope you enjoyed this small and useful tip.

Wednesday, January 22, 2014

Dynamically selecting DataTemplate for WPF ListView - Way 2

In continuation to my previous article titled 'Dynamically selecting DataTemplate for WPF ListView', in this article, I am discussing about the alternative way to achieve the same goal. But here, to make the example simple, I am going to display only Employee names as shown below:

Now this to achieve this, I am going to inherit MarkupExtension class provided by Microsoft. This class will give me the DataTemplate. If you will explore further, you will came to know that this MarkupExtension class has only one method named as ProvideValue, which will return me the appropriate template based on the supplied value. 

Before inheriting MarkupExtension, I created a class named MyDataTemplateDictionary, which will inherit Dictionary<object, DataTemplate>. Please note, here key will be my DataTemplate name and value will be the DataTemplate. Below is the code depicting the same:

Next comes is the class inheriting MarkupExtension. As there is nothing much to explain in this code, I'm directly showing it:

And finally the class inheriting DataTemplateSelector, which is exactly the same code as shown in previous post:

And last but not the least, our XAML:

And we are done. Isn't it the cleaner approach???

Tuesday, January 21, 2014

Dynamically selecting DataTemplate for WPF ListView - Way 1

Recently I get a chance to work on a project in which requirement was to select different different types of data templates based on the data. I faced bit difficulty, but afterwards I was manage to get it work.

Let's have a look at the scenario first: Inside a WPF ListView, there are two GridViewColumns for storing Name and Age. Now requirement is to highlight the name of the person based on certain age criteria. If age is below 25, then name should be highlighted as red else it should be in green color, with desired background. I know there are ways to implement this using the concept of triggers, but I personally refrain from using triggers due to performance fall back.

So, what else ???

The option left was dynamically selecting data templates. In this post I am going to write about the simplest approach and later on I'll do the same thing using Dictionary. Well, let's begin with our code.

First of all, I created a class named Employee and added some data which will be displayed on UI. Code to perform this is as:

Next thing, I did is, defined the two DataTemplate in XAML as:

Once the data templates are defined, next task is to figure out the way on how to select the data templates dynamically. So, to perform this task, Microsoft provide us with the class called DataTemplateSelector.  Using this class, one can select the data templates based on the business requirement and here is the code:

Next task is to bind this newly created class named MyTemplateSelector with out XAML. So, in order to perform this task, I created a ResourceDictionary and kept both the data templates inside it as:

Till here we are almost done. The only thing pending is binding our ListView control to collection and setting the cell template, which can be done as:

Once everything is in place, we will get the desired output:

All the above thing can be done by inheriting MarkupExtension class also. I covered that in my next post here.

Sunday, January 12, 2014

Better way to play sound file on WPF button click

Recently I was working on a XAML based application, in which my requirement was to play a sound (.wav file) whenever a given button is clicked. So, to achieve this, I wrote a below snippet:

My above snippet worked but at the same time, I feel a noticeable delay in beep sound and that make me analyze further and write a blog post :)

Now question is, why there is delay between button click and sound ???
Well, there is a simple concept behind it, which I missed while implementing above requirement :(

Reason is, the event hierarchy. 

Most of us might be aware that Click is a bubbling event, which means event will be fired from the control who initiated it. So, in our case, whenever button is clicked, it bubbles from button to window. And that's the reason, click event handler is executing before the window event is triggered, which is ultimately leading to delay.

Now, how to handle this???

Method 1:
Then I thought to write a preview event, which will be fired before my button click and came out with this below code:

In the above snippet, I am using VisualTreeHelper to verify is click event is occurred on button or not. Don't you think, it is bit dreadful? If it seems good, then you can go ahead with this approach else I got one more idea to implement this using ResourceDictionary.

Method 2:
Let's use Styles and EventSetter to achieve the same goal. Here I am going to define my style in a ResourceDictionary, now of course I don't have instance that I could wire my event to. For this, I created a code-behind file for ResourceDictionary, which will appear as a child of my XAML file and will contain the below code:

Now only thing pending is merging the ResourceDictionary with our MainWindow, which can be done as:

For me, this approach looks better. Hope you enjoyed reading!!!

Saturday, January 4, 2014

DataTemplating Overview

DataTemplate is a very powerful concept which allows you to provide a visualization for your objects in your application. DataTemplate objects are very useful specially dealing with collections. If you bind your collection with any of the ItemsControl, say ListBox then by using a DateTemplate one can change the appearance of data objects very easily. Well, now let's create a DataTemplate quickly.

Let's start by creating a class called Employee:

FirstName and Age will be our business objects that will reside in our application. Now we will go ahead and show the value of these objects on screen in a WPF application. For that our XAML will look like:

Now looking at the code-behind:

In code-behind, we have set the values for FirstName and Age with DataContext of main window. So, that XAML can bind to these values via EmployeeDetail property. At this point of time, if you will run the application, you will see:

By above image you can see that the default implementation of DataTemplate in WPF has simply put the string on my window, where TemplatingOverview is my namespace. So, to make it work in order to show proper values, let's go ahead and override ToString on Employee object, something like this:

In above snippet we are saying that please provide us the string with given format. Now, if you will go ahead and run this again you will find that our DataTemplate is changed and now it is using our overriden ToString.

Till here, I showed that what will happen if you will not provide your own DataTemplate. Now instead of writing overriden method, same thing can be performed fully in XAML as:

In above snippet, we have created a DataTemplate on the ContentControl and inside this DataTemplate, one can do any styling and can create any number of visual elements. Later on, these visual elements can be bind to any public property of Employee object. Please note, the Datacontext for this DataTemplate will be EmployeeDetail. Now, if you will run the app, still you can see the value of Employee object.

Sharing DataTemplate
Now in order to share this DataTemplate between multiple ContentControls, one has to make this as a part of resource. Let's have a look at the complete code to get clear idea:

Hope you enjoyed reading. In Next article, I'll be writing about DataTemplateSelector.

Thursday, January 2, 2014

Validating a WPF textbox to accept only negative decimal numbers

Recently working on one of the project, I came across an requirement of validating a TextBox in which Textbox should allow numbers only between range -999 and 0.

If you will surf on internet, you will perhaps find many solutions to this problem in which developers create their own versions of TextBox either by creating a Custom/User controls or by inheriting it. But problem of this approach is - you would need to replace your TextBox definitions with your newly created TextBox. Sometimes this solution can be opted but sometimes it is not feasible to do so.

This article describes on how to enhance existing WPF TextBox to make it happen.So, the approach I am proposing here doesn't require the replacement of existing TextBox control. Whilst it uses the very basic concept of Events. Well, enough of theory. Let's move on to coding part:

XAML code:

Code-Behind code:

Hope you like this clean approach.