Pages

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: