twitter

Bonafide Ideas Rss

Featured Posts

Microsoft Visual C++ MVP Award for 2013 G’day Community, Firstly, I’d like to wish you all a happy new year 2013, full of health, blessings & success Secondly, I’m happy to announce that Microsoft has awarded me with an MVP (9th consecutive year) in the Visual C++ category, therefore I’d like to thank God, my daughter, my wife (for all of her patience & understanding),...

Read more

Analysing assemblies and finding out possible leaks... Today’s post is about… A command line utility I wrote a few days back for analysing and finding out possible leaks by not disposing of objects properly. Before we get into the nuts and bolts of the utility, please find attached two files which are: MSIL Instruction Set Specification (Required to do any MSIL manipulation) Utility’s...

Read more

CyberNanny: Remote Access via Distributed Components This article is about an application called CyberNanny, which I recently wrote to allow me to remotely see my baby daughter Miranda at home from anywhere at any time. It’s written in Visual C++ (MFC) and it comprises different technologies such as Kinect and its SDK, Windows Azure, Web services and Office automation via Outlook. The project...

Read more

DDD Sydney - Slide deck Hi community, Please feel free to grab the slides I used at DDD Sydney from here Regards,   Angel

Read more

Developer… Developer… Developer Sydney! Hi Community, I would like to invite you all to “Developer… Developer… Developer Sydney”. This event will be held at UTS on Saturday 30th June 2012. I’ll be presenting “Building Windows 8 applications natively with Visual C++”. I look forward to seeing you there. Best Regards, Angel

Read more

Traversing a DOM tree and workaround for reading attribute value in WinRT with Visual C++

Category : C++, Microsoft, Visual C++, Windows 8 Developer Preview, WinRT, XML

Hi Community,

As a follow up to my previous post. This one shows how to execute an XPATH query, loop through the nodes returned by the query, how to use a lambda to retrieve the attributes from a given node but most importantly, how to read the attribute’s value… Yes, you read the last point right. Please remember that we’re working with a preview release and some of the features are not available yet like the one I just mentioned.  Let’s get started by having a look at the code snippet below

void DataContext::ParseXml() {

 

    if (!xml->IsEmpty()) {

 

        auto doc = ref new XmlDocument;

 

        ReplaceSpecialCharactersIfAny();

 

        doc->LoadXml(xml);

 


 

        if (doc->HasChildNodes()) {

 

            items->Clear();

 

            auto names = std::vector<String^>();

 

            auto values = ref new Vector<String^>();

 

            auto nodeList = doc->SelectNodes("uiInspector/element");

 

            names.push_back("id");

 

            names.push_back("hWnd");

 

            names.push_back("text");

 

            names.push_back("className");

 

            names.push_back("parentHwnd");

 


 

            for (unsigned int nNode = 0; nNode < nodeList->Length; nNode++)

 

            {

 

                auto attributes = nodeList->Item(nNode)->Attributes;

 


 

                std::for_each(names.begin(), names.end(), [&] (String^ propertyName) {

 

                    auto attribute = attributes->GetNamedItem(propertyName)->NodeValue;

 

                    values->Append(((Windows::Foundation::IReference<String^>^) attribute)->Value);

 

                });

 


 

                items->Append(ref new UIInspector::UIElement(values));

 

            }

 

        }

 

    } else throw ref new NullReferenceException;

 

}

 

The beauty of WinRT is that COM is made easier & cleaner than before, and the developer can focus on the requirement instead of the plumbing and counting of references, as depicted in the image below  (See __cli_refcount)

image

Let’s put it this way, by instantiating an object via ref new it’s similar to do it the old fashion way in COM through a smart pointer (e.g.: CComPtr), therefore the object is less prone to memory leaks by performing automatic reference counting.

Back to our code snippet, WinRT & STL are fully compatible – Let’s remember this is native code Smile , so I put in a vector the names of the attributes I want to read, and since there’s an outer for loop responsible for iterating the XML nodes we then retrieve the attributes while looping. We use std::for_each that takes a lambda (functor) in order to read the attributes we’re interested in… So far, so good… As mentioned at the beginning, we’re working with a preview release so it’s expected to find glitches, well… One of these glitches it’s the inability to read the attribute values via the NodeValue property because it returns an object regardless of calling the ToString() method which gives us the following

+        attributes->GetNamedItem(propertyName)->NodeValue->ToString()    0x03bb9a38 0x03bb9a38 L"Windows.Foundation.IReference`1<String>"    Platform::String *

 

An object of the Windows.Foundation.IReference type and I was like Disappointed smile that’s maybe (I’m speculating now) why the XML section is missing in the preview documentation. The easiest way to solve this issue was to cast the object to the right type, and read the attribute value from the Value property.

Regards,

Angel

How to locate and replace special characters in an XML string with Visual C++ and WinRT

Category : C++, Microsoft, Windows 8 Developer Preview, WinRT, XML

Hi Community,

I hope you all had a well-deserved Christmas break  Smile

A couple of days ago I began writing an article for MSDN Magazine. The article is about Metro, Windows 8 and interop between Win32  and WinRT. One of the most frequent and error prone operation is “String manipulation”, due to the possibility of a buffer overflow, encoding, an invalid pointer or different data types – Yes… data types to represent a string, it’s not the same a char  to a wchar_t or ANSI to UNICODE.

Every Windows based on NT (2000, XP & later) natively supports UNICODE, Actually, UNICODE has been the standard ever since. In fact, every string in .NET is UNICODE and strings like every other object are allocated by VirtualAlloc.

Now back to the article I’m currently writing, in my personal case I found in XML strings a convenient way to pass information between processes & DLLs, let’s say it’s like my custom IPC mechanism, of course when the amount of information being transferred is not a huge file but more an XML representation of an given object.

Before .NET even existed, we had MSXML which is an efficient XML parser. In the WinRT world, we can manipulate XML documents via the Windows.Data.Xml.Dom namespace.

In the code snippet shown below, we got a method called ParseXml which calls another method called ReplaceSpecialCharactersIfAny.

 void DataContext::ParseXml() {

 

     if (!xml->IsEmpty()) {

 

         ReplaceSpecialCharactersIfAny(); // Replace special characters

 

         auto doc = ref new XmlDocument;

 

         doc->LoadXml(xml);

 

         //TODO: Populate our object(s) based on XML document

 

     } else throw ref new NullReferenceException;

 

 }

The implementation of ReplaceSpecialCharacterIAny is pretty straightforward, we store in a std::map the character to be replaced & the replacement string. We also reserve twice the length of the input XML string (We don’t know for certain how many replacements we’ll do, so twice the size to be used as a buffer seems to be fair enough). Then we replaced every occurrence of the special characters in the std::map and an encoded String^ is returned.

 void DataContext::ReplaceSpecialCharactersIfAny() {

 

     auto tempXml = std::basic_string<wchar_t>();

 

     tempXml.reserve(xml->Length() * 2);

 

     auto replaceChars = std::map<wchar_t, String^>();

 


 

     replaceChars.insert(std::pair<wchar_t, String^>('<',"&lt;"));

 

     replaceChars.insert(std::pair<wchar_t, String^>('>',"&gt;"));

 

     replaceChars.insert(std::pair<wchar_t, String^>('\"',"&quot;"));

 

     replaceChars.insert(std::pair<wchar_t, String^>('&',"&amp;"));

 

     replaceChars.insert(std::pair<wchar_t, String^>('\'',"&apos;"));

 


 

     for (size_t pos = 0; pos <= xml->Length(); ++pos) {

 

         auto it =  replaceChars.find(xml->Data()[pos]);

 

         if (it != replaceChars.end()) {

 

             auto newValue = (*(it._Ptr))._Myval.second->Data();

 

             tempXml.append(newValue);

 

         } else {

 

             tempXml.append(&xml->Data()[pos], 1);

 

         }

 

     }

 


 

     xml = ref new String(tempXml.c_str());

 

 }

 

Another alternative to this approach could’ve also been via Regex (but I’ll leave it to another post) or a more specialized way.

Regards,

Angel