Azure Active Directory Logo

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


Introduction

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 https://manage.windowsazure.com 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.

image

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

image

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 https://manage.windowsazure.com and logged in with Work account.

image

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

image

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

image

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.

image

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.

image

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

image

image

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.

image

 

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

image

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

/bower_components/adal-angular/lib/adal.js
/bower_components/adal-angular/lib/adal-angular.js
 

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 “https://login.microsoftonline.com/
  • tenant – this is the domain name for your tenant, so I have the domain ithinksharepoint.com so that is what I use it, but it might be something like company.onmicrosoft.com 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.

image

  • 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.

/app/services/configurationService.js

 

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 :

/bower_components/adal-angular/lib/adal.js
/bower_components/adal-angular/lib/adal-angular.js
 

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.

image

Update this section of Azure Application configuration

image

 

 

 

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: https://github.com/ithinksharepoint/IT365.InvoiceFormApp.Client/commit/e02ac5c2af67245cbd5bacd7886b96fb4406c148

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


Introduction

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.

image

 

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.

image

 

Github

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

https://github.com/ithinksharepoint/IT365.InvoiceFormApp.Client/commit/5f8afd7e3f2987603b6baa692faa1dcdd722c3d1

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.

Dev Diary S01E03: Building the first Angular page


Introduction

In my previous post, Dev Diary S01E02, I explained the configuration of my environment for the client side. If you remember, I am building this application with Visual Studio Code and will also be building the server side component using Visual Studio 2015.

To be honest, I got impatient when developing this and decided that I would start to get to grips with the Angular part. I didn’t really understand things entirely but built my first page index.html.

 

Angular ng-app, ng-view and controllers

The Angular App Homepage (index.html)

So to get things running, I needed to reference the necessary components so that I could start to use them.

Angular is a JavaScript based Model View View Model based application framework which is used to build client side SPAs or Single Page Applications. We need a single page which is going to host the application. This is going to be our homepage, index.html.

Index.html had the following references added to load the Angular, jQuery, Bootstrap components. I added these under the closing tag as this allows the browser to load the page more quickly.


/bower_components/angular-route/angular-route.js
/bower_components/angular-resource/angular-resource.js
/bower_components/jquery/dist/jquery.js
/bower_components/bootstrap/dist/js/bootstrap.js

The other thing is that we need to tell Angular about the fact that this is an app and also tell it when to render the view.

Below is the index.html file

 

So you can see we have line #2 which an Angular directive, ng-app, which I will talk about a little later. This tells Angular that the application that will be loaded on this page is called itspInvoiceFormApp.

We have all the links to the scripts mentioned above and also the applications CSS for bootstrap.css and the application, invoiceformapp.css.

In the <body> tag, another Angular directive is added to a <div> tag. This is ng-view. This tells Angular where to render our view and provides the entry point for switching the content in our Single Page Application.

So now we have our index.html done lets move on to some JavaScript!

 

The Angular App Code (app.js)

Next, the Angular app was configured in /app/app.js. I had a look through the various examples on the Angular.js website and also out there via Bingle.

I added the following to app.js

 

 

So lets talk through this, the first line #1 is telling JavaScript to run in strict mode. This helps check for errors in the JavaScript, more information can be found here:

Line 3, creates a variable called invoiceFormApp using the angular.module() function. We pass in the name of the module, in this case ‘itspInvoiceFormApp’. The next parameter in the square brackets are the dependencies that the application relies on. This is important, Angular has this dependency injection engine, which we can take advantage of. In this case we are dependent on the Angular routing module, called ngRoute.

Next, I had to to configure the application, so create a function which provides the configuration of the app. From my limited experience, I know that this is going to change quite a bit as we start loading in more dependencies.

So the function currently has one parameter, this will increase as the number of dependencies get added to the application. The configurationProvider function has one parameter which maps to the invoiceFormApp.config() which is passing in the objects in the [‘$routeProvider’] into the function. So if we had the following [‘$routeProvider’, ‘myOtherThing’], then we would update the function assigned to configurationProvider to:

var configurationProvider=function($routeProvider,$myOtherThing).

 

Angular Routing

Anyway, I hope that helps clear that function up a bit, it took me a bit of time to get the hang of it. So within my app, I used the $routeProvider to create a route for ‘/invoices’. Now, when you setup a route you need to provide a couple of additional bits of information.

  • templateUrl: ‘[server relative url to the html file that is going to hold the view’
  • controller: ‘[name of the controller that will handle setting up the view]’

I setup the /invoice route to go to a view located at ‘/app/views/list-invoices.html’ and to use a controller named ‘listInvoicesController’. Notice the final call to .otherwise() on the $routeprovider variable this will cause the application to default to this route and page if there is no match found for the user’s input or the user is directed by the application to an invalid endpoint..

Now we have our routes setup, I had to give them something to point to.

 

Views and Controllers(View Model)

With the default route created,  next I had to create a view and a controller to implement the route.

 

View

Lets start with the view first, I created a view in VS Code called “list-invoices.html” in the /app/views folder.

Finally, we are getting to try out Angular. This page is being used just to view the data.

This is what I ended up putting together for list-invoices.html.

 

 

So basically I have a table wrapped up in some <divs> the outer <div> has the class name container, this is a bootstrap thing to demark the content that is to be styled by bootstrap, the inner div with the class name row creates a new row.

Now on to the actual Angular stuff. we have these various tags starting with “ng-“, these are called directives and allow you to do something with the data that you have bound to the page from your controller and data, or model.

The example that we can see is ng-show   (ine 5) this points to something in or model which evaluates to a boolean value and will display that <div> element when it evaluates to true.

I think this is pretty cool stuff, I was always amazed when I saw this kind of thing with Knockout.js

Anyway, so next we render our data, so we have a table which has been tagged with various bootstrap classes to make it responsive. At some point I am sure I will have to work out the responsive stuff works. The cool bit with the table, starts at row 16.

We have a line which reads <tr class=”clickable-row” ng-repeat=”invoice in invoices”>. So this Angular directive ng-repeat allows us to loop through an array of objects which are in an array called invoices.

This <tr> element block will get repeated for each invoice in invoices, within the <tr> we have a number of <td> elements which are being used to display the values in the properies found on the invoice  object. This is one way that Angular does its data-binding. So using {{invoice.invoiceDate}} we can display the contents within the invoice object.

The rest of the page is pretty uninteresting, I did also add a section to display errors which is quite neat and shows another thing that you can do with Angular directives which is actually add logic within the directive. So we have a <div> tag which has the ng-show  directive set to ng-show=”error!==’’”. So if there is an error in our data model then this div will show the error.

Anyway, so until I show you the controller, it does not really make sense as how do we know what data we are binding to the view?

 

Controller and Model

In order for the view to work we need to create a controller and also the model that the controller is going to pass into the view.

I created a file called invoiceControllers.js in the /app/controllers folder.

Within this file, I created a new module which created a module called InvoiceControllerModule. Then we registered a factory called invoiceController. I have to say that I now know that this was a mistake. But at the time I didn’t realise it. I will talk about the changes that I made in a later blog post.

Anyway, now that we have the factory we need to create a function which is called when the factory is initialised.

 

 

Note that the factory method takes a function and the parameters match the attributes defined in []. This controller is taking just a $scope variable.

Actually the $scope variable is very important and represents the view model which can be referenced within your (.html) view file.

We created a couple of properties of the $scope object to hold an error and also to hold a list of invoices.

Next, we need to add some invoices to the array, so that we have something to display.

To keep things easy I just created a load() method on the $scope object to load the data.

This now creates a controller which exposes a $scope variable, final file looks like this.

 

Now, that this is all put together it generates a page which looks a little like this.

image

 

Make sure that if you are loading some data n your controller with a load() function, that you call it. I spent a couple of minutes, wondering why I did not have any data loaded and the realised I hadn’t actually called the function.

 

When testing and debugging use http://localhost over http://127.0.0.1

Something that I noticed with Google Chrome when testing the environment is that the css would not work correctly if I tested using http://127.0.0.1:8080 so I ended up using http://localhost:8080 which caused the styling to render correctly.

 

Next Episode

I hope you found this useful, please let me know if there is something that needs more clarity.

I have moved this code into GitHub and it is currently available here:

https://github.com/ithinksharepoint/IT365.InvoiceFormApp.Client/tree/master

In the next episode we are going to put together some add functionality and also configure the application navigation.

Dev Diary S01E02: Angular / WebAPI / Azure Document Db App – Client Environment Setup


Introduction

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 http://code.visualstudio.com/ 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 https://nodejs.org/en/ 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: https://docs.npmjs.com/getting-started/installing-node

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.

 

Bower

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.

 

Angular

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.

 

Bootstrap

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

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.

Adal.JS

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!

 

jQuery

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

  • ADAL JS
  • 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 127.0.0.1 –p 8080
  • however, after more reading I realised I could run multiple commands using the && syntax
  • So we ended up with

npm-start-task-config

 

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!

image

 

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.

Dev Diary Entry 1: Azure Web App with MVC WebAPI, Angular and Azure DocumentDb


Introduction

This is the first time that I have tried writing a developer diary. So I would really appreciate it if you could let me know if you find it useful.

I find when I start building an Azure based application that I forget what I had to do the last time.

At the moment, my career has been working a lot with SharePoint and I want to move over to doing more Azure stuff. However, until I actually start doing more Azure applications then the process of building applications in Azure is not going to flow.

So this diary is for me to remind myself of what I did, plus I want to be completely transparent. When I find a problem or hit a blocker (no matter how stupid it is) I am going to try explain what it was, what I tried to do to fix it and hopefully the final fix.

It should be interesting to see where the application goes.

 

So what are we going to build?

Well currently I use a product called Microsoft InfoPath to manage my invoices to customers. InfoPath is no longer being worked on and Microsoft have said that it will not be supported after 2023 I thought why don’t I build something that a find useful and use that as an experience to learn. So here we are.

So we are going to build an Invoice management system, which allows someone to create, edit, view and publish an Invoice as a PDF into a SharePoint Online document library.

There are a load of other things that I am thinking about that would be useful, like reminders to send out invoices and being able to integrate with time management applications like Toogle and create invoices from those data endpoints.

 

 

Architecture

The application is going to be built in two parts:-

  • Client side Angular SPA application served by Azure Web Apps.
  • Azure hosted WebAPI MVC application using Azure Document Db to host the content

Invoice Form App Architecture

The application will use Azure AD as the authentication and authorisation engine. For monitoring, errors, statistics we will use Application Insights and both the Angular and MVC components will use the same Application Insight key so that we keep all the monitoring together.

 

Learning

Before I started the application I wanted to do some reading on Angular, Azure Document Db as I have never built anything with these technologies before.

I am using Angular 1.0 at Angular 2.0 is still in development. I have made the choice to build the client side using JavaScript rather than TypeScript. Though I am likely to convert over to TypeScript but thought that process would be interesting to capture.

So this is my reading list before I start:-

 

Development Environment

I am building this application with Visual Studio Code for the client side and Visual Studio 2015 for the MVC Web API component.

I wanted to build something with Visual Studio Code so that I learnt more about Node, Node Package Manager, Bower, Gulp etc.

I don’t really know what all those things are but we will find out!

 

Next Steps

So the next steps are to create the solutions for the Angular application and the MVC Web API.

That will explained in the next entry.

 

Thanks for reading.

Simon

PowerShell: Repairing SharePoint Content Databases


Introduction

When you get a warning from SharePoint saying that a database has orphaned content, the message is not the most helpful.

This is an example of health analyser message in SharePoint Central Admin

orphaneditemshealthcheckerror

There is no information on which content database is affected, although you can click on the “Repair Automatically” option but you don’t have any context as to which database is affected. This is going to be a problem if we need to repair the database via a documented change process.

The following process will show you how to identify the item and database that is affected.

Start by running the SharePoint Management Shell.

Get-SPContentDatabase | %{Write-Host $_; $_.Repair($false);}

This will return something like below:-

Database Name 1
<OrphanedObjects Count="0" />
Database Name 2
<OrphanedObjects Count="0" />
Database Name 3
<OrphanedObjects Count="0" />
Database Name 4
<OrphanedObjects Count="0" />
Database Name 4
<OrphanedObjects Count="0" />
Database Name 5
<OrphanedObjects Count="0" />
Database Name 6
<OrphanedObjects Count="0" />
Database Name 7
<OrphanedObjects Count="0" />
Database Name 8
<OrphanedObjects Count="1">
 <Orphan Type="SecurityScope" SiteId="{166BF298-DE66-4919-A506-4F3412E8A86E}"
Name="sites/test/SiteCollectionImages/Forms/Video/docsethomepage.aspx" InRecycleBin="Yes" />
</OrphanedObjects>

Now we can see that there is some orphaned content in content database “Database Name 8”.

To fix the database, run the following:-

$repairdb = Get-SPContentDatabase -Identity "[Database Name]";

Check that the database is the right one by outputting the $repairdb object.

To repair the database run the following command.

$repairdb.Repair($true)
<OrphanedObjects Count="1">
 <Orphan Type="SecurityScope" SiteId="{166BF298-DE66-4919-A506-4F3412E8A86E}"
Name="sites/test/SiteCollectionImages/Forms/Video/docsethomepage.aspx" InRecycleBin="Yes" />
</OrphanedObjects>

Now let’s check that the corruption is gone by re-running the command

Get-SPContentDatabase | %{Write-Host $_; $_.Repair($false);}

We should see that there are no more corruptions

Now go into Central Admin site and re-run the failed health rule, to resolve the issue.

SharePoint 2013 Incoming Email Issue : Emails disappear


 

Introduction

The other day we had a SharePoint 2013 development environment which had been configured up to receive email into libraries.

The configuration had been working for a while with no problems, there are issues with the incoming email on older versions of SharePoint 2013 but this farm was patched to May 2015.

We used the following Technet article to configure incoming email: https://technet.microsoft.com/en-us/library/cc262947.aspx

Unfortunately, email was never getting into SharePoint. The service had been working without any problems for a few weeks.

 

Problem Analysis

 

On investigation of the problem showed that email was successfully routed via Exchange to the SharePoint server via the locally installed SMTP service. The email was arriving successfully into the drop folder and after a few minutes the email disappeared. However, it would never appear in the document library! The email just disappeared.

Another symptom of the problem was seen when accessing the document library settings page for Incoming Email. Not all the settings would be loaded, the page was missing a large set of settings.

Normally the page looks like this :-

incoming-email-settings-library-ok

 

However, it was only showing this information :-

incoming-email-settings-library-broken

 

When someone attempted to make a change to the email settings for the list then the following error would be thrown:-


Server Error in '/' Application.

Error in the application.Description: An unhandled exception occurred during the execution of the current web request. 

Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: Microsoft.SharePoint.SPException: Error in the application.

Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: [SPException: Error in the application.]   
Microsoft.SharePoint.SPList.UpdateDirectoryManagementService(String oldAlias, String newAlias) +1239   
Microsoft.SharePoint.SPList.Update(Boolean bFromMigration) +311   
Microsoft.SharePoint.ApplicationPages.EmailSettingsPage.SubmitButton_Click(Object sender, EventArgs args) +1347   
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +146   
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3586

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34248

 

Strange behaviour indeed!

I fired up ULSViewer (http://www.microsoft.com/en-us/download/details.aspx?id=44020) on the offending server. Whilst watching the ULS log, another email was sent to the document library. After a minute or so a message popped up.

Cannot load type EWSSharePointEventReceiver from Assembly: [Assembly Name].

So for some reason the assembly could not be loaded, hmm so why is that?
I had a look through the GAC and could find the assembly name. However, using a .Net Reflector such as Just Decompile (http://www.telerik.com/products/decompiler.aspx) or .NET Reflector (http://www.red-gate.com/products/dotnet-development/reflector/). I could see that the class was not in the assembly. Speaking with the developers, I found out the class names had been changed. So the next thing I checked was the event receivers.

With a bit of PowerShell, I found a set of event receivers which were being fired by the item email received event.

I removed the event receiver using the following PowerShell and running it in the SharePoint 2013 PowerShell Management Shell:-

 


$eventReceiverName="EWSSharePointEventReceiver*";
$siteUrl="https://sharepoint";
$site = Get-SPSite $siteUrl;
$rootWeb = $site.RootWeb;
$allWebs = $rootWeb.AllWebs();

foreach($checkList in $allListsInWeb)        
{   
	Write-Host "Checking List: " $checkList.Title " for event receiver class: " $eventReceiverName;
	$eventReceivers = $checkList.EventReceivers | ?{$_.Class -like $eventReceiverName};            
 
        If($eventReceivers -ne $null -and $eventReceivers.Count -gt 0)
        {                   
             foreach($removeReceiver in $eventReceivers)                        
             {                       
	           Write-Host "Removing Event Receiver: $removeReceiver";
		   $removeReceiver.Delete();
             }
 
             $checkList.Update();
        }
}

 

After the corrupt event receivers were removed from the list then resending the email to SharePoint worked! Now the email appeared in the document library.