If you tried the Win8 Developer Preview and built WinRT components (native or managed) you noticed the .winmd files. The name stands for Windows Meta Data and the format of these files is the same used by the .NET framework for the CLI, i.e. ECMA-335. That means you can actually read these files with a tool such as ILDASM or Reflector, or of course, through .NET Reflection.

If you look in C:\Windows\System32\WinMetadata folder you’ll find the WinMD files for the Windows Runtime. You can browse the content of these files with one of the aforementioned disassemblers.

Here are two dummy WinRT components, one developed in C++/CX and one in C#.

Native WinRT component in C++/CX Managed WinRT component in C#
namespace WinRTNativeComponent
{
    public ref class MyWinRTComponent sealed
    {
        int _id;
		String^ _name;

    public:
		MyWinRTComponent () {}
		~MyWinRTComponent () {}

        property int Id
        {
            int get() { return _id; }
            void set(int value) { _id = value; }
        }

		property String^ Name
		{
			String^ get() {return _name;}
			void set(String^ value) { _name= value; }
		}

        bool Update(int id, String^ name)
		{
			{
				if(_id == id)
				{
					_name = name;
					return true;
				}

				return false;
			}
		}
    };
}
namespace WinRTManagedComponent
{
    public sealed class MyWinRTComponent
    {
        public int Id { get; set; }
        public string Name { get; set; }

        bool Update(int id, string name)
        {
            if (Id == id)
            {
                Name = name;
                return true;
            }

            return false;
        }
    }
}

In the case of the native component, the output includes a DLL and a WINMD file (and of course a PDB file). In the case of the managed component, the output is either a DLL only or a WINMD only (plus the associated PDB file), depending on the Output type as defined in the project properties. If the type is Class Library the output is a DLL; this is enough if your component is supposed to be consumed from a managed language. However, if the component should be consumed from C++/CX or Javascript, then the project type must be set to WinMD File. In this case the DLL is replaced by a WinMD file, that contains, at least in the current version, both the matadata (as implied by the name) and the implementation.

Native WinRT component in C++/CX Managed WinRT component in C#

It should be possible to use reflection with winmd files. However, the reflection capabilities of .NET 4.5 in this developer preview seem to be very limited. The only available Load method in the Assembly class is

public static Assembly Load(AssemblyName assemblyRef);

Trying to load the winmd file fails with a FailLoadException with the message “Could not load file or assembly ‘Winmdreflection, ContentType=WindowsRuntime’ or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0×80131515)”.

try
{
    var assembly = Assembly.Load(
        new AssemblyName()
        {
            Name = "WinRTManagedComponent",
            ContentType = AssemblyContentType.WindowsRuntime
        });
}
catch (Exception ex)
{
}

It is possible though to read information for the types described in an winmd file in native code using the IMetaDataImport/IMetaDataImport2 COM interfaces. You can find an example here. But this has the drawback that you have to instantiate an object first and then query for its type information.

To use a Windows Runtime component in a Metro application (managed or native) you have to add a reference to it. That is pretty straight forward. In the following example I’m adding a reference in a C++ Metro application to the two WinRT components, one native and one managed, shown earlier. To do this, you can go to the project’s property page and open the Common Properties > Frameworks and References page, or use the References command from the project’s context menu which opens that page directly. You can add a reference to a project from the same solution, to a Windows component or you can browse for the winmd file.

Having done that you can instantiate the WinRT components.

auto obj1 = ref new WinRTManagedComponent::MyWinRTComponent();
obj1->Id = 1;
obj1->Name = L"marius";

auto obj2 = ref new WinRTNativeComponent::MyWinRTComponent();
obj2->Id = 1;
obj2->Name = L"marius";
, , , , , , , Hits for this post: 9721 .

Not long ago I ran into a COM interop problem that was a bit tricky to fix. So I’m sharing the problem and the solution here in case others encounter the same problem.

I had this native in-proc COM server that initially was built only for x86. It was used in a native MFC application as well as a C# Windows Forms application, where it was added as a COM reference. Both worked nicely. But then I needed to port the MFC app to the x64 platform, so I had to do the same with the in-proc COM server. They both worked correctly, but the managed app, which had to be available also both as 64-bit and 32-bit (even on 64-bit machines), was broken. Eventually I traced the problem to some COM method calls which were a bit atypical, because the arguments to the methods were not COM “native” types, but custom structures.

These structures looked like this:

[uuid(6F13C84D-0E01-48cd-BFD4-F7071A32B49F)] struct S
{
      long a;
      BSTR b;
      long c;
      BSTR d;
      long e;
      BSTR f;
      BSTR g;
      BSTR h;
      BSTR i;
      long j;
      BSTR k;
      long l;
      BSTR m;
      long n;
};

and the COM method signature:

[id(42)] HRESULT GetListOfStructs(SAFEARRAY(struct S)* arrRes);

When you add a COM reference to a .NET assembly, Visual Studio runs tlbimp.exe to generate a .NET assembly with equivalent definitions to the type definitions found in the COM type library. This interop assembly is used to access the COM server. It contains Runtime Callable Wrappers that bridge the two worlds together. By default, the interop assembly, generated in the project’s output folder, is called Interop.<comname>Lib.dll. For instance if the COM server is called NativeCOMServer, the interop assembly is called Interop.NativeCOMServerLib.dll.

The wrapper that was generated in the interop assembly had the following signature for the aforementioned method:

[DispId(42)]
void GetListOfStructs(ref Array arrRes);

and therefore used like this:

System.Array result = null;
obj.GetListOfStructs(ref result);

The call was performed correctly, the native code was executing, but as soon as it was returning an access violation exception was occurring. Thanks to Hans Passant I figured the problem was rooted in the way Visual Studio generates the interop assembly. The generated RCW didn’t know how to handle the custom structure correctly. Probably different padding on the two sides generated the access violation.

The trick was to generate the interop assembly directly, as a custom build step in the COM server project, and include it as an assembly reference in the managed project. Here are the commands for the custom build (must to make sure you have the correct path to the 32-bit and the 64-bit version of tlbimp.exe):

\TlbImp.exe $(TargetPath) /out:$(TargetDir)\NativeCOMLib.Interop.dll /primary  /keyfile:mykey.snk /machine:x86
\TlbImp.exe $(TargetPath) /out:$(TargetDir)\NativeCOMLib.Interop.dll /primary  /keyfile:mykey.snk /machine:x64

The result was a wrapper with methods like this:

[DispId(42)]
void GetListOfStructs(ref S[] arrRes);

which of course had to be called like this:

S[] result = null;
obj.GetListOfStructs(ref result);

To include either one or the other in the C# project I had to manually change the project file, since Visual Studio does not know conditional references, a feature available in MSBuild. I didn’t build the managed app for Any CPU because it had to be able to run as 32-bit on 64-bit machines, so I had two configurations, one for x86 and one fore x64.

    <Reference Condition=" '$(Platform)' == 'x86' " Include="NativeCOMServer.Interop,
               Version=1.0.0.0, Culture=neutral, PublicKeyToken=f5b9312191a42d52, processorArchitecture=x86">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\Bin\NativeCOMServer.Interop.dll</HintPath>
    </Reference>
    <Reference Condition=" '$(Platform)' == 'x64' " Include="NativeCOMServer.Interop,
               Version=1.0.0.0, Culture=neutral, PublicKeyToken=f5b9312191a42d52, processorArchitecture=x64">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\Bin64\NativeCOMServer.Interop.dll</HintPath>
    </Reference>

But this time the wrappers were able to bridge the call and everything worked smoothly.

The lesson learned is that when you have COM custom structures you should not rely on the way Visual Studio generates the interop assembly. You should build the interop explicitly (maybe as a custom build step, like I did) and include it as an assembly reference to your managed project.

, , , , , , Hits for this post: 8096 .

Partial classes are finally available to C++. Sort of. It’s not part of the new C++11 standard, it’s part of the C++/CX language developed by Microsoft for targeting WinRT on Windows 8.

Partial classes mean that you can define a class spanned across several files. Why is this great? Because it allows developers and automatic code generator tools (such as designers) to edit parts of the same class without interfering one with another. WinRT allows C++ developers to write UI in XAML. This could not have been possible without the support for partial classes.

Partial classes:

  • are available only for ref classes; native classes are not supported
  • are introduced with the partial keyword in all definitions but one

Here is an example:

// foo.private.h
#pragma once

partial ref class foo // <- here the partial keyword is used
{
private:
   int _id;
   Platform::String^ _name;
};
// foo.public.h
#pragma once
#include "foo.private.h"

ref class foo // <- partial keyword is not used here
{
public:
   int GetId();
   Platform::String^ GetName();
};
// foo.cpp
#include "pch.h"
#include "foo.public.h"

int foo::GetId() {return _id;}
Platform::String^ foo::GetName {return _name;}

What happens when you add a new page to a C++ Metro style application? The wizard generates three files: a XAML file and a header and cpp file as the code behind. Let's say the page is called MainPage. In this case the three files are MainPage.xaml (code below is a dummy example), MainPage.xaml.h and MainPage.xaml.cpp.

<UserControl x:Class="DemoApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="768" d:DesignWidth="1366">

    <StackPanel Name="firstPanel">
        <Button Name="firstButon" />
    </StackPanel>

</UserControl>
//
// MainPage.xaml.h
// Declaration of the MainPage.xaml class.
//

#pragma once

#include "pch.h"
#include "MainPage.g.h"

namespace DemoApp
{
   public ref class MainPage
   {
      public:
         MainPage();
         ~MainPage();
   };
}
//
// MainPage.xaml.cpp
// Implementation of the MainPage.xaml class.
//

#include "pch.h"
#include "MainPage.xaml.h"

using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Data;
using namespace DemoApp;

MainPage::MainPage()
{
   InitializeComponent();
}

MainPage::~MainPage()
{
}

You can notice that the objects firstPanel and firstButton are not defined in the header for MainPage and second, MainPage.xaml.h includes MainPage.g.h. So what is this? This is a designer generated file, which together with MainPage.g.cpp completes the definition of the MainPage ref class. These files are not generated until you start a build. After you do that you can find them in the output folder (Debug or Release for instance). This is how they look:

#pragma once
//------------------------------------------------------------------------------
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
//------------------------------------------------------------------------------

namespace Windows {
    namespace UI {
        namespace Xaml {
            namespace Controls {
                ref class StackPanel;
                ref class Button;
            }
        }
    }
}

namespace DemoApp
{
    partial ref class MainPage : public Windows::UI::Xaml::Controls::UserControl,
                                                     public Windows::UI::Xaml::Markup::IComponentConnector
    {
    public:
        void InitializeComponent();
        void Connect(int connectionId, Platform::Object^ pTarget);

    private:
        Windows::UI::Xaml::Controls::StackPanel^ firstPanel;
        Windows::UI::Xaml::Controls::Button^ firstButon;
    };
}
//------------------------------------------------------------------------------
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
//------------------------------------------------------------------------------
#include "pch.h"

#include "MainPage.xaml.h"

using namespace Windows::Foundation;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Markup;
using namespace MyDemoApplication1;

void MainPage::InitializeComponent()
{
    // Call LoadComponent on ms-resource://DemoApp/Files/MainPage.xaml
    Windows::UI::Xaml::Application::LoadComponent(this, ref new Windows::Foundation::Uri("ms-resource://DemoApp/Files/MainPage.xaml"));

    // Get the StackPanel named 'firstPanel'
    firstPanel = safe_cast<Windows::UI::Xaml::Controls::StackPanel^>(static_cast<IFrameworkElement^>(this)->FindName("firstPanel"));

    // Get the Button named 'firstButon'
    firstButon = safe_cast<Windows::UI::Xaml::Controls::Button^>(static_cast<IFrameworkElement^>(this)->FindName("firstButon"));

}

void MainPage::Connect(int connectionId, Platform::Object^ pTarget)
{
}

The following image illustrates the grouping of these files:

MainPage.xaml is a XAML files, which can be edited both by the designer or manually by the developer (basically with the designer is still the developer that models the UI). The other files are C++/CX files. MainPage.xaml.h and MainPage.xaml.cpp are the files the developer writes, while MainPage.g.h and MainPage.g.cpp are edited by the designer. Do not modify the code in these files, because you could either mess up the designer, or all your changes would get lost when the file is regenerated.

, , , , , , Hits for this post: 10035 .

Earlier this year I published a series of articles on Codeguru about WP7 Silverlight development. Later on I have remastered them a bit and merged them together with a couple of articles by Vipul Patel into a small eBook that was published on internet.com, called Windows Phone 7 Quick Start Developer Guide. There is also a ZIP archive with the source code for all the sample projects presented throughout the book. While you can still find the articles online on the site, I recommend the eBook as a better learning material as it puts the various topics together.

The eBook is intended for developers with a fair knowledge of .NET programming that want to start developing Silverlight applications for Windows Phone 7. However, it is not a complete guide to Silverlight development for Windows Phone 7. The eBook covers a smaller set of Silverlight topics that is intended to prepare the reader for the most common challenges a Windows Phone 7 developer faces.

Here is the table of contents of the eBook.

  • Preface
  • Where to Start
  • Creating a Simple Windows Phone Application: “Hello World!”
  • The Application Bar
  • Page Navigation
  • Tombstoning and Data Persistence
  • Pivot and Panorama
  • Launchers and Choosers
  • Touch
  • Using Bing Maps Control
  • App Hub: Application Submission Walkthrough
  • References
  • About the Authors

Download the eBook from here.

, , , Hits for this post: 4879 .

Last year I posted a small MFC application on my blog, called Colors Game, about covering with a single color a grid initially colored in six colors. It wasn’t a big deal of an application, but it was fun and recently I decided to write a WPF version of that MFC game. This is the result:

The game is about covering in a single color a grid that starts with each cell colored randomly with one of six possible colors. You must expand the working region initially defined my the top-left cell throughout the entire grid. You select to color this working region with a new color that should match the color of neighboring cells. These cells are then merged into the working region. The game ends when you covered the grid in a single color. However, each level has a maximum allowed number of moves (or colorings) that you can do, and you only complete (or win) the level if you don’t exceed this number.

The image below shows how the working region expands towards the entire grid.

This new game has a more appealing interface and a richer set of features:

  • can select any of the available levels
  • you can change color themes for windows and for the grid
  • view statistics about your previous plays in any level
  • progress and settings are stored on disk and automatically reloaded when starting the application again

The game is described in details on this dedicated page. If you download an install the game, you should read that before playing.

If you find the game too easy, then I propose to use one of the more challenging color themes such as the Back and White one. Here is a screenshot:

Download the latest version of the game from here and enjoy it!

Hits for this post: 3747 .

Throughout January I have published on codeguru.com a series of articles about developing Silverlight applications for Windows Phone 7. Here is the list of articles:

If you want to develop for WP7 you need to install the Windows Phone 7 Developer Tools. They are available to download for free at AppHub, or using this direct link. You might also want to install the Silverlight for Windows Phone Toolkit that provides additional controls (such as WrapPanel, DatePicker, TimePicker, etc.) and higher-level support for touch.

Here is a list of recommended additional readings:

Enjoy the tutorials!

, , , Hits for this post: 6788 .

I’m using Red Gate’s .NET Reflector for decompiling .NET assemblies. It’s a great tool but it lacks, at least in the free version I’m using, information about the platform architecture of an assembly. Sometimes I want to know whether an assembly was built for Any CPU, x86 or x64.

The tool that help you find this information is CorFlags.exe from Windows SDK. It displays or configures the corflags section of a PE image. Here is an example of the output of corflags.exe:

Version   : v2.0.50727
CLR Header: 2.5
PE        : PE32
CorFlags  : 1
ILONLY    : 1
32BIT     : 0
Signed    : 0

The platform architecture is encoded in a combination of the PE and 32BIT flags:

  • Any CPU: PE=PE32 and 32BIT=0
  • x86: PE=PE32 and 32BIT=1
  • 64-bit: PE=PE32+ and 32BIT=0

So for the example above, PE is PE32 and 32BIT is 0, thus the platform architecture is Any CPU.

You can read more about this tool on Gaurav Seth’s blog.

, , , Hits for this post: 8734 .

Alchemy 1.3 is the latest update of Alchemy for Windows that brings 50 new exciting elements (taking the total to 350) and new features such as hints. The new elements in this release are focused on games; they include games such as Starcraft, Warcraft, Need For Speed, Tomb Rider, Resident Evil, characters such as Mario, Luigi, Yoshi, Jim Raynor, Zeratul, Queen of Blades, Lich King, and the races Zerg, Protoss, Terran, Fire Elemental.

Alchemy 1.3 new elements

The new elements are:



Aluminium Phoenix
Ant Protoss
Boo mushroom Queen of Blades
Computer game Resident Evil
Diet Robot
Easter egg Rust
Faberge egg Salamander
Fire elemental Sniper
Frog Spinning wheel
Infestation Starcraft
Insects Sushi
Jim Raynor Team
King Termite
Lara Croft Terran
Leach Tomb Raider
Lich King Undead
Lighthouse Vinegar
Luigi Vulture
Mantis Warcraft
Mario Weevil
Mosquito Yarn
Need for Speed Yoshi
Obesity Yoshi egg
OneUP Zeratul
Paint Zerg

You can find the list with all the 350 elements in Alchemy 1.3 here.

One new cool feature is the availability of hints. Press the new Hints button and a window pops-up displaying one possible element you can create, indicating also one of the two elements used to create it. To close the hints window, just click anywhere on it.

Another feature available in version 1.3 is adding elements to the desktop area by double clicking on them in the unlocked elements list. Terminal elements cannot be added to the desktop.

Note: if you already played Alchemy, just replace the old executable with the new one. Don’t delete the user settings file having your account name and extension .aus, or you loose the elements and combinations you unlocked so far.

Download the latest version from here.

, , Hits for this post: 23363 .

I have played recently a great game on Android, called Alchemy, created by Andrey Zaikin. You start with four basic elements, Fire, Water, Air and Earth and you can combine them to get more and more elements. The game was so catching that after finishing it I decided to write my own version for Windows. I chose WPF because I wanted to learn it and because I realized the stuff I wanted to create was too hard to do in MFC. This is my first real application in WPF, and what you see is the result of 4 days of work; in MFC it could have been 4 months, I believe.

You start with the four basic elements: air, earth, fire and water. You can combine them by dragging onto each other on the central area of the window, “the desktop”. When new elements are created they are added to one of the two lists from the left area. The top list has elements that can be combined again. The bottom list contains terminal elements, i.e. elements that can no longer be combined. You can drag elements from the non-terminals list back to the desktop area, but not from the terminals list.

You can quickly bring onto the desktop the four basic elements by double clicking on an empty area of it. Double clicking on an element from the desktop creates a duplicate of it. You can remove an element from the desktop by dragging it over the trash can icon. You can remove all the elements from the desktop by double clicking on the trash can.

When the number of elements gets too big scrolling through the list might be cumbersome. You can use the search textbox to filter the elements in the list. As you type only the elements that contain the typed text are displayed. It you press the X button of the textbox or clear its content, the list displays again all the unlocked elements.

On the right area of the window you find a help pane. When you select an element from one of the two lists on the left side, you can see a list of all the unlocked combinations in which the elements appears (either as input or output).

There are also several buttons: Cheat, Wikipedia, Help and About. Button Cheat opens a new window that displays the list of all available elements. So if you get stuck and don’t know what elements are left to discover you can cheat and see the list.

Button Wikipedia starts a search on Wikipedia for the currently selected element. Buttons Help and About display information about the game.

Note that your game progress is saved when you close the game and loaded when you start again. The information is stored in a file with your Windows user name and extension .aus. Don’t delete the file or you lose your game progress.

Here is the alphabetical list of all the 210 elements available in version 1.0:


Air Cochineal Gunpowder Ozone Soldier
Airplane Coffin Hippopotamus Panda Star
Alcohol Combustion engine Hourglass Paper Starfish
Algae Computer House Pearl Steam
Arable Concrete Hunter Penguin Steam engine
Arm Continent Hut Penicillin Steamer
Ash Corpse Hydrogen Perfume Stone
Assassin Country Ice Petroleum Storm
Bacteria Darth Vader Jedi Pie Sulfur
Barbeque Desert Kerogen Pinocchio Sun
Beach Diamond Knife Pizza Swamp
Bear Dinosaur Lava Planet Tequila
Beast Dough Library Plankton The Beatles
Beer Dragon Lichen Plesiosaur Thunderstorm
Beetle Dragonfly Life Poison Tiger
Bicycle Dust Light Poisoned weapon Time
Bird Earth Lightbulb Polar Bear Tom and Jerry
Bitumen Egg Lightsaber Pressure Tool
Boat Electricity Lime Pterosaur Tornado
Boiler Energy Limestone Radar Tortoise
Book Fern Livestock Radio Transistor
Bread Fire Lizard Rain Tree
Brick Firearm Locomotive Rainbow Turtle
Butterfly Fish Man Sand Uncut diamond
Cactus Fisherman Manure Santa claus Universe
Car Flour Meat Scarab Vodka
Carbon dioxide Flower Metal Scientist Volcano
Carmine Flu Milk Scissors Wagon
Cat Fly Mite Scorpion Warrior
Caviar Fondue Mold Seed Water
Cement Forest Monkey Shark Watermelon
Cheese Fossil Moon Shell Whale
Chicken Fruit Moss Silicon Wheat
Chip Fugu Motorboat Sith Wheel
Christmas tree Galaxy Motorcycle Sky Wind
City Gasoline Mouse Skyscraper Wine
Clay Geyser Mud Snail Wood
Cloth Ghost Mushroom Snake Wooden ship
Clothing Glass Ocean Snow Wool
Cloud Grape Old man Snowman Worm
Coal Grass Omelette Soda water Yeast
Coca cola Grove Oxygen Solar system Yogurt

Note: In order to run the game you need .NET framework 3.5 SP1.

Stay tuned, updates with more elements are coming!

Update: Download the latest version from here.

, , Hits for this post: 23357 .

For those that attended my last evening presentation about F# at Ronua Roadshow in Timisoara (but not only), here is the demo I’ve shown, and one that I planned to show but didn’t due to lack of time. The purpose of these demos was to shown simple Windows Forms applications written in F#.

Mandelbrot Fractal
A Mandelbrot set is a set of points in the complex plane, whose boundary forms a fractal. The fractal, known as Mandelbrot fractal, is obtain by associating a color with each point in the complex plane (or rather a subset of it). The color is chosen based on the result of computing the value of the complex quadratic polynomial Z(n+1) = Z(n)^2 + c for a number of iterations (100, 200, etc.). You can read more about it on Wikipedia.

The program that I shown exhibits traits of both functional (for computing the fractal) and object oriented (for displaying the fractal) paradigms. It is a variation of the program available here, for which I kept the functional part (computing the Mandelbrot set is not very fast, I must warn you), but redone the user interface part. You can use the mouse to drag the fractal and the wheel to zoom in and out.

You can download it from here.

Game of Life
I blogged about this two years ago, when F# was still far from a final release. In the meantime, syntax has changed, classes have changed, so if you try to run that implementation of mine you’ll run into some errors. I have updated the code to run correctly with Visual Studio 2010.

You can download it from here.

, , , Hits for this post: 12614 .