DV Sample

Thu, January 6, 2005, 02:16 AM under Whidbey | VisualStudio
As the sample I promised, I have written a visualizer for System.String. Given a string variable, it will show the bytes corresponding to that string based on the various encodings. The inspiration for it was the cry that a friend of mine got from their QA team recently regarding an app they have that "Doesn't work on a Chinese OS!".

To create it, we need a class library project that references Microsoft.VisualStudio.DebuggerVisualizers.dll and we add the following code:

1. Declare the attribute:
[assembly: System.Diagnostics.DebuggerVisualizer(

typeof(EncodingVisualizer.StringBytes),
Target = typeof(System.String),
Description = "Encoding Viewer")]

The above is all you need to enable the new menu item when you hover over a string variable (or in the Autos window). In the IDE, the menu looks something like this. Note how VS2005 gives us out of the box the HTML, XML and TEXT visualisers.

2. The code that runs when the "Encoding Viewer" menuitem is clicked, is in your class:
using Microsoft.VisualStudio.DebuggerVisualizers;

namespace EncodingVisualizer {
public class StringBytes : DialogDebuggerVisualizer {
protected override void Show(IDialogVisualizerService windowService,
IVisualizerObjectProvider objectProvider) {
string s = (string)objectProvider.GetObject();
frmStringBytes f = new frmStringBytes(s);
f.ShowDialog();
}
}
}
Naturally, you need a form frmStringBytes whose visual design looks like this; the constructor of the form does the work and is straightforward:
public frmStringBytes(string aString)

: this() {
txtExpression.Text = aString;

string s;
byte[] arr;
arr = System.Text.Encoding.ASCII.GetBytes(aString);
s = "ASCII = " + BitConverter.ToString(arr);
s += "\r\n\r\n";

arr = System.Text.Encoding.Unicode.GetBytes(aString);
s += "Unicode = " + BitConverter.ToString(arr);
s += "\r\n\r\n";

arr = System.Text.Encoding.Default.GetBytes(aString);
s += "Default = " + BitConverter.ToString(arr) + "\r\n";

// Do other encodings here e.g UTF7, UTF8, UTF32 etc

txtValue.Text = s;
}
You may download the dll and place it in the right place as discussed before.