New Toys : Part 1 – HTC Sensation

HTC-Sensationhtc_sensation_spec_sheet-small

HTC Sensation, a set on Flickr.

Advertisements

Auberge Du Lac

Once a year my wife and I treat ourselves to a meal at what many consider to be the best restaurant in England. It’s not cheap but Phil Thompson is an absolute food wizard. This is what was on the spring tasting menu tonight, each course accompanied by a different and perfect wine.

Canapés
– Pesto & Cream Cheese
– Walnut & Apple Salad
– Chicken parfait on toasted brioche
– Seared Tuna with Candied Orange Peel and Pomegranate

Amuse Bouche
– Leek and Chive Panna Cotta with Truffle Egg and Herb Foam

First Course
– Caramelised, Hand-Dived Scallop, William Pear Tart Fin, Crispy Pigs Trotter, Sherry Caramel & Thyme

Second Course
– Port & Armagnac Marinated Fois Gras Torchon with Gingerbread, Malt, Peanuts, Banana & Nougat

Third Course
– Morel Ash Coated Loin of Monkfish, Carpaccio of Cheek, Charred Spring Onion, Samphire, Mussels & Bacon Vinaigrette

Passion fruit sorbet

Main Course
– Serrano Ham Rolled Breast of Poussin, Honey Glazed Wing, Brocolli, Roasted Onions & Oregano

OR

– Butter Poached Best End of Little Braxted Hall Lamb, Rosemary Steamed Bun, Goats Curd, Yoghurt & Candied Olive

Champagne Jelly, Blackcurrant Jam & Vanilla Foam

Desert
– Glazed Dark Chocolate & Pear Ganache, Pear Jelly and Puree de Malt

OR

– Cheese Trolley <= has to be seen to be believed

Coffee & Petit Fours

Trying a slice of Blackbird Pie

Just trying out the Blackbird Pie feature on WordPress that lets you embed tweets.

Implementing a REST-ful service using OpenRasta and OAuth WRAP with Windows Azure AppFabric ACS.

I’ve been building prototypes again and I wanted to build a service that exposed a fairly simple, resource-based data API with granular security, i.e. some of my users would be allowed to access one resource but not another or they might be allowed to read a resource but not create or update them.

To do this I’ve used OpenRasta and created an security model based on OAuth/WRAP claims issued by the Windows Azure AppFabric Access Control Service (ACS).

The client can now make a rest call to the ACS passing an identity and secret key. In return they will be issued with a set of claims. A typical claim encompasses a resource in my REST service and the action(s) the user is allowed to perform, so their claim set might show that they were allowed to execute GET against resource foo but not POST or PUT.

In my handler in OpenRasta I add method attributes that indicate what claims are required to invoke that method, for instance in my handler for resources of type foo I might have the following method  :

[RequiresClaims("com.somedomain.api.resourceaction", "GetFoo")]
public OperationResult GetFooByID(int id)
{
	//elided
}

In my solution I have created an OpenRasta interceptor which examines inbound requests, validates the claim set and then compares the claims required by the method attribute to the claims in the claim set. Only if there is a match can the request be processed.

After a few tweets with @serialseb I refactored the above into an IAuthenticationScheme that validates the claims, leaving the original OperationInterceptor to check the claims required by the method to be invoked. I also added an extension method so that the whole thing can be fluently configured like so :

ResourceSpace.Uses.AzureClaimsAuthenticationScheme();

I was going to write a long blog post about how to build this from scratch with diagrams and screen shots and code samples but I found that I couldn’t be arsed. If you’d like more info more on how to do this just drop me a line. In the meantime I’ve dropped the source files as follows :

Getting the hang of hooks

wire-coat-hanger2I’m going to go out on a limb here and say that if I were to ask you which part of a wire coat hanger the “hooky” bit is, that is to say, the part of the hanger that endows it with all its “hookiness”, you’d quite reasonably tell me that it was the part circled in green and labelled A in the picture opposite. However, I have a theory that it is in fact the part circled in red and labelled B. Furthermore, it is a theory that I can back up with evidence from a simple, repeatable experiment which you can try for yourself at home.

1) On a school-day morning as you are trying to leave the house take the last clean school jumper one of your children owns and get them to drop it down the back of a radiator.

2) Run to your wardrobe and attempt to extract a wire coat hanger from in amongst the contents. You will notice that the hanger becomes repeatedly hooked on pretty much everything in the wardrobe. The rail, other hangers, clothes, itself, your hand. Even the very air itself seems to snag as you wrestle the hanger out of the wardrobe. It is, in short, a very hooky thing.

3) Now proceed to unwind section B and bend the hanger out until it is a long piece of wire with a hook on the end.

4) Finally attempt to hook the jumper out from behind the radiator. You will notice at this point that the hanger has lost all its hookiness. You might as well be trying to get the jumper out with a slice of cheese.

You see ? Same hook, same wire but once you undo that twisty bit in section B…useless.

Q.E.D

Amazon recommends…

Hi Bert, this is the Amazon Recommendation Selection Engine or A.R.S.E. Today we would like to recommend :

  1. Things you have already bought from us because you can never be too careful or have too much stuff.
  2. Things that are almost identical to things you have already bought from us because, God knows, once you bought a second one of the thing you already bought a third slightly different one will be hard to resist.
  3. Things you have already bought as gifts for other people and that were obviously gifts because they were completely outside of your known buying patterns.
  4. Things that are almost identical to things you already bought as gifts for other people just in case they need two of everything too.
  5. Things that you looked at accidentally or only because someone sent you a link entitled “LOL! Look at this ridiculous, furry, raccoon-head ski helmet“.
  6. Things that are similar to ridiculous, furry, raccoon-head ski helmets but probably a lot less LOL.
  7. 1 item that is completely inexplicable.

Basically I think that the A.R.S.E is an algorithm modelled on the Junk Lady from the film Labyrinth.

Scrummerfall

Scrummerfall. n. The practice of combining Scrum and Waterfall so as to ensure failure at a much faster rate than you had with Waterfall alone. – Brad Wilson.

I like this definition 🙂

Azure AppFabric ACS Gotchas : Longest Prefix Matching

I recently got bitten by a bit of Access Control Service logic related to the way it identifies which scope to issue claims for.

I have a service namespace foo. My Azure Service Bus scope for this namespace is therefore http://foo.servicebus.windows.net. When I create the solution for this namespace two ACS instances are created. One is https://foo.accesscontrol.windows.net which is a general ACS and the other is https://foo-sb.accesscontrol.windows.net which is scoped specifically to the Service Bus. This second ACS has a default Token Policy and Scope which I cannot change. NB : this has now changed. When you provision an AppFabric namespace now you can sepecify which services should be available (ACS, Service Bus and Cache). If you specify Service Bus you will get the bus-scoped ACS instance. You only get the generic ACS if you specifically request ACS as a service.

In my Service Bus solution I am exposing endpoints at http://foo.servicebus.windows.net/bar and http://foo.servicebus.windows.net/baz. I have an issuer (Alice) with claims for the scope http://foo.servicebus.windows.net who is able to create endpoints at both http://foo.servicebus.windows.net/bar and http://foo.servicebus.windows.net/baz. I have another issuer (Bob) who is able to send messages to endpoints at both http://foo.servicebus.windows.net/bar and http://foo.servicebus.windows.net/baz.

I introduce a new issuer (Ivan) to whom I only want to grant access to http://foo.servicebus.windows.net/baz. To this end I create a new scope specifically for http://foo.servicebus.windows.net/baz and create claims for Ivan in this new scope.

Here’s where I get bitten. Alice can still expose endpoints at http://foo.servicebus.windows.net/bar and Bob can still send messages to them. Ivan can send messages to http://foo.servicebus.windows.net/baz but not to http://foo.servicebus.windows.net/bar which is exactly as intended. However, Alice can no longer expose endpoints at http://foo.servicebus.windows.net/baz and Bob could not send to them even if she could. The reason for this is that although Alice and Bob have claims for http://foo.servicebus.windows.net when they try to access anything at http://foo.servicebus.windows.net/baz they automatically fall into the new scope, for which they have no claims. The ACS matches scopes using the longest possible prefix and if there are no claims it will not check parent scopes.

The solution is simple – add new claims for Alice and Bob in the new scope, but the problem is, at first, counter-intuitive.

RX Extensions & Threading

Like a lot of people, I’ve been playing with Rx recently, the Reactive Extensions for .Net. To find out a bit more about what these are have a look here. One of the things I found interesting was the use of Rx as a fluent interface for creating sets of asynchronous tasks and then subscribing to the collective result with both a result handler and error handler.

I’ve worked up a little example here that shows some code performing some fairly standard asynchronous tasks. When called, my code needs to call a web service, query a database and fetch a value from some cache. It then needs to combine the results. Since these processes each take different and often varying amounts of time and I want to minimise the executing time of my code I’m going to do them in parallel.

I have shown 4 different methods of achieving this, using my own threads, the thread pool’s threads by way of BeginInvoke(), the Tasks namespace new in .NET 4.0 and Rx.

namespace RXThreadingExample
{
	using System;
	using System.Collections.Generic;
	using System.Diagnostics;
	using System.Linq;
	using System.Threading;
	using System.Threading.Tasks;

	public class Program
	{
		public static void Main()
		{
			const bool throwException = false;

			ClassicAsync(throwException);
			WaitHandles(throwException);
			Tasks(throwException);
			RXExtensions(throwException);

			Console.ReadKey(true);
		}

		private static void ClassicAsync(bool throwException)
		{
			var sw = Stopwatch.StartNew();
			var wsResult = 0;
			string dbResult = null;
			string cacheResult = null;

			var callWebService = new Thread(() => wsResult = CallWebService());
			var queryDB = new Thread(() => dbResult = QueryDB(throwException, "Async"));
			var fetchCacheItem = new Thread(() => cacheResult = FetchCacheItem());

			try
			{
				callWebService.Start();
				queryDB.Start();
				fetchCacheItem.Start();

				callWebService.Join();
				queryDB.Join();
				fetchCacheItem.Join();

				Console.WriteLine(dbResult, wsResult, cacheResult, sw.ElapsedMilliseconds);
			}
			catch (Exception ex)
			{
				Console.WriteLine("Exception : {0}", ex);
			}
		}

		private static void WaitHandles(bool throwException)
		{
			var sw = Stopwatch.StartNew();

			var waitHandles = new List<WaitHandle>();
			Func<int> callWebService = CallWebService;
			var wsAsyncResult = callWebService.BeginInvoke(null, null);			
			waitHandles.Add(wsAsyncResult.AsyncWaitHandle);

			Func<bool, string, string> queryDB = QueryDB;
			var dbAsyncResult = queryDB.BeginInvoke(throwException, "WaitHandles", null, null);
			waitHandles.Add(dbAsyncResult.AsyncWaitHandle);

			Func<string> queryLocalCache = FetchCacheItem;
			var cacheAsyncResult = queryLocalCache.BeginInvoke(null, null);
			waitHandles.Add(cacheAsyncResult.AsyncWaitHandle);

			try
			{
				WaitHandle.WaitAll(waitHandles.ToArray());

				var wsResult = callWebService.EndInvoke(wsAsyncResult);
				var dbResult = queryDB.EndInvoke(dbAsyncResult);
				var cacheResult = queryLocalCache.EndInvoke(cacheAsyncResult);

				Console.WriteLine(dbResult, wsResult, cacheResult, sw.ElapsedMilliseconds);
			}
			catch(Exception ex)
			{
				Console.WriteLine("Exception : {0}", ex);
			}
		}

		private static void Tasks(bool throwException)
		{
			var sw = Stopwatch.StartNew();
			var wsResult = 0;
			string dbResult = null;
			string cacheResult = null;

			var tasks = new List<Task>
				{
					new Task(() => wsResult = CallWebService()),
					new Task(() => dbResult = QueryDB(throwException, "Tasks")),
					new Task(() => cacheResult = FetchCacheItem())
				};

			try
			{
				tasks.ForEach(t => t.Start());
				Task.WaitAll(tasks.ToArray());
				Console.WriteLine(dbResult, wsResult, cacheResult, sw.ElapsedMilliseconds);
			}
			catch (Exception ex)
			{
				Console.WriteLine("Exception : {0}", ex);
			}

		}

		private static void RXExtensions(bool throwException)
		{
			var sw = Stopwatch.StartNew();
			Observable.Join(
				Observable.ToAsync<int>(CallWebService)()
					.And(Observable.ToAsync<bool, string, string>(QueryDB)(throwException, "RX"))
					.And(Observable.ToAsync<string>(FetchCacheItem)())
					.Then((wsResult, dbResult, cacheValue) =>
						new { WebServiceResult = wsResult, DatabaseResult = dbResult, CacheValue = cacheValue })
				).Subscribe(
					o => Console.WriteLine(o.DatabaseResult, o.WebServiceResult, o.CacheValue, sw.ElapsedMilliseconds),
					e => Console.WriteLine("Exception: {0}", e));
		}

		private static int CallWebService()
		{
			Thread.Sleep(500);
			return new Random().Next(1,33);
		}

		private static string QueryDB(bool throwException, string name)
		{
			Thread.Sleep(1500);
			if (throwException)
			{
				throw new Exception("You asked for it !");
			}
			return name + " can rescue {0} Chilean miners in {2} ms. {1}";
		}

		private static string FetchCacheItem()
		{
			return new[]{"Awesome!", "Cool!", "Amazing!", "Jinkies!"}[new Random().Next(0,4)];
		}
	}
}

I have to say, I like the syntactic sugar of Rx. In the tests I have run, however, using Task consistently produces the fastest results. More to follow, I think.

Writing Style

I fed my last three blog posts into the “I write like…” analyzer at http://iwl.me. I got 2 David Foster Wallace’s and a Stephen King. Not a bad haul, I think 🙂
%d bloggers like this: