About the Author

Kevin is a Senior Software Engineer at Interknowlogy who moved from Germany to San Diego in beautiful Southern California in January 2012. He has switched from native C++ Developments to the .NET world in 2006 with a main focus on WPF. The release of ASP.NET MVC made him discover his passion for Web Application projects. Since the Windows 8 Customer Preview he enjoys exploring the new WinRT world whenever he finds time...

Session 4 of the WinRT Development Class – Async/Await, WinRT API, and Security

Thank you all for attending Session 4 of our WinRT Development Course. It was great to see you all understand, embrace and use the new WinRT API! J

Session Resources:

  • AsyncDemonstration.zip: Source code of the project I used to demonstrate the difference between synchronous and asynchronous code execution
  • DemoFinal.zip: Source code of the project we developed together. This application allows to take a picture from an attached webcam, save it in the Pictures Library and create diary entries.
  • Presentation.pptx: The slide deck
  • Session Recording
  • HomeworkFinal.zip: Sample implementation of the homework (please try to solve it on your own first!)

Please don’t forget about Danny’s upcoming session on Monday – Jan 28th! I will see you all again on February 4th!

Overview of sessions

The links below lead you to Meetup Events where you can RSVP. We look forward to seeing you at our next session!

1. Introductory Lecture (Nov 27th by Danny & Kevin)
2. Introduction to XAML and WinRT’s powerful Control Framework; (Dec 4th by Danny & Kevin Click here for the video recording)
3. Page-Navigation Model and Application Lifecycle (Jan 8th by Danny Click here for the video recording)
4. Fundamentals (Async/Await, WinRT API, Security) (Jan 15th by Kevin Click here for the video recording)
5. Settings and Search Contract (Jan 28th by Danny)
6. Share Contract (Feb 4th by Kevin)
7. Live Tiles and Background Tasks (March 18th by Kevin)
8. Orientation Handling and Proximity using Near Field Communication (NFC) (March 25th by Danny)
9. Introduction to ModelViewViewModel (MVVM) (April 8th by Danny)
10. InterKnowlogy’s WinRT MVVM Framework Session Part I/II(April 22nd by Kevin)
11. InterKnowlogy’s WinRT MVVM Framework Session Part II/II(May 6th by Danny)
12. Presentation of Hackathon Results + Certificate/Prize Giveaway(May 22nd by Danny and Kevin)

Impressions





Introduction to Windows 8 and WinRT – vNext OC Event Debrief

Last Tuesday – October 9th – I had the pleasure to introduce Windows 8, its most important new features, the details of the Windows Runtime (WinRT), .NET’s new role and WinRT’s limitations to a very engaged crowd at Kim Schmidt’s vNext UserGroup in Irvine, Orange County. You can find details and photos of the event here.

The event showed that – while there exists a lot of interest for Windows 8 in the Developer community – there is still a lot of confusion about Win8’s place and its technical details (in particular the distinction between WinRT and Win32).

In cooperation with Kim Schmidt, my coworker Danny Warren and I are hoping to provide clarification and to eliminate some of that confusion through a series of lectures we are going to hold over the next couple of months.
The details are not set in stone yet, but our goal is to introduce the development of Windows 8 (WinRT) apps and to explain how you can leverage Win8’s new features in your own application. This will include tutorials, in which we will show how to build the foundation for a sophisticated WinRT application (Page-Navigation, Application state restoring, Usage of the MVVM pattern etc.). Consequently no knowledge of Windows 8 is required.

This is the current outline of sessions we came up with (subject to change!):
(B: Beginner, I: Intermediate, A: Advanced)

Windows 8 Installation (VHD) – B
Hello Windows 8 and Introduction to Windows 8’s new Controls – B
Page and Navigation Model – B
Saving and Restoring Application States – I
Settings and Search Contracts – B
Share Contract – B
Live Tiles and Orientation Handling – I
Working with Background Tasks – A
MVVM Refresher – A
Windows 8 & MVVM – Introduction to IK’s WinRTFramework Session 1 – A
Windows 8 & MVVM – Introduction to IK’s WinRTFramework Session 2 – A
Windows 8 & MVVM – Introduction to IK’s WinRTFramework Session 3 – A

If you have requests for additional lectures, please let us know.

Kim Schmidt is still trying to find the perfect venue. It will most probably be in Orange County, though.
We are also trying to figure out how many of you guys are interested in joining these classes.
So if you are – please shoot me an Email!

Thank you

Some impressions (more can be found here):





SoCal Code Camp: WinRT Fundamentals

Thank you all for joining my session “WinRT Fundamentals” at the SoCal Code Camp in San Diego last Saturday, June 23rd 2012. (http://bit.ly/MwUUmn)

I uploaded the deck on slideshare.net: WinRT Fundamentals Slide Deck

Attached you find the sample projects for C#, C++ and JavaScript. If there is strong demand I’ll put my VB hat on and translate it to my – not quite favorite yet – language VB.

Sample Projects

Declarative approach to manage your Property Dependencies in a MVVM architecture

One pretty common scenario in MVVM architectures is that your ViewModel has several interdependent Properties.

Let’s consider the following example:

	public class Constants : Bindable
	{
		private int _factor;
		public int Factor
		{
			get { return _factor; }
			set { _factor = value; NotifyPropertyChanged(() => Factor); }
		}
	}


	public class Calculator : Bindable
	{
		private readonly Constants _constants;

		public Calculator(Constants constants)
		{
			_constants = constants;
		}

		private int _a;
		public int A
		{
			get { return _a; }
			set
			{
				_a = value;
				NotifyPropertyChanged(() => A);
			}
		}

		private int _b;
		public int B
		{
			get { return _b; }
			set
			{
				_b = value;
				NotifyPropertyChanged(() => B);
			}
		}

		public int Sum
		{
			get
			{
				return (A + B) * _constants.Factor;
			}
		}

		public int Div
		{
			get
			{
				return (B == 0 ? Int32.MaxValue : A / B) * _constants.Factor;
			}
		}

		public int Mul
		{
			get
			{
				return (A * B) * _constants.Factor;
			}
		}

		public int Sub
		{
			get
			{
				return (A - B) * _constants.Factor;
			}
		}

	}

As you can tell, we have a simple Calculator which does basic maths on the two integer Properties A and B and shows the result in the View. Sum, Sub, Mul and Div are evaluated on the fly. No setter is necessary.

The task is now to automatically reevaluate the Properties Sum, Sub, Mul and Div whenever A or B change. One common solution is to change Sum, Sub, Mul and Div to Getter/Setter Properties and explicitly set their values when A or B change:

		private int _a;
		public int A
		{
			get { return _a; }
			set
			{
				_a = value;
				NotifyPropertyChanged(() => A);

				Sum = (A + B) * _constants.Factor;
				Sub = (A - B) * _constants.Factor;
				Mul = (A * B) * _constants.Factor;
				Div = (B == 0 ? Int32.MaxValue : A / B) * _constants.Factor; ;
			}
		}

		private int _b;
		public int B
		{
			get { return _b; }
			set
			{
				_b = value;
				NotifyPropertyChanged(() => B);

				Sum = (A + B) * _constants.Factor;
				Sub = (A - B) * _constants.Factor;
				Mul = (A * B) * _constants.Factor;
				Div = (B == 0 ? Int32.MaxValue : A / B) * _constants.Factor;
			}
		}

		private int _sum;
		public int Sum
		{
			get { return _sum; }
			set
			{
				_sum = value;
				NotifyPropertyChanged(() => Sum);
			}
		}

		//Implementation of Sub, Mul and Div are analogous

This approach, however, has several draw downs:

  1. A and B now have to know, which properties depend on them. Whenever the calculation of Sum, Sub, Mul or Div changes we would have to remember to go back to all dependent Property setters and make sure they force the reevaluation of the property. This is not the desired behavior. A ViewModel only notifies all its observers that a certain Property has changed. The subscribers should then themselves decide how they want to react. This is the so called event/observer-pattern, which should allow us to fire events and forget, without having to bother about the subscribers.
  2. The Property Dependency is present in different spots:
    • The calculation itself by explicitly accessing the Properties it is dependent on
    • The setter of every single Property, the calculations dependent on, by forcing the reevaluation of the calculation
  3. The calculation logic is in every property setter, which influences the calculation output (this could be avoided by extracting another method which does the calculation)

My first step to avoid this problem was to call a single method in the constructor of the ViewModel, which registers all Property Dependencies:

		//...
		public Calculator(Constants constants)
		{
			_constants = constants;

			RegisterPropertyDependencies();
		}

		private void RegisterPropertyDependencies()
		{
			Property(() => Sum)
				.DependsOn(() => A)
					.AndOn(() => B)
					.AndOn(_constants, k => k.Factor);

			Property(() => Sub)
				.DependsOn(() => A)
					.AndOn(() => B)
					.AndOn(_constants, k => k.Factor);

			Property(() => Mul)
				.DependsOn(() => A)
					.AndOn(() => B)
					.AndOn(_constants, k => k.Factor);

			Property(() => Div)
				.DependsOn(() => A)
					.AndOn(() => B)
					.AndOn(_constants, k => k.Factor);
		}
		//...

The PropertyDependency Framework that I’ve introduced here is part of the underlying ViewModel base class and offers a declarative syntax to register all Property Dependencies in your ViewModel. The syntax is implemented using fluent interfaces.
The implementation hooks up to the PropertyChanged Events of all objects that expose the properties, the Property in question is dependent on. When it notices, that a dependent Property has changed, it fires the PropertyChanged Event for the dependent Property.

Example:

Property(() => Sum)
	.DependsOn(() => A)
		.AndOn(() => B)
		.AndOn(_constants, k => k.Factor);

The ViewModel subscribes to the PropertyChanged event of the _constants instance and waits for the Property “Factor” to change. In case it notices a change of that property, it automatically fires the PropertyChanged event for the local “Sum” Property. The same applies to the properties “A” and “B” (in this case it would subscribe to the PropertyChanged event of the this instance).

This approach has several advantages over the previous one:
1. The properties A and B can fire and forget. They don’t have to know about all Properties that are dependent on them.
2. As a consequence of 1., whenever we change the logic of one of the calculated Properties, we only have to go to one specific spot – the Method RegisterPropertyDependencies – and modify the registered PropertyDependency.
3. The Properties Sum, Sub, Mul and Div can simply be Getter Properties that contain the calculation logic. No Setter, which fires the PropertyChanged notification, is required. The logic is where it should be: At the Property, that represents the calculation result.

Looking at this implementation I was still not completely satisfied; mainly, because the Property Dependency is still visible in two totally different spots:
1. The RegisterPropertyDependencies method explicitly registers, which Properties a certain Property depends on.
2. The Getter of the calculation properties implicitly describe the Dependency by actually using their values during the calculation.

So my goal was to come up with a cost-efficient solution that allows me to have the declarative and explicit PropertyDependency registration at the same spot, where my Property is.
First I tried to use C# Attributes. However, they are simply too limited. You cannot use my so beloved Expression Syntax to retrieve the Properties’ names. You also cannot refer to external objects (in our case, the _constants instance), which the calculation depends on.

Here is the final solution I came up with:

		//....
		private int _a;
		public int A
		{
			get { return _a; }
			set
			{
				_a = value;
				NotifyPropertyChanged( () => A );
			}
		}

		private int _b;
		public int B
		{
			get { return _b; }
			set
			{
				_b = value;
				NotifyPropertyChanged( () => B );
			}
		}

		public int Sum
		{
			get
			{
				Property(() => Sum)
					.Depends(p => p.On(() => A)
								.AndOn(() => B)
								.AndOn(_constants, k => k.Factor));
								
								

				return (A + B) * _constants.Factor;
			}
		}

		public int Div
		{
			get
			{
				Property(() => Div)
					.Depends(p => p.On(() => A)
								.AndOn(() => B)
								.AndOn(_constants, k => k.Factor));
				
				return (B == 0 ? Int32.MaxValue : A / B) * _constants.Factor;
			}
		}

		public int Mul
		{
			get
			{
				Property(() => Mul)
					.Depends(p => p.On(() => A)
								.AndOn(() => B)
								.AndOn(_constants, k => k.Factor));

				return (A * B) * _constants.Factor;
			}
		}

		public int Sub
		{
			get
			{
				Property(() => Sub)
					.Depends(p => p.On(() => A)
								.AndOn(() => B)
								.AndOn(_constants, k => k.Factor));

				return (A - B) * _constants.Factor;
			}
		}
		//....

As you can see, the Property Registration is in the very same spot as the calculation logic.
No switching back and forth between the logic and the explicit Dependency Registration is necessary anymore. When you change the property implementation, you see immediately that there exists a PropertyDependency Registration and you know, that you have to modify it as well.
Furthermore, the PropertyDependency is registered the first time you access the Property. That means, if you show that Property in the UI and bind to it, the registration will automatically be done for you on the fly. As a consequence, if you have an orphan Property that no one uses, no unnecessary registration would take place.

The observing reader might have noticed that the syntax changed a bit.
It changed from

			Property(() => Sum)
				.DependsOn(() => A)
					.AndOn(() => B)
					.AndOn(_constants, k => k.Factor);

to

				Property(() => Sum)
					.Depends(p => p.On(() => A)
								.AndOn(() => B)
								.AndOn(_constants, k => k.Factor));

The Depends method now expects a Action delegate.
I introduced this change, because the usage of Expressions in C# are rather costly. The former solution would always evaluate all four Expressions (() => Sum, () => A, () => B, () => Factor).
The final solution, in contrast, only evaluates the very first Expression that points to the dependent Property. In case it notices that the Dependency has already been registered, it does nothing. This causes the other three Expressions to be evaluated only the very first time the Getter is accessed.

Important notice:
You might think that this pattern is too costly to use. However, it is just as “cheap” as the usage of the NotifyPropertyChanged version, which uses Expressions to extract the Property’s names.
(Evaluating the Sum property 10.000 times took 57 milliseconds on my machine.)

I am not going to explain the PropertyDependency registration syntax implementation in detail as I’ve already talked about the concept. If you are curious or want to use it in your own project, just download the attached sample project. I’ll be happy to answer all arising questions :-)

Download sample project

Windows 8 Developer Event – LA

On Monday, May 23rd, I had the chance to talk about Interknowlogy and some of our latest Developments at Microsofts Windows 8 Developer Event in Los Angeles.
In particular, I spoke about our “Personal Rehab Trainer” which enables patients to practice their rehab exercises at home instead of having to go to rehab sessions. If you want to find out how this Rehab Trainer cuts costs, how it provides patients with better service and what all this has to do with WinRT and Windows 8, make sure to check out the recorded event at Windows 8 Developer Event. My presentation can be found between 1h:44m and 1h:51m.

I met a ton of great and really inspiring Microsoft Developer Evangelists who spoke about the following topics:

  • Windows 8 from the Consumer’s Perspective
    (by Jerry Nixon)
  • Windows 8 Store and Developer Opportunity
    (by Michael Johnson)
  • Windows 8 Hello World
    (by Alice Pang (Make sure to register for her Windows 8 Developer Camp))
  • Visual Studio 11
    (by Jeremy Foster)
  • Windows 8 Core Capabilities & Interactions
    (by Matt Harrington)
  • Metro Design Language
    (by Jeremy Foster)
  • Building Metro Apps with JavaScript
    (by Michael Palermo)
  • Building Metro Apps with XAML
    (by Jerry Nixon)
Thanks to the pictures Justine Li took from the event I can provide you with a few impressions of the event!

MS Evangelists

The Audience

The Audience the day before

Me speaking

Me giving autographs 😉

The demo on the demo table

Our VIP booth

Thank you, Microsoft, for this great event!

How to create a WinRT WRL C++ Component from scratch that can be consumed by .NET components

If you have to develop Hybrid WinRT Components that expose both COM and WinRT components you have to either write bare metal C++ or use the new Windows Runtime Template Library, which supports you in dealing with COM. More about WRL can be found at http://msdn.microsoft.com/en-us/library/hh438466(v=vs.110).aspx

Microsoft provided a few sample WRL C++ Projects. However they did not include a WRL C++ Project Template in the Visual Studio 2011 Consumer Preview. I reverse-engineered the Sample Projects to find out what is necessary in order to develop a WRL Component from scratch as I didn’t want to use the available Sample Projects as my Project foundation. I also modified the Project in a way that the resulting DLL contains not only the COM component itself but also the proxy/stub implementation.

These are the steps I came up with:

  1. Create a new “Visual Studio C++ – Windows Metro Style – WinRT Component DLL” Project. I called it “WRLTemplate”.
    (Please make sure that the solution folder does not contain any white spaces.)
  2. Delete the automatically created WinRTComponent.cpp/h files.
  3. Add Module-Definition File “WRLTemplate.def”

    Set the content to the following, describing all exported methods of the DLL

    EXPORTS
    DllCanUnloadNow         PRIVATE
    DllGetActivationFactory PRIVATE
    DllGetClassObject       PRIVATE
    
  4. Add the MIDL File “WRLTemplate.idl”. The content will be added later, when we define the modules’ functionality.
  5. Open the Project Settings from the Solution Exporer and adjust the following settings
  6. C/C++ General Tab
     
    • Additional Include Directories: $(IntermediateOutputPath);$(ProjectDir);$(OutDir);%(AdditionalIncludeDirectories)
    • Consume Windows Runtime Extension: No
  7. C/C++ Preprocessor Tab

    • Preprocessor Definitions:
      ENTRY_PREFIX=Prx;REGISTER_PROXY_DLL;PROXY_CLSID_IS={ 0x24352b56, 0xa2ea, 0x4327, { 0xba, 0xcb, 0xe9, 0xea, 0x33, 0x8d, 0xb3, 0x9d } };_WINRT_DLL;WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)

      Those are mainly necessary for the Proxy/Stub, which will be part of the same component. ENTRY_PREFIX defines the Prefix of the generated exported DLL entry methods of the Proxy/Stub and is necessary to avoid naming conflicts

  8. Linker – Input Tab.
    Add rpcrt4.lib as an Additional Dependency
  9. MIDL General Tab
    • Additional Include Directories: $(LibraryWPath);$(ProjectDir);%(AdditionalIncludeDirectories)
    • Additional Metadata Directories: $(LibraryWPath);%(AdditionalMedataDirectories)
  10. MIDL Output Tab
    • Metadata File:$(OutDir)%(Filename).winmd
    • Header File:%(Filename).h
    • IID File:%(Filename)_i.c
    • Proxy File:%(Filename)_p.c
  11. MIDL Command Line
    • Additional Options: /ns_prefix
      This will add the “ABI” Prefix to the generated namespaces in the proxy/stub files.
  12. Custom Build Step General Tab

    • Command Line: mdmerge -partial -i “$(OutDir).” -o “$(OutDir)Output” -metadata_dir “$(WindowsSDK_MetadataPath)” && copy /y $(OutDir)Output\* $(OutDir)
    • Outputs: $(OutDir)%(TargetName).winmd
    • Execute After: Midl
  13. Add common includes to the generated pch.h file
    #pragma once
    
    #include <SDKDDKVer.h>
    
    #define WIN32_LEAN_AND_MEAN
    
    //Windows Header Files:
    #include <windows.h>
    #include <assert.h>
    #include <tchar.h>
    #include <Strsafe.h>
    
    //WRL
    #include <wrl\client.h>
    #include <wrl\implements.h>
    #include <wrl\ftm.h>
    #include <wrl\event.h> 
    #include <wrl\wrappers\corewrappers.h>
    #include <wrl\module.h>
    
  14. Set the WRLTemplate.idl content, which describes what functionality your Component will expose
    import "Windows.Foundation.idl";
    
    #include <sdkddkver.h>
    
    namespace WRLTemplate
    {
    	runtimeclass MyComponent;
    
    	[version(NTDDI_WIN8), uuid(9789F754-FF6E-4AB5-9868-C1430D294A1B)]
    	interface IMyCallbackProvider : IInspectable
    	{
    		HRESULT Call([in] HSTRING callbackValue);
    	}
    
    
    	[version(NTDDI_WIN8), uuid(1589F754-FF6E-4AB5-9868-C1430D294A1B), exclusiveto(MyComponent)]
    	interface IMyComponent : IInspectable
    	{
    		HRESULT Foo([in] HSTRING someString, [in]IMyCallbackProvider* myCallback);
    	}
    
    
    	[version(NTDDI_WIN8), activatable(NTDDI_WIN8)]
    	runtimeclass MyComponent
    	{
    		[default] interface IMyComponent;
    	}
    }
    
  15. Add MyComponent.h
    #include "pch.h"
    #include "WRLTemplate.h" //Generated by the MIDL compiler
    
    using namespace Microsoft::WRL;
    using namespace ABI::WRLTemplate;
    
    namespace WRLTemplate
    {
    	class DECLSPEC_UUID("A23CF192-F869-4DFE-9477-4045A73CA2AB") MyComponent : 
    		public RuntimeClass<
    			// WRL				
    			RuntimeClassFlags<RuntimeClassType::WinRtClassicComMix>,
    			FtmBase	,
    			// Custom
    			IMyComponent>
    	{
    		InspectableClass(RuntimeClass_WRLTemplate_MyComponent, TrustLevel::BaseTrust);
    
    	public:	
    		// IMyComponent
    		IFACEMETHOD (Foo)(HSTRING someString, IMyCallbackProvider* myCallback);
    	};
    }
    
  16. Add MyComponent.cpp
    #include "pch.h"
    #include "MyComponent.h"
    
    namespace WRLTemplate
    {
    	IFACEMETHODIMP MyComponent::Foo (HSTRING someString, IMyCallbackProvider* myCallback)
    	{
    		myCallback->Call(someString);
    
    		return S_OK;
    	}
    }
    
  17. Add WRLTemplate.cpp
    #include "pch.h"
    #include "MyComponent.h"
    
    // COM proxy/stubs
    extern "C" HRESULT WINAPI PrxDllGetClassObject(REFCLSID, REFIID, _Deref_out_ LPVOID*);
    extern "C" BOOL WINAPI PrxDllMain(_In_opt_ HINSTANCE, DWORD, _In_opt_ LPVOID);
    extern "C" HRESULT WINAPI PrxDllCanUnloadNow();
    
    
    BOOL WINAPI DllMain( __in_opt HINSTANCE hInstance, __in DWORD dwReason, __in_opt LPVOID lpReserved )
    {
        if( DLL_PROCESS_ATTACH == dwReason )
        {
    
            //
            //  Don't need per-thread callbacks
            //
            DisableThreadLibraryCalls( hInstance );
    
            Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule().Create();
        }
        else if( DLL_PROCESS_DETACH == dwReason )
        {
            Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule().Terminate();
        }
    
        PrxDllMain( hInstance, dwReason, lpReserved );
    
        return TRUE;
    }
    
    STDAPI DllGetActivationFactory(_In_ HSTRING activatibleClassId, _COM_Outptr_ IActivationFactory** factory)
    {
        auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
        return module.GetActivationFactory(activatibleClassId, factory);
    }
    
    STDAPI DllCanUnloadNow()
    {
        auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
        return module.Terminate() ? S_OK : S_FALSE;
    }
    
    STDAPI DllGetClassObject( __in REFCLSID rclsid, __in REFIID riid, __deref_out LPVOID FAR* ppv )
    {
        auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
        HRESULT hr = module.GetClassObject( rclsid, riid, ppv );
        if (FAILED(hr))
        {
            hr = PrxDllGetClassObject( rclsid, riid, ppv );
        }
        return hr;
    }
    
    namespace WRLTemplate {
    	ActivatableClass(MyComponent)
    }
    
  18. Try to compile. It will fail.
  19. Add the Proxy Stub files to the solution: Select “Show all files” in the Solution explorer and include dlldata.c + WRLTemplate_i.c, WRLTemplate_p.c to the solution
  20. Deactivate the usage of Precompiled Headers on these 3 files by going to their properties (right click and select Properties) and changing the Precompiled Header to Not Using Precompiled Headers
  21. Recompile – should work fine. Now use the Component from a C# project
  22. Create a new C# project

  23. Add Reference to the winmd file. Make sure you do NOT select WRLTemplate.winmd from the Output folder. Although they are binary equal you will get an exception at runtime, telling you that the Type is not registered.
  24. Instantiate the COM component and use it for example in your BlanPages’ OnNavigatedTo-Method
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                var comp = new MyComponent();
                var callback = new Callback();
    
                const string testString = "Test";
                comp.Foo(testString, callback);
    
                Debug.Assert(callback.ReceivedValue == testString);
            }
    
            class Callback : IMyCallbackProvider
            {
                public string ReceivedValue { get; set; }
    
                public void Call(string callbackValue)
                {
                    ReceivedValue = callbackValue;
                }
            }
    
  25.  If you followed all steps correctly, the solution should compile and work as expected :-)

If you have specific questions regarding any of these settings please post a comment and I will get back to you.
I attached the example solution (WRLTemplate). Please note that you will have to compile the project “WRLTemplate” and again reference its WRLTemplate.winmd afterwards in the ConsumerApp project.

How to REALLY consume a WinRT object with the WRL

Microsoft published an example that supposedly demonstrates how to consume a WinRT object with the WRL at How to Create and Consume an Object.

However, if you’ve tried that example you probably noticed that it simply does not work as the following snippet returns E_INVALIDARG.

ComPtr<IActivationFactory> uriActivationFactory;
HRESULT hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Foundation_Uri).Get(), &uriActivationFactory);

The problem is, that HString::MakeReference(RuntimeClass_Windows_Foundation_Uri) does not return a valid HStringReference-instance.

Instead, you should create a HStringReference-object using its constructor and pass that instance to the GetActivationFactory call:

ComPtr<IActivationFactory> uriActivationFactory;
HStringReference runtimeClassUri(RuntimeClass_Windows_Foundation_Uri);
HRESULT hr = GetActivationFactory(runtimeClassUri.Get(), &uriActivationFactory);

Now, the call should return S_OK and you’ll have a valid uriActivationFactory that you can work with.

How to reference C++ WRL Components from a .NET project

Whenever your Windows Runtime (WinRT) component has to implement COM interfaces as well as WinRT interfaces, Microsoft advises you to use the Windows Runtime Template Library (WRL), because the C++/CX – which otherwise is recommended to develop WinRT components – does not allow to implement COM interfaces.

However, if you are trying to use some of Microsoft’s publicly available samples from a .NET component, you might run into trouble. The problem is, that the winmd file that gets generated when you compile a WRL C++ Component – by default – does NOT reference the “Windows.winmd”-file, which provides the meta data for the WinRT API as a whole. Instead, it references only the particular winmd-files that describe partial areas of the WinRT API. These partial WinRT descriptions can all be found at a location similar to “C:\Windows\System32\WinMetadata”, whereas the complete WinRT API can be found at “C:\Program Files (x86)\Windows Kits\8.0\Windows Metadata\Windows.winmd”.

To demonstrate this problem I am referring to Microsoft’s “Real-time communication sample” that can be found at http://code.msdn.microsoft.com/windowsapps/Simple-Communication-Sample-eac73290. If you try to consume the “Microsoft.Samples.SimpleCommunication” component, which is part of the solution, from a Metro-style based C# application, you will have to add a reference to the components winmd-file (“Microsoft.Samples.SimpleCommunication.winmd”). Your C# application will still work fine. However, try to instantiate a class such as StspMediaSink next:

Microsoft.Samples.SimpleCommunication.StspMediaSink k = new Microsoft.Samples.SimpleCommunication.StspMediaSink();

This should produce the following error at compile time:
The type 'Windows.Media.IMediaExtension' is defined in an assembly that is not referenced. You must add a reference to assembly 'Windows.Media, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime'.

Metro-style based C# applications by default reference the WinRT API as a whole. This means that your project references the “Windows.winmd”-file. The problem now is, that the compiler is not smart enough to recognize, that the Windows.Media.IMediaExtension-interface, which is implemented by the StspMediaSink-class, is already defined in the referenced “Windows.winmd”-file. Instead it wants you to add a reference to the same “Assembly”.

You cannot simply go ahead and add a reference to the “Windows.Media.winmd”-file as requested. If you added a reference to Windows.Media.winmd the compiler would complain about ambiguous references to Windows.Media.IMediaExtension. Instead we have to modify the C++ Microsoft.Samples.SimpleCommunication-project in a way that it does not reference the “Windows.Media.winmd”-file anymore, but instead the “Windows.winmd”-file.

This can be achieved by adding the following custom build step to the C++ project:

Command Line: mdmerge -partial -i “$(OutDir).” -o “$(OutDir)Output” -metadata_dir “$(WindowsSDK_MetadataPath)” && copy /y $(OutDir)Output\* $(OutDir)
Outputs: $(OutDir)%(TargetName).winmd
Execute After: Midl

If you recompile the component now, you should be able to reference and consume it from your C# component. If you disassemble the component’s winmd-file, you will notice that it now references “Windows.winmd” and not the “Windows.Media.winmd”-file anymore.

In a future blog post I am going to describe how you can create your own WRL C++ project from scratch as Visual Studio 2011 currently does not ship a project template, unfortunately.