Thursday, April 17, 2014

Deadlock and Livelock

Deadlock: Deadlock is a situation when two processes, each having a lock on one resource and attempt to acquire a lock on the other's resource. In this case, each process would have to wait indefinitely until one of them releases the lock on the holding resource.
Livelock: Livelock is a situation, where in a request for an exclusive lock is repeatedly denied because of series of overlapping shared locks keeps interfering. A livelock also occurs when read transactions monopolize a resource(file/page/memory location), forcing a write transaction to wait indefinitely.

Wednesday, April 9, 2014

Controlling Degree of Concurrent Execution in Parallel Loops

Having multi-core machine, one can get the benefit of Parallelism for long-running and blocking tasks. I hope most of you might have used Parallel. For, Parallel. Foreach and TPL several times. Generally parallelism is used to get the benefits of all the available cores on the machine that commonly leads to the shortest execution time for any task.
  1. Did you ever thought about what can be the possible demerits of using all the available cores for just a single application?
  2. Is it really required to use all the available cores of your machine for a single application? Can't we use only a few of the cores?
  3. Is there any way to restrict these parallel loops in terms of cores?
The answer of all the preceding questions is YES.

But why should we bother about how many cores are participating in execution?
Well, there can be several reasons behind this. The foremost reason that I feel is, when a single time consuming application/task is running on all the available cores utilizing most of the processing power, what will happen to other applications running on the same machine. Those other applications might hang and may even encounter performance issues, which is not at all acceptable. Isn't it?

Another reason can be, if your long running process is executing on the server, then it is not a good idea to raise an unlimited number of requests at the same time, since it may lead to server timeout or may introduce a DoS attack. In layman words, your server may go down, which is again an unacceptable behavior. Isn't it?

Solution
All the preceding problems can be resolved by managing the available cores explicitly, especially when dealing with parallel loops. Instead of using all the cores for a single long running process, use only a few of them. So, the other cores can be used by the rest of the applications.

Before proceeding, let's have a look at a small code snippet.

Parallel.For(1, 10, i =>
{
    Debug.WriteLine("{0} is executed on Task {1}", i, Task.CurrentId);
});

If you run the code above multiple times, definitely your output may vary. Let's have a look at a few outputs:

Output on first run
3 is executed on Task 2
7 is executed on Task 4
4 is executed on Task 2
6 is executed on Task 2
1 is executed on Task 1
9 is executed on Task 5
8 is executed on Task 4
2 is executed on Task 2
5 is executed on Task 3

Output on second run
9 is executed on Task 5
5 is executed on Task 3
7 is executed on Task 4
3 is executed on Task 2
1 is executed on Task 1
6 is executed on Task 3
2 is executed on Task 5
8 is executed on Task 4
4 is executed on Task 2

How to control this degree of concurrency?
There is already a property available in C#. So, by using this property one can restrict the number of concurrent tasks created during the execution of parallel loops. By assigning some value to MaxDegreeOfParallelism, we can restrict the degree of this concurrency and can restrict the number of processor cores to be used by our loops. The default value of this property is -1, which means there is no restriction on concurrently running operations. Let's quickly jump to the code:

ParallelOptions po = new ParallelOptions();
po.MaxDegreeOfParallelism = 2;
Parallel.For(1, 10, po, i =>
{
    Debug.WriteLine("{0} is executed on Task {1}", i, Task.CurrentId);
});

In code above, I am setting MaxDegreeOfParallelism to 2, which means that only a maximum of 2 tasks will be created, that will in turn use fewer cores, which is 2 here. On executing the code above, you will get the following output:

Output on first run
5 is executed on Task 2
6 is executed on Task 2
7 is executed on Task 2
8 is executed on Task 2
9 is executed on Task 2
2 is executed on Task 2
3 is executed on Task 2
4 is executed on Task 2
1 is executed on Task 1

Output on second run
1 is executed on Task 2
2 is executed on Task 2
5 is executed on Task 1
6 is executed on Task 1
3 is executed on Task 2
7 is executed on Task 1
4 is executed on Task 2
9 is executed on Task 2
8 is executed on Task 1

Whatever number of times you execute your code above, the number of concurrent tasks will never go above 2.

The same concept can be applied for a parallel Foreach loop also.

When concurrency needs to be controlled ?
It is not necessary that you always need to tweak this setting. It fully varies from scenario to scenario. Please use it with caution. The most common scenarios for using this setting is:
  1. When a huge number of automatically created threads may lead to deadlock or livelock
  2. When you want your loop or algorithm to use only a limited number of cores. It is usually required when more than one time-consuming algorithm needs to be run simultaneously
Happy learning!!!
Hope you enjoyed concurrency.

Thursday, April 3, 2014

New features of Windows Phone 8.1

2nd April 2014, during the //BUILD 2014 conference Microsoft officially showcased the set of new features which will be coming as part of Windows Phone 8.1. In my this post, I am touching those features.

1) Cortana - new personal assistant: 
Cortana is voice-based virtual assistant provided by Microsoft. It is similar to Apple’s ‘Siri’ and is powered by Bing. It can do everything that one would expect from any virtual assistant. Cortana offers advanced settings and preferences with more than the default voice commands. One can talk with her and can also give her instructions to perform any operations behalf on you. Cortana is fully based on your search queries, she learns your interests, she learns about the most important people in your life. For example, you can instruct her “Cortana, call Shweta on Skype” and it will open Skype to call the person. Isn’t it interesting ?
You can also use Cortana to set reminders by saying “Cortana, remind me to go to parlor when I am in MG Road” and she will remind you whenever you are in MG Road.

2) Sensing capability:
  • Battery Power Sense – App will monitor which all apps are drawing more power and will turn them OFF when not in use
  • Data Sense – Detailed tracking of data can be done remotely based on time(a month, a week, etc)
  • Wi-Fi Sense – Wi-Fi can be auto enabled after certain duration of time. Another interesting thing is, Wi-Fi Sense app will automatically connect to nearby available free Wi-Fi hotspot and will accept the terms of use automatically for us.

3) Action Center for notifications:
Action center will show notifications related to calls, messages, emails, etc. It will also provide quick settings to Flight Mode, Wi-Fi, Bluetooth and Rotation Lock options. Interesting thing is these quick access options are customizable.

4) Internet Explorer 11:
IE11 will be able to save and remember the passwords for websites, allows uploading of files, YouTube player including HTML5 video support and many more…

5) Enhanced Calendar:
It will allow you to synchronized Google calendar in your WP, supports week view and also supports multiple calendars which will allow you to view all the invites in one place.

6) Enhanced Email feature:
In //BUILD 2014 conference, Nick showcases on how emails can be encrypted and signed before sending to anyone. This enhancement, also allows user to download images attached or associated with email.

7) VPN Support:
WP 8.1 has in-built VPN support with ability to auto-trigger VPN connectivity. One of the very useful part of this enhancement is, it allows to password protect office documents and also allows access to corporate resources which are behind the firewall. Isn’t it cool?

8) Additional features to Camera:
Photography experience is also changed by adding few features like quick access to clicked images and tweaking tools. One good addition is burst mode features for clicking continuous images

9) More minor changes:
  • New lock screen with multiple themes
  • Improvements in Music, video apps
  • Backup of app + game data to OneDrive
  • App filtration based on install date and usage
  • Option to update store apps automatically
  • Smart search
  • Silent as well as actionable notification for apps
  • Rebranding of SkyDrive to OneDrive
  • Double tap to Unlock and Power off
  • Separate volume controls ringtones and music
  • Back button is modified to suspend app, instead of closing the app
  • Support for in-call speech commands
  • Chkdsk for testing SD cards health
  • Miracast support

Hope all of you will enjoy these new features.

Wednesday, April 2, 2014

Cursor Position on Enter key

Recently, one of my followers requested for a code snippet to implement the ENTER key press. The requirement was to move the cursor on the next WPF UI element, whenever the ENTER key is pressed.

Implementation of the above requirement is straight forward, if one has the knowledge of InputBindings and Command. Using these two, MoveFocus method of currently focused element, can be called, as shown in the mentioned below code snippet:
















Hope it will help you.

Sunday, March 30, 2014

Restoring Nuget packages in less annoying way

Hope most of you are aware of Nuget packages. It is a way to get 3rd party libraries into your project. Nuget also makes developer's life easier by checking for updates for all the available libraries.

Apart from this Nuget also provides package restoration option, which is disabled by default. Another annoying thing about restoration is, it is very very slow. So, it means that until your restoration is complete, you can not do anything.

What is the solution or workaround of this slow restoration of Nuget package ?

Well, one workaround can be instead of restoring packages from Visual Studio, why can't we do it outside of Visual Studio. Interesting, isn't it ???

A Very simple and straight forward command to do this is:

NuGet.exe restore [SolutionFile] –PackagesDirectory [PackagesDirectory]

Tuesday, March 18, 2014

Congratulations! You have received MVP award

Hey folks,
I have something very exciting to share with you all. Today morning, I received a mail stating "Congratulations!  You have received MVP award”. At first I didn’t believed my eyes, but after reading a mail, finally I got a feel that I really won. Actually it was surprised for me too !!!

I’m really proud that someone noticed my technical skills and what I do for community. Whenever I meet or look at other MVPs, I always think, “Wow, these guys are brilliant! Simply awesome…I wish I could…”

But finally it happened. I’m honored to be a part of the C# community. It’s a privilege.

MVP: MVP is an annual award given by C# corner to its community leaders who actively share their technical skills and excellent knowledge. This award recognizes exceptional technical community leaders who have deep understanding on some technology and how they can contribute to communities so that people around them can make the most out of them.Every day, around the world, MVP Award recipients contribute to online technical communities in a range of ways, including providing helpful answers, online discussions, translating online resources into local languages and serving as moderators.


Today, millions of people gain valuable information through C# corner online forums, a number which is steadily growing. C# corner community helps in closely knitting the worldwide spread IT community, support each other and churn out revolutionary ideas. It helps the IT community realize the strategy to explore and widen their wing span. This time C# corner is having its largest annual conference in North India (Noida) on 11th April (http://www.c-sharpcorner.com/conference2014/). See you there ;)

Sunday, March 16, 2014

Customizing debugging session - Part II

Continuing to my previous article on 'Customizing debugging session', we can further control on how properties and fields appear in our debugger window. Based on our debugging requirement, we can show and hide properties in our debugging session using one of the useful attribute named DebuggerBrowsableAttribute.

Let’s go ahead and see debug window for one of the code snippet:






In above image you will notice that by default list of Awards is not in expanded form. In order to view the values of awards, one needs to expand that forcibly either by hovering the mouse or by click on the plus symbol, which will result in below screenshot:






How to hide unwanted properties during debugging session? What if a developer is not interested in viewing employee’s branch?

Well, that unwanted property can be made hidden by using DebuggerBrowsableState as Never as shown below:












Now let’s run the code and check, whether it is hidden:






As expected, you land up with above debugger window with Branch property hidden. Great !!! Let's move to next question...

Is there any way to expand list of awards automatically in my debugger window?
Yes, we can. Using the DebuggerBrowsableState as RootHidden as shown below:





On debugging the application, you will notice that list of awards are in expanded state now as below:






Hope you enjoyed playing with your favorite debugger window.

Wednesday, March 12, 2014

Customizing debugging session - Part I

I hope, being a developer everyone needs to debug their code at least once a day even if it is a very small snippet. Frankly speaking, sometimes it becomes very frustrating when we are looking for a value of particular property or let’s say very few properties of a huge object and it gets TIMEOUT. Uhhh !!!

This time, we feel like there should be some easy way to navigate to that particular property instead of going to the object and clicking on plus symbol to reach the required property. Well, let’s understand it via code:

Aim: I have an Employee class with two members as EmployeeName and BranchName. I want to know the name and branch of an Employee during my debugging session. So, I start debugging and lend up on below screen:







Now in order to view the required details, I need to expand the employee object as shown in below screenshot:







Now first question is, is there any way to display customized message in debugger window? Answer would be YES. One simple override method will do this job for us.

Let’s go ahead and override the ToString method as shown below:












Now launch the application and you will be able to view your text during debugging as shown below:







Point to understand here is, by default Visual Studio uses ToString method in the debugger. Please note, overriding the method will only display the message and it won’t affect the values of your employee object. In other words, on click on plus symbol in debugger window, you will still be able to view employee’s branch and name.

Well, it’s time to move for next question which I feel is very important concept.
Second question is, is there any way to display value of required property instead of customized message? Again answer is a big YES. A simple attribute named DebuggerDisplay will rescue you.

Let’s quickly jump on the code to check, how to use this attribute:






As you can see that the attribute can be applied to class level and takes a string as a parameter and inside the string, one can reference the member variables of the class using curly braces. Now time to see, what debugger will show us:






Isn’t it a cool feature? Hope you will use it :)

One can use this DebuggerDisplay attribute with classes, enums, delegates, structs, fields, properties as well as with assemblies.

When to use this DebuggerDisplay attribute?
One certainly can’t use it all the time due to its maintenance overhead. I would recommend it to be used at class level and can be at properties level, if your properties are complex and less self-explanatory. Enjoy debugging!!!



Saturday, March 8, 2014

FallbackValue and TargetNullValue

One of the ability of binding in WPF is the ability to support Fallback values. Fallback values are used when a binding comes up with an un-appropriate value which in turn can't be set on binding target. There are 2 types of Fallback values:

      TargetNullValue:
    As its name communicate itself that when a source object’s property is null, then what is the alternate value you want to set for the target. So, whatever value is set for TargetNullValue, it will be set for target. Pretty simple, isn't it ?

2   FallbackValue
    This is used when a binding cannot come up with a value at all, based on the the data source and the path. Or in other words, FallbackValue is used when the property binded with source is not at all available. In that case, value supplied to FallbackValue will be considered at the target end.

Getting into the code: 
Now, let’s jump on to the code on how to use both of these. Here aim is to bind the given text box with EmployeeName property.

My code behind class contain just the basic code to create a property for employee name, so that we can bind it with TextBox. Here goes the code:











  
And my XAML file contains below code:









Till this point, we haven’t done anything extra. It’s pretty simple and self-explanatory code. Let’s go ahead and quickly change the code a bit.

Demonstration of TargetNullValue:
As I mentioned earlier, TargetNullValue comes into picture only when your source object is null. To make source object null, let’s go ahead and do the minor changes into the code, as:


     






Now, next step is to set the value for TextBox, which will be displayed if source object (in our case source object is EmployeeName) is null. Let’s modify XAML file for this:




Now, when you will run the application, you will find the TargetNullValue is set for the TextBox as:






Demonstration of FallbackValue: 
This FallbackValue will play its role when binding is not able to resolve the source. So, for this missing source, one can set the default value for the target. Let’s have a look at the code:






In above code, instead of binding TextBox to EmployeeName, I am binding it to EmployeeNames which is not the correct property as no such property is defined with this name. Hence my FallbackValue will come into picture and will give us the below output:






Hope this article was useful :)


Wednesday, March 5, 2014

Gotcha with StringFormat

Hope most of you have used StringFormat property on your binding to render the formatted value on the user interface. But are you aware about one of its secret. Well before revealing that secret, let’s have a look at how StringFormat works with binding.

Scenario problem: I am taking an example scenario, in which my text box will display amount till three decimals. 

Now there are multiple ways to achieve this. One way can be by using Converters, another way can be by using StringFormat along with TextBox binding. Perhaps there can be more ways apart from these two ;)

In below sample I am going to take StringFormat trick to achieve this and code to perform this operation is very straight forward as:

<TextBox Text="{Binding Amount,StringFormat=f3}" />

With above code, whenever you will lost focus from your TextBox, given amount will be displayed as three decimal points. Till here everything is perfect as expected BUT with one downsize.

Important point on StringFormat: 
What one sees on the screen is not the actual value that will be stored in the storage and can be different from the underlined value. But if this is really a requirement on what we want to show to the user then it’s up to developer to manage such inconsistencies.

Gotcha with StringFormat:
Now time came to know about that GOTCHA. If you want to add UpdateSourceTrigger property = PropertyChanged along with your StringFormat, then guess what will happen???

Code:
<TextBox  Text="{Binding Amount, UpdateSourceTrigger=PropertyChanged, StringFormat=f3}"/>

To understand this issue, let’s go step by step.
Step 1: Run the application and you will get below output.









Step 2: Enter value in the text box as 35.45. You will land up with below screen:









Explanation: Please note, you have applied UpdateSourceTrigger=PropertyChanged. So, as soon as you will hit a keyboard key, immediately StringFormat will be called due to change in target property and sets the underlined source property. Our source property raises a PropertyChanged event that forces the binding to re-bind and re-render based on the StringFormat. 

Problem occurs with fast input scenarios as shown in above screenshot and you will end up with RED rectangle.
Reason: After each key stroke, it is re-rendering the value of a given text box.

Step 3: Click on Save button in order to fire the loose focus from text box as shown below:









Explanation: As per the StringFormat property, given text box should be able to change the value to required precession. But it doesn’t happen. 
Reason: Due to UpdateSourceTrigger=PropertyChanged

One should avoid using UpdateSourceTrigger=PropertyChanged with StringFormat, due to this re-rendering issue.