Friday, March 12, 2010

.Net Type names, creating objects at runtime, etc.

I keep forgetting these…. so here is post to log it to memory….

1. .Net Type Name:

The format is: “Namespace.TypeName, DLLName, Version=x.x.x.x, Culture=culture, PublicKeyToken=key”

Eg: Class MyHelloWorldClass in namespace MySampleNamespace.SubNamespace in the DLL MyHelloWorldDll.dll with version 1.0.0.0, no culture or publickey specified.

“MySampleNamespace.SubNamespace.MyHelloWorldClass, MyHelloWorldDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”

2. Creating an object of MyHelloWorldClass at runtime by using only the fully qualified type name.

Type typeLoadedAtRunTime = Type.GetType("MySampleNamespace.SubNamespace.MyHelloWorldClass, MyHelloWorldDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
Object objectLoadedAtRuntime = Activator.CreateInstance(typeLoadedAtRunTime);

Why are the above 2 useful? If you want to separate out the implementation details of certain parts of your application, such that your application does not care about exactly how certain methods are performed, then you develop your application to interfaces. You then create separate classes that implement those interfaces and provide the concrete implementation of the methods needed by your application. When your application runs, you can decide based on a variety of factors (eg: configuration file information), which class should be created to handle the methods needed by the application and your application then uses this runtime generated object for all its processing needs. (As you will be using Interfaces, the last line above will change to create an instance of a particular type).

eg: IHelloWorldClass objectLoadedAtRuntime = Activator.CreateInstance(typeLoadedAtRunTime) as IHelloWorldClass;

And if you need to list out the fully qualified names for all the types in your dll, here is some code to do just that.

string assemblyPath = args[0]; 
if (string.IsNullOrEmpty(assemblyPath))
{
    Console.WriteLine("Path to assembly not specified at command line");
    return;
}
Assembly loadedAssembly = null;
try
{
    Assembly.LoadFrom(assemblyPath);
}
catch (Exception exp)
{
    Console.WriteLine("Error: " + exp.Message);
    return;
}

Module[] modules = loadedAssembly.GetModules();
Console.WriteLine("Assembly: " + loadedAssembly.GetType().Name);
foreach (Module module in modules)
{
    Console.WriteLine("Module: {0}\nFullyQualifiedName: {1}", module.Name, module.FullyQualifiedName);
    Type[] types = module.GetTypes();
    foreach (Type type in types)
    {
        Console.WriteLine(type.AssemblyQualifiedName);
    }
}

No comments: