Click here to Skip to main content
Click here to Skip to main content

Loading an assembly using Reflection and invoking static methods from it

, 14 May 2010
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Syed Fasih
Software Developer (Senior) MasterKey Computer Systems
Pakistan Pakistan
My name is Syed Fasih-ud-Din
I live in Karachi, Pakistan.
Feel free to contact me
at syedfasih@gmail.com.
 
Programming is my profession. I like to share my knowledge with others whatever be its standard..
Currently I am working with a very good organization: MasterKey Computer Systems.
 
Wish Happy Programming To All..
Thank you,

Comments and Discussions

 
GeneralWay too much work... PinmemberDewey14-May-10 8:43 
GeneralRe: Way too much work... PinmemberSyed Fasih14-May-10 19:49 
GeneralRe: Way too much work... PinmemberDiamonddrake15-May-10 18:21 
GeneralRe: Way too much work... PinmemberSyed Fasih16-May-10 20:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140902.1 | Last Updated 14 May 2010
Article Copyright 2010 by Syed Fasih
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid