Monthly Archives: March 2016

AngularJS : copy vs extend

While using AngularJS, we come across some situation in which we need to copy one object to another object. In that case, we probably have two solutions: angular.copy() or angular.extend(). Lets see how they work differently.

1. angular.copy(source, destination) : It creates a deep copy of source object or array and assign it to destination where ‘destination’ is optional. By writing deep copy, we mean that a new copy of the referred object is made. For example:

var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = {}
angular.copy(mySource, myDest);

Output: {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}

If we check mySource.obj === myDest.obj, this will give false because both point to different objects. This is called as deep copying.

2. angular.extend(destination, src1, src2 …) : It creates a shallow copy of one or more sources provided and assign them to destination. For example:

var mySource1 = {'name' : 'neha', 'age' : '26', obj2 : {}}
var mySource2 = {'course' : 'MCA'}
var myDest = {}
angular.extend(myDest, mySource1,mySource2)

Output: {name: "neha", age: "26", course: "MCA", obj2: Object}

Now we check mySource1.obj2 === myDest.obj2, this will give true because both point to same reference of object. This is called as shallow copying.

NOTE: angular.copy() is slower than angular.extend()

So, by keeping these points into mind, we can make our decision of when to use copy and when to use extend.

Injecting Repository into Custom Action Filter using Unity

create UnityFilterAttributeFilterProvider .cs class
public class UnityFilterAttributeFilterProvider : FilterAttributeFilterProvider

private readonly IUnityContainer _container;

public UnityFilterAttributeFilterProvider(IUnityContainer container)
_container = container;

protected override IEnumerable<FilterAttribute> GetControllerAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
var attributes = base.GetControllerAttributes(controllerContext, actionDescriptor).ToList();
foreach (var attribute in attributes)
_container.BuildUp(attribute.GetType(), attribute);

return attributes;

protected override IEnumerable<FilterAttribute> GetActionAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
var attributes = base.GetActionAttributes(controllerContext, actionDescriptor).ToList();
foreach (var attribute in attributes)
_container.BuildUp(attribute.GetType(), attribute);

return attributes;

In global.asax
protected void Application_Start() {
// ...

var oldProvider = FilterProviders.Providers.Single(
f => f is FilterAttributeFilterProvider

var container = new UnityContainer();
var provider = new UnityFilterAttributeFilterProvider(container);

// ...

Since Unity is not instantiating the Filters, it cannot inject them. You would have to resort to service locator pattern such as in the following:
Authenticate is the custom action filter where I am injecting IAuthenticate and ILibrary repository
public class Authenticate : AuthorizeAttribute
public IAuthenticate AuthenticateLibrary { get; private set; }

public ILibrary BaseLibrary { get; private set; }

public Authenticate()
AuthenticateLibrary = DependencyResolver.Current.GetService<IAuthenticate>();
BaseLibrary = DependencyResolver.Current.GetService<ILibrary >();

ViewComponents in ASP.NET 5 and ASP.NET MVC 6

Let’s have a quick look at another new feature in ASP.NET MVC 6, and that is the ViewComponent feature. View components are intended to be replacements to ChildActions and, to some extent, of partial views.

Traditionally in ASP.NET MVC (and in general in the textbook MVC pattern), you had to compose the entire model in the controller and pass it along to the view, which simply rendered the entire page based on the data from the model. The consequence of this is that the view does not need to explicitly ask for any data – as its sole purpose is to just act upon the model it received.

While this sounds very nice in theory, it has traditionally posed a number of practical difficulties. There are a number of reusable components on pretty much every website – think a menu, a shopping cart, lists of all kinds, breadcrumbs, metadata and so on – so things that appear on multiple pages.

Let’s have a look at how this is solved in MVC 6.

The reusable component problem

Having to compose and gather the data required to create these components in multiple controllers over and over can be really painful, and has often led developers to create a all kinds of model builders and inherited models (have you ever created aBaseModel containing things like menu or page metadata?).

One way to easy that pain was to try to use child actions – which were actions that could only be called from the view (not publicly by the client). I have seen plenty of MVC projects that used child actions to render such reusable components. Another alternative has always been to create elaborate HtmlHelpers. Unfortunately since the helpers were static, you couldn’t do dependency injection into them, so trying to load any extra data for the purpose of such helper, would require you to use service locator – the MVC global DependencyResolver.

View components are really a mesh of both HtmlHelper and child actions.

ViewComponents example

Consider the following sample service:

It’s not unreasonable to think that you might have code resembling something that in your projects. Imagine that we need to display a list of these promoted products in multiple places on the website.

Typically in MVC 5 and earlier, you would have a child action, an HtmlHelper or a base model builder to handle this. With view component you can simply add a view component class:

That class can use ASP.NET 5 dependency injection – which is very convenient. It can return something primitive like a JSON or a string, but it can also have its own partial view; in the above example the partial exists under/Views/Shared/Components/{componentname}/Default.cshtml. The Default.cshtml is the default convenion for all views of view component. You can also pass the name of the view returning i.e. return View(“_Products”, products)

In our case the Razor view would look like you would expect any partial view to look:

In order to embed this view component into a proper, main view, you use the Component property of the Razor pages – in the form of the following syntax:

There is also a sync version, if your component is synchronous. And that’s about it – a bit against the textbook MVC pattern, but very convenient and much cleaner than the old approaches or workarounds we had to use.

Some background info

In order for a class to be recognized as a view component, it needs to be:

  • public
  • non-abstract
  • non generic
  • end with ViewComponent suffix or be decorated with ViewComponentAttribute

As you can see, just like the rest of MVC 6, it heavily relies on conventions. To build a view component you do not need to inherit from any specific class or implement any interface.

As far as the actual functionality inside your view component, it is also defined by convention – it should be wrapped in one of the following methods (the method name and return type are important):

The default view component invoker (which could be changed if you wish) will first try to look for the async method, and if it’s not found, then it will try to fallback to the sync version. Afterwards, if it’s still not found, you’ll get a runtime error. This is important to note, because given the above mentioned requirements for a class to be considered a valid view component, it is still possible to get a runtime error if you misspell or misname the actual Invoke method.

Depending on what you need to do, there is a base class ViewComponent, which you can choose to inherit from for your own convenience. It will give you – through it’s expose properties – access to all contextual information about the view such as user principal information, current HttpContext, ViewData and all other information you typically would have inside a view. It will also allow you to easily attach a Razor view to the view component – which you can do by calling the base View() method when returning from your view component.

As far as discovery of view components goes, all assemblies that reference ASP.NET MVC packages will be considered valid to search. This is particularly important for developers of reusable, CMS-like components that are intended to be used cross-project. The discovery is controlled by a type called DefaultViewComponentDescriptorProvider, which allows you to extend itself with additional source to look at or provide different rules for the class to be recognized as view component.

Finally, it is also possible to pass data to the components. Then you add the relevant parameters to the signature, for example:

In order to invoke such a component from a view, you use an overload of the Component.InvokeAsync which takes param ofobject[]:

WCF Service returning “requested service ‘…’ could not be activated” the first time it’s accessed from an MVC site

I’ve just manage to solve similar problem of random ‘System.ServiceModel.ServiceActivationException’ (thrown exception, then run on second hit.). The reason for the exception in my case was lack of memory on the server. To confirm the memory problem, you can do following:

Application calling web service:

System.ServiceModel.ServiceActivationException: The requested service, 'XXX' could not be activated. See the server's diagnostic trace logs for more information.

Server stack trace: 
   at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory`1 factory, WebException responseException, ChannelBinding channelBinding)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

WCF trace log: nothing logged.

On server hosting wcf service (the same as the calling application btw) in event logs except lot of crap info I’ve found:

Custom event details:

WebHost failed to process a request.
 Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/58366981
 Exception: System.ServiceModel.ServiceActivationException: The service 'xxx' cannot be activated due to an exception during compilation.  The exception message is: Memory gates checking failed because the free memory (xxx bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.. ---> System.InsufficientMemoryException: Memory gates checking failed because the free memory (xxx bytes) is less than 5% of total memory.  As a result, the service will not be available for incoming requests.  To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

So solution for me was: 1. add more ram 2. release some of ram (temporary solution) 3. update web config of the web service:

    <serviceHostingEnvironment ... minFreeMemoryPercentageToActivateService="0" />

Serializing Entity Framework objects to JSON in ASP.NET Web API

Recently, I’ve been playing a lot with ASP.NET Web API, as it is really an exciting technology. It works exceptionally well with JSON.NET (Henrik Nielsen wrote a great post on how to return JSON from ASP.NET Web API using JSON.NET).

However, as it’s been the case in the past with i.e. WCF, I’ve run into a issue with serializing Entity Framework object to JSON when returning them from the ApiController. This is not, by any means, an issue in ASP.NET Web API, as the problem in this case lies in the EF lazy loading, which causes circular reference between the objects. This then throws a corresponding error – “A circular reference was detected while serializing an object of type (…)” if you are using JavaScriptSerializer, “Self referencing loop detected for type (…)” if you are using JSON.NET and so on.

I thought it might be useful to remind about possible solutions to this. There is an easy workaround.

More after the jump.

Our models & errors

For starters let’s take a look at our two simple models.

And the DbContext.

Finally, here is our ApiController.

If we try to return a simple Url from the ApiController, using the example above, we’d get the following error (note, the error comes from JSON.NET, but any other serializer would throw similar.

Solution – data projection

Data projection – in other words, passing to serializer only a selected set of values, in a form of an object different from Domain Model Object. DTO is a massive topic on its own, so I will not discuss it here. In case you are interested, there is a great article on that here. In short, let’s just say that many people consider using DTO these days a very poor approach, while others firmly believe that it is abolutely necessary to use DTO instead of trying to serialize your Domain Model Objects. Personally, I am a data projection advocate as to me it only makes sense to NOT expose domain models to the View.

Anyway, moving aside from the discussion, we could use data projection to an anonymous type in the LINQ query and serialize that. In other words, that would act kind of like a ViewModel.

This still wouldn’t compile as our old Get() method was returning a List, whereas in here we are dealing with IQueryable of Anonymous Type. Unfortunately there is no simple way to return IQueryable of Anonymous Type or IEnumerable of Anonymous Type from an ApiController method. So we’ll use a bit of hack and change the method signature to:

This is C# 4.0+ only, but we are talking ASP.NET Web API here, aren’t we? So the whole thing now looks like this:

Of course in this case we lose the type safety, but again, it produces the expected result.


If you run into problems with your EF objects, do not worry, there are ways to work around them. I’ve found this solution useful when experimenting with ASP.NET Web API, especially with much more complex entities that the ones used here as an example. If you don’t entirely agree, instead of returning anonymous object, you can also return a custom type, and effectively have a ViewModel.

you can also disable Lazy Loading in the constructor of the dbContext… I.E.
public DbContext(){
Configuration.LazyLoadingEnabled = false;
Then you won’t have to do it every time you need to use your DbContext.

If you wanted you could also use a viewmodel approach. While you are returning a view per se, you return a model designed around what you want exposed in the API.

public list Get()
var urls = db.Urls.Include(“Tags”).Select(i =>
new ViewModels.Url { i.Uid, i.UrlId, i.Address, i.Description, i.Tags});
return urls;

The concurrent dictionary-Multithreading

convert a ‘foreach’ loop into a parallel foreach loop

Let’s say you have the following foreach loop, which sends an output of results to Grasshopper:

var results new List<bool>(new bool[pts.Count]);
foreach (Point3d pt in pts)
    bool isIntersecting = CheckIntersection(pt, shape);

DA.SetDataList(0, results);

We set up a list to take our results, we cycle through our points, do a calculation on each, and then save the result. When finished, we send the result as an output back to Grasshopper. Simple enough.

The best thing to do is I show you how to parallelise this, and then explain what’s happening. Here’s the parallel version of the above code:

var results = new System.Collections.Concurrent.ConcurrentDictionary<Point3d, bool>(Environment.ProcessorCount, pts.Count);
foreach (Point3d pt in pts) results[pt] = false; //initialise dictionary

Parallel.ForEach(pt, pts=>
    bool isIntersecting = CheckIntersection(pt, shape);
    results[pt] = isIntersecting; //save your output here

DA.SetDataList(0, results.Values); //send back to GH output

Going from ‘foreach’ to ‘Parallel.ForEach’

The Parallel.ForEach method is what is doing the bulk of the work for us in parallelising our foreach loop. Rather than waiting for each loop to finish as in single threaded, the Parallel.ForEach hands out loops to each core to each of them as they become free. It is very simple – we don’t have to worry about dividing tasks between the processors, as it handles all that for us.

Aside from the slightly different notation, the information we provide is the same when we set up the loop. We are reading from collection ‘pts’, and the current item we are reading within ‘pts’ we will call ‘pt’.

The concurrent dictionary

One real problem though with multithreading the same task is that sometimes two or more processes can attempt to overwrite the same piece of data. This creates data errors, which may or may not be silent. This is why we don’t use a List for the multithreading example – List provides no protection from multiple processes attempting to write into itself.

Instead, we use the ConcurrentDictionary. The ConcurrentDictionary is a member of the Concurrent namespace, which provides a range of classes that allow us to hold and process data without having to worry about concurrent access problems. The ConcurrentDictionary works just about the same as regular Dictionaries, but for our purposes we can use it much like a list.

It is a little more complicated to set up, as you need to specify keys for each value in the dictionary, as well as the value itself. (I have used dictionaries once before here.) Rather than having a collection of items in an order that we can look up with the index (the first item is 0, the second item is 1 and so on) in a dictionary we look up items by referring to a specific item. This specific item is called the ‘key’. Here, I am using the points as the key, and then saving their associated value (the results we are trying to calculate) as a bool.

How much faster is parallel computation?

Basic maths will tell you that you will that your code should increase at a rate of how many cores you have. With my 4-core machine, I might expect a 60 second single-threaded loop to complete in about 15 seconds.

However, there are extra overheads in parallel processing. Dividing up the work, waiting for processes to finish towards the end, and working with the concurrent dictionary, all take up processor power that would otherwise be used in computing the problem itself.

In reality, you will still likely get a substantial improvement compared to single-threaded performance. With 4 cores, I am finding I am getting a performance improvement of around 2.5 to 3.5 times. So a task that would normally take 60 seconds is now taking around 20 seconds.

C# Multithreading Loop with Parallel.For or Parallel.ForEach

Loop is such a trivial and so frequently used thing. And sometimes loops just killing performance of the whole application. I want the loop perform faster, but what can I do?

Starting from .NET Framework 4 we can run loops in parallel mode using Parallel.For method instead of regular for or Parallel.ForEach instead of regular foreach. And the most beautiful thing is that .NET Framework automatically manages the threads that service the loop!
But don’t expect to receive performance boost each time you replace your for loop with Parallel.For, especially if your loop is relatively simple and short. And keep in mind that results will not come in proper order because of parallelism.

Now let’s see the code. Here is our regular loop:

for (int i = 1; i < 1000; i++)
    var result = HeavyFoo(i);
    Console.WriteLine("Line {0}, Result : {1} ", i, result);

And here is how we write it with Parallel.For:

Parallel.For(1, 1000, (i) =>
    var result = HeavyFoo(i);
    Console.WriteLine("Line {0}, Result : {1} ", i, result);

Same story with Parallel.ForEach:

foreach(string s in stringList)
    var result = HeavyFoo(s);
    Console.WriteLine("Initial string: {0}, Result : {1} ", s, result);

Parallel.ForEach(stringList, s =>
    var result = HeavyFoo(s);
    Console.WriteLine("Initial string {0}, Result : {1} ", s, result);