Listing 2

#include "stdafx.h"
#include "CodeCompiler.h"

using namespace Microsoft::CSharp;
using namespace System::Reflection;
using namespace System::Security;
using namespace System::Security::Policy;

DynamicCompilation::CodeCompiler::CodeCompiler ()
{
  SourceCode = new String("");
}
CompilerErrorCollection* DynamicCompilation::CodeCompiler::CompileCode()
{
  CSharpCodeProvider* oCodeProvider = new CSharpCodeProvider();  // Line 18
  ICodeCompiler* iCC = oCodeProvider->CreateCompiler();         // Line 17
  // Create the compiler parameters object
  CompilerParameters* oParameters = new CompilerParameters();
  oParameters->IncludeDebugInformation = false; // No symbol  Line 20
  oParameters->GenerateExecutable = false;      // DLL       Line 21
  oParameters->GenerateInMemory = true;  // Code stays in memory Line 22
  // Secure the code
  Evidence* oEvidence = new Evidence();
  oEvidence->AddHost(new Zone(SecurityZone::Internet));    // Line 25
  oParameters->Evidence = oEvidence;                     // Line 26
  // Invoke the compiler
  CompilerResults* oCR = iCC->CompileAssemblyFromSource(oParameters, 
                                           SourceCode); // Line 28
  // Save the assembly
  if (oCR->Errors->Count == 0) oAssembly_ = oCR->CompiledAssembly;
  // Return the error(s) if any
  return oCR->Errors;
}
Object* DynamicCompilation::CodeCompiler::Invoke
  (String* sObjectName, String* sMethod, Object* oArguments[])
{
  // Create an object's instance using in memory IL code
  Object* oInMemObject = oAssembly_->CreateInstance(sObjectName);
  // Reflect on the object to find the method the client wishes to run
  Type* oType = oInMemObject->GetType();
  BindingFlags oBF = (BindingFlags) 
                        (BindingFlags::Static | BindingFlags::Public);
  MethodInfo* oMethodInfo = oType->GetMethod(sMethod, oBF);
  // Invoke the function f(x)
  return oMethodInfo->Invoke(oInMemObject, oArguments);
}