Search This Blog

Loading...

Wednesday, March 14, 2012

Understanding the Portable Library by Chasing ICommand (3 of 3)

Part 1: Creating the Portable Library
Part 2: Portability in Silverlight and WPF: a Tale of Type Forwarders
Part 3: Portability in Metro: A CLR and WinRT Love Affair (this post)

Portability in Metro: A CLR and WinRT Love Affair

In this series we’ve covered the portable library and reviewed how it allows you to create assemblies that can be shared without recompilation across multiple platforms. You created a portable assembly with a view model and a command in it, then successfully integrated it in a WPF and a Silverlight project. Now it’s time to code for the future and go Metro.

Create a new C# Metro application using the blank page template. Reference the PortableCommandLibrary project. Open the BlankPage.xaml file and drop in the same XAML you used for WPF and Silverlight. First, fix up a reference:

xmlns:portable="using:PortableCommandLibrary"

Next, add the XAML inside of the main grid:

<Grid.DataContext>
    <portable:ViewModel/>
</Grid.DataContext>
<Button Content="{Binding Text}" Command="{Binding ClickCommand}"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Margin="10"/>

Now compile, deploy, and run the application. It will work just as it did for WPF and Silverlight.

First the button:

portablelibmetro1

Then the disabled button:

portablelibmetro2

What’s interesting for this example is that you know when you want to wire a command, you have to use a completely separate namespace from Silverlight. In fact, the namespace implies that you are accessing a WinRT component that is part of the operating system and not even a managed object. How do we pull that off with an assembly that isn’t modified?

To begin the journey, start with the assembly that is referenced directly by the portable library. This is System.Windows.dll only this time you’ll inspect it in the .NETCore folder, which is the smaller profile allowed for Metro applications. Once again, the assembly contains no implementation. Opening the manifest, you will find a series of type forwarders. This time the ICommand interface is redirected to System.ObjectModel.dll.

portablelibmetro3

What’s next? You guessed it. Pop open the System.ObjectModel.dll assembly and you’ll find:

portablelibmetro4

So there it is … but there’s a problem. When you specify your own command implementation, you have to reference the Windows.UI.Xaml.Input namespace. So how will this reference work? This is where Metro works a little bit of magic.

It turns out the platform maintains an internal table that maps CLR namespaces to the WinRT equivalents. This allows seamless integration between the types. For example, the CLR may be exposed to the type Windows.Foundation.Uri when dealing with a WinRT component. When this happens, it automatically maps this to the .NET System.Uri. When the CLR passes System.Uri to a WinRT component, it is converted to a Windows.Foundation.Uri reference.

In our case, the code references:

System.Windows.Input.ICommand

The platform will automatically map this to the WinRT counterpart,

Windows.UI.Xaml.Input.ICommand

This is a very powerful feature because it enables compatibility between legacy code and the new runtime with minimal effort on the part of the developer. If your type maps to an actual object that can have an activated instance, rather than just an interface, the CLR will automatically instantiate a Runtime Callable Wrapper (RCW) to proxy calls to the underlying WinRT (essentially COM) component.

The whole portable path looks like this in the end:

portablelibmetro5

If you want to see the “projected” types you can use ildasm.exe with the /project switch and in theory, if you run this against one of the .WinMD files (such as Windows.UI.Xaml.Input.WinMD) located in %windir%\winmetdata you should see .NET projected types instead of Windows Runtime types … I have yet to get this to work but if you have, please post the details here.

And that’s it – you’ve learned how to create an assembly that is completely portable between .NET Framework 4.5 (WPF), Silverlight 4.0 and 5.0, and Windows 8 Metro, and learned a bit about how it works by chasing down ICommand under the covers. Hopefully this helps with understanding the library and also with planning out how to map future projects that need to share code between existing implementations and future Metro targets.

Friday, March 9, 2012

Understanding the Portable Library by Chasing ICommand (2 of 3)

Part 1: Creating the Portable Library
Part 2: Portability in Silverlight and WPF: a Tale of Type Forwarders (this post)
Part 3: Portability in Metro: A CLR and WinRT Love Affair

Portability in Silverlight and WPF: a Tale of Type Forwarders

In the last post, I walked through creating a portable assembly that will target Silverlight 4.0 and above, .NET Framework 4.5, and Windows 8 Metro. In the assembly were a few classes that handled commands and property change notification for a simple view model. In this post I’ll show you how to reference the assembly in Silverlight and WPF and explain why it works.

The first step is to create a new Silverlight 5.0 project (just using that because it’s the latest version, I know the library will technically support 4.0). Just make a simple application (no need to have a web project as well). The project will be created with the default App.xaml and MainPage.xaml. In the solution explorer, right-click on the References node and add a reference to the PortableCommandLibrary project. Now open up the XAML for the main page. At the top, add a namespace declaration for the view model:

xmlns:portable="clr-namespace:PortableCommandLibrary;assembly=PortableCommandLibrary"

Next, paste the following XAML inside the main grid called LayoutRoot (you’ll use the exact same snippet for all of the projects in this series).

<Grid.DataContext>
  <portable:ViewModel/>
</Grid.DataContext>
<Button Content="{Binding Text}" Command="{Binding ClickCommand}"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Margin="10"/>

Now compile and run the application. You should see something like this:

portablelibsilverlight1

If you follow the instructions, you should end up with this:

portablelibsilverlight2

I’d love to show you how this worked with the portable library, but the answer is pretty boring. As I showed you in the last post, the portable assembly points to an ICommand interface that lives in the System.Windows.Input namespace in the System.Windows.dll assembly. If you peek inside Silverlight’s assemblies and run ildasm.exe you’ll see:

portablelibsilverlight3

The reference can be visualized like this:

portablelibsilverlight4

Really no magic at all – Silverlight is a lowest common denominator here. So let’s try something a little more interesting. Create a new WPF project and reference the same portable library. Add the same namespace declaration to the MainWindow.xaml file and drop in the XAML inside the Grid tag. Run the application – look familiar?

portablelibwpf1

Click it.

portablelibwpf2

OK, so it works the same way, but we noted earlier that the ICommand interface lives someplace different. How does this work? If you recall, the reference to System.Windows.dll in the portable library was tagged as retargetable. This tells the runtime that the target may really exist somewhere else. In fact, if you look at the references available for the .NET Framework 4.5 (here’s a tip: forget that old %windir%\Microsoft.NET\Framework\ stuff … instead, try the newer %programdir%\Reference Assemblies\Microsoft\Framework\.NETFramework\ folder), you’ll find there is a System.Windows.dll file. Pop it open with ildasm.exe and you’ll see there is no implementation in the file, only metadata. Read the manifest and you’ll come across this little gem:

portablelibwpf3

Ah-hah! The portable library people have been planning this for longer than most readers suspect. There’s a nice reference now that politely invites the CLR to look somewhere else for the implementation, specifically in System.dll. If you open that assembly, you’ll see the interface is indeed defined there. So, what really happened looks a little like this for the .NET Framework 4.5:

portablelibwpf4

If you’re turning pale at the thought of so many hops, don’t get worried. These tables are loaded into memory and represent very miniscule lookups. The portable team assured me that any performance cost due to a little indirection is negligible.

What I love about the approach is that it uses a lot of pieces that have been already in place but in a clever way that gives us this powerful functionality of using the same assembly in Silverlight (web) or WPF (desktop). In the next post, we’ll take it even further and see how it relates to the brand new platform of the Windows Runtime (WinRT) for a Windows 8 Metro application. How on earth do we go from this to an unmanaged code base?

Thursday, March 8, 2012

Understanding the Portable Library by Chasing ICommand (1 of 3)

Part 1: Creating the Portable Library (this post)
Part 2: Portability in Silverlight and WPF: a Tale of Type Forwarders
Part 3: Portability in Metro: A CLR and WinRT Love Affair

The portable library tools have been available for several months now. The goal for this add-in to Visual Studio 2010 was to enable you to create special portable assemblies that can run on various platforms, ranging from XBox and Windows Phone 7 to various versions of the .NET Framework and Windows 8, without having to recompile them. That’s a pretty amazing feat and allows developers to avoid some crazy practices like linking source code.

With Visual Studio 11, the tools are no longer an add-in but are a built-in part of the product. You can directly create portable class libraries and build these magic assemblies that can be reused without recompiling. For many users, this is incredibly important because it means they can not only reuse their libraries between platforms like the phone and the desktop, but also can build insurance for the future. Think about it: you can build a Silverlight application today, share your libraries with a Metro application you are developing for tomorrow, and only have to branch the parts of the code that are necessary.

You may be surprised to learn just how much functionality can be shared. Property change notification, commands, even the network stacks can be shared across targets. The purpose of this post is to summarize some of the capabilities, show you how to build a project that shares portable libraries, and then get into the dirty details of how the magic really works. How can we possibly have an assembly that Silverlight recognizes today work without modification or recompilation in our Windows 8 Metro application of the future? Keep on reading if you want to uncover the answer.

For this example I’ll walk you through creating a view model that executes a command and changes some text. The view model will be reused without modification in a Silverlight, WPF, and Windows 8 Metro project, along with property change notification and the implementation of ICommand. What makes this interesting is the fact that ICommand lives in very different places on these platforms.

In Silverlight and WPF, ICommand lives in the System.Windows.Input namespace. While the namespace is the same, the assemblies are not. The definition exists in System.Windows.dll for Silverlight but in WPF and the .NET Framework 4.5 it is defined in System.dll. On Windows 8 Metro, the namespace for ICommand is Windows.Xaml.UI.Input. There, it doesn’t even live in an assembly but is defined through metadata and projected by the underlying OS. How does the portable library reconcile these differences?

If you want to follow along and have Visual Studio 11 Beta Ultimate (this won’t work with Express) simply create a new solution called PortableCommandLibrary and with a project of type Visual C# –> Windows –> Portable Class Library.

portablelib1

Now you can modify the target frameworks. As you may imagine, the platforms you wish to target will limit your options. For example, if you want to target the phone, you won’t be able to use the Managed Extensibility Framework (MEF). If you want to target the XBox, you won’t have the networking stack available. The combination of targets will limit the portable APIs available for you to use in your portable library. The beauty is that you don’t have to figure out what’s compatible as the team has figured this out for you and will automatically restrict your options based on what you select.

Right-click the project node and go into Properties (ALT+ENTER). Click on the Change button.

portablelib2

This will give you the option to select the profile you wish to use. For this example, we’ll build a library that targets .NET Framework 4.5 for WPF, Silverlight 4.0 and higher, and Metro.

portablelib3

Great! Now take a look at the Solution Explorer under References. What is that? “Portable Subset”?

portablelib4

Look at the properties for the reference and you’ll see a path. Navigate to the path. Wow, now this is interesting! There are the DLLs you can safely use between the targets. You can see a redistribution list and a set of supported frameworks as well.

portablelib5

The magic here is worked by a new Visual Studio 11 feature called Extension SDKs. This feature allows you to use a “reference” that is actually a package of files. It solves the problem of deploying custom controls with assets and also helps us write portable code. The portable team was kind enough to figure out all of the available permutations of framework combinations and package them as specific extensions to make a seamless reference experience in Visual Studio 11. You can read Microsoft’s documentation on how to create your own SDKs here.

OK so now we’ve learned a little bit about the magic that makes this work. The SDK reference constrains what we can do to code that is portable between the target runtimes. So what next? How about create a command that can perform a single action and then disables itself? You’ll need to add a using statement for System.Windows.Input:

public class ClickOnceCommand : ICommand 
{
    public ClickOnceCommand(Action action)
    {
        _action = action;
    }

    private Action _action; 
    private bool _canClick = true;

    public bool CanExecute(object parameter)
    {
        return _canClick;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _canClick = false;
        _action();
        var handler = CanExecuteChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}

Great! Next, let’s create a view model that exposes a text property. The property invites the user to click. The view model will expose a command and feed it the action to change the text (to admonish the user not to click). The view model looks like this:

public class ViewModel : INotifyPropertyChanged 
{
    public ViewModel()
    {
        ClickCommand = new ClickOnceCommand(() => Text = "Don't Click Me");
        _text = "Click Me";
    }

    private string _text;

    public string Text
    {
        get { return _text; }
        set
        {
            _text = value;
            RaisePropertyChanged("Text");
        }
    }

    public ICommand ClickCommand { get; private set; }

    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Here’s the interesting part: we’ve now created a functional view model and command that will work on multiple platforms from a single assembly without recompilation. If you’re concerned about your path from now to Windows 8, consider Silverlight 5 or WPF as an interim because the following XAML will work without a single modification across all of these targets (Silverlight, WPF, and Windows 8 Metro):

<Grid>
    <Grid.DataContext>
        <portable:ViewModel/>
    </Grid.DataContext>
    <Button Content="{Binding Text}" Command="{Binding ClickCommand}"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Margin="10"/>
</Grid>

Obviously it won’t always be that simple but there is a lot of opportunity for sharing code here. Don’t worry about using the XAML just yet – I’ll walk through that in the next post. You don’t have to be an expert to figure out what the goal is: we want to show a button that invites the user to click. When clicked, it will disable itself and tell the user not to click it. Simple, no?

You can build the portable library and inspect it with ildasm.exe. What I want you to notice is that the ICommand reference points to the System.Windows.dll assembly:

portablelib6

For Silverlight, this is fine … that’s exactly where it lives. In the .NET Framework 4.5, however, it lives in System.dll. Windows 8 Metro defines it in a different namespace: Windows.UI.Xaml.Input. So how can this single assembly work in those environments without being rebuilt?

I’ll explore the answer for WPF and the .NET Framework 4.5 in the next post. For now, take a look at the manifest that was generated for our portable assembly. Note the special tag on the external references.

portablelib7

More to come!

Tuesday, March 6, 2012

Windows 8 Icons: Segoe UI Symbol

Here’s a quick and easy tip for developing Windows 8 Metro applications. Are you looking for decent icons to use in your Application Bar? Windows 8 makes it incredibly easy by using the built-in Segoe UI Symbol font. There are tons of icons embedded in the font that are perfect for using in your applications.

Take a look at the following XAML snippet from the Microsoft quick start for adding an app bar:

<StackPanel Orientation="Vertical" Margin="0,14,0,5" Grid.Column="1">
   <Button Style="{StaticResource AppBarButtonStyle}"
       FontFamily="Segoe UI Symbol" FontSize="18.667" 
       Padding="8,8,0,0" Margin="0,0,0,10"
       Content="&#xE112;"/>
   <TextBlock Text="Back" />
</StackPanel>

It defines the section of the application bar you see below:

back

The key is in the content tag that specifies the arcane text &#xE112; – this is simply a notation that references the location of the symbol in the font (you can see the “font family” is set to the appropriate font). So how do you go about finding these icons? Fairly simple: on the Windows 8 machine, press the Windows Start Button (that button that has the Windows logo on it) or open the start menu and type “Character Map.” This will give you access to launch the Character Map application. Switch the font to Segoe UI Symbol and scroll down to the bottom until you see something like this:

segoeuisymbol

Now you can simply select the icon you wish to include. For this example I’ve selected the camera icon. Note the code at the bottom: U+E114. That is the code I need to know I can use &#xE114; in text for the Segoe UI Symbol font to make the camera icon appear.

How cool is that? You’ll find the font covers most of the icons you would need for your application. By using the icons from the font set, you also ensure consistency with other Metro applications. Users will be familiar with the fonts and it will make it easier for them to choose the right one for the task they intend to perform.

Wednesday, February 29, 2012

Windows 8 Consumer Preview 101

It’s finally here! Unless you’ve been hiding under a rock, you have heard the buzz around the Windows 8 Consumer Preview. If you haven’t had the opportunity to grab it and install it, I suggest you browser over to this link now and download your copy! There are many exciting new features, and this post will guide you through a few of them.

It is a Beta After All

There has been much buzz around whether or not the name “Consumer Preview” means it is not a beta and therefore the final release will be delayed. There is a lot of speculation around why the word “beta” is being avoided. Here is an article explaining some of these ideas. When you install the Consumer Preview – in fact, any time it loads or wakes up – you are presented with an image of, well, a Beta.

addmef

The Green Stack Isn’t Only Green

A common name for Metro-style applications you may hear is the “green stack.” This is named because the Developer Preview sported a green background. That’s no longer the case. You can now customize the color and design of the background for your Metro experience. I proudly present the Metro palette:

personalize

Where is the Start Button?

Twitter, Facebook, and blogs were going crazy over the rumors that the start button was going away. As a few people quickly pointed out, that isn’t really the case. True, there is no long a pervasive Start Button sitting on the corner of your task bar. But do you need it? First, most hardware and keyboards have a Start Button already – new tablets for Windows will feature this, so you can use the version on your device (this is similar to the way Windows Phone comes with hardware Back, Home, and Search buttons).

Even if you think resorting to the hardware is a cop-out, there is hope. Simply swipe your thumb in from the right edge of the screen or move your mouse pointer over to the right edge, and you will be greeted with … well … it’s a button, and I’m pretty sure it takes you to the screen you’re looking for.

startmenu

Lots of New Tiles

One thing you’re sure to notice immediately is the number of new tiles. Microsoft has been working hard to add additional functionality to the Metro stack and it shows. Just take a look.

start

Does that look busy or what? This snapshot was from a new install because I didn’t want to share too much personal information, but once you log into the various tools, the tiles will begin to update. I’ll go into some more interesting features below. You can see that instead of Windows Live, you have applications integrated into the platform for things like Mail and Messaging. What else can you see?

  • XBox Live Games – along with all of the fun integration with your account and avatar
  • Bing Maps – yes, it will find your current location and give you driving directions
  • Calendar – once you link your accounts, the Calendar works very similar to the way the Windows Phone does and aggregates your calendars together with a live tile announcing upcoming events
  • XBox Live Companion – yes, you can link to your favorite console and control it from your tablet
  • Store – everyone has a store, right?

These are just some of the highlights. Let’s dive a layer deeper.

Mail

Mail is an integrated feature. I like having mail right there, but it feels a bit raw. I was not able to hook into my hosted Exchange (soon to be Office 365) account and once I closed and came back, lost the ability to add a new account. Still, it allows me to browse mails quickly and easily and demonstrates the potential of where the platform can go.

mail

Music and Videos

Ah, now this one was fun! I wondered whether or not I would have to install Zune. When you first pop in, you get some encouraging sections like this:

music

What? No music? Do I have to go online and grab it? On a whim, I decided to copy over my Zune library from another laptop. This was just a straight file system copy, but guess what? It worked. Once I had the music moved over, it was instantly recognized and available to shuffle, play, and enjoy from my tablet. My tile turned into this:

music-tile

Previewing just a cross-section of some of the albums I have digitized. As for videos, I have lots of DVDs. Anyone have a good, um, ripper they can recommend?

People

This is by far my favorite feature. Like mail, it has a lot of work left to be done. The interface is not great and in fact scanning updates is tedious. However, the potential is what excites me the most. I love this feature on my Windows Phone. Basically, add connections to social networks, mail, etc. and all of your contacts meld together into one place. You get tile notifications, seamless history between messages, emails, and phone calls, and updates and notifications all in one place. The potential exists here for the same integration, it just needs to mature more.

Below you can see some of the potential – the cut off portion has contact names and pictures (I don’t think they’d be happy if I shared them here, hence the crop).

people

Closing Applications

Oh, remember how everyone complained that app swapping was a pain because there was no easy way to close applications? Not any more. There is a new gesture to take care of this. With your finger you can simply swipe downward from the top of the tablet display. This will shrink the current application. From there you can release and have it snap back, or continue to swipe down off the bottom and this action will close the application. Using a mouse? No problem. Hover near the top of the application until the pointer turns into a little hand. Click to grab, then drag it down and toss it off the bottom of your screen to close it.

Conclusion

I think there is a huge step forward between the Developer Preview and the Consumer Preview. It seems Microsoft is working hard and listening to feedback. There is a lot of work to do, however.

Did you install the Consumer Preview? If so, what are your thoughts? Ping back with the comments below.