joi, 10 noiembrie 2011

WinCE C++ Silverlight Bug

Yesterday while working at my C++ Silverlight application I encountered a WinCE bug.


The problem:

We have simple Silverlight application running with two buttons: "Button 1" and "Button 2". When pressing "Button 1" I launch a Message Box using the following code sequence:

HRESULT MainPage::btnPushMe_Click (IXRDependencyObject* pSender, XRMouseButtonEventArgs* pArgs)
{
    HRESULT hr = S_OK;

    if ((NULL == pSender) || (NULL == pArgs))
    {
        hr = E_INVALIDARG;
    }

   HWND hWnd;
   IXRVisualHostPtr pVisualHost;
   App::GetVisualHost(&pVisualHost);
   pVisualHost->GetContainerHWND(&hWnd);

   MessageBox(hWnd, L"Error message", L"Error caption", MB_OK);


    return hr;

}


We click the "OK" button of the modal message box, next the Silverlight application doesn't accept any input anymore. It's like the other controls lost their handlers and when the user presses the second button nothing happens.

My assumption

I noticed that if instead of hWnd I just put zero, the message box closes and all works fine after. My logic says that it is something related with the window handler parameter. MSDN says ( http://msdn.microsoft.com/en-us/library/ee504207.aspx ) : "Use the GetContainerHWND method with caution because the handle you obtain from it is also shared with the Silverlight system." so when the message box is closed something bad happens with that HWND.

My idea it was that the parent HWND is the container HWND. If I am wrong... what owner window HWND I should pass to the MessageBox? ( http://msdn.microsoft.com/en-us/library/ee503608.aspx )

Somehow my Silverlight app window is not getting anymore Windows messages, and this is why it's not reacting.


Because one picture is like one thousand words, I attached a short video:



joi, 22 septembrie 2011

An WinCE SOAP/Webservice Client

This week I continued my Odyssey in building a thin-client (a fanless PC). After a nice user-interface the next thing I needed it was to speak with the outside world.

So, it's all about connectivity!

Yeah, connectivity on a Windows Compact Embedded 7 machine aka WinCE 7.0! Connectivity has to asspects: the physical communication medium and application level connectivity. I will talk about application connectivity.

Application connectivity means a SDK/Toolkit, an API that abstracts the communication aspects like marshaling/unmarshaling, serialization/deserialization, fault management and so on, making programming agnostic - allowing us this way to focus on our business logic: send message A from computer 1 to computer 2, without worrying about all possible technical aspects.

What do we have available in a WinCE 7 to make a SOAP call? Some will say SOAP Toolkit - I said so also first time, unfortunately Microsoft is not so generous in giving lots of documentation for it. Moreover the API is not so handy, they don't deal entirely with the serialization/deserialization process. Another possible Microsoft API from the WinCE 7 platform it could be MSXML, but I had refused to investigated after SOAP Toolkit experience.

Finally I found two possible APIs which by chance are also Open Source too, and have a permissive license: PocketSOAP and gSOAP Toolkit. Both look good but PocketSOAP it wasn't available for x86 too, I didn't had time to migrate it, so I preferred to focus on gSOAP.

gSOAP it is the choice

gSOAP Toolkit is developed and maintained by Robert A. van Engelen - professor at Florida State University and is available for download from SourceForge or as an Enterprise version from Genivia

The concept used by this toolkit is similar with the Web Reference from .net project in Visual Studio, you just add a web reference which is a path to your webservice, a tool parses the WSDL file and generates some proxy C# or Vb.Net classes that are included in your project. In a similar manner using two command prompt tools, a set of proxy classes are generated, these classes must be included in your project plus two extra files that are the engine core of this SOAP toolkit. gSOAP know how to generate pure C code if need it, and C++ with or without STL. The code is portable through multiple platforms, personally I compiled the same code on Win32 and WinCE. Another good thing is that gSOAP has a lot of documentation and good samples that you can use.

As a wishlist for gSOAP I would like to have an add-on in Visual Studio that can automate all this command prompt and integrate them automatically into my project.

Conclusion

I am sorry to say but WinCE 7 platform is lacking of a good API or Toolkit for building a SOAP/webservice client. I am wondering how Microsoft can market "The Internet of Things" with WinCE 7, since a SOAP communication it's something basic during these times?

And again: Good job Robert!

miercuri, 14 septembrie 2011

Silverlgith for Embedded #2 - Loading Dynamically UserControls

Yesterday I wanted to write a post about a classic but, fancy "Hello World!" using Silverlight for Embedded UI framework running on a WinCE 7 machine (or virtual machine). Anyway this kind of posts are already on the Internet, so after a few days of headaches I come with something else, maybe not so original, but good enough to help other people.

The idea is that I want to take the advantages of a WinCE 7 machine - low power, low form factor and build a fanless PC that can run in an industrial harsh environment with lots of dust. Moreover I want to give a resistive touchscreen (for workers' gloves) and a cool simple UI that can be used by anyone without an initial training. For me Silverlight for Embedded sounded like a valuable framework and I decided to use it, but like always the things are not as they seems to be. Yeah, that's a powerful framework built on top of OpenGL and DirectX, but not so friendly at least at first sight.

My goal was to build a full screen UI with several screens (similar to webpages) that you can navigate back and forth and insert some data in these forms to be saved in a database somewhere remote on a server. 

The first problem is how you can abstract this notion of screen and how can you make a minimal navigator? I want always to remain in the same application because I need to share some information between screens similar with the Session of a web-application.

The Session object could be a DataPool implemented with a minimal Singleton. But the core problem remains the screens and the navigation mechanism between them.

After reading and reading and walking through the samples and the generated code during project conversion from Blend 3 to Visual Studio with WEST I figured out a solution. I noticed that in fact the MainPage is a UserControl that is loaded during initialization phase of the Windows application (the WinMain stuff), so my idea was to somehow dynamically load user controls. 


My first attempt was to remove the first control created during initialization process and replaced with a new UserControl, but this approach even if it was a good idea as a principle was a failure. Probably it's still technically possible but is too complicated and unsafe, so I realized that is a dead end.


The approach was to keep the skeleton of the application as it was generated by Microsoft guys and find something else. So I added two more controls in the Blend 3 project, as it can be seen in the following image:


So, the App.xaml belongs to Microsoft and we don't have to touch it, the MainPage.xaml will act as a main container where all the other UserControls are going to be loaded. For the sake of this demonstration I created two UserControls: UserControl1.xaml and UserControl2.xaml, they will be the children of MainPage.xaml.


Next step is to go in MainPage.xaml and design it in a manner that can load these two controls like in the next picture:




As you can I split the LayoutRoot which is a grid in two rows and in the upper row I placed a navigation bar with two simple buttons: "Load Control 1" and "Load Control 2". The lower row is going to be the place holder of the dynamic loaded UserContols, for this purpose I added a new Grid with one row and one cell named "HostGrid".


For readability purposes UserControl1 is a big red square, while UserControl2 is blue.
Next step is to go in Visual Studio, create a new Silverlight for Embedded project and import the Blend 3 project. We open MainPage.xaml and from Windows Embedded Events window we will select btnCtrl1 and attach a handler to the Click event, the same will be done to btnCtrl2. We will write the following code-snippet:


// ============================================================================
//  btnCtrl1_Click
// 
//  Description: Event handler implementation
//
//  Parameters:  pSender - The dependency object that raised the click event.
//               pArgs - Event specific arguments.
// ============================================================================
HRESULT MainPage::btnCtrl1_Click (IXRDependencyObject* pSender, XRMouseButtonEventArgs* pArgs)
{
    HRESULT hr = E_NOTIMPL;

    if ((NULL == pSender) || (NULL == pArgs))
    {
        hr = E_INVALIDARG;
    }

    IXRFrameworkElementPtr pRoot;
    IXRVisualHostPtr pVisualHost;
    App::GetVisualHost(&pVisualHost);

    pVisualHost->GetRootElement(&pRoot);

    XRPtr pControlTemp;
    pRoot->FindName(L"UserControl1", &pControlTemp);

    XRPtr pControlTemp2;
    pRoot->FindName(L"UserControl2", &pControlTemp2);

    if (pControlTemp2)
    {
        pControlTemp2->SetVisibility(XRVisibility_Collapsed);
    }

    if (0 == pControlTemp)
    {
        IXRGridPtr pGrid;
        pRoot->FindName(L"HostGrid", &pGrid);

        IXRUIElementCollectionPtr pCollection;
        pGrid->GetChildren(&pCollection);

        IXRApplicationPtr pApplication;
        App::GetApplication(&pApplication);

        XRPtr pControl;
        hr = pApplication->CreateObject(__uuidof(UserControl1),&pControl);
        pControl->SetName((TEXT("UserControl1")));

        pCollection->Add(pControl, NULL);
    }
    else
    {
        pControlTemp->SetVisibility(XRVisibility_Visible);
    }

    return hr;
}


As you can see first I am getting the root element, and we look for UserControl1 and UserControl2. If UserControl2 was found we set the visibility collapsed, since we want to display UserControl1. 
The next step is to check if UserControl1 was created and if yes set it on Visible, otherwise create it and display it. I think the code is self describing. In MainPage.cpp I included UserControl1.h and UserControl2.h

First Control loaded



Second Control loaded
Above are two print-screens from a WinCE 7 running inside a Virtual PC machine, when we press first button it is loaded UserControl1, when is pressed the second button is loaded UserControl2.


Conclusions


The solution is simple, but it can be developed. For example a nice thing to have would be a Screen Manager like a screen factory and based on some IDs to give us the instance we need. The code can be refactored the creation of the screen and the check that if already exists or not is the same for any screen so we could have it in a helper class.


Another possible improvement would be to move the navigation structure in an XML file, and validate somehow the transitions from screen to screen. Having this for complex HMIs we could think for using a finite-state machine like IBM Rational Rapsody OXF framework.


The developer should evaluate if it worth to keep all the screens in memory or not. It depends on the memory of the device, the number of screens and the size in memory of each screen. Personally if I would have a light HMI I would keep all the screens in memory for a fast user-experience.


Notes:


The code above is just an example concept and needs to be polished before ever be used in production.
The solution is based on a Microsoft WinCE 7 white-paper called: Silverlight for Windows Embedded Developer's Guide the second tutorial "Create a Custom User Control in Silverlight for Windows Embedded"
To setup a Virtual PC with WinCE 7 on it you can follow other two whitepapers:
Getting Started with Virtual CEPC
Advanced Virtual CEPC 


marți, 13 septembrie 2011

Silverlight for Embedded #1

In the following days I will publish a list of posts about Silverlight for Embedded devices. 

So, what is Silverlight for Embedded? is a UI framework like Nokia Qt developed by Microsoft for their Windows Compact Embedded 6.0 R3 and 7.0 devices. Unlike Nokia Qt is not portable and targets only WinCE 6.0/7.0. Another thing that must be mentioned is that is not a managed framework like everybody is thinking at first sight, it is a pure C++ framework on top of OpenGL and DirectX. They chose this name because it uses XAML and Microsoft Expression Blend for UI design, but it has nothing to do with the Silverlight you know: the managed browser plugin.

Actually the development flow would be like this: the designer works in Blend, later in Visual Studio using an add-on called WEST (Windows Embedded Silverlight Tools) the C# project created with Blend is imported and converted in a C++ project for WinCE. In the end it can split designer's work from developer's work, which is not a bad thing. Also because it relies on OpenGL and DirectX it allows all kind of fancy user interfaces or HMIs, with gradients, and other visual effects.

The idea is good and the framework seems to be impressive in terms of what it can do, but the bad part is that the documentation is lacking. Except a few "Hello World!" demos nothing valuable can be found across the Internet. It was an enthusiasm in March at Microsoft when they launched WinCE 7.0 to write and developed some technical resources, but in time the interest was lost. Probably like in any corporation the management decided that focus must be shifted on other projects.

I will start with a series of posts that I hope can will be useful for other people like me.

duminică, 6 martie 2011

Pensiile private in Romania

Mi-am facut un obicei in a asculta dimineatza inregistrarea din ziua anterioara a emisiunii lui Moise Guran - Biziday de la TVR 2 (ar fi grozav sa puna si de-un podcast sa il pot asculta in masina in drum spre serviciu). Ieri am aflat o informatie interesanta: faptul ca daca te incadrezi la pilonul III de pensii private poti primi o deducere fiscala de maxim 400 euro pe an din baza de impozitare. Aceasta deducere o poate primi angajatul sau angajatorul in functie de cine decide sa plateasca aceasta contributie. Frumos, idea e sa incurajezi economisirea si in acelasi timp sa oferi o perspectiva decenta la batranetze propriilor cetateni. In alte tari din Vest e mai mult dar totusi e bun si frumos si atat. Cu putin goagle pe net am gasit si un post interesant pe aceasta tema scris de Razvan Pascu pe care il puteti citi aici.

Un alt site interesant a fost cel al APAPR - Asocitatia pentru Pensiile Administrate Privat din Romania. Aici puteti gasi multe informatii utile despre fondurile de pensii private de la noi, atat pentru pilonul II cat si III. De curiozitate m-am uitat la informatiile legate de pilonul III, si un lucru m-a frapat: lista de comisioane. Ideea e ca platim tot felul de comisione acestor administratori privati ai banilor nostri, dupa cum urmeaza:

  1. Comision suportat din contributii 2,5% - adica la 10.000.000 lei colectati 250.000 lei din oficiu se duc la ei.
  2. Comisionul suportat din contributii 0,05%/luna - adica suma lunara care o vireaza angajatorul isi retin si ei un share
  3. taxa de audit - intre 250.000 si 400.000 lei pe an in functie de fond - vine o alta firma sa ii verifice ca totul e ok. Partea interesanta ca auditorii sunt cam aceasi care au auditat Enron, Lehman Brothers sau Madoff
  4. Penalitate de transfer 5% - oamenii isi fac niste planuri financiare in functie de banii tai si daca te sucesti... frate nu am mai putut atinge targeturile corporatiste asa ca platesti
  5. tarife de informare
Acum comisioanele astea ridica o problema de moralitate, in sensul ca... inteleg sa platesc daca obtii performanta si randament, dar fondurile noastre au performanta medie spre mediocra. Imi aduc aminte parabola lui Iisus cu pungile de galbeni lasate de stapan slugilor, una din slugi a ingropat punga, iar celalti doi au facut afaceri si din 2-3 pungi cat primisera facusera 5-10 pungi cu galbeni. Cand stapanul s-a intors cei ce au inmultit banii au primit, iar cel care a ingropat banii a fost alungat. Cred ca se poate ghici usor cam la ce categorie de slugi se incadreaza si administratorii nostri.

Ideea e ca ei nu fac decat sa investeasca in titluri de stat, creditand astfel statul, lucru care il putea face si statul insusi, in loc ca acesti bani sa ajunga in economia reala si sa ajute dezvoltarea locala. Spre ex o investitie desteapta ar putea fi un pod cu taxa la Braila sau Galati care in 20 ani ar intoarce profit cu varf si indesat. Ar ajuta niste constructori ar uni niste comunitati, ar dezvolta economia regionala, si contributorii ar face profit din taxa de trecere, e doar un exemplu... sunt sigur ca sunt multe alte oportunitati. In schimb noi avem niste directori grasi, corporatisti, cravatzoshi care stau in niste birouri luxoase in Bucuresti si percep comisioane.

In al doilea rand aceste banci practic sunt creditate de noi, banii in loc sa stea in Trezorerie practic s-au mutat in conturile unor banci. Altfel ar fi trebuit sa se duca prin Londra sau Frankfurt dupa lichidatati.

Mda... slugi credincioase...

miercuri, 23 februarie 2011

Dacia, Bras si Wizrom

Ieri am ajuns in service Dacia ce apartine de BRAS Iasi, pentru revizia de 60.000 de km. Distributie, pompa de apa (by the way avea floare - hey Dacia), bieleta stanga fata (multumita drumurilor lui Gheorghe Nichita primarul Esilor), in fine o suma marisoara pentru bugetele noastre romanesti. Imi fac oamenii factura si intreaba cum platiti numerar sau card? Ii raspund operatorului numerar si card. La inceput foarte ferm ca nu se poate, intrigat cer sa vina managerul service-ului si intreb de ce nu se poate domnule? Cica nu permite programul informatic.

Am platit in atea locuri cu numerar si card simultan, ce treaba au facturile cu chitantele? O factura poate avea una sau mai multe chitante :) o relatie de la (1) la (1..n) pentru cei care se pricep la baze de date. Dar se pare ca analistii de la Wizrom nu s-au gandit la aceasta posibilitate. Contrar la tuturor chestiilor frumoase de pe site-ul lor nu pera si-au inteles clientii. So be wise, inainte de a cumpara un ERP de la Wizrom.

In cele din urma am rezolvat problema in mod clasic: chitanta de mana pentru numerar si chitanta separata de la POS :), iar maretzul sistem ERP implementat la nivel national de Wizrom pentru Dacia la folosit doar pt generat factura.

Noi sa fim sanatosi - fatum

luni, 21 februarie 2011

The Weakest Link Property

Zilele astea citesc cartea "Practical Criptography" scrisa de Bruce Schneier si Neil Ferguson, citesc destul de rar o carte "computer science" cap-coada, de regula le studiez pe sarite in functie de ce am nevoie. Este o lectura captivanta, iar ca si voie a sortii :) semnul meu de carte este o foaie din vinul.ro cu o reclama pentru fatum.

Despre mine

Fotografia mea
Just another guy from the old city of Iaşi