WinRT Extensions using RuntimeBroker

by clovett15. December 2015 11:24

Have you ever wanted to do something naughty from your lovely well behaved sandboxed WinRT application?  Do you need to call some Win32 API that you don’t have permission to do from WinRT?

Well WinRT itself does this using a separate service called the RuntimeBroker.  Many WinRT objects use RPC to call into this broker process and do those things that need elevated priviledges.

I built a sample application that shows how to do this.  Essentially it goes something like this:

  1. Create a static C++ library containing a MIDL interface and compile it using /winrt to make it a windows runtime (WinRT) interface. 
  2. This generates RPC proxy stuff needed to marshal the interface across processes.  Compile this into a new C++ DLL called “YourInterface.ProxyStub.dll”.  You will register this dll using regsvr32 and this is needed for RPC to work.
  3. Next create a Universal C++ DLL called “YourInterfaceBroker.dll” – this will contain the implementation of the interface and is designed to run in the RuntimeBroker process.  This DLL will be able to call out to Win32 and do interesting things.
  4. Register the broker using a custom registry script.
  5. Lastly create a C# Blank Universal WinRT application to test out your new interface, referencing the *.winmd that was generated by step 1.  When you instantiate your new runtime class it is loaded into the RuntimeBroker process, and your C# app gets back the client proxy to it so each call to that object is marshalled automatically to the RuntimeBroker. 

 See the sample code:

MIDL Interface Library

In my sample I started with this static C++ library, I added a MIDL file called Microsoft.Service.Sample.idl, this defines the name of the *.winmd so its namespace has to match the filename.  I then used the MIDL Tab in the C++ properties to turn on “Enable Windows Runtime” /winrt compile option.  The *.winmd file is placed in the project output directory. I built it once and this also generates a dlldata.c and *_i.c and *_p.c files.  I added those files to the project.  To compile them it is easier if you just turn off the C++ option for precompiled headers.  I also added the C++ preprocessor defines: WIN32;_WINDOWS;.  So now you have a static library containing the RPC stubs needed later.  For the purposes of this sample app I defined the following simple WinRT interface and runtime class:

#ifndef NTDDI_WIN8
#define NTDDI_WIN8                          0x06020000
namespace Microsoft
    namespace Service
        namespace Sample
            interface IMyService : IInspectable
                HRESULT DoSomethingFun();
            runtimeclass MyService
                [default] interface IMyService;



I then added a C++ Win32 DLL project called MyService.ProxyStub.  This dll has to include the above files again, but this time with the C++ preprocessor definition “REGISTER_PROXY_DLL”, and you need to generate a new GUID for your runtime class id (different from the one in the MIDL file) in a new ProxyEntry.c file as follows:

// {62C41977-4CCC-4D4E-9C8C-A842DB7182E6}

#definePROXY_CLSID_IS { 0x62c41977, 0x4ccc, 0x4d4e,{ 0x9c, 0x8c, 0xa8, 0x42, 0xdb, 0x71, 0x82, 0xe6 } };












This is also easier to compile if you turn off precompiled headers.  You also need to add a Modile Definition file for the DLL containing:

    DllGetClassObject           PRIVATE
    DllCanUnloadNow             PRIVATE
    DllRegisterServer           PRIVATE
    DllUnregisterServer         PRIVATE


You’ll also need to add a VC++ Include Directory pointing at your interface static lib directory where the dlldata.c and *_i.c and *_p.c files got generated.  You will also need to add the linker input “rpcrt4.lib”.  This generates the proxy stub needed for RPC to work.  This dll will be registered using regsvr32.


Next I added a Universal C++ DLL project called “MyServiceBroker”.  I added a reference to the static library project, I included #include<ObjIdl.h>in the pch.h file and again added the VC++ include directory where the *_h.h file was generated.  I wanted this DLL to work on the IoT SKU of Windows 10, which is why I used Universal DLL, but I want to run this outside an app container so I removed the following from the *.vcxproj file: <AppContainerApplication>true</AppContainerApplication>.  I also added the following linker instructions to each <Link> section:
    <IgnoreSpecificDefaultLibraries>comsuppwd.lib; comsuppw.lib; kernel32.lib; ole32.lib; user32.lib</IgnoreSpecificDefaultLibraries>
AdditionalDependencies>Wlanapi.lib;mincore.lib;onecoreuap.lib; WindowsApp.lib;</AdditionalDependencies>

Lastly I added the a class that implements my new interface as follows:


namespace Microsoft
namespace Service
namespace Sample
classCMyService : public Microsoft::WRL::RuntimeClass<ABI::Microsoft::Service::Sample::IMyService, Microsoft::WRL::FtmBase>
InspectableClass(RuntimeClass_Microsoft_Service_Sample_MyService, PartialTrust);



constCMyService& operator = (constCMyService&);


Then I added an empty implementation the the .cpp file.  I also replaced the contents of the dllmain.cpp file with the following:


using namespace Microsoft::WRL;

STDAPI DllGetActivationFactory(_In_HSTRINGactivatableClassId, _COM_Outptr_IActivationFactory **factory)
return Module<ModuleType::InProcDisableCaching>::GetModule().GetActivationFactory(activatableClassId, factory);

DllGetClassObject(_In_REFCLSIDrclsid, _In_REFIIDriid, _Outptr_LPVOIDFAR* ppv)
return Module<ModuleType::InProcDisableCaching>::GetModule().GetClassObject(rclsid, riid, ppv);

STDAPI DllCanUnloadNow()
if (Module<ModuleType::InProcDisableCaching>::GetModule().GetObjectCount() == 0)
        hr =
return hr;

STDAPI_(void) DllAddRef()

STDAPI_(void) DllRelease()

STDAPI_(BOOL) DllMain(_In_opt_HINSTANCEhinst, DWORDreason, _In_opt_void*)
if (reason == DLL_PROCESS_ATTACH)
return TRUE;


To register the broker I created a custom registry script containing the following.  Notice the GUID used here matches the one I generated for the ProxyEntry.c file earlier.

Windows Registry Editor Version 5.00



Running this from administrator command prompt makes it possible for WinRT to construct your runtime class.  You may need to take ownership of the WindowsRuntime part of the registry in order to do this.  There is a tool floating around called TakeRegistryAdminOwnership.exe that can help with this.

You may also need to install the VC++ debug C++ runtime bits (vcruntime140d.dll and ucrtbased.dll) if you have not already installed that on your test machine.  Use depends.exe to find out what else the proxy and broker are dependent on if they still refuse to load.

C# App

To test out my new brokered service I created a blank C# windows application and added a reference to the generated Microsoft.Service.Sample.winmd file, then added the following lines:

            var service = new Microsoft.Service.Sample.MyService();

When you run these lines the MyServiceBroker.dll is loaded into the RuntimeBroker.exe process (you can attach to that process using your VS debugger and watch it happen and you can debug your broker that way also).  You will see RPC stuff on the stack when the DoSomethingFun call comes in.  Don't worry about terminating the RuntimeBroker.exe process, it will auto-restart.


If you need to have your broker do something async and call back to your C# application later you can easily define a new interface, implement that in C# and pass it to your broker as an argument, then the broker can call that interface.  This RPC interface will “timeout” after a minute, so you may need to repeat that process periodically or do a heartbeat kind of thing to keep it alive.  You could build a WinRT component project that wraps all this and exposes a new “Client” interface that turns all this callback stuff into C++/CX events so that it is easier to consume in your C# applications.  Your “Client” interface could also expose C++/CX properties and events so you have a nice modern interface to your new broker. 




Tools | Windows Store Apps

Efergy Alljoyn Fun

by clovett13. May 2015 12:58

Alex Kelly showed me this really cool project by Nathaniel Elijah where he used a software defined radio to decode the power data from an Efergy power monitor.  So I had some fun adding an AllJoyn wrapper on that so that my Raspberry Pi can act as an Alljoyn sensor which I can then easily connect to using my PC where I can grab the data and have fun with it in C#.



See Demo Video (27mb)


Magic LED Lights Rock

by clovett6. January 2015 06:23

I had some fun over the Christmas holiday playing with my new toy, Magic LED Lights.  These are controlled from your phone using Bluetooth Low Energy.  But as is often the case there was no Windows Phone app for these, so hey, it was the holidays, I had some time, so I built one.  Actually, I built a Windows Phone app and a Windows 8 app.  It is implemented in C# and most of the code is shared between the two apps.

See Demo Video of bluetooth lights and Wifi Demo Video for wifi lights.  So far the light bulb has worked perfectly!   You can get more information from the manufacturer at  

Of course, this is just the beginning.  Imagine the lights turn on when I walk into my office.  Or the XBox controls the lights so they turn red when I get shot in Halo. There are many fun applications of this really simple but very cool new tool.


Update to XML Notepad

by clovett30. November 2014 00:55

As  XML has exploded across the planet I continue to get many requests for improvements to my XML Notepad of 2007.  The tool has been downloaded over a million times, so I figured it's time to show it some love and fix some bugs.  In the process I updated it to NET 4.0 using VS 2013.  I was amazed how everything from back then still works, including the Unit Tests.  That is pretty amazing platform compatibility.  Windows is a great platform and Visual Studio is still best of breed for software development, and I still love C#.

See Download


Tools | XML

Seismograph App

by clovett3. April 2014 11:47

I built a simple app called Seismograph to visualize the accelerometer data on my phone.  The reason I built this is because I wanted a simple way to check the vibration of the motors on my quadrocopter.  I saw some really nice apps for android, but all the windows phone accelerometer apps were crap.  So I built my own :-) 

I then ported this Seismograph for Windows RT so I could also run it on my Surface device.  When I did that port I discovered that the same approach to graphing the data didn't work well on a bigger screen, it slowed down way too much.  So I had to re-implement the scrolling graph control.  Previously I was building a new PathFigure with the new points scaled to fit the screen, and so each frame was a new Path object and that's how it would scroll across the screen.  Turns out the performance is a lot better if I reuse the PathFigure and only add to the Path object and never remove any points, and rarely re-scale the points.  But in order to scroll then I needed to adjust the canvas position of the path to the left, well turns out I can do the scrolling at a higher rate than the point adding which results in a very smooth scroll which looks great.  The problem is I would run out of memory if I never removed points, so what I do is cycle two Path objects, when one is completely offscreen on the left, I recycle it and use it on the right, and this is how I get really nice performance on the Surface.  So I back ported that to the phone and it looks great there too.

Privacy Policy

The app records the accelerometer sensor data so that you can choose to save it locally on your device either in a bitmap image or in an XML file.  The app does not send your data anywhere else, so the data is not shared with anyone.  You can choose to send the bitmap image or the XML file to someone else, but that is up to you.  The app does not even know if you have shared your data with anyone.


Windows Phone | Windows Store Apps | XAML

Outlook Sync

by clovett9. January 2014 23:56

UPDATE: Microsoft made me change the name of my app from "Outlook Sync" to "Sync for Outlook".  In order to get this new version which has some other fixes as well, please uninstall "Outlook Sync" and install the new version below, thanks.

So a friend of mine was thinking of ditching is iPhone and trying Windows Phone, but couldn’t find a way to sync his PC Outlook Contacts with Windows Phone without pushing everything up to  He didn’t want to do that.  He came to me and asked why Apple can sync Outlook directly but Microsoft’s own Windows Phone can’t?  Well, I took it as a challenge J

Turns out it is not that hard to do.  First you will need to install the Phone App, the following link will take you to the app store:

Sync for Outlook, Windows Phone App

The second step is to install the following app on your Windows PC where you have Outlook installed:

Outlook Sync

(*This is a ClickOnce link, you cannot download it and run it locally - for security reasons).  So if you are using Chrome you may need to first get this ClickOnce Chrome extension).

See my demo video below:

            Demo Video

This is a Click Once app what should work on Windows 7 or Windows 8 and on Windows 8 you will see the following popup from Windows:

click More Info and you will see the following: 

Click Run Anyway and after the app launches you will see this Firewall alert.  The app needs to be able to receive requests to sync from your Phone over wifi, so checking both boxes on this alert will allow that to happen:

Now when you launch the Phone version of the app it will connect to your PC over wifi and you should see the following:

If this is your phone, click "Sync this phone" to give it permission to push your Outlook Contacts info to your phone. Now on your phone you should see a report showing what was updated, here we see we received 4 new contacts, 2 were updated, and 2 were deleted.

The new contacts will show up in your People Hub:

and you can edit these contacts or delete them and the sync will pick up your changes and push that back to Outlook.  These contacts are associated with the "Outlook Sync" app, notice the account is named "Outlook Sync" below.  This means if you uninstall the app on the phone all the contacts it has downloaded to your phone that are not associated with any other account will be removed, leaving your phone in the same state it was in before you started which is nice and friendly.

I hope you enjoy it!


Windows Phone

Remote Control Phone

by clovett20. July 2013 01:18

Have you ever wanted to control your PC using your Windows Phone?  Well it turns out to be surprisingly simple to do.  I found some sample code on MSDN that plays tic-tac-toe and so I took that and made some simple changes.

See mp4 Video (12mb) 

Download Source Code:


Windows Phone

FIRST Event Planner

by clovett12. July 2013 02:20

I received an email from a friend asking for help figuring out a fun math problem.  He works for FIRST and the problem is figuring out how to match up over 400 teams in Washington State with 5 separate event locations, minimizing the driving distance for each of those teams.  Each event was happening on the same day, and each team gets to compete at only one of these events.

So I quickly cranked out a nice little Silverlight Application to do the job.  And I hooked up to the BING Mapping API to calculate the actual driving distances from each team to each event location.  Silverlight and BING worked beautifully together.  So far so good, but now for the hard part.  How do you calculate the optimal assignment of teams to events that results in minimal total driving distance?  I hacked out a brute force solution that first assigned every team to their closest venue, but then there were additional constraints that got more interesting.  Each event has a minimum and maximum capacity, so if an event was over populated, some teams had to move to the second or third closest venue.  This wasn’t too hard to code, but I quickly realized, the solution I was getting was not necessarily the best.  For example, in the diagram below, let’s say the maximum capacity for each event is 3 teams, which means team “i” needs drive all the way to “C”.  Clearly this is silly.  


It is better to move “c” to “B” and “f” to “C”, making room for “i” to join “A”, like this:

But this is a tricky “ripple” effect that is hard to find programmatically without having to essentially search all combinations of teams to events, but then I quickly realized it would take about 100 years to execute that kind of exhaustive search on my machine because 400 factorial is a large number.

So this is when I contacted Microsoft Research.  Lev Nachmanson works there and is a good friend of mine and a powerful magician when it comes to mathematics.  So I presented the problem to him, and he said he’d think about it.

In a short while I got an email back saying he had a solution.  He explained it to me over the phone, I implemented it, and it worked, finding the solution in less than a second.  I was very impressed, but I also a bit skeptical.  I couldn’t believe it could be so simple.  I went to his office to get a better understanding of how it worked.

This is how he explained it to me. The global task is to drive to the minimum the sum of the distances from teams to the events they are assigned to. To initialize a solution assign each team to their closest event, but then think of the remaining optimization problem as a type of traffic flow problem.  We will be shifting the teams between the events, so we need to consider a graph for doing this. The edges of this graph are AB, AC, and BC. (It is called a complete graph.) For example, above we moved “c” along edge AB, "f" along BC and "i" along AC. To find a solution we need to consider all paths on the complete graph that don’t repeat an edge. A path can be a cycle, like ABCA, but every edge in it should appear at most once.

To run one iteration, take a path as described above, then take the first edge of the path and shift a team along it such that shifting it along this edge “makes the least damage”. Here the total sum can even grow. Take the second edge and do the same, and do it for every edge of the path. When we are done with the path, look at the total sum. If we are lucky and it went down, we accept the move, otherwise, we discard it. When no path gives us a gain we are done!

Then how many possible paths do we have? Well in this case with 3 events there is AB, AC, BA, BC, CA, CB, ABC, ACB, BAC, BCA, CBA, CAB  plus all the cyclic versions of these: ABA, ACA, BAB, BCB, CAC, CBC, ABCA, ACBA, BACB, BCAB, CBAC, CABC, a total of 24. It is not a huge amount of paths. The last thing to do for running the algorithm fast is to know how efficiently to find a team which can be shifted along an edge with the minimal damage. The best data structure for this is a priority queue.

The end result was that on my desktop machine I could use this algorithm to find the optimal solution in sub-second times, which is fantastic.  Super thanks to Lev!   I just love it when a nice elegant algorithm makes software work really well.  As I like to say, "there's genius in simplicity".


Model Based UI Testing using DGML

by clovett2. December 2012 15:33

Video: (WMV 26mb) (MP4 24mb).

Transcript: In this video  I'm going to explain how to use the DgmlTestMonitor  that I published to the Visual Studio Gallery. 

I've got a test project loaded here with some test methods and I have a DGML document.  The Directed Graph Markup Language is supported by Visual Studio 2012 and it allows me to edit these diagrams.  I created this diagram to model the user interface of an application that I'm testing.  Not only that, I have a way of executing this model and even setting breakpoints using the DgmlTestMonitor which you will find under View/Other Windows.

Now I can come in here and set a breakpoint on this node. So whenever it gets into editing transactions and editing categories  the model will stop executing.  Alright, so let’s run the test.  Notice I don’t actually have to debug the test to get these breakpoints.

1:00: This is the application that I’m testing, it’s a simple financial management tool that allows me to create bank accounts and transactions and so forth, and right there it has edited a category and so the model has paused.  So let’s go back to the application and we see it sitting on that node and if we look at the DgmlTestMonitor output we can see everything that it has done up until that point. I can even select through here and watch what it did up until that point. 

1:30: If you put Visual Studio on another monitor you will be able to watch the model executing while it’s actually testing the application.  Now that’s it’s reached this point I’m going to move the application to another monitor.  Now we can watch the model executing.  Maybe I want to stop it when it adds a transfer.  I’ll clear the previous breakpoint, tell it to resume, and off it goes. So the UI test is continuing, it’s doing various different steps.  Since I can watch the model executing I can get a feel for whether this is accurately modeling and end-user or not and I can edit the model, I can add links, I can add nodes and I can make the test do different things. 

2:15: Now in this case we hit a test bug because if we switch to the Test Explorer we see the test terminated when it was trying to set the date on a transaction.  Now it turns out this is a product bug, sometimes setting the date is a little flakey.  This is the kind of thing that model based testing is really good at, finding edge conditions that are really hard to find any other way, which is why I’m a big fan of model based testing.  I’m not saying this is going to replace all static testing, but I think this is a very interesting thing to add to your suite of test tools. 

2:45: Alright, a lot of magic to explain here.  How does this actually work?  Let’s take a look at the test code.  The way you do this is with in normal MSTest [TestMethod] you create a new DgmlTestModel , you give it the filename of the DGML document that you want to load and then you tell the model to run until you’re happy.  I’ve provided a Predicate that says run until 500 states have been executed.

All right, now you pass in an object to the DgmlTestModel constructor which is the target object that implements the states – so the test model is connected to my code.  If I double click this node it will take me to that method and this is the implementation of editing a category.  Notice that there’s lots of random number generation going on, some keystrokes to tab through various fields until it finds the category and so on.

3:43: This framework doesn’t change how you build test wrappers, you could use the CodedUI, I created these wrappers so I could automate, using System.Automation, the user interface of my application.   What’s new here is the way you can actually visually define the states that you want to travel through and the links that connect the states.  So when I edit a category I can go over here or I can go down there and the test model execution decides randomly which of these paths to take that have multiple choices. 

4:15: When you create a group you can encapsulate the complexity of editing transactions and you can define an entrypoint, so a node that has the EntryPoint Category which you can define using the property window, you can add the entry points.  You can also have entry points that are mutually exclusive, so if you choose this one, don’t choose that one and so that has a category on it saying it is a singleton.  You can define predicates on a link, so you can add link labels “IsSecuritySelected” we see that’s just a implemented as a Boolean  property.  You can implement all kinds of state machinery in your Boolean properties which will then guide the test in the right way.  For example, IsAccountSelected, or IsEditable and so forth.  So all of these things can encode various state about what your application is doing to make sure your test model doesn’t get stuck in a weird state and try to do something that’s invalid. 

5:16: Now since it is random, you’ll want to also be able to reproduce a failure and if you scroll to the bottom of the test output and you will see the “Model Seed = 3122235”.  This number is the seed to the random number generator.  If I plug this number in I will get the exactly the same test sequence that I got before.  So basically you can create a static test by just copying down these seeds, which is a pretty low maintenance way of creating static regression tests.

5:43: Ok, let’s edit this model and see if we can make some changes here.  So when we edit the payee we can go to SalesTax, or Deposit or Payment.  Well maybe I always want to have salestax, so I just delete those links and maybe I want to have the memo field be optional, so instead of always going from EditCategory to EditMemo, I’ll give it one more route from there to SelectTransaction and now I will only have EditMemo sometimes.  That’s it, that’s all you have to do, save the document and re-run the test.  Ok, we see it now adding a new transaction, that time it added a memo, this time it didn’t, this time it did, and now it added a transfer and it stopped, so let’s see what happened.

6:43: Ah, that’s because we have a breakpoint on AddTransfer, remember?  So I can go to the DgmlTestMonitor and we can see that it hit a breakpoint on that node and I can tell it to resume running the test.  You can also pause the test at any time, using the pause button, which is handy for a UI test because often interrupting a UI test is kind of tricky but when you tell the model to pause it’s usually in a pretty good place. 

7:18: Alright, so, one more thing and that is you can modify the thickness of these links.  If you go to the Property Window this link has a priority of 10 which means it’s going to pick that link more often than this link with Priority 1.  This way you can weight the model so that it’s doing various things in a way that’s similar to the way a real user would use your product. 

7:40: Lastly, when the model enters a group, like View Categories, notice there’s no exit links from SelectCategory.  Just to make it simple to create these models what happens when it hits a leaf node that has no exit, it will jump back up to the parent group and it will use any exit links that the parent has, and if the parent doesn’t have any exit links then it will go back to the root and look for an entry point there, and re-entry the model at the root and keep executing from there.  So that makes it easy, you don’t have to specify all possible exit routes and it makes your model a little bit simpler. 

8:18: That’s it!  I hope you like it.  I’ve posted a blog on my website, and in there you’ll see a readme that points to the source code that you can download so you can play with it, including sample code on how to wire it up and also documentation on this class, DgmlTestModel.  You will find DgmlTestModel and also the NamedPipeReader that listens to the model while it’s executing in case you want to build your own user interface. 

Thanks for watching!





Software Trails

by clovett7. September 2012 16:11

Video: (WMV 33mb)


Download Tool: SoftwareTrails.application


Have you ever wanted to see what is going on in your program in real time?  I built a light weight profiling tool that shows you exactly that. Let me show you how it works.  To get started you click the Launch button and find the application you want to profile and immediately we see a bunch of activity showing what’s happening as the app launches.  This dashboard is showing a roll up across the top level Namespaces and the counters are showing the total number of function calls in each area.

You can scroll down and see everything that is going on.  We can see that there are some Microsoft namespaces, but there’s also a Walkabout namespace which happens to be the code for this application.  So I can take a look at startup again without the .NET frameworks by drilling down into the Walkabout namespace – this shows me the drill down path and the green blocks represent classes and namespaces and the white blocks represent method calls. 

So we can now see that we’re getting down to the method call level – maybe we’re interested in seeing what happens during LoadConfig and we can click that method and it will search the call information and build a conglomerate call stack graph basically showing a combination of all call stacks that it has seen involving that method Loadconfig.  And from this you can actually explore down into WPF or you can explore upwards and see what those function calls are doing.  You can also try and expand the entire graph but in this case it’s not recommended because the graph is huge.  When you’re done exploring the call stack you can close that and go back to the dashboard.

You can also Filter this information – so maybe I care about anything involving the word “Transaction” and I can see that during the launching of the application that there’s some Transactions Namespaces and I can also see that it shows up over here in the View namespace.  Let’s drill down into some controls and we see a class named TransactionView. 

At any point you can clear the buffer and start over and go back to <Home> and remember to clear the filter.  When I do that I can see that there’s actually a heart-beat going on with this application and the reason for that if I drill into the MainWindow is that there’s an OnTick method that is being fired by a DispatcherTimer. 

Ok, let’s go back over here and let me show you more about this application that I’m profiling.  Let me just disconnect for a second (you can disconnect at any time if you want to just pause the profiling).  I’m going to load some sample data into this application.  It’s basically a personal finance application like Quicken and I’m going to show you the real scenario that I’d like to debug, so now I have some sample data, the scenario that I want to debug is drag/drop – I want to find out why drag drop isn’t working in this window here.  Alright, so I can now reconnect back to that application, the profiler is ready for work, probably want to go back home, and let’s run the drag/drop scenario.  We see a lot of activity, 16 million function calls already, even after clearing the buffer, I see some stuff in the Walkabout namespace, and the System namespace, so let me apply a filter again and just search for anything containing the word “Drag”.

Now I could look at the Walkabout code, but first I want to take a look at the .NET frameworks.  So in the history of calls that we have in the buffer, this is everything that WPF does to implement Drag/Drop.  This gives me a really great place to start looking up documentation on MSDN to find out what these methods do, OnDragOver, OnDragEnter, OnDragLeave and so on, and also I see a method called DoDragDrop which sound like an interesting place to start, let’s take a look at that method, and if I look at the caller, well it’s this class called MoneyDataGrid.  So now we know the class over here in the UI is called MoneyDataGrid.

So now if we go back to the Walkabout namespace, there I can see the Controls namespace and the Views namespace and I can see the classed called MoneyDataGrid.  This is the guy that starts the drag/drop operation – so let’s remove the filter and take a closer look at everything he’s doing.  He’s getting the mouse move which begins the drag/drop operation and here we see a flag called “get_SupportDragDrop” and we see the OnQueryContinueDrag method which the MSDN documentation tells us is used by WPF to figure out whether the drag/drop operation should continue.  So let’s select OnQueryContinueDrag and see what it calls.  Now I have an excellent place to go and look in the code  - it’s in MoneyDataGrid, to find out why when I drag this window nothing happens.

Now if I clear the buffer and do it again, now I can see in real time a lot of these mouse moves come in, I see the call to get_SupportDragDrop and so on.  So being able to see in real time what’s happening, for example, when I do mouse moves, it’s is a really useful way to see what’s going on in my code.

I can also see that when I wiggle the mouse there are lots and lots of function calls, so if I’m worried about performance at all, that counter down there, plus the rollup for each Namespace is going to be a great way to figure out where I need to optimize and see if I can remove some of those calls and get better performance. 

Profiling Very Large Applications

Ok, enough of that application.  Now what about a bigger application?  I’m going to launch Visual Studio - Visual Studio consists of a huge amount of code.  I want to see what the overhead then is of the profiler in launching Visual Studio.  Already we can see all the .NET framework stuff that’s happening, and Visual Studio is already up and running in about 10 seconds.  So we can also see here that in order to launch Visual Studio it takes about 46 million function calls, but there’s only about 15 thousand unique functions.  Again, here’s the top level view, I can see the Microsoft.VisualStudio namespace, which is where all the Visual Studio code lives so I can drill down and re-run the launch scenario and I can see everything that happens in the Microsoft.VisualStudio namespace when it launches.  I can see stuff in the Platform, in the Shell, there’s some Packages, let’s see what package is doing, and drill down, and so on.

The breadcrumb toolbar allows you to go jump back up to any level that I want.  Let’s go back to VisualStudio. 
Now the same thing can be done – let’s say I want to explore a drag/drop scenario inside Visual Studio with the “Drag” filter.  First let’s clear the 50 million function call history, that was quick, and let’s load a DGML graph so we can explore drag/drop in DGML.  First off when I load the graph I can already see a bunch of classes, “GraphDragDrop”, and “DragSourceGesture” and these are getting fired up inside Visual Studio, so that’s promising.  Those things will probably add drag/drop support.  Let’s zoom in and grab one of these nodes, and do a drag/drop.  Just as before I’m able to see in real-time everything that’s happening – the DragSourceGesture did a lot of work, let’s drill into that and take a look at that again, ok, I’ve got too much stuff in my buffer, let’s clear that and do the drag/drop again, and instantly we see exactly what’s happening deep down inside Visual Studio to support that Drag/Drop operation and now I know where to find the code and set breakpoints and continue my debugging.
So I think you’ll find that this profiler scales up to some pretty big software. 


I think this tool will also make a great testing companion.  For example, if you own a document editor then there’s a special call deep down in the VS shell called “ReleaseDocument” that needs to happen when your document window is closed.  Bang, all right, so deep inside this Visual Studio namespace,  inside WindowManagement, there should be a call to ReleaseDocument.  If that doesn’t happen you have a pretty bad memory leak in your editor.  So this tool is a great way to do an ad hoc test that certain things are happening when they are supposed to.

That’s it, I hope you enjoy it, please send your comments to my blog.

Download Tool: SoftwareTrails.application


About the author

Chris Lovett is a Software Engineer at Microsoft working on Windows Phone.

See Resume in SVG

Month List