Custom filters in AngularJS

February 23, 2016 Leave a comment

In this post I am going to show you how easy it is to write custom filters in AngularJS and for the simplicity of the demo I am going to display a list of cron-jobs in a tabular data. Each job has details like the Id, action etc. and has a status which is represented in numbers like 0,1,2 etc. This may be suitable from a storage or system point of view but is not that user-friendly, so lets write a custom filter to transform numeric values into user-friendly status.

First we start with an AngularJS controller "CronJobsController" and it will be responsible for calling the cronjobs ASP.NET Web API.If the call is successful the returned data is assigned to $scope.jobs object so that we can bind the data to our view.

app.js

var app = angular.module('mainApp', []);
app.controller('CronJobsController', function ($scope,$http) {
    $scope.jobs = [];
    $http({
        method: 'GET',
        url: '/api/cronjobs'
      })
      .then(function(response) {
        $scope.jobs = response.data;
      },function(reason) {
        $scope.error = reason.data;
      });
});

Next step is to wire up the "myApp" to the HTML page by using the ng-app directive.

CronJobs.html

<body ng-app="mainApp">
    <!--Html omitted for brevity -->
</body>

Now I am going to create the view by adding some table mark-up and use bootstrap to format the HTML table. For data binding I’m going to use the ng-repeat directive to enumerate through the jobs and bind the data to the table.

CronJobs.html(cont.)

<div class="row">
    <!-- Jobs Controller Scope -->
    <div class="col-md-12" ng-controller="CronJobsController">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Correlation Id</th>
                    <th>Action</th>
                    <th>Created</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="job in jobs">
                    <td>{{job.id}}</td>
                    <td>{{job.correlationId}}</td>
                    <td>{{job.action}}</td>
                    <td>{{job.created | date:'dd-MM-yyyy'}}</td>
                    <td>{{job.status}}</td>

                </tr>
            </tbody>
        </table>
    </div>
    <!-- End of Jobs Controller Scope -->
</div>

Lets run the application and we can see that everything is working perfectly.

Cron Job Display Data without filter

Now we are going to build our custom filter "status" which will return a user-friendly status based on the numeric value.

statusfilter.js

/// <reference path="app.js" />

app.filter('status', function() {
    return function(status) {
        switch(status) {
            case 0:
                return "Not Started";
            case 1:
                return "In Progress";
            case 2:
                return "Completed";
            default:
                return "Unknown";
        }
    }
})

Nothing special here a simple switch case statement returning user-friendly text and all is left is to apply this filter to our model’s status property as shown in below code snippet.

<td>{{job.status | status}}</td>

And after applying the filter we can see the user-friendly status is displayed instead of the numbers.

Cron Job Display Data with filter

It’s a very simple yet powerful feature and another reason to love AngularJS.

ASP.NET Core – Exceeds 1.15 Million request/s

February 20, 2016 Leave a comment

Congratulations to the ASP.NET Core team for hitting this amazing milestone of 1.15 Million request/s http://www.ageofascent.com/asp-net-core-exeeds-1-15-million-requests-12-6-gbps/ . Now is an amazing time to work with ASP.NET Web API and AngularJS.

Shaping up with Angular.js

November 30, 2015 Leave a comment

This is one the finest and free AngularJS webcasts I have seen so far . If you are new to AngularJS development and want to learn AngularJS but have no clue where to start then this is tutorial to go for.

https://www.codeschool.com/courses/shaping-up-with-angular-js .

Thanks to the guys at codeschool to make this fun driven tutorial which is so exciting to watch and learn.:-)

Table Splitting in Entity Framework

October 15, 2015 2 comments

In my previous post I covered the Entity Splitting technique and in this post I am going to talk about just the opposite of that technique.

Table Splitting:- In this scenario there are multiple entities or domain objects but the data is stored in a single table. Lets say in our database we have an employee table which stores basic information like first name, last name, DOB as well their photo. However in our domain model we want to create two different entities.

Lets write our domain objects to see this is action.

Employee.cs

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public DateTime DOB { get; set; }
    public virtual EmployeePhoto Photo { get; set; }
}

EmployeePhoto.cs

public class EmployeePhoto
{
    public int Id { get; set; }
    public byte[] Photo { get; set; }
    public Employee Employee { get; set; }
}

As you can see we have define two entities Employee and EmployeePhoto in our domain model and we have declared EmployeePhoto as virtual, with this declaration we can take advantage of lazy loading and when we query the Employee entity through EF the photo column will not be selected as part of the linq query. Second it also indicates that EmployeePhoto entity cannot exist without an Employee. It is also important that EmployeePhoto has a reference of Employee entity and has an Id properties which we will use to map the two entities into one table.

Lets wire up the relationship in our context class as shown below.

EmployeeContext.cs

public class EmployeeContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<EmployeePhoto> Photos { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<EmployeePhoto>().HasKey(p => p.Id);

        modelBuilder.Entity<Employee>()
            .HasRequired(e => e.Photo)
            .WithRequiredPrincipal(p => p.Employee);

        modelBuilder.Entity<EmployeePhoto>().ToTable("Employee");
        modelBuilder.Entity<Employee>().ToTable("Employee");
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

We first defined the secondary entity( Employee Photo ) that and state that it has an identity key which is identical in our main entity. Next in our Employee entity we defined that the photo property is required with the Employee as the primary entity and then using ToTable function we map both the entity to the same table i.e. Employee.

Entity Splitting in Entity Framework

September 30, 2015 1 comment

I have done a lot of post on Entity Framework Code First which includes some simple tips and tricks to more complex scenarios of mapping relationship and here are some of those post if you want to read them.

Entity Framework Tutorial

However recently I was helping a friend of mine to understand Entity Framework modelling for a legacy system. Since the schema is already defined it becomes a bit difficult to create a rich domain model keeping the model in your design. The other thing I have seen is that people simply follow the schema and let schema dictating what your domain is, which in my opinion is not correct.

Anyways, after some discussion I realized that they are not taking advantage of Entity Splitting in Entity Framework, so I thought about blogging it.

Entity Splitting:- In this scenario there is a single entity or domain object but the data is stored in multiple tables with a one to one relationship. For example lets say the domain is a fitness/health industry and you have customer table which stores basic information like first name, last name, DOB in the customer table and other vital stats like resting heat beat,blood type,cholesterol level, blood pressure, Sugar level etc. in their health information table. However in your domain model the customer object is composed of both information.

Lets see this in action.

Customer.cs

public class Customer
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime DOB { get; set; }

    public int RestingHeartBeat { get; set; }

    public string BloodType { get; set; }

    public decimal Cholesterol { get; set; }

    public string BloodPressure { get; set; }
}

So this is my domain object which represents the whole customer object however in the legacy system some information is stored in the Customer table and some in the VitalStats table.

And lets write the configuration for customer in which we will split the entity into two different tables using the Map and ToTable function as shown below.

CustomerConfiguration.cs

public class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
    public CustomerConfiguration()
    {
        this.Map(c =>
       {
           c.Properties(p => new
           {
               p.Id,
               p.FirstName,
               p.LastName,
               p.DOB
           });
           c.ToTable("Customer");
       })
        .Map(v =>
       {
           v.Properties(p => new
           {
               p.Id,
               p.BloodPressure,
               p.BloodType,
               p.Cholesterol,
               p.RestingHeartBeat
           });
           v.ToTable("VitalStats");
       });
    }
}

And here is my DbContext class.

public class HealthContext : DbContext
{
    DbSet<Customer> Customer { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

Entity Framework 7: In Memory Testing

August 31, 2015 1 comment

I am really excited about the in-memory testing feature of Entity Framework 7 as testing in the previous versions of Entity Framework wasn’t straight forward and painful at times .

Let’s get started by installing the Entity Framework “InMemory” testing nuget package and make sure you have selected the “Include Prerelease” in the nuget dialogue as Entity Framework 7 is still in beta 6.

install ef7 pre release using nuget

Alternatively the old-fashioned way

PM>Install-Package EntityFramework.InMemory -Prerelease

 

As you can see that when we install the EntityFramework.InMemory package it also brings the EntityFramework.Core package.These are some of the new changes to Entity Framework as EF has been decomposed into smaller manageable packages.

Lets start writing our domain objects and I am going to use the simple example of Student and Course as show below.

Student.cs

public class Student
{
    public Student()
    {
        Courses = new HashSet<Course>();
    }
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public ICollection<Course> Courses { get; set; }

    public override string ToString()
    {
        return 
            string.Format(
                    "Id = {0}, FirstName = {1}, LastName = {2}", 
                    this.Id, 
                    this.FirstName, 
                    this.LastName);
    }
}

Course.cs

public class Course
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

}

Next we will define the database context and this is where you will see a significant change to the previous version. In the constructor of our context we are creating a dependency on DbContextOptions which will decide which source to use to persist the data.

TrainingContext.cs

public class TrainingContext : DbContext
{
    public TrainingContext(DbContextOptions options)
        : base(options)
    {
    }

    public DbSet<Student> Student { get; set; }

    public DbSet<Course> Course { get; set; }
}

Now we will wire up the TrainingContext to the main program and using the DbContextOptionsBuilder we will instruct the entity framework to use the in-memory database. I also created a separate method to populate the student table with 2 records.

Program.cs

class Program
{
    static void Main(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<TrainingContext>();
        optionsBuilder.UseInMemoryDatabase(true);

        using (var context = new TrainingContext(optionsBuilder.Options))
        {
            AddStudentData(context);

            var student = context.Student.FirstOrDefault(x => x.Id == 1);

            Console.WriteLine(student.ToString());

            student.FirstName = "James";
            context.SaveChanges();

            student = context.Student.FirstOrDefault(x => x.Id == 1);

            Console.WriteLine(student.ToString());

            Console.ReadLine();

        }
    }

    private static void AddStudentData(TrainingContext context)
    {
        context.Student.Add(new Student { Id = 1, FirstName = "Joe", LastName = "Blogg" });

        context.Student.Add(new Student { Id = 2, FirstName = "Jane", LastName = "Doe" });

        context.SaveChanges();
    }
}

As you can see we first retrieve the student with id 1 then we changed the first name of the student and asked entity framework to save the changes into the in-memory database.

And below is the output of the before and after state of that record.

Saved changes output to the console window

Testing Web API

July 31, 2015 3 comments

Continuing with my previous post on Implementing Web API Versioning using OWIN, in this post I am going to show how to write unit test for your Web APIs.

As we know that the beauty of OWIN is able to run your web application independent of the web server and based on this principle the Microsoft.Owin.Testing takes advantage of this feature to host the Web API in memory and execute the methods. Very simple and straight forward.

Lets get started by creating a new Unit Test project in Visual Studio and get the Microsft.Owin.Testing package from the Nuget Server as shown below.

PM> Install-Package Microsoft.Owin.Testing

Next step is to create a custom Startup class and bring in any services or OWIN Middleware which our Web API depends upon. As this is a demo Web API application I will just configure the DefaultVersionSelector we build in the previous post.

CustomStartup.cs

public class CustomStartup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();

        config.Routes.MapHttpRoute(
            "DefaultApi",
            "api/{controller}/{id}",
            new
            {
                id = RouteParameter.Optional,
                version = "1"
            });

        config.Services.Replace(
            typeof(IHttpControllerSelector),
            new DefaultVersionControllerSelector(
                config,
                new DefaultVersionSelector()));
        app.UseWebApi(config);
    }
}

As you can see nothing special in the startup class it is identical to our Web API project startup class and all I am doing is registering my DefaultVersionSelector and it dependencies and asking the IAppBuilder to invoke the OWIN Web API Middleware.

Now we are going to write a unit test which will use the OWIN testing component and invoke a simple get on our values controller.

WhenUsingOwinTestServer.cs

public class WhenUsingOwinTestServer
{
    private const string ContentTypeJsonVersion1 = "application/json;version=1";

    private const string AcceptHeader = "Accept";

    private const string RequestUri = "/api/values";

    private const string ExpectValueVersion1 = "[\"value1-Version1\",\"value2-version1\"]";


    [TestMethod]
    public void ShouldBeAbleToGetResultForVersion1()
    {
        using (var server = TestServer.Create<CustomStartup>())
        {
            var client = server.HttpClient;

            client.DefaultRequestHeaders.Add(AcceptHeader, ContentTypeJsonVersion1);
            var task = server.HttpClient.GetAsync(RequestUri);
            var response = task.Result.Content.ReadAsStringAsync();
            Assert.AreEqual(ExpectValueVersion1, response.Result);
        }
    }
}

As you can see in the above code we are using the TestServer to host Web API with our custom startup class. First we get a reference of the it’s HttpClient object and add our accept header with the versioning information. Next we make a GET request at the api/values end point,as everything is happening in memory you can see we don’t specify the web server in our URI.

Rest is pretty straight forward and we assert that the expected values and the results do match.

Follow

Get every new post delivered to your Inbox.

Join 72 other followers