Posted by & filed under .Net.

A little side-project of mine has involved building a new plugin for Enterprise Tester, the Test Management Software I’ve spent the last few years working on for Catch Software.

As of a couple of weeks ago I have finally released the plugin to the public.

 

Thoughtmix.com – Powerpack Plugin for Enterprise Tester

 

If you head on over to the website you can download the plugin installer, and sign up for a free 30 day trial. The plugin is compatible with Enterprise Tester version 4.10 and above.

As the name suggests, the “powerpack” is a grab-bag of new features for Enterprise Tester which allow customers to do more with their ET investment.

  • Custom Fields – Cascading Select, Geolocation, Labels, Sliders, Hidden Fields, Time Of Day, Users & Groups etc.
  • Dashboard Portlets – Including a grid search results portlet, tag cloud & Who’s online
  • Run History Grid Column
  • TQL Search functions for find results based on attachments or comments
  • Community comments for the in-app help

And based on community feedback we plan to add more features over time.

For any Enterprise Tester users out there – I would love it if you could give the plugin a try and provide any feedback you might have so we can continue to improve the product.

Also if you have any great ideas for other plugins you would like to see us build for ET, or features to add to the powerpack plugin, then head on over to our uservoice site thoughtmix.uservoice.com where you can post new ideas or vote for existing ones you would like to see implemented in upcoming releases of the product.

Happy Testing!

Posted by & filed under News.

For those who know me personally, they probably know Renee & I were expecting our first child this month. Well she has finally arrived.

Ivy McAuley Henderson, Born 24th August, 10:26pm.

Both Mum and Baby are very well :)

Posted by & filed under .Net.

So I had a spare half-hour this weekend, and thought I would take the time to finally plug in Mindscape’s Raygun service to Enterprise Tester.





For this I decided to implement it as a plugin to Enterprise Tester, as it doesn’t really make sense as a core feature for an application which is deployed both on-premise and hosted.

For Enterprise Tester, many of the exceptions within the application are not unhandled, but logged as ERROR level events in log4net with an associated exception object (especially on background threads), So for the plugin implementation I ended up:

  • Building a simple log4net appender that then logs to Raygun for ERROR and greater level events when an exception is present.
  • Building a simple listener for the app-specific “UnahandledException” event (this is where failures to start ET up, or fatal errors causing the shutdown of ET would crop-up, if the log4net configuration etc. has yet to be loaded).
  • Building a wrapper for the raygun message builder, that encapsulates adding some user custom data to the message being built – in this case containing details of the current user and their license entitlement (making it easy to identify the customer associated with the exception).

The whole process was incredibly simple, using the RaygunMessageBuilder class really simplifies the process of building up a suitable raygun message to fire at the service, and is a great starting point for creating a more application-specific message builder.

As I mentioned, this is built as a stand-alone plugin (not bundled with Enterprise Tester) – so if you want to get it, the source is available on the Enterprise Tester API examples project on github, and if you have any questions about it, please log them as issues on the github project.

Posted by & filed under Architecture Chat, Community.

Hi All,

It’s 2013, and the Architecture Chat is back for the new year, after taking a little break.

We will be meeting this Thursday, 17th January at 11:30am, at Benediction Cafe, Newton.

We are collecting topics on the following google doc:

https://docs.google.com/document/d/1g2rCkS1DhnpulLlEjIsCL_ayrATC5zifLjyViz_jEYM/edit

And if you have not been to the Architecture Chat before, you can find more about it here:

http://blog.bittercoder.com/architecture-chat/

Also, don’t forget that Codemania is on the 12th April, 2013 this year, with tickets on sale now.

Early-bird pricing runs out on the 13th of Feb – this year also sees the introduction of a couple of half-day workshops as well.

More goodness for all!

Posted by & filed under .Net, News.

Catch Software, where I lead development on Enterprise Tester (among other products) are expanding the development team.

We are looking to add a full-time (Salary) software developer to work on product development.

If you are:

  • Pragmatic.
  • Passionate.
  • Based in Auckland, New Zealand.
  • Care about your craft.

And have a keen interest in:

  • Shipping! Often!
  • Directly influencing the design inside and out of software being delivered.
  • Building extensible software.

Then we want to talk to you.

Enterprise Tester is a web application primarily written in C# and JavaScript (and a bit of F#), so those skills will be essential for you to fit well into the roll. The codebase is very JavaScript heavy so candidates with exceptional JavaScript development skills, with less experience in C# (or just a waning interest) would also be a great fit.

Beyond that the ideal addition to our team will need to be somebody who:

  • Has a sense of humour.
  • Proven track record.
  • Does not drink too deeply of the Microsoft cool-aid.
  • Interested in the challenges of building a platform (API’s, plugins, server-side and client-side extension points etc.)
  • Enjoys constantly learning.
  • Has great spoken and written communication skills.

We are a close-knit group at Catch Software, and have a great team – so we are going to be a little picky about who we add to it, be fore-warned – but to counter this, for the developer we decide to add to the team, this is also a well remunerated position acknowledging the skills you can bring to our team ($150K+).

P.S. If I talked to you about working at catch software over the last year, and you’re looking for a change of scene in 2013, Drop me a line and we can catch up for a coffee/talk.

The official job advert can be found here:

And if you want to know more about what Catch Software does, check out the following links (or just talk to me).

If you wish to contact me directly, you can find my contact details here.

Posted by & filed under .Net, Code Retreat, Community.

This year New Zealand participated in the Global Day of code-retreat, with 2 groups in Auckland, and 1 group in Wellington participating last Saturday, 8th December 2012.

First off, I want to give a big shout out to all the people involved in organising the events:

As well as to all the local sponsors:

And definitely a big shout out to the global sponsor Jetbrains and the nice folks behind code retreat including of course Corey Haines, Jim Hurne, Alissa Conaty and Adi Bolboaca.

And last of all, a huge shout-out to all who came and attended – The weather on Saturday was really nice, so to have people take a whole day out of their weekend to come code, instead of spending it at the beach, is huge, and there wouldn’t have been a GDCR in Auckland without your participation!

First-time Facilitator experience

My role for the day was as the code retreat Facilitator – so I spent my time leading everyone through the 5 x 45-minute sessions as different pairs worked through Conways game of life with different constraints, and while they were coding I would move around observing, poking at peoples code where they were having difficulty with the constraints, or where names, tests etc. could be improved (so I would suggest things such as “is that code very intent-revealing?” .. then breeze away before they asked how ;o) or just needed some general guidance – and of course generally trying to keep the day moving along, pulling people together for retrospectives and organizing the final circle.

For our group, there was a mix of Javascript, Java and C# mostly- though there were people giving Clojure, F# and C++ a go as well.

Overall I think they day went really well – Certainly for the first 2 sessions, some people were struggling to make much progress, but for the third session we did baby-steps, which forced people into focusing on writing a passing test + working code within 3 minutes, or rolling back their changes, which really focused some of the people used to working in a test-after fashion, driving out much smaller tests – and I think set the tone for the last 2 sessions, as people really began to focus on implementing solutions in an incremental fashion.

For the afternoon we did no return values (which really got some people twisted up, though we also had some pretty creative solutions as well!)

Last session was a choice of verb instead of noun – or – free choice of constraints from an earlier session, though most people opted to try out verb vs. noun, and lots of people found that quite challenging as well, and sparked some interesting discussions on how verb vs. noun can lead you incrementally towards a very functional solution.

Herding people is a skill

As a first-time facilitator I found one of my weaknesses was in getting people gathered for the retrospective immediately after the session… people would delete their code and stand up – but there was a good few minutes of herding cats to get everyone into a circle (entirely my own fault) as people really wanted to talk about what they had been doing with their pair, this disrupted the flow between sessions a bit, but thankfully didn’t cause too much issue really, In the future I think I would try and launch into the retrospective even if there were a few stragglers, so as to keep the flow of the day.

Probably the most frustrating thing during the day was that internet access at our venue spent more time down then up, which really hampered out ability to participate in some of the “global” aspects of the global day of code retreat… That said we did manage a hookup with both Corey in the morning, and the Australian (Sydney) and New Zealand venues during the day (at least long enough to wave “hi”). The poor internet access was also wreaking havoc for those trying to download packages via maven or nuget (and yet again stresses the fact that having your environments setup before hand is a good idea!)

Personally as a first-time facilitator I found the experience really rewarding, it’s not often you are given an opportunity to observe a room of almost 30 developers, all really smart and passionate people practicing their craft – and it really provides an insight (albeit brief) into how people think and approach solving problems.

I think if I took anything away from the day, it’s that our community have a handle on the complex technical aspects of their craft, but what we consider the “Simple” aspects of our work (good names for both code and tests, writing tests that don’t test too much or too little, and writing test-first red/green/refactor) are things we talk about more then actually practice.

I don’t think we’re lazy, I just think these simple things are actually pretty damn hard – and when under the pressure to deliver, “it works” and “that’s an acceptable number of defects” override our drive for good names, and code that readily reveals intent for the future maintainer (normally ourselves, at a later date).

2013, year of Practice?

Looking towards 2013 I would love to see what interest we could get in:

  • More code retreats.
  • Legacy code retreats (I would really like to run or participate one of these, as legacy code is something dear to my heart)
  • TDD like you mean it (I think we could do some half-day events around this, but I’m not sure if I’d be the best person to run it!)

There’s also been some discussion around maybe kicking off some more informal things like a “Coffee and Code” club in Auckland, which sounds like a great idea, assuming we can find some “understanding” cafe’s (with wifi) where we can do this, and times that work for people.

All in all, it sounds like 2013 might be the year of “Practice” for developers in the Auckland region (here’s hoping!).

Awesome Flickr Gallery Error - SSL is required

Posted by & filed under Code Retreat, Community.

What is it

The 8th of December (Saturday) is the Global Day of Code-retreat, and through the virtue of timezone magic, New Zealand will be kicking off this global event.

Global Day of Coderetreat is a world-wide event celebrating passion and software craftsmanship. Last year, over 1800 passionate software developers in 94 cities around the world spent the day practicing the craft of software development using the coderetreat format. This year, we are aiming for 200 cities! With an average of 15-20 participants per city, that’s over 3000 developers!

The previous code retreat was a great experience, organized by Ian Randall (@kiwipom, of Codemania and not to mention XAML fame) and was facilitated by none other then Corey Haines himself. If you didn’t make it along (or were stuck on the waiting list) – then you really did miss out on a great event!

Unfortunately Corey can’t be with us on the 8th of December… so we have the second best.. no wait the third best.. no wait definitely the fourth best… well a thing, that is me, who has offered facilitate the #GDCR12 event in Auckland, and Ian Randall is again stepping up as organizer for this event.

Should I come?

Yes!

I think the evidence of how much fun and value people find in attending a code retreat is that many of the first-time attendees have signed up once again!

So if you are keen to come – definitely get in quick and sign up on the meetup event.

Depending on interest I believe a second code-retreat session may open up, but regardless, spaces are limited, as these events are generally restricted to around 20-30 people each for reasons of practicality.

If you plan to sign up, please:

  • Only sign up if you definitely can attend (and withdraw ASAP if you learn you can no longer attend) as space is limited.
  • Don’t sign up unless you plan to be around the whole day, if you can only come for a couple of hours, be fair and give up your slot to someone else who can attend the whole day.

Costs

As Ian indicated on the meetup event, the first event was free to everyone, but ran to a cost of about $50+GST per person (covered kindly by the sponsors) – and costs are expected to be similar this time around, so if you know of anyone (such as the company you work for) who would be willing to sponsor some or all of the costs associated with the day, please contact Ian ASAP.

Venue

The first code retreat was held at the BizDojo Makerspace – which was a great venue – but unfortunately it’s not available for the 8th of December, so we need a new venue for the Code Retreat to be held at.

Ideally a location close to or within the Auckland CBD would be great, with space for 30 or so people to sit at tables, and with power and internet connectivity.

If you know of a space, please contact the organizer (Ian), to discuss it further.

Attending

For those attending the event:

  • Keep in mind you will be pair-programming, so you will need to bring along a laptop and a power cable.
  • Ensure you have the tools/editors etc. installed before the day for languages you are comfortable in – the aim is not to learn a new language, but hone your craft – so you don’t want to spend the first session setting up an environment.
  • This is a pretty full-on day of coding, and can be exhausting, being well-rested is definitely a good idea

FYI – if you do want to get a feel for a different language – don’t forget that there will be plenty of developers working in different languages, so you can always pair with them to get a taste (and this is a great way to see how people familiar with those languages think and work with the tools they are intimately familiar)

If you have not attended a code retreat before, you might also find it interesting to read about what a code retreat is!

coderetreat.org – about

And also watching Corey’s retreat introduction on Vimeo gives you a good taste for what we will be doing:

This will be my first time facilitating a code retreat – so things are bound to be a little rough around the edges (Corey has had years to master the code retreat format, and is also crazy smart) – but I’m confident everyone will have a great experience.

(FYI – For those interested in how the day will unfold, we will be following the structure outlined here – but this will all be covered during the start of the code retreat session, so don’t feel you have to swat up on what we will be doing)

coderetreat.org – structure of a code retreat

See you there!

Can’t wait to see everyone there, and have some fun honing our craft together.

Posted by & filed under .Net, Code Retreat, Community.

Auckland Code Retreat



The first code retreat in NZ (AFAIK) was organised by Ian (@kiwipom) on Saturday October 27th, and facilitated by the one and only Corey Haines.

It was a great event – and I offer a big thanks to Ian, Corey and the sponsors, as well as the gracious hosts at the Bizdojo makerspace who diligently made coffee and kept us well fed.

The whole day was great, and I think a comment from a fellow attendee Josh Robb in the closing circle rang very true with me as well, in that I came away pleasantly surprised at how much relevance the sessions had to the day to day work I do. Every time we commenced a new session, with some different constraints, I found myself thinking of code I’ve written in the past where the same challenges were faced, or problems such as primitive obsession perhaps led me away from discovering a far more suitable abstraction or approach to solving a problem.

Through the day I got to pair with people mostly in .Net (C#) – as well as with a scala developer (though we paired using Java) – and a good mix of developers at different experience levels (at one point I even found myself having to give a very brief crash-course in Lambda’s to my pair who I guess was probably stuck working with older versions of Visual Studio/legacy code bases).

Comfort

I think one thing that surprised (but also, not really… ) was how ‘comfortable’ I’ve got in the last 7 years, since I started working from home.

I’m not talking comfortable i.e. lazy / set in my ways – the last 7 years I’ve spent working from various home-office’s have probably been some of the busiest times of my life, with lots of challenging tasks. And I certainly keep myself busy talking to other developers, sharing experiences and trying to learn from others.

But what I mean is comfortable in my working environment…

Over the years I have slowly reduced my tech life down to:

  • A fast Desktop PC.
  • Lots of screen space (3 x 30″ monitors + sometimes some additional smaller screens)
  • A good full-sized keyboard (currently using a daskeyboard, though the previous Logitched G15 I had was also good for other reasons).
  • Full size mouse (or a mouse at all).
  • Windows.
  • Resharper
  • Coding largely in isolation.
  • Using a laptop probably once every couple of months.
  • Largely working on brown fields projects.

So when it came to pairing on laptops throughout the day (and deleting my code every 45 minutes) I found:

  • My muscle memory for different laptop keyboard layouts was non-existent.
  • I really struggled with laptop keyboard cramping/typing accuracy
  • My Mac keyboard knowledge is very poor – and same goes for my knowledge of Elicpse shortcut keys.
  • I struggle to work around Visual Studio without ReSharper, and my ReSharper keyboard short cuts are somewhat non-standard.
  • I struggle with a single screen (I generally work with test + code side-by-side on one large screen, and the test runner on another).
  • I wasted time setting up test frameworks etc. unnecessarily (A force of habit coming from my brown-fields background) – when I could just have easily written a single-line Assert method that throws an exception and been done with it – and had a few extra minutes to focus on the actual problem.
  • I wasn’t great an articulating my ideas to other developers necessarily

This all lent itself towards a feeling of general uneasiness. But the good, motivating kind, if you catch my drift. The up-side of the code-retreat session is that deleting your code after 45 minutes makes it easier to forget the uneasiness and clear your mind ready for the next session.

So What?

Well I think I came away overall with a stronger desire to start pairing with people more often. The 45 minute session format really surprised me – it may not be long enough to necessarily solve the problem, but it’s a great length of time to learn something / hone your craft around a particular constraint.

And it’s certainly pushed me into trying and see if I can fit at least 1 session of pair-programming into my weekly routine if at all possible.

One Idea I have is perhaps pairing with somebody either immediately before or after the Architecture Chat that’s run every second Thursday… so if anyone is in town and keen for a quick hour of pair-programming, let me know and perhaps we can catch up :)

Posted by & filed under .Net.

Demonstrate all the things!

As you might have noticed, I have been doing a bit of work on API’s in the past couple of months – and one of the things that has evolved out of this work, is my approach to demonstrating an API to an audience of developers and non-developers alike, for example during meetings to discuss progress etc.

I have tried a few things, including cURL, Fiddler, Javascript (with CORS) etc. in the past – but have settled on the combination of google chrome + a chrome browser add-in called “Advanced REST client”, available from the chrome store for free:

Quick Tour

It’s a pretty basic tool (also why I like it..)

The main interface is geared towards sending requests:

And here we can see the list of previously saved request (this will include the raw request body, headers etc.)

And here an example of a POST request, with a JSON body:

So to recap, advantages this tool has over some of the alternatives I have tried:

  • Simple
  • Does not require admin access, or a specific Operating System (like say Fiddler) – though still no support for the chrome store on iPad unfortunately.
  • Pretty-printing of JSON results (but still being able to access the raw response)
  • History of requests (persisted between sessions transparently)
  • “linkifying” hyperlinks in responses
  • Ability to save requests (and keyboard shortcuts for features like Save)
  • Handles form encoding and mixed/multipart file uploads

And of course, like any tool, it’s not perfect – in particular:

  • Sometimes automatic hyperlinking in responses does not work
  • It would be nice if you could click on a link in a response, and have it update the URL text field
  • Basic auth doesn’t work using Username:password in URL most of the time, you need to assign a header (which requires manually base64 encoding the username/password pair).

But overall I’m pretty happy with it.

So, Are demo’s important?

Yes!

Obviously a demo is great to get buy in and upskill your whole team internally, or for getting customers up to speed on what’s possible with your particular API.  But even more so an API is feature that provides very little value unless people use it, even less so then the 80% of the features in your App that are seldom used, as the cost of maintaining an API is high (it becomes part of the work you do for every release of your product once incorporated into your product).

Beyond the obvious though, the thing I have found most interesting is how demonstrating an API really focuses your attention on what’s missing in your API from a usability perspective (especially with consideration to hypermedia) – I would rate this activity almost as high as attempting to develop a client for your API (another great way of finding missing features).

Give it a try, I think you will find it a really effective way to shake out bugs, oversights and general “cruftyness” issues in your API design.

Tell a Story

In demonstrating an API, the approach I use is to first whip up a quick narrative or story for the parts of the API I want to demonstrate (thanks sublime text distraction-free mode!)…

One approach to use when trying the pique the interest of a mixed audience is choosing a story which demonstrates things you can do via the API which are not possible or easy to achieve via the user interface – Focus on points of difference, as opposed to what’s similar, or appeal to past pain that an API might be able to resolve for them.

If you want to know after your demo if you got the narrative right, just observe your audience… far-away looks in peoples eyes and lack of questions == story they don’t care about.

When doing this I try to avoid:

  • “Given When Then” – Given you want to create a widget, when the widget does not exist, then you POST to widgets collection resource. It’s not engaging or fun for people to listen to..
  • Skipping the steps to finding the resource you are going to work on – so for example if I’m going to update the groups a user belongs to, performing a GET request directly on a /user/{id}/groups collection resource is guaranteed to loose parts of your audience. Performing a search on /users (by name), then retrieving the individual user, and then traversing the rel=groups link from the user to fetch the groups, will be more familiar.

And I also try to incorporate:

  • Switching back to the User Interface regularly (if applicable) – as you fetch resources, relating that back to the equivalent UI (if one exists) can keep people on-track, it also leads to useful observations i.e. I can see this field in the UI, but I can’t see it in the representation returned.
  • Selecting parts of a response (using your mouse to hilight) for example what might have changed as the result of a PUT request – especially for people who don’t speak “JSON”.
  • JOSN lessons – People are familiar with XML, but don’t assume the same of JSON. Take some time to explain how a value relates to a key, or what an array is. The pretty printing of JSON in the REST client helps here as well, because you can easily collapse parts of the JSON response, showing that all the items belong to an array etc.
  • HTTP Method refreshers – Keep explaining what PUT, POST and if you support it, PATCH do… it’s not enough to just explain this once.
  • Relate what you are doing back to any API documentation you have (so for each request you end up flipping to the API help, then issue the request, review response, flip back to API help, look at response example, and then back into the UI).
  • Failed requests are important too i.e. accessing a resource with missing/invalid query parameters, or missing parts in the request JSON – make these part of the story, and relate them back to your API documentation as well. And take a critical eye to anywhere you turn up a 500 general exception error – is it truly exceptional, or a common failure case that deserves a response guiding API users towards the pit of success, if so, fix it and also demonstrate it so API users are encouraged to explore.

Dry-run

Once I have my narrative sorted out (and have included some queues in the story to remind me about things like switching to UI etc.) then I’m ready for a dry run.

At this point I work through each step of the narrative – this is normally where you become immediately aware of usability issues in your API:

Inability to navigate:

These normally turn up as “smells” as opposed to outright bugs:

  • Having to copy an ID from the current request to then construct your next request URI.
    • Action: Add a link to your response, or consider an Expand if applicable (favour links over expands though I think).
  • Moving to next page of a page collection resource requires you to change the URI.
  • Navigating to a link, and getting an exception message back due a missing parameter.
    • Action: return a human friendly message explaining how the resource needs to be used.
  • 404 not found.
    • Action: Fix it, probably an issue with routing, or a resource you have forgotten to implement, doh!

Errors when reusing responses as the body of requests:

This is a death move when demonstrating API’s, but often not an issue when writing a client. If you make a GET request, you should be able to use the response in a PUT request without changing anything, even if some of the content is ignored.

Failures here indicate problems with adhering to the Robustness Principle (Be conservative in what you send, liberal in what you accept). Common causes for this failure are things like expanded properties and links, which adorn but don’t necessarily make up part of the DTO underlying the API implementation, which might be rejected if you have an “error on missing member policy” in your JSON deserializer (normally only applies to an API written in a statically typed language).

Unable to locate/display the results in the UI

This is another common issue – normally because you have too much data in your sample set, or don’t have features in your UI to navigate directly to an item by ID or Name.

There are a couple of ways to make this easier – either make it really easy to locate an entity by some kind of unique ID also present in your resource representations (In a thick client App I normally like to do this via a bespoke “go to’ dialog, activated via CTRL+G).

Or (my preferred approach for a web app) include an “Edit” absolute URI as a link associated with your API resource, which can be used to navigate to the equivalent UI screen in your application – as an added bonus, the Advanced REST client will “linkify” these hyperlinks in your response – so you can just right-click, open in new window, and be taken directly to the equivalent item in the UI, making your demo very seamless.

General Tips

Demonstrating from a data set that you can revert back to is also important, especially if you want to create a screen cast, where multiple takes may be required.  Any demo you do should be easily repeatable.

Also, for each request where you are making a request with a body or complex URI (i.e. maybe containing a search query) then use CTRL+S to save your request as well, this can be helpful in cases where you are having trouble during your Demo and need to get a known good response (requests are also saved in history, but this is limited to last 60 or so requests by default).

Also, remember to always use the Raw input / Raw output tabs in the REST client when copying a response for use in a new request – and explain this when demonstrating the API to people who might want to go and try your demo for themselves, as copy/pasting from the pretty-printed response tab, when not understanding JSON structure, can lead to people getting frustrated quickly.

Live demo

At this point your live demo should go smoothly, but there are certainly some things to check off your list before starting:

  • Reverting to your known good data set, if possible
  • Having a couple of displays attached, so you can have your narrative+support data on one screen, and the demo of another.
  • Pre-load pages for the help content you will need (if your API documentation is too large to quickly navigate).
  • Check all your automated integration tests still pass before demoing off a W.I.P codebase.. nothing worse then having to fix bugs/routing issues mid-demo

Side note – Authentication

Thought not strictly necessary – I think supporting session based authentication for web application API’s really helps with the demonstration process – though security is important, and session is not a common use case for programmatic access to the API, as a learning aid it’s very useful.

This advice only applies to API’s in the small (what I have been working on mostly i.e. API exposed as part of an on-premise/hosted application) – For large public web properties and multi-tenanted applications, this is probably not a wise decision, depending on how the API is deployed, and I would revert to using Basic Auth for demonstration purposes, and probably use a different tool to the Advanced rest client plugin as well (say fiddler).

Posted by & filed under .Net.

Introduction

CORS (Cross-origin resource sharing) is a way in which a browser can make a request to a web server other then the one which served up the original resource.

As per the Mozilla docs:

The CORS specification mandates that requests that use methods other than POST or GET, or that use custom headers, or request bodies other than text/plain, are preflighted. A preflighted request first sends the OPTIONS header to the resource on the other domain, to check and see if the actual request is safe to send. This capability is currently not supported by IE8′s XDomainRequest object, but is supported by Firefox 3.5 and Safari 4 with XMLHttpRequest. The web developer does not need to worry about the mechanics of preflighting, since the implementation handles that.

You can achieve this using a DelegatingHandler in ASP.Net Web API – the way it works is to:

  • Identify requests containing the “Origin” header”
  • If the request is NOT of HTTP method “OPTIONS” (no preflighting) then we add the following headers to the response:
    • Access-Control-Allow-Origin – this will have the same value as the Origin value passed in the request.
    • Access-Control-Allow-Credentials – this will have the value true, allowing requests to contain basic-auth credentials
  • If the request is of HTTP method “OPTIONS”, then we treat this as a “pre-flighting” request, responding with a 200-OK response, and returning the following headers in the response:
    • Access-Control-Allow-Origin – this will have the same value as the Origin value passed in the request header.
    • Access-Control-Allow-Credentials – this will have the value true, allowing requests to contain basic-auth credentials
    • Access-Control-Allow-Methods – this will have the same value as the Access-Control-Request-Method value passed in the request header.
    • Access-Control-Allow-Headers – this will have the same value as the Access-Control-Request-Headers value passed in the request header.

And here’s the code to achieve that:

public class CORSHandler : DelegatingHandler
{
 const string Origin = "Origin";
 const string AccessControlRequestMethod = "Access-Control-Request-Method";
 const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
 const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
 const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
 const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
 const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";

 protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
  bool isCorsRequest = request.Headers.Contains(Origin);
  bool isPreflightRequest = request.Method == HttpMethod.Options;
  if (isCorsRequest)
  {
   if (isPreflightRequest)
   {
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Headers.Add(AccessControlAllowOrigin, 
      request.Headers.GetValues(Origin).First());

    string accessControlRequestMethod = 
      request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();

    if (accessControlRequestMethod != null)
    {
     response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
    }

    string requestedHeaders = string.Join(", ", 
       request.Headers.GetValues(AccessControlRequestHeaders));

    if (!string.IsNullOrEmpty(requestedHeaders))
    {
     response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
    }     

    response.Headers.Add(AccessControlAllowCredentials, "true");

    TaskCompletionSource tcs = new TaskCompletionSource();
    tcs.SetResult(response);
    return tcs.Task;
   }
   else
   {
    return base.SendAsync(request, cancellationToken).ContinueWith(t =>
    {
     HttpResponseMessage resp = t.Result;
     resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
     resp.Headers.Add(AccessControlAllowCredentials, "true");
     return resp;
    });
   }
  }
  else
  {
   return base.SendAsync(request, cancellationToken);
  }
 }
}

If using basic-auth, it’s worth noting that the pre-flighted request is unauthenticated – so add the CORSHandler to your configurations set of MessageHandlers prior to any authentication handlers, so the OPTIONS requests can be handled correctly.

Access-Control-Allow-Credentials

In the handler above we enable Access-Control-Allow-Credentials – meaning if the Web API supports basic auth, then the browser is able to authenticate with the API using basic-auth cross-origin, in a jQuery ajax request that would look like this:

$.ajax({
  url: "http://localhost/myapp/api/collectionres,
  type: "GET",
  username: "mylogin",
  password: "mypassword",
  data: "$top=10"
  xhrFields: {
 withCredentials: true
  },
  crossDomain: true,
  success: success
});

I definitely don’t recommend this approach for production code – but, it can make for great way for people to play with an API programmatically in javascript, without having to resort to using Node (and using a tool like Dropbox allows them to privately “host” their html/javascript as well, making it possible to share and collaborate on simple mashups).