Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

how to use loaded DLLS assembly' methods which is referenced to another assembly?

Posted on 2012-03-12
3
Medium Priority
?
531 Views
Last Modified: 2012-03-12
i have 2 assemblies. i added classlib1 into classLib2 references. like that:
soru1
USAGE:

namespace ClassLibrary2
{
    public class Class1
    {
        public Class1()
        {

        }

        public int GetSum(int a , int b)
        {
            try
            {
                ClassLibrary1.Class1 ctx = new ClassLibrary1.Class1();
                return ctx.Sum(a, b);
            }
            catch
            {
                return -1;
            }

        }
    }
}

Open in new window


Also i want to load (class1lib and Class2Lib) another C# project dynamically by using AppDomain.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Reflection.Emit;

namespace WcfService3
{
    public partial class Default : System.Web.UI.Page
    {
        public static ArrayList arryFiles { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            arryFiles = new ArrayList();
            List<byte[]> binaryList = new List<byte[]>();
            // string fileName = @"S:\Source\Yusuf.Karatoprak\plugin\ClassLibrary1.dll";
            DirSearch(@"S:\Source\Yusuf.Karatoprak\plugin");
            foreach (var filePath in arryFiles)
            {
                FileStream fileStream = File.OpenRead(filePath.ToString());
                byte[] buffer = new byte[fileStream.Length];
                fileStream.Read(buffer, 0, Convert.ToInt32(fileStream.Length));
                fileStream.Dispose();
                binaryList.Add(buffer);
                //Assembly[] assBefore = AppDomain.CurrentDomain.GetAssemblies();
              
                //AppDomain.CurrentDomain.Load(buffer);

                //Assembly[] assAfter = AppDomain.CurrentDomain.GetAssemblies();

                //Type t = Type.GetType("ClassLibrary1.Class1,ClassLibrary1");
            }

            new AssemblyLoader().LoadAndCall(binaryList);
        }
        static void DirSearch(string sDir)
        {
            try
            {
                foreach (string f in Directory.GetFiles(sDir, "*.dll"))
                {
                    if (!arryFiles.Contains(f))
                        arryFiles.Add(f);
                }
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    if (d != null)
                    {
                        foreach (string f in Directory.GetFiles(d, "*.dll"))
                        {
                            if (!arryFiles.Contains(f))
                                arryFiles.Add(f);
                        }
                        DirSearch(d);
                    }
                    else
                        break;
                }

            }
            catch (System.Exception excpt)
            {
                throw new Exception(excpt.Message);

            }
        }
    }

    public class AssemblyLoader : MarshalByRefObject
    {
        public void LoadAndCall(List<byte[]> binaryList)
        {
            Assembly loadedAssembly=null;
            Assembly[] assBefore = AppDomain.CurrentDomain.GetAssemblies();
            foreach (byte[] binary in binaryList)
            {
                loadedAssembly = AppDomain.CurrentDomain.Load(binary);
                foreach (var assemblyName in loadedAssembly.GetReferencedAssemblies())
                    AppDomain.CurrentDomain.Load(assemblyName);
            }
            Assembly[] assAfter = AppDomain.CurrentDomain.GetAssemblies();
            object[] tt = { 3, 6 };
            Type type = loadedAssembly.GetType("ClassLibrary2.Class1");
            object loaded = loadedAssembly.CreateInstance("ClassLibrary2.Class1", true, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, new object[] { }, null, null);
           // object obj = Activator.CreateInstance(type);
            
          

            ObjectCreateMethod inv = new ObjectCreateMethod(type); //Specify Type
            Object obj = inv.CreateInstance();

            MethodInfo minfo = type.GetMethod("GetSum", BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance);
            int x = (int)minfo.Invoke(obj, new Object[] { 3, 6 });
            Console.WriteLine(x);
        }
    }

    public class ObjectCreateMethod
    {
        delegate object MethodInvoker();
        MethodInvoker methodHandler = null;

        public ObjectCreateMethod(Type type)
        {
            CreateMethod(type.GetConstructor(Type.EmptyTypes));
        }

        public ObjectCreateMethod(ConstructorInfo target)
        {
            CreateMethod(target);
        }

        void CreateMethod(ConstructorInfo target)
        {
            DynamicMethod dynamic = new DynamicMethod(string.Empty,
                        typeof(object),
                        new Type[0],
                        target.DeclaringType);
            ILGenerator il = dynamic.GetILGenerator();
            il.DeclareLocal(target.DeclaringType);
            il.Emit(OpCodes.Newobj, target);
            il.Emit(OpCodes.Stloc_0);
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ret);

            methodHandler = (MethodInvoker)dynamic.CreateDelegate(typeof(MethodInvoker));
        }

        public object CreateInstance()
        {
            return methodHandler();
        }
    }

}

Open in new window


Why can not load and Exception error return to me:
GetSum method not working
innerexception not load classlib1
Look inner exception: Could not load file or assembly 'ClassLibrary1 But i loaded Classlib2 abd Classlib1 . class2 depends on classlib1 how to use classlib1 method i want to use GetSum(int a , int b) method after load assemblies?
0
Comment
Question by:programmerist
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 3

Expert Comment

by:zofcentr
ID: 37709042
Is missing assembly file inside BIN directory of calling assembly (this one which is dynamically loading assemblies).
As you do not add references then normally it is not copied during build operation.
Check whether file exists and has correct version.

Other solution is to register it in GAC.
0
 

Author Comment

by:programmerist
ID: 37709261
do you have any professional answer? with code and technical help
0
 
LVL 3

Accepted Solution

by:
zofcentr earned 2000 total points
ID: 37709519
I am not sure whether you comment was ironic and rude or not?
But I will try one more time.
Code of what ? It does not look that there is problem wit hcode.
I can not deliver code except some scripts to register assembly in GAC see under this link.

http://msdn.microsoft.com/en-us/library/ex0ss12c%28v=vs.80%29.aspx

Script for copying file I think is not needed ?
0

Featured Post

[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question