Categorie: c#

Getting started with ASP.NET API with MongoLab and Angularjs part 4

In my previous blogpost we created a Web API with a Mongodb backend. Now we’ll create a client application that consumes the API with a JavaScript framework.
That is obviously the way to go nowadays.

There is a plethora of Javascript frameworks to use and Angular.js is in fact the first one that I’ve tried, because it gets a lot of traction lately.

What are we creating?

Let’s try to make a single page application (SPA) where people can enter and lookup their contacts. Instead of the classic addressbooks, it is possible to enter Facebook pages, Twitter accounts and so on.
To make sure it looks nice we will be using Twitter Bootstrap.

Getting ready for Angular

First get the Angular.js and Twitter Bootstrap through the Nuget Package Manager Console:

Install-Package angularjs
Install-Package bootstrap

Then, create a folder named ‘app’ with the following subfolders:

Then drag the css and angular etc to this new folder structure, like so:

2013-11-02 12_02_23-AddressBook - Microsoft Visual Studio

In case you are wondering why I am doing this. When I first started to look at Angular, I used Angular-seed as a boilerplate. I think that is a good startingpoint for organizing code.
Further, the Web API has nothing to do with the client code I’m going to write. I will not be using ASP.NET MVC routing and views with Razor, instead I will be using the routing and the controllers from the Angular framework. So that explains the separate ‘app’ folder in the project.

We need to configure the AddressBook application to start in the app folder though:

2013-11-03 09_45_19-AddressBook - Microsoft Visual Studio

I’ve also changed to port to 8000 so it’s easier to remember.

A little bit of Angular background info

This is a good introduction to Angular by Dan Wahlin. Be sure to check it out.

Angular uses modules to specify how a web application should be bootstrapped.
Modules break an application up into functional sections. For example, services, directives, controllers and filters that are specific to a particular application can be added to the application module.
Ehm.. What does that even mean!?
Well, controllers for front-end development serve a very similar purpose as controllers we know from ASP.NET MVC. Controllers present data to the views, via a scope. And Angular services are singletons objects or functions that carry out specific tasks common to web apps. A typical task for a service would be fetching data from a server.

At Thruzero I found a very good explanation of the Angular architecture:
Angular architecture

Getting started

In /app/js create a javascript file named app.js.
I will be adding all the javascript in there because this app is very trivial. Later I will break it up in several files (javascript files for controllers, for services etc.).

Let’s first declare the module:

var addressbookModule = angular.module('addressbookModule',[])

The ‘[ ]’ array thing is very important, because later we can inject other modules into this array.

Next we can add a controller to the addressbookModule. The first argument is the controller name,’WelcomeController’ and the second argument is a function, in which we pass in a $scope.
The scope is the ‘glue’ between the controller and the view. We can give the scope properties in the controller which will be presented to the view.

var addressbookModule = angular.module('addressbookModule',[])

addressbookModule.controller('WelcomeController', function ($scope) {
    $scope.title = "Welcome to your AddressBook";

Finally, this is the view (/app/index.html):



This is the result:

2013-11-02 13_32_13-Mozilla Firefox

What we just did:

  • We wired up Angularjs in our application by adding angular.js to our html file
  • We created a module named AddressBookModule as an Angular module.
  • Now we can chain Angular functionality to this module (routing, services, controllers etc).
  • We added a Controller.

It took a while for me to grasp all this. If you’re coming from a C# world the whole Javascript syntax is already confusing enough. All these ‘function() { }’ curly braces, hooks and semicolons confuse me. And if you forget to put a }); well then it just doesn’t work.
You can have anonymous functions with 30 miles of arguments!

The solution is: practice, practice, practice. Make stupid mistakes and blog about it.

Next time we’ll add some CRUD.

Getting started with ASP.NET API with MongoLab part 3

This is the sequel to this post
We will be using MongoLab as a backend for our Web Api.

We are using the AddressBook again in this example, but for clarity we’re building it from scratch.

Creating the MongoLab database

Head over to MongoLab and create an account!

  • First create a new database. Make sure you choose the free plan. Name the database ‘addressbook’.
  • Click to create a new user.
  • Add a new collection (equivalent for a table) named persons.

Please take note of the connectionstring:

2013-11-01 08_12_03-MongoLab_ MongoDB-as-a-Service

Setting up the Web Api project in Visual Studio

Fire up Visual Studio 2013 and hit File -> New -> Project.
Choose Empty ASP.NET Web Application with a Web API and name the project AddressBook.

2013-11-01 08_07_48-New ASP.NET Project - AddressBook

We must install the Mongo Csharp Driver:

Install-Package MongoCsharpDriver

Now open App_Start\WebApiConfig.cs and add json formatting to it (see my previous post why):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace AddressBook
    public static class WebApiConfig
        public static void Register(HttpConfiguration config)
            // Web API configuration and services

            // Web API routes

                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }

//This section you need to add:
            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

Connecting to the MongoLab

Let’s not reinvent the wheel if you don’t have to. This article is a great introduction to Mongo and C#. I borrowed their MongoConnectionHandler.

using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AddressBook
    public class MongoConnectionHandler
        public MongoCollection MongoCollection { get; private set; }

 public MongoConnectionHandler()
            const string connectionString = "mongodb://";
            //const string connectionString = "mongodb://localhost:27017";
            //// Get a thread-safe client object by using a connection string
            var mongoClient = new MongoClient(connectionString);

            //// Get a reference to a server object from the Mongo client object
            var mongoServer = mongoClient.GetServer();

            //// Get a reference to the database object 
            //// from the Mongo server object
            const string databaseName = "persons";
            var db = mongoServer.GetDatabase(databaseName);

            //// Get a reference to the collection object from the Mongo database object
            //// The collection name is the type converted to lowercase + "s"
            MongoCollection = db.GetCollection(typeof(T).Name.ToLower() + "s");

The Person class

I want the Person_Id to be the same as the document id, so I can retrieve documents easily. I’m not sure though if this is best practice. But it works.

public class Person 
        public Person()
            Person_Id = ObjectId.GenerateNewId().ToString();

        public string Person_Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Phone { get; set; }
        public string Email { get; set; }
        public string Blog { get; set; }
        public string Facebook { get; set; }
        public string Twitter { get; set; }
        public string LinkedIn { get; set; }
        public string Googleplus { get; set; }

And here’s the POST method:

public class PersonController : ApiController
        public MongoConnectionHandler collection = new MongoConnectionHandler();

        public HttpResponseMessage Post([FromBody] Person person)
            var response = Request.CreateResponse(HttpStatusCode.Created, person);

            string uri = Url.Link("DefaultApi", new { id = person.Person_Id });
            response.Headers.Location = new Uri(uri);
            return response;



You can use the API with Fiddler.

2013-11-01 14_33_36-Fiddler Web Debugger

Look at the results it has returned:

2013-11-01 14_35_25-Fiddler Web Debugger

It returned the new URI with the new Id as you can see.

Now let’s check MongoLab, and lo and behold:

2013-11-01 14_39_53-MongoLab_ MongoDB-as-a-Service

Here’s the remainder of the CRUD methods:

        public IEnumerable Get()
            return collection.MongoCollection.FindAll().AsEnumerable();


        public Person Get(string id) {

            //var query = Query.EQ(p => p.Person_Id, id);
            return collection.MongoCollection.FindOne(Query.EQ("_id", id));


        public void Delete(string id)
            collection.MongoCollection.Remove(Query.EQ("_id", id));


        public HttpResponseMessage Put([FromBody] Person person)
            var p = collection.MongoCollection.FindOne(Query.EQ("_id", person.Person_Id));

            if (p != null)
            return Request.CreateResponse(HttpStatusCode.OK, person);

So, that works.
Next time, let’s consume this WebApi with Angularjs.

And here’s all the code: here

I have changed ‘Person’ to ‘Contact’ in the sourcecode