Rough Notes on Experiments with UWP APIs in the Unity Editor with C++/WinRT

This post is a bunch of rough notes around a discussion that I’ve been having with myself around working with UWP code in Unity when building mixed reality applications for HoloLens. To date, I’ve generally written the code which calls UWP APIs in .NET code and followed the usual practice around it but in recent times I’ve seen folks doing more around implementing their UWP API calls in native code and so I wanted to experiment with that a little myself.

These notes are very rough so please apply a pinch of salt as I may well have got things wrong (it happens frequently) and I’m really just writing down some experiments rather than drawing a particular conclusion.

With those caveats in place…

Background – .NET and .NET Native

I remember coming to .NET in around 2000/2001.

At the time, I had been working as a C/C++ developer for around 10 years and I was deeply sceptical of .NET and the idea of C# as a new programming language and that I might end up running code that was Just-In-Time compiled.

That said, I was also coming off the back of 10 years of shipping code in C/C++ and the various problems around crashes, hangs, leaks, heap fragmentation, mismatched header files, etc. etc. etc. that afflicted the productivity of C/C++.

So, I was sceptical on the one hand but open to new ideas on the other and, over time, my C++ (more than my C) became rusty as I transitioned to C# and the CLR and its CIL.

There’s a bunch of advantages that come to having binaries made up of a ‘Common Intermediate Language’ underpinned by the CLR rather than native code. Off the top of my head, that might include things like;

  • Re-use of components and tooling across programming languages.
  • CIL was typically a lot smaller than native code representation of the same functionality.
  • One binary could support (and potentially optimize for) any end processor architecture by being compiled just-in-time on the device in question rather than ahead-of-time which requires per-architecture binaries and potentially per-processor variant optimisations.

and there are, no doubt, many more.

Like many things, there are also downsides with one being the potential impact on start-up times and, potentially, memory usage (and the ability to share code across processes) as CIL code is loaded for the first time and the methods JITted to a specific process’ memory in order to have runnable code on the target machine.

Consequently, for the longest time there have been a number of attempts to overcome that JITting overhead by doing ahead of time compilation including the fairly early NGEN tool (which brought with it some of its own challenges) and, ultimately, the development of the .NET Native set of technologies.

.NET Native and the UWP Developer

.NET Native had a big impact on the developer targeting the Universal Windows Platform (UWP) because all applications delivered from the Windows store are ultimately built with the .NET native tool-chain and so developers need to build and test with that tool-chain before submitting their app to the Store.

Developers who had got used to the speed with which a .NET application could be built, run and debugged inside of Visual Studio soon learned that building with .NET Native could introduce a longer build time and also that there were rare occasions where the native code didn’t match the .NET code and so one tool-chain could have bugs that another did not exhibit. That could also happen because of the .NET native compiler’s feature to remove ‘unused’ code/metadata which can have an impact on code – e.g. where reflection is involved.

However, here in 2019 those issues are few and far between & .NET Native is just “accepted” as the tool-chain that’s ultimately used to build a developer’s app when it goes to the Windows Store.

I don’t think that developers’ workload has been affected hugely because I suspect that most UWP developers probably still follow the Visual Studio project structure and use the Debug configuration (.NET compiler) to do their builds during development making use of the regular, JITted .NET compiler and reserve the Release configuration (.NET Native compiler) for their final testing. Either way, your code is being compiled by a Microsoft compiler to CIL and by a Microsoft compiler from CIL to x86/x64/ARM.

It’s worth remembering that whether you write C# code or C++ code the debugger is always doing a nice piece of work to translate between the actual code that runs on the processor and the source that you (or someone else) wrote and want to step through getting stack frames, variable evaluation etc. The compiler/linker/debugger work together to make sure that via symbols (or program databases (PDBs)) this process works so seamlessly that, at times, it’s easy to forget how complicated a process it is and we take it for granted across both ‘regular .NET’ and ‘.NET Native’.

So, this workflow is well baked and understood and, personally, I’d got pretty used to it as a .NET/UWP developer and it didn’t really change whether developing for PC or other devices like HoloLens with the possible exception that deployment/debugging is naturally going to take a little more time on a mobile-powered device than on a huge PC.

Unity and the UWP

But then I came to Unity 😊

In Unity, things initially seem the same for a UWP developer. You write your .NET code in the editor, the editor compiles it “on the fly” as you save those code changes and then you can run and debug that code in the editor.

As an aside, the fact that you can attach the .NET debugger to the Unity Editor is (to me) always technically impressive and a huge productivity gain.

When you want to build and deploy, you press the right keystrokes and Unity generates a C# project for you with/without all your C# code in it (based on the “C# Projects” setting) and you are then back into the regular world of UWP development. You have some C# code, you have your debugger and you can build debug (.NET) or release (.NET Native) just like any other UWP app written with .NET.

Unity and .NET Scripting/IL2CPP

That’s true if you’re using the “.NET Scripting backend” in Unity. However, that backend is deprecated as stated in the article that I just linked to and so, really, a modern developer should be using the IL2CPP backend.

That deprecation has implications. For example, if you want to move to using types from .NET Standard 2.0 in your app then you’ll find that Unity’s support for .NET Standard 2.0 lives only in the IL2CPP backend and hasn’t been implemented in the .NET Scripting backend (because it’s deprecated).

2018.2.16f1, UWP, .NET Scripting Backend, .NET Standard 2.0 Build Errors

With the IL2CPP backend, life in the editor continues as before. Unity builds your .NET code, you attach your .NET debugger and you can step through your code. Again, very productive.

However, life outside of the editor changes in that any code compiled to CIL (i.e. scripts plus dependencies) is translated into C++ code by the compiler. The process of how this works is documented here and I think it’s well worth 5m of your time to read through that documentation if you haven’t already.

This has an impact on build times although I’ve found that if you carefully follow the recommendations that Unity makes on this here then you can get some cycles back but it’s still a longer process than it was previously.

Naturally, when Unity now builds what drops out is not a C#/.NET Visual Studio project but, instead, a C++ Visual Studio project. You can then choose the processor architecture and debug/release etc. but you’re compiling C++ code into native code and that C++ represents all the things you wrote along with translations of lots of things that you didn’t write (e.g. lists, dictionaries, etc. etc.). Those compilations times, again, can get a bit long and you get used to watching the C++ compile churn its way through implementations of things like generics, synchronisation primitives, etc.

Just as with .NET Native, Unity’s C#->C++ translation has the advantage of stripping out things which aren’t used which can impact technologies like reflection and, just like .NET Native, Unity has a way of dealing with that as detailed here.

When it comes to debugging that code, you have two choices. You can either;

  • Debug it at the C# level.
  • Debug the generated C++.
  • Ok, ok, if you’re hardcore you can just debug the assembly but I’ll assume you don’t want to be doing this all the time (although I’ll admit that I did single step some pieces while trying to fix things for this post but it’s more by necessity than choice).

C# debugging involves setting the “Development Build” and “Script Debugging” options as described here and you essentially run up the app on the target device with this debugging support switched on and then ask the Unity debugger to attach itself to that app similarly to the way in which you ask the Unity debugger to attach to the editor. Because this is done over the network, you also have to ensure that you set certain capabilities in your UWP app manifest (InternetClient, InternetClientServer, PrivateNetworkClientServer).

For the UWP/HoloLens developer, this isn’t without its challenges at the time of writing and I mentioned some of those challenges in this post;

A Simple glTF Viewer for HoloLens

and my friend Joost just wrote a long post about how to get this working;

Debugging C# code with Unity IL2CPP projects running on HoloLens or immersive headsets

and that includes screenshots and provides a great guide. I certainly struggled to get this working when I tried it for the first time around as you can see from the forum thread I started below;

Unity 2018.2.16f1, UWP, IL2CPP, HoloLens RS5 and Managed Debugging Problems.

so a guide is very timely and welcome.

As was the case with .NET Native, of course it’s possible that the code generated by IL2CPP differs in its behavior from the .NET code that now runs inside the editor and so it’s possible to get into “IL2CPP bugs” which can seriously impact your productivity.

C# debugging kind of feels a little “weird” at this point as you stare into the internals of the sausage machine. The process makes it very obvious that what you are debugging is code compiled from a C++ project but you point a debugger at it and step through as though it was a direct compilation of your C# code. It just feels a little odd to me although I think it’s mainly perception as I have long since got over the same feeling around .NET Native and it’s a very similar situation.

Clearly, Unity are doing the right thing with making the symbols line up here which is clever in itself but I feel like there are visible signs of the work going on when it comes to performance of debugging and also some of the capabilities (e.g. variable evaluation etc). However, it works and that’s the main thing 😊

In these situations I’ve often found myself with 2 instances of Visual Studio with one debugging the C# code using the Unity debugger support while the other attached as a native debugger to see if I catch exceptions etc. in the real code. It’s a change to the workflow but it’s do-able.

IL2CPP and the UWP Developer

That said, there’s still a bit of an elephant in the room here in that for the UWP developer there’s an additional challenge to throw into this mix in that the Unity editor always uses Mono which means that it doesn’t understand calls to the UWP API set (or WinRT APIs if you prefer) as described here.

This means that it’s likely that a UWP developer (making UWP API calls) takes more pain here than the average Unity developer as to execute the “UWP specific” parts of their code they need to set aside the editor, hit build to turn .NET into C++ and then hit build in Visual Studio to build that C++ code and then they might need to deploy to a device before being able to debug (either the generated C++ or the original .NET code) that calls into the UWP.

The usual pattern for working with UWP code is detailed on this doc page and involves taking code like that below;

which causes the Unity editor some serious concern because it doesn’t understand Windows.* namespaces;

And so we have to take steps to keep this code away from the editor;

And then this will “work” both in the editor and if we compile it out for UWP through the 2-stage compilation process. Note that the use of MessageDialog here is just an example and probably not a great one because there’s no doubt some built-in support in Unity for displaying a dialog without having to resort to a UWP API.

Calling UWP APIs from the Editor

I’ve been thinking about this situation a lot lately and, again, with sympathy for the level of complexity of what’s going on inside that Unity editor – it does some amazing things in making all of this work cross-platform.

I’d assume that trying to bring WinRT/UWP code directly into that Editor environment is a “tall-order” and I think it stems from the editor running on Mono and there not being underlying support there for COM interop although I could be wrong. Either way, part of me understands why the editor can’t run my UWP code.

On the other hand, the UWP APIs aren’t .NET APIs. They are native code APIs in Windows itself and the Unity editor can happily load up native plugins and execute custom native code and so there’s a part of me wonders whether the editor couldn’t get closer to letting me call UWP APIs.

When I first came to look at this a few years ago, I figured that I might be able to “work around it” by trying to “hide” my UWP code inside some .NET assembly and then try to add that assembly to Unity as a plugin but the docs say that managed plugins can’t consume Windows Runtime APIs.

As far as I know, you can’t have a plugin which is;

  • a WinRT component implemented in .NET or in C++.
  • a .NET component that references WinRT APIs or components.

But you can have a native plugin which makes calls out to WinRT APIs so what does it look like to go down that road?

Unity calling Native code calling UWP APIs

I wondered whether this might be a viable option for a .NET developer given the (fairly) recent arrival of C++/WinRT which seems to make programming the UWP APIs much more accessible than it was in the earlier worlds of WRL and/or C++/CX.

To experiment with that, I continued my earlier example and made a new project in Visual C++ as a plain old “Windows Desktop DLL”.

NB: Much later in this post, I will regret thinking that a “plain old Windows Desktop DLL” is all I’m going to need here but, for a while, I thought I would get away with it.

To that project, I can add includes for C++/WinRT to my stdafx.h as described here;


And I can alter my link options to link with WindowsApp.lib;

And then I can maybe write a little function that’s exported from my DLL;

And the implementation there is C++/WinRT – note that I just use a Uri by declaring one rather than leaping through some weird ceremony to make use of it.

If I drag the DLL that I’ve built into Unity as a plugin then my hope is that I can tell Unity to use the 64-bit version purely for the editor and the 32-bit version purely for the UWP player;

I can then P/Invoke from my Unity script into that exported DLL function as below;

And then I can attach my 2 debuggers to Unity and debug both the managed code and the native code and I’m making calls into the UWP! from the editor and life is good & I don’t have to go through a long build cycle.

Here’s my managed debugger attached to the Unity editor;

And here’s the call being returned from the native debugger also attached to the Unity editor;

and it’s all good.

Now, if only life were quite so simple 😊

Can I do that for every UWP API?

It doesn’t take much to break this in that (e.g.) if I go back to my original example of displaying a message box then it’s not too hard to add an additional header file;

And then I can write some exported function that uses MessageDialog;

and I can import it and call it from a script in Unity;

but it doesn’t work. I get a nasty exception here and I think that’s because I chose MessageDialog as my API to try out here and MessageDialog relies on a CoreWindow and I don’t think I have one in the Unity editor. Choosing a windowing API was probably a bad idea but it’s a good illustration that I’m not likely to magically just get everything working here.

There’s commentary in this blog post around challenges with APIs that depend on a CoreWindow.

What about Package Identity?

What about some other APIs. How about this? If I add the include for Windows.Storage.h;

And then add an exported function (I added a DuplicateString function to take that pain away) to get the name of the local application data folder;

and then interop to it from Unity script;

and then this blows up;

Now, this didn’t exactly surprise me. In fact, the whole reason for calling that API was to cause this problem as I knew it was coming as part of that “UWP context” includes having a package identity and Unity (as a desktop app) doesn’t have a package identity and so it’s not really fair to ask for the app data folder when the application doesn’t have one.

There’s a docs page here about this notion of APIs requiring package identity.

Can the Unity editor have a package identity?

I wondered whether there might be some way to give Unity an identity such that these API calls might work in the editor? I could think of 2 ways.

  1. Package Unity as a UWP application using the desktop bridge technologies.
  2. Somehow ‘fake’ an identity such that from the perspective of the UWP APIs the Unity editor seems to have a package identity.

I didn’t really want to attempt to package up Unity and so I thought I’d try (2) and ended up having to ask around and came up with a form of a hack although I don’t know how far I can go with it.

Via the Invoke-CommandInDesktopPackage PowerShell command it seems it’s possible to execute an application in the “context” or another desktop bridge application.

So, I went ahead and made a new, blank WPF project and then I used the Visual Studio Packaging Project to package it as a UWP application using the bridge and that means that it had “FullTrust” as a capability and I also gave it “broadFileSystemAccess” (just in case).

I built an app package from this and installed it onto my system and then I experimented with running Unity within that app’s context as seen below – Unity here has been invoked inside the package identity of my fake WPF desktop bridge app;

I don’t really know to what extent this might break Unity but, so far, it seems to survive ok and work but I haven’t exactly pushed it.

With Unity running in this UWP context, does my code run any better than before?

Well, firstly, I noticed that Unity no longer seemed to like loading my interop DLL. I tried to narrow this down and haven’t figured it out yet but I found that;

  1. First time, Unity wouldn’t find my interop DLL.
  2. I changed the name to something invalid, forcing Unity to look for that and fail.
  3. I changed the name back to the original name, Unity found it.

I’m unsure on the exact thing that’s going wrong there so I need to return to that but I can still get Unity to load my DLL, I just have to play with the script a little first. But, yes, with a little bit of convincing I can get Unity to make that call;


And what didn’t work without an identity now works when I have one so that’s nice!

The next, natural thing to do might be to read/write some data from/to a file. I thought I’d try a read and to do that I used the co_await syntax to do the async pieces and then used the .get() method to ultimately make it a synchronous process as I wasn’t quite ready to think about calling back across the PInvoke boundary.

And that causes a problem depending on how you invoke it. If I invoke it as below;


Then I get an assertion from somewhere in the C++/WinRT headers telling me (I think) that I have called the get() method on an STA thread. I probably shouldn’t call this method directly from my own thread anyway because the way in which I have written it (with the .get()) call blocks the calling thread so regardless of STA/MTA it’s perhaps a bad idea.

However, if I ignore that assertion, the call does seem to actually work and I get the contents of the file back into the Unity editor as below;

But I suspect that I’m not really meant to ignore the assertion and so I can switch the call to something like;

and the assertion goes away and I can read the file contents 😊

It’s worth stating at this point that I’ve not even thought about how I might try to actually pass some notion of an async operation across the PInvoke boundary here, that needs more thought on my part.

Ok, Call some more APIs…

So far, I’ve called dialog.show() and file.read() so I felt like I should try a longer piece of code with a few more API calls in it.

I’ve written a few pieces of code in the past which try to do face detection on frames coming from the camera and I wondered whether I might be able to reproduce that here – maybe write a method which runs until it detects a face in the frames coming from the camera?

I scribbled out some rough code in my DLL;

// Sorry, this shouldn't really be one massive function...
IAsyncOperation<int> InternalFindFaceInDefaultCameraAsync()
{
	auto facesFound(0);

	auto devices = co_await DeviceInformation::FindAllAsync(DeviceClass::VideoCapture);

	if (devices.Size())
	{
		DeviceInformation deviceInfo(nullptr);

		// We could do better here around choosing a device, we just take
		// the front one or the first one.
		for (auto const& device : devices)
		{
			if ((device.EnclosureLocation().Panel() == Panel::Front))
			{
				deviceInfo = device;
				break;
			}
		}
		if ((deviceInfo == nullptr) && devices.Size())
		{
			deviceInfo = *devices.First();
		}
		if (deviceInfo != nullptr)
		{
			MediaCaptureInitializationSettings initSettings;
			initSettings.StreamingCaptureMode(StreamingCaptureMode::Video);
			initSettings.VideoDeviceId(deviceInfo.Id());
			initSettings.MemoryPreference(MediaCaptureMemoryPreference::Cpu);

			MediaCapture capture;
			co_await capture.InitializeAsync(initSettings);

			auto faceDetector = co_await FaceDetector::CreateAsync();
			auto faceDetectorFormat = FaceDetector::GetSupportedBitmapPixelFormats().GetAt(0);

			// We could do better here, we will just take the first frame source and
			// we assume that there will be at least one. 
			auto frameSource = (*capture.FrameSources().First()).Value();
			auto frameReader = co_await capture.CreateFrameReaderAsync(frameSource);

			winrt::slim_mutex mutex;

			handle signal{ CreateEvent(nullptr, true, false, nullptr) };
			auto realSignal = signal.get();

			frameReader.FrameArrived(
				[&mutex, faceDetector, &facesFound, faceDetectorFormat, realSignal]
			(IMediaFrameReader reader, MediaFrameArrivedEventArgs args) -> IAsyncAction
			{
				// Not sure I need this?
				if (mutex.try_lock())
				{
					auto frame = reader.TryAcquireLatestFrame();

					if (frame != nullptr)
					{
						auto bitmap = frame.VideoMediaFrame().SoftwareBitmap();

						if (bitmap != nullptr)
						{
							if (!FaceDetector::IsBitmapPixelFormatSupported(bitmap.BitmapPixelFormat()))
							{
								bitmap = SoftwareBitmap::Convert(bitmap, faceDetectorFormat);
							}
							auto faceResults = co_await faceDetector.DetectFacesAsync(bitmap);

							if (faceResults.Size())
							{
								// We are done, we found a face.
								facesFound = faceResults.Size();
								SetEvent(realSignal);
							}
						}
					}
					mutex.unlock();
				}
			}
			);
			co_await frameReader.StartAsync();

			co_await resume_on_signal(signal.get());

			// Q - do I need to remove the event handler or will the destructor do the
			// right thing for me?
			co_await frameReader.StopAsync();
		}
	}
	return(facesFound);
}

That code is very rough and ready but with an export from the DLL that looks like this;

	__declspec(dllexport) int FindFaceInDefaultCamera()
	{
		int faceCount = InternalFindFaceInDefaultCameraAsync().get();

		return(faceCount);
	}

then I found that I can call it from the editor and, sure enough, the camera lights up on the machine and the code returns that it has detected my face from the camera so that’s using a few UWP classes together to produce a result.

So, I can call into basic APIs (e.g. Uri), I can call into APIs that require package identity (e.g. StorageFile) and I can put together slightly more complex scenarios involving cameras, bitmaps, face detection etc.

It feels like I might largely be able to take this approach to writing some of my UWP code in C++/WinRT and have the same code run both inside of the editor and on the device and debug it in both places and not have to go around longer build times while working it up in the editor.

Back to the device…

I spent a few hours in the Unity editor playing around to get to this point in the post and then I went, built and deployed my code to an actual device and it did not work. Heartbreak 😉

I was getting failures to load my DLL on the device and I quickly put them down to my DLL having dependencies on VC runtime DLLs that didn’t seem to be present. I spent a little bit of time doing a blow-by-blow comparison on the build settings of a ‘UWP DLL’ versus a ‘Windows DLL’ but, in the end, decided I could just build my code once in the context of each.

So, I changed my C++ project such that it contained the original “Windows Desktop DLL” along with a “UWP DLL” and the source code is shared between the two as below;

With that in place, I use the 64-bit “Windows Desktop DLL” in the editor and the 32-bit “UWP DLL” on the device (the ‘player’) and that seems to sort things out for me. Note that both projects build a DLL named NativePlugin.dll.

That said, I’d really wanted to avoid this step and thought I was going to get away with it but I fell at the last hurdle but I’d like to revisit and see if I can take away the ‘double build’ but someone will no doubt tell me what’s going on there.

Wrapping Up

As I said at the start of the post, this is just some rough notes but in making calls out to the few APIs that I’ve tried here I’m left feeling that the next time I have to write some Unity/UWP specific code I might try it out in C++/WinRT first with this PInvoke method that I’ve done here & see how it shapes up as the productivity gain of being able to press ‘Play’ in the editor is huge. Naturally, if that then leads to problems that I haven’t encountered in this post then I can flip back, translate the code back to C# and use the regular “conditional compilation” mechanism.

Code

I’m conscious that I pasted quite a lot of code into this post as bitmaps and that’s not very helpful so I just packaged up my projects onto github over here.

Inside of the code, 2 of the scenarios from this post are included – the code for running facial detection on frames from the camera and the code which writes a file into the UWP app’s local data folder.

I’ve tried that code both in the Unity editor and on a HoloLens device & it seems to work fine in both places.

All mistakes are mine, feel free to feed back and tell me what I’ve done wrong! 🙂

The Right Way to Maintain a Duplicate PC? Boot to VHD?

This post is really a cry for help Winking smile 

The other week I reinstalled my Surface Book as it had got itself into a bit of a mess with respect to the Windows 10 Fall Creators Update and so I spent maybe the best part of a day wiping the disk and reinstalling software and getting settings and things all set up the way that I like them. This is helped massively these days by a fast internet connection and a bunch of software (e.g. Microsoft Office and Store apps) being pretty quick and easy to install.

However, it still takes time.

My Surface Book is my main machine but it doesn’t meet the specifications for Windows Mixed Reality development or use and so there’s a bit of a challenge and, consequently, I recently managed to bag another laptop to do that development work (an HP Omen 15).

That left me asking the question of what would be the ‘easiest’ way to duplicate the setup of my Surface Book to this new Omen machine? as I really didn’t want to have to go through and repeat the whole process that I’d recently undertaken on the Book and so I was looking for a cheap way out.

I’m not sure of what the answer to the question is. I read a few sysprep guides but wasn’t sure it would do what I wanted and so in the short term what I tried out was to…

  1. Use Sysinternals Disk2Vhd to make a .VHDX file from my Surface Book’s disk. I had to first make sure that I wasn’t running Bitlocker before making that .VHDX.
  2. Copy that .VHDX file over to the Omen PC.
  3. Attach it as a disk inside of the Disk Management utility.
  4. Use the BCDBOOT utility to make that newly attached disk bootable on the Omen.

From there, I rebooted Windows and let it boot off the .VHDX file and sat back and watched Windows;

  1. Do a lot of disk checking.
  2. Do a lot of ‘getting devices ready’ type activities (not unexpected moving a drive from one PC to another).

and then it let me log in once it had got through its slight discomfort at not being able to log me in with Windows Hello face or PIN because whatever it had cached no longer matched the hardware.

Once logged in, I went through Device Manager and reinstalled lots of drivers for the Omen and that seemed to go fine and then I changed the machine name and tried to reactivate Windows (I’m using an Enterprise copy here) and that worked once I could make a VPN connection to my company.

The only place where I seemed to have a challenge with the Omen was with its Audio driver in that I kept getting the Device Manager showing me a problem with a “High Definition Audio Device” and I couldn’t get any sound of the Omen’s built in speakers but it seemed like a few reinstallations of the Realtek driver from HP’s site and a few reboots and this suddenly started working.

So…now I’m booting to VHD on the Omen and, hopefully, getting “native” everything with the slight overhead of the disk being a VHD rather than just a plain disk.

As/when I make updates to the Surface Book I’d need to repeat the process to get the Omen so that it was back in sync.

I’ll update the post as/when I find problems with what I’ve done here (I’m sure there’ll be some I haven’t thought through Smile) but I’d welcome people’s comments around whether this is a good/bad/ugly way to try and maintain a common configuration across these 2 PCs? I’d estimate that it took me about an hour to get the HP up and running so it feels like a reasonable trade-off at the moment.

As an aside, in this world of cloud-delivered software, Microsoft Graph and Store wouldn’t it be cool if there was some button that I could press to say “Please make this PC exactly the same as one of my other ones?” and build up some cloud-inventory of what was actually on my PC so that I could replicate it at any time?

Windows 8.1, Visual Studio 2013 Preview–Grid Template on PRISM

After the previous post, I wanted to take a look at how I might re-work the Visual Studio 2013 template such that it retained the same UI and functionality but was built on PRISM rather than code-behind and so on.

This doesn’t mean that I’m going to end up with some kind of “best practise”, I was just keen to see what dropped out if I tried to combine these two worlds.

So, I made a blank Grid XAML project in Visual Studio 2013 and started to move it around a little.

Adding in PRISM and “Friends”

The first thing I did was took my new blank project and went out and added in a bit of PRISM from NuGet and, while I was there I figured I’d probably be wanting some kind of IoC container so I brought in Autofac as well. This leaves me with a few new references;

image

All good stuff – next I wanted to encapsulate the code that already existed for accessing the data.

Moving the Data Access into a Service

The next thing I wanted to do was to take as much of the existing code (which loads up the SampleData.json file at runtime) and move it into a service that I can abstract behind an interface whose implementation can then be injected into view models.

I wanted to leave the code alone as much as possible but some of the existing code relied on statics so had to be changed a little (I can’t implement a static interface) but I dropped out a Services folder into my project and an Abstractions folder to with it;

image

and I defined myself a new interface IDataService;

namespace PrismGridTemplate.Abstractions
{
    interface IDataService
    {
        Task<IEnumerable<DataGroup>> GetGroupsAsync();
        Task<DataGroup> GetGroupAsync(string uniqueId);
        Task<DataItem> GetItemAsync(string uniqueId);
    }
}

which is essentially just a refactoring of the public methods on the Grid’s template’s SampleDataSource class into an interface. I implemented that interface in my DataService class mostly by stealing the implementation from the existing SampleDataSource code;

using PrismGridTemplate.Abstractions;
using PrismGridTemplate.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Storage;

namespace PrismGridTemplate.Services
{
    internal class DataService : IDataService
    {
        // MT: This is purely here to support this class nicely de-serializing itself from the
        // sample data that shipped with the original template.
        public  ObservableCollection<DataGroup> Groups { get; set; }
        public async Task<IEnumerable<DataGroup>> GetGroupsAsync()
        {
            await GetSampleDataAsync();
            return this.groups;
        }

        public async Task<DataGroup> GetGroupAsync(string uniqueId)
        {
            await GetSampleDataAsync();

            var matches = this.groups.Where((group) => group.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        public async Task<DataItem> GetItemAsync(string uniqueId)
        {
            await GetSampleDataAsync();
            // Simple linear search is acceptable for small data sets
            var matches = this.groups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        private async Task GetSampleDataAsync()
        {
            if (this.groups != null)
                return;

            this.groups = new List<DataGroup>();

            Uri dataUri = new Uri("ms-appx:///SampleData/SampleData.json");

            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);
            string jsonText = await FileIO.ReadTextAsync(file);
            JsonObject jsonObject = JsonObject.Parse(jsonText);
            JsonArray jsonArray = jsonObject["Groups"].GetArray();

            foreach (JsonValue groupValue in jsonArray)
            {
                JsonObject groupObject = groupValue.GetObject();
                DataGroup group = new DataGroup(groupObject["UniqueId"].GetString(),
                                                            groupObject["Title"].GetString(),
                                                            groupObject["Subtitle"].GetString(),
                                                            groupObject["ImagePath"].GetString(),
                                                            groupObject["Description"].GetString());

                foreach (JsonValue itemValue in groupObject["Items"].GetArray())
                {
                    JsonObject itemObject = itemValue.GetObject();
                    group.Items.Add(new DataItem(itemObject["UniqueId"].GetString(),
                                                       itemObject["Title"].GetString(),
                                                       itemObject["Subtitle"].GetString(),
                                                       itemObject["ImagePath"].GetString(),
                                                       itemObject["Description"].GetString(),
                                                       itemObject["Content"].GetString()));
                }
                this.groups.Add(group);
            }
        }
        List<DataGroup> groups;
    }
}

I don’t think I changed a whole bunch of code there from the original. Perhaps the main changes would be that the original code did some work to only load the data once (i.e. it stuck the loaded data into some static storage slot). I haven’t taken this decision here – I’m going to lead the decision around the instancing of this service to the way in which I configure my IoC container.

Moving the Data Classes into a Model

I took the original data classes that are called SampleDataGroup and SampleDataItem and renamed them and dropped them into a folder I called Model. This might be me being slightly pretentious but it seemed like a good place to put them. I called them DataGroup and DataItem and, beyond the naming, I don’t think I changed them at all.

While I was at it, I made a folder called SampleData and put the SampleData.json file in there for safe-keeping.

image

and, for completeness, those classes look like;

using System;

namespace PrismGridTemplate.Model
{
    internal class DataItem
    {
        public DataItem(String uniqueId, String title, String subtitle, String imagePath, String description, String content)
        {
            this.UniqueId = uniqueId;
            this.Title = title;
            this.Subtitle = subtitle;
            this.Description = description;
            this.ImagePath = imagePath;
            this.Content = content;
        }

        public string UniqueId { get; private set; }
        public string Title { get; private set; }
        public string Subtitle { get; private set; }
        public string Description { get; private set; }
        public string ImagePath 
        { 
            get
            {
                return (imagePath);
            }
            private set
            {
                imagePath = value;
            }
        }
        string imagePath;
        public string Content { get; private set; }

        public override string ToString()
        {
            return this.Title;
        }
    }
}

and;

using System;
using System.Collections.ObjectModel;

namespace PrismGridTemplate.Model
{
    internal class DataGroup
    {
        public DataGroup(String uniqueId, String title, String subtitle, String imagePath, String description)
        {
            this.UniqueId = uniqueId;
            this.Title = title;
            this.Subtitle = subtitle;
            this.Description = description;
            this.ImagePath = imagePath;
            this.Items = new ObservableCollection<DataItem>();
        }

        public string UniqueId { get; private set; }
        public string Title { get; private set; }
        public string Subtitle { get; private set; }
        public string Description { get; private set; }
        public string ImagePath { get; private set; }
        public ObservableCollection<DataItem> Items { get; private set; }

        public override string ToString()
        {
            return this.Title;
        }
    }
}


I chose to leave these classes alone because they lined up with the SampleData.json file and I figured it wouldn’t be too much pain to wrap some view models around them.

Adding ViewModels – Generalities

PRISM ships a ViewModel base class of its own. It’s mostly an implementation of INotifyPropertyChanged along with an (empty) implementation of INavigationAware which is a PRISM interface that can be used to involve your ViewModels in navigation events – e.g. as navigation occurs from “Page 1” to “Page 2” this interface allows you to hook a ViewModel into that navigation and grab navigation parameters. For me, this is one of the places where the Visual Studio templates fall down a bit. They tie up navigation with the views which makes it hard to implement your ViewModels.

PRISM also gives you an implementation of a NavigationService which it abstracts via an interface INavigationService. This means that it’s “easy” to inject some componentry that knows how to do navigation into your ViewModels whereas, again, in the Visual Studio templates the navigation is usually quite tied to the UI componentry like Frame, Page and so on.

If you haven’t already been through this stuff with PRISM then you could start at this earlier post and use it as a launching point into the other PRISM documentation which I can’t recommend highly enough.

I’m not claiming to have this quite right but I figured that my ViewModels would almost certainly want to surface implementations of ICommand so I derived from ViewModel and added that capability;

    class CommandableViewModel : ViewModel
    {
        public CommandableViewModel()
        {
            this.commands = new Dictionary<string, ICommand>();
        }
        protected void AddCommand(string name, Action action)
        {
            this.commands[name] = new DelegateCommand(action);
        }
        protected void AddCommand(string name, Action action, Func<bool> enabledAction)
        {
            this.commands[name] = new DelegateCommand(action, enabledAction);
        }
        public IReadOnlyDictionary<string, ICommand> Commands
        {
            get
            {
                return (this.commands);
            }
        }
        Dictionary<string, ICommand> commands;
    }

The idea of this is that it’s easy for a derived class to add commands into the Commands dictionary with something like;

    class NavigationViewModel : CommandableViewModel
    {
        public NavigationViewModel(INavigationService navService)
        {
            this.navService = navService;
            base.AddCommand("GoBackCommand", GoBack, this.navService.CanGoBack);
        }

and then a piece of XAML can bind to a command like that by using something like;

<Button Command="{Binding Commands[GoBackCommand]}">

I also figured that my ViewModels might want to be able to deal with navigation so I evolved a variant that had access to an INavigationService;

using Microsoft.Practices.Prism.StoreApps.Interfaces;

namespace PrismGridTemplate.ViewModels
{
    class NavigationViewModel : CommandableViewModel
    {
        public NavigationViewModel(INavigationService navService)
        {
            this.navService = navService;
            base.AddCommand("GoBackCommand", GoBack, this.navService.CanGoBack);
        }
        protected void GoBack()
        {
            this.navService.GoBack();
        }
        protected void Navigate(string token, object parameter)
        {
            this.navService.Navigate(token, parameter);
        }
        protected INavigationService NavigationService
        {
            get
            {
                return (this.navService);
            }
        }
        INavigationService navService;
    }
}

And so now anything that derives from this can offer the UI a way to bind to a GoBackCommand which will work with the underlying INavigationService (which I’m assuming will be injected) to do the actual work of navigation (under there somewhere is a Frame but in this sort of code that’s the last thing I want to know about Smile).

Being a little bit lazy, I figured that I would now want to produce specific view models (e.g. to surface my DataGroups and DataItems) and I figured that to some extent these would be aggregating those classes. I find aggregation in .NET a bit of a pain. If I have some type Foo then sometimes I’d like to be able to wrap some type Bar around Foo such that Bar surfaces all the public properties/methods of Foo. I want to write syntax something like;

class Bar aggregates Foo public properties
{
    Bar(Foo f)
  {
  }
}

but, clearly, this is fantasy! so instead I derived another ViewModel that does this in a less elegant way (I could derive from Foo of course but that’s another story) and so I came up with the horribly named;

using Microsoft.Practices.Prism.StoreApps.Interfaces;

namespace PrismGridTemplate.ViewModels
{
    class NavigationViewModelWrapsModel<T> : NavigationViewModel
    {
        public NavigationViewModelWrapsModel(T model, INavigationService navService)
            : this(navService)
        {
            this.model = model;
        }
        public NavigationViewModelWrapsModel(INavigationService navService)
            : base(navService)
        {

        }
        // Note, unless the Model property itself does INotifyPropertyChanged then 2-way
        // bindings to properties within that Model won't work. For this example, everything
        // is read-only so this doesn't matter.
        public T Model
        {
            get
            {
                return (this.model);
            }
            set
            {
                base.SetProperty(ref this.model, value);
            }
        }
        T model;
    }
}

and, as the comment in the code says, unless the underlying type T happens to implement INotifyPropertyChanged (and I don’t constrain it here to do that) I’m not going to get property changed notifications firing from any properties of T as they change value which is no problem in this particular template because there’s the Grid template only surfaces read-only data.

All these little base classes might seem like overkill and I could definitely have produced some ViewModels without them but they seem to make the specific ViewModel code a whole lot more succinct and (arguably for me) more elegant so I introduce them. I wouldn’t need to write them again, they’d do for other projects in the future where I was using PRISM.

Adding ViewModels – Specifics

I have 3 views ( GroupedItemsPage, GroupDetailPage, ItemDetailPage ) and I have 2 entities within my model ( DataGroup, DataItem ). They come together in the sense that;

  • GroupedItemsPage displays groups and items.
  • GroupDetailPage displays one group and its items.
  • ItemDetailPage displays one item.

In the interest of keeping things “short”, I decided that I could deal with all of those needs with 3 ViewModels. That is – when the GroupedItemsPage displays an Item it’s going to be using the exact same ViewModel as when the ItemDetailPage is displaying one item. I can argue back/forth about whether this is “right” or not but, hey, it works for me in this particular situation.

PRISM has conventions around naming of Views/ViewModels which work perfectly well for me and so I went along with them (you can easily change them) and named a folder ViewModels;

image

and dropped all my classes related to ViewModels in there but the three that are specifically about pages are ItemDetailPageViewModel, GroupDetailPageViewModel, GroupedItemsPageViewModel.

Taking a look at those alongside their corresponding, data-bound UI…

ItemDetailPageViewModel and ItemDetailPageView

The ItemDetailPageViewModel class I ended up is as below;

using Microsoft.Practices.Prism.StoreApps.Interfaces;
using PrismGridTemplate.Abstractions;
using PrismGridTemplate.Model;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.UI.Xaml.Navigation;

namespace PrismGridTemplate.ViewModels
{
    class ItemDetailPageViewModel : NavigationViewModelWrapsModel<DataItem>
    {
        public ItemDetailPageViewModel(IDataService dataService, INavigationService navService) : base(navService)
        {
            this.dataService = dataService;
            base.AddCommand("ItemInvokedCommand", OnItemInvoked);
        }
        public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);

            string uniqueItemId = (string)navigationParameter;
            this.LoadDataAsync(uniqueItemId);
        }
        async Task LoadDataAsync(string uniqueItemId)
        {
            this.Model = await this.dataService.GetItemAsync(uniqueItemId);            
        }
        void OnItemInvoked()
        {
            this.Navigate("ItemDetail", this.Model.UniqueId);
        }
        IDataService dataService;
    }
}

There’s not a whole lot to see – the ViewModel surfaces a property of type DataItem as its Model property and it takes a dependency on IDataService and INavigationService (for its base class) and when the ViewModel is “navigated to” it uses the IDataService to load the data using pretty much the same methods as the original Grid template from Visual Studio (albeit re-packaged as a service).

But there’s a little bit of weirdness here. What is the idea of the ICommand that can be invoked via Commands[“ItemInvokedCommand”] and which uses the INavigationService to navigate to the ItemDetail view? Isn’t this ViewModel supposed to already be supporting that very same view? Are we navigating to ourselves?

No, this comes back to the idea that this ViewModel sits behind the ItemDetailPageView (where it will be navigated to and will load data) but it’s also going to be used in my other 2 views where the user will be able to tap it, invoke this command and drive navigation to the ItemDetailPageView. So, it’s serving more than one purpose which might point to it needing to be re-worked but I went with it for now.

Here’s the UI that goes alongside it taken from ItemDetailPageView.xaml which I dropped into a Views folder;

<Page
    x:Name="pageRoot"
    x:Class="PrismGridTemplate.Views.ItemDetailPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PrismGridTemplate"
    xmlns:data="using:PrismGridTemplate.Data"
    xmlns:common="using:PrismGridTemplate.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:p="using:Microsoft.Practices.Prism.StoreApps"
    xmlns:svcs="using:PrismGridTemplate.Services"
    mc:Ignorable="d"
    p:ViewModelLocator.AutoWireViewModel="True"
    d:DataContext="{Binding Groups[0].Items[0], Source={d:DesignData Source=/SampleData/SampleData.json,Type=svcs:DataService}}">

    <Page.Resources>
        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </Page.Resources>


    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid Grid.Row="1" x:Name="contentRegion" DataContext="{Binding Model}" d:DataContext="{Binding}">
            <TextBlock Margin="120,0,0,0" Text="{Binding Description}"/>
        </Grid>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding Commands[GoBackCommand]}" 
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.Name="Back"
                          AutomationProperties.AutomationId="BackButton"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" 
                       DataContext="{Binding Model}" d:DataContext="{Binding}"
                       Text="{Binding Title}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
    </Grid>
</Page>

Bits that I’d perhaps highlight on this page;

  1. The Page asks PRISM to auto-wire its ViewModel which it will do based on convention and wire up a new ItemDetailPageViewModel instance.
  2. The AppBarButton binds its command to Commands[GoBackCommand]
  3. Anything else is bound to properties on the Model at runtime.
  4. The Page is trying (and succeeding) in using VS/Blend’s design time data support by taking the SampleData.json file and asking the environment to load it up as a deserialized version of my DataService class and then indexing into the Groups/Items of that data to get to the 1st group’s 1st item. Note that at design time this item is a DataItem and will directly have properties like Title, Description whereas at runtime the DataContext here will be a ItemDetailPageViewModel which wraps the DataItem as a property called Model. Because of this, you’ll see pieces in the XAML where I play with the design-time DataContext to add/remove the Model part of the path as necessary.

That all works fine.

GroupDetailPageViewModel and GroupDetailPageView

Having looked at the ItemDetailPageViewModel the GroupDetailPageViewModel probably doesn’t come as much of a surprise. Here’s the code;

using Microsoft.Practices.Prism.StoreApps.Interfaces;
using PrismGridTemplate.Abstractions;
using PrismGridTemplate.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml.Navigation;

namespace PrismGridTemplate.ViewModels
{
    class GroupDetailPageViewModel : NavigationViewModelWrapsModel<DataGroup>
    {
        public GroupDetailPageViewModel(
            IDataService dataService, 
            INavigationService navService,
            Func<ItemDetailPageViewModel> itemDetailPageViewModelFactory)
            : base(navService)
        {
            this.dataService = dataService;
            this.itemDetailPageViewModelFactory = itemDetailPageViewModelFactory;
            base.AddCommand("GroupInvokedCommand", OnGroupInvoked);
        }
        void OnGroupInvoked()
        {
            base.Navigate("GroupDetail", this.Model.UniqueId);
        }
        public IEnumerable<ItemDetailPageViewModel> Items
        {
            get
            {
                if ((this.itemViewModels == null) && 
                    (this.Model != null) && (this.Model.Items != null))
                {
                    this.itemViewModels = this.Model.Items.Select(
                        model =>
                        {
                            ItemDetailPageViewModel viewModel = this.itemDetailPageViewModelFactory();
                            viewModel.Model = model;
                            return (viewModel);
                        }
                    );
                }
                return (this.itemViewModels);
            }
        }
        public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);

            string groupUniqueId = (string)navigationParameter;
            this.LoadDataAsync(groupUniqueId);
        }
        async Task LoadDataAsync(string groupUniqueId)
        {
            DataGroup group = await this.dataService.GetGroupAsync(groupUniqueId);
            this.Model = group;
            base.OnPropertyChanged("Items");
        }
        IEnumerable<ItemDetailPageViewModel> itemViewModels;
        IDataService dataService;
        Func<ItemDetailPageViewModel> itemDetailPageViewModelFactory;
    }
}

This ViewModel is being used to support 2 views. One is the GroupDetailsPage which displays a DataGroup and its DataItems but this ViewModel is also going to be used on the main page of the app.

In one mode of use, the view will be navigated to and it will use the underlying IDataService to load up the specific group that it has been passed as a navigation parameter. In the other mode of operation, this view model will be created and passed a Model and in that mode the UI will ask it to surface an ICommand (via Commands[“GroupInvokedCommand”]) which will navigate to the details page for that DataGroup.

Perhaps the only other “interesting” thing here is that this ViewModel has 2 different ways of surfacing the DataItems that below to the group. One way is via the Model.Items property which will surface up an enumerable set of DataItem and the other means is via the Items property which surfaces up an enumerable of ItemDetailPageViewModels wrapped around those models. That latter collection is the one which would be bound to by any UI that wanted to display DataItems with bindable commands to “invoke” and cause the app to navigate the item detail page for that item.

In order to create that Items property value this ViewModel needs to be able to instantiate a ItemDetailPageViewModel along with its injected dependencies so it takes a dependency on a Func<ItemDetailPageViewModel> in its constructor and it uses that in the Items property to lazily construct that “list” of ItemDetailPageViewModel over the top of the existing “list” of DataItem.

In terms of the UI that presents the GroupDetailPage;

<Page
    x:Name="pageRoot"
    x:Class="PrismGridTemplate.Views.GroupDetailPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PrismGridTemplate"
    xmlns:data="using:PrismGridTemplate.Data"
    xmlns:common="using:PrismGridTemplate.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:p="using:Microsoft.Practices.Prism.StoreApps"
    xmlns:svcs="using:PrismGridTemplate.Services"
    mc:Ignorable="d"
    p:ViewModelLocator.AutoWireViewModel="True"
    d:DataContext="{Binding Groups[0], Source={d:DesignData Source=/SampleData/SampleData.json, Type=svcs:DataService}}">

    <Page.Resources>
        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <!-- Collection of items displayed by this page -->
        <CollectionViewSource
            x:Name="itemsViewSource"
            Source="{Binding Items}"/>
    </Page.Resources>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Horizontal scrolling grid -->

        <GridView
            x:Name="itemGridView"
            AutomationProperties.AutomationId="ItemGridView"
            AutomationProperties.Name="Items In Group"
            TabIndex="1"
            Grid.RowSpan="2"
            Padding="120,126,120,50"
            ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
            SelectionMode="None"
            IsSwipeEnabled="false">
            <GridView.ItemTemplate>
                <DataTemplate>
                    <Button Command="{Binding Commands[ItemInvokedCommand]}" Template="{x:Null}">
                        <Grid Height="110" Width="480" Margin="10" 
                              DataContext="{Binding Model}"
                            d:DataContext="{Binding}">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}" Width="110" Height="110">
                                <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
                            </Border>
                            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
                                <TextBlock Text="{Binding Title}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap"/>
                                <TextBlock Text="{Binding Subtitle}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="NoWrap"/>
                                <TextBlock Text="{Binding Description}" Style="{StaticResource BodyTextBlockStyle}" MaxHeight="60"/>
                            </StackPanel>
                        </Grid>
                    </Button>
                </DataTemplate>
            </GridView.ItemTemplate>
            <GridView.Header>
                <StackPanel Width="480" Margin="0,4,14,0" DataContext="{Binding Model}" d:DataContext="{Binding}">
                    <TextBlock Text="{Binding Subtitle}" Margin="0,0,0,20" Style="{StaticResource SubheaderTextBlockStyle}" MaxHeight="60"/>
                    <Image Source="{Binding ImagePath}" Height="400" Margin="0,0,0,20" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
                    <TextBlock Text="{Binding Description}" Margin="0,0,0,0" Style="{StaticResource BodyTextBlockStyle}"/>
                </StackPanel>
            </GridView.Header>
            <GridView.ItemContainerStyle>
                <Style TargetType="FrameworkElement">
                    <Setter Property="Margin" Value="52,0,0,2"/>
                </Style>
            </GridView.ItemContainerStyle>
        </GridView>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding Commands[GoBackCommand]}" 
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.Name="Back"
                          AutomationProperties.AutomationId="BackButton"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock DataContext="{Binding Model}" d:DataContext="{Binding}" x:Name="pageTitle" Text="{Binding Title}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
    </Grid>
</Page>

The page is set up with its DataContext as either a GroupDetailPageViewModel instance or, at design time, the DataContext will be an instance of DataGroup pulled out of the data that comes from the sample .json file.

Either way, the CollectionViewSource will bind into the Items collection which, for the former will be some list of ItemDetailPageViewModel and for the latter will be some list of DataItem.

Because of that, you will see places further on in the XAML where I attempt to set DataContext and the d : DataContext differently because the bindings change (adding or removing a “Model” into the path) depending on which scenario it is.

It’s perhaps worth pointing out that the display of items is wrapped in a Button which is bound to Commands[ItemInvokedCommand] – this is part of the DataTemplate for the item template. The button is there to let me easily add an ICommand to be invoked.

It’s perhaps also worth pointing out that the sample data aspect of this doesn’t work. My attempt (line 55 or so) to change the DataContext at runtime/design time inside of a DataTemplate doesn’t work. It seems like there’s bug filed on this so I’m hopeful that it’ll get resolved prior to Visual Studio 2013 shipping.

I think that my setting up of the design time DataContext is fine but it’s hard to know until Visual Studio fixes that bug.

GroupedItemsPage.xaml and GroupedItemsPageViewModel

The last ViewModel follows the pattern of the previous two so there’s perhaps little new in there at this point;

using Microsoft.Practices.Prism.StoreApps.Interfaces;
using PrismGridTemplate.Abstractions;
using PrismGridTemplate.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml.Navigation;

namespace PrismGridTemplate.ViewModels
{
    class GroupedItemsPageViewModel :
        NavigationViewModel
    {
        public IEnumerable<GroupDetailPageViewModel> Groups
        {
            get
            {
                return (this.groups);
            }
            private set
            {
                base.SetProperty(ref this.groups, value);
            }
        }
        public GroupedItemsPageViewModel(IDataService dataService, INavigationService navService, 
            Func<GroupDetailPageViewModel> dataGroupViewModelFactory) : base(navService)
        {
            this.dataService = dataService;
            this.dataGroupViewModelFactory = dataGroupViewModelFactory;
        }
        public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);
            this.LoadDataAsync();
        }
        async Task LoadDataAsync()
        {
            IEnumerable<DataGroup> dataGroups = await this.dataService.GetGroupsAsync();
            this.Groups = dataGroups.Select(
                model =>
                {
                    GroupDetailPageViewModel viewModel = this.dataGroupViewModelFactory();
                    viewModel.Model = model;
                    return (viewModel);
                }
            );
        }
        Func<GroupDetailPageViewModel> dataGroupViewModelFactory;
        IEnumerable<GroupDetailPageViewModel> groups;
        IDataService dataService;
    }
}

In essence, as this first page in the app is navigated to, it will LoadDataAsync() using the underlying IDataService and for each DataGroup model instance that’s returned from the data service, this ViewModel manufactures a GroupDetailPageViewModel instance wrapped around that model and surfaces the resulting list in the Groups property ready for binding.

There’s nothing else to it. The view sitting on top of it is bound;

<Page
    x:Class="PrismGridTemplate.Views.GroupedItemsPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:PrismGridTemplate"
    xmlns:data="using:PrismGridTemplate.Data"
    xmlns:common="using:PrismGridTemplate.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:p="using:Microsoft.Practices.Prism.StoreApps"
    xmlns:svcs="using:PrismGridTemplate.Services"
    p:ViewModelLocator.AutoWireViewModel="True"
    mc:Ignorable="d">

    <Page.Resources>
        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <x:String x:Key="ChevronGlyph"></x:String>
        <CollectionViewSource
            x:Name="groupedItemsViewSource"
            Source="{Binding Groups}"
            IsSourceGrouped="true"
            ItemsPath="Items"
            d:Source="{Binding Groups, Source={d:DesignData Source=/SampleData/SampleData.json, Type=svcs:DataService}}"/>
    </Page.Resources>
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <GridView
            x:Name="itemGridView"
            AutomationProperties.AutomationId="ItemGridView"
            AutomationProperties.Name="Grouped Items"
            Grid.RowSpan="2"
            Padding="116,137,40,46"
            ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
            SelectionMode="None"
            IsSwipeEnabled="false"
            IsItemClickEnabled="True">
            <GridView.ItemTemplate>
                <DataTemplate>
                    <Button Command="{Binding Commands[ItemInvokedCommand]}" Template="{x:Null}">
                        <Grid HorizontalAlignment="Left" Width="250" Height="250" DataContext="{Binding Model}" d:DataContext="{Binding}" >
                            <Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
                                <Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
                            </Border>
                            <StackPanel VerticalAlignment="Bottom" Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
                                <TextBlock Text="{Binding Title}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextBlockStyle}" Height="60" Margin="15,0,15,0"/>
                                <TextBlock Text="{Binding Subtitle}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>
                            </StackPanel>
                        </Grid>
                    </Button>
                </DataTemplate>
            </GridView.ItemTemplate>
            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <ItemsWrapGrid GroupPadding="0,0,70,0"/>
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>
            <GridView.GroupStyle>
                <GroupStyle>
                    <GroupStyle.HeaderTemplate>
                        <DataTemplate>
                            <Grid Margin="1,0,0,6">
                                <Button Foreground="{StaticResource ApplicationHeaderForegroundThemeBrush}"
                                    AutomationProperties.Name="Group Title"
                                    Command="{Binding Commands[GroupInvokedCommand]}"
                                    Style="{StaticResource TextBlockButtonStyle}" >
                                    <StackPanel Orientation="Horizontal" DataContext="{Binding Model}" d:DataContext="{Binding}">
                                        <TextBlock Text="{Binding Title}" Margin="3,-7,10,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
                                        <TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-7,0,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
                                    </StackPanel>
                                </Button>
                            </Grid>
                        </DataTemplate>
                    </GroupStyle.HeaderTemplate>
                </GroupStyle>
            </GridView.GroupStyle>
        </GridView>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding Commands[GoBackCommand]}" 
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.Name="Back"
                          AutomationProperties.AutomationId="BackButton"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
    </Grid>
</Page>

in terms of this view, it tries to use a similar technique of the previous one of having a CollectionViewSource with a Source bound to a Groups property on different objects at runtime versus design-time. At runtime, this will be an instance of the GroupedItemsPageViewModel whereas at design time it will be an instance of the DataService class which I hacked ever so slightly to include a Groups property purely so that it would deserialize from the data stored in the SampleData.json file and serve this purpose of being the design time DataContext for this view.

I’d perhaps revisit that if I was taking this further or if I was doing things a little more from scratch.

Like the previous view, there are places where I need to “add” a property path of “Model” into some of the bindings by changing the runtime DataContext versus the design time DataContext and, like the previous view, this needs to be done inside of DataTemplates which means that I hit the same bug in Visual Studio 2013 Preview which is a shame as it messes up my design time and gives me a nasty error in the XAML editor (at design time, not build time);

image

and that’s the end of the ViewModels/Views supporting the 3 pages – there’s no code in any of the code-behind files for the 3 views other than a single call to InitializeComponent() in each case.

Boot-Strapping the App’s Startup

In terms of getting the application up and running, there’s a need to setup my IoC container and navigate the app to my first view. That’s made very simple by PRISM in that my App.xaml.cs simply looks like;

 

using Autofac;
using Microsoft.Practices.Prism.StoreApps;
using Microsoft.Practices.Prism.StoreApps.Interfaces;
using PrismGridTemplate.Abstractions;
using PrismGridTemplate.Services;
using PrismGridTemplate.ViewModels;
using System;
using Windows.ApplicationModel.Activation;

namespace PrismGridTemplate
{
    sealed partial class App : MvvmAppBase
    {
        IContainer container;

        protected override object Resolve(Type type)
        {
            return (container.Resolve(type));    
        }
        protected override void OnInitialize(IActivatedEventArgs args)
        {
            base.OnInitialize(args);

            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<DataService>().As<IDataService>().InstancePerLifetimeScope();
            builder.RegisterInstance(this.NavigationService).As<INavigationService>();
            builder.RegisterType<GroupedItemsPageViewModel>().AsSelf();
            builder.RegisterType<GroupDetailPageViewModel>().AsSelf();
            builder.RegisterType<ItemDetailPageViewModel>().AsSelf();
            this.container = builder.Build();
        }
        protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
        {
            this.NavigationService.Navigate("GroupedItems", null);            
        }
    }
}

The OnInitialize override sets up an Autofac container and adds in my IDataService, INavigationService and my 3 ViewModels into that container. The IDataService is told to instance itself in a “singleton”-like manner and the INavigationService is registered as an existing instance which PRISM has already created for me.

The Resolve override simply delegates creating things to the Autofac container and the OnLaunchApplication asks the INavigationService to navigate to the first view in the application.

That’s it – clean and simple.

Wrapping Up

I wanted to take the Grid template and see what it was like moving it across to sit on top of PRISM with a bit more binding and commanding than the original template had and I think that I managed that reasonably well here without too much pain.

I’m reasonably happy that at the end of the process (minus unit-tests) I have something that’s more clearly layered than the initial template but I did introduce quite a few new base classes along the way and picking up PRISM (or another framework like this) involves a bit of conceptual learning over and above the regular Visual Studio template approach.

I think ultimately that I’d prefer to see Visual Studio taking an approach that was closer to this kind of pattern than the mixture of bindings, code-behind and so on as, for me, I find that more confusing in terms of trying to figure out which piece of code is responsible for what.

Beyond that, some of the attempt here to use design-time data in Visual Studio isn’t working for me so if I wanted to get that working better I might have to take a slightly different approach and you could definitely argue that my use of d : DataContext and d : Source sprinkled in a few places throughout the XAML isn’t very maintainable – I should perhaps try and do that in a better way but I  was originally trying to duplicate the way that the design time data is loaded up in the Grid project as it ships.

I’ll perhaps post again on this topic but, for now, here’s the source that I’ve got to if you want to play around in it.