Loading an assembly using Reflection and invoking static methods from it

, 14 May 2010

LoadAssembly.zip

Utility.zip

   

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:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Hide   Shrink    Copy Code

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:

Hide   Copy Code

// 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:

Hide   Copy Code

//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:

Hide   Shrink    Copy Code

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)

[출처] https://www.codeproject.com/Articles/81224/Loading-an-assembly-using-Reflection-and-invoking

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED