Wednesday, May 24, 2017

Possible Multiple Enumeration of IEnumerable

If you have worked with IEnumerable and using ReSharper, then you may land up into this warning, "Possible Multiple Enumeration of IEnumerable". So, what this warning is all about?
Well, before proceeding further, let’s see how we can store something into IEnumerable object .
IEnumerable items = GetAllItems()
So, above code itself speaks that items is a variable of type IEnumerable which will hold some values/objects we can iterate through.
Now here lies the performance hit, which is also indicated in the form of ReSharper warning. This performance hit may not be significant for a small number of items. But this can be noticed while dealing with a huge number of items.
Reason behind this is, whenever you are iterating through items collection, GetAllItems method will be called for the same number of times.
Solution: It is always good to materialized the result in a list or array like below:
IEnumerable items = GetAllItems().ToList()

Once you are done with mentioned code changes, you will notice that above warning doesn't exist any more.
Hope you like this small post.

Tuesday, May 16, 2017

.Net Architecture Guidance announced

Few days back, Microsoft announced the draft version of the .NET architecture guidance. This guidance is the combined effort of the Visual Studio team and the Microsoft Developer Division. As of today, it covers only 4 areas:
  • ASP.NET Web applications
  • Azure Cloud Deployment
  • Xamarin Mobile Applications
  • MicroServices and Docker
You can find more about this guidance on Microsoft’s official page.

Saturday, March 25, 2017

Why normal .NET exception handling doesn't work in WCF?

Errors and exceptions are part of our programming life and WCF is no different. So, when we get errors in WCF, we would like to propagate those errors to our WCF client so that they can accordingly take actions. In order to demonstrate this, let’s go through the code of a simple service:
       public int Add(int number1, int number2)
            return number1 + number2;

        public double Divide(int number1, int number2)
            return number1 / number2;
Both the above methods will perform some calculation and return the result to the client. Let’s say, now for some reason someone sent 2nd parameter of Divide method as 0. 

What will happen? Definitely code will throw an error or say DivideByZero exception. Isn’t it?

Know how to handle this error? Most of the developers will simply decorate Divide method with Try-catch block and throw the exception, similar to our normal .NET exception handling mechanism as shown in below code:
public double Divide(int number1, int number2)
                return number1 / number2;
            catch (DivideByZeroException exception)
                throw exception;
This normal exception handling mechanism will not work in WCF world. Now before discussing on WHY, let’s quickly see what is passed from the client:
MathClient math = new MathClient();
                math.Divide(10, 0);
            catch (Exception exception)

Now if we will run this client application, we will land upon such error message:

Now by looking at the error message, we cannot figure out what went wrong as it only mentions it is an internal error :(

Now coming back to the same question, why is this happening like this?

Well, reason behind this is the message format being used by WCF. WCF uses, XML or XML SOAP to communicate with clients. So, even if any exception is raised, it has to be in XML format. Hence normal .NET exception handling mechanism doesn’t work here because the error is not sent to clients in the form of XML.

So, the solution here is Fault Exceptions and rather than throwing a normal .NET exception, we have to throw a fault exception as shown below:
public double Divide(int number1, int number2)
                return number1 / number2;
            catch (DivideByZeroException exception)
                throw new FaultException(exception.Message);

Now re-run our application and we will be able to see proper error message.

On a summary note, we cannot use normal .NET exceptions to propagate exceptions to the client but same can be used within WCF service.

Hope you like this small but very useful tip. Happy learning!

Friday, February 17, 2017

Which WCF template to be used?

Recently, one of my colleague asked me, which WCF template should I use to create a service? For experienced people, it may be a silly question, but it is one of the common question among beginners, who just entered into the world of services. That’s the motivation who made me write this small post.

Well, let’s first have a look at what all templates are available in Visual Studio 2015 for WCF: 

The developer can choose any of the above templates as per project need. Let’s go through them one-by-one.

WCF Service Library: This template is nothing but a simple service library which uses App.config as its configuration file.

WCF Service Application: This template will create a web site which in turn will be hosting a service in it. Here Web.Config will be used to serve configuration settings.

WCF Workflow Service Application: This template is useful when you want your workflow to be accessed as a web service.

Syndication service Library: This template is useful when you want to expose RSS as a web service.

Hope now you are comfortable on which template to be chosen.Happy learning!

Monday, January 2, 2017

DependencyObject in ViewModelBase - Good or Bad?

First of all, a very-very Happy New Year to all my readers. If you are reading this post, then I’m assuming that you have a working experience of WPF using MVVM. 
Don’t worry, I’m not going to re-write a huge post on what MVVM is and where to use it? This blog is very small which talks about one of the best practices any developer implementing MVVM should follow.

Well, let me provide you the context first. Last week I was going through one of my colleagues’ code and noticed few interesting things in his ViewModelBase class:
  • It was holding few Dependency properties 
  • It was inheriting DependencyObject 

How it sounds to you? Good or … ? 
Of course, that is not at all a good practice as ViewModelBase is the base class for all the ViewModels and is not supposed to contain such code. Well, this is not the only reason. 

There are many other reasons which are making this implementation a BIG NO. 
1st Reason – A DependencyObject was never meant to be a Source of a binding, but rather it is a Target, which means its existence should be in the UI layer. So, if we are inheriting DependencyObject in ViewModelBase class, then we are not adding dependencies on view related objects.

2nd Reason – DependencyObject overrides and then seal two methods Equals and GetHashCode with a reason to prevent derived classes to define value equality for a DependencyObject as such sort of value equality will never be accurate due to value changing capabilities of DependencyObject and its dependency properties. Hence inheriting DependencyObject class in ViewModelBase will never let you override Equals and GetHashCode methods. Official link  

3rd Reason - Serialization – If you want to Serialize anything in VM, it’s not gonna happen because our Base class which is DependencyObject in our case is not Serializable. In other words, DependencyObject class is not marked as [Serializable]. So, the only solution left and can be used as a workaround is to implement ISerializable in ViewModelBase class which is not recommended solution here. 

4th Reason - CLR properties still needs INotifyPropertyChange implementation. 

5th Reason - Thread affinity – It says that an object created on one thread cannot be used by another. A DependencyObject has thread affinity means it can only be used on the thread that created it.

Hence never ever derive ViewModelBase class from DependencyObject. Enjoy learning!!!

Friday, December 30, 2016

Last blog post of 2016

This is my last blog of year 2016. I just want to take a minute to say thank you to all my readers who reads my blog. It’s prodigious erudition with you all.

I wish you all a very Happy New Year and a great beginning. Catch you all in next year with same zeal :) 

Tuesday, December 27, 2016

AccessKey not working on WPF ContentPresenter

Recently I received a query from one of my friends stating that access key is not working in his WPF project when he is using ContentPresenter. So, I thought to share a post on it as it may be helpful for other reader also. Before digging directly into the problem, first let’s see what happens when access key is set directly on the Content property of a WPF Button.

Below is my code for setting a Content on a Button:
        <Button Height="39" Width="100" Content="_Save"/>

If you will run your application with above snippet, you will notice that there is no underscore coming in front of word Save. But as soon as you press ALT key, underscore comes up. Which is an expected behavior :)
Now tweak the code a bit and instead of setting content directly on a button, do it on ContentPresenter as shown below:
        <Button Width="95" Height="34" Background="Orange">
                <ControlTemplate TargetType="Button">
                        <Rectangle Fill="{TemplateBinding Background}"/>
                        <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
Now, if you will run your application with above snippet, you will get an output in which underscore is coming at incorrect place, which is before S.

Question is how to get this underscore at proper location, below S?

No worries. A simple property RecognizesAccessKey does this for you.

  <Button Width="95" Height="34" Background="Orange">
        <ControlTemplate TargetType="Button">
            <Rectangle Fill="{TemplateBinding Background}"/> 
    <ContentPresenter RecognizesAccessKey="True" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>

And that's it, we are done. Now if you will run your application, you will see the underscore under S, which is the expected output.
Happy coding!!!

Friday, December 16, 2016

Can ASP.NET Core be chosen over ASP.NET MVC?

Nowadays one of the most popular question is ‘Can ASP.NET Core be chosen over ASP.NET MVC?’
So, to answer this question, let’s have a look at .NET architecture diagram: 

By looking at above diagram, one can easily see that .NET framework is used develop desktop Windows applications using WPF and Windows Forms and Web applications using ASP.NET MVC.

.NET Core supports UWP and ASP.NET Core libraries, in which UWP is used to create Windows 10 apps and ASP.NET Core is used to build Web applications for Windows/Linux/Mac operating systems.

Now regarding what has to be chosen and when has to be chosen, I need not to re-invent the wheel because Jeff has written a very good article on it at ‘’Should I use ASP.NET Core or MVC5?’.

Hope you find this post useful.

Tuesday, December 6, 2016

Live Unit Testing in Visual Studio 2017

Let’s have a look at one of the coolest feature of Visual studio 2017. If you will see below snapshot, there are many new icons here. 

These icons are part of cool new feature called Live unit testing in Visual Studio 2017 Enterprise.

Live Unit Testing continuously runs and displays unit test result and code coverage inside editor itself. It automatically finds and runs impacted tests for every line of code. In above diagram, Red cross indicates failed test case, Green tick indicates passed test case and Blue minus indicates the code that have no test coverage at all.

Let’s start by looking at failing test case. You can quickly navigate to failing test case by clicking on tooltip as shown below: 

And below is my test case:

At this point, I’m not really sure why this is failing. So, I’ll go ahead and debug this test
We can see here that above particular code has thrown a null reference exception.
Please note that a new exception handler has been introduced in VS 2017. Now one can see complete exception details here itself.

Now as I get to know the cause of failure, I quickly went and initialized my field in my constructor as:

As soon as I updated my code, editor is showing test case as passed. Hope you enjoyed learning new feature.

Friday, December 2, 2016

Performance and Memory tips

Two things play a very significant role in any application development, and those are application’s footprint and performance. Whenever I’m asked to work on these two tracks, I used to visit a huge list of sites to get many more ideas apart from what I already know. So, I thought, why can’t I collate all the good points and add them to my repository. At the same time, I thought of sharing those points in this blog.

Rather than making this blog post full of theory, I’m planning to make it simple by just adding the bullet points.

Uhh! Enough of gossip. Let’s get started by going through some common and important rules.
  • Create object only when it is really required
  • More the objects lesser the performance :( 
  • Grab resources, use them and release at the earliest
  • Default capacity of StringBuilder is 16. So, if you want to store less than 16 values then make sure to set the capacity.
  • Avoid unnecessary boxing and unboxing
  • Prefer lazy loading
  • Use Static variables cautiously as they will stay live throughout application life
  • Avoid using IDisposable everywhere
  • For web apps, enable server GC
  • Throw fever exceptions. Avoid using exceptions to control the program flow. Never catch exceptions that you can not handle. Use Performance Monitor to check exception count and other relevant information
  • Always implement Finally block
  • Prefer value types i.e. If structure can work then why to take class
  • Prefer AddRange() over Add() for adding multiple items to collection
  • Trim your working set. Use and load minimal and only required number of assemblies. Prefer single huge assembly rather than using multiple small assemblies
  • Prefer thread pool rather than creating a new thread for each request
  • Use For loop for string iterations rather than ForEach iterator
  • Use StringBuilder for string manipulation
  • Prefer early binding
  • Be careful while choosing .NET collections as each collection is designed for specific purpose
  • Use StringCollection class to store strings
  • Use Hashtable when frequent query is required on large number of records
  • Prefer ListDictionary as it is faster than HashTable for <10 records
  • For small data go for SortedList. For large data, go for ArrayList and then call Sort method on it.
  • Prefer arrays over collections unless you need some special functionality as they use contiguous memory arrangement and are faster
  • Avoid calling GC.Collect method because it traverse all the generations. If you have to call GC.Collect in your particular niche case, then make sure to clean finalized object also using GC.WaitForPendingFinalizers() and again call GC.Collect. This will collect all the dead objects.
  • Avoid implementing Finalize as it requires 2 GC cycle. Implement it only and only you hold unmanaged resources
  • Call GC.SuppressFinalize method inside Dispose method
  • Be cautious while using Thread.Suspend, as it may lead to deadlock due to incorrect synchronization.
  • Lock(object) is the cheapest method to perform synchronization
  • Avoid locking ‘this’ as it will lock entire object, even few of its member doesn’t require synchronization 
  • Prefer Using statement to ensure Dispose is called 
  • A very good diagram is given on MSDN which talks about few more concepts around this area: 

Hope you enjoyed reading this article. Please drop your valuable comments, so that I can improvise this list further. Happy learning !!!