This blog has moved to magnusmartensson.com

Hey readers!

My new domain is magnusmartensson.com and my new blog feed, to which you can subscribe on this feed:

Read “Demystified: The Windows Azure SDK Break Down” and more by subscribing here:

=> http://feeds.magnusmartensson.com/magnusmartensson <=

The time has come. My beloved domain noop.se with my personal Techie.notepad blog blog.noop.se which you are currently readihng has been with me a long time but now it’s time to move.

I am establishing a new more professional platform for my work-life. One which is not based on a geeky online handle, noopman. I have had this handle my entire online life and will continue to use it.

Hope to see you in the new feed and that you stay in touch!

Cheers,

Magnus

Google Chrome is vulnerable to, well, just about any virus attack!

The fact that Google don’t want to play nice on a PC environment and install where any responsible company would has been annoying me since Chrome came out! So imagine how I was not surprised and just felt like shouting from the roof tops today!

I’m not gonna, I’m not gonna… who am I kidding? ;~)

I told you so!

I guess since it’s Chrome and Google I’m sure there will be many people wanting to explain away this screen shot and say it’s something else! Go ahead – I dare you:

ChromeVirus

Please oh high lords of Google – don’t do evil on my system – fix your broken ass installer to install under normal security contexts!

Cheers,

M.

//build/ impressions

It is a really hard paced week here at the Build Windows (8) launch event (//build/). The 3500-5000, roughly, developers who are here are all scrambling to keep up while picking up pieces of our brains from the floors since most of what we see here in Anaheim CA is blowing our mind! Yes almost literally. Color me impressed folks!

The fact that we were given a Preview Tablet with Windows 8 and all the new development tools was really awesome:

WP_000425

With this we can get going immediately and develop the new Metro style apps with use the new Windows Runtime APIs and also use the new Cloud Syncing data service offerings that Microsoft are providing us. And then I’ve not even gotten started on Windows 8 Server.

Let’s try to break things down a little:

The new Metro design to the Windows 8 desktop is a HUGE shift in focus for Microsoft. This is a touch first design where a lot of research and attention to detail has been placed into making something beautiful as well as very easy to use. This will be a major change for users who begin using it when it comes out. Gone is the start menu with dead icons and hello there Live Tiles – big blocks of styled content which will bring you updated information at your fingertips from the status of your apps.

WP_0004302

The new Windows Runtime APIs some say is the announcement of the death of Win32. It is strange how we humans seem to love to relish in the negative. Win32 will be around for very many years. .NET is all staying around too btw. Another fun comment/question I heard here at Anaheim. There is no difference here for .NET or the CLR or the BCL. They are all evolving and sticking around. The new thing, WinRT, is a set of native APIs which we can use code almost no code at all to access the underlying hardware and many more things which I am just now coming into grasp on. But wait a minute! Did I just write native? Does this mean we have to do PInvoke and stuff in order to use this? Not at all! Microsoft has gone and changed the way we call from managed into unmanaged code and even provided us with rich metadata on the native libraries. This is as easy as adding a reference and addressing the namespaces in there. Really major for us developers! With just a few lines of code we can reach out and touch the camera or what have you connected to the system.

As many of you know I am a Windows Azure Cloud geek. Naturally one of the greatest parts of this for me was the massive new syncing services that Microsoft are enabling for us. Again with just a few lines of code! You see as a user on a Windows 8 system you can opt to associate a LiveID with your device and hey presto! Settings, session state and even your logins are migrated between your apps! Yes that’s right: I saw a key note demo of a login to a web app on one device, a workstation Windows 8 PC and that same login being re-used on a different device standing right next to it. No magic – just some real powerful sync services in the Cloud at your beck and call. Developers really only have to write data to be synced to a service – again a one-liner in order to make this happen.

The new and improved Developer Tools; Visual studio 11 and Expression Blend just have too much new goodness for me to even begin to cover today!

Dive right into the new Windows Dev Center download the Windows Developer Preview and get crackin’!

And you Swedes can go to the Swedish Build site Build Sweden to learn how to catch up to the latest and the greatest – and naturally “Everything about Windows” Allt om Windows.

Cheers,

M.

@bldwin the night before!

It is the night before the BIG announcements everyone is now eagerly anticipating. Speculations are running amok among the delegates here @ Build Windows. Fans are ready to cheer and competitors are dreading. Anticipation is a powerful tool and I trust you Microsoft not to let us down! At this point it is useless to rehash a lot of speculations since I don’t know. All of the softies are claiming equal levels of ignorance (and as usual if they did know they could not tell). This last bit is just a fancier way of saying “I’m not in the loop!”

Only one thing – semi-unrelated to the actual announcements will I dare to hope for and that is that Mary Jo Foley is right: Microsoft shows off quad-core Windows slate. Could this be its Build give-away?

I will be here in Anaheim and will bring you the latest and greatest news and/or analysis from the event. Since the schedule is packed and we will have a LOT to do over here I’m not making any promises on my delivery rate save a letter of intent: I will do my best to bring you the best from the event as it happens!

Naturally you too can follow this live at http://www.buildwindows.com/ or attend local Build Windows Key notes like the one Diversify is hosting as a .NET Community event in Malmo, Sweden: Swenug Skånde Build Key note event.

You should follow this blog and a lot of other resources (outlined some of them below) if you want to keep up with the flow!

Cheers,

Magnus

@bldwin in company with @bldwinswe

Building Windows 8 blog/B8 blog

http://blogs.msdn.com/b/b8/

The Swedish news blog:

http://blogs.technet.com/b/microsoftnyheter/

www.buildwindows.com/

www.migbi.se/build

www.microsoft.se/buildsweden

www.facebook.com/buildsweden

Dependency Injection into custom ClaimsAuthenticationManager and ClaimsAuthorizationManager

How do you do Dependency Injection on a custom ClaimsAuthenticationManager and ClaimsAuthorizationManager when you use Windows Identity Foundation and Claims Based Authentication? What you want to do is set a Factory or some kind of instance Resolver for the instance creation of the two manager instances. Can this be done? (Concept page for WIF managers and OriginalIssuer)

According to The Man himself Mr. Vittorio Bertocci it was not a scenario that made the cut on the feature list for the current version of WIF:

image

If @vibronet says to try to do it who am I to say no? ;~)

Actually I’ve not done it fully the right way; I’ve cheated but in a way that mitigates the cheat and brings the power of Dependency Injection to the WIF ClaimsAuthenticationManager and ClaimsAuthorizationManager!

The challenge

The two Manager instances are created by your ASP.NET pipeline or WCF pipeline and not by you. When you get power over the instances it is too late. Dependency Injection can’t happen. Or can it? Constructor Injection can’t happen because the instance is already created. Then again all of the IoC container libraries out there have the ability to do Property Injection on already created instances. This is the approach I will use.

The Cheat

In order to do this Property Injection we have to come to a point where we can get to our instances of the managers. Since this happens when you get a request to your WIF enabled service we have to cheat. Avert your eyes! Throw salt over your shoulder and spit etc. ;~)

Note: The code and artifacts for this post are available on the AzureContrib site or with your friendly call to the NuGet package manager: PM> Install-Package AzureContrib.

using System;
using AzureContrib.WindowsAzure.Diagnostics;
using AzureContrib.WindowsAzure.Properties;
using AzureContrib.WindowsAzure.ServiceLocation;
using AzureContrib.WindowsAzure.Utils;
using Microsoft.IdentityModel.Claims;

namespace AzureContrib.WindowsAzure.AppFabric.ACS
{
    /// <summary>
    /// Simple authentication manager which delegates to the real <see cref="IAuthenticationService"/>
    /// </summary>
    public class InjectedClaimsAuthenticationManager : ClaimsAuthenticationManager
    {
        private static IBuilder builder;

        /// <summary>
        /// A hook to access the <see cref="IBuilder"/>.
        /// </summary>
        /// <remarks>Please do no abuse this power!</remarks>
        /// <remarks>The purpose is to enable Dependency Injection on classes that are not createable through a factory!</remarks>
        public static IBuilder Builder
        {
            set { builder = value; }
            internal get
            {
                if (builder == null)
                {
                    throw new Exception(Strings.BuilderIsMissing.F(typeof(InjectedClaimsAuthenticationManager)));
                }
                return builder;
            }
        }

        /// <summary>
        /// <see cref="IAuthenticationService"/>
        /// </summary>
        public IAuthenticationService AuthenticationService { protected get; set; }

        /// <summary>
        /// ctor that uses <see cref="Builder"/> to Dependency Inject this resource.
        /// </summary>
        public InjectedClaimsAuthenticationManager()
        {
            // Perhaps not the prettiest of solutions but this little module is not created through the container.
            Builder.BuildUp(this);
        }

        /// <summary>
        /// <see cref="ClaimsAuthenticationManager.Authenticate"/>
        /// </summary>
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            return AuthenticationService.Authenticate(resourceName, incomingPrincipal);
        }
    }
}

And the same for authorization.

namespaceAzureContrib.WindowsAzure.AppFabric.ACS
{
    /// <summary>
    ///
Simple authorization manager which delegates to the real<see cref="IAuthorizationService"/>
    /// </summary>
  
public classInjectedClaimsAuthorizationManager : ClaimsAuthorizationManager
  
{
        private staticIBuilder builder;

        /// <summary>
        ///
A hook to access the<see cref="IBuilder"/>.
      
/// </summary>
        /// <remarks>
Please do no abuse this power!</remarks>
        /// <remarks>
The purpose is to enable Dependency Injection on classes that are not createable through a factory!</remarks>
      
public staticIBuilder Builder
        {
            set{ builder = value; }
            internal get
          
{
                if(builder == null)
                {
                    throw newException(Strings.BuilderIsMissing.F(typeof(InjectedClaimsAuthenticationManager)));
                }
                returnbuilder;
            }
        }

        /// <summary>
        /// <see cref="IAuthorizationService"/>
        /// </summary>
      
publicIAuthorizationService AuthorizationService { get; set; }

        /// <summary>
        ///
ctor that uses<see cref="Builder"/>to Dependency Inject this resource.
      
/// </summary>
      
publicInjectedClaimsAuthorizationManager()
        {
            // Perhaps not the prettiest of solutions but this little module is not created through the container.
          
Builder.BuildUp(this);
        }

      
/// <summary>
        /// <see cref="ClaimsAuthorizationManager.CheckAccess"/>
        /// </summary>
      
public override bool CheckAccess(AuthorizationContext context)
        {
            returnAuthorizationService.CheckAccess(context);
        }
    }
}

As you can see when the instances of the two Manager classes are created they grab the Builder of the static. While I detest this type of code this is a means to an end. The Builder must be set in place during application start up so that it is available when the WIF pipeline is activated.

InjectedClaimsAuthenticationManager.Builder = applicationBuilder;
InjectedClaimsAuthorizationManager.Builder = applicationBuilder;

Now it seems there has to be some kind of IBuilder? What this will do is perform Dependency, or in this case Property, Injection on the Manager classes effectively resolving and injecting live instances of, IAuthenticationService and IAuthorizationService. So what about those contracts? Here they are:

The Magic contracts

The following contracts are used to enable Property Injection and Inversion of Control on the Manager classes.

namespace AzureContrib.WindowsAzure.ServiceLocation
{
    public interface IBuilder
    {
        void BuildUp(object o);
    }
}

namespace AzureContrib.WindowsAzure.AppFabric.ACS
{
    public interface IAuthenticationService
    {
        IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal);
    }
    public interface IAuthorizationService
    {
        bool CheckAccess(AuthorizationContext context);
    }
}

OK so there is not very much magic here. Perhaps a little. The IBuilder instance is a hook to our underlying IoC container and it’s .BuildUp method. The IAuthenticationService and IAuthorizationService both map exactly to the two methods in their respective "”parent” Manager class.

The whole flow

1) Configure WIF for your application and specify the two Injection enabled Manager classes.

2) Start up the application. The IoC container is instantiated and configured. Wrap up the container in an IBuilder instance and set the instance of the IBuilder on the static hook in the to Manager classes.

Now we’re ready to rumble and receive traffic which uses WIF and Claims Based Auth.

3) On an incoming call the app host environment invokes the WIF pipeline and creates the instances of the two Manager classes.

4) When they are constructed the Managers reach out and do .BuildUp on themselves.

5) The real instances that handle authentication and authorization are resolved, injected, and any subsequent calls to .Authorize or .CheckAccess is forwarded to them.

6) All that is left now is to implement the IAuthenticationService and IAuthorizationService but I’ll leave that as an exercise to the reader! ;~)

At least the two service implementations are now fully testable! An naturally you don’t have to write tests for the two Manager classes since it’s effectively three lines of code or something. But you can if you want.

Summary

Sometimes a little pragmatism is in order. I cannot test the logic in my InjectedClaimsAuthenticationManager or my InjectedClaimsAuthorizationManager. In this case it does not matter since I’ll be having a lot of integration tests which will secure those few lines of code. One annoyance that remains is of course the static. I feel dirty just mentioning it. But as stated above it is a means to an end and if not abused it’s power can be harnessed and it’s weakness be contained. The problem with statics are very many but one obvious one of the top of my head is testing. Some times statics hold on to values between tests.

The end result here is fully separable and testable logic in the WIF Claims Authentication code and that is not bad at all!

HTH!

Cheers,

M.

A more strongly typed Windows Azure Storage Queue Service

Ever wanted to send a strongly typed message over a Windows Azure Storage Queue? Here is a neat little trick that helps you do that a bit better than the string payload the CloudQueueMessage carries.

Note: The code and artifacts for this post are available on the AzureContrib site or with your friendly call to the nuget package manager: PM> Install-Package AzureContrib.

The Windows Azure Storage Queue Service is a light weight easy to use queuing service used for “reliable, persistent messaging between Web Roles and Worker Roles”. It can be used for so much more like serializing and breaking down work tasks to smaller more manageable bits.

It’s light weight alright. A bit too light weight.

The problem is that the CloudQueueMessage sent through the queue has a payload of a, up to 8KB, string. So if you send a message as a string you have manually to agree with the receiving end on the format for this message. There is no format enforcement or verification and no strongly typed objects passed as the message. This is a bit of a nuisance in my book so let’s see what we can do to mitigate this!

Rather than adding the message body as a string we want to serialize a small object with the data and send that over the queue. Since we only have 8KB of space I opted to use the compact JSON format by way of the System.Web.Script.Serialization.JavaScriptSerializer. When we add a CloudQueueMessage to the CloudQueue we serialize our payload as JSON. On the receiving end we deserialize back to an object. One great advantage of using JSON is that the sender and receiver does not have to agree on type only on format. Why this is positive I will show you below.

Here is a sample usage:

namespace AzureContrib.WindowsAzure.Tests.Integration.StorageClient
{
   [TestClass]
   public class QueueIntegrationTests
  
{
       public class A
      
{
            public string Foo { get; set; }
            public int Bar { get; set; }
            public bool Baz { get; set; }
            public C Qux { get; set; }
        }

       public class B
      
{
            public stringFoo { get; set; }
            public int Bar { get; set; }
            public bool Baz { get; set; }
            public D Qux { get; set; }
       }

       public class C
      
{
            public DateTime Bar { get; set; }
       }

       public class D
      
{
            public DateTime Bar { get; set; }

            public string Baz { get; set; }
       }

        [TestMethod]
        public void Use_Queue_with_JSON_serialized_messages()
        {
           var a = new A
          
{
                Foo = "something",
                Bar = 42,
                Baz = true,
                Qux = new C
                              
{
                                    Bar = DateTime.Now
                               }
            };

            var cloudStorageAccount = CloudStorageAccount.DevelopmentStorageAccount;
            var cloudQueueClient = new CloudQueueClient(cloudStorageAccount.QueueEndpoint, cloudStorageAccount.Credentials);
            var queue = cloudQueueClient.GetQueueReference("queuename");

            queue.CreateIfNotExist();

            CloudQueueMessage queueMessage = a.AsMessage();

            queue.AddMessage(queueMessage);

            CloudQueueMessage cloudQueueMessage = queue.GetMessage(TimeSpan.FromSeconds(2));

            queue.Delete();

            B b = cloudQueueMessage.Payload<B>();

            Assert.AreEqual("something", b.Foo);
            Assert.AreEqual(42, b.Bar);
            Assert.AreEqual(true, b.Baz);
            Assert.IsNotNull(b.Qux);
            Assert.IsInstanceOfType(b.Qux.Bar, typeof(DateTime));
            Assert.IsNull(b.Qux.Baz);
        }
    }
}

We are sending a small message over the queue by means of an instance of the fictive class A. All we need to do is call a.AsMessaage() to get the CloudQueueMessage to add to the queue.

On the other end (here just on the next code line but still sent through the Development Storage Emulator) we call cloudQueueMessage.Payload<B>() to get the data deserialized back to a strong type B. But wait a minute ‘B’? Didn’t’ we send an ‘A’? As I hinted at above JSON does not care about the concrete type it serializes to in other respects than the names and types of the properties it deserializes. You can even send A with a property of type C to B with a property of type D where C and D are not the same without problems. In fact C is a class and D is a struct! If you screw it up too badly you will get a System.FormatException.

OK so it’s not exactly very strongly typed is it? ;~) Also I only promised a trick that “helps you do this a bit better! The code that does this is really small as you will see below. And after that I summarize what I feel is the benefit of this.

If you look at the message being sent on the wire in the REST call to the Windows Azure Storage Queue Service using Fiddler2 this is what you’ll find:

POST http://127.0.0.1:10001/devstoreaccount1/queuename/messages?timeout=90 HTTP/1.1
x-ms-version: 2009-09-19
User-Agent: WA-Storage/6.0.6002.18312
x-ms-date: Wed, 31 Aug 2011 05:25:13 GMT
Authorization: SharedKey devstoreaccount1:izFvglhwnqlAchjW1P2TgKXvG6jeN5JJNSN1Ql3BwZc=
Host: 127.0.0.1:10001
Content-Length: 161

<?xml version="1.0" encoding="utf-8"?><QueueMessage><MessageText>eyJGb28iOiJ0ZXN0aW5nIiwiQmFyIjowLCJCYXoiOmZhbHNlLCJRdXgiOm51bGx9</MessageText></QueueMessage>

I’m only kidding, the <MessageText> is Base64 encoded. The decoded version looks like this:

<MessageText>{"Foo":"testing","Bar":0,"Baz":false,"Qux":null}</MessageText>

Even if the receiving end does not decode the message automatically it is actually quite readable and useful.

Here is all the code you need to make the sample above work:

using System.Web.Script.Serialization;
using Microsoft.WindowsAzure.StorageClient;

namespace AzureContrib.WindowsAzure.StorageClient
{
    public static class CloudQueueMessageExtensions
    {
        public const int MaxMessageBuffer = 8 * 1024;

        private static JavaScriptSerializer JavaScriptSerializer
        {
            get
            {
                return new JavaScriptSerializer { MaxJsonLength = MaxMessageBuffer };
            }
        }

        public static T Payload<T>(this CloudQueueMessage cloudQueueMessage)
        {
            var toDeserialize = cloudQueueMessage.AsString;
            return JavaScriptSerializer.Deserialize<T>(toDeserialize);
        }

        public static CloudQueueMessage AsMessage<T>(this T instance)
        {
            var serialized = JavaScriptSerializer.Serialize(instance);
            return new CloudQueueMessage(serialized);
        }
    }
}

Just a few lines really which is nice. Both extension methods use a JavaScriptSerializer. .AsMessage<T>() returns the CloudQueueMessage we want to send over our CloudQueue. .Payload<T>() returns the actual payload as the message serialized back into something you can nicely use in your code.

We win two things using this approach:

  • It is easier to agree on format if it has some well known (JSON) structure between the sending party and the receiving party.
  • In our code we deal only with strongly typed instances and not at all with any serializing and deserializing some message as a string having a particular format.

Only thing you need to be careful with is not to serialize a playload into more than 8KB. But you always have to do that!

HTH!

Cheers,

M.

Upcoming events: BUILD follow up and Scandev on Tour 2011 in Stockholm

Two upcoming conference events in Stockholm, Sweden: Follow up event on BUILD and Scandev on Tour – the latter now with a brand new track!

Follow up on BUILD Windows in Stockholm

When the #Awesome BUILD conference (I’m just guessing here presupposing here nobody except the softies know) there will be a follow up event at China teatern in Stockholm on September 27. Sign up here:

Uppföljning Build, Stockholm 2011-09-27

image

Scandev on tour 2011

Later in the fall, on October 18, also in Stockholm there will be a one day developer conference: Scandev on Tour 2011. The conference today features .NET, Java, Web, Development Process & Methodology and Developer Effectiveness tracks.

And now announcing the brand new Cloud track hosted by yours truly! Thank you Lennart Olsson (@ScandevConf) for allowing me to come on board and help create this extra cloudy track at your event! The agenda for the track will be public very soon but there’s still room for more speakers on the track!

If you are or know a person who is interested in speaking on the topic of cloud – don’t hesitate to get in touch asap! (Especially Amazon, Google and VMWare speakers are most welcome.)

Cheers,

Magnus

August 2011 Releases: Windows Azure Tools for Visual Studio 2011 & Update to the Windows Azure Platform Training Kit

Two exciting new releases from the Windows Azure today which is already installed on my system:

Release of the Windows Azure Tools for Microsoft Visual Studio 2010

Update of the Windows Azure Platform Training Kit

So what’s new?

The new Azure Tools now include

  • Profile applications running in Windows Azure

This is a really cool new feature. You can now deploy your application with one of four profiling settings turned on. This enables collection of profiling information in the application as it is running in the cloud.

image

After a while of running your application you can then select “View Profiling Report” from your application shown in the Server Explorer inside of Visual Studio. This effectively downloads and opens up the profiling report right inside of Visual Studio where you can drill down into the profiling data and find out many interesting things about your application.

  • Create ASP.Net MVC3 Web Roles

I have actually deployed Razor (ASP.NET MVC 3) to Windows Azure as a script startup task (like Steve Marx shows here: ASP.NET MVC 3 in Windows Azure). Why? Because I could! ;~) Well no more of that. Windows Azure is now up to ASP.NET MVC code:

image

  • Manage multiple service configurations in one cloud project

Thank God or maybe Microsoft (same thing?) for this one! It’s been such a HUGE paint to have to handle one single configuration file for several different deployments (local development Compute Emulator, Windows Azure staging and Windows Azure Production, etc.). Now you can define multiple, I say again MULTIPLE (yay) service configuration files. Default is Cloud and Local:

image

  • Improved validation of Windows Azure packages

Appears there are a bunch of validation improvements for your package when you create or publish the Windows Azure Application Package. That is really friendly news for us developers. Anything you can do in advance, with validation, that helps you deploy to Azure fewer times is good in my book. Nay – it’s pretty great actually!

The updated Training Kit has a bunch of updates

All the labs and demos have been updated to leverage the new Window Azure Tools 1.4, the Windows Azure Platform Management Cmdlets are updatet to the latest version. Plus a bunch of smaller bug fixes. The Windows Azure Platform Training Course is also updated.

Also check out posts by Microsoft Windows Azure dudes: Wade Wegner, Nick Harris and Nathan Totten for all the details.

Cheers,

M.

Microsoft owned Skype update includes the Google Toolbar – WTF!?

It appears the Skype Upgrade (5.3.0.120) still offers a free Google Toolbar! I don’t know if WTF is too strong? One has to wonder what kind of deal Google had with Skype for them to honor it still in the installer even after the purchase by Microsoft?

Couldn’t stop myself from screenshooting and now blogging the latest Skype update when the installer ran on my machine:

Skype offers Google toolbar

Cheers,

M.

Windows Azure blog post on the interoperability team blog and video on Channel 9

Want to learn about Java on the Windows Azure Platform? Here is a good place to start with an epic blog post, Channel 9 video, .NET Rocks interview and session recording is a good way to start!

My friend Jas Sandhu has published an epic blog post about Windows Azure and Java interoperability on the Microsoft Interoperability Team Blog:

Neo4j, the open source Java graph database, and Windows Azure

Also he has put up a video on Channel 9 he shot when he was here in Sweden a while ago:

Neo4j, the open source Java graph database, and Windows Azure interview on Channel 9

Also check out the recording we did on Windows Azure and Java at Norwegian Developers Conference NDC this year (which is also linked from Jas blog post):

A journey to the other side Windows Azure + Java

Finally again here is the .NET Rocks interview we also did on the topic:

Stories from NDC!

It’s great to be on Channel 9 – thanks Jas! And thanks NDC for letting us re-publish the video links!

Cheers,

Magnus