Monday, 19 January 2015

How to add all controls on a page to the UIMap


This blog says how to add all controls on a page to the UI Map. This can be done with the following code.
Here I am adding all controls on the bing start page to the specified ui test file.

First create a UITest object from a file(i.e. empty UITest file).
You can add an empty UI Test file to your Test Project by right clicking on the Test Project and choosing Add –> New Item –> Coded UI Test Map.
UITest uiTest = UITest.Create(uiTestFileName);

The below 3 lines create a new UIMap object and adds it to UITest object
Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap newMap = new Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap();
newMap.Id = "UIMap";
uiTest.Maps.Add(newMap);

Now launch the browser, navigates to google.com and passes a reference to the browser & the UIMap object to GetAllChildren method. 
GetAllChildren(BrowserWindow.Launch(new Uri("http://bing.com")), uiTest.Maps[0];);
GetAllChildren is a method which recursively gets the children of the browser object and adds them to the UIMap.

The whole code

public void AddControlsToUIMap()
        {
string uiTestFileName = @"<LOCATION>\TestProject\UIMap.uitest";
UITest uiTest = UITest.Create(uiTestFileName);
Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap newMap = new Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap();
newMap.Id = "UIMap";
uiTest.Maps.Add(newMap);

GetAllChildren(BrowserWindow.Launch(new Uri("http://google.com/")), uiTest.Maps[0];);
             uiTest.Save(uiTestFileName);
        }

private void GetAllChildren(UITestControl uiTestControl, Microsoft.VisualStudio.TestTools.UITest.Common.UIMap.UIMap map)
        {
foreach (UITestControl child in uiTestControl.GetChildren())
            {
                map.AddUIObject((IUITechnologyElement)child.GetProperty(UITestControl.PropertyNames.UITechnologyElement));
                GetAllChildren(child, map);
            }
        }

You can now customize the code based on your need. 

If you wanted to add the Childrens of specific type, instead of GetChildren, you can use FindMatchingControls