Click here to monitor SSC
  • Av rating:
  • Total votes: 0
  • Total comments: 0
Michael Sorens

.NET Reflector Through the Looking Glass: The Meat and Potatoes

15 January 2013

.NET Reflector is most often used for viewing, filtering, navigating, and debugging assemblies to understand it better. Here is how all that is done.

Contents

Part 2: Meat and Potatoes

Part 1 of this series guided you through selecting an edition of .NET Reflector, installing it, and getting started with both the Reflector Desktop and the Visual Studio plugin. This article begins a comprehensive exploration of the key features of .NET Reflector, both natively and with enhancements provided by add-ins developed by the active Reflector community.

Part 2 covers the “meat and potatoes”, i.e. viewing, filtering, navigating, and debugging. Part 3 goes further into analyzing and exploring assemblies, showing you how to “slice and dice” to get to what you need. Part 4 rounds out the review of features explaining how to exercise the code in front of you or even any arbitrary code on the fly, as well as comparing and managing assemblies. The final part is a one-page companion wallchart that summarizes every feature in parts 2 through 4 and illustrates the key points of navigation in Reflector.

Reflector Desktop layout

Figure 1 .NET Reflector desktop layout. The Assembly Browser doubles as the navigation panel; other panels (those with white labels) are auto-populated based on its selection. The panels with black text are either independent of the assembly browser’s selection or not auto-populated.

View Code Without Source

Reflector Desktop: Load an assembly or executable, then drill down in the assembly list to the item of interest and select it. The source code for that item appears in the source code panel. The source code is, itself, instrumented with live links for code both within the same assembly and outside the assembly. Selecting any such item takes you to that item’s source code.

VS Extension: Once you have loaded an assembly as a project reference, you have access to its source code in different ways. (1) In the .NET Reflector object browser (not the VS object browser!) drill down in the assembly list to the item of interest and select it. Press F12 (if you have enabled that shortcut key on the .NET Reflector menu) or double-click the item to materialize the source code in a new tab, just like any other source code file. (2) Select an item in your source code and press F12 (or select GoTo Definition on its context menu).

Debug Code Without Source

VS Extension: With Reflector’s Visual Studio plugin, you can examine, step into, and set breakpoints on code for which you do not have source files! This particular feature arguably provides Reflector’s most important benefit. Decompiled source code becomes available to you just as if the generated source code files were part of your project. Step into foreign code from breakpoints in your own code, or open up the foreign code from .NET Reflector’s object browser and set breakpoints directly in the foreign code. In the first part of this series I discussed both automatic and manual techniques for decompiling assemblies. Once that is done, stepping into third-party code and setting breakpoints is as straightforward as it is in your own code. For another perspective on this, I encourage you to review Reflector’s own walkthrough that provides an illustrated step-by-step guide.

In many cases, debugging foreign code will be as simple as the walkthrough indicates. But there will sometimes be obstacles. According to Bart Read’s .NET Reflector doesn’t decompile some methods correctly, Reflector might fail to decompile a particular method or generate code that does not quite match the original for a number of reasons:

  • The code has been obfuscated.
  • The compiled IL could be decompiled to more than one source code construct with equivalent functionality.
  • The IL may look very different to the code produced by VB and C# compilers. This is particularly true for declarative languages..
  • You haven’t selected the correct .NET Framework optimization level.
  • The method is an unmanaged method called using P/Invoke.

One other source of difficulty lies with optimized assemblies, that you would typically get with commercial products. According to Clive Tong’s Debugging the debugging experience, optimized code can present a challenge. He provides a detailed description of his investigation into this issue (which I won’t repeat here), culminating in a simple recipe to strip away the optimization:

  • Set the environment variable COMPLUS_ZAPDISABLE to a value of 1 in the target process before the CLR starts.
  • Add an INI file next to the relevant assembly to ensure that optimization is turned down.

The MSDN article Making an Image Easier to Debug provides further detail about this last step and provides this simple example:

Assume you want to debug the assembly called MyApp.exe. Create an INI file—just an old-style (pre-.NET) configuration file format—and associate it with the assembly by giving it the same base file name and an ini extension (thus, MyApp.ini) and placing it in the same folder as MyApp.exe. The INI file should contain a section for .NET Framework Debugging Control with values for GenerateTrackingInfo and AllowOptimize, to wit:

[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0

For more on this, Adam Driscoll provides a detailed post putting this recipe into practice.

Looking forward to the imminent release of Reflector version 8, it gets even simpler to access decompiled code. If, for example, you are debugging an executable without source, Reflector generates decompiled code automatically when you hit an exception. Also, you will be able to click in the call stack and use it to navigate to the decompilation of any of the stack frames. Setting a breakpoint generates a PDB in the background.

View Code Signature

Reflector Desktop: Hover over the item of interest in the code panel; the code signature appears in a tooltip (Figure 2, top). Alternately, if you drill down to that object in the assembly list, the signature panel just below it will provide the same information (Figure 2, bottom). Of course, you have the signature visible in the code panel as well, but that can often be scrolled out of view.

Find the item's signature in decompiled code window

Figure 2 Hovering over an item in the decompiled code window (top) reveals the item’s signature. Alternately, drill down to that item and the signature panel (bottom) displays this information as well.

VS Extension: Hover over the item of interest in a source code window; the code signature appears in a tooltip (note that this is standard Visual Studio behavior, not Reflector-specific).

Manage Bookmarks

Reflector Desktop: .NET Reflector has a bookmark manager similar to those you find in a web browser.

  • Create a bookmark either with the context menu on an item in the Assembly Browser (menu >> Bookmark) or with the keyboard (Ctrl+K).
  • View bookmarks by opening the bookmark manager from the menu (View >> Bookmarks), from the toolbar (bookmark manager), or from the keyboard (F2).
  • Go to a bookmark by selecting an item in the bookmark manager and then pressing return or just by double-clicking an item in the bookmark manager.

Alternatively, Reflector also lets you create bookmarks to store and organize in your favorite browser or other bookmark manager. Create and load the clipboard with such an exportable bookmark either with the menu (Edit >> Copy Code Identifier) or with the keyboard (Ctrl+Alt+C) for the currently selected item in the assembly browser. You can then paste that URI into a bookmark manager of your choice. Upon activating such a bookmark, it launches .NET Reflector and automatically drills down to the target item.

VS Extension: Use Visual Studio’s own bookmarking facilities; these are most easily accessed from Visual Studio’s Text Editor toolbar (Figure 3).

Bookmark controls

Figure 3 Bookmark controls on Visual Studio’s Text Editor toolbar.

Extend Reflector

Reflector Desktop: Reflector provides an easy way to extend its capabilities with Add-Ins. These are easy to wire up. Open the add-in manager (Tools >> Add-Ins) then select the add (Open File dialog) button to open a standard open file dialog. (Note: At the time of writing this dialog always opens in Reflector’s program directory and you immediately see a subdirectory named Addins. Ignore it. It’s best not to put your add-ins there. It’s for Red Gate-supplied add-ins. You can keep your add-ins anywhere you like. Just not there:-)).

Select an add-in that you have downloaded (or built!) and select Open. The add-in is installed in Reflector and displayed on the add-in list—no restart is required. To remove an add-in, simply press the subtract (subtract button) button in the add-in manager. I recommend you collect all your add-ins in one directory so you can then register or unregister them with the add-in manager without having to hunt through different folders.

To find add-ins, start with the add-in manager itself; it provides a button to take you directly to Red Gate’s recommended add-in gallery in your browser. The other major source of add-ins is on Codeplex.

To create your own add-ins, start with An Introduction to Building .NET Reflector Add-ins to begin learning about .NET Reflector’s extensive add-in framework. Towards the end of that overview, you will find a further reading list to help you on your way.

Filter Code

Reflector Desktop: By default, you see all the code associated with the currently selected item, public or otherwise, when you decompile. But if you go to the visibility option (Tools >> Options >> Browser >> Visibility) you can change this All Items default to Public Items Only if desired. The typical scenario of examining a foreign library begins with entering through a call in your own code. So, selecting Public Items Only can reduce the clutter of what you are examining, at least initially.

The second facility for managing clutter comes automatically with Reflector, no settings necessary. If you have selected a class (or type) in the assembly browser, the source panel displays the signatures of its properties and methods along with its fields and nested types.At the very bottom, though, is a link labeled Expand Methods that lets you view the entire class in the same scrolling pane. You can still select individual methods in the assembly browser tree to bring them instantly into view in the source panel, but it is often quite convenient to have your list of methods scrollable in one text box. If, on the other hand, your current item is a namespace, the source panel summarizes the types (classes) in the namespace, and provides a live link labeled Expand Types at the bottom for similar convenience.

VS Extension: Within Visual Studio you view files in their entirety. While there is no analogous filtering to that in the Reflector Desktop, Visual Studio provides its own outlining controls, allowing you to expand or contract any explicit code regions (demarcated with #region and #endregion) or implicit code regions (methods, types, namespaces, comment sections, etc.).

Version 8 of Reflector will include searching and filtering in the Visual Studio extension.

Filter Navigation Tree

Reflector Desktop: By default, you see just the items that are local to the selected assembly when you drill down through the navigation tree in the assembly browser. But quite commonly a class will have inherited items as well. When you select a class in the assembly browser, you can then toggle the display of inherited members by context menu (menu >> Toggle Inherited Members) or keyboard (Ctrl+I). You can also change the default to display inherited members via the options dialog (Tools >> Options >> Browser >> Show inherited members).

VS Extension: In Visual Studio you only have the items local to the assembly, i.e. inherited items are not displayed.

Navigate to Code from Code

Reflector Desktop: When you view decompiled code, almost every token is a hyperlink to other code! Figure 4 shows a very typical example. There are 29 non-punctuation tokens (if I counted correctly ) in the figure; the ones in green—17 of them—are active links, either to variables, properties, or methods. Some of these are in my code, some in the .NET framework code. You can click on any of them to take you immediately to that underlying code. If you hold down Ctrl while clicking, the new item will conveniently open in a separate tab so you do not lose your original context.

Decompiled code

Figure 4 Decompiled code is profligately populated with hyperlinks for easy access to underlying types.

VS Extension: From any open code file, place your active cursor within the bounds of any code token. You do not get the convenient uniform highlighting of active links as in the Reflector Desktop because Visual Studio does syntax highlighting with a different focus. Nonetheless, .NET Reflector should provide all the same navigable links within Visual Studio. One big difference is that clicking the item does not take you to it—that would be rather inconvenient in a text editor, after all!

There are several possible keystrokes to navigate to the underlying source; open the context menu on an item to see some or all of these depending on your context and whether you have Resharper installed (Figure 5).

Choices supplied by VS, Reflector and Resharper

Figure 5 Choices supplied by Visual Studio, Reflector, and Resharper. Your best bet is usually F12.

You will note that two of these have keyboard shortcuts making them the most convenient to use. Though the Go to Decompiled Definition command is Reflector’s own command (as you can tell from the icon in the margin of the context menu), just pressing F12 usually works best. Be aware, though, that if you have Resharper it could occasionally get in the way here as well.

Navigate to Code from Documentation

Reflector Desktop: Besides navigating to other code elements from code you can also navigate from documentation if you satisfy these conditions:

  • You have the documentation file (library.XML) for the third-party library (library.DLL).
  • You installed the documentation file in the same directory as the DLL.
  • Reflector’s documentation display option is set to Formatted (which is the default).
  • The documentation includes well-formed references to code items.

If you satisfy the first three conditions you will automatically see a documentation panel when you view source code. Both source and documentation panels are actually subpanels of the same main panel. If the fourth condition is satisfied when you scroll through the documentation you will see links that appear just as they would in a web browser. Click on these to navigate directly to that code. Just like navigating from code to code, if you hold down Ctrl while clicking a link in documentation, the new item will conveniently open in a separate tab so you do not lose your original context.

VS Extension: Visual Studio displays only native documentation comments, not the resultant formatted documentation, so this capability is not applicable.

Search Code

Reflector Desktop: Open the search panel by menu (Tools >> Search), toolbar (Reflector Search panel), or keyboard (F3). Reflector’s powerful search facility allows you to search by type (class), member, or string/constant value; Figure 6 shows the result of searching for the same value with each of these filters. Simply select the desired filter at the upper right and the results change immediately. The button at the extreme right is a toggle for getting an exact match, and may be used with each of the three filters. Notice that the search is not just checking the name of the item—for example, searching for “Button” by type includes “CheckBox” in the results. Nor is it limited to checking just the displayed columns in the search panel. Rather, the search encompasses each item in its entirety: if you search for types, the search phrase appearing within any portion of the code comprising the type yields a positive match!

search filtering

Figure 6 Reflector’s search panel lets you filter by type, by member, or by string/constant.

Finding that something exists is only half the battle, of course. Once you run a search, you can immediately jump to that item in source code by double-clicking on it. If you hold down Ctrl while double-clicking, the target item will conveniently open in a separate tab so you do not lose your original context. This search examines both plain assemblies as well as those loaded into Reflector in a zipped package.

While Reflector’s basic search is useful, with an add-in you can jazz it up a bit. The Assembly Visualizer add-in collection from Denis Markelov provides several graphical perspectives of your assemblies but its assembly browser is its central focus. Once you install the add-in—see the discussion under Extending Reflector—you will have several new context menu entries to access different views provided by Assembly Visualizer. When you select an assembly node, the Browse Assembly command materializes, which takes you to Assembly Visualizer’s assembly browser. Note that Assembly Visualizer uses the same name for this window as Reflector’s own assembly browser because they essentially do the same thing at their core: select an item in either assembly browser and Reflector displays that item immediately in the decompiled code panel. But if you compare Reflector’s assembly browser from Figure 1 to Assembly Visualizer’s assembly browser in Figure 7, their appearances are quite different.

Assembly Visualizer's search panel

Figure 7 Assembly Visualizer’s search panel provides sorting and filtering options down the left side; the right side accumulates each assembly you initiated via the context menu command.

Reflector displays the assemblies hierarchically; Assembly Visualizer displays a flat list. But this flat list allows Assembly Visualizer’s search capability to fit right in—just type a phrase in the search box at the top and it immediately filters the list as the figure illustrates. Assembly Visualizer brings several other productivity enhancements as enumerated in the table; they more than make up for the drawback of being in a separate window. At the time of writing, Reflector version 8 is in development with beta versions already available. One of the key new features is a new search capability in Reflector’s own assembly browser! The search-related features are highlighted in the table and marked with “V8”.

Feature

Reflector

Assembly Visualizer

Applies to

Desktop and VS

Desktop

Organization

Hierarchical

Flat

Search capability

(V8) Yes

Yes

Search prunes list

(V8) Yes

Yes

Search window

(V8) Main window

Seperate window

Search highlights target

(V8) Yes

Yes

Search universe

(V8) All loaded assemblies

Selected assemblies

Search shows count

(V8) Yes

Yes

Search within zipped assemblies

(V8) No

Yes

Visualize descendants

No

Yes

Browse ancestry

No

Yes

Browse Interactions

No

Yes

Summarizes descendants/members

No

Yes

Filter visibility

Yes (via options)

Yes

Filter type categories

No

Yes

Sort

No

Yes

Table 1 Reflector’s assembly browser vs. Assembly Visualizer’s assembly browser.

Figure 8 provides a glimpse of Reflector 8’s new search facility. One of the most interesting features is that it prunes the list—just like Assembly Visualizer—but does so while maintaining a hierarchical organization! I find that very useful to maintain a better sense of where I am in the code.

Leaving perhaps the most critical advantage to last, Reflector’s enhanced search is available both in the desktop edition (assembly browser) and in the VS Extension (object browser)! Thus if you want to look up some framework class, you no longer have to walk through the browser to find it—just type in a full or partial word in Reflector’s object browser, double-click the item, and view the source!

Reflector 8 search

Figure 8 Reflector’s new search facility in version 8, directly filtering the navigation tree in the assembly browser.

Copy Code

Reflector Desktop: On the face of it seems silly to include the ability to copy as a feature—but that depends what you expect from a copy operation, and different people have different expectations! So Reflector tries to provide flexibility so that you can copy to get raw code or copy to do documentation. The first point to realize is that you do not need to select-then-copy as traditionally done with a copy operation. Simply right-click in the code panel and select Copy As from the context menu. In the samples below I have added the horizontal rules top and bottom to more easily delineate the fragments.

Choosing Text yields raw code:

public static string BuildComboKey(params string[] keyComponents)
{
	return string.Join("<-:_->", keyComponents);
}

Choosing Rich Text yields a code sample useful for documentation:

public static string BuildComboKey(params string[] keyComponents)
{
	return string.Join("<-:_->", keyComponents);
}

Choosing HTML gives you another variation:

public static string BuildComboKey(params string[] keyComponents)
{ 
	return string.Join("<-:_->", keyComponents);
}

Note that you get the code for the entire item—if it is a class, for example, you get all the methods expanded whether you have manually expanded them or not (via the Expand Methods link at the bottom of the code window).

More…

This concludes an examination of the first group of Reflector features. Refer to the companion wallchart to see the full list, and continue with the details in parts 3 and 4.

Michael Sorens

Author profile:

Michael Sorens is passionate about software to be more productive, evidenced by his open source libraries in several languages (see his API bookshelf) as well as SqlDiffFramework (a DB comparison tool for heterogeneous systems including SQL Server, Oracle, and MySql). With degrees in computer science and engineering he has worked the gamut of companies from Fortune 500 firms to Silicon Valley startups over the last 25 years or so. Current passions include PowerShell, .NET, SQL, and XML technologies (see his full brand page). Spreading the seeds of good design wherever possible, he enjoys sharing knowledge via writing (see his full list of articles), teaching, and StackOverflow. Like what you have read? Connect with Michael on LinkedIn and Google +

Search for other articles by Michael Sorens

Rate this article:   Avg rating: from a total of 0 votes.


Poor

OK

Good

Great

Must read
Have Your Say
Do you have an opinion on this article? Then add your comment below:
You must be logged in to post to this forum

Click here to log in.
 

Top Rated

Acceptance Testing with FitNesse: Multiplicities and Comparisons
 FitNesse is one of the most popular tools for unit testing since it is designed with a Wiki-style... Read more...

Acceptance Testing with FitNesse: Symbols, Variables and Code-behind Styles
 Although FitNesse can be used as a generic automated testing tool for both applications and databases,... Read more...

Acceptance Testing with FitNesse: Documentation and Infrastructure
 FitNesse is a popular general-purpose wiki-based framework for writing acceptance tests for software... Read more...

TortoiseSVN and Subversion Cookbook Part 11: Subversion and Oracle
 It is only recently that the tools have existed to make source-control easy for database developers.... Read more...

TortoiseSVN and Subversion Cookbook Part 10: Extending the reach of Subversion
 Subversion provides a good way of source-controlling a database, but many operations are best done from... Read more...

Most Viewed

A Complete URL Rewriting Solution for ASP.NET 2.0
 Ever wondered whether it's possible to create neater URLS, free of bulky Query String parameters?... Read more...

Visual Studio Setup - projects and custom actions
 This article describes the kinds of custom actions that can be used in your Visual Studio setup project. Read more...

.NET Application Architecture: the Data Access Layer
 Find out how to design a robust data access layer for your .NET applications. Read more...

Calling Cross Domain Web Services in AJAX
 The latest craze for mashups involves making cross-domain calls to Web Services from APIs made publicly... Read more...

Web Parts in ASP.NET 2.0
 Most Web Parts implementations allow users to create a single portal page where they can personalize... Read more...

Why Join

Over 400,000 Microsoft professionals subscribe to the Simple-Talk technical journal. Join today, it's fast, simple, free and secure.