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

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 S01E02: Angular / WebAPI / Azure Document Db App – Client Environment Setup


In my previous post: Dev Diary Entry 1: Azure Web App with MVC WebAPI, Angular and Azure DocumentDb, I introduced the Invoice Management App that I am planning to build.

For complete transparency, the application that I am talking about building has been in development for a week or so now. So, as I write this I am playing catch up. I have been writing down all the problems that I have had and how I resolved them. My aim is that we will quickly get up to date so that I am coding and then I can quickly write about what I did.

Today, we are talking about setting up Visual Studio Code and Visual Studio 2015 to host my applications. Remember we are building two components, the Angular client application in Visual Studio Code and the MVC Web API component using Visual Studio.


Setting up the Environment

Visual Studio Code

Developing in Visual Studio Code is quite different to using Visual Studio, the team at Microsoft are doing a great job at improving the application but it does feel very unfamiliar to me who has been using Visual Studio for a rather long time.

Anyway, I downloaded VS Code from and installed it on my machine.

I am developing on a Surface Pro 4 with Windows 10 x64. So the instructions provided are for Windows but it is pretty similar for MAC OSX and Linux.


Developer Directories

I am developing in the c:\dev folder and have created a subfolder called ITSP and then a subfolder, VSTS. The final directory is c:\dev\itsp\vsts


Node and NPM

The next step, was setting up the environment, I had spoken to a few people and read a few posts and the way to go with VS Code was using Node.js tooling and the Node Package Manager, npm.

Node provides a few lightweight services which we can take advantage of when developing. The one that I make most of is the built in HTTP server, but more on that later.

NPM or Node Package Manager provides a fantastic way of downloading, installing and keeping your dependencies up to date. I guess the name came from Redhat’s Package Manager or RPM. To be fair it is also like NuGet which the .NET world have been using to keep their dependencies in check.

So I downloaded and installed Node from and choose the latest build which was v5.6.0, I see that version v6 is out as I write this. The download is an MSI so was a quick simple install.

Next is NPM, so actually NPM comes included with Node.js but I wanted to make sure that I had the latest version of NPM. This is the advice in the NPM Installation instrucitons found here:

So to do that I started the Node,js command prompt

  • npm install npm –g

The command calls npm telling it to install a package called npm with –g which means to install it so it is available globally.



The other tool that seems to be great at dependency management is Bower. Now, I had a hard time working out what the difference was between Bower and NPM. Why do I need both. Well Bower seems to be better at installing and configuring the client side components and NPM for the server side components.

One of the reasons that I have chosen Bower is to be honest a lot of tutorials use it. Now, this is something that I will look into a little later on the project but I want to get up and running. There do seem to be a lot of alternatives such as Browserify and Webpack.



So this is my first project using Angular, I hear people talking about it all the time! As I was researching into the product more it became embarrassing to see how long its been out before I have had a go at using it!

One of the chaps speaking about this stuff from the SharePoint world is Andrew Connell via his blog. He has a great amount of content which I found really useful.

As I mentioned in my previous post, I have been reading up on Angular via their documentation pages. I also have been listening to Scott Allen’s AngularJS: Getting Started on Pluralsight.



As a developer, I need help with design so I have decided to use Twitter Bootstrap and fortunately this is quite easy to include in your project.

I am sure that you have used Bootstrap more than me!

However, Bootstrap is a framework which provides a grid based system for defining responsive designs based on having different css classes for different screen sizes.

I have to say I am always amazed what front-end developers can do with Bootstrap, I am sure in time that it will become second nature.



Yeoman is like File->New Project in Visual Studio. It is pretty cool actually and allows you to create or use pre existing templates to make the project scaffolding. I did look at this and various templates but I found them complex and they started to pull in a lot of stuff which I did not know about.

So to kept it simple, I haven’t used Yeoman as I wanted to learn how to build the project from scratch rather than have a tool do everything for me and I then don’t understand my dependencies.

I am sure that I will change my behaviour next time once I understand how everything fits together.


Now I know that I am going to be using Azure Active Directory as my authentication and authorisation mechanism.

ADAL is a library that has been created which provides a wrapper to manage authentication with Azure AD. The library is superb and really straight forward to use for the .NET stack. Fortunately, there is also a JavaScript implementation called Adal.js and even better there is a module created for Angular!

I have been following Adal for a while and the go to guy is Vittorio Bertocci, he has some great posts on all things ADAL.

Introducing ADAL JS v1

The article is great and talks about how to install the framework using Bower and then provides examples including one for authenticating your application with Angular!



Of course we need jQuery, I don’t think this framework needs any introduction.

This was installed from the node.js command line:

  •  using bower install jquery




Creating the Client Side Visual Studio Code Project

Ok so now I have talked about all the bits and pieces that I am using for the client side of the application, I will try and explain the steps that I took to create the project for Visual Studio Code.

Remember we have two components in this application:-

  • Angular Client side application being developed in Visual Studio Code
  • MVC WebAPI Server side application being developed in Visual Studio 2015

So,  to create the Visual Studio Code project you need to create a package.json file. This is the equivalent of a Visual Studio csproj file for Visual Studio C# Projects. It contains the version number, name of the project, description and also it has scripts section where you can define commands to perform actions when developing your application.

So to get started I did the following:-

  • started node.js command prompt
  • created a directory c:\dev\itsp\vsts\IT365.InvoiceApp.Client
  • from the directory just created I ran npm init
  • this wil start a wizard which then asks for various information about the project including its name, description and author details

Now that we have our package.json created we can fire up Visual Studio Code

  • code .

This will start Visual Studio Code in the current directory which will cause Visual Studio code to read the application information created so far.


Install Dependencies

Now we have the project created next it is time to bring in our dependencies.

We will use npm and bower to pull in the dependencies:-

  • bower install bower-angular
  • This will install the Angular component into our project into a folder called bower_components\angular
  • Angular Route
  • bower install bower-angular-route
  • This will allow us to define our routes in the application so that we can control where the user goes, what they see and which controller to use. More on this later
  • Angular Mocks
  • bower install bower-angular-mocks
  • This will allow us to do Test Driven Development when we start looking at Continuous Integration and Continuous Delivery
  • Angular Sanitizer
  • bower install bower-angular-sanitizer
  • This helps us to strip out dangerous characters from when parsing HTML


  • Bootstrap
  • bower install bootstrap
  • This will give us a better look and feel than I could do!

So, we have the Angular and Bootstrap stuff installed that I thought we needed.


Next we need to install the ADAL JS stuff

  • bower install angular-adal
  • This will allow us to manage the login / authentication, authorisation process in our application with Azure Active Directory

Then we have jQuery

  • bower install jquery


Finally, I want to be able to actually run the application locally and a really nice way of doing that is using the Node.js HTTP Web Server, http-server

  • Node http-server
  • npm http-server –g
  • This will install the http server globally so we can use it in our next applications


Create Application Structure

Next I created the application structure

So the following directories and files  were created from within Visual Studio Code

  • [app]
  • [controllers] – this will hold all our controllers
  • [services] – this will hold all our services
  • [entities] – this will hold our JavaScript objects relating to entities such as Invoices, Users etc
  • [views] – this will hold all our views
  • [css] – this will hold our CSS styles
  • [images] – this will hold our image
  • app.js
  • index.html

I am sure that I will be adding more folders etc but that gave me something to start with.


Trying out the Application quickly

So one of the tips that I picked up from the node.js documentation was how you can create tasks with NPM.

I was a little confused by this to be honest but after a bit of investigation I found out that I could modify the package.json to configure these tasks for NPM to be able to use.

  • Opening up package.json, i found the scripts section and added the following
  • When i first did this i added just the http server –a –p 8080
  • however, after more reading I realised I could run multiple commands using the && syntax
  • So we ended up with



Now this is pretty cool, from the node.js command prompt I can type

  • npm start

This will start a web server and fire up the browser taking me to the homepage!



Next Episode

So in the next episode, we will actually start develop something. I was pretty excited to try out Angular so I just started to build the application using client side data. So we will cover that.

I hope you can join me for the next episode.