<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Damian&#039;s Blog &#187; Debugging</title>
	<atom:link href="http://damianblog.com/category/debugging/feed/" rel="self" type="application/rss+xml" />
	<link>http://damianblog.com</link>
	<description>.NET from Geneva, Switzerland</description>
	<lastBuildDate>Fri, 30 Sep 2011 23:25:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Microsoft fixed my bug</title>
		<link>http://damianblog.com/2009/02/14/finally-an-os-bug/</link>
		<comments>http://damianblog.com/2009/02/14/finally-an-os-bug/#comments</comments>
		<pubDate>Sat, 14 Feb 2009 18:27:52 +0000</pubDate>
		<dc:creator>dmehers</dc:creator>
				<category><![CDATA[Debugging]]></category>

		<guid isPermaLink="false">http://damianblog.com/2009/02/14/finally-an-os-bug/</guid>
		<description><![CDATA[Like a lot of people, when I first began developing on a "proper" Operating System (as opposed to the 8 bit computers I started with), sooner or later I convinced myself I'd found a bug in the operating system. Of course I'd be wrong, and after suffering the embarrassment of discovering that it was my [...]]]></description>
			<content:encoded><![CDATA[<p>Like a lot of people, when I first began developing on a "proper" Operating System (as opposed to the 8 bit computers I started with), sooner or later I convinced myself I'd found a bug in the operating system.</p>
<p>Of course I'd be wrong, and after suffering the embarrassment of discovering that it was my own stupidity, rather than an OS bug, that was causing the errors, I eventually acquired an automatic reflex to never ever believe that there was a bug in the OS.&nbsp; It had to be a bug in my code.&nbsp; This was a good thing, since I was always right.</p>
<p>Despite this, it seems that I never fully learned this lesson.&nbsp; And so it was that last May I opened a <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=331513">bug report on Microsoft Connect</a>, fully expecting to be gently, but firmly rebuffed, with an explanation of where exactly I'd gone wrong.</p>
<p>The issue that I was facing was in detecting whether a connection to my web application was coming from the local machine (running the web application), or from a remote machine.&nbsp; I was calling the <a href="http://msdn.microsoft.com/en-us/library/system.net.httplistenerrequest.islocal.aspx">HttpListenerContext.Request.IsLocal</a> method, and it was always returning false, even though the client was definitely local.</p>
<p>A little digging with <a href="http://reflector.red-gate.com/Download.aspx">Reflector</a> showed that the method was implemented using "==" to compare the local address with the remote address, instead of the Equals method.&nbsp; If the "==" operator had been overloaded then it would have worked.</p>
<p>A couple of days ago, I got a message saying that this was indeed a bug, and that it was fixed in version 4.0 of the .NET framework.&nbsp; So it looks like I have finally actually discovered an honest-to-goodness bug.</p>
<p>Or perhaps they are just being kind to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://damianblog.com/2009/02/14/finally-an-os-bug/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>TraceJS V2 R.I.P.</title>
		<link>http://damianblog.com/2008/09/09/tracejs-v2-rip/</link>
		<comments>http://damianblog.com/2008/09/09/tracejs-v2-rip/#comments</comments>
		<pubDate>Tue, 09 Sep 2008 08:03:00 +0000</pubDate>
		<dc:creator>dmehers</dc:creator>
				<category><![CDATA[Debugging]]></category>

		<guid isPermaLink="false">http://damianblog.com/2008/09/09/tracejs-v2-rip/</guid>
		<description><![CDATA[A couple of years ago I posted a small blog entry on a throwaway tool that I had created that uses the Debug API to log all JavaScript that Internet Explorer executes. A year ago I decided to take a year off from consulting, mainly to spend a lot more time with our kids while [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of years ago I posted a <a href="http://damianblog.com/2006/11/23/tracejs/">small blog entry</a> on a throwaway tool that I had created that uses the Debug API to log all JavaScript that Internet Explorer executes.</p>
<p>A year ago I decided to take a year off from consulting, mainly to spend a lot more time with our kids while they are still young, but also to have some time to explore some product ideas.</p>
<p>The first idea I wanted to explore was whether or not it might be possible to extend the idea I'd had in that older blog post to actually make a commercial product that would not only trace all JavaScript, but would also show call stacks, and show how often functions were executed.</p>
<p>Technically it was tricky because I wanted my custom JavaScript debugger to be loaded in-process into Internet Explorer, since I thought that this might speed it up considerably. The secret turned out to be that I needed to pass a special flag to <a href="http://msdn.microsoft.com/en-us/library/bb147025(VS.80).aspx">IDebugProgramProvider2-&gt;GetProviderProcessData</a> (the PFLAG_DEBUGGEE flag).</p>
<p>After a couple of months of development I finally got it all working.</p>
<p>You started it from the IE Tools menu:<a href="http://www.atadore.com/images/TraceJSV2_8369/image.png">      <br /><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="234" alt="image" src="http://www.atadore.com/images/TraceJSV2_8369/image_thumb.png" width="476" border="0" /></a></p>
<p>This would create a separate TraceJS dialog: <a href="http://www.atadore.com/images/TraceJSV2_8369/image_3.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="242" alt="image" src="http://www.atadore.com/images/TraceJSV2_8369/image_thumb_3.png" width="480" border="0" /></a></p>
<p>Then as you access a page that contains JavaScript the TraceJS Window shows the statements that are being executed:<a href="http://www.atadore.com/images/TraceJSV2_8369/image_4.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="279" alt="image" src="http://www.atadore.com/images/TraceJSV2_8369/image_thumb_4.png" width="477" border="0" /></a>&#160;<a href="http://www.atadore.com/images/TraceJSV2_8369/image_5.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="244" alt="image" src="http://www.atadore.com/images/TraceJSV2_8369/image_thumb_5.png" width="484" border="0" /></a></p>
<p>Once you'd captured the JavaScript execution, you could replay the executed JavaScript, either step-by-step, or continually at a pace you define:<a href="http://www.atadore.com/images/TraceJSV2_8369/image_6.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="247" alt="image" src="http://www.atadore.com/images/TraceJSV2_8369/image_thumb_6.png" width="490" border="0" /></a></p>
<p>Finally you could&#160; drill-down to see which functions are called the most, and who calls them:<a href="http://www.atadore.com/images/TraceJSV2_8369/image_7.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="281" alt="image" src="http://www.atadore.com/images/TraceJSV2_8369/image_thumb_7.png" width="490" border="0" /></a></p>
<p>I had it all working in my initial build environment, which was XP based.&#160; Then I tested in Vista, and I couldn't get it to work&#160; (the GetProviderProcessData failed).&#160; Ouch!</p>
<p>I took a step back, gave the product a long hard look, and decided to stop development.&#160; It was too slow (despite being entirely in-process), I couldn't implement features I needed such as timing (the debugging/tracing added too much overhead), and I couldn't get it working on Vista.</p>
<p>Now that <a href="http://msdn.microsoft.com/en-gb/library/cc848895(VS.85).aspx">IE8 has similar profiling features</a> I'm happy I stopped when I did. </p>
<p>Of course the biggest mistake I made was to register the domain names for the product before it was completed (tracejs.com, jsprof.com, jsprofiler.com and javascriptprofiler.com are all mine). </p>
<p>If there is one sure way to kill a product idea it is to register domain names before you've executed on the product idea itself <img src='http://damianblog.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://damianblog.com/2008/09/09/tracejs-v2-rip/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>.NET Code Injection</title>
		<link>http://damianblog.com/2008/07/02/net-code-injection/</link>
		<comments>http://damianblog.com/2008/07/02/net-code-injection/#comments</comments>
		<pubDate>Wed, 02 Jul 2008 12:56:20 +0000</pubDate>
		<dc:creator>dmehers</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Media Center]]></category>

		<guid isPermaLink="false">http://damianblog.wordpress.com/2008/07/02/net-code-injection/</guid>
		<description><![CDATA[In this post I'll show how you can inject your own .NET code into a process that is already running the .NET framework. I needed to do this when developing for Windows Media Center because there is no official documented way to determine what page is currently being displayed in Media Center. I wanted to [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I'll show how you can inject your own .NET code into a process that is already running the .NET framework.</p>
<p>I needed to do this when developing for <a href="http://en.wikipedia.org/wiki/Windows_Media_Center" target="_blank">Windows Media Center</a> because there is no official documented way to determine what page is currently being displayed in Media Center.</p>
<p>I wanted to know when the user is showing the Media Center "now playing" page.</p>
<p>Media Center addins run in a completely separate process to the main Media Center process, which is ehshell.exe.&nbsp; Calls you make in your addin are remoted across to the Media Center ehshell.exe process.</p>
<p>The solution works using:</p>
<ul>
<li>an "Injecter" C# class&nbsp; which uses <a href="http://msdn.microsoft.com/en-us/library/ms682437.aspx" target="_blank">CreateRemoteThread</a> to load a Bootstrap DLL into the ehshell.exe process
<li>The "Bootstrap" C++ DLL which is injected into the ehshell.exe process uses the <a href="http://msdn.microsoft.com/en-us/magazine/cc163567.aspx" target="_blank">CLR Hosting API</a> to attach to the default .NET domain, and then load an instance of the "Injectee" C# class
<li>The "Injectee" C# class is loaded by the "Bootstrap" DLL and runs within the ehshell.exe process.&nbsp; It uses reflection to subscribe to an event within the ehshell.exe process and then sends an interprocess message when the event fires</li>
</ul>
<h3>The "Injecter"</h3>
<p>Using <a href="http://www.aisto.com/roeder/dotnet/" target="_blank">Reflector</a>, I looked around at the ehshell.exe assembly, and related assemblies, and eventually discovered that there is a PageChanged event fired by the ServiceBus.UIFramework.PageBasedUCPService class:</p>
<p><a href="http://damianblog.com/wp-content/uploads/2008/07/image5.png"><img style="border-width:0;" height="309" alt="image" src="http://damianblog.com/wp-content/uploads/2008/07/image-thumb5.png" width="465" border="0"></a>&nbsp;</p>
<p>What is more, there is a static PageBasedUCPService.DefaultUCP method to return a PageBasedUCPService instance.</p>
<p>There are of course a couple of problems.&nbsp; The first problem being that these classes are internal to the ehshell assembly,&nbsp; the second issue being that these are all running in a totally separate process to my addin.</p>
<p>I searched a little, and came across <a href="http://theoklibrary.org/showthread.php?p=605" target="_blank">this example</a> showing how you could use the <a href="http://msdn.microsoft.com/en-us/library/ms682437.aspx" target="_blank">CreateRemoteThread</a> from .NET to inject your own native code into a remote process.</p>
<p>Essentially it <a href="http://msdn.microsoft.com/en-us/library/ms684320(VS.85).aspx" target="_blank">opens a handle</a> to the remote process, finds the <a href="http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx" target="_blank">LoadLibrary</a> system call's address in the remote process, <a href="http://msdn.microsoft.com/en-us/library/aa366890(VS.85).aspx" target="_blank">allocates a chunk of memory</a> in the process, and fills the memory with a LoadLibrary call to load a DLL that you specify, and then creates the thread in the remote process, passing the address of the chunk of memory as the starting point for the thread.</p>
<p>I recommend taking a look at the CRT call in the <a href="http://theoklibrary.org/showthread.php?p=605" target="_blank">example</a>.&nbsp; I'll not be duplicating the code here.</p>
<p>To use the CRT call, I first find Media Center:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> Process FindMediaCenterProcess() {
  <span style="color:#008000;">// Could be more than one if an extender is running too</span>
  <span style="color:#0000ff;">foreach</span> (Process process <span style="color:#0000ff;">in</span> Process.GetProcessesByName(<span style="color:#006080;">"ehshell"</span>)) {
    <span style="color:#0000ff;">if</span> (process.SessionId == Process.GetCurrentProcess().SessionId) {
      <span style="color:#0000ff;">return</span> process;
    }
  }
  <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;
}</pre>
</div>
<p>I can then call the CRT method:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">Process mediaCenterProcess = FindMediaCenterProcess();
IntPtr hwnd;
<span style="color:#0000ff;">string</span> error;
CRT(mediaCenterProcess, dllPath, <span style="color:#0000ff;">out</span> error, <span style="color:#0000ff;">out</span> hwnd);
</pre>
</div>
<p>The dllPath is the full path to my C++ DLL, in my case this was </p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) +
                                  <span style="color:#006080;">@"\Atadore\MceFM\InjectBootstrap.dll"</span></pre>
</div>
<div>&nbsp;</div>
<h3>The "Boostrap DLL"</h3>
<p>The InjectBootstrap.dll is a pretty simple C++ library project.&nbsp; The DllMain calls a bootstrap function when the process is loaded:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    <span style="color:#0000ff;">switch</span> (ul_reason_for_call)
    {
    <span style="color:#0000ff;">case</span> DLL_PROCESS_ATTACH:
        Bootstrap();
        <span style="color:#0000ff;">break</span>;
    <span style="color:#0000ff;">case</span> DLL_THREAD_ATTACH:
    <span style="color:#0000ff;">case</span> DLL_THREAD_DETACH:
    <span style="color:#0000ff;">case</span> DLL_PROCESS_DETACH:
        <span style="color:#0000ff;">break</span>;
    }
    <span style="color:#0000ff;">return</span> TRUE;
}
</pre>
</div>
<div>&nbsp;</div>
<div>My bootstrap function attaches to the default .NET domain and loads an instance of one of my own classes:</div>
<div>&nbsp;</div>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">#include <span style="color:#006080;">"stdafx.h"</span>
#include &lt;stdio.h&gt;
#include <span style="color:#006080;">"objbase.h"</span>
#include <span style="color:#006080;">"MSCorEE.h"</span>
#import <span style="color:#006080;">"C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.tlb"</span> raw_interfaces_only
<span style="color:#0000ff;">using</span> <span style="color:#0000ff;">namespace</span> mscorlib;

<span style="color:#0000ff;">void</span> Bootstrap() {
    OutputDebugString(L<span style="color:#006080;">"MceFM Bootstrap Started"</span>);

    CoInitializeEx(0, COINIT_MULTITHREADED );
    ICorRuntimeHost* pICorRuntimeHost = 0;
    HRESULT st = CoCreateInstance(CLSID_CorRuntimeHost, 0, CLSCTX_ALL,
        IID_ICorRuntimeHost, (<span style="color:#0000ff;">void</span>**)&amp;pICorRuntimeHost);
    <span style="color:#0000ff;">if</span>(!pICorRuntimeHost) <span style="color:#0000ff;">return</span>; <span style="color:#008000;">// Clean up and log errror ...</span>

    HDOMAINENUM hEnum = NULL;
    pICorRuntimeHost-&gt;EnumDomains(&amp;hEnum);

    <span style="color:#0000ff;">if</span>(!hEnum) <span style="color:#0000ff;">return</span>; <span style="color:#008000;">// Clean up and log errror ...</span>

    IUnknown* pUunk = 0;
    st = pICorRuntimeHost-&gt;NextDomain(hEnum, &amp;pUunk);
    <span style="color:#0000ff;">if</span>(!pUunk) <span style="color:#0000ff;">return</span>; <span style="color:#008000;">// Clean up and log errror ...</span>

    _AppDomain * pCurDomain = NULL;
    st = pUunk-&gt;QueryInterface(__uuidof(_AppDomain), (VOID**)&amp;pCurDomain);
    <span style="color:#0000ff;">if</span>(!pCurDomain) <span style="color:#0000ff;">return</span>; <span style="color:#008000;">// Clean up and log errror ...</span>

    _bstr_t assemblyName =
        <span style="color:#006080;">"Last, Version=1.1.0.0, Culture=neutral, PublicKeyToken=792d614cdf38e9ce"</span>;
    _bstr_t typeName = <span style="color:#006080;">"MceFM.Last.Inject.Injectee"</span>;

    _ObjectHandle* pObjectHandle = 0;

    pCurDomain-&gt;CreateInstance(assemblyName, typeName, &amp;pObjectHandle);

}</pre>
</div>
<div>&nbsp;</div>
<h3>The "Injectee"</h3>
<p>Finally we come to the Injectee class, which is loaded by the DLL, and runs inside the remote (ehshell.exe) process.&nbsp; It is in a strongly named assembly which is stored in the GAC, so that the bootstrap call above can find it (note the strong name in the assembly name bstr).</p>
<p>I use a static constructor (which runs as soon as the class is loaded).&nbsp; In this static constructor I subscribe to the event:</p>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;"><span style="color:#0000ff;">using</span> System;
<span style="color:#0000ff;">using</span> System.Collections.Generic;
<span style="color:#0000ff;">using</span> System.Diagnostics;
<span style="color:#0000ff;">using</span> System.Net;
<span style="color:#0000ff;">using</span> System.Reflection;
<span style="color:#0000ff;">using</span> System.Reflection.Emit;
<span style="color:#0000ff;">using</span> System.Threading;

<span style="color:#0000ff;">namespace</span> MceFM.Last.Inject {
  <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> Injectee {

    <span style="color:#0000ff;">static</span> Injectee() {
      <span style="color:#0000ff;">try</span> {
        Assembly ehshell = Assembly.Load(<span style="color:#006080;">"ehshell"</span>);

        <span style="color:#008000;">// Get the PageBasedUCPService type</span>
        Type pageBasedUCPServiceType =
          ehshell.GetType(<span style="color:#006080;">"ServiceBus.UIFramework.PageBasedUCPService"</span>);

        <span style="color:#008000;">// Call static DefaultUCP method to get a PageBasedUCPService instance</span>
        <span style="color:#0000ff;">const</span> BindingFlags bindingFlags = BindingFlags.DeclaredOnly |
          BindingFlags.Static | BindingFlags.Public | BindingFlags.GetProperty;
        <span style="color:#0000ff;">object</span>[] args = <span style="color:#0000ff;">new</span> <span style="color:#0000ff;">object</span>[0];
        <span style="color:#0000ff;">object</span> defaultUCP = pageBasedUCPServiceType.InvokeMember(<span style="color:#006080;">"DefaultUCP"</span>,
          bindingFlags, <span style="color:#0000ff;">null</span>, <span style="color:#0000ff;">null</span>, args);

        <span style="color:#008000;">// Get a reference to the PageChanged event</span>
        EventInfo pageChangedEventInfo =
          pageBasedUCPServiceType.GetEvent(<span style="color:#006080;">"PageChanged"</span>);
        Type pageChangedDelegate = pageChangedEventInfo.EventHandlerType;

        <span style="color:#008000;">// Get the MethodInfo for the method to be called when the event fires</span>
        MethodInfo newPageHandlerMethodInfo =
          <span style="color:#0000ff;">typeof</span>(Injectee).GetMethod(<span style="color:#006080;">"NewPageHandler"</span>);

        <span style="color:#008000;">// Build an array of types used for new method we shall dynamically emit</span>
        Type pageType = ehshell.GetType(<span style="color:#006080;">"ServiceBus.UIFramework.Page"</span>);
        Type[] pageChangedDelegateParameters = <span style="color:#0000ff;">new</span>[] { pageType };

        <span style="color:#008000;">// Need a dynamic method because we can't create a method that has</span>
        <span style="color:#008000;">// the Page type as a parameter</span>
        DynamicMethod dynamicHandler = <span style="color:#0000ff;">new</span> DynamicMethod(<span style="color:#006080;">""</span>, <span style="color:#0000ff;">null</span>,
          pageChangedDelegateParameters, <span style="color:#0000ff;">typeof</span>(Injectee));
        ILGenerator ilgen = dynamicHandler.GetILGenerator();
        ilgen.Emit(OpCodes.Nop);
        ilgen.Emit(OpCodes.Ldarg_0);
        ilgen.Emit(OpCodes.Call, newPageHandlerMethodInfo);
        ilgen.Emit(OpCodes.Nop);
        ilgen.Emit(OpCodes.Ret);

        <span style="color:#0000ff;">if</span>(pageChangedDelegate != <span style="color:#0000ff;">null</span>) {
          <span style="color:#008000;">// Subscribe to the event</span>
          Delegate dEmitted = dynamicHandler.CreateDelegate(pageChangedDelegate);
          pageChangedEventInfo.GetAddMethod().Invoke(defaultUCP,
                                                     <span style="color:#0000ff;">new</span> <span style="color:#0000ff;">object</span>[] {dEmitted});
        }
      } <span style="color:#0000ff;">catch</span>(Exception ex) {
        Trace.TraceError(<span style="color:#006080;">"Unexpected error in Injectee initializer: {0}"</span>, ex);
        Trace.TraceError(ex.StackTrace);
      }
    }

    <span style="color:#008000;">// Queue of new pages that have been navigated to.  Decouples event handler</span>
    <span style="color:#008000;">// from re-despatching of the event to the addin process that is told</span>
    <span style="color:#008000;">// of the new event.</span>
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">readonly</span> Queue&lt;<span style="color:#0000ff;">string</span>&gt; newPages = <span style="color:#0000ff;">new</span> Queue&lt;<span style="color:#0000ff;">string</span>&gt;();

    <span style="color:#008000;">// Indicates whether background thread that despatches events is running</span>
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">bool</span> notifierActive;

    <span style="color:#008000;">// Called when Media Center navigates to a new page</span>
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> NewPageHandler(<span style="color:#0000ff;">object</span> page) {
      Trace.TraceInformation(<span style="color:#006080;">"New Page: "</span> + page);
      <span style="color:#0000ff;">lock</span>(newPages) {
        <span style="color:#0000ff;">if</span>(!notifierActive) {
          Thread thread = <span style="color:#0000ff;">new</span> Thread(NewPageNotifier) {IsBackground = <span style="color:#0000ff;">true</span>};
          thread.Start();
          notifierActive = <span style="color:#0000ff;">true</span>;
        }
        newPages.Enqueue(page.GetType().FullName);
        Monitor.Pulse(newPages);
      }
    }

    <span style="color:#008000;">// Thread that despatches events to addin process telling it that</span>
    <span style="color:#008000;">// a new page has been navigated to</span>
    <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">void</span> NewPageNotifier() {
      <span style="color:#0000ff;">while</span>(<span style="color:#0000ff;">true</span>) {
        <span style="color:#0000ff;">string</span> page;

        <span style="color:#0000ff;">lock</span>(newPages) {
          <span style="color:#0000ff;">while</span>(newPages.Count == 0) {
            Monitor.Wait(newPages);
          }
          page = newPages.Dequeue();
        }

        <span style="color:#0000ff;">try</span> {
          <span style="color:#008000;">// Use whatever interprocess notification mechanism you wish.</span>
          <span style="color:#008000;">// WCF could be good.  Here I use a simple web call.  My</span>
          <span style="color:#008000;">// addin has a web server in it to receive these calls.</span>
          WebClient webClient = <span style="color:#0000ff;">new</span> WebClient();
          webClient.QueryString[Server.PAGE_QUERY_STRING] = page;
          webClient.DownloadString(Util.LocalBaseUrl
                                   + Server.MCE_PAGE_CHANGED_ACTION);
        } <span style="color:#0000ff;">catch</span> (Exception ex) {
          Trace.TraceError(<span style="color:#006080;">"Error while sending new page notification: {0}"</span>, ex);
        }
      }
<span style="color:#cc6633;">#pragma</span> warning disable FunctionNeverReturns
    }
<span style="color:#cc6633;">#pragma</span> warning restore FunctionNeverReturns
  }
}</pre>
</div>
<div>&nbsp;</div>
<h3>The Result</h3>
<p>In my web server running within my addin (which is notified by the "NewPageNotifier" method above), I keep track of which is the current page, and log information when the page changes:</p>
<div>&nbsp;</div>
<div>
<pre style="font-size:8pt;overflow:visible;width:100%;color:black;line-height:12pt;font-family:consolas, 'Courier New', courier, monospace;background-color:#f4f4f4;border-style:none;margin:0;padding:0;">Server notified of page change MediaCenter.Audio.AudioNowPlayingPage
Server notified of page change MediaCenter.Audio.AudioNowPlayingTracklistPage
</pre>
</div>
<p>All this means that if you are a Last.fm user and want to tell Last.fm that you love a track that is currently playing then you can press the right-button on your remote control on the "now playing" page using my <a href="http://www.mcefm.com/" target="_blank">MceFM addin</a>.</p>
<p>I use low level system hooks to know when you press the right button, and the above technique to know that you are on the "now playing" page:</p>
<p><a href="http://damianblog.com/wp-content/uploads/2008/07/image11.png"><img style="border-width:0;" height="380" alt="image" src="http://damianblog.com/wp-content/uploads/2008/07/image-thumb11.png" width="476" border="0"></a></p>
<p><strong>Word if warning</strong>.&nbsp; If/When Media Center changes its internal structure this technique will completely fall over.&nbsp; Use sparingly, entirely at your own risk,&nbsp; to do the seemingly impossible.</p>
]]></content:encoded>
			<wfw:commentRss>http://damianblog.com/2008/07/02/net-code-injection/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Using mdbg to debug at the MSIL level instead of assembly code.</title>
		<link>http://damianblog.com/2008/06/12/using-mdbg-to-debug-at-the-il-level-instead-of-assembly-code/</link>
		<comments>http://damianblog.com/2008/06/12/using-mdbg-to-debug-at-the-il-level-instead-of-assembly-code/#comments</comments>
		<pubDate>Thu, 12 Jun 2008 10:32:13 +0000</pubDate>
		<dc:creator>dmehers</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Media Center]]></category>

		<guid isPermaLink="false">http://damianblog.wordpress.com/2008/06/12/using-mdbg-to-debug-at-the-il-level-instead-of-assembly-code/</guid>
		<description><![CDATA[Windows Media Center (MCE) lets you create addins to provide new functionality.&#160; There are two kinds of addins -- normal addins, and background addins.&#160; Background addins run continuously as soon as MCE starts up, and are limited in the user-interaction they provide. One thing they are allowed to do is to pop up a dialog [...]]]></description>
			<content:encoded><![CDATA[<p>Windows Media Center (MCE) lets you create addins to provide new functionality.&nbsp; There are two kinds of addins -- normal addins, and background addins.&nbsp; Background addins run continuously as soon as MCE starts up, and are limited in the user-interaction they provide.</p>
<p>One thing they <em>are</em> allowed to do is to pop up a dialog message to the user using the <em>AddInHost.Current.MediaCenterEnvironment.Dialog(...)</em> method call.</p>
<p>I was doing this in my background addin, but I was getting an error from MCE saying that I was not allowed to make that call.</p>
<p>Addins run in separate processes to the main MCE process, which is ehshell.exe, and the Dialog call is remoted into the ehshell.exe process.</p>
<p>Using <a href="http://en.wikipedia.org/wiki/.NET_Reflector" target="_blank">Reflector</a> I could see that the call was eventually failing in <em>MediaCenter.Extensibility.ExtensibilityAutomation.EnforceApplicationPermission(...) </em>which was calling through to<em> Microsoft.MediaCenter.Hosting.Infrastructure.RegisteredApps.IsBackgroundEntryPoint</em> which looks like this:</p>
<p><font face="Courier New" size="2">public static bool IsBackgroundEntryPoint(ExtensibilityEntryPointInfo epi)<br />{<br />&nbsp;&nbsp;&nbsp; return (0 == string.Compare(epi.Category, "Background", true,<br />CultureInfo.InvariantCulture));<br />} </font></p>
<p>Somehow I needed a way to use the debugger to see what the <em>epi.Category</em> value was when the call was failing.</p>
<p>The standard Visual Studio debugger just drops you through to x86 assembly code if it has no debugging symbols.&nbsp; I needed a debugger which shows <a href="http://en.wikipedia.org/wiki/Common_Intermediate_Language" target="_blank">.NET IL</a> instead.</p>
<p>This is where <a href="http://msdn.microsoft.com/en-us/library/ms229861.aspx" target="_blank">mdbg</a> comes in. Mdbg is a command line debugger created by <a href="http://blogs.msdn.com/jmstall/" target="_blank">Mike Stall</a>.</p>
<p>Once you have <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=38449a42-6b7a-4e28-80ce-c55645ab1310&amp;displaylang=en" target="_blank">downloaded</a> it and started running it, then you can use the '<strong>a</strong>' command to list available processes, and then <strong>'a &lt;pid&gt;</strong>' to attach to a specific process.</p>
<p>Once attached, you can set a breakpoint using '<strong>br &lt;module name&gt;!&lt;type&gt;.&lt;method name&gt;</strong>", and then '<strong>go</strong>' to resume:</p>
<p><a href="http://damianblog.com/wp-content/uploads/2008/06/image7.png"><img style="border-width:0;" height="214" alt="image" src="http://damianblog.com/wp-content/uploads/2008/06/image-thumb7.png" width="477" border="0"></a> </p>
<p>Once the breakpoint is hit, you can use the '<strong>print</strong>' command to display a parameter value:</p>
<p><a href="http://damianblog.com/wp-content/uploads/2008/06/image8.png"><img style="border-width:0;" height="98" alt="image" src="http://damianblog.com/wp-content/uploads/2008/06/image-thumb8.png" width="472" border="0"></a></p>
<p>There is also a GUI which can be invoked using '<strong>load gui'</strong>:</p>
<p>&nbsp;<a href="http://damianblog.com/wp-content/uploads/2008/06/image9.png"><img style="border-width:0;" height="408" alt="image" src="http://damianblog.com/wp-content/uploads/2008/06/image-thumb9.png" width="470" border="0"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://damianblog.com/2008/06/12/using-mdbg-to-debug-at-the-il-level-instead-of-assembly-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

