Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Depends4Net - Part 1

0.00/5 (No votes)
1 Sep 2011 1  
Dependency Walker light for .NET using a separate AppDomain and the reflection-only context

Introduction

I’ve been looking for something like “Dependency Walker” for a while – something that simple to deploy. Currently Depends4Net allows me to view a tree of all dependent assemblies – even those not present on the system, or otherwise inaccessible to the rather simple assembly resolver currently implemented, in a manner similar to “Dependency Walker”.

A .NET 2.0 Windows Forms based version of the utility is available in the second part of this series. Also includes a preview of an Expression Dark like style for the WPF DataGrid.

Depends4NetFound600.png

While far from production quality, it’s still a useful little tool that allows me to figure out which assemblies are missing from a given installation. The code depends on the WPF Toolkit, included with Visual Studio 2010, and does not require any other framework to build. You can easily use this code to create a command line utility requiring nothing but a working .NET 4 installation.

To keep things interesting, I load the assemblies into a separate application domain, and this presents us with a few challenges. As the .NET Assembly class is [Serializable], accessing the assembly directly would actually load the assembly into the current domain, and hence defeat the whole purpose of creating a separate domain, so another type must be used to transfer information about the loaded assemblies back to the primary AppDomain. A bit of testing also seems to indicate that this gives us the correct version the .NET Framework libraries.

The class responsible for loading the assemblies is part of the primary assembly for the application, and as I really want to be able to load assemblies from any location, this requires a little trick.

AppDomainSetup domainSetup = new AppDomainSetup();

domainSetup.ApplicationName = fileInfo.Name;
domainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;

appDomain = AppDomain.CreateDomain("ReflectionLoader", null, domainSetup);

Loader loader = (Loader)appDomain.CreateInstanceAndUnwrap
			(Assembly.GetExecutingAssembly().FullName, 
    "Harlinn.Depends4Net.Utils.Assemblies.Loader");
loader.AddPath(fileInfo.DirectoryName);

loader.LoadAssembly(filename);
assemblies = loader.Assemblies;
rootAssembly = loader.RootAssembly;

Notice that the domainSetup.ApplicationBase is set to the BaseDirectory of the current domain – this allows appDomain.CreateInstanceAndUnwrap to locate the currently executing assembly and create an instance of the Loader class. At this point, the new AppDomain does not know where to find the assembly we want to inspect – so we pass the “real” ApplicationBase to loader.AddPath before calling loader.LoadAssembly.

The Loader

The Loader class is derived from MarshalByRefObject, so when we call loader.AddPath and loader.LoadAssembly the code is executed in our new AppDomain and not in the primary AppDomain. So when we implement loader.LoadAssembly

public void LoadAssembly(string filename)
{
    if (File.Exists(filename))
    {
        AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoaded;
        try
        {
            InternalLoadAssemblyFrom(filename);
                    
        }
        finally
        {
            AppDomain.CurrentDomain.AssemblyLoad -= OnAssemblyLoaded;
        }
    }
}

AppDomain.CurrentDomain refers to the new AppDomain. By adding our OnAssemblyLoaded event handler to the AssemblyLoad event, we get notified whenever an assembly gets loaded into the domain. Since we are using Assembly.ReflectionOnlyLoadFrom and Assembly.ReflectionOnlyLoad to load assemblies, the event handler loads referenced assemblies into the AppDomain until all the resolvable assemblies are found, and we also add an AssemblyInfo element for each assembly we are unable to locate – as my primary reason for writing Depends4Net is to collect information about missing assemblies.

void OnAssemblyLoaded(object sender, AssemblyLoadEventArgs args)
{
 Assembly loadedAssembly = args.LoadedAssembly;
 AssemblyName assemblyName = loadedAssembly.GetName();
 
 AssemblyInfo assemblyInfo = new AssemblyInfo();
 assemblyInfo.AssemblyName = assemblyName;
 assemblyInfo.ManifestModuleName = loadedAssembly.ManifestModule.Name;
 assemblyInfo.LoadedFromGlobalAssemblyCache = loadedAssembly.GlobalAssemblyCache;
 assemblyInfo.Location = loadedAssembly.Location;
 assemblyInfo.Found = true;

 assemblies.Add(loadedAssembly.FullName, assemblyInfo);
 if (currentReferencingAssembly != null)
 {
  currentReferencingAssembly.
           ReferencedAssemblies.Add(loadedAssembly.FullName, assemblyInfo);
  assemblyInfo.FirstLoadedBy = currentReferencingAssembly;
 }
 else
 {
  rootAssembly = assemblyInfo;
 }

 AssemblyName[] referencedAssemblies = args.LoadedAssembly.GetReferencedAssemblies();
 
 if (referencedAssemblies.Length > 0)
 {
  AssemblyInfo previouslyReferencingAssembly = currentReferencingAssembly;
  currentReferencingAssembly = assemblyInfo;
  try
  {
   foreach (AssemblyName referencedAssemblyName in referencedAssemblies)
   {
    if (assemblies.ContainsKey(referencedAssemblyName.FullName) == false)
    {
     string fileName = resolver.Resolve(referencedAssemblyName);

     if (InternalLoadAssemblyFrom(fileName) == false)
     {
      if (InternalLoadAssembly(referencedAssemblyName) == false)
      {
       AssemblyInfo referencedAssemblyInfo = new AssemblyInfo();
       referencedAssemblyInfo.AssemblyName = referencedAssemblyName;
       assemblies.Add(referencedAssemblyName.FullName, referencedAssemblyInfo);
       currentReferencingAssembly.
             ReferencedAssemblies.Add(referencedAssemblyName.FullName,
			referencedAssemblyInfo);
      }
     }
    }
    else
    {
     AssemblyInfo referencedAssemblyInfo = 
          assemblies[referencedAssemblyName.FullName];
     currentReferencingAssembly.
          ReferencedAssemblies.Add(referencedAssemblyName.FullName, 
			referencedAssemblyInfo);
    }
   }
  }
  finally
  {
   currentReferencingAssembly = previouslyReferencingAssembly;
  }
 }
}

The XAML

In “App.xaml”, we pull in the “ExpressionDark.xaml” resource dictionary giving us a nice “expression” like user interface – without exactly exerting ourselves. This theme and a few others are available from as part of the WPF Toolkit on CodePlex.

<Application x:Class="Harlinn.Depends4Net.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:types="clr-namespace:Harlinn.Depends4Net.Types"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary >
            <ObjectDataProvider x:Key="DependsDataSource" 
		ObjectType="{x:Type types:Depends}">
                <ObjectDataProvider.ConstructorParameters />
            </ObjectDataProvider>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ExpressionDark.xaml" />
            </ResourceDictionary.MergedDictionaries>
            
        </ResourceDictionary>
    </Application.Resources>
</Application>

Building the Hierarchy

A careful look at how I build the hierarchy will reveal that each assembly is only represented by one AssemblyNode instance – even if present at several locations in the hierarchy. AddAssemblyNode is called recursively and takes a dictionary containing all the nodes created so far, this allows me to reuse existing nodes for assemblies that are referenced by multiple assemblies.

private AssemblyNode AddAssemblyNode(AssemblyNode parent, 
    Dictionary<string, AssemblyNode> assemblyNodes, AssemblyInfo assemblyInfo)
{
    AssemblyNode result = null;
    if (assemblyNodes.ContainsKey(assemblyInfo.AssemblyName.FullName))
    {
        result = assemblyNodes[assemblyInfo.AssemblyName.FullName];
        if (parent != null)
        {
            parent.ReferencedAssemblies.Add(result);
        }
    }
    else
    {
        result = new AssemblyNode();
        result.AssignFromAssemblyInfo(assemblyInfo);

        assemblyNodes.Add(assemblyInfo.AssemblyName.FullName, result);
        if (parent != null)
        {
            parent.ReferencedAssemblies.Add(result);
        }

        Dictionary<string, AssemblyInfo>.ValueCollection referencedAssemblyCollection = 
            assemblyInfo.ReferencedAssemblies.Values;

        List<AssemblyInfo> referencedAssemblies = new List<AssemblyInfo>();
        referencedAssemblies.AddRange(referencedAssemblyCollection);
        referencedAssemblies.Sort(new AssemblyInfoComparer());

        foreach (AssemblyInfo referencedAssemblyInfo in referencedAssemblies)
        {
            AddAssemblyNode(result, assemblyNodes, referencedAssemblyInfo);
        }
    }
    return result;
}

Concluding Remarks

The most interesting thing here is how I set up the paths for the new AppDomain and that I avoid instantiating the assemblies in the primary domain by inadvertently serializing them from the new AppDomain to the primary AppDomain.

History

  • 29th of August, 2011 – Initial posting

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here