Peter Derwa

Peter Derwa

  • NA
  • 4
  • 0

How to load a method from an unsaved (dynamically created) assembly?

Apr 14 2009 2:09 AM
Hey guys,

In our current application we are working with a plugin structure where a customer can create it's own code for validation of database entities.
this is managed by a BusinessLogic editor which saves the businessrules to a database and also creates a DLL of all project specific validationrules. (method validate)

Before I'm saving the DLL i would like to test the by running the Validate method with the businessLogic created by the customer.
Is it possible to get the type out of the assembly, and get the method out of that type?

I'm running this in a WCF Service. (check  --- Type ClassType = kvp.Value.GetType("DynamicAssemblyClass") ---> is giving back null, while i'm very sure that i've got this class in my asm)

   CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Web.Services.dll");
parameters.ReferencedAssemblies.Add(PathUtils.ApplicationBasePath + @"\ET.Common.dll");
parameters.ReferencedAssemblies.Add(PathUtils.ApplicationBasePath + @"\ET.Deap.BusinessLogic.Plugins.Interfaces.dll");

// When you need to add more References: add the correct assemblyname HERE
CompilerResults results = provider.CompileAssemblyFromSource(parameters, sb.ToString());

// if errors occured in the programming Code out of the database
if (results.Errors.HasErrors)
{
// Do Something
}
else // no errors occured in the code, proceed with testing the businessRules
{
Assembly assembly = results.CompiledAssembly;
// add to dictionary with codesnippet id as key
asmList.Add(cs.Id,assembly);
}


foreach (KeyValuePair<int, Assembly> kvp in asmList)
{
// this one is not giving back the type!!!!
Type ClassType = kvp.Value.GetType("DynamicAssemblyClass");
MethodInfo methodInfo = ClassType.GetMethod("BusinessRuleMethod");
ValidationResult vr2 = new ValidationResult(true);
try
{
methodInfo.Invoke(null, new object[] { obj, projectId, vr2 });
}
catch (Exception ex)
{
// do something
}