How different is WinRT really?
Update 29 Feb 2012: There is now a post covering the Consumer Preview/Beta changes: How different is Metro Style (WinRT) development really? The beta post
Note: Before you read this post, it is using the public technical preview of Windows 8, VS 11 & .NET 4.5, so I expect some issues will likely be resolved in later releases. Check the site out for more info!
Recently I have been working on a MVVM framework (it’s the new Hello World project for developers) and I wanted to make sure it worked with WPF, Silverlight & the new hotness: WinRT (or Metro or Windows 8 depending on who you ask). So I started to retrofit the framework and build a demo application at the same time to show it off. I quickly found a bunch of issues that you need to take care of when moving to WinRT.
Namespaces
It has been mentioned since //Build that we will have new namespaces so this should not be a surprise. In my MVVM framework it looks like this:
#if WINRT using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Core; using Windows.UI.Xaml.Data; #else using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Controls.Primitives; using System.ComponentModel; #endif
You should be able to spot almost a one to one mapping there, except for the last few, but we will get to those.
Duplication of INotifyPropertyChanged, ICommand & INotifyCollectionChanged
This issue will affect EVERY developer in WinRT and it is a MASSIVE fail on Microsoft’s part. The INotifyPropertyChanged, ICommand & INotifyCollectionChanged that are used in every XAML based system are not the ones used in WinRT XAML based systems. In fact the framework has TWO of each – one in the old namespace and one in the new namespace. So you will find your databinding just broken with no compiler errors! To solve this you have to switch the namespaces.
ObservableCollection<T> is broken
Hand in hand with the previous one is that the trusted ObservableCollection<T> no longer works either! It implements the old (wrong INotifyCollectionChanged) and thus all bindings to it are broken. You need to bind to a class that implements IVectorCollection<T>. One problem, the framework doesn’t ship with an implementation! So to bind to collections, you need to build your own collection class or grab a shim (as I chose to).
Proxies & WebRequest
I used WebRequest in the demo to pull images from Flickr and you know what just worked – proxy settings. The first time ever in .NET! I hope who ever decided that proxies should just work gets an award!
Reflection has added a whole new layer
In non-WinRT we can get all kinds of info on a type directly by working with that type (i.e. Type.GetType). However in WinRT that is not the case! Type.GetType is no longer enough, when you have gotten the type you need to call GetTypeInfo on that to get to all the information on the type. Why this extra layer is here is beyond me.
#if WINRT if (control != null && typeof(ButtonBase).GetTypeInfo().IsAssignableFrom(control.GetType().GetTypeInfo())) #else #if SILVERLIGHT if (control != null && typeof(ButtonBase).IsAssignableFrom(control.GetType())) #else if (control != null && control is ICommandSource) #endif #endif
MIA Types & Methods
For a MVVM framework you will have a bit of reflection and so the first thing I noticed is the super handy Types.EmptyTypes is gone! So to have as close to a single code base I am doing this nonsense now
#if (WINRT) private readonly Type[] EmptyTypes = new Type[] { }; #else private readonly Type[] EmptyTypes = Type.EmptyTypes; #endif
There is a fair bit of these missing properties & methods like Type.GetType is missing some of the overloads I have come to love:
#if WINRT var viewType = Type.GetType(viewName); #else var viewType = Type.GetType(viewName, true, true); #endif
Lastly do not expect the trusted methods like GetConstructor, GetMethod or GetProperty to exist. Now we have collections we can iterate over. I admit this is a better option, but some helper methods here would've been useful.
public static MethodInfo GetMethod(this Type type, string methodName, Type[] parameters) { var results = from m in type.GetTypeInfo().DeclaredMethods where m.Name == methodName let methodParameters = m.GetParameters().Select(_ => _.ParameterType).ToArray() where methodParameters.Length == parameters.Length && !methodParameters.Except(parameters).Any() && !parameters.Except(methodParameters).Any() select m; return results.FirstOrDefault(); }
So be aware when working in reflection be aware that it will work differently.
User Controls must be created on the main thread!
This I do not get at all, but in WPF & Silverlight a background thread can create a user control and pass the content to a Window on the main thread. This is SUPER useful for the creation of content and then when needing popping it into the foreground almost instantly! However WinRT has different ideas, all user controls MUST BE created on the main thread – YUCK!
#if (WINRT) Window.Current.Dispatcher.Invoke(CoreDispatcherPriority.High, (s, e) => { #endif shell = (IShell)typeof(TShell).GetConstructor(EmptyTypes).Invoke(null); #if (WINRT) }, this, null); #endif
Simpson Fail Image from: http://www.thebuzzmedia.com/creator-of-wikipedia-fail-fast-fail-often/
Double face palm image from: http://tvtropes.org/pmwiki/pmwiki.php/Main/FacePalm
The MVP award
Being a MVP gets you very little, some status boost in those who misunderstand it (MVPs are not awarded for technical skill & a lot of people think MVP = expert), a MSDN subscription, a lot of paperwork (including multiple NDA’s), some access to product teams (this varies from product team to product team – some have great interactions others are poor) and a trophy.
To the right is my MVP trophy (as well as ALM Rangers award and MVP of the year cube) and I think it looks pretty awesome but how does it get to me?
In this post I want to take a slightly tongue in cheek look at the box the MVP award comes in and what it is saying about MVP’s.
Above you can see the three years of the trophy box. So lets analyse those box covers. I am assuming that the person on the box is supposed to represent MVP’s.
- MVP’s are dress smart casual always – chinos & a blue shirt are required. Hah, not likely.
- MVP’s have neck problems causing them to tilt their heads. This is likely true from all the time people spend at their machines.
- MVP’s always have their laptops with them. Also likely true. Next year he better have a Windows 8 tablet though.
- Interesting that 2010 guy got one cover while 2011 guy got to come back in 2012. Guess 2010 guy wasn’t re-awarded
- 2011 guy has gotten smaller in 2012 – are we shrinking away or did Mr 2011 not do enough work?
- In 2010 and 2011 the ghosts of MVP’s past are clearly standing in support for the MVP. In 2012 they aren’t concerned anymore and just chatting with each other.
What would I do differently? Easily, take a photo from MVP summit with real MVP’s engaging with each other and put that on the cover. What may be nice is to have new 2012 MVP’s (i.e. first timers) get together to pose for it and so there is extra incentive for 2013 – a box with real MVP’s that could include you.
You never debug standing up
Being a professional developer means following standards, standards that are set by smart people (smarter than me at least) and when you start to break those standards will wrong. I know this! However this past Friday I broke many a rule and failed, because thought I knew better this one time. So this post is a retrospective of what went wrong, so that I never forget again.
The project is a fairly complex backend system for a special mobile device, and when I mean complex I mean in size and scope. We have VB.NET, C#, Java, JavaScript and a ton of inline SQL! The work itself is done by three different companies with three different agreements, policies and methodologies! That sounds like a recipe for disaster but it isn’t – we have exceeded every goal! That is until Friday.
On Friday we get told the customer is coming at 9am on Monday for a demo! We have 8 hours to get ready for it! The software is in a state between alpha and beta and we have known issues that need resolving by the demo. So we worked hard and make great headway until about 3pm. Then we hit an issue everyone in the room thought was on the mobile device. The first problem is the mobile dev company isn’t onsite today, so we are really guessing at the issue.
We start experimenting at fixes, pushing 7 builds to QA in an hour (in reality we are lucky if get 5 build to QA in a day). At the same time we are adding bug fixes and tweaks for other items too! Then the answer comes in the mobile device developer – they breaking because their expectation of the spec is not the same as ours. More fixes and adjustments and then the server just stops.
At this point, I am looking at my watch, I have a two year old son sitting at school and it is almost time to pick him up. tick tock. Being a single parent means I MUST leave and soon. The mobile guys have gone offline completely. Another dev from the third company is needing to go and propose (she said yes )! We are all rushing, skipping testing, skipping building locally before checkins… I even checked code in without comments! NOTHING, no matter what I try it keeps breaking, tick tock, same error every time, tick tock, I can’t find it, tick tock, the PM is looking worried and looking at me to solve it, tick tock. OUT OF TIME.
I apologise and leave, feeling crap. I failed. I let a client down.
Saturday, I sit down to dig into the code. Now without the time pressure, and I read the stack trace properly for the first time (stopped assuming what it was saying as I was when I was rushed) and quickly found the issue and resolved it. One code checkin (built first locally, with check in comment, and assigned to work items etc…) and it is working. The test client works too!
In retrospect what should I have done is simple: We knew there is a demo, it was late notice but we had chance to choose what to show to the customer. We should’ve set a cut off time after lunch for fixes and changes and then just not included broken things in the demo. Rather have taken that after lunch time and made sure the demo showed 80% and that 80% worked 100% than rush to get 100% to show and in the end break it all.
I should’ve also stepped back earlier and done something else for a second – get coffee or something. Just to clear my mind and calm myself. Stepping back always helps, just think of how many times you ask someone for help and in explaining it you solve it yourself.
Finally skipping the standards that make us professional leads to disaster and I should’ve made sure the following standards were kept!
- make sure it builds locally before checkin
- check in comments
- assign each checkin to a work item
- test locally before checkin
- If we have a deadline, then we get everyone in the room to make it happen. We win and lose as a team.
- The more detailed the spec is, the better for everyone.
- Do one thing per checkin (keep those checkins small and focused)
Monday has come and gone, the customer loves it and the demo was great. We succeeded. It required sacrifice from the team of some of their weekend, a sacrifice that if we have acted more professionally and clear headed could’ve been avoided. This doesn’t happen often to me, as I am often surrounded by professionals and when one of us loses it the rest helps push that one back into place, so this post really is a reminder why we do that for each other and what others can learn.
Management is doing things right; leadership is doing the right things – Peter Drucker
Presentation Dump - End 2011: Azure, Windows 8, Lightswitch, Visual Studio Tools, TFS & Roslyn
With 2011 finally done and dusted it is time for the bi-annual presentation dump, where I upload most of the slides I have done in the last six months to share with you! I say most, as some presentations are NDA and those, unfortunately, I can’t share out – but where I can upload slides I do!
In this presentation dump we have:
- Windows Azure Platform Overview: This is a talk I gave at the ImagineCup to faculty members about what Microsoft Azure can offer!
- Windows 8: A brief introduction shortly after the //Build conference to help share what information we had on Windows 8
- Lightswitch: The latest iteration of my Lightswitch talk contains a structure overview before the demo and then goes into detail on the themes and extension model in the product.
- Developer Productivity Tools: A session that looks at FIVE FREE tools for Visual Studio that will assist in the productivity of any Microsoft .NET developer in Visual Studio. Tools covered are fxCop, StyleCop, Pro Power Tools, CodeRush Xpress & Nuget.
- An Introduction to TFS: The target audience for this is someone or company who is using another source control (like VSS) and is thinking about moving to TFS but isn’t sure where to start. This BRIEF introduction tries to provide a high level view that TFS is not just source control it is a LOT of more and thus has a lot more power. It also mentions migration from VSS and provides guidance for success.
- Roslyn: This is an early look at Roslyn
It is definitely a quieter period than most, in terms of number of unique slide shows and I think a lot of that comes out of the information black out from Microsoft prior to //Build, but it was still a very period with me presenting Lightswitch NUMEROUS times and also Tech·Ed Africa where I did four presentations!
You can get all the slides and details by clicking “read more” below!
Windows Azure Platform Overview
Windows 8
Lightswitch
Developer Productivity Tools
An Introduction To TFS
Roslyn
MVP for a third time :)
364 days ago & 829 days ago, I blogged about being awarded a MVP from Microsoft and I am proud to announce that I have been awarded a MVP for a THIRD time!
Thank you to all that were part of making this happen, I am very honoured by all of you.
What is an MVP? In short it is a thank you for helping Microsoft communities. The long version can be found here.
Portal 2: Lab Rat
If you do not know what Portal is, then you are dead to me! DEAD! But since I know everyone knows of Portal that won’t be an issue. What you may not have known is that Valve created a comic book that chronicles the gap between the end of Portal 1 and the beginning of Portal 2, and your character (Chell) ends up back inside the facility.
This comic is called Lab Rat and you can view it in super great details at http://www.thinkwithportals.com/comic/
But what about when you are travelling this festive season and want to read it quickly, or show your family so they can be caught up before you take them through Portal 2 on Christmas day? Well, for my seventh WP7 app (yes, I have build 7 Windows Phone apps this year!) let me introduce Lab Rat.
In addition to offering the comic in your pocket you can save any page, with or without text, to your phone for use as a login screen or any such thing! AWESOME!
In no way should you think this is an alternative to going online though, the detail of this comic should be seen at the BEST resolution possible – but this makes a good companion experience.
Platforms > Implementations
I recently read an insightful post about how being a developer is less about coding and more about tooling, and while I do not agree with all of the post, the fact we as developers are tool obsessed rings very true. This obsession with tools becomes a white hot rage when our favourite tool is threated with extinction or causes a world of panic when a competing tool is proposed without enough information on it.
Let’s look at two key examples of that:
- WinForms was very popular and when Microsoft brought us WPF, there was major push back from those who did not want to change and learn a new tool. If you reading this, then you are thinking well time solved that, I disagree. This very week I was asked about WinForms vs. WPF again. Time doesn’t heal all wounds, it just gives some of us time to move on.
- To illustrate the world of panic I can use a more recent issue – Windows 8! Remember all the discussion before //Build about the death of <insert your favourite tool here>? The confusion caused by incomplete discussions around tools we love caused panic.
So what is the solution to this? I think simply a mind set change would be enough. The mind set change needed is to remember that a platform is more important/powerful/useful than a tool. I would like to take credit for this idea, but the first time I heard anyone mention this was a few years back and it was Scott Hanselman talking on MVC almost three years ago to the day. He mentioned that ASP.NET > ASP.NET Web Forms and ASP.NET > ASP.NET MVC. In short he was saying that the core understanding of ASP.NET, the core features and the core uses of the platform are bigger than a single implementation (tool) could be. Sure, you need to learn a new tool, but you aren’t starting at zero if you know the platform.
Why I am bringing this up? It is because of the discussions I have been having about another tool recently: Silverlight. We are approaching the panic stage on this tool due to rumours of it’s demise. However it is VERY important to take a step back and see what the platform is and how knowing the platform means that a tool can move along and we are still able to work/code/make money etc…
The platform Silverlight uses is XAML based UI technologies, a core set of how we can layout UI components using an XML dialect called XAML. This platform also has lots of options for things like binding, the MVVM patterns and so on that are either difficult or impossible to do with other UI technologies (like WinForms for example).
XAML based UI technologies started with a single tool: WPF – an implementation of the platform designed to run on top of the .NET Framework. A second tool, Silverlight, later appeared – this is an implementation of the platform designed to run as a plugin in a browser. A third tool, Silverlight for Windows Phone 7, came next and while very close to Silverlight it had it’s differences as it was an implementation of the platform for the phone. In the last few months we have had the forth implementation of the XAML based UI technologies appear: WinRT. This is the Windows Runtime in Windows 8 and when you develop with C#, VB.NET or C++ your UI technology is just another implementation of the platform.
Every implementation of the platform has been different, some in big ways and some in smaller ways but the core of the XAML based UI technology platform hasn’t changed and there is not a single rumour, plan, or hint that we are even close to seeing the end of XAML based UI technologies. We may see a tool end of life and die (like some rumours say about Silverlight) or other tools just find completeness and not need new work done (like WPF if) but the platform remains and grows and learning a platform is always more important/powerful/useful.
Firefly for Windows Phone 7
I am a brown coat – if you know what that means then you will be excited to see my new application for Windows Phone 7: a Firefly hub app which contains news, images, sounds & ringtones from the show and from the movie, Serenity.
This started as me wanting a sound board for the show, but grew larger
This is the first app I have done since my UX training and I hope a lot of the tools and skills I learnt in that training comes through in the application.

TCP servers with .NET: Scenario 4 & Non-blocking servers with .NET 4.5
This post is part of a series, to see the other posts in the series go to the series index.
Scenario 3 is a great solution to the problem, but the problem with it was the complexity of the code is way higher than in scenario 1 or scenario 2. We are calling to other methods, using recursive like behaviours and all kinds of things that are not obvious or easy to grasp.
Thankfully Microsoft has identified this issue and in .NET 4.5 we will be getting some help with this thanks to the new ASYNC features, in particular the async & await keywords.
In short async provides information to the compiler that this method will spawn off an asynchronous process and will return to the caller at some point while the await points out the line of code that line asynchronously.
So using this allowed me to modify the code back to pretty close to the scenario 1 code (I even have the Boolean continue running server flag). However the two methods are enhanced with the async keyword and in there the await keyword is used with AcceptTcpClientAsync and ReadAsync – these are new methods in the TCP stack which return Task<T>, a fundamental requirement of calls that work with async.
I think this is a fantastic improvement, and I cannot wait for .NET 4.5 to ship
class Program { private const int BufferSize = 4096; private static bool ServerRunning = true; static void Main(string[] args) { var tcpServer = new TcpListener(IPAddress.Any, 9000); try { tcpServer.Start(); ListenForClients(tcpServer); Console.WriteLine("Press enter to shutdown"); Console.ReadLine(); } finally { tcpServer.Stop(); } } private static async void ListenForClients(TcpListener tcpServer) { while (ServerRunning) { var tcpClient = await tcpServer.AcceptTcpClientAsync(); Console.WriteLine("Connected"); ProcessClient(tcpClient); } } private static async void ProcessClient(TcpClient tcpClient) { while (ServerRunning) { var stream = tcpClient.GetStream(); var buffer = new byte[BufferSize]; var amountRead = await stream.ReadAsync(buffer, 0, BufferSize); var message = Encoding.ASCII.GetString(buffer, 0, amountRead); Console.WriteLine("Client sent: {0}", message); } } }
TCP servers with .NET: Scenario 3 & Non-blocking (Async) optimistic servers
This post is part of a series, to see the other posts in the series go to the series index.
The first two posts (post 1, post 2) in this series were really to just set the stage and help explain problems with TCP servers that do blocking. The code and method is not wrong, they are okay for some scenarios, but if you want a really robust model, a model that fixes the issues with them without any extra technical issues being added you need to use a non-blocking server.
We start the server the same way, however instead of using the blocking AcceptTcpClient method we use the non-blocking method BeginAcceptTcpClient which implements the async or begin/end (I’ll call it async from here on) pattern. Mark Pearl has a great post explaining the async pattern.
When a client connects, it runs the code associated when we setup the async and in there we call the EndAcceptTcpClient to end the async process and get the TcpClient implementation.
We repeat this process with reading from the client by switching from Read to BeginRead.
The advantage of this model is the only blocking point is the Readline so shutting the server is very easy, we have no thread management to worry about (it is using threads under the covers, but we do not need to care), and clients can connect now and send data at any time – it doesn’t matter!
This pattern does require a lot more code and it is more complex to setup, but once you understand the async pattern (call begin > pass the info we need in state > call end to get more info we need) it is pretty easy
class Program { private const int BufferSize = 4096; static void Main(string[] args) { var tcpServer = new TcpListener(IPAddress.Any, 9000); try { tcpServer.Start(); tcpServer.BeginAcceptTcpClient(ClientConnection, tcpServer); Console.WriteLine("Press enter to shutdown"); Console.ReadLine(); } finally { tcpServer.Stop(); } } private static void ClientConnection(IAsyncResult asyncResult) { Console.WriteLine("Client connection"); var tcpServer = asyncResult.AsyncState as TcpListener; var tcpClientConnection = tcpServer.EndAcceptTcpClient(asyncResult); tcpServer.BeginAcceptTcpClient(ClientConnection, tcpServer); var stream = tcpClientConnection.GetStream(); var buffer = new byte[BufferSize]; var clientData = new ClientReadData() { Buffer = buffer, Stream = stream }; stream.BeginRead(buffer, 0, BufferSize, ClientRead, clientData); } private class ClientReadData { public byte[] Buffer { get; set; } public NetworkStream Stream { get; set; } } private static void ClientRead(IAsyncResult asyncResult) { var clientReadData = asyncResult.AsyncState as ClientReadData; var amountRead = clientReadData.Stream.EndRead(asyncResult); var buffer = new byte[BufferSize]; var clientData = new ClientReadData() { Buffer = buffer, Stream = clientReadData.Stream }; clientReadData.Stream.BeginRead(buffer, 0, BufferSize, ClientRead, clientData); var message = Encoding.ASCII.GetString(clientReadData.Buffer, 0, amountRead); Console.WriteLine("Client sent: {0}", message); } }