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

Loading an assembly using Reflection and invoking static methods from it

0.00/5 (No votes)
14 May 2010 2  
Invoking static methods from an assembly at runtime using Reflection.

snapshot.png

Introduction

In this article, I will show how to load an assembly at runtime using Reflection and to invoke static methods from it.

Background

Reflection is Microsoft's extra-ordinary feature. Before we begin, we must know some very important concepts about assemblies. Assemblies are the building blocks of .NET Framework. An assembly is a collection of types and resources that are built to work together, and form a logical unit of functionality.

An assembly contains modules, modules contain types, and types contain members. Using Reflection, we can create an instance of a type, can invoke a type's methods, or access its fields and properties. For this tutorial, the above statement is enough. For a detailed information, click here.

Using the code

This tutorial consists of two projects:

  1. Utllity (the Class Library)
  2. LoadAssembly (application that will load Utility using Reflection)

The Utility Class Library consists of two methods:

  • Encrypt (takes a string as input and returns the encrypted string as output)
  • Decrypt (takes an encrypted string as input and returns the original string)

I will not discuss the utility code as it is not needed to. The utility code is as under:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Utility
{
    public static class Cryptography
    {
        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Dated : 15, March 2009  @  12:10
        /// Description : Decrypts Encrypted Text to Original Message
        /// </summary>
        /// <param name="EncryptedText">Encrypted string</param>
        /// <returns></returns>
        public static string Decrypt(this string EncryptedText)
        {
            byte[] bytes = Encoding.UTF8.GetBytes("LcB!ZLtd");
            byte[] rgbIV = Encoding.UTF8.GetBytes("!nforM@#");
            byte[] buffer = Convert.FromBase64String(EncryptedText);
            MemoryStream stream = new MemoryStream();
            try
            {
                DES des = new DESCryptoServiceProvider();
                CryptoStream stream2 = new CryptoStream(stream, 
                   des.CreateDecryptor(bytes, rgbIV), CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }



            return Encoding.UTF8.GetString(stream.ToArray());
        }

        /// <summary>
        /// Author : Syed Fasih-ud-Din
        /// Dated : 15, March 2009  @  12:10
        /// Description : Encrypts Plain Text to Unreadable Form
        /// </summary>
        /// <param name="PlainText">Plain Text intended to Encrypt</param>
        /// <returns></returns>
        public static string Encrypt(this string PlainText)
        {
            byte[] bytes = Encoding.UTF8.GetBytes("LcB!ZLtd");
            byte[] rgbIV = Encoding.UTF8.GetBytes("!nforM@#");
            byte[] buffer = Encoding.UTF8.GetBytes(PlainText);
            MemoryStream stream = new MemoryStream();
            
            try
            {
                DES des = new DESCryptoServiceProvider();
                CryptoStream stream2 = new CryptoStream(stream, 
                   des.CreateEncryptor(bytes, rgbIV), CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }


            return Convert.ToBase64String(stream.ToArray());
        }
    }
}

LoadAssembly

The LoadAssembly project will load the assembly using Reflection and will invoke the methods. The code with the explanation is as under.

The variables that will be used in the application are:

// Will be holding the Types in the Assembly
Type[] TypesInAssembly = null;
// Will hold the Fully Qualified Name of the Assembly i.e. Namespace.Class
string AssemblyName = string.Empty;
// Will be holding the Full path of the Assembly
string AssemblyPath = string.Empty;
// Will hold the Path of the Currently Executing Assembly
// i.e. the Project EXE filr
string ExecutingAssemblyPath = string.Empty;
// These will hold the results of Encryption
// and Decryption from the loadedAssembly
object Result, DecryptedResult = null;

Form load

On the Form load, the application will load Utility.dll, which then will be used by the button events to invoke the methods. The Form load event code is shown here:

//Getting Application Startup Path
ExecutingAssemblyPath = Application.StartupPath;

//Getting the Exact Directory where the application is running
ExecutingAssemblyPath = 
   System.IO.Path.GetDirectoryName(ExecutingAssemblyPath);

//Creating Full Path of Assembly
AssemblyPath = ExecutingAssemblyPath + "\\" + 
  ConfigurationManager.AppSettings["Location"].ToString() + 
  ConfigurationManager.AppSettings["Assembly"].ToString();

//Loading An Assembly From desired path
System.Reflection.Assembly MyAssembly = 
       System.Reflection.Assembly.LoadFrom(AssemblyPath);

//Getting Assembly Types (i.e. classes) here we have only 1 class
TypesInAssembly = MyAssembly.GetTypes();

//Creating Full Name of Assembly i.e. Namespace.ClassName
AssemblyName = TypesInAssembly[0].Namespace + "." + TypesInAssembly[0].Name;

//Getting Methods in Assembly Types
System.Reflection.MethodInfo[] MethodsCollection = TypesInAssembly[0].GetMethods();

Invoking methods

Before you do an invoke, you must know about invoking a static method. For a static method to be invoked, there is a parameter named 'target'. If you are invoking a static method, then leave this parameter as blank, this will be ignored by the framework. If your method is not static, then you have to provide the instance of the class and that instance will be creating the CreateInstance method. In our case, we are calling a static method.

Here are the button events that will be invoking the Utility.dll member methods:

private void bttnEncrypt_Click(object sender, EventArgs e)
{
    try
    {
        //Invoke Loaded Assembly Method
        Result = TypesInAssembly[0].InvokeMember("Encrypt", 
           System.Reflection.BindingFlags.InvokeMethod, System.Type.DefaultBinder, 
           "", new object[] { txtMessage.Text });
        txtEcnryptedMessage.Text = Result.ToString();
    }
    catch (Exception ex)
    {
       MessageBox.Show(ex.Message);
    }
}
private void bttnDecrypt_Click(object sender, EventArgs e)
{
    try
    {
        //Invoke Loaded Assembly Method
        DecryptedResult = TypesInAssembly[0].InvokeMember("Decrypt", 
            System.Reflection.BindingFlags.InvokeMethod, System.Type.DefaultBinder, 
            "", new object[] { txtEcnryptedMessage.Text });
        MessageBox.Show(DecryptedResult.ToString());
    }
    catch (Exception ex)
    {

          MessageBox.Show(ex.Message);
    }
}

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