February 2008

How to determine event subscribers

While debugging a reasonably complex .NET application, many times you may come across a situation where you want to know which different methods have subscribed to your event. If you are using VS2005 or VS2008 then DebuggerTypeProxyAttribute, a relatively unknown feature of Visual Studio, comes to your rescue. For a long time Visual Studio has allowed developers to customize the information about the variable that is displayed in the IDE during debugging. Before VS2005 the customization was done using mcee_cs.dat (C#), mcee_mc.dat (MC++), and autoexp.dat (C++) files. Starting with VS2005, this customization is taken to next level. VS2005 introduces two new attributes, DebuggerDisplayAttribute and DebuggerTypeProxyAttribute, that allows you to change the information displayed in the Visual Studio debugger. Typically one would apply these attributes to the class in the code which the VS debugger will use to display information. However, there is a trick in which you can use these attributes outside of the original code. This means that you can change the information displayed about ANY class, even the classes that you did not write yourself. VS2005 and above use AutoExp.dll which provides display information about various types to the debugger. The code for AutoExp.dll is provided in AutoExp.cs file with the Visual Studio installation in Common7\Packages\Debugger\Visualizers\Original\ folder. You can add your own code to this file, compile the AutoExp.dll, and place it in either the Common7\Packages\Debugger\Visualizers folder or in the My Documents\Visual Studio 2005 (or Visual Studio 2008)\Visualizers folder. I learned about this trick a while back from John Robbins' excellent book Debugging .NET 2.0 Applications. It turns out that Visual Studio loads all the valid assemblies from the Visualizers folder, and if the assembly contains Visualizer or any debugger related objects then it will use it during the debugging session. Now back to the topic of this post; to easily display which methods have subscribed to an event I wrote a class called MulticastDelegateDebuggerProxy for MulticastDelegate class. Since, all the events are delegates that are derived from MulticastDelegate class, my MulticastDelegateDebuggerProxy class will be used for all the events. The DebuggerTypeProxyAttribute is used at the assembly level to tell Visual Studio debugger that MulticastDelegateDebuggerProxy class is the proxy for MulticastDelegate class. The code for MulticastDelegateDebuggerProxy is listed below.

 
using System;
using System.Diagnostics;
using System.Reflection;
using System.Text;
 
[assembly: DebuggerTypeProxy(typeof(MulticastDelegateDebuggerProxy),
		Target = typeof(MulticastDelegate))]
 
public class MulticastDelegateDebuggerProxy
{
	private string[] m_methods;
 
	public MulticastDelegateDebuggerProxy(System.MulticastDelegate del)
	{
		m_methods = GetMethodList(del);
	}
 
	[DebuggerDisplay(@"Subscribers:\{{Methods.Length}}")]
	public string[] Methods
	{
		get { return m_methods; }
	}
	private string[] GetMethodList(System.MulticastDelegate myEvent)
	{
		string retType = myEvent.Method.ReturnType.Name;
 
		Delegate[] delegates = myEvent.GetInvocationList();
		string[] methods = new string[delegates.Length];
 
		for (int i = 0; i < delegates.Length; ++i)
		{
			Delegate del = delegates[i];
			MethodInfo m = del.Method;
			string accessModifier =
				m.IsPrivate ? "private" : (m.IsPublic ? "public" : (m.IsFamily ? "protected" : ""));
			StringBuilder sb = new StringBuilder();
			foreach (ParameterInfo param in m.GetParameters())
			{
				sb.Append(param.ParameterType.FullName).Append(" ").Append(param.Name).Append(",");
			}
			if (sb.Length > 0)
			{
				sb.Remove(sb.Length - 1, 1);
			}
			string isStatic = m.IsStatic ? "static" : string.Empty;
			string isVirtual = m.IsVirtual ?
				(((m.Attributes & MethodAttributes.NewSlot) == MethodAttributes.ReuseSlot)
				? "override" : "virtual") : string.Empty;
			methods[i] = string.Format("{0} {1} {2} {3} {4}.{5}({6})",
				accessModifier, isStatic, isVirtual, retType, m.ReflectedType.FullName, m.Name, sb.ToString());
		}
 
		return methods;
	}
}

The information displayed in VS2005 by default is shown below.
Default Event information in VS2005

The information displayed in VS2005 with MulticastDelegateDebuggerProxy is shown below. The MulticastDelegateDebuggerProxy displays fully qualified method name and the parameter names used in the method.

Event information in VS2005 with MulticastDelegateDebuggerProxy
In VS2008, the default information displayed is slightly better than VS2005 as it shows _invocationList by default which can be drilled down to the actual methods. However, the default display can get ambiguous as shown in the screenshot below. The MulticastDelegateDebuggerProxy does a much better job at displaying the same information.

Default event information in VS2008

.NET Framework
Debugging
VS2005
VS2008

Comments (0)

Permalink

Learning .NET debugging using WinDBG

If you wanted to learn advanced debugging of .NET application using WinDBG but didn't know where to start, look no further. Tess Ferrandez has started posting debugging labs to teach you how to debug tough problems. Her blog has invaluable tips about debugging real world problems. She has posted real world case studies and explained how to approach and solve the problems. In debugging labs, she posts a buggy application with instructions for troubleshooting the problem. A couple of days later, she posts a review of the lab where she walks you through troubleshooting the problem in great detail. So far she has posted 3 debugging labs (one, two, three) and 2 lab reviews (one, two). She will be posting a total of 10 labs. These labs are a great learning tool and best of all, they are all free! Thank you Tess!

.NET Framework
Debugging

Comments (0)

Permalink

Ghazal-E-Surat

Ghazal is a form of poetry that was introduced to India by the Moghuls in the 12th century. While Ghazals can be written in any language, in India it is more popularly written in Urdu, Hindi and Gujarati. When it comes to Gujarati Ghazals, the city of Surat is considered the front runner with the most popular Ghazalkars or Shayers (i.e. poets) coming from Surat. In an unprecedented move, a publisher from Surat has published a book called Ghazal-E-Surat that contains about 76 Ghazals from the 41 living Ghazalkars. I came across this news on the blog of Dr. Vivek Tailor a Ghazalkar from Surat, and Layastro a leading Gujarati Ghazal site. One of the Ghazalkars published in the book is my Grandfather, H. N. Keshwani. My Grandfather is well known in the Gujarati Ghazal circle in Surat, but little outside of it. I am very proud of my Grandpa for his achievements, and very happy that he was recognized by the publishers of Ghazal-E-Surat. Among the other Ghazalkars' pictures on the front and back cover of the book, my Grandpa is on front cover, first picture on the third row.

Ghazal-E-Surat

Image courtesy: Dr. Vivek Tailor who is also published in the book.

Ghazal

Comments (1)

Permalink

Vista Dual Monitor Woes

This issue with the dual monitor setup in Vista has been bugging me a lot. I have 2 19" Westinghouse monitors that have DVI and VGA inputs. I have an ATI Radeon 9200 video card that has a DVI and a VGA output. The left monitor (primary) is connected using DVI and the right one is connected to VGA. The dual monitor is working fine except for one problem. When I turn off the left primary monitor (the one using DVI) and turn it back on, I get no signal. I only have two options, either reboot the machine, or login to the machine from another machine using remote desktop. As soon as I login using RDP, the monitor comes to life. I Googled for dual monitor related issues in Vista and followed through various suggestion including installing the latest ATI Catalyst video drivers, disabling turning off monitors in the power management settings and disabling Transient Multi-Monitor Manager (TMM) task, but nothing has helped so far. I have found only one reference to the exact same issue that I am facing, but there is no resolution. The exact same setup works fine on Windows XP.

Vista

Comments (0)

Permalink

DEP, NXCOMPAT Redux

I recently wrote about the impact of DEP on .NET applications due to changes in the .NET Framework 2.0 SP1. A couple of days later I came across Michael Howard's post about new APIs related to DEP. As Michael points out, in Windows Vista SP1, Windows XP SP3 and Windows Server 2008, it is possible for developers to enable DEP for an application at runtime instead of using a linker switch or being forced into setting NXCOMPAT bit by the C# compiler. The new function SetProcessDEPPolicy, allows the running process to change the DEP settings for the process calling it. I think this is a much more flexible option since it puts application developers in control of using DEP for their applications. Michael also explains the options available in SetProcessDEPPolicy API which allows the application that is using the old ATL code to enable DEP, and not throw the DEP exception at runtime. Raymond Chen has written about how in Windows XP, DEP will not throw an exception for what he calls "well-known DEP-voilating thunks". The new DEP API brings this feature to WinXP SP3, Vista, and Windows Server 2008. Now if only Microsoft would release a hotfix for the C# compiler to provide a /NXCOMPAT switch, the .NET development world would be a much better place.

.NET Framework

Comments (0)

Permalink

How JNI calls functions from DLL

When a function is exported from a DLL the compiler will decorate or mangle the function name. To export the undecorated function name the linker needs an export definition file (.DEF). A while back I was working on a project in Java that calls functions from a DLL using JNI. I had created a DLL that exported some functions to be called from a Java application. Just when I started to test the application I realized that I had forgotten to update the .DEF file. I was expecting the Java application to fail when it would try to call the functions in the DLL. To my surprise, the function calls succeeded. I was curious to find out why these calls succeeded. I wrote a sample Java application that had one class called Hello which would call a native function called sayHello in a DLL called Hello.DLL. Running javah on the Java source generated the header file with a native function named Java_Hello_sayHello. I created the DLL and made sure that the exported function was undecorated. Using the fantastic Dependency Walker's lightweight profiler I ran the Java application. Looking at the output window in Depends, it was clear why a call to a function in decorated form, would succeed. JNI first tries to call the function using two decorated names before calling it with the undecorated name as illustrated in the image below.

JNI calling native function

The JNI specification mentions the naming convention for the native function. However, there is no mention of the fact that when calling the functions from a native library the runtime will try to call the functions using both the decorated and undecorated names. Another peculiar behavior that I noticed is that when calling the other JNI related functions that you can export from a native library such as JNI_OnLoad, JNI_OnUnload, the runtime tries only one decorated name before calling the undecorated function as shown above. I find this very strange.

JNI

Comments (0)

Permalink