Wednesday, January 28, 2009

How to add custom data to an AutomationPeer

In a recent project, we needed to provide extra data through Automation in order to achieve more rigorous testing. We wanted some of our own properties and data types unrelated to the available control patterns and properties.

After spending some time searching for a mechanism to add new properties we came to the conclusion that there wasn't one - the only choice is to hijack an existing property. As far as I can tell the only automation property you're allowed to put whatever you want in is ItemStatus.

The MSDN page for ItemStatus says:
  • Gets or sets a description of the status of an item within an element.
  • This property enables a client to ascertain whether an element is conveying status about an item. For example, an item associated with a contact in a messaging application might be "Busy" or "Connected".
That sounds pretty hijackable to me.

ItemStatus is hidden by default in UISpy but you can show it by going to:
View -> Configure Properties -> AutomationElement -> Misc

You set it in your automation peer by overriding GetItemStatusCore(). You can then serialize any type and send it through:
public class Window1AutomationPeer : WindowAutomationPeer
{
    public Window1AutomationPeer(Window1 owner)
        : base(owner)
    {
    }

    protected override string GetItemStatusCore()
    {
        // use XmlSerializer to serialize custom data
        
        XmlSerializer serializer = new XmlSerializer(typeof(CustomData));
        CustomData data = new CustomData(...);
        StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
        serializer.Serialize(stringWriter, data);
        return stringWriter.ToString();
    }
}

The example contains a working example complete with app, automation-client and XML serialization.



0 comments: