Valter Minute's blog

Silverlight for Windows Embedded tutorial (step 3)

After the first two tutorial steps were published on this blog I received many requests about using images inside a Silverlight for Windows Embedded application. This is the topic of this post.
To be able to load and use image files (jpegs,bmps,gifs) inside your application you should include the imaging library components in your OSDesign.
Those component are not included automatically when you add the XAML runtime (the runtime can run also without the imaging components, it will simply not load your images!).
To display an image inside your application user interface you have to use the image control of Silverlight.
This is a very simple XAML file that includes just an Image object and a button:


<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="ImgTest.Page"
    Width="640" Height="480" x:Name="ImagePage">
    <Grid x:Name="LayoutRoot" Background="White">
        <Image Margin="17,25,25,103" x:Name="MyImage" Source="\Windows\img01.JPG"/>
        <Button Height="49" Margin="259,0,253,28" VerticalAlignment="Bottom" Content="Button" x:Name="MyButton" Click="OnClick"/>
    </Grid>
</UserControl>

The image object is named "MyImage" and the button is named "MyButton".

We also have an OnClick event handler for the Click event of the button.

We can create a new Win32 application inside platform builder.

Using the XAML2CPP we can generate some code for us.

We will just have to include "XAML2CPP.h" inside your main C++ source file to use the code that XAML2CPP created for us:

#include "XAML2CPP.h" 

We also have to include "XAML2CPP.rc" inside the rc file of our application to include the XAML code as a resource inside our application.

XAML2CPP has created a base class that we can use to implement our own class and handle the OnClick event:

class ImagePage : public TImagePage<ImagePage>  {  ...  }


In this sample we will just swap two images inside the image control each time you click on the button.
We have to declare a state flag (to be able to swap images) and two IXRBitmapImagePtr objects to store our bitmaps.

    bool state;          IXRBitmapImagePtr    img01;     IXRBitmapImagePtr    img02;   

A very simple constructor will reset the state:

    ImagePage()     {          state=false;          }  

The main initialization will be performed inside our Init method (it's not a good idea to put this kind of initialization code inside the constructor because some API calls may fail and you don't have a way to return an error code from a C++ constructor).

    virtual HRESULT Init(HINSTANCE hinstance,IXRApplication* app)          {             ...     } 

Inside our Init method we have to call the Init method of our base class (declared by XAML2CPP), and check its return code for errors:

        HRESULT retcode;                    if (FAILED(retcode=TImagePage<ImagePage>::Init(hinstance,app)))              return retcode;

We declared two IXRBitmapImagePtr objects but we still haven't initialized them.
To create a Silverlight for Windows Embedded object we should use the CreateObject method of the IXRApplication object:

        if (FAILED(retcode=app->CreateObject(IID_IXRBitmapImage,&img01)))              return retcode;         if (FAILED(retcode=app->CreateObject(IID_IXRBitmapImage,&img02)))              return retcode;

The we can load the bitmaps and store them inside the IXRBitmapImagePtr objects:

        if (FAILED(retcode=img01->SetUriSource(TEXT("\\Windows\\img01.jpg"))))                           return retcode;         if (FAILED(retcode=img02->SetUriSource(TEXT("\\Windows\\img02.jpg"))))              return retcode;

In the OnClick event handler we just have to swap the image displayed by the MyImage object and change the state flag:

    HRESULT OnClick(IXRDependencyObject* source,XRMouseButtonEventArgs* args)      {                    HRESULT retcode;                    if (FAILED(retcode=MyImage->SetSource(state?img01:img02)))                          return retcode;                   state=state?false:true;                  return S_OK;           }

The main function of this sample is quite simple and it's not much different for the WinMain functions of the previous samples (just the class name changes):

int WINAPI WinMain(HINSTANCE hInstance,                       HINSTANCE hPrevInstance,                       LPTSTR     lpCmdLine,                       int       nCmdShow)  {      if (!XamlRuntimeInitialize())              return -1;          HRESULT retcode;            IXRApplicationPtr app;          if (FAILED(retcode=GetXRApplicationInstance(&app)))          return -1;        ImagePage imagepage;        if (FAILED(imagepage.Init(hInstance,app)))          return -1;        UINT exitcode;        if (FAILED(imagepage.GetVisualHost()->StartDialog(&exitcode)))          return -1;        return 0;   }

You can download the full source code of this sample here:

http://cid-9b7b0aefe3514dc5.skydrive.live.com/self.aspx/.Public/ImageTest.zip

 

XAML2CPP ver. 1.0.0.1

I just found (and fixed) some bugs inside the XAML2CPP tool.

You can download the new release from here:

http://cid-9b7b0aefe3514dc5.skydrive.live.com/self.aspx/.Public/XAML2CPP.zip

Changes history:

ver 1.0.0.1

- the application version is inserted in the generate files and written on the console

- the x:Name tag of the user control is used as class name instead of the XAML file name. If no x:Name attribute is specified the XAML file name will be used.

 


XAML2CPP


Before I start to explain the topic of this post I should confess one of my many defects: I'm very lazy.
Someone may have noticed that from the update rate of this blog, but I really like to avoid as much work as I can.
I also really like to experiment new technologies and embedded devices, and that's bad for a lazy guy because that means having to write some code...
While experimenting with Silverlight for Windows Embedded I found myself trying to write some more complex samples to continue my own tutorial (it's idle, but I told you that I'm lazy...) but I hate to write all the "boilerplate" code required to connect C++ objects to XAML code and register event handlers on those objects.
Being as lazy as I am I decided that writing a simple tool once it's better than re-writing more or less the same code over and over again, so I wrote a small tool that without much fantasy (I'm lazy also about coming out with fancy names for tools!) I called XAML2CPP.
XAML2CPP is a very simple command line utility that parses a XAML file and generates some C++ code for you.
It generate a class for each XAML file (I suppose that you have one user control per file so that makes sense) with all the code needed to access the objects inside your XAML and to invoke event handlers when an event is generated by the runtime.
It also generates a "cumulative" include file (to avoid to include each class file in my sources, you know...I'm lazy) and resource definitions (to avoid to define your own XAML resources).
It generates code only for objects and event handlers that have a name (memory is not an infinite resource, as our colleagues programming desktop application may believe, and declaring objects and event handler for everything looks like a waste to me).
Let's start with an easy sample (I'm too lazy to write a complex one!):

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SimpleApp.Page" 
Width="640" Height="480">
    <Grid x:Name="LayoutRoot" Background="White">
        <Button Height="87" Margin="189,106,209,0" VerticalAlignment="Top" Content="Button" 
x:Name="MyButton" Click="OnClick"/>
    </Grid>
</UserControl>


As you can see this is more or less the same XAML code we used in the first tutorial step (being lazy it's easier to modify an existing sample than creating a new one!), I just specified "OnClick" as name for the Click event handler of the MyButton object.
If we run XAML2CPP using this command line syntax:
XAML2CPP Page.XAML
It will generate five source files:
XAML2CPP.rc
XAML2CPP.h
XAML2CPPBase.h
XAML2CPP_res.h
T_Page.h
I'm lazy, but my tools aren't: five files out of a single one!

Never change the code inside those files, if your run XAML2CPP again it will overwrite them and your modifications will be lost forever (and even if you are not lazy like me, rewriting the same code over and over again after it has been overwritten don't look so smart).
I know that modifications are not lost forever because you are a good programmer and you have multiple backups of all your sources... but that doesn't change the concept: never modify XAML2CPP generated code!
And also never use for your own files the same file names that may be generated by XAML2CPP, of course.
Let's see what those files contains and how you can integrate them in your Silverlight for Windows Embedded application.
XAML2CPP.rc includes all the resource definitions that we need to include our XAML inside the executable file resources.
In this case it will include only our Page.XAML file (you can run XAML2CPP with multiple input file names or with wildcards to generate multiple XAML resources).
Those are the contents of XAML2CPP.rc:
XAML_RESOURCE_Page   XAML ".\Page.xaml"
Pretty minimal, isn't it? But this has saved writing at least one row of code. Since I had to write "xaml2cpp page.xaml" on the command line this hasn't saved too much time... let's see what's inside other files.
XAML2CPP_res.h includes the definitions of the resources that XAML2CPP brought inside your executable.

/*
This file has been generated by XAML2CPP tool.
Modifications to this source code may be overwritten without warning when the XAML2CPP tool is executed.
XAML2CPP (c) 2009 by Valter Minute (valter.minute@gmail.com)
This code is provided as is and it's generated automatically. It's up to the developer to check that it works as expected.
*/
/*
This file includes all the resource identifiers of the XAML files embedded inside the application resources
*/
#ifndef XAML2CPP_RES_H
#define XAML2CPP_RES_H
#define IDR_XAML_Page TEXT("XAML_RESOURCE_Page")
#endif //XAML2CPP_RES_H


Four rows of code, not including the copyright. Not bad!
XAML2CPPBase.h will have always the same content, it's the definition of a class (XAML2CPPBase) that is used as base class for all the XAML2CPP generated classes. Even if that's not strictly necessary, the file is generated by XAML2CPP each time it's run. In this way some modifications of the base classes introduced by a new release of the tool will not require re-distribution of a new header and udating it inside all the project using it (sometimes being lazy may prevent some maintenance nightmare).
This will allow a single declaration of some members and methods that are common between all those objects.
After the copyright you'll find the base class declaration:

class XAML2CPPBase
{
...
}

In this class we will find some XAML runtime objects:

    // Pointer to the visual host
    IXRVisualHostPtr vhost;
    
    // Pointer to the root of the XAML visual tree
    IXRFrameworkElementPtr root;

and some methods to access them (they are declared as protected inside our base class):

    // returns the visual host
    IXRVisualHost* GetVisualHost() { return vhost; }
    
    // returns the visual tree root
    IXRFrameworkElement* GetRoot() { return root; }


We also find two string pointers and a constructor to inizialize them:

    // Pointer to the page title
    TCHAR* windowtitle;
    
    // Pointer to the resource name
    TCHAR* xamlresourceid;
    
public:

    XAML2CPPBase(TCHAR* windowtitle,TCHAR* xamlresourceid)
    {
      this->windowtitle=windowtitle;
      this->xamlresourceid=xamlresourceid;
    }

Those pointers will be used to set the window title for our visual host (you may not need to set a title if your window has no title bar) and the resource id of the XAML associated with a specific instance of a XAML2CPPBase derived class.
Those field are used in the two function that setup window creation parameters and XAML loading method:

    // Initializes Windows parameters, can be overridden in the user class to change its appearance
    virtual void InitWindowParms(XRWindowCreateParams* wp)
    {
            wp-&gt;Style       = WS_OVERLAPPED;
            wp-&gt;pTitle      = windowtitle;
            wp-&gt;Left        = 0;
            wp-&gt;Top         = 0;
    }

    // Set the XAML source path. By default loads the XAML that is included in the resources script
    virtual void SetXAMLSource(HINSTANCE hInstance,XRXamlSource* xamlsrc)
    {
        xamlsrc->SetResource(hInstance,TEXT("XAML"),xamlresourceid);
    }

 

 

In this way we will create an overlapped (top level) window with the title we passed to the constructor and we will load our XAML from the resource specified by the other constructor parameter.
If we want to change this behavior we may override InitWindowParms or SetXAMLSource method in our derived class. Lazy people love C++ inheritance!

Those method are called by the CreateHost method, the method that initializes our visual host and loads our XAML:

    // create the visual host and loads the XAML
    virtual HRESULT CreateHost(HINSTANCE hInstance,IXRApplication* app)
    {
        HRESULT retcode;
        
        XRWindowCreateParams wp;

        ZeroMemory(&amp;wp, sizeof(XRWindowCreateParams));
        
        InitWindowParms(&amp;wp);

        XRXamlSource xamlsrc;

        SetXAMLSource(hInstance,&amp;xamlsrc);
        
        if (FAILED(retcode=app-&gt;CreateHostFromXaml(&amp;xamlsrc, &amp;wp, &amp;vhost)))
            return retcode;

        if (FAILED(retcode=vhost-&gt;GetRootElement(&amp;root)))
            return retcode;
        
        return S_OK;
    } 

This method is also marked as virtual so you may override it if you need to perform some particular initialization steps inside your own class. Usually overriding InitWindowParms and SetXAMLSource should be enough but a virtual function call during initialization won't impact performances so much, so I preferred to leave more room for customization in this case.
If you override CreateHost remember that the rest of the code expects root and vhost smart pointers to be initialized after this method has been called.

Now let's see what's inside XAML2CPP.h.

/*
This file has been generated by XAML2CPP tool.
Modifications to this source code may be overwritten without warning when the XAML2CPP tool is executed.
XAML2CPP (c) 2009 by Valter Minute (valter.minute@gmail.com)
This code is provided as is and it's generated automatically. It's up to the developer to check that it works as expected.
*/
/*
This header includes all the classes generated by XAML2CPP the last time it was executed.
*/
#ifndef XAML2CPP_H
#define XAML2CPP_H

#include "T_Page.h"

#endif //XAML2CPP_H

In this file you'll find an #include directive for each class that has been generated by XAML2CPP from the XAML files it processed. This will allow you to simply include "XAML2CPP.h" in each source file where you need to access one of the classes generated by the tool. Including it in your pre-compiled header file (usually stdafx.h) could save some build time.
Now let's see in detail what's inside T_Page.h.

#ifndef Page_TEMPLATE_HEADER_FILE_H
#define Page_TEMPLATE_HEADER_FILE_H
#include "windows.h"
#include "pwinuser.h"
#include "xamlruntime.h"
#include "xrdelegate.h"
#include "xrptr.h"
#include "XAML2CPP_res.h"

After an #ifdef used to avoid multiple inclusion of this file you'll find a list of includes for all the header  files needed to build a Silverlight for Windows Embedded  application. This will save some time and some time spent understanding build errors.

Then we find a template declaration:

/*
class generated by XAML2CPP from .\Page.xaml
*/
template <class X>
 class TPage : public XAML2CPPBase
 {
 ...
 }
 


I used templates to be able to link event handlers directly to your own code and not to some code generated by the tool.
I may have used a function invoking a pure virtual method inside my class and let you implement your own method in a derived class but that may have a (small) impact on performances.
We will see how we can derive our own class from the one generated by XAML2CPP in a short time. Right now, let's focus on the TPage class code.
We have a constructor that takes two (optional) parameters and passes them to the XAML2CPPBase constructor. In this way you can change the title of your window and XAML resource id or use the default ones generated by the tool.

public:
    TPage(TCHAR* title=TEXT("Page"),TCHAR* xamlid=IDR_XAML_Page) : XAML2CPPBase(title,xamlid)
    {
    }

The we have two smart pointers:

protected:

    // XAML defined objects (declared as smart pointers)
    IXRGridPtr LayoutRoot;
    IXRButtonPtr MyButton;

The tool generates them using the names you specified in the x:Name attribute of your XAML code (or that you set in the properties window inside Expression Blend, of course).
For each object with an x:Name attribute in your XAML you'll have an object, no need to declare them! Great for lazy people and also great to avoid that a designer changes the name of an object without informing you. In this way you can re-generate code and then you'll have to replace the old name with the new one but you'll discover that at build time, not when you run you application.
Those smart pointer need to be bound to XAML objects and that's done inside the BindObjects method:

    // binds objects smart pointers to objects created by the runtime
    virtual HRESULT BindObjects()
    {    
        HRESULT retcode;
            
            
        if (FAILED(retcode=root->FindName(L"LayoutRoot",&LayoutRoot))) 
            return retcode;
                       
            
        if (FAILED(retcode=root->FindName(L"MyButton",&MyButton))) 
            return retcode;
                       
    
        return S_OK;
    }


The code of this method looks boring and repetitive... but you don't have to write it, XAML2CPP has generated it for you. And no chances to type the wrong name or forget something during cut&paste (I know that you write this kind of code using cut&paste, like I do!).
Now we have to bind our event handlers to the objects, and that's exactly what the BindEventHandlers method does:

// binds event handlers to template class member functions   
    // should be called after BindObjects
    virtual HRESULT BindEventHandlers()
    {
        HRESULT retcode;
        
    
        //declare your own event handler as 
        // HRESULT OnClick(IXRDependencyObject* source,XRMouseButtonEventArgs* args)
        IXRDelegate<XRMouseButtonEventArgs>* OnClickDelegate;

        retcode=CreateDelegate<X,XRMouseButtonEventArgs>((X*)this,&X::OnClick,&OnClickDelegate);
        
        if (FAILED(retcode))        
          return retcode;
            
    
        if (FAILED(retcode=MyButton->AddClickEventHandler(OnClickDelegate)))
            return retcode;
    
        OnClickDelegate->Release();
    
        return S_OK;
    }

As you can see a delegate is created using the OnClick method of the class parameter passed to the template and this is your own class. You'll have to declare the OnClick method inside your class. If you don't you'll get a build error on the CreateDelegate call. Just  above that line you'll find a prototype of that method ready to be cut and pasted inside your code!

Now we have seen how to run XAML2CPP and the code it has generated. We still have to see how we can integrate it in our own code.

You can start by creating an empty Win32 application subproject inside Platform Builder.

You can repeat the steps we did in the first Silverlight for Windows Embedded tutorial here:

http://geekswithblogs.net/WindowsEmbeddedCookbook/archive/2009/10/01/silverlight-for-embedded-tutorial.aspx

Then move your XAML file inside the subproject directory and run XAML2CPP on it. You'll have all the files we described above inside your subproject directory.

Add a resource (.rc) script to your project, as described in the tutorial but don't add the XAML resource to it.

Simply include the .rc script that XAML2CPP has generated for you.

Move to the "resource view" tab, right click on your project .rc file and select "Resource includes...".

Add:

#include "XAML2CPP.rc"

and close the dialog.

In this way you'll include all the resources generated by XAML2CPP, you don't need to add them by hand (and discover that you forgot that when you run your application!).

Now you can edit our main .cpp source file.

Fist of all you can include "XAML2CPP.h" :

#include "XAML2CPP.h"

Then you can declare a class to implement the code that XAML2CPP hasn't (and could not have) generated for you:

class Page : public TPage<Page>
{
public:

    HRESULT OnClick(IXRDependencyObject* source,XRMouseButtonEventArgs* args)
    {
        MessageBox(NULL,TEXT("Click!"),TEXT("Click!"),MB_OK);
        return S_OK;
    }
};

As you can see the class is quite simple. You'll have to write only your own even hander code (and you may copy its prototype from the comment inside TPage.h, a dream for a lazy programmer like me!). No initialization code, no event binding code.

Sounds great?

Let's see what you have to add to your WinMain function to create your own XAML UI.

You should still add the runtime initialization code (you can copy it from our previous sample, so don't be too lazy!):

int WINAPI WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR     lpCmdLine,
                     int       nCmdShow)
{
    if (!XamlRuntimeInitialize())
            return -1;

    HRESULT retcode;

    IXRApplicationPtr app;
    
    if (FAILED(retcode=GetXRApplicationInstance(&app)))
        return -1;

Now you can create and display your XAML page:

    Page page;

    if (FAILED(page.Init(hInstance,app)))
        return -1;

    UINT exitcode;

    if (FAILED(page.GetVisualHost()->StartDialog(&exitcode)))
        return -1;

    return 0;

You should declare an istance of your class, call Init on it (passing the application HINSTANCE and a pointer to the XAML runtime application object) and then you can show it accessing its visual host methods.

As you can see XAML2CPP has generated only the "boilerplate" code and just a simple wrapper around some features (initialization, mostly). It's not a big framework, I don't like them and I'm too lazy to build one!

You can download XAML2CPP from here:

http://cid-9b7b0aefe3514dc5.skydrive.live.com/self.aspx/.Public/XAML2CPP.zip

It's still an alpha release, so use it carefully (read that as backup everything you can backup and don't blame me for problems) and let me know if you experience problems or have ideas about ways to improve it.

As I told you, I'm a lazy guy... so don't hold your breath waiting for updateas and bugfixes. But I promise that I'll try to improve this tool and when the code is stable and readable enough, maybe publish it on codeplex or other open-source repositories.

 


Silverlight for Windows Embedded tutorial (step 2)

In our first tutorial
http://geekswithblogs.net/WindowsEmbeddedCookbook/archive/2009/10/01/silverlight-for-embedded-tutorial.aspx
we learnt how to load a XAML-based user interface inside your own application and intercept the events that it generates.
In this second tutorial we will learn how to use storyboards to create animations inside our user interface and how we can control them from code.
We can reopen our silverlight2 application project in Expression Blend 2 SP1 and add a new element to our UI: a TextBlock.

We can place it just under our button.

Then we can create a new storyboard, using the "+" button that we can find just under the "Objects and Timeline" toolbox header.

We should assign a name to our new Storyboard, as we did with the button control.

Now we can move our storyboard time cursor to the 1 second mark and change our page to the end point of our animation.

We can rotate our TextBlock, for example.

Expression Blend create for us the animation and transformation objects required to perform the desired visual effect.
We want to have our TextBlock performing a full rotation, so we can edit the parameters of the rotation transform and set the angle to 360 degrees.

By right clicking on the tranform item we can also set the number of iteration that this animation performs. We set it to infinite to have a continous rotation of our poor TextBlock.

Now we save the changes we did to our project in Expression Blend and go back to Platform Builder to change our code.
First of all we have to get a pointer to our Storyboard. We can retrieve it using the FindName method of our visual root, like we did to retrieve a pointer to the button object in the first step of this tutorial.

    IXRStoryboardPtr sboard;

    if (FAILED(retcode=root->FindName(TEXT("SpinText"), &sboard)))
        return -1;


We will need to use the storyboard and button object inside your event handler class, so we need to change it to store those two smart pointers:

class BtnEventHandler
{
protected:

    IXRButtonBasePtr    btn;
    IXRStoryboardPtr     sboard;

public:

    BtnEventHandler(IXRButtonBasePtr& button, IXRStoryboardPtr& storyboard) : btn(button),sboard(storyboard)
    {    
    }

   
We also need to change its declaration inside the WinMain function:

    BtnEventHandler handler(btn,sboard);


Now we can edit our OnClick event handler to use our button to start and stop spinning animation.
First of all we should know if the animation is running. To do that we can retrieve the state of our storyboard object:

        HRESULT        retcode;
        XRClockState ckstate;

        if (FAILED(retcode=sboard->GetCurrentState(&ckstate)))
            return retcode;


if ckstate is XRClockState_Stopped, our animation is stopped, so we will need to start it, using the Begin method of our Storyboard object.
If the animation is running we should stop it using the Stop method.
At the same time we want to change the text on the button object to reflect the action it performs. The IXRButton object (COM interface) derives from the IXRContentControl object that defines methods to access a control "content".
What is "content" for a Silverlight for Windows Embedded object? It's an instance of the XRValue class. This class can contain different kinds of data: strings, numbers, coordinates etc. It's current content type is defined by the vType field and may be one of the VALUE_TYPE enumeration values:
VTYPE_NONE = 0,
VTYPE_FLOAT = 1,
VTYPE_INT = 2,
VTYPE_BOOL = 3,
VTYPE_UINT = 4,
VTYPE_COLOR = 5,
VTYPE_READONLY_STRING = 6,
VTYPE_BSTR = 7
VTYPE_POINT = 8,
VTYPE_RECT = 9,
VTYPE_THICKNESS = 10,
VTYPE_SIZE = 11,
VTYPE_GRIDLENGTH = 12,
VTYPE_CORNER_RADIUS = 13,
VTYPE_OBJECT = 14
Depending on the type you set, you can use one of the fields of the object (defined as an unnamed union) to set the actual value of your XRValue objects.
If you worked on COM (Component Object Model) applications in the past (or you are working on this kind of technology right now, of course!) the XRValue object will remind you the VARIANT object that is used in COM to define "generic" data.
To change the content of our button we need to declare an XRValue object of type "read only string":

        XRValue btnvalue;

        btnvalue.vType=VTYPE_READONLY_STRING; 


We can assign its value trough the pReadOnlyStringVal field and set it to "Spin!" or "Stop!" depending on our animation current state.
The full code of our event handler will be:

    HRESULT OnClick(IXRDependencyObject* source,XRMouseButtonEventArgs* args)
    {
        HRESULT        retcode;
        XRClockState ckstate;

        if (FAILED(retcode=sboard->GetCurrentState(&ckstate)))
            return retcode;

        XRValue btnvalue;

        btnvalue.vType=VTYPE_READONLY_STRING; 

        if (ckstate==XRClockState_Stopped)
        {
            btnvalue.pReadOnlyStringVal=L"Stop!";
            if (FAILED(retcode=sboard->Begin()))
                return retcode;
        }
        else
        {
            btnvalue.pReadOnlyStringVal=L"Spin!";
            if (FAILED(retcode=sboard->Stop()))
                return retcode;
        }

        if (FAILED(retcode=btn->SetContent(&btnvalue)))
            return retcode;

        return S_OK;
    }

   
A little more complicated than the event handler of our previous tutorial step, but not so much. And in this function we used two very useful features of Silverligh for Embedded: animations and control content access.
You can download the full source code here:
http://cid-9b7b0aefe3514dc5.skydrive.live.com/self.aspx/.Public/SilverlightSample2.zip
Please use the comments to let me know if you find this kind of tutorial useful, to report mistakes and to suggest the arguments that you would like to see discussed in the next steps.


Interfaccia uomo macchina

Sevilla (Spain) - The alcazar
If you want to discover something more about Windows Embedded CE 6.0 R3 and you live close to Padua, Milan or Bologna (or you want to travel to those cities, of course!), you can register for those Arrow, Microsoft and Freescale sponsored events:
http://www.silverstar-celdis.it/index.php?id=834&tx_ttnews%5Btt_news%5D=253&tx_ttnews%5BbackPid%5D=831&cHash=6a2c437777
If you read my blog and come to those events, let me know that!

Silverlight for Windows Embedded tutorial

Windows Embedded CE 6.0 R3 has been released yesterday, you can download it from here:
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=bc247d88-ddb6-4d4a-a595-8eee3556fe46
One of the most exciting new features of R3 is Silverlight for Windows Embedded.
With this technology the UI of an application can be described using XAML, an XML-based language, and can be designed using visual tools like Expression Blend.
This will allow UI designers to work on embedded devices using the same tools they use on the desktop and it will let embedded developers concentrate on the core application features and not on the design of the UI.
I hope that this will lead to visually pleasing but also more user friendly interfaces on any kind of embedded device. Using visual tools for UI design should also improve development time and allow minor fixes to the UI without code modifications. This will improve device development times and reduce maintenance costs.
This simple tutorial will show how you can design a very basic UI in Expression Blend 2, load it inside an application and interact with it.
The first step you need to perform is include the components needed to support Silverlight for Windows Embedded inside your OS Image and rebuild it.
Jochen Dieckfoß provided a good description of that process on his blog here:
http://discovertheexperience.blogspot.com/2009/09/windows-embedded-ce-60-r3-using.html
Now that you have an OS image supporting Silverlight for Windows Embedded you can start to design your UI.
Start Expression Blend and create a new Silverlight application.

You'll have to use Expression Blend 2 SP1 (thanks Shai for the useful advice!) because this is the release that support Silverlight 2, the version that is currently supported on embedded devices.
This will create a Visual Studio solution (that we don't need for this tutorial).
As you can see the wizard allows you to choose a language between C# and Visual Basic. Silverlight for Windows Embedded supports only C++ programming and it's currently not integrated with Expression Blend, so you'll not use the source code generated by this tool.
Remember to disable Visual Studio integration inside Expression Blend or it will generate C# or VB.NET code for event handlers etc.

After you created a new project, Expression Blend will present you with an empty XAML document (named page.xaml by default).

We can draw a simple button inside it picking it from the rich collection of controls provided by Silverlight.

Using the properties window we can assign a name to our new button.

The properties toolbox allows you to customize many aspects of your button: it's colors, it's rotation (yes you can have a vertical button or a button turned at 45 degrees!), it's opacity etc.
We will experiment with all these features in the next tutorials, for now we will keep the button as is and save our XAML.
If you open the XAML file using a text editor or view it using the XAML view inside Expression Blend you'll see that it's quite simple:

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SimpleApp.Page" 
Width="640" Height="480">
    <Grid x:Name="LayoutRoot" Background="White">
        <Button Height="87" Margin="189,106,209,0" VerticalAlignment="Top" Content="Button" 
x:Name="MyButton"/>
    </Grid>
</UserControl>


We have a top level container (UserControl) that uses a Grid layout (objects are organized in rows and columns) and contains our button.
The button has attributes for placement inside its own grid cell (the only one we have), alignment, content (the text "Button") and its name ("MyButton").
Now we can start Platform Builder and add a new subproject to our OS Design.
You may develop your Silverlight for Windows Embedded application also using Visual Studio 2005 or 2008 Smart Device application if you generate an SDK from your R3 OS design and install it on your development PC, but for this tutorial we will keep things simple...
Move to the solution tab, right click on the subprojects node and select "add new...".
Create a Win32 application.

And choose the simple Win32 application template.

This will create an application containing only WinMain, it's enough to start experimenting with our first Silverlight for Embedded UI.
The first thing we should do is add the Silverlight for Windows Embedded includes to our source code:

#include "pwinuser.h"
#include "xamlruntime.h"
#include "xrdelegate.h"
#include "xrptr.h"


We will add the XAML that we generate with expression blend to our application resources. In this way we will not need to distibute the XAML file with it. On the other side changes to the XAML will require a rebuild of the application, you may choose the best method to integrate XAML and C++ source code in your application.
To include resources inside your executable file you need to add a resource script (rc file) to your subproject.
Right click on the subproject in solution view, select "add\new item" and then select resource file from the dialog box and assign a name to it (usually you have only one resource file per application so using the application name for that file sounds like a good idea).

Now that you have your resource file you can add the XAML data to it by creating a new resource.
Go to the "resource view" tab, right click on your resource file and select "add resource..."

Now you can import your XAML file data inside your executable. It will be stored inside it (at the end of the file) as binary data.

Type "XAML" as resource type.

For the tutorial you can leave the default ID (IDR_XAML1) for that resource, but it's a good idea to give meaningful names to your XAML components in a real project.

To use our resource IDs we need to include "resource.h" inside our .cpp file:

#include "resource.h"


Then, inside our application main function (WinMain) we can start to interact with the XAML runtime.
First of all we need to initialize it:

    if (!XamlRuntimeInitialize())
        return -1;


If XamlRuntimeInitialize succeeded, the Silverlight for Windows Embedded runtime is loaded inside your application and it's ready to handle the UI.
Each Silverlight for Windows Embedded application has a singleton "Application" object that allows us to access global application properties and features.
To access it we should use the GetXRApplicationInstance API.

    HRESULT retcode;

    IXRApplicationPtr app;
    
    if (FAILED(retcode=GetXRApplicationInstance(&app)))
        return -1;



Someone will notice that we are using HRESULTs and classes that use the "I" prefix and the "Ptr" suffix and understand that this new technlogy is based on COM (Component Object Model) that may sound like an ancient tool in those .NET and managed code days but it's still the foundation of many technlogies on both CE and desktop Windows releases. All Silverlight for Windows Embedded objects are implemented as COM objects that export specific interfaces (COM interfaces have names beginning with "I"). Since using interfaces directly requires handling of their reference count and this may lead to memory leaks or premature object deletions, COM programmers prefer to use "smart pointers" that are wrappers around the interfaces and manage reference counting internally, destroying the COM object when the smart pointer object goes out of scope inside your C++ application (function return if it's allocated on the stack, object destruction if it's declared as a class member etc.). Smart point classes add the "Ptr" suffix to the interface name.
After this 30 seconds introduction to COM, we can return to our application.
The first thing we have to do with our application object is tell it where it can find its resources (XAML, images etc.).
We included them inside the executable using the resource file and so we can pass our HINSTANCE handle to it:

    if (FAILED(retcode=app->AddResourceModule(hInstance)))
        return -1;


Now that we have initialized our application object we can create our main window and let Silverlight for Windows Embedded manage its contents:

    XRWindowCreateParams wp;

    ZeroMemory(&wp, sizeof(XRWindowCreateParams));

    wp.Style       = WS_OVERLAPPED;
    wp.pTitle      = L"S4E Test";
    wp.Left        = 0;
    wp.Top         = 0;

    XRXamlSource xamlsrc;

    xamlsrc.SetResource(hInstance,TEXT("XAML"),MAKEINTRESOURCE(IDR_XAML1));

    IXRVisualHostPtr vhost;

    if (FAILED(retcode=app->CreateHostFromXaml(&xamlsrc, &wp, &vhost)))
        return -1;


The VisualHost object "hosts" the runtime and allows us to access its contents and load our XAML from resources (using the XRXamlSource object).
Now our XA
The object inside our Silverlight for Windows Embedded application are organized in a objects tree. To access the object inside it we need a pointer to its root:

    IXRFrameworkElementPtr root;

    if (FAILED(retcode=vhost->GetRootElement(&root)))
        return -1;


From the root object we can access our button using the name we assigned to it inside Expression Blend:

    IXRButtonBasePtr btn;
    
    if (FAILED(retcode=root->FindName(TEXT("MyButton"), &btn)))
        return -1;


To receive a notification when the user clicks our button we need to provide a delegate. A delegate is a pointer to a member of an istance of a C++ class that should have a specific prototype.
We can declare a simple C++ class inside our .cpp source and implement our button click event delegate inside it:

class BtnEventHandler
{
public:

    HRESULT OnClick(IXRDependencyObject* source,XRMouseButtonEventArgs* args)
    {
        MessageBox(NULL,TEXT("Click!"),TEXT("Silverlight for Windows Embedded test"),MB_OK);
        return S_OK;
    }
};


Our event handler will simply display a message box when the button is clicked.
As you can see the event handler takes two parameters. A pointer to the object that generates the event (our button) and a pointer to a structure that contains the event parameters.

To connect our event handler to the button we have to create a delegate object:

    BtnEventHandler handler;

    IXRDelegate<XRMouseButtonEventArgs>* clickdelegate;

    if (FAILED(retcode=CreateDelegate(&handler,&BtnEventHandler::OnClick,&clickdelegate)))
        return -1;

    if (FAILED(retcode=btn->AddClickEventHandler(clickdelegate)))
        return -1;


Our event handler has been connected to the button, now we can show our UI and wait that the user presses our wonderful button:

    UINT exitcode;

    if (FAILED(retcode=vhost->StartDialog(&exitcode)))
        return -1;


Our clickdelegate object is not a smart pointer, so we will have to release it explicitly:

    clickdelegate->Release();


Before we can build our subproject we need to add the include directories and the libraries needed to support Silverlight for Windows Embedded inside our application.
Open the subproject sources script by right clicking on the subproject and choosing "open".
Add includes:

INCLUDES=$(_OEMINCPATH)

and libraries:

TARGETLIBS= \
    $(_PROJECTROOT)\cesysgen\sdk\lib\$(_CPUINDPATH)\coredll.lib \
    $(_PROJECTROOT)\cesysgen\sdk\lib\$(_CPUINDPATH)\xamlruntime.lib \
    $(_PROJECTROOT)\cesysgen\sdk\lib\$(_CPUINDPATH)\uuid.lib \


(you should already have the TARGETLIBS directive inside your sources script)
Now you can run the application on your device and push that button!

You, like me, are too lazy to type sample code, you can download a zip containing our demo application here:
http://cid-9b7b0aefe3514dc5.skydrive.live.com/self.aspx/.Public/SilverlightSample.zip

You can find the next step here:
http://geekswithblogs.net/WindowsEmbeddedCookbook/archive/2009/10/11/silverlight-for-embedded-tutorial-step-2.aspx


Windows Embedded support the Italian way


The new Italian Windows Embedded support forum is now active:
http://social.microsoft.com/Forums/it-IT/windowsembeddedit/threads
Here Italian speaking users of the different Windows Embedded platforms can discuss, post their questions and, hopefully, receive good answers in their own mother tongue (and also my own mother tongue, as you can understand from the poor english of this blog!).

Windows Embedded CE SR3

Dutch cheese in Alkmaar
Windows CE SR3 has been announced today at ESC in Boston:
http://www.microsoft.com/windowsembedded/en-us/news/pressreleases/cer3_release.mspx
This new "service release" will include many new features, mostly focused around the user experience, providing more applications and better tools to develop them.
One of the most exciting new features is Silverlight for Windows Embedded:
http://www.microsoft.com/windowsembedded/en-us/products/windowsce/silverlightforwe.mspx
it's an implementation of Silverlight on embedded devices.
Now I'll be able to understand the cool Silverlight blogs of Corrado (http://blogs.ugidotnet.org/corrado/Default.aspx) and Andrea (http://blog.boschin.it/) and, maybe, learn from them how to use the new tools to provide a great UI on embedded devices. I hope to be able to show some cool samples of this technology soon.
I'll discuss about the other new features of R3 in the next days, now I'm going to finish my demos for tomorrow conference:
http://www.silverstar-celdis.it/index.php?id=949

Salmone svuotafrigo

This is a recipe that I carefully planned and designed after checking the contents of my fridge after a three weeks holiday in California.
I found some salmon at the local supermarket and I had to decide how to cook it. Olives and leeks seems the only things still edible inside my fridge.
The result tasted quite good, but my perception could have been impacted by the jet-lag... so handle this recipe carefully!

Ingredients:
- salmon (one large filet serves two people)
- leeks (200 g)
- olive oil (three table spoons)
- green olives (100 g)
- apple cider (one glass)

Drop the olive oil in a pan and heat it.
When the oil is hot, add the leeks cutted in small pieces and the olives cutted in slices.
Let them cook in the oil for a couple of minutes and then add the cider.
Reduce the heat and add the salmon cut in 2cm thick pieces and with no skin.
Cover the pan with its own cover and let the salmon cook slowly, turning it after 5 minutes and let it cook for another 10 minutes at least. Open the pan and rise the fire under it to reduce the sauce. Serve the salmon pieces covered with leeks and olives and enjoy.
If you don't like the taste... try it again after some serious jet-lagging!

Design with Freescale event

If you want to meet me in person an, maybe, learn something new about Windows Embedded CE 6.0, you can attend the "Design with Freescale" event in Milan on the 23rd of semptember.
You can discover all Freescale's solutions for embedded devices, see some cool hardware running Windows CE and other embedded operating systems and find many experts to discuss your new designs.

You can find more information about the event here: http://www.silverstar-celdis.it/index.php?id=949 (italian)