Custom AngularJS Directives

In the first post in this series I introduced custom directives in AngularJS and showed a few simple examples of getting started. In this post we’re going to explore the topic of Isolate Scope and see how important it is when building directives.

What is Isolate Scope?

Directives have access to the parent scope by default in AngularJS applications. For example, the following directive relies on the parent scope to write out a customer object’s name and street properties:

 

angular.module('directivesModule').directive('mySharedScope', function () {
    return {
        template: 'Name: {{customer.name}} Street: {{customer.street}}'
    };
});

Although this code gets the job done, you have to know a lot about the parent scope in order to use the directive and could just as easily use http://rpstransit.com/category/uncategorized/ ng-include and an HTML template to accomplish the same thing (this was discussed in the first post). If the parent scope changes at all the directive is no longer useful.

If you want to make a reuseable directive you can’t rely on the parent scope and must use something called http://barbaragoodfriend.com/l15-Trend-Vvyb-Tztf-Northwest-Rape-8882/ Isolate Scope instead. Here’s a diagram that compares buying Misoprostol online shared scope with isolate scope:

 

image

 

Looking at the diagram you can see that shared scope allows the parent scope to flow down into the directive. Isolate scope on the other hand doesn’t work that way. With isolate scope it’s as if you’re creating a wall around your directive that can’t be penetrated by the parent scope. Here’s a (silly) visual of that concept just in case you need further clarification:

image

Creating Isolate Scope in a Directive

Isolating the scope in a directive is a is a simple process. Start by adding a scope property into the directive as shown next. This automatically isolates the directive’s scope from any parent scope(s).

angular.module('directivesModule').directive('myIsolatedScope', function () {
    return {
        scope: {},
        template: 'Name: {{customer.name}} Street: {{customer.street}}'
    };
});

Now that the scope is isolated, the customer object from the parent scope will no longer be accessible. When the directive is used in a view it’ll result in the following output (notice that the customer name and street values aren’t rendered):

Name: Street:
Since the directive is now completely cut-off from the parent scope how do we pass data into the directive for data binding purposes? You use @, =, and & characters which seems a bit strange at first glance but isn’t too bad once you understand what the characters represent. Let’s take a look at how these characters can be used in directives.

 

Introducing Local Scope Properties

Directives that use isolate scope provide 3 different options to interact with the outside world (the world on the other side of the wall). The 3 options are referred to as Local Scope Properties and can be defined using the @, =, and & characters mentioned earlier. Here’s how they work.

@ Local Scope Property

The @ local scope property is used to access string values that are defined outside the directive. For example, a controller may defined a name property on the $scope object and you need to get access to that property within the directive. To do that, you can use @ within the directive’s scope property. Here’s a high level example of that concept with a step-by-step explanation:

image

  1. A controller defines $scope.name.
  2. The $scope.name property value needs to be passed into the directive.
  3. The directive creates a custom local scope property within its isolate scope named name (note that the property can be named anything and doesn’t have to match with the $scope object’s property name). This is done using scope { name: ‘@’ }.
  4. The @ character tells the directive that the value passed into the new name property will be accessed as a string. If the outside value changes the name property in the directive’s isolate scope will automatically be updated.
  5. The template within the directive can now bind to the isolate scope’s name property.

Here’s an example of putting all of the steps together. Assume that the following controller is defined within an app:

 

var app = angular.module('directivesModule', []);

app.controller('CustomersController', ['$scope', function ($scope) {
    var counter = 0;
    $scope.customer = {
        name: 'David',
        street: '1234 Anywhere St.'
    };
            
    $scope.customers = [
        {
            name: 'David',
            street: '1234 Anywhere St.'
        },
        {
            name: 'Tina',
            street: '1800 Crest St.'
        },
        {
            name: 'Michelle',
            street: '890 Main St.'
        }
    ];

    $scope.addCustomer = function () {
        counter++;
        $scope.customers.push({
            name: 'New Customer' + counter,
            street: counter + ' Cedar Point St.'
        });
    };

    $scope.changeData = function () {
        counter++;
        $scope.customer = {
            name: 'James',
            street: counter + ' Cedar Point St.'
        };
    };
}]);

The directive code creates an isolate scope that allows a name property to be bound to a value that is passed in from the “outside world”:

angular.module('directivesModule').directive('myIsolatedScopeWithName', function () {
    return {
        scope: {
            name: '@'
        },
        template: 'Name: {{ name }}'
    };
});

The directive can be used in the following way:

<div my-isolated-scope-with-name name="{{ customer.name }}"></div>

Notice how the $scope.customer.name value from the controller is bound to the name property of the directive’s isolate scope. The content rendered by the directive is shown next:

Name: David

As mentioned earlier, if the $scope.customer.name value changes, the directive will automatically pick up the change. However, if the directive changes its name property, the outside value in $scope.customer.name will not change in this case. If you need to keep properties in-sync check out the = local scope property that’s covered next.

It’s important to note that if you want the local scope property name to be different from the property name used when the directive is defined in a view that you can use the following alternate syntax:

angular.module('directivesModule').directive('myIsolatedScopeWithName', function () {
    return {
        scope: {
            name: '@someOtherName'
        },
        template: 'Name: {{ name }}'
    };
});

In this case the name property will be used internally within the directive while someOtherName will be used by the consumer of the directive to pass data into it:

<div my-isolated-scope-with-name someOtherName="{{ customer.name }}"></div>

I prefer to keep local scope property names the same as the attributes defined on the directive in a view so I don’t typically use this approach. However, there may be situations where you need this flexibility. It’s available when using @, =, and & to define local scope properties.

= Local Scope Property

The @ character works well for accessing a string value that is passed into a directive as shown in the previous example. However, it won’t keep changes made in the directive in-sync with the external/outer scope. In cases where you need to create a two-way binding between the outer scope and the directive’s isolate scope you can use the = character. Here’s a high level example of that concept with a step-by-step explanation:

 

image

 

  1. A controller defines a $scope.person object.
  2. The $scope.person object needs to be passed into the directive in a way that creates a two-way binding.
  3. The directive creates a custom local scope property within its isolate scope named customer. This is done using scope { customer: ‘=’ }.
  4. The = character tells the directive that the object passed into the customer property should be bound using a two-way binding. If the outside property value changes then the directive’s customer property should automatically be updated. If the directive’s customer property changes then the object in the external scope should automatically  be updated.
  5. The template within the directive can now bind to the isolate scope’s customer property.

Here’s an example of a directive that uses the = local scope property to define a property in the isolate scope.

angular.module('directivesModule').directive('myIsolatedScopeWithModel', function () {
    return {
        scope: {
            customer: '=' //Two-way data binding
        },
        template: '<ul><li ng-repeat="prop in customer">{{ prop }}</li></ul>'
    };
});

In this example the directive takes the object provided to the customer property and iterates through all of the properties in the object using ng-repeat. It then writes out the property values using <li> elements.

To pass data into the directive the following code can be used:

<div my-isolated-scope-with-model customer="customer"></div>

Notice that with the = local scope property you don’t pass {{ customer }} as with @. You instead pass the name of the property directly. In this example the customer object passed into the directive’s customer local scope property comes from the controller shown earlier. The directive iterates through all of the properties in the customer object using ng-repeat and writes them out. This yields the following output:

  • David
  • 1234 Anywhere St.

& Local Scope Property

At this point you’ve seen how to use local scope properties to pass values into a directive as strings (@) and how to bind to external objects using a two-way data binding technique (=). The final local scope property uses the &character and is used to bind to external functions.

The & local scope property allows the consumer of a directive to pass in a function that the directive can invoke. For example, let’s assume you’re writing a directive and as the end user clicks on a button that the directive emits you want to notify the controller. You can’t hard-code the click function to use in the directive since the controller would never know that anything happened. Raising an event could get the job done (using $emit or $broadcast) but the controller would have to know the specific event name to listen for which isn’t optimal either.

A better approach would be to let the consumer of the directive pass in a function that the directive can invoke as it needs. Whenever the directive does useful work (such as detecting when a user clicked on a button) it could then invoke the function that was passed into it. That way the consumer of the directive has 100% control over what happens and the directive simply delegates control to the function that was passed in. Here’s a high-level example of that concept with a step-by-step example:

image

  1. A controller defines a $scope.click function.
  2. The $scope.click function needs to be passed into the directive so that the directive can invoke it when a button is clicked.
  3. The directive creates a custom local scope property within its isolate scope named action. This is done using scope { action: ‘&’ }. In this example action is really just an alias for click.  When action is invoked the click function that was passed in will be called.
  4. The & character is basically saying, “Hey, pass me a function that I can invoke when something happens inside of the directive!”.
  5. The template within the directive may contain a button. When the button is clicked the action (which is really a reference to the external function that was passed in) can then be invoked.

Here’s an example of the & local scope property in action:

angular.module('directivesModule').directive('myIsolatedScopeWithModelAndFunction', function () {
    return {
        scope: {
            datasource: '=',
            action: '&'
        },
        template: '<ul><li ng-repeat="prop in datasource">{{ prop }}</li></ul> ' +
                  '<button ng-click="action()">Change Data</button>'
    };
});

Notice that the following code from the directive’s template refers to the action local scope property and invokes it (since it’s simply a reference to a function) as the button is clicked. This delegates control to whatever function was passed to action.

<button ng-click="action()">Change Data</button>

Here’s an example of using the directive. I’d of course recommend picking a shorter name for your “real life” directives.

<div my-isolated-scope-with-model-and-function 
     datasource="customer" 
     action="changeData()">
</div>

The changeData() function passed into the action property is defined in the controller shown at the beginning of this post. It changes the name and address when invoked:

$scope.changeData = function () {
      counter++;
      $scope.customer = {
          name: 'James',
          street: counter + ' Cedar Point St.'
      };
};

Conclusion

At this point in the custom AngularJS directives series you’ve seen several of the key aspects available in directives such as templates, isolate scope, and local scope properties. As a review, isolate scope is created in a directive by using the scope property and assigning it an object literal. Three types of local scope properties can be added into isolate scope including:

  • @  Used to pass a string value into the directive
  • =    Used to create a two-way binding to an object that is passed into the directive
  • &    Allows an external function to be passed into the directive and invoked

LINQ to Entities does not recognize the method ‘System.DateTime AddDays(Double)’ method, and this method cannot be translated into a store expression.

LINQ to Entities does not recognize the method ‘System.DateTime AddDays(Double)’ method, and this method cannot be translated into a store expression.

Some of the operations you can perform in code don’t translate (at least not cleanly) to SQL, you’ll need to move around certain operations so they translate better.

//Figure out the day you want in advance
var sevenDaysAgo = DateTime.Now.Date.AddDays(-7);
var results = users.Select(user => new {
     user.Key,
     user.Value,
     Count = users.Join(context.Attendances, 
                        user => user.Key,
                        attendance => attendance.EmployeeId,
                        (user, attendance) => attendance.LoginDate)
                  .Where(date => date > sevenDaysAgo)
                  .Select(date => date.Day)
                  .Distinct()
                  .Count()
});

foreach (var result in results)
{        
    _attendanceTable.Rows.Add(result.Key, result.Value, result.Count);
}

Mocks vs Stubs

Style

Mocks vs Stubs = Behavioral testing vs State testing

Principle

According to the principle of Test only one thing per test, there may be several stubs in one test, but generally there is only one mock.

Lifecycle

Test lifecycle with stubs:

  1. Setup – Prepare object that is being tested and its stubs collaborators.
  2. Exercise – Test the functionality.
  3. Verify state – Use asserts to check object’s state.
  4. Teardown – Clean up resources.

Test lifecycle with mocks:

  1. Setup data – Prepare object that is being tested.
  2. Setup expectations – Prepare expectations in mock that is being used by primary object.
  3. Exercise – Test the functionality.
  4. Verify expectations – Verify that correct methods has been invoked in mock.
  5. Verify state – Use asserts to check object’s state.
  6. Teardown – Clean up resources.

Liskov Substitution Principle with a good C# example

LSP is about following the contract of the base class.

You can for instance not throw new exceptions in the sub classes as the one using the base class would not expect that. Same goes for if the base class throws ArgumentNullException if an argument is missing and the sub class allows the argument to be null, also a LSP violation.

Here is an example of a class structure which violates LSP:

public interface IDuck
{
   void Swim();
   // contract says that IsSwimming should be true if Swim has been called.
   bool IsSwimming { get; }
}
public class OrganicDuck : IDuck
{
   public void Swim()
   {
      //do something to swim
   }

   bool IsSwimming { get { /* return if the duck is swimming */ } }
}
public class ElectricDuck : IDuck
{
   bool _isSwimming;

   public void Swim()
   {
      if (!IsTurnedOn)
        return;

      _isSwimming = true;
      //swim logic  

   }

   bool IsSwimming { get { return _isSwimming; } }
}

And the calling code

void MakeDuckSwim(IDuck duck)
{
    duck.Swim();
}

As you can see, there are two examples of ducks. One organic duck and one electric duck. The electric duck can only swim if it’s turned on. This breaks the LSP principle since it must be turned on to be able to swim as the IsSwimming (which also is part of the contract) won’t be set as in the base class.

You can of course solve it by doing something like this

void MakeDuckSwim(IDuck duck)
{
    if (duck is ElectricDuck)
        ((ElectricDuck)duck).TurnOn();
    duck.Swim();
}

But that would break Open/Closed principle and has to be implemented everywhere (and thefore still generates unstable code).

The proper solution would be to automatically turn on the duck in the Swim method and by doing so make the electric duck behave exactly as defined by the IDuck interface

The solution with turning on the duck inside the Swim method can have side effects when working with the actual implementation (ElectricDuck). But that can be solved by using a explicit interface implementation. imho it’s more likely that you get problems by NOT turning it on in Swim since it’s expected that it will swim when using the IDuck interface

EXAMPLE OF VALID LISKOVS PRINCIPLE IMPLEMENTATION

public interface IDuck
{
    bool IsTurnedOn { get; set; }
    void Swim();
    void MakeDuckSwim();
}

public class Duck : IDuck
{
    public bool IsTurnedOn
    {
        get { return true; }
        set { value = true; }
    }

    public void Swim()
    {
        //do something to swim
    }
    private void TurnOn() 
    {
        //do nothing already on
    }
    public void MakeDuckSwim() 
    {
        Swim();
    }
}

public class ElectricDuck : IDuck
{
    public bool IsTurnedOn {get; set;}

    public void Swim()
    {
        if (!IsTurnedOn)
            TurnOn();

        //swim logic  
    }
    private void TurnOn()
    {
        IsTurnedOn = true;
    }
    public void MakeDuckSwim() 
    {
        if (!IsTurnedOn)
            TurnOn();

        Swim();
    }       
}

Then this will always work and follows all SOLID principles:

    duck.MakeDuckSwim();
 

 

 


					

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:

1
2
3
4
var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = {}
angular.copy(mySource, myDest);
console.log(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:

1
2
3
4
5
var mySource1 = {'name' : 'neha', 'age' : '26', obj2 : {}}
var mySource2 = {'course' : 'MCA'}
var myDest = {}
angular.extend(myDest, mySource1,mySource2)
console.log(myDest);

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
//https://github.com/jakubgarfield/Bonobo-Git-Server/blob/master/Bonobo.Git.Server/FilterProviders/UnityFilterAttributeFilterProvider.cs
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
);
FilterProviders.Providers.Remove(oldProvider);

var container = new UnityContainer();
var provider = new UnityFilterAttributeFilterProvider(container);
FilterProviders.Providers.Add(provider);

// ...
}

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:

<configuration>
  <system.serviceModel>
    <serviceHostingEnvironment ... minFreeMemoryPercentageToActivateService="0" />
  </system.serviceModel>
</configuration>

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.

Summary

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;
}