Pages

Tuesday, December 2, 2008

Managed, Unmanaged, Native: What Kind of Code Is This? By Kate Gregory

With the release of Visual Studio .NET 2003 (formerly known as Everett) on April 24th, many developers are now willing to consider using the new technology known as managed code. But especially for C++ developers, it can be a bit confusing. That's because C++, as I pointed out in my first column here, is special.

What Is Managed Code?

Managed Code is what Visual Basic .NET and C# compilers create. It compiles to Intermediate Language (IL), not to machine code that could run directly on your computer. The IL is kept in a file called an assembly, along with metadata that describes the classes, methods, and attributes (such as security requirements) of the code you've created. This assembly is the one-stop-shopping unit of deployment in the .NET world. You copy it to another server to deploy the assembly there—and often that copying is the only step required in the deployment.

Managed code runs in the Common Language Runtime. The runtime offers a wide variety of services to your running code. In the usual course of events, it first loads and verifies the assembly to make sure the IL is okay. Then, just in time, as methods are called, the runtime arranges for them to be compiled to machine code suitable for the machine the assembly is running on, and caches this machine code to be used the next time the method is called. (This is called Just In Time, or JIT compiling, or often just Jitting.)

As the assembly runs, the runtime continues to provide services such as security, memory management, threading, and the like. The application is managed by the runtime.

Visual Basic .NET and C# can produce only managed code. If you're working with those applications, you are making managed code. Visual C++ .NET can produce managed code if you like: When you create a project, select one of the application types whose name starts with .Managed., such as .Managed C++ application..

What Is Unmanaged Code?

Unmanaged code is what you use to make before Visual Studio .NET 2002 was released. Visual Basic 6, Visual C++ 6, heck, even that 15-year old C compiler you may still have kicking around on your hard drive all produced unmanaged code. It compiled directly to machine code that ran on the machine where you compiled it—and on other machines as long as they had the same chip, or nearly the same. It didn't get services such as security or memory management from an invisible runtime; it got them from the operating system. And importantly, it got them from the operating system explicitly, by asking for them, usually by calling an API provided in the Windows SDK. More recent unmanaged applications got operating system services through COM calls.

Unlike the other Microsoft languages in Visual Studio, Visual C++ can create unmanaged applications. When you create a project and select an application type whose name starts with MFC, ATL, or Win32, you're creating an unmanaged application.

This can lead to some confusion: When you create a .Managed C++ application., the build product is an assembly of IL with an .exe extension. When you create an MFC application, the build product is a Windows executable file of native code, also with an .exe extension. The internal layout of the two files is utterly different. You can use the Intermediate Language Disassembler, ildasm, to look inside an assembly and see the metadata and IL. Try pointing ildasm at an unmanaged exe and you'll be told it has no valid CLR (Common Language Runtime) header and can't be disassembled—Same extension, completely different files.

What about Native Code?

The phrase native code is used in two contexts. Many people use it as a synonym for unmanaged code: code built with an older tool, or deliberately chosen in Visual C++, that does not run in the runtime, but instead runs natively on the machine. This might be a complete application, or it might be a COM component or DLL that is being called from managed code using COM Interop or PInvoke, two powerful tools that make sure you can use your old code when you move to the new world. I prefer to say .unmanaged code. for this meaning, because it emphasizes that the code does not get the services of the runtime. For example, Code Access Security in managed code prevents code loaded from another server from performing certain destructive actions. If your application calls out to unmanaged code loaded from another server, you won't get that protection.

The other use of the phrase native code is to describe the output of the JIT compiler, the machine code that actually runs in the runtime. It's managed, but it's not IL, it's machine code. As a result, don't just assume that native = unmanaged.

Does Managed Code Mean Managed Data?

Again with Visual Basic and C#, life is simple because you get no choice. When you declare a class in those languages, instances of it are created on the managed heap, and the garbage collector takes care of lifetime issues. But in Visual C++, you get a choice. Even when you're creating a managed application, you decide class by class whether it's a managed type or an unmanaged type. This is an unmanaged type:

class Foo
{
private:
int x;
public:
Foo(): x(0){}
Foo(int xx): x(xx) {}
};

This is a managed type:

__gc class Bar
{
private:
int x;
public:
Bar(): x(0){}
Bar(int xx): x(xx) {}
};

The only difference is the __gc keyword on the definition of Bar. But it makes a huge difference.

Managed types are garbage collected. They must be created with new, never on the stack. So this line is fine:

Foo f;

But this line is not allowed:

Bar b;

If I do create an instance of Foo on the heap, I must remember to clean it up:

Foo* pf = new Foo(2);
// . . .
delete pf;

The C++ compiler actually uses two heaps, a managed an unmanaged one, and uses operator overloading on new to decide where to allocate memory when you create an instance with new.

If I create an instance of Bar on the heap, I can ignore it. The garbage collector will clean it up some after it becomes clear that no one is using it (no more pointers to it are in scope).

There are restrictions on managed types: They can't use multiple inheritance or inherit from unmanaged types, they can't allow private access with the friend keyword, and they can't implement a copy constructor, to name a few. So, you might not want your classes to be managed classes. But that doesn't mean you don't want your code to be managed code. In Visual C++, you get the choice.

About the Author

Kate Gregory is a founding partner of Gregory Consulting Limited (www.gregcons.com). In January 2002, she was appointed MSDN Regional Director for Toronto, Canada. Her experience with C++ stretches back to before Visual C++ existed. She is a well-known speaker and lecturer at colleges and Microsoft events on subjects such as .NET, Visual Studio, XML, UML, C++, Java, and the Internet. Kate and her colleagues at Gregory Consulting specialize in combining software develoment with Web site development to create active sites. They build quality custom and off-the-shelf software components for Web pages and other applications. Kate is the author of numerous books for Que, including Special Edition Using Visual C++ .NET.

Tuesday, November 25, 2008

Using WebServices with ASP.NET

Daniel Penrod

Using WebServices with ASP.NET

14 December 2007

by Daniel Penrod

Webservices without tears? Popup maps in your websites? Ajax-based Search-engines? No problems, with Daniel's sample application to guide you.

SOAP Webservices provide a simple way of providing public information in websites. Directories, maps, translations, searches and zipcode/postcode lookup all suddenly become quick and easy to implement, especially in .NET. Windows Live Webservice have now joined the market with a whole range of services which are likely to change the way we use the Web.

In this article I will show off the abilities of ASP.NET 2.0 to consume the Windows Live Search Webservice and use AJAX 1.0 and the AjaxControlToolkit to replicate some of the features in Microsoft’s search engine Live Search. I am going to take a more advanced approach to the solution I wrote for the Code Project and provide a richer overall experience in this demo. I've provided the source too so you can try it yourself, and experiment

This article will demonstrate the following:

  • Consumption of the Windows Live Search Webservice and the ability to bind these results to an ASP.NET Gridview control
  • The use of AJAX 1.0 to search and page through the search results
  • Using the AjaxControlToolkit and an online dictionary web service to create an auto complete function that aids in finding search words
  • Tapping into the Live Search spelling suggestion service to display a polite message to the user of a possible spelling suggestion for their misspelled word(s)
  • Enhancing the search experience with a Live.Local lookup to display listings out of the yellow pages with their associated local addresses
  • Taking the local addresses and providing a dynamic Microsoft Virtual Earth map of the location to include all the power and enhanced features associated with the Virtual Earth API.

Some of the advantages of using these web services include:

  • A full blown SOAP Webservice allowing you to take control of the data
  • The ability to search multiple websites from your company and / or its partners
  • Not having to worry about indexing the content of your company’s global website(s)
  • Harnessing the power of Live Search’s advanced search features in your queries
  • Using Virtual Earth to map out streets in your local area.

Some of the limitations include:

· A limit of 10,000 queries a day to use the service for free. (Note: Normally each page in the Gridview Control will fire a new query even though the search query is the same. This demo makes use of sessions to prevent this from happening. – Optional in web.config)

· You can only return a maximum of 50 results per query.

Getting started

Setting up the environment

The first steps are to set up your demo/development environment. This demo was created in Windows XP Pro using IIS. The following actions need to occur in order to run this demo locally.

  1. Install ASP.NET 2.0 (http://www.windowsupdate.com/)
  2. Install ASP.NET 2.0 AJAX Extensions 1.0 (http://asp.net/ajax/downloads/archive/)
  3. Download and Setup the demo application in IIS and choose the ASP.NET 2.0 framework
  4. Obtain a Key from Microsoft to use this Webservice (http://search.msn.com/developer)
  5. Add the key to the appropriate app setting in web.config
  6. (Optional) Follow the additional instructions in web.config to customize your output.

It is suggested that you open this website up in Visual Studio 2005 or greater and take advantage of IntelliSense and explore the methods, properties and various classes that make up the Live Webservice and this demo.

Setting up web.config
The app key for this web service

Get the key from here ... http://search.msn.com/developer
and insert it into Add the appropriate app setting in web.config

<add key="SearchLic" value=""/>

The dictionary service for autocomplete

Choose a dictionary from here: AonaWare's DictService
In this demo I use WordNet (r) 2.0 (wn)

<add key="DictService" value="wn" />

The Windows Live Search expression

By default I leave this key blank to search the entire Internet but you could use an expression such as:

{frsh=100} {popl=100} (site:www.ci.fayetteville.nc.us OR site:jobs.ci.fayetteville.nc.us OR site:www.faypwc.com OR site:www.fcpr.us OR site:flyfay.ci.fayetteville.nc.us OR site:police.ci.fayetteville.nc.us OR site:www.ccbusinesscouncil.org OR site:www.co.cumberland.nc.us) -www.ci.fayetteville.nc.us/portal/council_meeting_minutes/

This expression can be built using the Advance Search Feature of Windows Live (http://www.live.com/). It basically states to make the search have 100% fresh content with a popularity of 100% and search the sites in parenthesis with the exception of the council meeting minute’s directory.

<add key="SearchSites" value=""/>

The Results Size

The limit is 50 results. By default I set the results size to 25.

<add key="ResultsSize" value="25"/>

Logging

Most errors get encapsulated in the AJAX 1.0 abyss. To make things easier on me when developing this application I created an optional logging feature. By default I have this turned off, but if you decide to set this to true then you must provide a physical path to write the log files.

<add key="IsLogging" value="false"/>
<add key="ErrorLogPath" value="C:\Inetpub\wwwroot\Windows.Live.Search\Logs\"/>

Location for Local.Live Services

Add the longitude and latitude of your local area. The default location of this demo is Seattle, WA with a radius of 25 miles. The values should be written as doubles.

<add key="Latitude" value="47.603828" />
<add key="Longitude" value="-122.328567" />
<add key="Radius" value="25.0"/>

Sessions

Use this key to turn sessions on or off. Sessions will help you save your available queries. MS gives you a 10,000 daily limit. With paging turned on in the GridView Control, each time a user selects a new page it will constitute a new search query if sessions are turned off. Turn the session switch on to avoid this. By default I have sessions turned on.

<add key="IsSearchSession" value="true"/>

Exploring the WindowsLiveSearch class
Items to consider

On a security note, the possibility of cross site scripting getting stored in the results became a real problem. This would not only wreck havoc on your presentation layer markup, but more importantly it could ultimately send your users to dangerous and inappropriate places on the Internet. To solve this dilemma I referenced Microsoft’s AntiXssLibrary.dll in the class. I then called the AntiXss.HtmlEncode() function for each result returned by the webservice. This will strip cross site scripts and secure your output for the client.

When consuming the results from the Webservice I immediately ran into null reference exceptions for fields that ultimately did not exist. For example, a result set usually contained the usual fields such as the title, URL, description, etc. If by chance no information was indexed for the description field, the webservice returned null for that particular item. I created a function called CheckforNull that simply returned an empty string if a null was present. That solved that problem.

Another item of consideration was the use of sessions. Storing objects in sessions isn’t a good idea for a number of reasons, but when you weigh the alternative it doesn’t seem so bad anymore. The limit of free queries a day by Microsoft is 10,000. Not so bad, huh? Well let’s say you have one user who really wants to find something and makes five queries and you display five results a page for the maximum 50 results total. This user also decides to look at all 10 pages of results for each of the five queries. Well instead of five queries, you now have used 50 for just that one person. And if that person wanted to page backwards because they thought they missed something then it would only add to the queries because each page clicked in the Gridview control fires another instance of the search and creates another query. That is definitely a worse case scenario, but websites that receive a lot of traffic have to take these things into consideration. With sessions active, five queries will remain five queries. For those who ultimately hate the idea of storing an object in a session then you can always turn sessions off in web.config as stated earlier in this article.

The Search Method

Of course the main method is the search method.

Figure 1 – The main entry point of the class
public IList<LiveSearchResults> Search(string searchQuery)
        {
// Basic checks
if ((searchQuery == null) ||
                (searchQuery.Length == 0) ||
                (searchQuery.Trim() == ""))
return null;
IList<LiveSearchResults> webCollection = new List<LiveSearchResults>();
using (MSNSearchService s = new MSNSearchService())
            {
                SearchRequest searchRequest = new SearchRequest();
                searchRequest = SetUpRequest(searchRequest, searchQuery, SearchProperties);
                SearchResponse searchResponse;
try
                {
// If the searchQuery is the same
// Session flag checked in function
if (IsSameSearch(searchQuery))
                        searchResponse = (SearchResponse)HttpContext.Current.Session["searchResponse"];
else // Use Live Search to get the Response
                        searchResponse = s.Search(searchRequest);
// Session flag checked in function
                    GenerateSession(searchResponse, searchQuery);
                    webCollection = CaptureWebResults(searchResponse);
                }
catch (Exception e)
                {
                    ErrorMsg = e.ToString();
                }
finally
                {
// If there was an error
// Logging flag checked in function
if (ErrorMsg.Length > 0)
                        LogMessage("There was an error with searchQuery: " +
                            searchQuery);
else
                        LogMessage("A successful search was made with searchQuery: " +
                            searchQuery);
                }
            }
return webCollection;
        }

This is all the client application is concerned with. In the order of operations, this is how the webservice is consumed via this function.

  1. It creates an instance of the MSNSearchService
  2. It creates a SearchRequest object
  3. It calls a local method to set up and store all the setup information into the newly created SearchRequest object
  4. It creates a SearchResponse object
  5. It queries and stores the search results into the searchResponse object. (s.Search is the query itself)
  6. It sends the searchResponse off to another local method called CaptureWebResults to make a generic list of the results.
  7. Then it hands that list off to a local list object called webCollection and returns the webCollection to the client.
  8. In this case, the client then binds the webCollection to a Gridview control.

Those eight items are essentially all you need to know about the logic of consuming the MSNSearchService in ASP.NET.

You then have the optional session logic in there and the optional logging logic. The IsSameSearch method is a local method to check whether the query is the same. At the same time there is a check with web.config to see if sessions are on. If all is a go, it pulls the searchResponse from the session instead of firing s.Search again, which will create another query. This will ultimately spare your 10,000 query daily limit from getting consumed so fast!

The LogMessage method has a flag that checks whether logging is turned on. ErrorMsg is a public property of the class and is exposed in the LogMessage function.

The main local methods of this class are:

  • SetUpRequest – Here you have the opportunity to let Windows Live know what and how you want your results to be returned. I set up three main Requests in this function. The first is the obvious web request. The second request is the spelling request, which will return the misspelled words. The third request is the Phonebook request for all those Live.Local results.
  • CaptureWebResults – This is the heart of the class. It takes everything in the web service response and stores the data in generic lists. Here we also secure the data and ensure there are no null values. This method fires up another method to handle any spelling suggestions.
  • HandleSpellingSuggestion – This method I got straight from the LiveSearch sdk. It pulls the response from the response object and then turns it into a readable string that’s ready for printing.
  • CheckForNull – As mentioned earlier in this article, a search response may contain null fields. This method ensures there will be no null values stored in the list.
The Web Client

There are many ways a client can go about handling the search method. I decided to go the ObjectDataSource method of handling it. I also decided to use the AJAX 1.0 library for searching and paging and the AJAXControlToolkit for the autocomplete functionality.

The ObjectDataSource

Just writing that makes me want to cringe. I guess it wasn’t as scary as I originally thought. The main challenge was figuring out how to expose the public properties to the web client for the right instance of the class.

So after much trial and error I tried:

Figure 2 – Getting the instance of the class WindowsLiveSearch thisObject = new WindowsLiveSearch();
protected void ObjectDataSource1_ObjectCreated
(object sender, ObjectDataSourceEventArgs e)
  {
    thisObject = (WindowsLiveSearch)e.ObjectInstance;
  }

Now I have the instance of the class used by the ObjectDataSource, and I can expose the public properties to the Web Client.

Another road block came when I wanted to get the total count of the results set. The ObjectDataSource has a Rows.Count method but that only returns the count of the visible rows on the screen, not the entire results set.

So to solve this I used this logic in the ObjectDataSource1_Selected method:

Figure 3 – Getting the return value    try
    {
IList<LiveSearchResults> resultsCollection = new List<LiveSearchResults>();
      resultsCollection = (IList<LiveSearchResults>)e.ReturnValue;
      resultsTotal = resultsCollection.Count;
if (resultsTotal == 0)
        Instructionlbl.Text = "Your search provided no results.";
    }
catch (System.NullReferenceException)
    {
      Instructionlbl.Text = "Please enter a search term.";
    }

I first created a local list object of the LiveSearchResults Type. This type contains public properties that represent the web results returned by the webservice. I used the ObjectDataSourceStatusEventArgs e to get the return value. The return value is what the Search method returns, a generic list. So then I take that list and get the count.

This not only gave me the opprotunity to get the total results count from the generic list, but now I can detect whether a search provided results or whether a search was even performed at all! So I threw an instruction label on the web form to print out those messages to the user.

Figure 4 – Handling Spelling    if (thisObject.SpellingSuggestion.Length > 0)
    {
      Spellinglbl.Text = "Did you mean "
        + "<a href='javascript:void(0);' onclick='submitSpellingSuggestion()' title='"
        + thisObject.SpellingSuggestion
        + "'>"
        + thisObject.SpellingSuggestion
        + "?</a>";
      SpellingSuggestion.Text = thisObject.SpellingSuggestion;
    }
else
      Spellinglbl.Text = "";

Still in the ObjectDataSource1_Selected method I check to see if the spelling suggestion has length. If there is a suggestion, I throw it inside a label..

Figure 5 – Handling the Phone Book Results// Get the Phone Results and bind them
    PhoneResultsView.DataSource = thisObject.PhoneResults;
    PhoneResultsView.DataBind();
    thisObject.Dispose(); // Dispose of this instance

Since I have access to my public properties, I decided to store the PhoneResults in one via the class. I then bind that property to the PhoneResults Gridview Control. I am now done with the class object so I dispose of it..

AJAX AJAX AJAX

My mother thinks I invented a way to clean websites when I mention that I use AJAX in my web applications. My wife can tell anyone I don’t like to clean! So what am I referring to? Well the AJAX library from Microsoft of course! With a few server tags you can be implementing some powerful AJAX features. In this application all I did was surround the portion of the page I wanted updated in the AJAX 1.0 UpdatePanel tag.

Figure 6 – The AJAX 1.0 UpdatePanel tag<asp:UpdatePanel ID="UpdatePanel1" runat="server">
... The Gridview for the web results
... The Gridview for the phonebook results
... The instruction label
... The spelling label
... yada yada yada!
</asp:UpdatePanel>

That is all there is to that! Thanks Microsoft!

Figure 7 – AutoComplete

The AJAXControlToolKit and the AutoComplete function

This was the fun part of the application. What happens when you mix an online dictionary web service with the AJAXControlToolKit? Well nothing, unless you take the AutoCompleteExtender and put it to use. I basically just copied over the example Microsoft made in the toolkit itself and consumed an online dictionary web service instead. So the logic is this. When you finally type at least 3 letters in the search field the AutoCompleteExtender will call a local webservice to handle the operation. This local service then calls the dictionary web service over the Internet and returns words based upon the 3 letter prefix you provided. Cool, huh? Well to make things even cooler you can choose different dictionaries to get different results. This setting is configured in web.config.

Virtual Earth API

To top things off, I decided to add one more piece to this solution: Virtual Earth. The Virtual Earth API offers a way for map enthusiast to display maps via JavaScript. What I wanted to do was present the Live.Local results in a way that a user could mouse over them and get a map of the address in the results. So where would I display this map? To solve this problem I downloaded the latest version of overlibmws, which was spawned from the original overlib library created by Erik Bosrup.

Figure 8 – The overlibmws popup displaying a virtual earth map

After mousing over a result on the right, a JavaScript call throws the address up to the overlibmws handler. This simple JavaScript function throws an iframe in the popup bubble which contains all the logic necessary to search for the local address and display the map. The iframe is actually a .NET webform that takes the address in the form of a QueryString and inserts it into the client side Virtual Earth code. On the screen you can take advantage of all the powerful features Virtual Earth provides, including a 3d view (After a small installation) and Bird’s eye view of the location.

You can easily use Google Maps API instead, but I found Virtual Earth to be more powerful and useful than Google Maps and at the last minute I made a call to use Virtual Earth.

Summary

There are a number of ways to use Live Webservices to customize your own solutions. Because the Search API is a full blow SOAP webservice you have control of the data. The interoperability of Windows Live Services and ASP.NET allows you to easily incorporate a number of features in a short amount of development time. In short, there are a number of ways these services can benefit businesses and organizations by helping users find data faster and helping developers looking for a quick solution to save a few keystrokes.

 

Daniel Penrod

Author profile: Daniel Penrod

Daniel works as an Application Development Specialist for Goodyear Tire & Rubber Company. He primarily uses: Java, C#.NET and occasionally Ruby depending on which type of server he is messing with. He enjoys spending time with his family even if the majority of that time is spent sleeping.

Search for other articles by Daniel Penrod

Reference URL: Using WebServices with ASP.NET

Thursday, November 20, 2008

Using .NET Reflector Add-ins

Andrew Clarke

Using .NET Reflector Add-ins

19 November 2008

by Andrew Clarke

.NET Reflector by itself is great, but it really comes into its own with the help of some add-ins. Here we provide you with an introduction to the Add-ins, explain briefly what they do, and encourage you to write your own in order to get .NET Reflector to work the way you want it to!

Introduction

Whereas .NET Reflector aims to provide all the basic functionality for browsing assemblies and their contents, it has been designed from the start to encourage others to add functionality to it.  Some of these add-ins were written initially by Lutz Roeder as an illustration of the ways that Reflector can be extended, but there have been many other contributions that have turned .NET Reflector into a much more versatile tool that has kept up with all the diverse ways that the NET platform has developed, and has evolved to meet the needs of development teams. It also means that a ‘power’ user can add functionality for particular, almost unique, requirements.

Downloading an add-in

The latest version of most of the add-ins are available from the Codeplex site, and can be retrieved by clicking the Download link next to the listed Add-in, or going direct to the downloads page

Installing an Add-In

Installing an add-in is generally very easy. It is just a matter of copying the add-in to the directory in which you installed .NET Reflector and then registering it on NET Reflector using  the View->Add-ins… Menu item

Clicking on the Add-Ins… menu item displays the Add-ins maintenance dialog box. Clicking on the Add… button allows you to select the DLL file that represents the Add-in you want to register with .Net Reflector.

It really is that simple.

The Add-ins

The existing add-ins are all worth trying out. All the ones listed here are free to download. Some, such as CodeModelView and ClassView are really no more than learning tools for anyone wanting to write an Add-in. Some are ‘alpha’ projects that are awaiting completion, whereas many are complete and would be difficult to improve upon. Not all Add-ins will be useful to the average developer; some were written for a specific use which is unlikely to cause general excitement, and others are useful only very occasionally. Others are essential. It is difficult to make hard-and-fast rules about this, but, for example, anyone developing CLR routines for SQL Server will need  SQL2005Browser, and probably also the  FileGenerator For Reflector, whereas anyone working with Silverlight would do well to have  either SilverlightLoader or SilverlightBrowser.  By using Add-ins, one can make .NET Reflector a far better fit with the architecture you are developing with. We have included those add-ins for IDEs such as Visual Studio and SharpDevelop that allow Net Reflector to be used as part of the IDE, so that, by right-clicking a method or class, it can be examined in .NET Reflector.

The Add-ins can be categorized in the following ways

Languages for the disassembler.
These add to the built-in languages. Each language that is installed is added to the language drop-down list in the icon bar.
McppLanguage, Delphi Language for Net Reflector, PowerShellLanguage, ReflectionEmitLanguage, CppCliLanguage
File Writers.
As .NET Reflector has no built-in way of writing decompiled assemblies out to file, these addins are geared to do this
FileDisassembler, FileGenerator For Reflector
Browser extensions.
These allow assemblies to be fetched from  Silverlight, SQL Server,  running assemblies, zipped files etc.
BizTalk Disassembler, Running Assembly Reflector Add-in, OpenZip, ComLoader,
IDE Addin-managers.
These allow .NET Reflector to be invoked from within Visual Studio and other IDEs.
Building the reflector Add-in, SharpDevelop Community, TestDriven, Hawkeye add-in, Scout
Assembly diagramming and metrics.
E.g. Graph, SequenceViz, CodeMetrics, XMI4dotnet, Autodiagrammer, DependencyStructureMatrix, TreeMap
Sample Add-ins
These were written primarily as example add-ins 
CodeModelViewer, Classview
Comparing assemblies
Diff
Searching and sorting
AssemblyCollection.Sort, CodeSearch
Team-working
Review
Resource Viewers
BamlViewer, Enums, RuleSetEditor
Debugging and modifying assemblies
Reflexil, Deblector
Testing
Doubler, Pex

Author

Name

What

Jason Haley

AssemblyCollection.Sort

This add-in sorts (or reorders) the assembly listing in Reflector alphabetically.

AssemblyListEx

The AssemblyListEx add-in allows you to create assembly list files (.ref) and load a set of assemblies directly into reflector by double clicking on the file.

Sacha Barber

Autodiagrammer

This add-in draws class diagrams. provides the class diagramming capabilities. It is well-documented on  CodeProject

Lutz Roeder.

BamlViewer

This add-in loads assemblies containing BAML resources (e.g. localized resource assemblies) and shows the corresponding XAML.

Gilles Zunino

BizTalk Disassembler

This Add-in will list, and optionally extract, BizTalk artifacts from within an assembly. You can see a list of all artifacts, with their type, name, and the namespace they were compiled into, by rBy then clicking the "Decompile..." button, you can decompile all selected artifacts into source files.

Jamie Cansdale

Building the reflector Add-in

This is a Visual Studio addin called ManagedAddIns that  makes Reflector  into an Add-In for Visual Studio.NET . It allows almost any Windows Forms application to be run as an add-in to Visual Studio

RemObjects

ChromeLanguage

This add-in extended Reflector with a Chrome language rendering module. Now withdrawn.

Lutz Roeder

Classview

Shows class definitions as plain text with color

Coding.  It is a sample add-in which is designed to  illustrate how to add a view window to reflector and to demonstrate using the code model, code translation and language writer APIs

Jonathan de Halleux

CodeMetrics

The CodeMetrics add-in analyses and computes several code quality metrics on your assemblies. This add-in uses Reflector to compute classic metrics such as cyclomatic complexity or more straightforward ones such as the number of local variables in a method. All results can be saved to a file.  When you explore the result, you can double-click on an item to show the item in the browser window. Selecting a column will size the items in the tree map to the values in that column. Using shift+click will assign the values as colors.

Lutz Roeder

CodeModelViewer

This add-in shows the underlying code model objects for a selected node in .NET Reflector. The menu item is registered under the "Tools" menu.

Herve Chapalain

CodeSearch

Code Search is an add-in for .Net Reflector that allows searching within the source code.
You can either search using plain text or using regular expressions like such as … (try).+(catch)?
You can search from the Assembly to the Function level, which means that  you can't search within all loaded assemblies at the same

Jason Haley

CodeShortcut

This provides a 'Create Shortcut' context menu item for creating a ‘code://’ shortcut on your desktop to the item you currently have selected. URI Shortcuts can be transmitted to anyone with Reflector, and the same .dll/.exe that you created a shortcut to. They can also be put on the clipboard by selecting the item and pressing Cntl Alt C

Jonathan de Halleux

ComLoader

Allows importing COM/OLE type libraries using Reflector's file menu. It lists the COM components for browsing and converts them into managed interop assemblies.

Dean Wills,

CppCliLanguage

This is a C++/CLI language rendering module.

Falice Pollano

Deblector

Deblector is an add-in that allows debugging from NET Reflector

Peter Sawatzki, Hallvard Vassbotn

Delphi Language for Net Reflector

This add-in extends Reflector with a Delphi language rendering module.

Tom Carter.

DependencyStructureMatrix

This add-in generates and manipulates Dependency Structure Matrices (DSMs) in order to untangle complex inter-module dependencies, Identify design violations  and Identify cyclic dependencies

Sean Hederman

Diff

This add-in shows differences between two versions of the same assembly. If you select a Framework DLL  in the tree node in the Reflector main window, and then choose Tools->Assembly Diff from the menu, it will display  the Diff automatically. If you select anything else,  you will need to select an assembly from an Assembly selection screen. The Diff utility will remember the match, and will always select that destination assembly when you next select the source assembly, up to 20 matches by default.

Jay Flowers

Doubler

Doubler is a code generator (C# and VB.NET)for unit testing ,especially legacy code. It helps cleave dependencies apart, create test doubles, and write unit tests . It features a

  • Recording Generator – Use against an abstract type. It will create a Recording Test Stub.
  • Fake Generator - Use against an abstract type. It will create a Fake Object.
  • Test Generator – Use against a concrete type. It will generate a unit test fixture and test methods for each public method on the test subject..

Jason Haley

Enums

Enums provides a Bit Flag Converter for helping to determine which bits are turned on by providing an integer or vice versa. This addin also includes an Enum Viewer that is a custom enum disassembler (for VB and C# only) that allows the user to decide whether enum fields should be shown in alphabetical order or by value.

Denis Bauer

FileDisassembler

The Reflector.FileDisassembler can be activated from the Tools-File disassembler menu and is used to  dump the decompiler output to files of any language supported by Reflector (e.g. C#, VB.NET, Delphi). This will then allow file-based searching or  help to convert a class from one language to another.

Jason Bock

FileGenerator For Reflector

This Add-In generates code and resource files for a selected assembly, module, namespace, or type. It also creates a VS project file to see the generated files in Visual Studio.

Jonathan de Halleux

Graph

This add-in draws assembly dependency graphs, IL flow graphs and class diagrams. Recommended.

Hawkeye add-in

HawkEye, a free tool for debugging the UI tree of Windows Forms applications, is able to use Reflector by means of an Add-in . If you select your element,  and select ‘Show source code’ on the context menu, Hawkeye will immediately ask Reflector to show you the source code of the selected element, whether it is a field, property, event, method or class.

McppLanguage

A Managed C++ language add-in for .NET Reflector.

Jason Haley

OpenZip

The OpenZip addin makes it easier to add a dll/exe from a zip file into Reflector's list of assemblies. The addin places itself on the File menu with the other Open commands. When you choose it, a dialog will open allowing you to browse to a zip file. Once you have chosen a zip file, any dlls or exe's will show up in the list box allowing you to select it. Once you have selected all the assemblies you want to extract and add to Reflector, you can open it as usual.

Jonathan 'Peli' de Halleux

Pex

This add-in allows you to start the Pex wizard directly from Reflector. The wizard generates a suite of parameterized unit tests from any assembly. This suite can later be run through Pex to generate unit tests.

Daniel Cazzulino

PowerShellLanguage

This provides an extra entry in the language list for Powershell. If selected, It will decompile the IL into Powershell

Jonathan de Halleux

ReflectionEmitLanguage

This add-in translates the IL code of a given method into the C# code that would be needed to generate the same IL code using System.Reflection.Emit

Sebastien LEBRETON

Reflexil

Reflexil is an assembly editor and runs as a plug-in for Reflector. Using Mono.Cecil, written by Jb Evain, Reflexil is able to manipulate IL code and save the modified assemblies to disk. Reflexil also supports 'on the fly' C# and VB.NET code injection.

Jonathan 'Peli' de Halleux

Review

This is a lightweight code annotation tool for Reflector that can be used during code reviews or API reviews to take notes and pass them to other project members. It stores the annotations in an XML-based Review file.  These Review files can be merged.

Review files consist of code annotations. These consist of a list of changes. Each change consists of a comment, a date, a user, a status and resolution. To avoid losing any information, changes are written to disk after each 'commit'.

RuleSetEditor

This allows editing, assign, or removing rules from a rule set in Windows Workflow Foundation

Kevin Dente

Running Assembly Reflector Add-in

This Add-in will open an assembly or dependency from a process that is running on the system. The add-in adds a new menu to the Tools menu called “Open Running Assembly“. When you select it, the add-in displays a dialog that displays a list of managed processes running on the system. You can choose the process, or any managed assembly loaded in that process, and the selections will be loaded  into Reflector.

pbludov

Scout

Integrates Reflector into Resharper

Nauman Leghari

SequenceViz

This is a reflector addin using the WPF renderer to generate a sequence diagram or code flow

Christian Hornung

SharpDevelop Community

This is an add-in to the free SharpDevelop  source-code editor. It opens NET Reflector directly from the SharpDevelop 221 and positions it on the selected code element. Reflector will load the required assembly and directly go to the selected method (or classes and other types of class members). This is now integral to the current SharpDevelop 3.0 so is no longer required

Ernie Booth

SilverlightBrowser

This loads and shows the files associated with a Silverlight website. It takes a URL to a Silverlight page and finds the assembly for that page. It also loads up the JavaScript and root Xaml for the page.

SilverlightLoader

This add-in adds an item in the File menu to allow you to  browse a Silverlight website and load assemblies from it.

Denis Bauer

SQL2005Browser

This allows you browse of .NET assemblies within databases stored in a local or remote SQL Server 2005 instance, and download them directly into .NET Reflector

Jamie Cansdale

TestDriven

This is a Visual Studio add-in. Within Visual Studio,  Right click and 'Test With... Reflector' to navigate to any code element inside Reflector. This works with methods, types, fields, events, enums and delegates.

Jonathan de Halleux

TreeMap

This is Peli's bid to use an Add-in to  compute and visualize coverage, and inspire others to write  Reflector Addins for code coverage visualization.

Andrew Cain

XMI4dotnet

This is an Add-in that allows you to export an assembly to an XMI file that can then be imported into a variety of UML tools. Xmi4DotNet examines your assembly and exports XMI  It is useful for exporting your code model into a UML package to simplify drawing.


Writing or modifying an Add-in.

Writing an Add-in, or modifying an Add-in, is reasonably easy, and will not tax any experienced .NET programmer.  Because most of the Add-ins are available in source-code on CodePlex, one can get a long way by modifying these for particular requirements, or to change the interface to suit the way you work.  There is also Jason Haley’s great resource for Add-In writers, that includes templates and walkthroughs to make the work even easier. He includes easily-followed instructions on getting started.  Lutz has even provided a ‘Hello world’ add-in to get started with.  If you write anything that could be of use to another .NET Reflector users, then please add it to the Codeplex archive

This article has been viewed 252 times.

Andrew Clarke

Author profile: Andrew Clarke

Andrew Clarke has been developing software applications for over 25 years. He is a database expert, but has a particular interest in website-publishing and ECommerce. He recently worked with the first two winners of the 'Apprentice' program at Amstrad, creating various business applications, and since worked with Tim Campbell setting up the 'Bright Ideas Trust'. He also subedits and reviews articles for Simple-Talk.

Search for other articles by Andrew Clarke

REFLECTION AND ATTRIBUTES (Part Two) - The System.Type Members

Today I am going to continue my series of Reflection And Attributes Tutorial. Lets begin with System.Type Members.

System.Type Members

Once a Type object is created, the fun begins. You can use Type properties and methods to inspect the type’s constructors, methods, attributes, fields, interfaces, and events. Examples
of their use are provided throughout this chapter.

For each method that returns an array of types or members, there is a corresponding method (same name without the final “s”) that searches for a single member or value. For example, to return a Type reference to the IDictionary interface, you could use:

Type hType=Type.GetType("System.Collections.Hashtable");
// Return null if interface no inherited
Type inType = hType.GetInterface("IDictionary");

Core Note

Most of the Type methods include an overload with a BindingFlags parameter. BindingFlags is an enumeration that includes values that can be used to filter the reflection search for members and types. Some of its more useful members include NonPublic, Public, Static, and DeclaredOnly (not inherited).


that's it for today.

Related topic:

REFLECTION AND ATTRIBUTES (Part One)

Related Post:

Reflection – Finding Type Members

C# .NET Reflection : Obtaining a Type Object with Object.GetType()

Monday, November 3, 2008

REFLECTION AND ATTRIBUTES (Part One)

Today I decided to post a series of tutorials about Reflection and Attributes from the free chapter of Core C# book.  So I'm going to start it with Reflection (Creating a Type Object).  Read the first part of the chapter below:

 

19.1 Reflection

  In general terms, reflection is the ability of a system to reason and act upon itself.  More specifically, .NET supports reflection as a mechanism for reading an assembly’s metadata in order to glean information about types within the assembly. It has many uses. For example, VS.NET uses it to implement Intellisense; and .NET object serialization relies on reflection to identify whether a type can be serialized (by looking for the SerializableAttribute) and which of its members are serializable.

While reflection is a powerful technique, it’s not difficult to understand. Think of the reflection API as a set of methods that can be applied at each level of the .NET coding hierarchy. The Assembly.GetTypes method yields all the types in an assembly
as System.Type objects. The System.Type class, in turn, exposes methods that return a specific type’s properties, methods, constructors, events, and fields. At an even more granular level, you can then examine the parameters of a method or constructor.

Before a type (class, struct, array, enum, generic types, value types, or interface) can be reflected, a Type reference must be acquired for the type. This reference is the key that unlocks the door to the .NET reflection API.

 

The System.Type class

System.Type is an abstract class whose members provide the primary means of accessing the metadata that describes a type.

Syntax:
public abstract class Type : MemberInfo, _Type, IReflect

The Type class inherits from the MemberInfo class and two interfaces—_Type and IReflect. Of these, MemberInfo is of particular interest. It serves as the base class for some of the most important classes in the reflection namespace, and defines
many of the methods and properties that provide information about a type’s members and attributes. We’ll look at it in detail shortly.


Creating a Type Object

In order to use reflection to examine a type’s metadata, it is first necessary to obtain a reference to a Type object that is associated with the type to be reflected. There are several ways to obtain a Type object reference. The choice varies depending on whether the object is being created from a type’s definition or an instance of the type.  To illustrate the first case, consider the following code segment that lists the methods for the System.Object class.

// (1) Get Type for System.Object definition
          
Type obType = typeof(System.Object);
            // Alternative: Type obType= Type.GetType("System.Object");
            // (2) Call a method to return list of methods for Object
          
MethodInfo[] mi = obType.GetMethods();
            for(int i = 0; i < mi.Length; i++)
            {
                MethodInfo myMethodInfo = (MethodInfo)mi[i];
                Console.WriteLine("Method name: {0}({1})",
                myMethodInfo.Name, myMethodInfo.ReturnType);
                /* Output:
                Method Name: GetHashCode (System.Int32)
                Method Name: Equals (System.Boolean)
                (remaining methods listed here)
                */
          
}


This example uses the C# typeof operator to obtain a Type reference. Alternatively, the Type.GetType method, which accepts a type’s name as a string value, could be used. Once the Type object is obtained, the Type.GetMethods method is called to return an array of MethodInfo objects that represent the methods for the type. The Name and ReturnType properties of the MethodInfo class expose the name and return type of each method.  To acquire a Type object reference for an instance of a type—rather than its definition—use the GetType method that all types inherit from System.Object:

Device myDevice = newDevice(); // Create class instance
Type t = myDevice.GetType(); // GetType reference
// Reflection can also be used on value types
int[] ages = { 22, 43, 55 };

Type ageType = ages.GetType();
Console.WriteLine(ageType.Name); // Output: Int32[]

Later in this section, we’ll see how to use the Assembly.GetTypes and Module.GetTypes methods to obtain Type object references for types in an assemblyand module, respectively.

So there it goes that's the first part of chapter 19 of the book Core C#, on the next series I am going to post the System.Type Members

Related topic:

REFLECTION AND ATTRIBUTES (Part Two)

Related Post:

Tuesday, October 28, 2008

.NET Reflector: Soup to Nuts by Andrew Clarke

I found this great post last week on simple-talk and I decided to repost it here on my blog. Happy Learning!

Andrew Clarke

.NET Reflector: Soup to Nuts

22 October 2008

by Andrew Clarke

Nobody could  accuse .NET Reflector of being over-documented. The information is around, but has never, up until now, been pulled together into one place.  We decided to try to make a start! This article supplements the demonstration video by Jason Crease, which comprehensively covers the basics of how to use .NET Reflector, and which should be seen first if you are new to NET Reflector.

NET Reflector has a special place in the pantheon of NET Development tools. It was first written by Lutz Roeder when the .NET Framework was still in beta, and since then has developed alongside it. So ubiquitous has it become that .NET Developers use its' name as a verb, as in 'let's reflector it'. What they mean is to browse and investigate the assemblies that comprise the code with a tool that is capable of showing what's there, and how classes, methods, or entire assemblies relate to each other, within the context of the application.

Why use .NET Reflector?

NET Reflector gives you the means to inspect, analyze, and browse the contents of a .NET component, such as an assembly. It will show you the metadata, IL instructions, resources and XML documentation. This tool can disassemble the instructions into source code in a variety of .NET languages, and translates the other binary information into an intelligible form. It does this through a process called 'reflection', which retrieves information about the various classes, methods, and properties included in a particular assembly (hence the name of the tool).

Most likely, you'll need .NET Reflector to track down performance problems and bugs. It is great for browsing classes, and maintaining, or becoming familiar with, code bases. Some of its features include:

  • An Analyzer option, which can be used to find assembly dependencies, and even windows DLL dependencies.
  • A call tree and inheritance-browser, which will pick up documentation or comments, stored in the xml files that are used to drive Intellisense inside Visual Studio. It will then display this information alongside the associated assemblies.
  • Ability to cross-navigate related documentation (xmldoc), searching for specific types, members and references.
  • Ability to convert your source between languages, such as C# and VB!

All sorts of questions crop up during development that can be answered with .NET Reflector:

  • What line of code is producing that error message?
  • What uses a particular piece of code, and what code does it, in turn, use?
  • How does a class, method, or entire assembly fit into your application?
  • What are the differences between two versions of the same assembly?
  • What features of the API of some legacy code can you use?
  • How do the various parts of your system interact with each other?

When you're working on a large team-based project, .NET Reflector is often the quickest way of getting a clear insight into how the application is working and where the bugs and weaknesses are. There is a great difference between knowing the public interface of a module and actually seeing what the code does.

Once .NET Reflector is combined with add-ins, it can become a tool to facilitate testing and make team-working more effective. There have been many occasions when .NET Reflector has assisted in the recovery of source code after it has been lost.

What is in a .NET Assembly?

Essentially, .NET Reflector allows you to 'see' what is in a .NET assembly.

A .NET language compiler will produce binary CIL (MSIL) code, and any resources that are required, in a file called an 'assembly'. The binary CIL code is written for a theoretical stack-based processor, to make it easy to run assemblies securely on different processors, in any environment supporting the .NET framework.

Then, a just-in-time (JIT) compiler will compile this abstracted, language-independent binary code, and optimise it into actual machine 'native' code for the target processor, and compile all the resources used. The .NET Common Language Runtime (CLR) supplies at least one JIT compiler for every NET-supported computer architecture, so the same set of CIL can be JIT-compiled and run on different architectures.

The CIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. It is designed to support polymorphism, inheritance, abstract types, and so on. When a high level language, such as C#, compiles code, it converts it to CIL. The process is reversible but because it is possible for two different high-level syntaxes to produce the same CIL, it may not be exactly the same as the original code.

As well as producing CIL, a .NET compiler will also produce metadata. This will contain everything needed for runtime, sufficient for the code to describe itself during execution without needing type libraries or the Interface Definition Language (IDL), and allowing JIT compilation, linking and introspection to work.

All the classes and class members that are defined in the assembly, as well as the external classes and class members called from the assembly, are described in the metadata, as are all the class methods. This includes details of its parameters, the return type, and the assembly in which it belongs. When the CLR executes CIL, it checks that the metadata of the called method matches that of the calling method. This metadata is used by the process of reflection, and is read by ..NET Reflector.

As well as the metadata, the assembly will also contain any required resources such as attributes, custom attributes, images and strings, and will also contain security information. You can browse this information from within reflector, as shown in Figure 1:

Figure 1: .NET Reflector displaying string resources

The whole assembly is put in an extended version of the portable executable (PE) file, used for executables, object code, and DLLs, and which enables the operating system to recognize common language runtime images. The PE file has only one import – mscoree.dll – which then loads the CLR Header and Data sections, and runs the assembly's just-in-time (JIT) compiler. The PE header's data directory contains a .NET directory entry, which points to a new header in the file containing everything the operating system needs to run it.

.NET Reflector, ILASM and ILDASM

Microsoft supplies two tools for investigating assemblies:

  1. ILASM, the Microsoft IL Assembler. It will take an ASCIII assembly language source-code file, and produce binary IL (MSIL) code. It adds in all the specified resources to create the assembly.
  2. ILDASM, the .NET disassembler. This is part of the .NET framework, and works the other way round. It will produce an 'assembly' file from an IL file. This assembly file is very much like a traditional Assembly source code file.

They are designed to be complementary, so that the output of one can go into the other to produce an identical file to the original.

The ILASM and ILDASM tools are useful, but not sufficient by themselves. Unfortunately, ILDASM is best only with CLI assembly sections, whereas EXE files are in PE format, which ILDASM may not extract correctly. The tool will show method signatures and member variables, but the code will be in .NET byte code.

To be able to extract everything you want from a NET assembly, in the language that was used originally to create the assembly, you will need .NET Reflector. This will also allow you to browse and inspect the other resources in the assembly, and even the XML documentation used by the IDE that created the assembly.

.NET Reflector, as we've said, uses 'Reflection' to do its work. Reflection is used to retrieve information about the various classes, methods, and properties included in a particular assembly. Reflection has to determine the interface, structure, enumeration, or delegate of a type at runtime. This process can be used to examine any .NET code, whether a single class or an entire assembly, and .NET Reflector uses this process to make sense of the contents of an assembly.

Reflector cannot view itself.  It needs to use reflection but, because .NET Reflector needs to work with all versions of the .NET Framework, it uses its own assembly loading infrastructure, which does not rely on the Reflection API. This allows .NET Reflector to load .NET Framework 2.0 assemblies without having the .NET Framework 2.0 installed. However, it also makes it difficult for anyone trying to explore how .NET Reflector works!

Installing, Registering and Launching .NET Reflector

.NET Reflector was written by Lutz Roeder, and has evolved over the entire life of the .NET Framework. It was first released in October 2000 running on .NET Framework 1.0 Beta. It has been updated continuously to work with each new release of the framework and is now on Version 5. This current version supports query expressions and other concepts introduced in C# 3.5 but only if you select ".NET 3.5" as the optimisation within the menu (under View |Options | Disassembler | Optimization). Along the way, a number of additions have been made, on request, sometimes for very general requirements, but occasionally for supporting special uses.

Lutz provided licenses only to users who register their names and email addresses. Registration was, and remains, free, but the software was never open-source or in the public domain. The new owners, Red Gate, will continue with this policy.

The application comes as a zipped package without an installer. It consists of .NET Reflector, the configuration file, license file and readme file.

Reflector can be launched, unregistered, just by clicking on the file in Explorer. However, there are many advantages to registering it with the Windows Shell.

You can register Reflector simply by issuing the following from the command line:

Reflector.exe /register

Once Reflector is integrated into the Windows shell, you can simply right-click on any DLL to open and browse it using Reflector, as shown in figure 2:

Figure 2: Immediately you've registered the program, life becomes easier (Note the context menu)

You can unregister Reflector by issuing:

Reflector.exe /unregister

As discussed, once registered, you'll generally launch Reflector just by clicking on the file in Explorer. However, if you are using reflector as a tool for several projects you may want to invoke it from the command line, using a particular configuration file (more on this later) for each project:

Reflector.exe  /configuration:<filename>

Or, to specify the assembly you wish to examine:

Reflector  <assembly>

This syntax is used by the operating system to display assemblies on startup of .NET Reflector once .NET Reflector is registered.

A Quick Spin through .NET Reflector

The following sections provide a simple example of the "disassembling" power of Reflector, followed by a brief tour of some of the useful features that are enabled once you register the tool with the operating system.

Disassembling Hello World

We can create the simplest possible program, and assemble it:

Figure 3: Assembler source code for  Hello World

And, at the command-line, execute:

C:\WINNT\Microsoft.NET\Framework\v2.0.50727\ilasm.exe helloWorld.il

Run the program:

HelloWorld.exe

You can then do one of the following…

  • Drag and drop it into Reflector
  • Use 'File-> Open' in Reflector (or Ctrl O)
  • Use the following URI (from Notepad, for example):
    code ://HelloWorld:1.0.0.1/<Module>/main()
  • Pop the above URI in your browser (if you ran Reflector.exe /register)
  • Run reflector from the command line

And this is what you'd see…

Figure 4: Hello World in Reflector, with disassembler window set to IL

Notice that the disassembly is not perfect, because some symbolic information is always lost in the original compilation.

Ever wondered how what the PowerShell 'Hello world' looks like?

Figure 5: PowerShell Hello world!

You can right-click any type or Assembly, or press Ctrl-R, to see what the class depends on, and what is exposed by, instantiated by, and assigned by the class.

Figure 6: The analyser looking at class dependencies

Maintaining Assembly lists

When you launch Reflector for the first time, you can choose a default set of assemblies. With .NET Reflector, you can create the groups of assemblies that you are interested in, and open/browse them as a set. The list of assemblies is stored in the Reflector configuration file, Reflector.cfg, and will be loaded next time you open the program. Reflector allows you to create as many assembly lists as you want.

As discussed earlier, not only can you define and store an assembly set into a file, but you can also launch reflector.exe with a particular assembly list file, via the command line.

Creating, selecting and deleting assembly lists in Reflector can be slightly confusing at first because it's not immediately obvious that the place to go to do it is the File | Open List dialog box. You can create new lists from the box by clicking 'Add' to clone the current list.You can also remove assembly lists from the same dialog box.

Figure 7: Managing your assembly lists!

You can switch between assembly lists with the same dialog box, or from the command line. To choose a different set of default assemblies for the current assembly list you should:

  1. Remove all assemblies from the list, by selecting them and using the Delete key
  2. Invoke the Refresh command.
  3. Add the assemblies to make up the set

This feature makes it easy to browse a variety of projects and frameworks, even if they have conflicting names

Sharing URIs

One of the great advantages of registering Reflector is that you can then, from within reflector, 'bookmark' any item within an assembly just by recording a custom URI for it (i.e. putting the URI on the clipboard by pressing Ctrl-Alt-C). Once a URI is clicked on, .NET Reflector displays the item. The URI includes the version and hash value for the assembly.

The URI can be shared with fellow developers to provide a link to the item, since it only requires the other person to have Reflector and the same .dll/.exe to which you created a shortcut. There is also a CodeShortcut add-in that allows you to save URIs on the desktop.

So, if you click on the following URI:

code://System.Xml:2.0.0.0:b77a5c561934e089/System.Xml.XmlConvert

You will see something similar to figure 7:

Figure 7: Opening a file in Reflector from a URI

Reflector Add-ins

A number of add-ins have been written for Reflector most, but not all, of which are open-source. There are many different add-ins and it is best to get an up-to-date listing and description than to rely on an article like this that will soon get out-of-date. An up-to-date listing is always kept at CodeProject:

http://www.codeplex.com/reflectoraddins

Some of the add-ins extend the language that Reflector disassembled to, such as PowerShell, Delphi, and MC++. Other add-ins will analyse assemblies in different ways, such as providing quality metrics, sequence diagrams, class diagrams, dependency structure matrices or dependency graphs. It is possible to use add-ins to search text, save disassembled code to disk, export an assembly to XMI/UML, to do side-by-side comparisons of different versions of code, or to search code.

Add-ins are being added the whole time and include those that: allow the debugging of processes, Facilitate testing by creating stubs and wrappers and allow browsing assemblies in other .NET foundations, such as Silverlight, WWF, Biztalk, SQL Server,  or windows Forms

There are also a range of utility add-ins, one of which allows .NET Reflector to be used within Visual Studio, and another that allows you to save the URI shortcuts of an item onto the desktop

Conclusions

.NET Reflector has always been an essential tool for understanding NET assemblies. There are many reasons for wanting to look at what is going on in an assembly. Any developer will need to do so, even if it is just a tool to help with understanding performance issues. With all the features that have been added over the years in response to requests by developers, and the add-in contributions, it has become a tool that it is impossible to be without when doing .NET software development.

Andrew has, for a while, been helping to flesh out the Wikipedia entry for .NET Reflector, and has modified parts of this article to do so. We're very conscious that .NET Reflector is generally very easy to use, and in that sense doesn't need documentation, but some features, such as the use of URIs, aren't intuitive! If you would like to add to this article, or you spot errors, then send an edited version to editor@Simple-Talk.com and we'll update the article and add you to an acknowledgements section.

Acknowledgements

  • Lutz Roeder, Jason Haley, and countless bloggers about .NET Reflector for supplying material
  • Bart Read for checking the first draft
  • Tony Davis for proofing the Article
  • Colin Patel-Murray for spotting a typo

Andrew Clarke

Author profile: Andrew Clarke

Andrew Clarke has been developing software applications for over 25 years. He is a database expert, but has a particular interest in website-publishing and ECommerce. He recently worked with the first two winners of the 'Apprentice' program at Amstrad, creating various business applications, and since worked with Tim Campbell setting up the 'Bright Ideas Trust'. He also subedits and reviews articles for Simple-Talk.

Search for other articles by Andrew Clarke

Monday, October 27, 2008

Ongoing Phishing Attack Exposes Yahoo Accounts

The Netcraft toolbar community has detected a vulnerability on a Yahoo website, which is currently being used to steal authentication cookies from Yahoo users — transmitting them to a website under the control of a remote attacker. With these stolen details, the attacker can gain access to his victims' Yahoo accounts, such as Yahoo Mail.

The attack exploits a cross-site scripting vulnerability on Yahoo's HotJobs site at hotjobs.yahoo.com, which currently allows the attacker to inject obfuscated JavaScript into the affected page. The script steals the authentication cookies that are sent for the yahoo.com domain and passes them to a different website in the United States, where the attacker is harvesting stolen authentication details.

When websites use cookies to handle authenticated sessions, it is extremely important to protect the cookie values and ensure they are not seen by other parties. Cross-site scripting vulnerabilities often allow these values to be accessed by an attacker and transmitted to a website under their control, which then allows the attacker to use the same cookie values to hijack their victim's session without needing to log in. This type of attack can be mitigated to some extent by using HttpOnly cookies to prevent scripts gaining access to the cookies — a feature that is now supported by most modern browsers.

Earlier this year, Netcraft blocked a similar flaw on another Yahoo website. The previous attack targeted a cross-site scripting vulnerability on Yahoo's ychat.help.yahoo.com site, which was served securely using a valid SSL certificate, adding further credibility to the attack. The attacker used the vulnerability to inject malign JavaScript into one of the site's webpages. Unlike the current attack, the injected code was sourced from a server in Spain, but also resulted in the victim's cookies being stolen and transmitted to a PHP script on the same server.

pula.js-resized.png
The small cookie-stealing script injected by the attacker.

hotjobs-yahoo-xss.png
A similar technique employed by the current attack.

In both cases, Netcraft found that the Yahoo cookies stolen by the attacker would have allowed him to hijack his victims' browser sessions, letting him gain access to all of their Yahoo Mail emails and any other account which uses cookies for the yahoo.com domain.

Simply visiting the malign URLs on yahoo.com can be enough for a victim to fall prey to the attacker, letting him steal the necessary session cookies to gain access to the victim's email — the victim does not even have to type in their username and password for the attacker to do this. Both attacks send the victim to a blank webpage, leaving them unlikely to realise that their own account has just been compromised.

ychat-resized.png
Both attacks send victims to a innocuous-looking, blank webpage.

The Netcraft Toolbar protects users against both of these attacks, warning that the malformed Yahoo URLs contain cross-site scripting elements, and that the URLs have been classified as known phishing sites.

Netcraft has informed Yahoo of the latest attack, although at the time of writing, the HotJobs vulnerability and the attacker's cookie harvesting script are both still present.

Reference URL: Netcraft

Sunday, October 26, 2008

Terrorist 'tweets'? US Army warns of Twitter dangers

WASHINGTON (AFP) - - A draft US Army intelligence report has identified the popular micro-blogging service Twitter, Global Positioning System maps and voice-changing software as potential terrorist tools.

The report by the 304th Military Intelligence Battalion, posted on the website of the Federation of American Scientists (FAS), examines a number of mobile and web technologies and their potential uses by militants.

The posting of the report on the FAS site was reported Friday by Wired magazine contributing editor Noah Shachtman on his national security blog "Danger Room" at wired.com.

The report is not based on clandestine reporting but drawn from open source intelligence known as OSINT.

A chapter on "Potential for Terrorist Use of Twitter" notes that Twitter members sent out messages, known as "Tweets," reporting the July Los Angeles earthquake faster than news outlets and activists at the Republican National Convention in Minneapolis used it to provide information on police movements.

"Twitter has also become a social activism tool for socialists, human rights groups, communists, vegetarians, anarchists, religious communities, atheists, political enthusiasts, hacktivists and others to communicate with each other and to send messages to broader audiences," the report said.

Hacktivists refers to politically motivated computer hackers.

"Twitter is already used by some members to post and/or support extremist ideologies and perspectives," the report said.

"Extremist and terrorist use of Twitter could evolve over time to reflect tactics that are already evolving in use by hacktivists and activists for surveillance," it said. "This could theoretically be combined with targeting."

The report outlined scenarios in which militants could make use of Twitter, combined with such programs as Google Maps or cell phone pictures or video, to carry out an ambush or detonate explosives.

"Terrorists could theoretically use Twitter social networking in the US as an operation tool," it said. "However, it is unclear whether that same theoretical tool would be available to terrorists in other countries and to what extent."

Besides Twitter, the report examined the potential use by militants of Global Positioning Systems and other technologies.

"GPS cell phone service could be used by our adversaries for travel plans, surveillance and targeting," it said, noting that just such uses have been discussed in pro-Al-Qaeda forums along with the use of voice-changing software.

"Terrorists may or may not be using voice-changing software but it should be of open source interest that online terrorist and/or terrorist enthusiasts are discussing it," the report said.

Reference URL: Yahoo News

Tuesday, October 21, 2008

Microsoft Web Application Installer

The IIS team of Microsoft have new Web Application Installer, follow the blog of Rob Conery of SubSonic to learn more.

Overview

The Web Application Installer Beta is designed to help get you up and running with the most widely used Web Applications freely available for your Windows Server. Web AI provides support for popular ASP.Net and PHP Web applications including Graffiti, DotNetNuke, WordPress, Drupal, OSCommerce and more. With just a few simple clicks, Web AI will check your machine for the necessary pre-requisites, download these applications from their source location in the community, walk you through basic configuration items and then install them on your computer.

System requirements

  • Supported Operating Systems are: Windows Vista RTM, Windows Vista SP1, Windows Server 2008
  • You must have administrator privileges on your computer to run Web Platform Installer Beta
  • .NET 2.0 Framework
  • Supported Architectures: x86 and 64-bit

Friday, October 17, 2008

What is Visual WebGui?

I have a little conversation with our Architech who lives in Florida and I've learned from him this Visual WebGui. I believe this is something interesting. We are going to use this in our next Enterprise Application.

What is Visual WebGui?

Visual WebGui introduces a different approach to AJAX front-ends. While the trend is towards empowering the client (browser) with more capabilities, enabling direct consumption of services by client side objects and distributing processing between the client and the server, WebGui adopts the server based computing approach whereby service consumption and processing is handled on the server and human interaction is handled on the client. This model provides intrinsic benefits for enterprise applications since it provides additional measures of security and control which are not available on browser based solutions. This approach, called "Empty Client", employs de-coupled GUI components which decouple GUI logic from GUI presentation (rendering) and enable remoting of the display/input capture between the client (browser) and the server. It is this approach that provides an even greater benefit by enabling application logic (usually entailing both business and presentation logic) to be handled within one, stateful, object-oriented environment developed in a high level, OOP language such as C#, VB.Net or Java rather than a mix between Javascript and a server based language.

Using a homogenous platform provides developers with immeasurable productivity benefits and enables developers to make better use of existing assets, knowledge and experience rather than requiring the steep learning curve of AJAX. Visual WebGui provides server side controls which behave like existing desktop application controls both in design time and in run-time. These controls manifest themselves as AJAX controls on the browser in run-time and look like their desktop counterparts. The architecture of the system is in no way limited to representing these base controls in their current "desktop" look and feel since it makes use of de-coupled components. Our initial offering contains the popular Microsoft controls that are a basic part of any Windows based application. These controls provide a huge productivity benefit to web developers who lag behind their desktop bretheren, while supporting the most common needs of desktop application developers without letting them down.

In addition the system is extremely extensible. Visual WebGui's SDK enables extending the framework by adding additional controls, changing themes/flavors (skins), creating composite controls based on base controls and creating gateway components. Since ultimately Visual WebGui is an extension to the app servers context (in the case of .Net an extention to IIS/ASP.net) it can interoperate with client side and server side legacy code. This means that Visual WebGui UIs can host and interoperate with existing HTML/Javascript client only controls or with embedded DOM objects such as Applets and ActiveX controls. Similarly existing web applications can interoperate with WebGui components/forms/windows since they are in essence URLs like any other sharing the same application and session context.