Category Archives: WinRt

So i have managed to get myself out of bed (yes feeling quite sick today), just long enough to push out something I finished writing on Friday. Which means I don’t have to take my laptop with me tomorrow now. Less weight, cool.

Anyway its part 2 of my StyleMVVM series. This time we look at a full demo app I have written in Style MVVM. I think this app is worth a look:

In this article I discuss what StyleMVVM gives the average developer that might choose to use it. The article is definately written from an ed user point of view. I think once you have read the article you will see that StyleMVVM is indeed very useful.

About a year ago I contacted by this uber sharp american guy called Ian Johnson, who asked me if I would be so kind as to review his upcoming Windows 8 MVVM library. I stated that I was currently on holiday, but when I got back I would be glad to. Now I have been in pretty much constant contact with Ian over the past year and have been fielding his questions, and we have even written a joint article (Expression API Cookbook) . What immediately struck me about Ians framework (here after known as StyleMVVM) was how feature rich it was, and how well thought out it all was. Remember I have taken time to look at his code base.

At the time I was lucky enough to be asked to be an advisory member for the new PRISM offering for Windows 8 code name “Kona”. I didn’t really have enough time to do much on this but it was still an honor. Though I have since spent quite a bit of time getting to known “Kona” now known as “PRISM for Windows Runtime“.

Now I love PRISM and have nothing but respect for that team, and previous team members, but I have to also say at the moment, I prefer the StyleMVVM offering, as I think it is just more feature rich, and some of the code seems to be better to use than PRISM for Windows Runtime.

One thing I really liked in StyleMVVM was the fact that Ian had written a Expression Tree (fast as hell) IOC container from scratch. He has bench marked this and it is rihgt up there, with speeds far exceeding Castle / Unity and AutoFac. It is based around the MEF style attribute model, but fluent registration is also happening any second now (I know I have seen the beta versions of it, and it looks very cool). Ian is very proud of this piece of StyleMVVM , and rightly so, its awesome.

Now that is no small thing, for a single individual to come up with a framework as feature rich as one of the big boys in the MVVM arena, kudos to Ian.

I believed in Ians work so much I have been working on a demo app using it in my spare time. This demo app will be the source for a series of articles on how to use StyleMVVM which I hope to have out there in the wild very soon. You will hear about it here. In the mean time I just want to list some of the features of StyleMVVM, which I have shamelessly stolen from the StyleMVVM codeplex site.

Some of the core features are:

StyleMVVM is the only MVVM toolkit for Window Store App that supports all three development languages C#, C++/CX and HTML/JS. Allowing you to export components written in C++/CX and import them into a C# applications.

Built in validation engine that supports ValidationAttributes, Fluent validation and Method validation depending on your needs. You can validate ViewModels as well as DataModels.

Conventions module to allow for easier development, as well as templates to setup your project to use conventions.

Event Handlers can be easily hooked up to your view model using the simple syntax View:EventHandler.Attach=”EventName => ViewModelMethod($sender,$eventArgs); etc…”

Supports Regions similarly to Prism with region registration happening in XAML and navigation being driven from the ViewModel

Attribute Based IoC container (Export, Import), container is also environment aware and sorts exports accordingly returning the best match at Locate time (RunTime, DesignTime, UnitTest).

IActivationService that can create or clone any Object (satisfying Imports and message registration)

ITransformService can transform data objects from one type to another using reflection and Linq Expressions, you can use the Transform attribute to give the service hints on how to transform the property.

Visual Studio Template for Projects and Items

So you can expect to see some more material on how to use StyleMVVM very soon. If you just can’t wait, grab the code and have a look at the demo, which is very good and showcases most of the features very nicely.

So I have just finished doing my 1st WinRT demo article (and yes it is for an article for codeproject), which I will have up soon. Coming from a place where I was working a lot with WPF I thought it might be a good idea to capture some of my thoughts/current gripes when working with Win8/WinRT.

I have tried to be as pragmatic as possible, and view WinRT as a v1 thing, which will (hopefully) get better in time. That said there were certain things I just missed a lot. I think what I will do is just list some of the things I found lacking when I was doing my little demo app, and then I will talk about how I found the whole Win8/WinRT ecco system.

Some Of The Issues That Bugged Me

So here is a list of things that I found a bit odd/off, now that is not to say that these will not get fixed, but they still bugged me all the same

XAML Issues

DependencyProperty system, looked far less able when compared to WPF

On more than 1 occassion I found that my ComboBox ItemSource Binding must appear before SelectedItem Binding in XAML if you want SelectedItem to populate correctly from the ViewModel (this seemed to be a problem in 8.0 at least), also I believe I have seen this bug before in days of old in both WPF and SL

No binding in setters within Styles (even SL has this now in SL5). This one needs fixing like NOW. Its plain wrong, and the work around sucks

RelativeSource binding is far less able when compared to WPF

Visibility is lacking “Hidden”, which is actually useful

No DependencyPropertyDescriptor

Can’t do BasedOn style that allows you to BasedOn default style (or maybe I just didn’t know how to do it)

No x:Static markup extension. This is extremely useful for binding to singleton instance (which I use for all my ValueConverters)

No x:Type markup extension

No custom markup extension

No DynamicResource markup extension

No VisualStateManager.GoToElementState(..)

I may be wrong on this, but didn’t seem to be able to have nested VisualStates one for top level control, and then some for some inner control.

WebView is still 2nd class citizen, in certain scenarios its still ALWAYS on top.

ListBox backgroundColor / BorderBrush do not work that well with Focus, you have to restyle either whole control or ListBoxItem (container) taking into account Focus VisualState (I think this is a pain others probably disagree)

Decision Issues

No DatePicker control (ok its coming in 8.1, but please what the heck, do people not need to amend/pick dates in Windows 8. This is plain lazy)

No Triggers in Styles/DataTemplates. Follows the SL model of VisualState(s). In my opinion (and I am not alone here) Triggers are and ALWAYS will be more powerful than visual states. At least give us both and let us use which model we prefer

No Blend interactivity interactions. My god so we are now back in WPF v1 land where we have to right our own attached behaviors for everything. Practically any XAML developer will have become accustomed to using the standard Blend interactions / behaviours. We want these back.

Plain Weird Issues

Enumerable.Range(2013,2023) plain doesn’t work. Try that and see what you get. It is very odd

DateTime object is very limited compared to .NET version

What Was The Win8 Ecco System Like To Use

WinJS or C#

Now as I have stated I am predominately involved with WPF, I do however also do a fair amount of ASP .NET MVC / and MVC/MVVM client side Javascript development (Knockout.js / Angular.js / BackBone.js). So what language did I pick when doing my Win8 article. For me that was a no brainer, C#. Too be honest I find the whole idea of a bastardized version of Javascript that will only run on Windows8.* completely alien. If you believe the press, its plain JavaScript. Sure it is.

The other thing I just don’t see it as a very transferrable skill (oddly XAML is, its in WPF / SL and now WinRT). For example if I used just WinJS every day, do you think that would be a transferrable skill, cos I sure don’t. Lets say I was doing TypeScript or native JavaScript would they be transferrable skills, well yes they would. C# on the other hand, still very much in vogue if you ask me. So that 1st language choice hurdle was an easy one for me to make.

Others may strongly disagree, but that was just my take on it.

App Structure

I have to say I am not mad keen on the overall application structure. I mean have you seen how much boiler plate code you get in App.xaml.cs, here it is for a new project. Thats nasty if you ask me:

///
/// Provides application-specific behavior to supplement the default Application class.
///
sealed partial class App : Application
{
///
/// Initializes the singleton Application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
///
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
///
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
///
///Details about the launch request and process.
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
//Associate the frame with a SuspensionManager key
SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// Restore the saved session state only when appropriate
try
{
await SuspensionManager.RestoreAsync();
}
catch (SuspensionManagerException)
{
//Something went wrong restoring state.
//Assume there is no state and continue
}
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllGroups"))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
///
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
///
///The source of the suspend request.
///Details about the suspend request.
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
await SuspensionManager.SaveAsync();
deferral.Complete();
}
}

Coming from other stuff like there is a lot less clutter in the main entry point.

The other thing I really didn’t like is the way you had to have this special ResourceDictionary called “StandardStyles.xaml“. If they truly are standard, what the hell are they doing in my app, and why aren’t they included in the framework. Also why are most of the styles in there commented out, and we have to uncomment them as we need them.

Magic Classes That Are Provided

I also didn’t like the fact that there are a bunch of classes provided which I have no idea whether I need them or not.

For example if you create a new Grid application you get this.

Common

BindableBase

BooleanNegationConverter

BooleanToVisibilityConverter

LayoutAwarePage

RichTextColumns

SuspensionManager

Now I know what a value converter is, so they are ok, but don’t things like “LayoutAwarePage” and “SuspensionManager” sound like framework issues to you? They sure do to me, again why are these classes in my codebase. Surely a LayoutAwarePage should be the defacto page for ANY WinRT application. You know we are supposed to think that the Surface is an iPad rival, yet last time I looked I could twist an iPad this way and that, and you can also do that with a Surface. So why isn’t the LayoutAwarePage the standard. By the same token since there is a suspension type of lifecycle in WinRT why is the SuspensionManager not in the class library.

Also what the heck is “RichTextColumns” do I need that, what does it do. Is it required for a GridView, and if so (yes I’ll say it again) why isn’t it in the framework.

Ok, I could find out, but when I start a new app, I would much prefer to see a clean slate really.

Early Days But

To my mind it just feels like it was rushed out the door, and feels very unpolished. Now I am a massive Microsoft fan boy, but I just felt let down by WinRT. As I say I will still be putting out this WinRT article soon, but it will likely be my one and only for a while.

Anyway those are just my thoughts, no one elses, many will likely disagree, which is fine.

As part of something a lot larger that I am currently working on I wanted to implement the Search charm logic in Windows 8.

Now being the model citizen that I am, I have read all the good technical bumpg around Windows 8, and I paid particular attention to the fact that we really need to keep the UI free, as anything more than 30/300ms (can’t recall which) on a touch system just feels broken.

So what does that mean? Well it means I have been a good chat and played nice and used Async/Await where needed. All good so far.

So now onto the Search charm. I obviously enabled this in the manifest file. Then I wrote the following code which I expected to work

That looked fair enough to me. But when I ran this code I got this Exception

Most strange.

Turns out this is an issue for which there is a solution, that is just rather poorly documented. In fact it borrows a lot from the jQuery Deferred pattern (which you can read more about here)

So what is the solution. Well as I say WinRT has certainly borrowed from the jQuery Deferral / Promise idea. Where we ask for a Deferrable object, do some work, and then complete the Deferrable object.

So here is the code above refactored to use a WinRT Deferrable object. This technique can be used with most of the charms.

The other day I was contacted by one of the fellow Xaml Disciples (who have been dormant for a long time, but hey ho), who was asking how he might
determine if some audio within a web site was playing or not. I thought he problem could be solved using the WebView available
in WinRT. Turns out I didn’t get what his actual problem was, and this did not help him. I did however try something out before I answered him, which
was how to communicate with the WebView hosted HTML/JavaScript from c# and vice versa.

I thought that may make a semi-useful blog post. So I have provided a dead simple example, the c# code will try and change the FontSize of a DIV
within the hosted HTML content by calling a JavaScript function in the hosted HTML content. The JavaScript will then double the incoming FontSize and use
it for the DIV, and at the same time tell the c# what the doubled size is via a callback into the c3 code. Simple requirement really

This is done using the WebView.InvokeScript() method, where it expects a name of a function, and a string[] for the arguments

Calling c# from JavaScript

This is slightly trickier as you need to carry out the following 3 steps

Step 1 : Hook up the WebView.ScriptNotify event

Step 2 : Use the result of the NotifyEventArgs.Value from Step 1

Step 3 : Get the WebView to actually call the ScriptNotify c# event, which is done via this bit of code:

window.external.notify(..)

NOTE

WinRT makes a big point out of the fact that the WebView control is a regular WinRT control that can be treated as any other element
such as applying Transforms etc etc, while this is true (I have seen the demos/videos/screenshots). However it seems one area has been missed (at least in Windows 8.0 that
I am currently using), which is that the WebView seems to be the top most element. Try the XAML below and see what you think

As some of you may know I have been somewhat of a fan boy of WPF. All of a sudden there is this new kid on the block, WinRT and Windows store applications. So far. I have not ventured into this world, as I think it is early days with WinRT, and I expect it to change a lot. I did however quite like some of the look and feel elements of it, and thought what the heck it can’t hurt to take it for a quick spin. I also just co-authored an article with a fine yanky chap (hey Ian) who contacted me to review his WinRT MVVM framework, called : StyleMVVM which I promised Ian I would look at, and also take for a spin.

Thing is I did not want to start a big WinRT application (I like to write full apps as you tend to learn a lot more that way), without at least trying out WinRT on something smaller. I still fully intend on doing a larger StyleMVVM app, in fact the material presented in the associated article will form part of the larger StyleMVVM demo application that I promised Ian.

The code attached to this demo is pretty simple, but actually is was enough for a WPF guy to try and find out the WinRT way of doing things, and I have to say there certainly were a few weird things that were quite unexpected coming from WPF land. I will talk about these in the body of the article, but we digress, what does the demo app do?

Like I say I wanted to keep things very simple, so I have written a very simple grid based schedule control, that is readonly you can not add items to it by clicking, its all setup via existing code. Ok that data could suck stuff from a database, but there is no way to dynamically add appointments to the schedule using touch, or the mouse at runtime, though that may feature in the fuller StyleMVVM app.

So in summary, the associated article demo code is a simple schedule control that works with touch or the mouse.

You can download the code and get a full blow by blow account of it right here :