Monthly Archives: July 2014

Requiring the use of https on an AngularJS application hosted in an Azure Website

As I was reaching the tail end of my AngularJS coding challenge one of the tasks I had outstanding was to enforce the use of https across the site, even if a visitor accessed it via a http prefixed link.

For the last few years I’ve mostly been working in MVC and have done this selectively at the filter level (RequireHttps) but my Angular site was just a collection of client side files with no server component – that was hosted off in a second site that fronted up only a restful web API.

I’m familiar with the concept of URL rewriting from ages back but hadn’t used it (ever? or at least for as long as I can remember) on IIS / ASP.Net. Turns out it’s pretty simple to do, all I had to do was drop the block below into my sites web.config file:

    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
        <clear />
        <rule name="Redirect to https" stopProcessing="true">
          <match url="(.*)" />
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />

Handy to know if you’re deploying an AngularJS site to an Azure website or IIS.

CORS with Owin

In a recent post I’d written about my struggles with the Web API CORS support and in the comments Taiseer suggested looking at accomplishing it through OWIN. I needed to create a new Web API project this week and so tried out this approach – the short version is it was utterly painless.

This project is (sorry!) closed source / commercial so I can’t share the source directly however it was an easy set of steps to enable CORS support through OWIN on my Web API project.

1. Either through the Package Manager GUI or console install the package Microsoft.Owin.Cors into your Web API project.

2. Within one of your startup files (easiest one out the box is Startup.Auth.cs and that seemed to be a reasonable place for enabling CORS) just add the line:


And that’s it.

If you want finer grain support over what domains and verbs are allowed you can supply detailed configuration via a the CorsOptions class.

Angular JS Pack

I’ve spent some time over the weekend and last week tidying up my initial AngularJS code and learning about some more advanced topics in order to reduce code repetition and standardise my approach to handling success and failure around $http calls to Web API.

Not being someone who is shy of creating new public GitHub repositories I’ve spun what I’ve written out into an open source (MIT License) Accidental Fish AngularJS Pack (how grand!) and written some documentation for it. You can find it over at GitHub.

It contains some element level directives for Bootstrap 3 boilerplate and some wrappers for communicating with Web API responses.

Code quality should improve over time as I learn more about AngularJS – I’m really only a beginner.

12 Hour Coding Challenge – AngularJS and Azure

This last weekend I set myself a challenge to build and ship a web application in under 12 hours and in the process learn something about AngularJS – a framework I’ve been itching to try for some time. I also wanted to build something that would serve as a basis for a small iOS application written in Swift (to learn a little about that) and that might allow for extension opportunities in iOS8.

The good news is I succeeded in my challenge and you can find the website here and the source code on GitHub. I’ll post more details on how to build, configure and deploy this application shortly.

Without further ado – this is how my day went.

Hour 1 – Idea, Technology Choices, System Architecture

With only 12 hours and some learning to do I needed something I could pair back to a useful absolute minimum but that I could evolve additional features on top of easily in the future. I used to be a big user of delicious but gave up on it while it was under Yahoo’s tenure. I have tonnes of different devices, on different platforms (so for example iCloud syncing of bookmarks isn’t enough for me iPhone and iPad yes but what about my Surface?) so thought I’d have a bash at a simple online bookmark site. I paired things back to a handful of requirements I thought I could achieve:

  • Signup and sign-in (in a way that I could expand to include social account sign in in a later version)
  • View links in descending order they were saved
  • Save links in the website
  • Save links from a bookmarklet (button on your browsers toolbar)
  • Tag links
  • View links in tags in descending order they were saved

As both AngularJS is new to me, and Swift also when I get rount to that, I wanted to build everything else on a solid well understood foundation and so for the backend picked:

  • C# and .Net 4.5.1 – I’m hankering to experiment with Go but if I added that to everything else there’s no way I’d finish in 12 hours so I stuck to C#.·
  • Azure – table storage, web sites and a worker role. I plumped for table storage rather than SQL as I want this to scale easily and be super cheap to run – I’m paying for it myself and am willing to sacrifice features and some development complexity for a lower monthly bill.
  • Asp.Net Web API – I know this really well now so an obvious choice for the web service layer given I was using C#.
  • My open source Azure application framework, it wraps up most common operations you’d undertake against the core of Azure in a testable fashion and makes deployment and configuration easy.
  • My open source ASP.Net Identity 2.0 table storage provider.
  • The Bootstrap CSS template for the UI. Looks ok out the box and I can apply an off the shelf theme easily later (or tinker with it myself).

Most of the above took place in my head with a handful of notes.

Hour 2 – AngularJS Research

I didn’t expect this to hold too many surprises in terms of the overall system architecture as I’m pretty familiar with rich browser application development in jQuery and have some experience in backbone and Knockout but I didn’t know how to structure an application properly in AngularJS.

All I’d done with this previously was really an equivalent of the sample on the home page tucked away inside another website but it looked to be a super useful and comprehensive single page application framework that could provide a really clean MVC structure for a JavaScript client. I basically went through the developer guide at quite a clip and looked at the structure of a couple of non-trivial apps.

I was no expert after an hour, and didn’t expect to be, but I felt I could build the backend and not get surprised by the front end to a degree that would cause me to uproot the system architecture. Importantly I learned how I could integrate the client with the authentication endpoint via a helpful blog post (thank you!) which also introduced me to interceptors – most handy.

Hours 3 to 6 – Build the Backend

The storage model fell pretty trivially out of the requirements and came together quickly. I used the Chrome plugin Postman to test my REST interface without needing to write further code. I used my standard approach to this sort of thing in terms of project structure.

Nothing really new at all so largely just predictable legwork and at the end of the period I had a clean back end following a fairly pure REST model that I was fairly sure would work for the UI and I could deploy into Azure. So I did just that.

Hours 6 to 12

Best summarised as grappling with AngularJS with lots of Googling and referring to the documentation!

Actually to be fair other than a couple of pain points it was rather simple and I’m pretty sold on AngularJS as a framework for single page applications, I will certainly be using it on future projects.

I basically copied the application folder structure I would use if I was building a traditional server page request website in ASP.Net MVC and that I’d seen used in a couple of other apps that worked out really well with controllers, views and services separated by folders. I added a service layer that used the $http angular module to talk to my Web API and kept the http grub out of the controllers.

I managed to avoid the temptation to fall back to old patterns and stuck as far as I could to straight AngularJS, for example it was tempting to start inserting jQuery all over the place to show and hide things whereas I really wanted to do this in a clean and declarative fashion using Angular.

I had to refactor things a couple of times but nothing major – it came together quite easily. The last hour was putting a front page on it and dealing with something I hadn’t considered – as a new user when I went to the bookmark feed there is no real clue as to what to do next so I added a quick “if there are no links welcome page”. By the time I’d begun the UI work my own test account was littered with links!

The things that caused me most pain:

  • CORS support. My client website was running in a different domain (localhost in development) to my Web API and would in production (it’s static HTML so why waste expensive Asp.Net server resource!) and this meant I needed to use the CORS protocol (Cross Origin Resource Sharing) to access the Web API from JavaScript. Except…. it didn’t work. After much teeth gnashing it turned out that there were issues with the Web API 2.0 binaries and accompanying Web API 2.0 CORS package and I would need to upgrade to 2.2. I did this but in Microsoft’s recent “fun” fashion that included breaking changes on a point release. Fortunately simple to fix and then everything worked fine.
  • Infinite scrolling. I wanted to take an infinite scrolling approach to the bookmark list. You’ll have seen this if you’ve use things like Facebook or Twitter in a web browser – there are no “next page” and “previous page” buttons you simply scroll towards the end of the page and the next page is fetched in the background and added to the bottom. There is an AngularJS module that purports to assist with this however it had a number of bugs (must do a pull request) and so I spent 30 minutes learning the code and fixing them. Fortunately it was only 100 lines of code to deal with and still was a net win in terms of time. Maybe I’ve just missed something in terms of library dependencies.

Lessons Learned

  • AngularJS is pretty cool! Easy to use, well considered, and provides excellent structure. My only concern is that while digging around for answers to common problems it seems to be evolving very quickly with not a lot of consideration given to backwards compatibility. Maybe I’m wrong – I’m utterly new to it.
  • By keeping things tightly focussed I had something in the hands of a customer (me!) in 12 hours from start to finish. It doesn’t let me do things I’d eventually want to do (edit links and tags, delete links for example) and has some rough edges but I can already use it and “pilot” it myself in a beta fashion. I shipped as early as I absolutely possibly could.
  • The aggressive timescale meant I couldn’t go off on architectural / development flights of fancy, not that that’s really my thing – see below. I think every line of code I wrote in this system is specific to the business problem in hand. No custom UI components, no custom architecture, no funky “time saving” code / model / blah blah blah generators that are often the symptom of over architected solutions put together by people with too much time on their hands! My first choice was always to go find something off the shelf (hence my infinite scrolling bug fixes – and even factoring that in it was quicker than writing it myself).
  • There are lots of things I’d like a site like this to do (social sharing, editing as above, public / private feeds and links, trending URLs) and while I had those in mind and have rough views of how to build them I did not allow myself to get distracted by them. If I had my 12 hours would have become a week, would have become 2 weeks and so on. Just because they are not in v1 (or v0.1 if you prefer) doesn’t mean they can’t be put into v1.1.
  • You really do need to stand on the shoulders of giants – I can’t emphasise enough how strong my belief is that if the code you are writing is not specific to your particular problem then you’re going wrong: you’re hovering around the ankle while someone else starts at head height!

Next Steps

  • Understand the best way to unit test AngularJS and, errr, write the unit tests.
  • Present a tag list in the UI.
  • Deal with error conditions, particularly http errors, in a consistent way.
  • Beef up validations on both the server and the client.