Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically use runtime compiled assemlby
    primarykey
    data
    text
    <p>I compile code dynamically from code:</p> <pre><code> string code = @" namespace CodeInjection { public static class DynConcatenateString { public static string Concatenate(string s1, string s2){ return s1 + "" ! "" + s2; } } }"; // http://stackoverflow.com/questions/604501/generating-dll-assembly-dynamically-at-run-time Console.WriteLine("Now doing some injection..."); Console.WriteLine("Creating injected code in memory"); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; //parameters.OutputAssembly = "DynamicCode.dll"; // if specified creates the DLL CompilerResults results = icc.CompileAssemblyFromSource(parameters, code); </code></pre> <p>Then I can invoke the method with reflection:</p> <pre><code> Console.WriteLine("Input two strings, and I will concate them with reflection:"); var s1 = Console.ReadLine(); var s2 = Console.ReadLine(); var result = (string)results.CompiledAssembly.GetType("CodeInjection.DynConcatenateString").GetMethod("Concatenate").Invoke(null, new object[] { s1, s2 }); Console.WriteLine(); Console.WriteLine("Result:"); Console.WriteLine(result); </code></pre> <p>But I would like to invoke something like this:</p> <pre><code> Console.WriteLine("Input two strings, and I will concate them with dynamic type:"); var s1 = Console.ReadLine(); var s2 = Console.ReadLine(); dynamic type = results.CompiledAssembly.GetType("CodeInjection.DynConcatenateString"); var resultA = (string)type.Concatenate(s1, s2); // runtime error // OR var resultB = (string)CodeInjection.DynConcatenateString.Concatenate(s1, s2); // compile error (cannot find assembly) Console.WriteLine(); Console.WriteLine("Result:"); Console.WriteLine(resultA); Console.WriteLine(resultB); </code></pre> <p>The resultB would be better. Any ideas how to do it? I need strictly .NET 4.0, we have not updated to 4.5 yet (because the half of the team uses VS 2010). (I can invoke with reflection, I know, I am just looking for another way, because we need to test dyn. code)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload