Thursday, April 24, 2014

EF warning while using Database first approach

Error 6002: The table/view 'AdventureWorks.dbo.BuildVersion' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.

Explanation: The above warning is generated when you use Database first approach for Entity Framework model creation. Such warning appears due to entity key. Every Entity needs to have an entity key and when EF creates an entities, what it does is, it tries to find an primary key from the database and creates an entity key from that. 

But it may be the case that few of the database objects doesn't have primary key defined. In that case, EF tries to infer a key based on your view or table's columns. So, here it becomes necessary to have at lease a non-null column in your database object. 

It's just a warning, so nothing harmful here. But still if you need a solution to get rid of this warning, then it is posted by Hilmi Aric.

Monday, April 21, 2014

Visual Studio Extension for Installer Templates

Finally Installer Projects templates are back with Visual Studio. Hope most of you are aware that few years back, Microsoft removed the templates for installer projects from Visual Studio and we all were obliged to use InstallShield. 

Till Visual Studio 2010, these templates were shipped along with VS but post releases were not having these templates. But user voice and vocal feedbacks made this possible and now these templates are again part of Visual Studio 2013 and will continue to be the part in all the Visual studio’s future versions.

This Extension can be downloaded either from Visual StudioGallery or by using ‘Extensions and Updates’ dialog’s online section with a search string as ‘Visual Studio Installer Projects Extension’.

Important point to mention here is, Visual Studio will still provide the in-box solution for InstallShield limited edition. As of now, this update is part of preview release version;)

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?

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 ( 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!!!