Live coding session – Developing an app prototype in less than an hour

Got some alone time and decided to spend an hour on coding. I recorded my coding session, making this my first official screencast! The idea is to share my thoughts when I write code and perhaps get some constructive criticism / feedback. The task was to create an app to keep track of how much meetings cost for companies. I started from scratch and managed to get a prototype up and running in windows azure in ~50 minutes or so.

Live demo @ http://meetometer.azurewebsites.net/

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

The video is unedited and shot in one take. I hadn’t approached the task more than giving it a thought the night before. With the result in hand I’m pretty satisfied with how it went. Sure I got some errors due to typos but that’s part of the day to day work for a developer. I also encounterd some bugs due to framework incompatibilies which I managed to tackle as well.

If I do a second sitting the roadmap is to implement a server side solution. Perhaps make it a multi-tenant site and store all meetings to get an overall cost per month for instance. Sounds like a plan? ;-)

Happy holidays!

 

Keywords : VS2013, Azure, HTML5, JavaScript, AngularJS, jQuery Mobile, AmplifyJS

Using Microsoft OAuth Identity provider with IIS Express

Shouldn’t be any problem right? Facebook apps allows you to specify localhost for the callback/redirect url. Sweet! But microsoft doesn’t! So this is what I did.

I created a new application https://account.live.com/developers/applications/create and specified kingen.se as redirect domain.

I added a DNS record to C:\windows\system32\drivers\etc\hosts that routes 127.0.0.1 to kingen.se.

I changed the site binding in %Documents%\IISExpress\config\applicationHost.config :

<site name="<site name>" id="24">
  <application path="/" applicationPool="Clr4IntegratedAppPool">
    <virtualDirectory path="/" physicalPath="<your-path>" />
  </application>
  <bindings>
    <binding protocol="http" bindingInformation="*:80:kingen.se" />
  </bindings>
</site>

I changed the “Default Web Site” binding to port 8080 (or whatever) for IIS.

I turned off SQL Reporting Services because the agent used port 80. Use netsh to list port usage if you run into other problems.

netsh  http show urlacl | Select-String :80
Finally in my asp.net mvc project I changed the properties for the project to
  • Use Local IIS Web server
  • Check Use IIS Express, Project Url: http://localhost
  • Check override application root URL: http://kingen.se
  • Set Start URL to: http://kingen.se/
Voilá, press F5 and IIS Express will fire up on http://kingen.se with a working Microsoft OAuth Identity provider.
Cheers!

ASP.NET MVC and AngularJS

I really think these two frameworks don’t mesh together too well and this blog post is me trying to explain why.

If you’re used to traditional MVC with full page refreshes, views, server side partials etc. and you’ve decided that you want to use a bit of angular inside your pages you are going to be very frustrated. Angular is really best for single page applications (SPA seems to be a buzz word for the moment). If you just want some javascript goodness just use knockoutjs.

I’d suggest using WebApi instead. This is what I’ve found out works best.

  • The server side actions on the ApiController should only return JSON data to the client and be consumed by ajax calls from angular.
  • Stop thinking in terms of razor and writing C# code in your views and working with the @model passed from the controller.
  • Only have one razor page for your app (Index.cshtml), no views, no partials. Load everything on the index page.
  • Do not use the MVC routing, let angular perform the dynamic page updates.
You might ask yourself; why use razor at all? Well the Web.Optimization bundle is quite neat and I’ve grown quite attached to it :-)
 
For SPAs sure go ahead and use angular it’s awesome. But stick with angular/javascript for front-end and use WebApi for back-end if you’ve decided that you want to try out angular on top of asp.net.
 
Also imo SPAs should be fairly small, if you know your project will be fairly big SPA really isn’t the way to go. It could be me just having a hard time to adapt since I’m used to hooking everything up in a spaghetti of document.ready-functions :-P I’ve always been a “back-end / do it on the server / use as much static typing as possible” kind of guy but perhaps that’s changing, especially with tools like TypeScript which is a must in all my web projects nowadays.
 
I might add that I also have experience using angular together with jQuery mobile when developing a scorecard app for golf (golf-caddie.se) which wasn’t too pleasant but that’s another blog post (two frameworks manipulating the DOM don’t play nice together). 
 
Just my thoughts, it’s not written in stone :D

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! ;-)