Posts

First pluralsight course live

ps_course
I’m proud to announce that my first pluralsight course now is live, make sure to check it out:

Authenticating Your Angular SPA with ASP.NET Web API and Auth0

Modules

The course is split into the following three modules.

An Introduction

Course introduction with brief overview of Auth0, where we also register for a free developer account.

Building the Back-end API

In this module we create the back-end and secure it with Auth0, we also test our API by making secure calls with postman.

Building the Front-end SPA

In this module we create the front-end using AngularJS to communicate securely with our back-end. We use Auth0Lock to get a professional looking login dialog that displays well on any resolution and device.

Time spend

I must admit that it was quite cumbersome to edit the material especially since camtasia was really buggy on windows 10. I kept track of all my time and this is how I spent it.

Audition

8 hours to learn/record/edit the audition video. Check it out here if you’ve missed it!

Recording

19 hours to learn the tech I want to teach and record.

Editing

11 hours editing.

Total

38 hours for an hour of production material.

Financially worth it? (UPDATE)

Since I’m an independent consultant I can calculate if it was worth my time. UPDATE: Now after I’ve received my first royalty check and with my second course in the pipeline to be released soon, I can confidently say it was worth it. Both experience wise and financially. I also got reimbursed $200 for the new microphone, which was cool since I needed a new one for my youtube screencasts anyway.

One thing I do know though is that it’s good PR to be a pluralsight author, which could lead to higher hourly rating.

Working with pluralsight

From the initial contact with the audition to working close with my editor on the course, pluralsight was super professional. I really enjoyed the experience, and it’s definitely something I recommend and encourage others to do. Being a web developer using the aspnet stack it was quite hard to find a course that wasn’t already done though. First I wanted to do an angular 2 course, but that was off the table since it’s still in alpha and a lot of authors are standing in line on that topic. My second idea was to do something with aspnet5, but that was off the table as well since it’s in beta, soon to be RC.

One thing that bothers me though is that as I was completing my course, I saw Shawn Wildermuth do a course on aspnet5 that has gone viral. Seems like different rules apply to different authors, which isn’t cool. Other than that, I really enjoyed working with pluralsight.

In conclusion

So, 38 hours to produce a 1 hour long course, to be fair the audition process is something I only need to do once so it’s really 30 hours spend on the actual course. As I recorded the course I became better at it, I’m sure the next course I do will be quicker. I definitely encourage other developers to go through the experience of creating a course, even if I have some experience from creating screencasts on youtube this was something entirely different.

My ambition is definitely to create more courses for pluralsight, preferrably on angular 2 when it’s released.

Until next time, have an excellent day!

SignalR Scaleout with SQL Server in Azure

A project for one of our customers recently had this scenario where mobile clients posted updates to a REST-backend running on one site and we needed to notify all clients browsing a different site. The first technique that came into mind was SignalR but we had only used it within the same app before. Now we’d like to share a hub across apps.

Fortunately, the solution was very simple, SignalR supports CORS and scaling out with SQL server out of the box. All you need to install is the following two nuget packages.

PM> Install-Package Microsoft.AspNet.SignalR
PM> Install-Package Microsoft.AspNet.SignalR.SqlServer

This is truly powerful and the SignalR-team has done a great job making it easy to use. There’s an excellent official guide here. Here’s a screencast to show how quickly and easy you can get it up and running in Azure from scratch.

 

Source code @ https://github.com/ajtowf/signalrlab/

 

Hope you find it useful!

 

Keywords : VS2013, Azure, SignalR, WebApi, MVC, OWIN, SQL Server

socialtime.se lab days project

Lab days

I’ve been super busy at work but finally I’ve come around for some fun lab days coding.

The objective

I’ve often wondered how much time we spend on social media apps on our phones. The idea came pretty naturally – create an app that accurately measures the time for us.

Coding sessions

The 1.0 version of socialtime.se was coded in 4 sessions and this is how I disposed the time. The sessions are 1 or 2 days apart since I rarely have the time to sit and code for 8h straight nowadays, unless it’s for a paying customer of course.

  1. 2h developing the android app for monitoring running processes.
  2. 1h studying the android facebook SDK and implementing auth from the app.
  3. 4h developing REST backend with facebook auth and a super simple frontend.
  4. 1h publishing the app to play store and minor refactorings.
  5. 1.5h writing this blog post, 45 minutes on creating the graphics ;-)

Android App

The app is really basic, it has a background service running which monitors the running processes on a separate thread and just one activity to display the social time.

socialtime_app_v1.0

My first approach was to read the log and filter for ActivityManager since that seemed to work with the adb. But when running logcat from within the app I didn’t get the same information, which I guess is a good thing looking at it from a security standing point.

REST API and Authentication

Since we initially only measure facebook time it’s safe to assume that the users could use facebook to authenticate themselves. One other upside is that we can retrieve their identity by requesting their public information, meaning they won’t need to create a local account for providing a username.

This is where it became interesting, we’ve built a backend using asp.net webapi which allows authorized calls if the user’s authenticated via facebook. The user is authenticated via facebook but via the app, we can’t use the access token issued for the app to communicate securely with our backend. So this is my solution.

android facebook webapi authentication

In a sentence – We issue a new custom token by validating the facebook access token that is passed to us which can be used for secure communication. Pretty neat!

Frontend

I think it was about 2:55am when I finished the app and the API and everything was in place and working. My deadline was 3pm and not a minute more, I needed to be at work 9am and since I’m not in my twenties anymore I need the sleep to function properly.

I hosted the backend in an azure website and I had bought the domain socialtime.se via surftown and once I uploaded the page to surftown I noticed it couldn’t fetch the data. Why? You guessed it, I hadn’t enabled cross-origin resource sharing. So I quickly just installed the nuget package for cors, enabled it, decorated the controller with a EnableCors-attribute, re-deployed the API and voilá, beautiful fully working stack in place. And all this exactly as the clock turned 3am!

 

socialtime_v1.0

It isn’t pretty but hey, it worked!

Future

The infrastructure is in place so adding functionality will go fast. My unprioritized backlog looks something like this.

  • Measure time for Twitter, Instagram and G+, separately.
  • Measure time spent per app and per day. (now it’s just milliseconds since forever)
  • Proper frontend and move it to azure.
  • Remove the public list, you’ll need to login to see only your social time. Several requests for this actually :-)
  • Use some cool HTML5 charting lib to display your social time.

Until then, get the app and have a nice day!

 

googleplay

 

Lab days with focus on security (STS, WebApi, WCF and WIF)

Lab days once again at work, this time I focused on security. Can’t share the code this time since it contains some company confidential stuff but the diagram below basically summarizes my architecture idea.

lab_days_security

Securing WCF service with WIF

There are plenty of blogs out there descibing how to do this so I’m not going to explain this i depth, if you however only have experience with using WIF 3.5 as me I found an excellent migration guidelines page on msdn (http://msdn.microsoft.com/en-us/library/jj157089.aspx). We use a custom binding for tcp transport support with reliable sessions which makes you wanna kill yourself when you see the binding configuration. Due to this I can’t share the code since it is considrered “intellectual property” of Saab (me?).

Important WIF 3.5 to 4.5 change!

You could previously access the calling users claims in the WCF service by casting ServiceSecurityContext.Current.PrimaryIdentity to ClaimsIdentity. This is no longer true, you’ll get the claims by casting Thread.CurrentPrincipal to ClaimsPrincipal or Thread.CurrentPrincipal.Identity directly to ClaimsIdentity. For this to work you’ll also need to set <serviceAuthorization principalPermissionMode=”Always” /> on the service behavior declaration. See also Dominick Baiers post for more details.

JWT, Identity Server v2 and WebApi

I’ve updated our development STS in our product at work from startersts to identityserver v2, which I thought was a great platform to continue exploring, especially since it supported to issue JWT (json web tokens). At least I thought it did until I discovered that it doesn’t! They do however have a branch that supports it and uses Microsoft JWT (https://github.com/thinktecture/Thinktecture.IdentityServer.v2/tree/Microsoft-JWT).

I found a nice message handler that validates JWTs which uses JSON Web Token Handler For the Microsoft .Net Framework 4.5 written by the security guru Vittorio Bertocci (http://code.msdn.microsoft.com/AAL-Native-Application-to-fd648dcf/sourcecode?fileId=62849&pathId=697488104). And as always I encountered major problems when trying to validate the JWT issued by identity server on the server-side (webapi). Victor uses windows azure ad together with Windows Azure Authentication Library which of course validates the token correctly.

I think there is a may release coming up for identity server, perhaps I’ll give it another shot then, but for now I had to use Azure AD.

The outcome wasn’t actually what I expected when I began but the road there was educative, I suggest following Victor on http://www.cloudidentity.com/blog to keep up with the updates on the json web token handler which currently only is in the developer preview stage. It hurts to keep up and always use bleeding edge technology but hey, they don’t call it lab days for nothing. ;-)

 

Peace!

Migrating ASP.NET MVC to WebApi with no breaking changes

Recently I’ve had the pleasure to upgrade our REST interface at work from Asp.Net MVC3 to WebApi so I thought a lessons learned or “watch out for this” blog post was suitable, especially since I managed to do it without the need to bump any version number on our server i.e. no breaking changes.

I think there are others out there that have been using the MVC framework as a pure REST interface with no front end, i.e. dropping the V in MVC, before webapi was available.

Filters

First of all webapi is all about registering filters and message handlers and letting requests be filtered through them. A filter can either be registered globally, per controller or per action which imo already is more flexible than MVC.

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        ...
        GlobalConfiguration.Configuration.MessageHandlers.Add(new OptionsHandler());
        GlobalConfiguration.Configuration.MessageHandlers.Add(new MethodOverrideHandler());
        GlobalConfiguration.Configuration.Formatters.Insert(0, new TypedXmlMediaTypeFormatter ...);
        GlobalConfiguration.Configuration.Formatters.Insert(0, new TypedJsonMediaTypeFormatter ...);
        ...
    }
}

 

Metod override header

Webapi doesn’t accept the X-HTTP-Method-Override header by default, in our installations we often see that the PUT, DELETE and HEAD verbs are blocked. So I wrote the following message handler which I register in Application_Start.

public class MethodOverrideHandler : DelegatingHandler
{
    private const string Header = "X-HTTP-Method-Override";
    private readonly string[] methods = { "DELETE", "HEAD", "PUT" };

    protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Method == HttpMethod.Post && request.Headers.Contains(Header))
        {
            var method = request.Headers.GetValues(Header).FirstOrDefault();
            if (method != null && methods.Contains(method, StringComparer.InvariantCultureIgnoreCase))
            {
                request.Method = new HttpMethod(method);
            }
        }

        return base.SendAsync(request, cancellationToken);
    }
}

 

Exception handling filter

In our controllers we throw HttpResponseExceptions when a resource isn’t found or if the request is bad for instance, this is quite neat when you want to short-circuit the request processing pipeline and return a http error status code to the user. The thing that caught me off guard is that when throwing from a controller action the exception filter is not run, but when throwing from a filter the handler is run. After some head scratching I found a discussion thread on codeplex where it’s explained that this is intentional, so do not throw exceptions in your filters.

We have a filter which looks at the clients accept header to determine if our versions (server/client) are compatible, this was previously checked in our base controller but with webapi it felt like an obvious filtering situation and we threw Not Acceptable if we weren’t compatible. This needed to be re-written to just setting the response on the action context and not calling on the base classes OnActionExecuting which imo isn’t as clean design.

public class VersioningFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {            
        var acceptHeaderContents = ...;
        if (string.IsNullOrWhiteSpace(acceptHeaderContents))
        {                
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "No accept header provided");
        }
        else if (!IsCompatibleRequestVersion(acceptHeaderContents))
        {             
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "Incompatible client version");
        }
        else
        {
            base.OnActionExecuting(actionContext);
        }
    }
}

 

Request body model binding and query params

In MVC the default model binder mapped x-www-form-encoded parameters to parameters on the action if the name and type matched, this is not the case with webapi. Prepare yourself to create classes and mark the parameters on your controller with the FromBody attribute even if you only want to pass in a simple integer that is not a part of the URI. Furthermore to get hold of the query params provided in the URL you’ll need to pass in the request URI to the static helper method ParseQueryString on the HttpUtility class. It’s exhausting but it will work and it still doesn’t break any existing implementation.

[HttpGet]
public HttpResponseMessage Foo([FromBody]MyModel bar)
{
    var queryParams = HttpUtility.ParseQueryString(Request.RequestUri.Query);
    string q = queryParams["q"];
    ...
}

 

Posting Files

There are plenty of examples out there on how to post a file with MVC or WebApi so I’m not going to cover that. The main difference here is that the MultipartFormDataStreamProvider needs a root path on the server that specifies where to save the file. We didn’t need to do this in MVC, we could simply get the filename from the HttpPostedFiledBase class. I haven’t found a way to just keep the file in-memory until the controller is done. I ended up with a couple of more lines of code where I create the attachments directory if it doesn’t exist, save the file and then delete it once we’ve sent the byte data to our services.

[ActionName("Index"), HttpPost]
public async Task<HttpResponseMessage> CreateAttachment(...)
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    } 

    string attachmentsDirectoryPath = HttpContext.Current.Server.MapPath("~/SomeDir/");
    if (!Directory.Exists(attachmentsDirectoryPath))
    {
        Directory.CreateDirectory(attachmentsDirectoryPath);
    }

    var provider = new MultipartFormDataStreamProvider(attachmentsDirectoryPath);
    var result = await Request.Content.ReadAsMultipartAsync(provider);
    if (result.FileData.Count < 1)
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }
    
    var fileData = result.FileData.First();
    string filename = fileData.Headers.ContentDisposition.FileName;
    
    Do stuff ...

    File.Delete(fileData.LocalFileName);    
    return Request.CreateResponse(HttpStatusCode.Created, ...);
}

 

Beaking change in serialization/deserialization JavaScriptSerializer -> Newtonsoft.Json

So WebApi is shipped with the Newtonsoft.Json serializer, there are probably more differences than I noticed but date time types are serialized differently with Newtonsoft. To be sure that we didn’t break any existing implementations I implemented my own formatter which wrapped the JavaScriptSerializer and inserted it first in my formatters configuration. It is really easy to implement custom formatters, all you need to do is inherit MediaTypeFormatter.

public class TypedJsonMediaTypeFormatter : MediaTypeFormatter
{        
    private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
    
    public TypedJsonMediaTypeFormatter(MediaTypeHeaderValue mediaType)
    {        
        SupportedMediaTypes.Clear();
        SupportedMediaTypes.Add(mediaType);
    }

    ...

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
    {
        var task = Task<object>.Factory.StartNew(() =>
        {
            var sr = new StreamReader(readStream);
            var jreader = new JsonTextReader(sr);
            object val = Serializer.Deserialize(jreader.Value.ToString(), type);
            return val;
        });

        return task;
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
    {
        var task = Task.Factory.StartNew(() =>
        {
            string json = Serializer.Serialize(value);
            byte[] buf = System.Text.Encoding.Default.GetBytes(json);
            writeStream.Write(buf, 0, buf.Length);
            writeStream.Flush();
        });

        return task;
    }
}

 

MediaFormatters Content-Type header

Any real world REST interface needs to have a custom content type format and by default the xml and json formatter always returns application/xml respectively appliation/json. This is not good enough, I suggest that you create custom implementations of JsonMediaTypeFormatter and XmlMediaTypeFormatter and insert them first in your formatters configuration. In your custom formatter just add your media type that includes the vendor and version to the SupportedMediaTypes collection. In our case we also append the server minor version to content type as a parameter, the easiest way to do that is by overriding the SetDefaultContentHeaders method and append whichever parameter you want to the header content-type header.

public class TypedXmlMediaTypeFormatter : XmlMediaTypeFormatter
{
    private readonly int minorApiVersion;

    public TypedXmlMediaTypeFormatter(MediaTypeHeaderValue mediaType, int minorApiVersion)
    {
        this.minorApiVersion = minorApiVersion;
        SupportedMediaTypes.Clear();
        SupportedMediaTypes.Add(mediaType);
    }

    ...

    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
    {
        base.SetDefaultContentHeaders(type, headers, mediaType);
        headers.ContentType.Parameters.Add(new NameValueHeaderValue("minor", minorApiVersion.ToString(CultureInfo.InvariantCulture)));
    }
}

 

I think that covers it all, good luck migrating your REST api!

I might cover upgrading from WIF 3.5 (Microsoft.IdentityModel) to WIF 4.5 in my next post, or thinktectures startersts to identity server v2. Take a wild guess what I’ve been busy with at work! ;-)

Performance measurement ASP.NET MVC vs. WebAPI

I’ve been playing around with WebAPI for a couple of days now and I’m quite pleased with most of it so far. At work we have a stripped down a MVC3 site (threw away the M and the V) for ur public REST interface. Except for the ugly ActionResults in the controllers we are satisfied with it so far. I’ve read some articles on how the web api pipeline is supposed to be more optimized so I thought I’d put it up for a test before trying to sell in the platform upgrade to our product owners, also it would result in our first major version bump so we need to be sure that we can benefit from it and not just do it for the sake of fun (for me :-)).

The server side is a simple controller with 4 actions, 1 get, 1 post, 1 put and 1 delete method that only returns a status code, no I/O or business logic we just want to compare the pipelines. The test will run a five parallel threads executing 100 000 requests all together. The MVC site is hosted on a IIS 8 Express server and the WebAPI is both self hosted and hosted on a IIS8 Express server. The test was performed on my developer laptop running on Intel Core i7 CPU @ 2.67 (dual core with two threads on each CPU), 8GB RAM and 64 bit Win7 operating system.

  Avg. request time (ms) Total run time (s) Requests per second
MVC (IIS) 0.42 41.83 2391
WebAPI (IIS) 0.35 35.06 2852
WebAPI (Self Hosted) 0.12 11.67 8567

 

The results don’t say much since the average request time is very fast in all three cases but a relative comparison shows that MVC vs. WebAPI on IIS is ~20% and the self hosted console application is a whole ~260% faster. Although this pure pipeline time will be negligible when adding business logic with I/O operations or even a single WCF call (~50ms perhaps?).

There’s a whole lot more I could write about asp.net webapi but I’ll save it for future blog posts and leave you with the performance measure for now. 

The code for the test is available for download here, please don’t contact me about translating it to VB ;-)

Peace!