Huge library hallway filled with books

Dev Diary S01E09: Implementing Azure Document Db and MVC WebAPI


Finally we are getting to the point where we are calling into Azure Document Db.

In the last post we built the application so that it was talking to the Web API which stored the invoices as in memory objects.


So Azure Document Db?

Right then so let’s talk about Azure Document Db. I found the following resources really useful when learning about Azure Document Db:


Azure Document Db Architecture

The diagram below shows the architecture of the Azure Document Db, we have an Azure document db account. Within the account there are databases and within a database are collections which contain the JSON documents inside.


diagram referenced from


Azure DocumentDb Account

This is the guide that I used for creating my Azure Document Db account.

The approach is to login through the Azure Portal:

  • Click on DocumentDB Accounts
  • Click Add
    • Provide an ID
    • Subscription
    • Resource Group
    • Location (suggest choosing the nearest data centre)
  • Click Create

In a few moments your Document Db will be created! Smile



Install Azure Document Db Nuget Package

Before I could get coding I needed to add support for DocumentDb to my MVC project.

This was achieved by adding the Azure Document Db NuGet Package: Microsoft.Azure.DocumentDb

Once installed, this added all the appropriate references and assemblies to my project.


Connecting to the Azure Document Db Database with DocumentClient

The DocumentClient is the gateway into the Azure Document Db, it provides a way for us to connect to the Azure Doument Db instance.

When creating the DocumentClient object, it requires the following parameters.

  • Uri – represents the endpoint for the Azure Document Db
  • SecureString – represents the key to access the document db system.
  • ConnectionPolicy – this allows you to decide how to connect to Azure Document Db. I used the ConnectionPolicy.Default option however there are gains in performance by using a Direct Connection Mode. More information can be found here:
  • ConsistencyLevel – this parameter provides details on how the database works and how data become consistent. The Azure Document Db is a distributed database and therefore there is a compromise between availability, performance and data consistency. There are four different types of consistency available, I generally use session consistency. To find out more about the different consistency levels and how they work.

Anyway, lets  create the Azure DocumentDb Database.


DocumentDB Databases

The Azure Document Db Database is stored in an Azure Document Db account and it is a storage container which contains Collections and Users.

The way that we create a database is use a method on the DocumentClient called CreateDatabaseAsync.

This function is called with an Id parameter which provides the name of the database.

Once the database has been created then subsequent calls to access the database use the DocumentClient method ReadDatabaseAsync().

This function requires a Uri which is created using the UriFactory.CreateDatabaseUrl() function by passing in the name of the document id.

Now that we have the database, we need to create the collection where our documents will be stored within the database.


DocumentDB Collections

The last piece of the puzzle when it comes to Azure Document DB are the DocumentDB Collections. These are containers which store JSON documents.

When we are creating a DocumentDB Collection we need to think about a couple of things:

  • IndexingPolicy – this provides information about the type of data that is being stored and therefore the type of indexing that is possible with this data. Also the IndexingPolicy provides a choice around how consistent the data is. We will go into this in more detail later on in the article.
  • RequestOptions – these options are used to denote how much throughput the DocumentDb Collection can support. This will also have an effect on the cost of the DocumentDb Collection. There are a number of different options each with a maximum number of Requests Per Second. Currently, I am using the smallest amount of 400RPS
  • Data Structure – if we need serious performance we may need to shard our data so that we can get the required request per second. Each DocumentDb Collection has a restriction on the maximum throughput. If that throughput is exceeded then the call will be rejected with an HTTP Status of 429. In the response there is a header added x-ms-retry-after-ms. This provides details of the number of milliseconds that should be waited before retrying the call into the DocumentDb Collection. Therefore, this will need to be factored into the design of the DocumentDB if the maximum of 5000RPS is going to be a bottleneck.

Anyway, with all these we need to describe the process of creating a DocumentDb Collection. The code base is simlar in structure to the creation of the DocumentDb Database.


Indexing Policies

Indexing Policies are really interesting and will have an impact on a number of areas. These include performance and storage costs.

The type of index will denote the type of actions that can be performed on data:

  • hash index – provides the ability to equality
  • range index – provides equality and other filters such as more than or less than

Another capability of an Index Policy is to configure the latency when a change is made to the document collection. Either the write to change the document is waited for (sync) or it is not waited on (async)

  • Consistent – the write process is synchronous and is waited for before the update is completed
  • Lazy – the write process is asynchronous and the is not waited for before control is retuned back to the process that performed the update
  • None – no index is associated and with this then document can only be accessed via their id

There is a lot more to index policies and more information on indexing policies can be found here:



The following section discusses how we bring all of the above together and implement our Azure Document Db. As I write this, I need to say that this was my first attempt and it will need some refactoring. We will pick that up in a subsequent post as it will be good to explain that process!


Data Model

So the first step was to create the classes to connect to the Azure Document DB Account.

A folder called DataAccess  was created in the Invoice WebApi project. There were three classes created:

  • DatabaseConfig – used to load the configuration used to connect to the Azure Document DB account
  • InvoiceDatabase  – this is used to create and connect to the Azure Document Db Database
  • InvoiceDocumentCollection – this is used to create and connect to the Azure Document Collection within the Database
  • InvoiceDataContext – this wraps all the Azure Document DB entities into one class. This includes the InvoiceDatabase and InvoiceDocumentCollection so that they are initialised and created.

All the three Invoice Database classes follow the same pattern. That is they implement a singleton pattern which is accessed via a GetCurrent() function. This function returns the singleton instance of the object wrapped up by a Task<> object.

This approach was used to implement a suitable pattern for use with asynchronous calls. All the Azure Document Db functions such as ReadDatabaseAsync are as the name suggest asynchronous calls.

With my initial implementation I had issues with blocking of the async call.  The thread never got the chance to return the result back from the async method and the thread hung. I had no idea what was going on and thought it was some issue with Azure DocumentDb.

I found the following articles useful in helping me to understand what was happening and why these deadlocks were occurring:

The key takeaway that I got from these articles is if you are going to call into ASync functions then try and make everything asynchronous!

Anyway, now it is time to talk about each of the implementations.


Database Config Class

This class provides the mechanism to load in the Azure Document Db configuration used by the application.

I will be looking at how we can move the storage of the configuration out of the web.config so its centralised and more secure. Plus it will make life easier for keeping my code in GitHub too Winking smile.


Invoice Database Class

This class provides the implementation used to ensure that the Database is created if it does not already exist. It also ensures that the Azure DocumentClient is created and setup using a singleton pattern. The singleton pattern ensures that the connection to Azure Document Db is created and exists for the lifetime that the WebAPI is loaded.

The implementation of the InvoiceDatabase object is shown below:


As mentioned previously, the pattern for this InvoiceDatabase class is to provide a static method GetCurrent()  which will return a Task<InvoiceDatabase> parameter because the calls to the Azure DocumentDB Database layer are asynchronous calls.

The code will attempt to read the database, if this fails then the database will be created.



The InvoiceDocumentCollection class is implemented as shown below:

Again in a similar approach the pattern is to have a static method called GetCurrent() which creates an instance of the object if it does not already exist. The constructor calls into an Initialize() method which ensures that the Document Collection is there, even if it has to be created.

It is within the DocumentCollection that we define the IndexingPolicy for string content and also the number of requests that can be processed at one time. In this code base we are using 400RPS which is the minimum.



The InvoiceDataContext class is implemented as shown below:


This object is the wrapper for all things Azure Document Db in this solution. The code follows the same pattern as before. It has implemented a GetCurrent() function which returns back a Task<InvoiceDataContext>.

The function will get the current database configuration, get the current InvoiceDatabase instance and along with the database, get the current InvoiceDocumentCollection.

Please notice that the Initialise() functions which have no data to return are returning back ask objects with no return data type specified. This is rather than using void  which seemed to cause issues with the code locking.


Now that we have covered the core Azure Document Db classes in this project, lets talk about the implementation of the system.



The Invoice Repository has changed to implement the calls in Azure DocumentDb.


Please note: the implementation for the Update function has not been completed yet. This is so that I can show you later an issue which I had when trying to update a document in Azure.

So lets have a look at how the Invoice Repository is now setup. First of all the repository has a couple of new private member variables:

  • InvoiceRepository – this is our singleton instance of the repository
  • InvoiceDataContext – this is an instance of the object InvoiceDataContext which will be our gateway into the Azure DocumentDb.
  • List<InvoiceForm> – this now redundant and we will remove later on

Let’s talk about how we get data. So we have a GetAll() function which returns IOrderedQueryable<InvoiceForm> this allows us to decide when we want the query to execute and provides additional commands via the Azure Document Db Linq provider, Microsoft.Azure.Documents.Linq to decide the data we would like.

The point that we make where we can decide when the query is executed is really important. If we were to get all the data by calling .ToList() on the entire dataset this would cause the Azure Document Db to download all the data from the database, which could be rather slow!

The Document Collection is accessed by creating a System.Uri using the DocumentCollection’s AltLink property to call into the Azure Document Db to create the DocumentQuery object using CreateDocumentQuery  as the code as is shown below

All of the other data retrieve function such as Get(string reference) makes use of the GetAll() function as a repeatable function.



The Invoice Controller represents the WebApi for accessing the data through into Azure. The implementation is shown below:

The InvoiceController has been changed to now include a private member field to hold the InvoiceRepository  object.

The InvoiceController WebApi calls have now been changed to return Task<> objects so that they can be used in an asynchronous way. The InvoiceController needs to be Initialised() before each call is made into the repository. This is to make sure the DataContext object in the InvoiceRepository is  valid and created correctly. When using the API we found in testing that the DataContext object would become invalid. I will be looking into this in more detail to see if there is a reason why this might be happening.



Setting up the web.config

I made some changes to the web.config to incorporate the new settings required. The changes have included the configuration of the Azure Document Db system. These include the following settings:

  • Document Db Url
  • PrimaryKey
  • SecondaryKey
  • DatabaseId
  • DocumentCollectionId

We will be looking to move these out of web.config and into some other configuration container so that we can change these settings without having to redeploy our code. Also it makes this blog series easier as I do not have to keep moving the configuration out of the code base before I upload the source code into GitHub.


The configuration information can be found here:

Primary and Secondary Keys



Document Db Url is found on the Azure Portal,, in the Document Db Account section.




Performance Tips

The Microsoft team provide some great tips for improving performance with Azure Document Db.

One of them is related to DocumentClient. They suggest that you create one DocumentClient instance as a singleton. This is then reused throughout the lifetime of your application’s instance.


Azure Portal Tools for Document Db

Some of the tooling is very nice in the Azure Portal and Azure Document Db is one of them.

I found the ability to browse the data via the Azure Portal very useful, to access your DocumentDb data do the following:


  • Select DocumentDB Accounts
  • Choose your DocumentDb Account


  • Select your database


  • Select a Collection


  • Click on Document Explorer


  • Select a document


  • You can now see the JSON object in the viewer
  • It is possible to make changes to the data via this window too

There are a number of other features but this should get you started and help you explore the data in the database.


Source Code

The source code that accompanies this blog post for the Web API project can be found here:


Conclusion and Next Episode

I did have a few problems and by far the biggest one I have already mentioned, is the Async and Await issues. I would definitely recommend reading Stephen Clary’s articles.

The other thing that did take me sometime to get my head around are the different links. Each link is a URI and every object in Azure Document Db has a path to reference it by. It is important that you learn about these. I will talk about these in the next post.

At the time of implementing the Azure Document Db side I did have some problems with updating documents. However, I have talked enough in this post and will take you through those issues and also introduce to Application Insights. I hope that  you can join me.

Use NPM and gulp build tasks to support Continuous Integration with VSTS and Azure for an AngularJS app

Interesting stuff from Matt, will have to incorporate this into the Invoice Form Application.



This is the first in a series of posts will take you through the steps required to take a static website, in my case an Angular SPA and deploy this to an Azure App Service (Web App) via Visual Studio Team Services (VSTS). The Angular SPA is secured by ADALJS and the last part of this series will help us use gulp tasks within VSTS to configure the Angular app for different environments.

The application is built using Visual Studio Code all in HTML and JavaScript, so no Visual Studio and no VS builds. The aim is that when we check code into VSTS source control a build task will run and deploy this into Azure for us. Although my app is written in Angular, only the last post makes actual reference to this and shows anything Angular specific. Your app could be written with any framework you like…

View original post 470 more words


Dev Diary S01E08: Fleshing out the Angular and Azure Web API components



In the last post we talked about me deleting the Azure Application by mistake! In this post we will flesh out our Azure Web API so that we can start to add, edit and store our Invoices in the API layer. We are not quite ready to start implementing the Azure Document Db side yet, that will be in the nexr post.

Let’s get started!


Implement the Invoice API

So I am going to implement the Invoice API using a new Web API Controller, the InvoiceController .

In this initial version, the InvoiceController has implementations for getting all the invoices, get a particular invoice with its reference and add a new invoice and update an existing one.

The guts of the InvoiceController works with an Invoice Repository which has been implemented with the Repository pattern. .

Finally, we need our plain-old CLR objects (POCO), which will represent our Invoices.


Invoice Controller

So firstly, I created an InvoiceController in the Controllers folder using the WebAPI item template.

The code for the InvoiceController.cs is shown below:


Invoice Repository

Next, I created the InvoiceRepository class in a Repositories folder. The repository has been implemented so that it returns a list of Invoice objects.

The InvoiceRepository.cs implementation is shown next:


Invoice Entities and the Special Case Pattern

The Invoice entity is implemented as a new class held within the Models/Entities folder. The Invoice Poco class has all the fields which are used to hold the information related to the Invoice.

The code for the invoice.cs is shown below:


The special case pattern is a approach that I use in most of my applications. The objects have an Exists field which can be used to check whether the object has been found.

This approach helps to avoid using nulls which can be ambiguous when returning data from a particular method. I implemented the InvoiceNotFound  class special case.


Json camelCase formatting

One of the things that we need to do is make sure that the WebAPI formats the JSON in the right way. For JavaScript the right format for an objects properties in JSON is camelCase, where the first letter of the object’s property name is lower case and each subsequent word starts with an upper case.

For example:-

CustomerRelationshipNumber becomes customerRelationshipNumber

So how do we set this up with Web API? Well we needed to do a little tweak to the WebAPIConfig.cs file. This is how it looks:

The code sets up the Json Serialisation so that it uses a CamelCaseFormatter to resolve the property names on objects. This is applied globally.



Update the Angular Application to call the Invoice API

Now that the Invoice Controller is implemented in the WebAPI, next I started on the Angular client so that it calls into the API.


invoiceDataService.js – calls into the API directly, the code is shown below:

The invoiceDataService calls into a shared function executeSave() which will serialize the data being passed into it. Depending on the type of operation on the data, add/update etc then a different method is used.

POST – used to add a new object to the data through the API

PUT – used to update an existing object through the API


InvoiceControllers.js – implements the list invoices and add invoice controllers which call into the invoiceDataService. The code is shown below:


app.js – changed to add the modules for these new files

Also we added new routes for the add, edit, view invoices.


Update the List Invoice View to allow editing of the Invoice

So now we have the ability to view a list invoices from the GetAll() function of the InvoiceController.

We should allow a user to view and edit an invoice. This is implemented by the following changes.

list-invoices.html – the code is shown below:

The list-invoices.html now has an event to respond to an onclick event. This passes through the current invoice.reference of the record so that we are editing the right Invoice.

This calls into the updated controller, which exposes the function showInvoice()  on the $scope object. The function uses the $location service to change the Angular view to #/invoice/{reference]/view which will in turn direct the user to the view-invoice.html page.

We will discuss that bit of the solution next.


Another view was created called invoice-display.html, this is the code:

The code above represents the display invoice view, a bit of a mouthful I know. To be honest I am not sure why I did it this way but hey ho. I mean, there is no need for a view for new, edit and view Invoice. I will come back and refactor this in a later episode.

This view has got an edit button, which will allow us to transition and edit the invoice. This calls into the viewInvoiceController.editInvoice() function.



Another view was created for edit-invoice.html  this is the code:

The code above represents the edit invoice view. This allows a user to make changes to the invoice and then save those changes back by calling into the Invoice Controller REST API.

The code is structured in a similar way to that of the edit Invoice and add Invoice.

On a successful save then the user is returned back to the list of invoices.



The following problems were experienced whilst building out this portion of the application.

Error when viewing the invoice due to issue with routing

Error: {“message”:”The request is invalid.”,”messageDetail”:”The parameters dictionary contains a null entry for parameter ‘id’ of non-nullable type ‘System.Int32’ for method ‘Itsp365.InvoiceFormApp.Api.Models.Entities.InvoiceForm Get(Int32)’ in ‘Itsp365.InvoiceFormApp.Api.Controllers.InvoiceController’.

The cause of this was my WebApiConfig.cs. Which setup a route:

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

Unfortunately, this did not resolve to the function

InvoiceController.Get(string reference);

bur rather the function

InvoiceController.Get(int id);

The following change was made to fix the routing:

name: “DefaultApi”,
routeTemplate: “api/{controller}/{reference}”,
defaults: new { reference= RouteParameter.Optional }


Method HTTP Status Code 405: Method not allowed

This error message was thrown when I added the edit Invoice feature. The edit invoice feature when it saves, calls into the API using an HTTP PUT method. The call fails with a message saying that the Method is not allowed.

In turns out that this issue was very similar to the routing error just mentioned.

The default route was changed to:

name: “DefaultApi”,
routeTemplate: “api/{controller}/{reference}”,
defaults: new { reference= RouteParameter.Optional }

Therefore, the routing was expecting to the PUT method to have method signature such as:


Update(string reference, [FromBody] invoice)

but we had:


Update(string id, [FromBody] invoice)

Making the change to the function to correct the name of the first parameter from id to reference resolved the issue and the save button worked correctly.


This episode we added support to add/edit and update our Invoices through the MVC Web API. This involved additions to both the server side WebAPI and the Angular client side.

We had a few problems which have been explained.


Here are the screenshots showing the changes in action:





The repository for the Invoice Form App Client can be found here:


The repository for the Invoice Form App API can be found here:


Next Episode

In the next episode we will start to actually do some Azure Document DB. The WebAPI will be modified and we will implement the calls into Azure Document Db.

Thanks for reading, I hope you can join us for the next session!


Dev Diary S01E07: Deleted Azure Apps, 401, Reoccurring Client Id and Publishing Settings



So in our last post, we talked about setting up the Visual Studio 2015 C# MVC WebApp project. This application is going to be our API for communicating with Azure DocumentDb.

Now this post talks about a mistake I made and the fall out of that mistake.


The Mistake

So I made a big mistake, I am not sure what I was doing or thinking but I was cleaning up the Azure Active Directory applications. By mistake, I deleted the Azure Active Directory application for our API application!


So what did I do to resolve this, well I created a new Azure Application which of course created a new ClientId and Password.

I then went through recreating the application as I remembered. I then updated the ClientId inside the web.config for the MVC Web API application.



401 Unauthorised Exceptions

Now unfortunately these changes did not work. For some reason I kept getting 401 Unauthorised exceptions when trying to access the API.

This was massively frustrating and I spent a few hours trying to resolve the issue.

There were various things that I looked at. I will be honest I can’t remember all the things that I tried but I did update the Client Id and Password a couple of times, in case I did it incorrectly. This was achieved by deleting and recreating the Azure AD Application.

However, the approach that started to give me some results involved using the “Server Explorer”  in Visual Studio.


Server Explorer to the rescue

The Server explorer is pretty cool, I used it last episode to attach and debug the Web App API. This time, I used the Server Explorer to browse the file system in the cloud.



I ended up looking through the file system and opened the web.config. I was  checking the settings and it was then I noticed that the Azure App Client Id was set to the deleted Azure App Client Id rather than my new one.

If I changed the Client Id in the web.config and save it via the Server Explorer then the application would start to work and the client could authenticate successfully against the API!

However, as soon as I published the application it would stop working!




What’s going on? Why won’t the ClientId die?

I used the find tool  (ctrl+ff) in Visual Studio and searched for the old App Id. I ended up finding it in the .pubxml  file!

Ahh, so every time I publish the application, it would reconfigure the web.config file and incorrectly setup the Azure Application’s Client Id, that makes sense!

Expanding the Project->Properties->PublishProfiles folder, I found the .pubxml file.

I updated the <ADClientAPPID> element value to the new Azure AD and then published the application into Azure.

The next thing that I had to do was update the Angular client Azure application and make sure that it had access to our newly created Azure Application for the MVC .NET application.

This was achieved by browsing on, browsing to the Active Directory section. Clicking on the Azure aplication related to the Angular Client and adding the permission to the client for the new application.



Do not delete the Azure AD application!! Smile

if you do make sure you check your publishing settings and also update any Azure applications that use it.


Next Episode

In the next episode, we will start building out the API so that we can store and save Invoice objects in our API layer rather than just using the client side JavaScript.

I hope you found this post useful, to be honest I hope you don’t as that way I know you haven’t deleted your Azure Application by mistake! Winking smile


Dev Diary S01E06: Azure MVC Web API, Angular and Adal.JS and 401s


In my previous post, we discussed how to implement Adal.JS into your Angular application. This allows us to use Azure Active Directory as our authentication mechanism.

In this post I am going to go through and create the MVC Web API which we will then start to call from our Angular client to manipulate the Invoices.


Creating the MVC Web API Project

Right then, so first of all we need to create an MVC Web API Project. There are lots of guides out there such as this one on the ASP.NET site.

Anyway, I fired up Visual Studio 2015.

  • File->New Project
  • Chose the Visual C# ASP.NET Web Application template
  • Created an MVC 4.5.2 template Web Application


  • Selected the folders and core reference for MVC and Web API
  • Selected to “Host in the cloud”
  • Then clicked Change Authentication
    • Clicked on Word and School Accounts
    • Choose Single organisation and selected my domain
    • Also selected Read Directory data option


  • Now click Ok
  • Clicked Ok to start creating the project

Next, you are presented with a screen to start configuring your App Service.

So I setup an appropriate name for the Web App

  • appropriate Web App Name
  • Choose my subscription
  • Chose Resource Group
  • Chose App Service Plan
  • Clicked Create

Visual Studio then worked its magic and created the Project with all the Azure services behind the scenes.

Then it setup the Organizational Account and App Insights. Once this was all completed we have a working Azure Web Application and are ready to start adding the Web API components.


Configuring Azure AD Authentication for the WebAPI Application

To be honest I was a bit surprised that I had to do this next step but when I was trying to find the application in Azure AD, I could not find anything. Also I could not find anything in the project either related to Azure AD.

So to configure Azure AD Authentication for the WebAPI application I had to do the following:

  • Right-click on the project
  • Choose “Configure Azure AD Authentication”

This fires up the Azure AD Authentication wizard

  • Click Next
  • Under Single-Sign-On
    • Choose your domain
    • Provide an appropriate App ID Uri.
    • Choose create a new Azure AD Application
    • Click Next
  • Under Directory Access Permission
    • Select Read Directory Access is not already enabled
    • Click Finish

This will start a wizard which will set everything up. The end result is visible in



Adding the WebAPI Components

We have a .NET MVC WebAPI project with very little in it.

Let me explain what I did next, so I would like to have two services for the first phase.

  • Configuration Controller – used to get the system and user configuration for the application.
  • Invoice Controller – used to add, edit, remove and list the invoices found in the application.

What we will do is create the Configuration service with a simple stub, firstly with no authentication so that we make sure it works and then we will make changes to the WebAPI layer so that it requires authentication.


I created the Configuration Controller. This was achieved by the followingNyah-Nyah

  • Browsed to the Controllers folder
  • right-clicked Add->Web->Web API->Web API 2.1
    • ConfigurationController.cs
  • Modified the initial code so that it looked like this


Next, we need to deploy this code to Azure and try it out.

I published the project to Azure by doing the following:

  • Right-click on the project –> Publish


  • Next choose Publish from the wizard

This will start the publishing process and push the code up into Azure.
Oh dear, this did not go so well and I received the following screen:


I ended up having to switch on customErrors as recommended by the error message. It turned out that there was a reference to the System.Spacial.dll. The project did not need this and removed it from the project references. The site was published and then ended up with the following screen.


I accepted the request for permissions and then was redirected to http://localhost which failed to work as I was not debugging the application.

Third time lucky, this time I ran the project using F5 and it all worked nicely, redirecting to http://localhost.

Just in case you do not believe me, I took the screenshot below:



We can also see that our API is working by browsing to https://localhost:44356/api/configuration and we receive a block of Xml as shown below.


Ok, now that we have the service up in the cloud, lets update Angular to consume it.


Update Angular client application to consume WebApi

So I thought I would update the Angular application, add a new page for settings. Firstly, the page would just load in the configuration but eventually this page will allow users to setup and configure the settings for the application.

In order to be able to consume the configuration api endpoint, I needed to do a couple of things to the application.

  • create a new view called settings.html
  • create a new service called configurationService.js
  • create a new controller called settingsController.js
  • configure the app.js to load these new modules
  • configure the index.html to load the scripts

So lets go through each of the components, starting with the settings.html page


Next, we have the settingsController.js


Lastly, we have the configurationService


We have the guts of the changes required, of course we need to link these pages into the application.

So the app.js needs to be updated with the new route for the settings page. Also we need to setup the configurationService.


Also the index.html needed to be updated so that we have a link for the settings page.


Phew, that is quite a big change, so lets go and try this out.


I browse to the application and click on the settings button.


Unfortunately, I get an error and looking into the browser developer tools we see the following message:

XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 404.


Cross-Origin Resource Sharing (CORS) issues

So, what is going on?

Well we haven’t allowed the API to be able to process requests from domains that isn’t its own. The way we do that is through CORS configuration within the WebAPI.

To get this to work we need to configure the WebAPI by

  • Installing the Microsoft.AspNet.WebApi.Cors NuGet Package (current v5.2.3)
    • Not the Microsoft.AspNet.Cors NuGet Package (this does not give you the assembly System.Web.Http.Cors).
  • Modify /App_Start/WebApiConfig.cs

Now,its able to call in and get the configuration settings correctly!



Switching on Adal.js

We have proven that we can talk to our MVC Web API endpoint. So that is good news but now I had to get it to authenticate through Azure AD, get a access token and use that when making requests to the API.

Fortunately, Adal.js comes to the rescue here and a lot of the heavy lifting is done for you!

So let’s have a look at this. This bit did take me a while and I will explain why a little later. Though the following people and posts really helped me get to understand how Adal.js handles authentication when  authenticating against different endpoints.

First, we need to tell Adal.Js about the endpoints that will require authentication and we need to provide a way to map those endpoint URLs to resource name.

So to do that we configure the endPoints object when setting initialising the Adal library. Currently this is being setup by the following code snippet in app.js :-



The important part of this is the endPoint array object. This is an array of objects where you have the URL associated to the application Id Uri.

If you remember that is this section of the application configuration in Azure Ad.


Once we have that value we need to associate the APi Url to the App Uri Id.

This allows Adal.JS to provide the right resource id when requesting an auth token.


Turn on Authentication in our Web API layer

So now we have Angular configured to authenticate against Web API with Adal.js. We just need to switch on authentication for the Web API layer.

This is pretty straightforward and requires the addition of the [Authorize] attribute to our Web API Class or Methods. The change is shown below:


A recompile of code and Publish now allows us to test the changes out.


HTTP 401s and Debugging Azure WebApps

So I thought I had everything setup to allow the Angular application to authenticate against the Web API. Unfortunately I was seeing 401 Unauthorised when using the browser’s development tools.



After quite a lot of trying things out, I was stumped so I tried out debugging the WebAPI code running on Azure. Fortunately, Azure has some pretty cool development debugging tools.

To start debugging the API, I had to fire up Server Explorer. Apparently you should be able to use Cloud Explorer in Visual Studio 2015 but I have not been able to get this to work.

To debug your application do the following:

  • View->Server Explorer
  • Expand the Azure node in Server Explorer
  • Expand the App Service node in Server Explorer
  • Expand the resource group
  • Right click on the App and choose “Attach debugger”


The debugger takes a few moments to organise itself but eventually it will attach.

Now we can setup our breakpoints and start debugging the application. I put a breakpoint in the startup.cs file on the ConfigureAuth(app)  line within the Configuration function.

Even when I had the debugger running and tried to access the application, at no time did the breakpoint get picked up.

So what is going on?

I looked at the Azure configuration for the API application and made the following changes:-

  • Added a reply url for the Angular application which is currently being run using http://localhost:8080
  • Added an application permission so that the application can read directory data

This had no effect and I was still getting the error.


Examining the Angular Azure AD Application Configuration

Next I thought I better make sure that Angular is sending over an authentication token when making the request to Azure. For more information, watch this brilliant video on OAuth: Deep Dive into the Office 365 App Model: Deep Dive into Security and OAuth in Apps for SharePoint


I used the browser development tools and set a breakpoint in the settingsController.js on line 14 which is where the error is processed.


When the breakpoint is reached then we could look at the response object, fortunately the response object is pretty detailed and it has a config object which provides information about what was sent with the request. We can see here that there is a header object, now this should have an Authentication header with a Bearer token. There is not one, so what is going on? It must be our Adal Angular configuration.


Immediately when I saw this, I thought ah maybe its our endPoint configuration. There is a function as part of the Adal Angular service object, in our code that is adalService. This function is called getResourceForEndPoint(), this function will return back the App Id Uri based on a provided URL. Now interestingly, when this function was called with the following argument:

  • adalService.getResourceForEndPoint(“”);

This function returned null. This is very strange as our endPoints are configured. After a lot of playing about I realised my error. The configuration of the adalService is performed in app.js.

The problem was the object name given for endPoints. The object name should be endpoints. So the updated app.js  was changed to the following:


Now that we have this change made, I tried to login but got the error that the application could not reply back to the URL http://localhost:8080/app/

The fix was made to the Azure Application for the Angular client app, itsp365.invoiceformapp.client, by adding http://localhost:8080/app to the list of Reply URLs.



Whilst looking at this page, I realised that the client Angular application did not have any permissions to access the API Azure application. So to fix this, I added a new permission, chose the application:


Once this was added then the delegated permissions to access the application was given.

If we had not set this permission we would have seen the following error when trying to access the API application.

“response = “AADSTS65001: The user or administrator has not consented to use the application with ID = ‘{clientid}’”


So, actually these two changes really started to make a difference. Now when I accessed the settings view, we received the following error:

“AADSTS70005: response_type ‘token’ is not enabled for the application ↵Trace ID: 2c370e50-63ff-41e1-8cc1-fe90c8ef7b98 ↵Correlation ID: 0d1dd4db-cc4f-4bc1-b7c6-54812dfc3142 ↵Timestamp: 2016-05-14 21:35:39Z”

This requires the application manifest to be modified to enable something called the oAuth2AllowImplicitFlow.



This setting is changed by browsing to the itsp365.invoiceformapp.client Azure Application:

  • scroll to the bottom, click “Manage Manifest”
  • Click Download Manifest


  • Open up the downloaded file, this will have the filename of {clientid}.json, I use VS Code to do this.
  • Find the line below and change the false to true.image[27]
  • Save the file and then back on the Azure Application page choose Manage Manifest and click Upload Manifest

Wait for the manifest to be uploaded and processed.

Now when I made this change I kept getting the error “response_type token is not enabled…”. So I opened up the browsers settings and deleted the site cookies. This deleted the Azure AD authentication cookies and when I next opened up the Angular application I had to login. Now accessing the settings page, it worked!

So if you make changes , either do what I did above or run the browser in incognito mode to force an authentication.

Now the call to the configuration service API was successful!


Quick Refactor of the Application Constants

After I did everything, I was not happy with the way that the applicationConstants were part of the configurationService. This does not make sense so I moved them into their own folder and file. A file was created in /app/common/constants.js

The constants.js file had a new module called “applicationConstantsModule” and this defined the constant, applicationConstant.

You can see the code below:


I then had to update the index.html to load the /app/common/constants.js and also tell the invoiceFormApp to load the module, applicationConstantsModule within the app.js file.


With those changes made the refactoring is done.


Source Code

The source code for this blog post can be found in the following GitHub repositories:-


So now in this episode we have an application which has a basic REST API which is secured by Azure AD. We have made it possible for the Angular client to be able to authenticate against the REST API endpoint.

I hope you found this useful and there are some good resources for troubleshooting.


Next Episode

In the next episode, I will talk about my big mess up where I deleted the Azure AD app by mistake.

Thanks for reading, as always I would be interested in hearing what you think. Are these instructions useful, do they make sense?



Azure Active Directory Logo

Dev Diary: S01E05: Angular App – Setting up Azure Apps and ADAL.JS


In the previous post we setup a page to add an invoice, adding the controller to manage that process. We explained in a bit more detail about the difference between factories and services. Hopefully, the explanation helped and made sense.

Anyway, today we are going to go and create our Azure Application, talk about setting up ADAL.JS. This will get us ready to create the Visual Studio 2015 project which will host the MVC Web API. This will be how we communicate with the Azure Document DB database.

Right lets get started.


Creating Azure Applications

Firstly, when ever I do this, I get it wrong and cannot remember what I need to do. Before we go into the detail, lets briefly explain what Azure Applications are and what it will do for us.

Also, I need to explain a bit about the design of the Azure Applications and how we are going to create two Azure Apps, one for the Angular bit and another for the Web API component.


What are Azure Applications?

Azure Applications are entities that are associated to an instance of Azure Active Directory. They can be found in by clicking the  Active Directory heading on the left hand side. Once we have loaded Active Directory, then we click on the name of the Active Directory item in the list.


The “Applications” tab contains the applications that you have available in your Azure AD.


Applications have various attributes including a Name, Sign-On URL, Client ID, App Id, Reply URL and also provide you with a way to manage permissions that users have when using this application.

Also, it is possible to assign whether someone has access to an application as well. By default, this capability is switched off.

We will explain the configuration in more detail shortly.


Why are we creating two applications?

We are creating two applications:

  • Angular SPA Web App
  • Web API MVC App

The two apps are one for the Web API service components and one for the Angular SPA Web App component. This allows us to manage who can access the Angular application  separately as to who can access the Web API.

Also this helps to keep the Web API component more secure as an app has a key which allows the application to be accessed and configured. By having two separate keys we won’t have the situation that the application cannot interfere with each other. Also the nature of an Angular component means it is client facing and so slightly less secure that the Web API component.

As we have support for new clients, then we can start creating new applications for each of the clients.

Anyway, lets get to creating the Azure Applications in our Azure Active Directory.


Creating the applications

To create the application, I browsed to and logged in with Work account.


Browsed to the Active Directory icon and clicked the link, next I opened my Active Directory Domain “iThink SharePoint”.

I clicked on Applications

This brings up the dashboard for the domain, which looks like below


From the footer, I clicked “Add” and chose “Add an application my organisation is developing”.

Then the following screen was displayed, a name was given to the application and the web application / web api option was chosen


Next we need to provide the Sign-On URL and App Id Url.

The Sign-On URL is the start page when the application needs to login and the App Uri Id, is the unique URI that that the application is identified with when trying to authenticate with the application.


The App Id Uri, should not be confused with the Client Id which is a GUID that we use to identify the application later on.

Now we click the tick box and the application is created.

Within our application we can see what the Client Id is by clicking on the Configure tab.


The example of the app shown below has been deleted but shows you all the settings.



The Reply Url section will need to be populated with the URLs that we are going to use to debug and test the application. These URL are trusted by the application as a URL that can be redirected to as part of the OAuth flow.

You can also upload a custom logo here, maybe we will do that when we get a bit further with the development of the app!


The section as the bottom is the Application permissions which we will cover this later.



The last point that I will make with this page is the Manifest button


We can use this to download and upload the application manifest. This can be used to configure additional application settings, that cannot be configured by the UI. An example would be , setting up custom application permissions. More on that later.


Now we have created one application, I could create one for the Web API application, but Visual Studio does a great job of setting these up so we will let it do its magic once we get to the Web API project configuration.


Adal.JS (Active Directory Authentication Library)

So now that we have the application, we need to setup Angular to use Adal to login.

I want users to login to the Angular client before they can use it.

This library allows us to integrate our application so that we can authenticate users with Azure AD.

As I have mentioned in my first post, we are using Adal.JS and the man with the knowhow is Vittorio Bertocci who has a great post, Introducing ADAL JS v1.

Adal.JS is packaged up for Angular as a bower package, so can be installed using bower install adal-angular. I have already done this in the client environment post.

Now that we have the adal-angular package installed in the solution, we can start to integrate it with our application.


Linking Adal.js into the application

First we need to add the Adal.js library so that it is referenced in our application. Next, we need to tell our Angular application that it is a dependency and then finally we can start to configure Adal. This will ensure that it knows about our application and where it is hosted.

Firstly, lets add the Adal.JS references to the application. This is achieved by the following to /app/index.html


Adal Angular comes with two versions of the library, a minified version which is found in /bower_components/adal-angular/dist/ folder and a debug/dev version which is in the folder /bower_components/adal-angular/lib/ folder.

I am linking to the debug/dev version which is not minified but allows us to be able to debug what’s going on!


Ok, so now we have the library referenced in our application. We need to tell Angular to load it as part of its list of dependencies. To do that I modified the following line in /app/app.js  to add the dependency ‘AdalAngular’


var invoiceFormApp = angular.module(‘itspInvoiceFormApp’,
   ‘ngRoute’, ‘invoiceControllersModule’, ‘dataModelService’, ‘AdalAngular’

Once we have the dependency, we are ready to setup Adal.JS configuration. How exciting!


To initialise the Adal,JS library it needs to know the following information.

  • instance – this is the Microsoft Azure login page to direct to, it always seems to be “
  • tenant – this is the domain name for your tenant, so I have the domain so that is what I use it, but it might be something like if you do not have a custom domain setup.
  • client id – this is the GUID that we saw when setting up the Azure Application, it is sometimes referenced to as the App Id.


  • endpoints – we will talk about these later but they allow us to map a URL endpoint to resource, so that Adal,JS can authenticate against the endPoint correctly.


Angular Constants

When I was looking at where to store this information, I did originally have it hardcoded into the /app/app.js file. However, after more reading and thinking I decided on another approach, using Angular constants.

To ease the configuration for the app, I decided to keep it all in one place and created  an object stored as a Constant.

This will be part of the configurationService module which we will complete later on but let’s create this constant first.

The configuration service module is going to live in /app/services/configurationService.js. So a new file was created and the following added

Please note that the clientId is not a valid one, but just shows you the value that you need to use.

Finally, we need to add the reference to the script in our /app/index.html file.



Configuring Adal.JS

As mentioned previously, there are some things we need to tell Adal.JS before it can do its magic. These are the instance, tenant and CliientId settings.

The following changes were made to the /app/app.js. file.


Error: Authentication Context is not defined

When I first put the code together, I got the error above. This was resolved by making sure index.html referenced both :


Having Adal.JS installed also allows us to configure which routes require authentication, so we need to modify those too. This is achieved by adding the requireADLogin: true property to the route. Please refer to the app.js gist above for more info.


Changing the Homepage to handle Authentication

Now that we have the Adal.JS configured in our application, I thought I better handle authentication when the user hits our homepage.

So the following changes were made to the /app/contollers/invoiceControllers.js for the listInvoiceController.


Also, the following changes were made to list-invoices.html.

The changes use ng-hide to show the login button when the user is not logged in.


Note: whilst testing this I tried to upgrade to use 1.0.10 of Adal.JS but seem to have an error related to anonymousEndpoints. I am going to look into this but all was fixed when I reverted back to v1.0.8 of Adal Angular.

A couple of problems that I had included a fix to the Azure Application to allow add the redirectUrl: http://localhost:8080/app/index.html  to the list of Reply Urls.


Update this section of Azure Application configuration





Next Session

So we are now at at the end of the session, thanks for reading.

We have Adal.JS integrated and we have authentication, we are ready to start bring in the WebAPI MVC side. We can move the Invoices to be held in the API and start allowing us to create, edit and view the invoices.

I hope you find the information useful, please let me know if things are unclear or you need more information about anything that I have talked about.

The code that was commited for this episode can be found in Github:


Dev Diary: S01E04: Angular Services vs Factories & adding data to the underlying View Model from the View


In the last episode, Dev Diary S01E03, we added our first Angular page and hooked up the application landing page with a view. This view then displayed some data.

Now I wanted to add a new page which allows me to add an invoice to the list of invoices. Also I think we need some navigation so you can get easily Add an Invoice.


Adding Invoice Feature

Add Invoice Page

So I added a new page called /app/views/add-invoice.html to my VS Code project.

This look as below



The page is used to create new Invoices. There are a few things to point out on this page.

We are going to have to tell Angular how to bind the view model to the various input form controls. This will allow Angular to pick up the values that the user puts into text boxes, date picker controls and applying those values to the model.

So how does this work, well there is the Angular directive ng-model.  This will bind the value of the control to the value inside the ng-model directive.

For example, line 22 we have the html :



The <input> control has ng-model=”invoice.reference” this will bind the value of invoice.reference to the text box control and also update the view model as the textbox changes. We will see later where that value coming from but this will be taken from our $scope.invoice.reference object found in the view model.

The other directive to mention is ng-click which binds the button’s click event is bound to an action or function found in the view model. In this case it will be bound the controllers, $scope.saveInvoice() function.



Another lovely feature of Angular is the ng-repeat directive which is used in the next code snippet to populate a drop-down list.



This will populate the drop-down list with a list of options for the types of units.

Now that we have the view created, I had to create the data model service, controller to manage the view and then setup routing.

$injector, $provide and Provider, Factory and Services

Before we move on to creating the Data Model Service. We need to talk about $provide. I had to create my first instance of a service and started by creating a  factory.

I could not get it to work how I wanted with the factory method and then after some further reading, I read about providers and service functions. This led me into looking into the various different methods that the $provide object implementation.

The Angular documentation on $provide gives some good information on this, but after reading I was a little confused about what the difference was between a factory and a service in Angular.

I  found this wiki article, Understanding Dependency Injection,  within the Angular GitHub project. It really was good explaining the concepts, under the hood mechanics and reasoning behind the approach in more detail.

The $provide methods are helpfully made as part of the Angular module object and you have the following types:-

  • provider – registers a service provider for the Angular $injector object. This is used to create and initialise a service.
  • service – registers the service, which is created by the service provider function. When a service is created there is also an associated service provider created with the name of ‘servicename’ + ‘Provider. e.g. DataModelService will have a provider called DateModelServiceProvider.
  • factory – this registers a factory function, which is called by the service provider.
  • constant – these are created as constants which allows them to be available as object which cannot be changed and are available for the lifetime of the application. I have not used these yet, but will get to use them shortly.
  • value – constants and values are very similar. The only difference is that constants can be used in service provider functions as part of the $provide.provider() flow. This wiki article on Understanding Dependency Injection talks about this further.

Anyway so what is the difference between a factory and a service? They are very similar and under the hood call the same $provide.provider function when created. The difference as I see it, is that a service can be initialised by a provider under the hood to return a singleton object for the service.

Whereas a factory is initialised by data which you pass into it. So a factory is great when you know that you will have the data to initialise it but you may not know what that is or have reference to it. This makes sense for a factory as that is what the factory pattern  does, create me something based on an argument that I pass into it.

The service pattern  create me an instance of a service but I don’t need to know the ins and outs of how to create that service. The service is initialised by the service provider function.

I hope that helps clear it up, I am sure that I will need to explain that again to myself.

Anyway, now that we have an understanding of the difference, lets create the Data Model Service.


Data Model Service

Firstly, let’s explain what the Data Model Service is. I am looking to create invoices. So I thought it would be nice to have a place or a service which I can use to create the objects that my application needs. So that is what the Data Model Service does, it allows me to create instances of my Data Model. This will include being able to create instances of the Invoice entity object and an Invoice has multiple Invoice Lines so I will need to be able to create InvoiceLines to add to the Invoice.

So let’s get started!

The data model service is implemented as a new module via a new file created at /app/services/dataModelService.js.

A new module was created called the dataServiceModule. The module creates an object and we use that object to create the provider and the service. Here is the implementation of dataModelService.js



A service in Angular has two parts, the service and the provider service. The service represents all the operations that can be perfomed by the service. The provider service is used to initialize the service.

Currently, in my DataModelService I have two functions

  • Invoice()
  • InvoiceLine()

Next, we will go through how I can then implement this service and make it available in the “Add Invoice Controller” which we will create next.


The Invoice Controller

So now we have a way to create our Invoice objects which is centralised. Next we can create the controller for using in the add-invoice.html view.

So our controller starts by creating the controller in file, /app/controllers/invoicecontrollers.js

The controller “addInvoiceController”, looks like this:



The other thing we must do is make sure that Angular is aware of our new module, so we need to add a reference to the JS file in index.html. Also we need to update the app.js so that the module, ‘itspInvoiceFormApp’ requires the module ‘dataModelService’.



With out this configuration, I was seeing the following error in the Chrome developer tool when trying to go to the add-invoice.html page.



Adding a new Invoice Line

We need to be able to add a new line to our invoice, we will probably need to remove them too but one step at a time.

The approach to adding these, is that we will create a button which will add a new invoice line. The button will call a function on our controller’s $scope object called addInvoiceLine().

This function will grab the $scope.invoice object and then will get an instance of a new InvoiceLine from our DataModelService. This object is then added to $scope.invoice.invoiceLines.

One of the great things is that Angular will pick up this change and will immediately update the UI to reflect the underlying objects, that is pretty cool.


Saving the Invoice

Currently the add invoice controller, does not do anything to actually save the invoice but rather pretends that it has been successful and then redirects the user to the homepage.

This is achieved by the controllers, $scope.saveInvoice().

The redirection is performed by the $location object. Pages are referenced within Angular, using “#” which represents the start homepage for Angular.

So we call $location.path(‘#’);  to return back to the homepage.

We are now done with our Add Invoice Controller, next I had to provide a way for users to get to the new page!


Adding the route

To handle directing the user to the add invoice page, add-invoice.html when the user goes to /invoices/add.

The following was added to app.js so that I had the following:



Now we need to provide a way to add an invoice, time for some navigation.


Adding Navigation

So, it is about time we have some navigation in our application. This will be added to the index.html  page.

We will add to links, one for the add invoice link and another to take you back to the homepage.



Using an <a> link tag to get to another page, is achieved using the <a href> element and using the special character # which represents the Angular home page. To go to the add invoice page we used, ‘’#/invoices/add”.

This gives us the following updated index.html page.




You can find the code here, this commit represents the updates made to the repository for this post

Next Episode

So we now have a way of adding Invoices to the page. It is about time that we start actually calling into our WebAPI hosted in Azure.

So next episode, I will explain what I did to create the Azure Application and then start to organise how we authenticate via ADAL JS.

As always please let me know what you think and if you have any feedback, let me know via the comments.