Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Created November 25, 2010 00:47
Show Gist options
  • Save leandrosilva/714717 to your computer and use it in GitHub Desktop.
Save leandrosilva/714717 to your computer and use it in GitHub Desktop.
Live samples on how to read the metadatas of .NET solutions, projects and assemblies with C#
using System;
using System.Reflection;
using System.Security.Permissions;
[assembly:AssemblyVersionAttribute("1.0.2000.0")]
public class Metadata
{
private int factor;
public Metadata(int f)
{
factor = f;
}
public int SampleMethod(int x)
{
Console.WriteLine("\nMetadata.SampleMethod({0}) executes.", x);
return x * factor;
}
public static void Main()
{
Assembly assem = Assembly.GetExecutingAssembly();
Console.WriteLine("Assembly Full Name:");
Console.WriteLine(assem.FullName);
// The AssemblyName type can be used to parse the full name.
AssemblyName assemName = assem.GetName();
Console.WriteLine("\nName: {0}", assemName.Name);
Console.WriteLine("Version: {0}.{1}",
assemName.Version.Major, assemName.Version.Minor);
Console.WriteLine("\nAssembly CodeBase:");
Console.WriteLine(assem.CodeBase);
// Create an object from the assembly, passing in the correct number
// and type of arguments for the constructor.
Object o = assem.CreateInstance("Metadata", false,
BindingFlags.ExactBinding,
null, new Object[] { 2 }, null, null);
// Make a late-bound call to an instance method of the object.
MethodInfo m = assem.GetType("Metadata").GetMethod("SampleMethod");
Object ret = m.Invoke(o, new Object[] { 42 });
Console.WriteLine("SampleMethod returned {0}.", ret);
Console.WriteLine("\nAssembly entry point:");
Console.WriteLine(assem.EntryPoint);
}
}
using System;
using System.Reflection;
class ReferencedAssemblies
{
public static void Main()
{
Assembly a = Assembly.LoadFrom("/opt/sqlite-dotnet/bin/ManagedOnly/System.Data.SQLite.dll");
Console.WriteLine("Assembly identity={0}", a.FullName);
Console.WriteLine("Codebase={0}", a.CodeBase);
// Display the set of assemblies our assemblies reference.
Console.WriteLine("Referenced assemblies:");
foreach (AssemblyName an in a.GetReferencedAssemblies() )
{
Console.WriteLine(" Name={0}, Version={1}, Culture={2}, PublicKey token={3}", an.Name, an.Version, an.CultureInfo.Name, (BitConverter.ToString (an.GetPublicKeyToken())));
}
}
}
using System;
using System.Reflection;
using System.Security.Permissions;
[assembly:AssemblyVersionAttribute("1.0.2000.0")]
public class SelfMetadata
{
private int factor;
public SelfMetadata(int f)
{
factor = f;
}
public int SampleMethod(int x)
{
Console.WriteLine("\nSelfMetadata.SampleMethod({0}) executes.", x);
return x * factor;
}
public static void Main()
{
Assembly assem = Assembly.GetExecutingAssembly();
Console.WriteLine("Assembly Full Name:");
Console.WriteLine(assem.FullName);
// The AssemblyName type can be used to parse the full name.
AssemblyName assemName = assem.GetName();
Console.WriteLine("\nName: {0}", assemName.Name);
Console.WriteLine("Version: {0}.{1}",
assemName.Version.Major, assemName.Version.Minor);
Console.WriteLine("\nAssembly CodeBase:");
Console.WriteLine(assem.CodeBase);
// Create an object from the assembly, passing in the correct number
// and type of arguments for the constructor.
Object o = assem.CreateInstance("SelfMetadata", false,
BindingFlags.ExactBinding,
null, new Object[] { 2 }, null, null);
// Make a late-bound call to an instance method of the object.
MethodInfo m = assem.GetType("SelfMetadata").GetMethod("SampleMethod");
Object ret = m.Invoke(o, new Object[] { 42 });
Console.WriteLine("SampleMethod returned {0}.", ret);
Console.WriteLine("\nAssembly entry point:");
Console.WriteLine(assem.EntryPoint);
}
}
using System;
using System.Runtime.InteropServices;
using Microsoft.Build.BuildEngine;
class Tester
{
static void Main(string[] args)
{
Engine.GlobalEngine.BinPath = RuntimeEnvironment.GetRuntimeDirectory();
Console.WriteLine("Runtime directory: {0}", RuntimeEnvironment.GetRuntimeDirectory());
Console.WriteLine("----------------------------------");
// Create a new empty project
Project project = new Project();
// Load a project
project.Load("../ASPNetMVCOne/Tests/Tests.csproj");
Console.WriteLine("Project Properties");
Console.WriteLine("----------------------------------");
// Iterate through the various property groups and subsequently
// through teh various properties
foreach (BuildPropertyGroup propertyGroup in project.PropertyGroups)
{
foreach (BuildProperty prop in propertyGroup)
{
Console.WriteLine("{0}: {1}", prop.Name, prop.Value);
}
}
Console.WriteLine();
Console.WriteLine("Project Items");
Console.WriteLine("----------------------------------");
// Iterate through the various itemgroups
// and subsequently through the items
foreach (BuildItemGroup itemGroup in project.ItemGroups)
{
foreach (BuildItem item in itemGroup)
{
Console.WriteLine("{0}: {1}", item.Name, item.Include);
}
}
}
}
using System;
using System.Reflection;
class ReferencedAssemblies
{
public static void Main()
{
// This variable holds the amount of indenting that
// should be used when displaying each line of information.
Int32 indent = 0;
// Display information about the EXE assembly.
Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
Display(indent, "Assembly identity={0}", a.FullName);
Display(indent+1, "Codebase={0}", a.CodeBase);
// Display the set of assemblies our assemblies reference.
Display(indent, "Referenced assemblies:");
foreach (AssemblyName an in a.GetReferencedAssemblies() )
{
Display(indent + 1, "Name={0}, Version={1}, Culture={2}, PublicKey token={3}", an.Name, an.Version, an.CultureInfo.Name, (BitConverter.ToString (an.GetPublicKeyToken())));
}
Display(indent, "");
// Display information about each assembly loading into this AppDomain.
foreach (Assembly b in AppDomain.CurrentDomain.GetAssemblies())
{
Display(indent, "Assembly: {0}", b);
// Display information about each module of this assembly.
foreach ( Module m in b.GetModules(true) )
{
Display(indent+1, "Module: {0}", m.Name);
}
// Display information about each type exported from this assembly.
indent += 1;
foreach ( Type t in b.GetExportedTypes() )
{
Display(0, "");
Display(indent, "Type: {0}", t);
// For each type, show its members & their custom attributes.
indent += 1;
foreach (MemberInfo mi in t.GetMembers() )
{
Display(indent, "Member: {0}", mi.Name);
DisplayAttributes(indent, mi);
// If the member is a method, display information about its parameters.
if (mi.MemberType==MemberTypes.Method)
{
foreach ( ParameterInfo pi in ((MethodInfo) mi).GetParameters() )
{
Display(indent+1, "Parameter: Type={0}, Name={1}", pi.ParameterType, pi.Name);
}
}
// If the member is a property, display information about the property's accessor methods.
if (mi.MemberType==MemberTypes.Property)
{
foreach ( MethodInfo am in ((PropertyInfo) mi).GetAccessors() )
{
Display(indent+1, "Accessor method: {0}", am);
}
}
}
indent -= 1;
}
indent -= 1;
}
}
// Displays the custom attributes applied to the specified member.
public static void DisplayAttributes(Int32 indent, MemberInfo mi)
{
// Get the set of custom attributes; if none exist, just return.
object[] attrs = mi.GetCustomAttributes(false);
if (attrs.Length==0) {return;}
// Display the custom attributes applied to this member.
Display(indent+1, "Attributes:");
foreach ( object o in attrs )
{
Display(indent+2, "{0}", o.ToString());
}
}
// Display a formatted string indented by the specified amount.
public static void Display(Int32 indent, string format, params object[] param)
{
Console.Write(new string(' ', indent*2));
Console.WriteLine(format, param);
}
}
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
class SolutionProjects
{
public static IEnumerable<string> GetAllProjectFileNames(string solutionFile)
{
string guidExpression = "{[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}";
Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)(EndProject)?", RegexOptions.Singleline);
string solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}";
StreamReader reader = new StreamReader(solutionFile);
string line = reader.ReadToEnd();
line = line.Replace ("\r\n", "\n");
string soln_dir = Path.GetDirectoryName(solutionFile);
Match m = projectRegex.Match(line);
while (m.Success)
{
if (String.Compare(m.Groups[1].Value, solutionFolderGuid, StringComparison.InvariantCultureIgnoreCase) != 0)
{
yield return Path.Combine(soln_dir, m.Groups[3].Value).Replace ("\\", "/");
}
m = m.NextMatch ();
}
}
public static void Main()
{
foreach (var project in GetAllProjectFileNames("../ASPNetMVCOne/ASPNetMVCOne.sln"))
{
Console.WriteLine("Project: {0}", project);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment