Uncategorized

Code from my TechEd Australia 2012 Sessions

This year at TechEd on the Gold Coast I delivered two sessions:

DEV324: Windows 8 with a view

A session where I took MVVM as a base to launch your applications to the next level. 

WPH222: Windows Phone SDK – Be productive straight out of the blocks

Think of this one as you’ve started your first serious application, what are some of the common issues you’ll run in to, and what are the common techniques you’ll need.

https://webjak.blob.core.windows.net/posts/Teched12/Teched.zip

 

 

MVVM, Windows 8

DataStateBehavior for Windows 8 XAML Applications

Note: Knowledge of MVVM and Binding etc is assumed.

You can download the source from here

At Xamling we work very hard to maintain strict standards and practices during development – one reason we do this is to maintain the best parallel workflows between design and development as we can.

Something that we’ve used extensively in the past with Silverlight is the ability to create DataStateBehaviors, which allow us to bind values from our view model to our visual states. When those values change a VisualState is automatically selected, meaning that we can separate our XAML and code very nicely.

An example might be a view that has two states: UserLoggedIn and UserNotLoggedIn. Depending on the value the VM supplies we want to switch these states.

You could imagine in the past with Silverlight and Expression Blend interactivity stuff, you could do the below:

<Behaviors:DataStateBehavior TrueState="UserLoggedIn" FalseState="UserNotLoggedIn" Value="True" Binding="{Binding IsLoggedIn}"/>

Well after much mucking around tying to keep some semblance of parallel workflows and code that is *not* aware of the view, I decided to bite the bullet and see if the DataStateBehavior could be implemented.

I went on the hunt, and found a number of sites that allow us to replicate behaviors, and using some code pinched from the Expression Blend samples site ages ago, I managed to get it working.

First, the excellent post by Joos van Schaik was a great start, and he even has a nice little library that we’ll use here: http://winrtbehaviors.codeplex.com/.

Grab that, and add it to your project. (there is a copy in the sample, but please see attribution above).

Next, Miguel Fernandes had a great idea to use the BindingListener from the WP7 Prism Phone project on codeplex.

With these two bits, now all I had to do is dig out a class from years ago that was pinched from the Express Blend Samples site, and modify it to work on XAML WINRT.

Once you’ve done that, add a propery to your view model – in the sample the propery is IsLoggedIn. It starts as false, then after 5 seconds moves to true. The sample view model is in ViewModel/SomeViewModel.cs.

I’ve also added a couple of grids to the MainPage.xaml, one for logged in and one for not logged in.

There are two states, once again for the login status.

Finally, I’ve added in the DataStateBehavior itself:

<Behaviors:DataStateBehavior TrueState="UserLoggedIn" FalseState="UserNotLoggedIn" Value="True" BindingName="IsLoggedIn"/>

NOTE: We use BindingName, which is a string unlike the original binding in the Blend stuff, this is because WinRT seems to pass through the bound value, not the actual binding class itself.

NOTE: This only works when the behavior is attached to a control (will not work on FrameworkElements etc like Grid). So bang it on your UserControls.

NOTE: This wont be “Blendable” – i.e. no UI to manage the behavior like in the past 😦

NOTE: Sample is built on VS2012 RTM.

You can download the source from here

MVVM, Silverlight, Xamling

Core Series Part 2b – Automatic template selection (this time real automatic selection!)

In the previous post I demonstrated the concept of automatic template selection in a very very simple way. The post was designed to demonstrate the concepts that will be applied in this post – you really shouldn’t use the methods described in the previous post in real projects!

This series is starting out covering off some very basic concepts that are important to understand before progressively up the complexity until we jump in the a full solution – so be patient if you find this stuff a little simple for your tastes!

In this post I will demonstrate a very simple way to apply convention to automatically select a View for the current ViewModel.

Convention is great – as long as you follow the convention (creating files with the correct names, and putting them in the correct spot) this it will “just work”. Yeah I know, never say it will “just work” – phrases like that curse software projects 🙂

Once again to reiterate, the ViewModels do not have any idea what View will be displayed… and you should always try to achieve this in your projects. As soon as the ViewModel knows about the View you are risking breaking all manner of software dev rules, but more importantly your code will lack elegance and be far harder to create and maintain. With this in mind, we “publish” the current ViewModel through a property in the “frame” – the frame being the VM (ViewModel) that looks after creating and displaying child VM’s, and eventually in later posts navigation and tombstoning etc. The VM is then picked up by a ContentControl which will then figure out which View to show. The frame is on the VM side of the fence, the ContentControl is on the View side of the fence. The link between the fence is DataBinding.

Example – automatic view selection using convention

First, you can download the example here.

You can view a video run through of the example here.

The code examines how to pass in a VM to the ContentControl and automatically resolve the view to show.

There are two concepts that are important to take away from this example: first is convention. Creating Views called xxxView and VMs called xxxViewModel. The ContentTemplateSelector is then called upon to look at the type names, figure out the View to show (by replacing ViewModel with View from the original VM type name), then dynamically building some XAML which contains a DataTemplate.

The second concept is of course the dynamic generation of a DataTemplate. It’s important to note that child controls in DataTemplates are not ingratiated when the DataTemplate is created – it’s not until the DataTemplate is applied against some content (in this case the VM) in the ContentControl. This is nice, it means we can cache the DataTemplate to negate the need to re-generate them when the same VM type is used next time.

The XamlReader is used to process the dynamic XAML and returns a DataTemplate, which the ContentControl sets to it’s ContentTemplate property at runtime.

So what’s the benefit?

Convention is great for writing code and building projects *fast*. To add a new View using this system takes minutes (if not seconds). Navigating to the new view is very simple also.

In the next post we will example some further benefits of letting the “View” side of the fence handle control resolution – mainly automatic, designer friendly, centrally managed content transitions!

MVVM, Silverlight, Xamling

Core Series Part 2 – Automatic template selection – marrying a view to a view model

This is the second part of my series on a different approach to MVVM. I highly recommend you read part one to get some background.

This series introduces concepts around MVVM – mainly around view and viewmodel selection, navigation and transitions. The concepts here can be applied to WP7, Silverlight or WPF (including Surface). Further on in the series I will demonstrate how simple more advanced topics like circular navigation and tombstoning can be made (very) simple. All of the techniques I talk about in this series are implemented in XamlingCore – an simple reference MVVM framework. You may choose to use XamlingCore or take the concepts from this series and use them as you please. I recommend you at least have the XamlingCore code available on your system as I will reference files here and there from the framework.

Keeping things simple

A big part of MVVM is figuring out how to match up the view to the view models that you create. Typically for each view, there is a view model (simple right??). Making this process as intuitive and straightforward as possible is very important.

XamlingCore works a little bit different than you may be used to. In XamlingCore you first create a viewmodel and then navigate to your new viewmodel… this is a little different than other systems – where you first create a view and the viewmodel is then “discovered”. This is called ViewModel first navigation.

I really like ViewModel first navigation – for a few simple reasons. Firstly – your code is completely agnostic to what the view is doing… in fact you could create all your ViewModels and navigate around your application without any views being generated at all! This makes it really easy to test. Secondly the very fact that the ViewModel side is completely view agnostic means that you are achieving a very high level of separation of concerns. It also allows for a really simple navigation system (you just keep your ViewModels in a stack, then pop them as the user navigates back).

The main reason I like this method however is that you create ViewModels just like you would any other object, calling constructors, properties etc to pass around data – and I’ll show some great things you can do with this later.

It may sound a little complex, but in practice it’s actually *really* simple.

ViewModel/View Marriage

The main concept we want to achieve is that ViewModels only worry about themselves, and the view side of the fence handles everything to do with choosing how to display the ViewModels (which templates, user controls etc to choose). This keeps the ViewModels very simple. The view stuff makes sense on the “view side”.

At the top level of our application there will be a NavigationFrame – much like the in built navigation system in Silverlight/WP7. The navigation frame has both View and ViewModel side components. It is responsible for taking the current ViewModel and displaying the appropriate view.

The basic workflow is: Construct new ViewModel -> Navigate to it -> Navigation presents the ViewModel to the frame -> frame resolves and creates view (via a DataTemplate) -> hands off ViewModel and new DataTemplate to a content control for display.

A really simple example

I have prepared a really simple example that demonstrates this basic workflow to give you a more hands on idea about how this would work.

Download the sample here.

View the quick screen cast here.

Obviously this sample wouldn’t work very well in the real world, but it demonstrates the concept of choosing a template based on the ViewModel type that is being shown in the ContentControl.

In the next part we will move on to a more automated, convention based approach!

Happy MVVMing!

MVVM, Silverlight

Core Series Part 1 – XamlingCore – a cross platform MVVM framework for Silverlight

Get the code from Codeplex

Well I’m the first to admit I’ve been rather slack with my blog lately! It’s for good reason I promise!

We’ve started a new business (Xamling) which is running nicely now, with three or four decent sized projects behind us now. Oh, if you think our site is a little plain, there is a new site coming soon!

It’s been mega busy the last couple of months, two of our big projects have been Windows Phone 7 launch apps for *big* companies – explaining my lack of blogging!

But it’s not all bad…

XamlingCore!

I was tasked a while ago with building a demo for Remix Australia using MS Surface, Phone 7, desktop and touch based slate PC’s. It was a very big job, and that was without the 20 (yes twenty) day time limit!

With this in mind, I had to re-think the way I build applications. The tech included Silverlight, WPF (with Surface SDK) and Silverlight for Windows Phone 7…

The framework has since been used in a range of production projects in Silverlight desktop and WP7…

The end result is a little framework called XamlingCore which allows you to build MVVM based applications on all these platforms very quickly and simply.

It’s doesn’t have all the bells and whistles of other MVVM frameworks, but XamlingCore has pragmatism at it’s heart – think of it as the pragmatic MVVM framework. In fact, we suggest using something like MVVM light for most of the base level MVVM stuff, like commanding and event aggregation etc – in conjunction with XamlingCore… why re-invent the wheel.

Whaaaa?

At it’s most basic level, XamlingCore is a set of classes coupled with convention to allow simple view selection and navigation. It’s a lot more than that, but that is it’s most important feature. This series of posts will demonstrate the various abilities of the framework.

One of the biggest problems facing a good MVVM framework is how to perform view selection. Another problem facing MVVM frameworks is that they must be simple enough to pass off to “end” developers. XamlingCore addresses these two issues. It’s extremely easy to use, and makes developing multi view applications extremely simple.

View Selection?

One of the tricky bits with MVVM is what is view selection / pairing them up with a ViewModel. Some call it the “triad” – the Model – View – ViewModel triad process. This process can be difficult to understand…

Normally in applications, the developer will decide they want to show View X, lets for example use a Login screen. In MVVM, the login screen will need a ViewModel, which will expose properties that the View (Login.xaml) will databind to. The process needs to somehow address:

  • Creation of a view
  • Creation of a view model
  • Pass in parameters to the view model
  • Join the view to the view model
  • Navigate to the view (once it is ready)
  • Some how transition to the new view (slide, 3d spinny thingo etc.)
  • Navigate back
  • Plus a whole lot more

So, there is a built in navigation framework in Silverlight and WP7 SDK’s right? Yes… but…

The navigation framework I’m referring to here only allows the developer to navigate to a URI, which points to a XAML file. It’s difficult/un-intuitive to then pair up the ViewModel… especially when you start navigating around a complex application (like navigating back etc). It also precludes you from a few “tricks” to make your dev effort even easier.

Separation of concerns

Any good developer will tell you separation of concerns is very important. In Silverlight, two such concerns are the View and the ViewModel. Each have very different semantics.

The idea in XamlingCore is to draw a very thick line between these two areas – let the view side worry about what to show, and let the ViewModel side worry about itself. It might not be immediately obvious what we mean by this, so read on 🙂

ViewModel first versus View first navigation

We briefly mentioned above the navigation framework in Silverlight – this is a view first scenario… you select the view to navigate to. Selecting a view kicks off the navigation process.

In XamlingCore, you select (create) a ViewModel then navigate to it… strange? Maybe at first – until you see how the view side is configured to handle this. The view side consists of a “NavigationFrame” which takes the selected ViewModel and automatically picks up which XAML file to show (creating it in the process).

This allows you to code in your ViewModel agnostically (i.e. pretty much ignore the view) – at the same time creating a really strong workflow with sample data etc for designers is very easy too. You can create Views and ViewModels very quickly and easily

This series of posts will go through how to get XamlingCore up and running, and show you how it can help you in your development effort. Most of the series will be screen cast based, with some text articles.

For now, check out XamlingCore on Codeplex – review the FlickrSample application to get started… first video coming very soon!

Control, Silverlight

Tech.Ed Australia and New Zealand Code

Exploding elements, MVVM, Prism, Unity, RIA Service and offline apps!

Well the Tech.Ed time of year is over and let me tell you I had a fantastic time!

I was lucky enough to be asked to present a number of sessions in both Australia and New Zealand:

  • Going Deeper in Silverlight 3 (AU WEB309, NZ WUX301)
  • Architectural Considerations for Silverlight (AU ARC401, NZ ARC301)
  • Live Meeting stream of Going Deeper in Silverlight 3
  • Silverlight Birds of a Feather Lunch
  • A panel discussion on Rich vs Reach in Australia
  • A panel discussion on Designer and Developer workflow in New Zealand

All in all it was a massive fortnight and I’m only starting to catch up with the real world now!

As promised I’m releasing the code from my talks here.

The Architectural Considerations demo code should just start… but the Going Deeper code may need some “jiggling” as it is using IIS to run (so you can start and stop IIS to see server ping working).

<Sample Code>

TechEd 09 Australia and New Zealand Demo Code

</Sample Code>

  • Make sure you run VS as elevated
  • Once the IIS site has been created, go to IIS settings, create a new app pool. Run this app pool as local system (never do this in production!!). Make sure you set your site to use the new app pool. Without this the database would not load for me
  • Ensure you set the web project and sample ASPX file as start up

Both my talks take the real world approach – I didn’t want to just talk about stuff you can easily find by searching the ‘net – I wanted to show methods that I would employ in a real world application if asked to use these features.

The Architecture talk also concentrated heavily on how you can set up your project to make it nice and easy for developers to extend and maintain the application using Prism and MVVM.

This said, keep in mind this *is* demo code 🙂

Going Deeper in Silverlight 3

This session was split in to two sections – first we talked about some of the UI enhancements in Silverlight 3 then on to some of the more business style enhancements.

Perspective 3D

For perspective 3d and plane projection I demonstrated how to create a control based on ItemsControl to convert a standard boring old items list in to a fully 3d tag cloud complete with mouse interaction to move the items around the screen.

This can be found under Controls/3D/TagCloud and TagCloud item.

The ItemsControl (TagCloud) creates the item wrapper control (TagCloudItem). This is required for all items controls. For comparison ListBox control uses ListBoxItem <- each item in the list is wrapped in in a ListBoxItem, to which the DataTemplate is applied. A few methods are overridden in TagCloud, including GetContainerForItemOverride (create the TagCloudItem), IsItemItsOwnContainerOverride (to check that the user didn’t add TagCloudItems to the ItemsSource of the TagCloud) and PrepareContainerForItemOverride (which isn’t used, but gives you the chance to do something with the TagCloudItem and the data that will be applied to it).

The TagCloudItem is then responsible for making itself 3d. This is a great approach because you can template each item like normal, but the TagCloudItem brings the extra 3d behaviour – staying completely away from template modification and it will work straight out of the box when inserted in to a page.

The TagCloud is applied in MainPage.xaml.

Animation Easing

After a quick introduction to animation easing in Blend, I demonstrated how to create a custom animation easing function. The function is called RandomEase and can be found in Controls/Easing/RandomEase.cs.

This easing function basically takes any animation and randomises it – the best way to see this in action is to just run the app, 1000 words and all that. You will see my blog url in the bottom right of the app going crazy 🙂

The easing function is applied to the animations in MainPage.xaml in the UserControl.Resources section.

Behaviours, WritableBitmap and Perspective 3D

To demonstrate behaviours I created a special behavior called SuperVortex (Controls/Behavior/SuperVortex). There are two versions of this control, one which targets my custom control called TimerContentControl and one which can target any panel (Canvas, Grid etc).

The TimerControlControl is a cool little control I created which has a couple of states – one for when it’s content is null and one for when it’s content is set. This control is then bound to a property in the ViewModel, and when that property changes the control switches states allowing it to be shown on the screen. The control will show for a number of seconds before timing out the hiding itself again.

The SuperVortex behavior is then added to this control. A few seconds after the TimerContentControl is shown the SuperVortex kicks in and breaks the control in to a number of separate tiles, makes them spin around the screen before disappearing off in to the ether.

It achieves this by calculating a range of 50×50 tiles, then using the WritableBitmap control it splits it up by taking multiple snapshots of the control. Each snapshot uses a TranslateTransform to position itself to take a snapshot of the control in the right spot, creating a 50×50 tile. This snapshot is then added to a dynamically created image which is in turn added to the page (once again using another translate transform to reposition it where the original snapshot was crated).

Once all the tiles are created and overlaid, the original control is hidden. PlaneProjection is then used to spin the image tiles around of off the screen.

OOB and Network Detection

This is my favourite part of the talk – it revolves around using real world network detection, a service manager, a service locator and dependency injection to create a nice little loosely coupled network dection and management of online and offline services solution.

All data access in the application is performed through “repositories”. A repository is a small class which contains all the operations required to get data from the server. Each repository only contains methods to get a particular entity type. In this case we are getting Player entities from the server, so our repositories are called PlayerRespoistory. There are two PlayerRepositories, one for Online and for Offline.

The PlayerRepositories implement IPlayerRepository. When using a repository in code the app always references IPlayerRepository.

It all starts with the NetworkManagementService (Model\AppServices\NetworkStatusManager.cs). This service starts with the application (it implements IApplicationService). It then hooks up to the network changed events. Then it checks to see if the network adaptor is available. If it isn’t then it sets itself to be offline (firing events too). If the network adaptor is available, it will start a timer which will ping the server (using .NET RIA Services) to see if it is available. It then fires events based on whether the server is there or not.

These network events are detected by the ServiceManager. The ServiceManager is provided an instance of the Unity IOC Container. The Unity IOC container allows you to configure which concrete class will be resolved at a given time. As the network state changes from NetworkManagementService, the ServiceManager changes Unity to resolve a different version of the PlayerRepository by configuring IPlayerRepository to resolve to the online or offline version.

The ViewModel then asks the ServiceLocator for the IPlayerRepository. The ServiceLocator also uses Unity – this time to resolve the dependency. The ServiceLocator can just ask Unity to resolve the IPlayerRepository without having to know about the NetworkManagementService or the ServiceManager (i.e. it is loosely coupled). This is great as it makes it very easy to alter the behavior of the network and service management stuff without the rest of the application worrying about it.

Online and Offline

The two repositories operate different to each other. They both have to same methods to please the IPlayerRepository interface, but internally they do different things. First, the online version will serialise the retrieved entities to Isolated Storage for later retrieval, and the offline version will check for these saved entities, and deserialise them if available.

Once the application is running if you stop IIS the system will automatically switch between online and offline versions of the repositories, allowing offline data access.

Architectural Considerations for Silverlight

In this talk I (with Mahesh in Australia!) demonstrated more real world scenarios, this time around Prism (Composite UI) and MVVM (Model-View-ViewModel).

This talk takes the approach of creating good Silverlight architecture around these concepts to assist developers in working on the code on a day to day basis. It hides the complexity of using MVVM and Prism in a set of self documenting base classes. Developers that use these classes will find it very easy to create new Prism modules and ViewModels.

Prism

First up the Prism stuff. I demonstrated how easy it can be to create a new module with Prism with a simple Module base class, ViewModel base class and an interface for your views (called IView). The ViewModelBase base class takes the IView in its constructor and then using this interface is able to apply itself to the DataContext of the View (through the only method, ApplyModel). So now the ViewModelBase class will automatically do View hookup for us.

Then you create a new Prism module class and base it on ModuleBase. This class has one abstract method called Initialize. It also requires IUnityContainer and IRegionManager in its constructor (these are used by the base class).

In the Initialize method we call Register<ViewType, ViewModelType>(“RegionName”);. This makes it very easy for developers to create a view and view model, have the view model married up to the view and then register them in to a region. It uses Unity to create the instances (check out the Register method to see how). Because of the generic method, it is very self documenting and developers will be able to follow this without any extra instruction.

MVVM

For the last part of this talk I demonstrated a series of ViewModel base classes that I’ve been working on and improving for a while now.

The basic idea is that I wanted to create ViewModel base classes to encapsulate CRUD operations for both single entities and lists of entities.

EditableEntityViewModelBase

This view model class has all the commands and operations required to edit a single entity. It is based on ViewModelBase so can do to auto view model hookup talked about above. This class contains Commands which can be bound to buttons in the UI to allow the Save and Cancel edit of entities. What’s cool here is that using RIA Services, cancel will automatically roll back the edit of the entity. It also contains things like validation, logs errors in to an ObservableCollection for easy binding to the UI etc.

EditableCollectionViewModelBase

This view model allows for the editing of multiple items in a list. It is based on EditableEntityViewModelBase. This means that it can be used to edit the collection and also single items in the collection.

What’s cool here is that you can add new items, edit existing items, then click cancel – the new items will be removed again and the existing items will be reverted.

CharacterEditViewModel

This view model is based on EditableCollectionViewModel. It basically only has to get a list of the characters from the repository, other than this all other functionality is gained from the base classes.

As the base classes are once again generic they are self documenting to the developer – the developer cannot implement these classes wrong without getting a compiler error.

DataForm Commands

The edit screens use the Silverlight ToolKits DataForm. This control allows you to create edit forms for entities, complete with validation. The problem is that when the save or cancel buttons are pressed you need a way to inform the ViewModel that something happened. You don’t want to create any code behind in your view to do this or you are breaking the MVVM pattern.

To solve this I created a custom command handler that hooks up to the DataForm and allows commands to be bound that will fire when the DataForm Saves or Cancels. These commands are then bound up to the Commands from EditableEntityViewModel base… a nice solution all round.

Thanks!

As always if you have any questions or comments please don’t hesitate to ping me a comment, or contact me on twitter (@jakkaj).

Cheers!

Jordan.