public static string compilerte(string outputname, string sourcecode)
        {
            var codeProvider = new CSharpCodeProvider();
            var provider = CodeDomProvider.CreateProvider("CSharp");

            var exeName = outputname;

            var cp = new CompilerParameters
            {
                GenerateExecutable = true,
                OutputAssembly = exeName,
                GenerateInMemory = false,
                TreatWarningsAsErrors = false
            };

            var cr = provider.CompileAssemblyFromSource(cp, translatetocsharp(sourcecode));

            if (cr.Errors.Count > 0)
            {
                var builder = new StringBuilder();
                builder.Append("Cehape broke our codes that were supposed to be compiled here: " + cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    builder.Append(Environment.NewLine + ce.ToString());
                }
                codeProvider.Dispose();
                return builder.ToString();
            }
            else
            {
                codeProvider.Dispose();
                return ("We were able to compile {0} successfully without cehape messing with it.".Replace("{0}", cr.PathToAssembly));
            }
        }
示例#2
0
        private CompilerResults Compile(string code, CompilerParameters compilerParameters)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider(new Dictionary<String, String> { { "CompilerVersion", "v4.0" } });

            CompilerResults results = codeProvider.CompileAssemblyFromSource(compilerParameters, new string[] { code });

            codeProvider.Dispose();

            return results;
        }
示例#3
0
        internal static async Task<LiveCodeCompilationResult> Compile(IEnumerable<string> sourceFilesPaths, string projectName, IEnumerable<string> references, bool createAssemblyFiles = false)
        {
            string[] filesPaths = sourceFilesPaths as string[] ?? sourceFilesPaths.ToArray();
            string[] sourceFiles = filesPaths.ToArray();
            string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string assemblyName = GetNewAssemblyName(projectName, location);

            // clean up previous assemblies

            DeletePreviousAssemblies(projectName, location);

            // setup compilation parameters

            var options = SetupCompilationParameters(createAssemblyFiles, assemblyName, sourceFiles, location, references);

            // compile

            var cSharpCodeProvider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } });
            CompilerResults results = await cSharpCodeProvider.CompileAsync(options, sourceFiles);
            cSharpCodeProvider.Dispose();

            var errorMessage = new StringBuilder();
            if (results.Errors.HasErrors)
            {
                errorMessage.Append(string.Format("Compilation errors for {0}", projectName));
                foreach (CompilerError error in results.Errors)
                {
                    errorMessage.Append(string.Format("{0}({1},{2}): {3}", error.FileName, error.Line, error.Column, error.ErrorText));
                }

                return new LiveCodeCompilationResult{ ErrorMessage = errorMessage.ToString() };
            }
            
            // load compiled assembly

            if (createAssemblyFiles)
            {
                // load from disk
                return await LoadAssemblyFromDisk(assemblyName);
            }
            
            // load from memory 
            return new LiveCodeCompilationResult { Assembly = results.CompiledAssembly, HasSucceed = true };
        }
示例#4
0
 /* From http://www.codeproject.com/Articles/9019/Compiling-and-Executing-Code-at-Runtime */
 public Assembly BuildAssembly(string[] Code, string[] ReferencedAssemblies)
 {
     Microsoft.CSharp.CSharpCodeProvider Compiler = new CSharpCodeProvider();
     CompilerParameters CompilerParams = new CompilerParameters();
     CompilerParams.GenerateExecutable = false;
     CompilerParams.GenerateInMemory = true;
     CompilerParams.IncludeDebugInformation = false;
     CompilerParams.ReferencedAssemblies.AddRange(ReferencedAssemblies);
     CompilerResults Results = Compiler.CompileAssemblyFromSource(CompilerParams, Code);
     Compiler.Dispose();
     if (Results.Errors.HasErrors)
     {
         StringBuilder Errors = new StringBuilder("Compiler Errors :\r\n");
         foreach (CompilerError Error in Results.Errors)
         {
             Errors.AppendFormat("Line {0},{1}\t: {2}\n", Error.Line, Error.Column, Error.ErrorText);
         }
         throw new Exception(Errors.ToString());
     }
     else
     {
         return Results.CompiledAssembly;
     }
 }
            public DynamicAssembly(string nameWithoutExtension, DynamicAssembly[] references = null, Version version = null, bool fakeIdentity = false)
            {
                if (version == null)
                {
                    version = new Version(1, 0, 0, 0);
                }

                if (references == null)
                {
                    references = new DynamicAssembly[0];
                }

                Name = nameWithoutExtension;
                Namespace = nameWithoutExtension;
                FileName = $"{Namespace}{Path.GetFileNameWithoutExtension(Path.GetRandomFileName())}{Interlocked.Increment(ref dynamicAssemblyId)}.dll";
                DynamicName = Path.GetFileNameWithoutExtension(FileName);

                var builder = new StringBuilder();
                builder.AppendLine("using System.Reflection;");
                builder.AppendLine($"[assembly: AssemblyVersion(\"{version}\")]");
                builder.AppendLine($"[assembly: AssemblyFileVersion(\"{version}\")]");

                builder.AppendFormat("namespace {0} {{ ", Namespace);

                var provider = new CSharpCodeProvider();
                var param = new CompilerParameters(new string[]
                {
                }, FileName);
                param.GenerateExecutable = false;
                param.GenerateInMemory = false;
                param.OutputAssembly = FilePath = Path.Combine(TestAssemblyDirectory, FileName);
                param.TempFiles = new TempFileCollection(TestAssemblyDirectory, false);

                foreach (var reference in references)
                {
                    builder.AppendLine($"using {reference.Namespace};");
                    param.ReferencedAssemblies.Add(reference.FilePath);
                }

                builder.AppendLine("public class Foo { public Foo() {");
                foreach (var reference in references)
                {
                    builder.AppendLine($"new {reference.Namespace}.Foo();");
                }
                builder.AppendLine("} } }");

                var result = provider.CompileAssemblyFromSource(param, builder.ToString());
                ThrowIfCompilationWasNotSuccessful(result);

                provider.Dispose();

                if (fakeIdentity)
                {
                    var reader = AssemblyDefinition.ReadAssembly(FilePath);
                    reader.Name.Name = nameWithoutExtension;
                    reader.MainModule.Name = nameWithoutExtension;
                    reader.Write(FilePath);
                }

                Assembly = result.CompiledAssembly;
            }
示例#6
0
        public void CompilePlugins(PermissionSet pluginSandboxPermissions, List<String> ignoredPluginClassNames = null) {
            try {

                if (File.Exists(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml")) == true) {
                    WritePluginConsole("Loading plugin cache..");

                    try {
                        this.PluginCache = XDocument.Load(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml")).Root.FromXElement<PluginCache>();
                    }
                    catch (Exception e) {
                        WritePluginConsole("Error loading plugin cache: {0}", e.Message);
                    }
                }

                // Recover from exceptions or logic errors if the document parsed correctly, but didn't deserialize correctly.
                if (this.PluginCache == null) {
                    this.PluginCache = new PluginCache();
                }

                // Make sure we ignore any plugins passed in. These won't even be loaded again.
                if (ignoredPluginClassNames != null) {
                    IgnoredPluginClassNames = ignoredPluginClassNames;
                }

                // Clear out all invocations if this is a reload.
                Invocations.Clear();

                WritePluginConsole("Preparing plugins directory..");
                PreparePluginsDirectory();

                WritePluginConsole("Moving legacy plugins..");
                MoveLegacyPlugins();

                WritePluginConsole("Creating compiler..");
                // CodeDomProvider pluginsCodeDomProvider = CodeDomProvider.CreateProvider("CSharp");
                var providerOptions = new Dictionary<String, String>();
                providerOptions.Add("CompilerVersion", "v3.5");
                CodeDomProvider pluginsCodeDomProvider = new CSharpCodeProvider(providerOptions);

                WritePluginConsole("Configuring compiler..");
                CompilerParameters parameters = GenerateCompilerParameters();
                // AppDomainSetup domainSetup = new AppDomainSetup() { ApplicationBase = this.PluginBaseDirectory };
                // Start of XpKillers mono workaround

                AppDomainSetup domainSetup = null;
                Type t = Type.GetType("Mono.Runtime");
                if (t != null) {
                    //Console.WriteLine("You are running with the Mono VM");
                    WritePluginConsole("Running with Mono VM..");
                    //AppDomain.CurrentDomain.BaseDirectory
                    domainSetup = new AppDomainSetup() {
                        ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
                    };
                    domainSetup.PrivateBinPath = PluginBaseDirectory;
                }
                else {
                    // Console.WriteLine("You are running something else (native .Net)");
                    WritePluginConsole("Running with native .Net..");
                    domainSetup = new AppDomainSetup() {
                        ApplicationBase = PluginBaseDirectory
                    };
                }
                // Workaround end

                WritePluginConsole("Building sandbox..");
                var hostEvidence = new Evidence();
                hostEvidence.AddHost(new Zone(SecurityZone.MyComputer));

                AppDomainSandbox = AppDomain.CreateDomain(ProconClient.HostName + ProconClient.Port + "Engine", hostEvidence, domainSetup, pluginSandboxPermissions);

                WritePluginConsole("Configuring sandbox..");
                // create the factory class in the secondary app-domain
                PluginFactory = (CPRoConPluginLoaderFactory) AppDomainSandbox.CreateInstance("PRoCon.Core", "PRoCon.Core.Plugin.CPRoConPluginLoaderFactory").Unwrap();
                PluginCallbacks = new CPRoConPluginCallbacks(ProconClient.ExecuteCommand, ProconClient.GetAccountPrivileges, ProconClient.GetVariable, ProconClient.GetSvVariable, ProconClient.GetMapDefines, ProconClient.TryGetLocalized, RegisterCommand, UnregisterCommand, GetRegisteredCommands, ProconClient.GetWeaponDefines, ProconClient.GetSpecializationDefines, ProconClient.Layer.GetLoggedInAccounts, RegisterPluginEvents);

                WritePluginConsole("Compiling and loading plugins..");


                var pluginsDirectoryInfo = new DirectoryInfo(PluginBaseDirectory);

                foreach (FileInfo pluginFile in pluginsDirectoryInfo.GetFiles("*.cs")) {
                    string className = Regex.Replace(pluginFile.Name, "\\.cs$", "");

                    if (IgnoredPluginClassNames.Contains(className) == false) {
                        CompilePlugin(pluginFile, className, pluginsCodeDomProvider, parameters);

                        LoadPlugin(className, PluginFactory, pluginSandboxPermissions.IsUnrestricted());
                    }
                    else {
                        WritePluginConsole("Compiling {0}... ^1^bIgnored", className);
                    }
                }

                XDocument pluginCacheDocument = new XDocument(this.PluginCache.ToXElement());

                pluginCacheDocument.Save(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml"));

                pluginsCodeDomProvider.Dispose();
            }
            catch (Exception e) {
                WritePluginConsole(e.Message);
            }
        }
示例#7
0
        public void CompilePlugins(PermissionSet pluginSandboxPermissions, List<String> ignoredPluginClassNames = null) {

            try {

                // Make sure we ignore any plugins passed in. These won't even be loaded again.
                if (ignoredPluginClassNames != null) {
                    this.IgnoredPluginClassNames = ignoredPluginClassNames;
                }

                // Clear out all invocations if this is a reload.
                this.Invocations.Clear();

                this.WritePluginConsole("Preparing plugins directory..");
                this.PreparePluginsDirectory();
                this.CleanPlugins();

                this.WritePluginConsole("Moving legacy plugins..");
                this.MoveLegacyPlugins();

                this.WritePluginConsole("Creating compiler..");
                // CodeDomProvider pluginsCodeDomProvider = CodeDomProvider.CreateProvider("CSharp");
                Dictionary<String, String> providerOptions = new Dictionary<String, String>();
                providerOptions.Add("CompilerVersion", "v3.5");
                CodeDomProvider pluginsCodeDomProvider = new CSharpCodeProvider(providerOptions);

                this.WritePluginConsole("Configuring compiler..");
                CompilerParameters parameters = GenerateCompilerParameters();
                // AppDomainSetup domainSetup = new AppDomainSetup() { ApplicationBase = this.PluginBaseDirectory };
                // Start of XpKillers mono workaround

                AppDomainSetup domainSetup = null;
                Type t = Type.GetType("Mono.Runtime");
                if (t != null)
                {
                    //Console.WriteLine("You are running with the Mono VM");
                    this.WritePluginConsole("Running with Mono VM..");
                    //AppDomain.CurrentDomain.BaseDirectory
                    domainSetup = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory };
                    domainSetup.PrivateBinPath = this.PluginBaseDirectory;
                }
                else
                {
                    // Console.WriteLine("You are running something else (native .Net)");
                    this.WritePluginConsole("Running with native .Net..");
                    domainSetup = new AppDomainSetup() { ApplicationBase = this.PluginBaseDirectory };
                }
                // Workaround end

                this.WritePluginConsole("Building sandbox..");
                Evidence hostEvidence = new Evidence();
                hostEvidence.AddHost(new Zone(SecurityZone.MyComputer));

                this.m_appDomainSandbox = AppDomain.CreateDomain(this.m_client.HostName + this.m_client.Port + "Engine", hostEvidence, domainSetup, pluginSandboxPermissions);

                this.WritePluginConsole("Configuring sandbox..");
                // create the factory class in the secondary app-domain
                CPRoConPluginLoaderFactory pluginFactory = (CPRoConPluginLoaderFactory)this.m_appDomainSandbox.CreateInstance("PRoCon.Core", "PRoCon.Core.Plugin.CPRoConPluginLoaderFactory").Unwrap();
                this.m_cpPluginCallbacks = new CPRoConPluginCallbacks(this.m_client.ExecuteCommand, this.m_client.GetAccountPrivileges, this.m_client.GetVariable, this.m_client.GetSvVariable, this.m_client.GetMapDefines, this.m_client.TryGetLocalized, this.RegisterCommand, this.UnregisterCommand, this.GetRegisteredCommands, this.m_client.GetWeaponDefines, this.m_client.GetSpecializationDefines, this.m_client.Layer.GetLoggedInAccounts, this.RegisterPluginEvents);

                this.WritePluginConsole("Compiling and loading plugins..");


                DirectoryInfo pluginsDirectoryInfo = new DirectoryInfo(this.PluginBaseDirectory);
                FileInfo[] a_pluginsFileInfo = pluginsDirectoryInfo.GetFiles("*.cs");

                foreach (FileInfo pluginFile in a_pluginsFileInfo) {

                    string className = Regex.Replace(pluginFile.Name, "\\.cs$", "");

                    if (this.IgnoredPluginClassNames.Contains(className) == false) {
                        this.CompilePlugin(pluginFile, className, pluginsCodeDomProvider, parameters);

                        this.LoadPlugin(className, pluginFactory, pluginSandboxPermissions.IsUnrestricted());
                    }
                    else {
                        this.WritePluginConsole("Compiling {0}... ^1^bIgnored", className);
                    }
                }

                pluginsCodeDomProvider.Dispose();
            }
            catch (Exception e) {
                this.WritePluginConsole(e.Message);
            }
        }
示例#8
0
		private void ThrowIfErrorsIn(CompilerResults results, IEnumerable<SourceFile> files)
		{
			if (results.Errors.Count > 0)
			{
				StringBuilder message = new StringBuilder();
				CodeDomProvider cSharpCodeProvider;
				try
				{
					cSharpCodeProvider = CodeDomProvider.GetCompilerInfo("csharp").CreateProvider();
				}
				catch (SecurityException)
				{
					cSharpCodeProvider = new CSharpCodeProvider();
				}
				catch (ConfigurationException)
				{
					cSharpCodeProvider = new CSharpCodeProvider();
				}

				try
				{
					foreach (SourceFile file in files)
					{
						CompilerResults result = cSharpCodeProvider.CompileAssemblyFromSource(parameters, file.ConcreteClass);
						if (result.Errors.Count > 0)
							foreach (CompilerError err in result.Errors)
								message.AppendLine(string.Format(@"
On '{0}' (class name: {1}) Line {2}, Column {3}, {4} {5}:
{6}
========================================",
								file.ViewName,
								file.ClassName,
								err.Line,
								err.Column,
								err.IsWarning ? "Warning" : "Error",
								err.ErrorNumber,
								err.ErrorText));
					}
				}
				finally
				{
					cSharpCodeProvider.Dispose();
				}
				throw new Exception("Error while compiling views: " + message);
			}
		}
        internal static Assembly GetProxyAssembly(string wsdlUri, string codeNamespace)
        {
            var provider = new CSharpCodeProvider();
            var client = new WebClient();
            var referenceAssemblies = new[] { "system.dll", "System.Xml.dll", "System.Web.Services.dll" };
            var wsdlStream = client.OpenRead(wsdlUri);

            var wsdl = ServiceDescription.Read(wsdlStream);
            var wsdlImport = new ServiceDescriptionImporter();
            wsdlImport.AddServiceDescription(wsdl, null, null);

            var proxyClassNamespace = new CodeNamespace(codeNamespace);
            var codeCompileUnit = new CodeCompileUnit();
            codeCompileUnit.Namespaces.Add(proxyClassNamespace);

            var warnings = wsdlImport.Import(proxyClassNamespace, codeCompileUnit);
            if (warnings != 0)
            {
                throw new ApplicationException("SOAPHTTPRequestResponseStep experienced problems while importing the WSDL!");
            }

            var compileParam = new CompilerParameters(referenceAssemblies)
                                   {
                                       GenerateInMemory = false,
                                       OutputAssembly = GetProxyFileName()
                                   };

            CompilerResults compilerResults = provider.CompileAssemblyFromDom(compileParam, codeCompileUnit);

            if (compilerResults.Errors.HasErrors)
            {
                throw new ApplicationException("SOAPHTTPRequestResponseStep experienced problems while executing CompileAssemblyFromDom");
            }

            provider.Dispose();

            return compilerResults.CompiledAssembly;
        }
示例#10
0
        /// <summary>
        /// Compile Script -> Return Assembly
        /// </summary>
        public Assembly CompileScript(IRefObject ScriptObject, out CompilerResults Result, String script, bool ClientSide = false)
        {
            String ClassName, PrefixName, AssemblyName = "";

            switch (ScriptObject.Type)
            {
                case IRefObject.ScriptType.WEAPON:
                    ClassName = "ScriptWeapon";
                    PrefixName = "WeaponPrefix";
                    ServerWeapon tempWeap = (ServerWeapon)ScriptObject;
                    AssemblyName = tempWeap.Name.Replace("-", "weapon").Replace("*", "weapon");
                    break;
                case IRefObject.ScriptType.CLASS:
                    PrefixName = "NpcClass";
                    ServerClass tempClass = (ServerClass)ScriptObject;
                    ClassName = tempClass.Name;
                    AssemblyName = "NpcClass." + tempClass.Name + ".dll";
                    break;
                default:
                    ClassName = "ScriptLevelNpc";
                    PrefixName = "LevelNpcPrefix";
                    //ScriptLevelNpc tempNpc = (ScriptLevelNpc)ScriptObject;
                    AssemblyName = "";
                    break;
            }

            // Setup our options
            CompilerParameters options = new CompilerParameters();
            options.GenerateExecutable = false;

            if (ClientSide || ScriptObject.Type == IRefObject.ScriptType.CLASS)
                options.GenerateInMemory = false;
            else
                options.GenerateInMemory = true;

            if (!ClientSide)
                options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Core.dll");
            options.ReferencedAssemblies.Add("OpenGraal.Core.dll");
            options.ReferencedAssemblies.Add("OpenGraal.Common.dll");
            options.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            options.ReferencedAssemblies.Add("MonoGame.Framework.dll");
            if (this.GetClasses() != null)
            {
                foreach (KeyValuePair<string, ServerClass> npcClass in this.GetClasses())
                {
                    if (npcClass.Value.Asm != null)
                        options.ReferencedAssemblies.Add(npcClass.Value.Asm);
                }
            }

            //options.ReferencedAssemblies.
            options.CompilerOptions = "/optimize";

            if (AssemblyName == "")
                AssemblyName = PrefixName + NextId[(int)ScriptObject.Type];

            if (ClientSide)
                options.OutputAssembly = AssemblyName + "_ClientSide.dll";

            if (ScriptObject.Type == IRefObject.ScriptType.CLASS)
                options.OutputAssembly = AssemblyName;

            // Compile our code
            CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider();

            string usingNamespace = "";
            usingNamespace = "using Microsoft.Xna.Framework.Input;";
            string[] CompileData = new string[1];
            if (ScriptObject.Type != IRefObject.ScriptType.CLASS)
                CompileData.SetValue("using System;" + usingNamespace + "using OpenGraal; using OpenGraal.Core; using OpenGraal.Common.Levels; using OpenGraal.Common.Players; using OpenGraal.Common.Scripting; " + (this.GetClasses() != null && this.GetClasses().Count > 0 ? "using OpenGraal.Common.Scripting.NpcClass;" : "") + " public class " + PrefixName + NextId[(int)ScriptObject.Type] + " : " + ClassName + " { public " + PrefixName + NextId[(int)ScriptObject.Type] + "(CSocket Server, IRefObject Ref) : base(Server, Ref) { } " + script + " } ", 0);
            else
                CompileData.SetValue("using System;" + usingNamespace + "using OpenGraal; using OpenGraal.Core; using OpenGraal.Common.Levels; using OpenGraal.Common.Players; using OpenGraal.Common.Scripting; namespace OpenGraal.Common.Scripting.NpcClass { public class " + ClassName + " { " + script + "\n } }", 0);

            Result = null;
            try
            {
                Result = csProvider.CompileAssemblyFromSource(options, CompileData);
            }
            catch (Exception e)
            {
                return null;
            }
            csProvider.Dispose();

            NextId[(int)ScriptObject.Type]++;
            return (Result.Errors.HasErrors ? null : Result.CompiledAssembly);
        }
        /// <exception cref="Exception"><c>Exception</c>.</exception>
        public void CreateLauncher(bool retributionLauncher)
        {
            LoggingManager.SendMessage("ModPacker - Generating launcher for mod " + ModManager.ModName);

            string outputPath = m_sOutputDirectory + "Launch " + ModManager.ModName + ".exe";
            CodeDomProvider provider = null;
            try
            {
                var provOpts = new Dictionary<string, string> { { "CompilerVersion", "v2.0" } };
                provider = new CSharpCodeProvider(provOpts);
                var compilerParams = new CompilerParameters
                {
                    GenerateExecutable = true,
                    IncludeDebugInformation = false,
                    OutputAssembly = outputPath
                };
                compilerParams.ReferencedAssemblies.Add("System.dll");

                // set an icon if the user wishes to include one
                if (m_sIconPath != string.Empty && File.Exists(m_sIconPath))
                    compilerParams.CompilerOptions = "/win32icon:\"" + m_sIconPath + "\"";
                string tmp = Resources.CrudeLauncherSource.Replace("_MODNAME_", ModManager.ModName);
                tmp = tmp.Replace("_APPID_", retributionLauncher ? GameConstants.RETRIBUTION_APP_ID : GameConstants.CR_APP_ID);
                provider.CompileAssemblyFromSource(compilerParams, tmp);
                provider.Dispose();
            }
            catch (Exception ex)
            {
                if (provider != null)
                    provider.Dispose();
                LoggingManager.SendMessage("ModPacker - Failed to create launcher for mod " + ModManager.ModName);
                LoggingManager.HandleException(ex);
                throw;
            }
            LoggingManager.SendMessage("ModPacker - Successfully created launcher for mod " + ModManager.ModName);
        }
示例#12
0
  public static ValuesPair<CodeQuery, List<String>> GetCodeQuery(Type type, string typeWrapperCode)
  {
   CSharpCodeProvider cscp = null;

   try
   {
    cscp = new CSharpCodeProvider();
    ValuesPair<CodeQuery, List<String>> res = 
    new ValuesPair<CodeQuery, List<string>>(null, new List<string>());
    CodeQuery query = new CodeQuery();
    query.CodeText = typeWrapperCode;
    query.ObjectType = type.FullName;

    CompilerParameters cp = new CompilerParameters();
    cp.GenerateInMemory = true;
    cp.TreatWarningsAsErrors = false;
    foreach(Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
     if(asm.IsDynamic == false)
      cp.ReferencedAssemblies.Add(asm.Location);
    CompilerResults cr = cscp.CompileAssemblyFromSource(cp, typeWrapperCode);
    if(cr.Errors.Count > 0)
    {
     foreach(CompilerError err in cr.Errors)
      res.Value2.Add(String.Format("[{0},{1}] {2} {3}: {4}",
       err.Line, err.Column, err.IsWarning ? "Warning" : "Error", err.ErrorNumber, err.ErrorText));
    }
    if(cr.Errors.HasErrors)
     return res;

    MethodInfo mi = cr.CompiledAssembly.GetType(type.Name).GetMethod("DynamicMethod",
                                                                     BindingFlags.NonPublic | BindingFlags.Instance);
    MethodBody mb = mi.GetMethodBody();
    query.MaxStackSize = mb.MaxStackSize;
    query.Body = mb.GetILAsByteArray();
    query.Schema = Discover(query.Body, mi, type);

    if(mb.LocalVariables.Count > 0)
    {
     query.LocalVariables = new List<KeyValuePair<Type, bool>>(mb.LocalVariables.Count);
     foreach(LocalVariableInfo lvi in mb.LocalVariables)
      query.LocalVariables.Add(new KeyValuePair<Type, bool>(lvi.LocalType, lvi.IsPinned));
    }
    res.Value1 = query;

    return res;
   }
   finally
   {
    if(cscp != null)
     cscp.Dispose();
   }
  }
示例#13
0
        public List<string> AnswerCheck(int id, string source)
        {
            string fileName = @"c:\Test\"+DateTime.Now.Ticks+".dll";

            Task task = new Task(id);

            //Configure compiler
            Dictionary<string, string> CompilerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v3.5" }
            };

            CSharpCodeProvider provider = new CSharpCodeProvider(CompilerOptions);

            CompilerParameters compileParam = new CompilerParameters
            {
                OutputAssembly = fileName,
                GenerateExecutable = false
            };

            CompilerResults result = provider.CompileAssemblyFromSource(compileParam, source);
            provider.Dispose();

            //check result of compile
            if (result.Errors.Count != 0)
            {
                List<string> list = new List<string>();
                foreach (CompilerError err in result.Errors)
                    list.Add(err.ToString());
                return list;
            }

            //Invoke user method
            Assembly assembly = result.CompiledAssembly;
            Type type = assembly.GetType("Task.User");
            if (type == null)
            {
                throw new Exception("Type not found!");
            }
            MethodInfo method = type.GetMethod(task.MethodName);
            if (method != null)
            {
                //Check answer
                int res = (int)method.Invoke(null, null);
                if (res == task.Answer)
                    return new List<string> { "true" };
                else
                    return new List<string> { "false" };
            }
            else
                throw new Exception("method not found!");
        }