示例#1
2
文件: test.cs 项目: mono/gert
	public static void Main ()
	{
		CompilerParameters options = new CompilerParameters ();
		options.WarningLevel = 4;

		CodeDomProvider provider = new CSharpCodeProvider ();
#if NET_2_0
		CompilerResults result = provider.CompileAssemblyFromDom (
			options, new CodeSnippetCompileUnit (src));
#else
		ICodeCompiler compiler = provider.CreateCompiler ();
		CompilerResults result = compiler.CompileAssemblyFromDom (
			options, new CodeSnippetCompileUnit (src));
#endif

		Assert.IsFalse (result.Errors.HasErrors, "#1");
#if ONLY_1_0
		Assert.IsFalse (result.Errors.HasWarnings, "#2");
		Assert.AreEqual (0, result.Errors.Count, "#3");
#else
		Assert.IsTrue (result.Errors.HasWarnings, "#2");
#if MONO
		Assert.AreEqual (2, result.Errors.Count, "#3");
		Assert.AreEqual ("CS0108", result.Errors [0].ErrorNumber, "#4");
		Assert.IsTrue (result.Errors [0].IsWarning, "#5");
		Assert.AreEqual ("CS0169", result.Errors [1].ErrorNumber, "#6");
		Assert.IsTrue (result.Errors [1].IsWarning, "#7");
#else
		Assert.AreEqual (1, result.Errors.Count, "#3");
		Assert.AreEqual ("CS0108", result.Errors [0].ErrorNumber, "#4");
		Assert.IsTrue (result.Errors [0].IsWarning, "#5");
#endif
#endif
	}
    protected override void Compile(string code, string[] references)
    {
        var parameters = new CompilerParameters()
        {
            OutputAssembly = FileName,
            IncludeDebugInformation = true
        };

        parameters.ReferencedAssemblies.AddRange(
            GetStandardReferences().Concat(references ?? new string[0])
                                   .Select(ResolveReference)
                                   .ToArray());

        var compilerOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
        var provider = new CSharpCodeProvider(compilerOptions);
        var results = provider.CompileAssemblyFromSource(parameters, code);

        if (results.Errors.Count != 0)
        {
            var errors = new List<string>();

            foreach (CompilerError error in results.Errors)
                errors.Add($"{error.FileName}({error.Line},{error.Column}): error {error.ErrorNumber}: {error.ErrorText}");

            throw new InvalidOperationException($"Compilation Failed:{Environment.NewLine}{string.Join(Environment.NewLine, errors.ToArray())}");
        }
    }
示例#3
0
    public static void Compile(string source, string Output, string EFResource, string Icon = null)
    {
        CompilerParameters CParams = new CompilerParameters();
            CParams.GenerateExecutable = true;
            CParams.OutputAssembly = Output;
            string options = "/optimize+  /t:winexe";
            if (Icon != null)
                options += " /win32icon:\"" + Icon + "\"";
            CParams.CompilerOptions = options;
            CParams.TreatWarningsAsErrors = false;
            CParams.ReferencedAssemblies.Add("System.dll");
            CParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            CParams.ReferencedAssemblies.Add("System.Drawing.dll");
            CParams.ReferencedAssemblies.Add("System.Data.dll");
            CParams.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
            CParams.EmbeddedResources.Add(EFResource);
            Dictionary<string, string> ProviderOptions = new Dictionary<string, string>();
            ProviderOptions.Add("CompilerVersion", "v2.0");
            CompilerResults Results = new CSharpCodeProvider(ProviderOptions).CompileAssemblyFromSource(CParams, source);
            if (Results.Errors.Count > 0)
            {
                MessageBox.Show(string.Format("The compiler has encountered {0} errors",
                    Results.Errors.Count), "Errors while compiling", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                foreach (CompilerError Err in Results.Errors)
                {
                    MessageBox.Show(string.Format("{0}\nLine: {1} - Column: {2}\nFile: {3}", Err.ErrorText,
                        Err.Line, Err.Column, Err.FileName), "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
    }
示例#4
0
    protected void Compile(string code, string[] references)
    {
        var parameters = new CompilerParameters()
        {
            OutputAssembly = FileName,
            IncludeDebugInformation = true
        };

        AddStandardReferences(parameters);

        if (references != null)
            foreach (var reference in references)
            {
                var localFilename = Path.Combine(BasePath, reference);

                if (File.Exists(localFilename))
                    parameters.ReferencedAssemblies.Add(localFilename);
                else
                    parameters.ReferencedAssemblies.Add(reference);
            }

        var compilerOptions = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
        var provider = new CSharpCodeProvider(compilerOptions);
        var results = provider.CompileAssemblyFromSource(parameters, code);

        if (results.Errors.Count != 0)
        {
            var errors = new List<string>();

            foreach (CompilerError error in results.Errors)
                errors.Add(string.Format("{0}({1},{2}): error {3}: {4}", error.FileName, error.Line, error.Column, error.ErrorNumber, error.ErrorText));

            throw new InvalidOperationException(string.Format("Compilation Failed:{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, errors.ToArray())));
        }
    }
示例#5
0
	static bool createDLL( bool isEditorDLL, string DLLName )
	{
		var compileParams = new CompilerParameters();
		compileParams.OutputAssembly = Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop ), DLLName );
		compileParams.CompilerOptions = "/optimize";

		if( isEditorDLL )
			compileParams.CompilerOptions += " /define:UNITY_EDITOR";
		
		compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "Frameworks/Managed/UnityEngine.dll" ) );
		compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll" ) );

		if( isEditorDLL )
		{
			compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "Frameworks/Managed/UnityEditor.dll" ) );
			compileParams.ReferencedAssemblies.Add( Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop ), "ZestKit.dll" ) );
		}

		var source = isEditorDLL ? getSourceForEditorDLL() : getSourceForDLL();

		var codeProvider = new CSharpCodeProvider( new Dictionary<string,string> { { "CompilerVersion", "v3.0" } } );
		var compilerResults = codeProvider.CompileAssemblyFromSource( compileParams, source );

		if( compilerResults.Errors.Count > 0 )
		{
			Debug.Log( "Errors creating DLL: " + DLLName );
			foreach( var error in compilerResults.Errors )
				Debug.LogError( error.ToString() );

			return false;
		}

		return true;
	}
    static void createDLL()
    {
        var compileParams = new CompilerParameters();

        var buildTargetFilename = "SomeFancyDLL.dll";

        compileParams.OutputAssembly = Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop ), buildTargetFilename );
        // for all available compiler options: http://msdn.microsoft.com/en-us/library/6ds95cz0(v=vs.80).aspx
        compileParams.CompilerOptions = "/optimize";
        compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "Frameworks/Managed/UnityEngine.dll" ) );

        var source = getSourceForSelectedScripts();

        var codeProvider = new CSharpCodeProvider( new Dictionary<string, string> { { "CompilerVersion", "v3.0" } } );
        var compilerResults = codeProvider.CompileAssemblyFromSource( compileParams, source );

        if( compilerResults.Errors.Count > 0 )
        {
            foreach( var error in compilerResults.Errors )
                Debug.LogError( error.ToString() );
        }
        else
        {
            // the dll exists
            EditorUtility.DisplayDialog( "Fancy Script Compiler", buildTargetFilename + " should now be on your desktop.", "OK" );
        }
    }
示例#7
0
文件: test.cs 项目: mono/gert
	static void Main ()
	{
		const string source = @"
			public class Scriptefaa4ad0a85c49519cad6a19fbb93caf
			{
				string PadRight (string str, int padding)
				{
					return str.PadRight(padding);
				}
			}";

		CompilerParameters parameters = new CompilerParameters ();
		parameters.GenerateInMemory = true;

		CodeDomProvider provider = new CSharpCodeProvider ();
#if NET_2_0
		CompilerResults results = provider.CompileAssemblyFromSource (
			parameters, source);
#else
		ICodeCompiler compiler = provider.CreateCompiler ();
		CompilerResults results = compiler.CompileAssemblyFromSource (
			parameters, source);
#endif

		Assert.AreEqual (1, results.Errors.Count, "#1");
		Assert.IsFalse (results.Errors.HasErrors, "#2");
		Assert.IsTrue (results.Errors.HasWarnings, "#3");

		foreach (CompilerError error in results.Errors)
			Assert.IsTrue (error.IsWarning, "#4");

		Assert.IsNotNull (results.CompiledAssembly, "#5");
	}
        public void BuildTest()
        {
            var g = new GhostProviderGenerator();
            var codes = g.Build(
                "GPIProvider",
                new[]
                {
                    "Regulus.Tool.GPI"
                },new [] {typeof(Regulus.Tool.GPI.GPIA) });

            Dictionary<string, string> optionsDic = new Dictionary<string, string>
            {
                {"CompilerVersion", "v4.0"}
            };
            var provider = new CSharpCodeProvider(optionsDic);
            var options = new CompilerParameters
            {
                GenerateInMemory = true
                ,GenerateExecutable = false,
                ReferencedAssemblies =
                {
                    "System.Core.dll",
                    "RegulusLibrary.dll",
                    "RegulusRemoting.dll",
                    "protobuf-net.dll",
                    "GhostProviderGeneratorTests.dll"
                }
            };
            var result = provider.CompileAssemblyFromSource(options, codes.ToArray());

            Assert.IsTrue(result.Errors.Count == 0);
        }
示例#9
0
    static Calculator()
    {
        provider = new CSharpCodeProvider();

        // get all System.Math class members
        // so user doesn't need to add "Math." before them
        // and make them case-insensitive (pi, Pi, PI)
        PopulateMathLibrary();
    }
    public static StringBuilder GenerateCode(CodeNamespace ns)
    {
        var codeProvider = new CSharpCodeProvider();
        var builder = new StringBuilder();
        var writer = new StringWriter(builder);

        codeProvider.GenerateCodeFromNamespace(ns, writer, new CodeGeneratorOptions());
        writer.Flush();
        return builder;
    }
 public static void loadCompiledTypes()
 {
     if (!GlobalVariables.EnableExtensions)
     {
         // extensions not enabled
         return;
     }
     if (compiledTypes == null)
     {
         compiledTypes = new List<Type>();
         loadAllExtensionFiles();
         TextWriter tw = null;
         try
         {
             tw = new StreamWriter("Resources/Extensions/Errors.txt");
             foreach (KeyValuePair<String, String> file in extensionFiles)
             {
                 var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
                 var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll", 
                     ProgramFilesx86() + @"/Microsoft XNA/XNA Game Studio/v3.0/References/Windows/x86/Microsoft.Xna.Framework.dll", 
                     "GameObjects.dll", "GameGlobal.dll" });
                 parameters.GenerateExecutable = false;
                 CompilerResults results = csc.CompileAssemblyFromSource(parameters, file.Value);
                 if (results.Errors.Count <= 0)
                 {
                     Type t = results.CompiledAssembly.GetModules()[0].GetTypes()[0];
                     compiledTypes.Add(t);
                 }
                 else
                 {
                     tw.WriteLine(">>> Cannot compile file " + file.Key);
                     foreach (CompilerError error in results.Errors)
                     {
                         tw.WriteLine(error.ErrorText);
                     }
                 }
             }
         }
         catch (DirectoryNotFoundException)
         {
         }
         finally
         {
             if (tw != null)
             {
                 tw.Dispose();
             }
         }
         try
         {
             File.Delete("Resources/Extensions/RuntimeError.txt");
         } catch {}
     }
 }
    public static StringBuilder GenerateCode(CodeNamespace ns)
    {
        var compileUnit = new CodeCompileUnit();
        var codeProvider = new CSharpCodeProvider();
        var builder = new StringBuilder();
        var writer = new StringWriter(builder);

        compileUnit.Namespaces.Add(ns);
        codeProvider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions());
        writer.Flush();
        return builder;
    }
示例#13
0
    static object Evaluate(string expr)
    {
        var compiler = new CSharpCodeProvider();
        var options = new CompilerParameters();
        options.ReferencedAssemblies.Add("system.dll");
        options.GenerateInMemory = true;

        string source = PrepareSource(expr);
        var assembly = compiler.CompileAssemblyFromSource(options, source).CompiledAssembly;
        var evaluator = assembly.CreateInstance("Evaluator");
        return evaluator.GetType().GetMethod("Evaluate").Invoke(evaluator, null);
    }
示例#14
0
 public void Translate(string filename, TextReader input, TextWriter output)
 {
     Debug.Print("Translating module {0} in namespace {1}", moduleName, nmspace);
     var lex = new Lexer(filename, input);
     var par = new Parser(filename, lex);
     var stm = par.Parse();
     var unt = new CodeCompileUnit();
     var gen = new CodeGenerator(unt, nmspace, Path.GetFileNameWithoutExtension(moduleName));
     var xlt = new ModuleTranslator(gen);
     xlt.Translate(stm);
     var pvd = new CSharpCodeProvider();
     pvd.GenerateCodeFromCompileUnit(unt, output, new CodeGeneratorOptions { });
 }
示例#15
0
 public CodeGenerator(CodeCompileUnit unt, string modulePath, string moduleName)
 {
     this.unt = unt;
     this.provider = new CSharpCodeProvider();
     this.Scope = new List<CodeStatement>();  // dummy scope.
     this.CurrentNamespace = new CodeNamespace(modulePath);
     this.CurrentType = new CodeTypeDeclaration(moduleName)
     {
         IsClass = true,
         Attributes = MemberAttributes.Static | MemberAttributes.Public
     };
     CurrentNamespace.Types.Add(CurrentType);
     unt.Namespaces.Add(CurrentNamespace);
 }
示例#16
0
文件: NDocGen.cs 项目: tgassner/NDoc
	static void Main(string[] args)
	{
		int namespaces = 10;
		int classesPerNamespace = 10;
		int methodsPerClass = 10;

		CodeCompileUnit codeCompileUnit = new CodeCompileUnit();

		for (int i = 0; i < namespaces; ++i)
		{
			CodeNamespace codeNamespace = new CodeNamespace();
			codeCompileUnit.Namespaces.Add(codeNamespace);
			codeNamespace.Name = "Namespace" + i;

			for (int j = 0; j < classesPerNamespace; ++j)
			{
				CodeTypeDeclaration codeTypeDeclaration = new CodeTypeDeclaration();
				codeNamespace.Types.Add(codeTypeDeclaration);
				codeTypeDeclaration.Name = "Class" + j;
				codeTypeDeclaration.TypeAttributes = TypeAttributes.Public;
				
				codeTypeDeclaration.Comments.Add(
					new CodeCommentStatement(
						"<summary>This is a summary.</summary>",
						true
					)
				);

				for (int k = 0; k < methodsPerClass; ++k)
				{
					CodeMemberMethod codeMemberMethod = new CodeMemberMethod();
					codeTypeDeclaration.Members.Add(codeMemberMethod);
					codeMemberMethod.Name = "Method" + k;
					codeMemberMethod.Attributes = MemberAttributes.Public;

					codeMemberMethod.Comments.Add(
						new CodeCommentStatement(
							"<summary>This is a summary.</summary>",
							true
						)
					);
				}
			}
		}

		CodeDomProvider codeDomProvider = new CSharpCodeProvider();
		ICodeGenerator codeGenerator = codeDomProvider.CreateGenerator();
		CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
		codeGenerator.GenerateCodeFromCompileUnit(codeCompileUnit, Console.Out, codeGeneratorOptions);
	}
示例#17
0
    /// <summary>
    /// Compiles the source_code 
    /// </summary>
    /// <param name="source_code">source_code must implements IScript interface</param>
    /// <returns>compiled Assembly</returns>
    public static CompilerResults CompileCode(string source_code)
    {
        CSharpCodeProvider provider = new CSharpCodeProvider();

        CompilerParameters options = new CompilerParameters();
        options.GenerateExecutable = false;  // generate a Class Library assembly
        options.GenerateInMemory = true;     // so we don;t have to delete it from disk

        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
        foreach (Assembly assembly in assemblies)
        {
            options.ReferencedAssemblies.Add(assembly.Location);
        }

        return provider.CompileAssemblyFromSource(options, source_code);
    }
    private static void CreateResourceFile(
        string csFile, string resFile, string outputDir, out string sourceHash, out int viewCount)
    {
        viewCount = -1;
        sourceHash = string.Empty;

        var codeProvider = new CSharpCodeProvider();
        var inMemoryCodeCompiler = codeProvider.CreateCompiler();
        var parameters = new CompilerParameters();
        parameters.ReferencedAssemblies.Add("System.Data.Entity.dll");
        parameters.GenerateInMemory = true;
        CompilerResults results = inMemoryCodeCompiler.CompileAssemblyFromFile(parameters, csFile);

        if (results.Errors.Count == 0)
        {
            Assembly resultingAssembly = results.CompiledAssembly;
            Type[] typeList = resultingAssembly.GetTypes();
            foreach (Type type in typeList)
            {
                if (type.BaseType == typeof(EntityViewContainer))
                {
                    MethodInfo[] methodInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
                    var instance = (EntityViewContainer)Activator.CreateInstance(type);
                    sourceHash = instance.HashOverAllExtentViews;
                    viewCount = instance.ViewCount;
                    using (var resWriter = new ResourceWriter(Path.Combine(outputDir, resFile)))
                    {
                        foreach (MethodInfo method in methodInfo)
                        {
                            if (char.IsDigit(method.Name, method.Name.Length - 1))
                            {
                                var result = (KeyValuePair<string, string>)method.Invoke(instance, null);
                                resWriter.AddResource(method.Name.Replace("GetView", string.Empty), result);
                            }
                        }

                        resWriter.Generate();
                        resWriter.Close();
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("Unable to Generate Resource File");
        }
    }
示例#19
0
  public static void Main (string [] args) 
  {
    if (args.Length < 1) 
    {
      Console.WriteLine (usage);
      Console.WriteLine ();
      Console.WriteLine ("Press enter to continue...");
      Console.ReadLine();
      return;
    } //if
	
    string typeName = args[0];
    string ns = null;
    string suffix = "cs";
    string compileLine = "csc /t:library {0}";
    ICodeGenerator cg =new CSharpCodeProvider().CreateGenerator();

    foreach (string arg in args) 
    {
      if (arg.ToUpper().StartsWith ("-?") || arg.ToUpper().StartsWith ("/?")) 
      {
        Console.WriteLine (usage);
        Console.WriteLine ();
        Console.WriteLine ("Press enter to continue...");
        Console.ReadLine();
        return;
      } //if

      if (arg.ToUpper().StartsWith ("-N:") || arg.ToUpper().StartsWith ("/N:")) 
      {
        ns = arg.Remove(0,3);
      } //if
    } //foreach

    string fileName = typeName + "Collection." + suffix;
    Console.WriteLine ("Creating source file {0}.", fileName);
    if (compileLine != null)
    {
      Console.WriteLine ("compile with: '{0}'.", string.Format (compileLine, fileName));
    } //if

    TextWriter t = new StreamWriter (new FileStream (fileName, FileMode.Create));
    SpitList (t, typeName, cg, ns);
    t.Close();
  } //Main()
示例#20
0
    internal static void testCompileFiles(List<string> files)
    {
        if (files.Count == 0) return;
        Dictionary<string, string> options = new Dictionary<string, string>();
        options.Add("CompilerVersion", "v3.5");
        CodeDomProvider codeProvider = new CSharpCodeProvider(options);
        CompilerInfo compilerInfo = CodeDomProvider.GetCompilerInfo("cs");
        CompilerParameters compilerParam = compilerInfo.CreateDefaultCompilerParameters();
        compilerParam.TreatWarningsAsErrors = false;
        compilerParam.IncludeDebugInformation = true;
        compilerParam.GenerateInMemory = true;
        foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) {
            try {
                compilerParam.ReferencedAssemblies.Add(assembly.Location);
            } catch {
            }
        }

        CompilerResults result = codeProvider.CompileAssemblyFromFile(compilerParam, files.ToArray());
        List<CompilerError> errors = new List<CompilerError>();
        foreach (CompilerError error in result.Errors) {
            errors.Add(error);
        }
        var criticalErrors = from err in errors where !err.IsWarning select err;
        if (criticalErrors.Count() > 0) {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(criticalErrors.Count() + Local.Text("Web.WAF.Edit.ExplorerCriticalCompileError"));
            sb.AppendLine("<ol>");
            foreach (CompilerError error in criticalErrors) {
                if (!error.IsWarning) {
                    sb.Append("<li>" + error.ErrorText + ":");
                    if (error.FileName.Length > WAFContext.PathFromRootToAppFolder.Length) {
                        sb.Append("<div style=\"color:gray\"> -> " + error.FileName.Substring(WAFContext.PathFromRootToAppFolder.Length) + "</div>");
                    } else {
                        sb.Append("<div style=\"color:gray\"> -> " + error.FileName + "</div>");
                    }
                    sb.Append("<div style=\"color:gray\"> -> Line " + error.Line + " Col " + error.Column + "</div>");
                    sb.Append("<br/><br/></li>");
                }
            }
            sb.AppendLine("</ol>");
            throw new Exception(sb.ToString());
        }
    }
    static void CompileAndRun(string csharpCode)
    {
        // Prepare a C# program for compilation
        string[] csharpClass =
        {
            @"using System;

                  public class RuntimeCompiledClass
                  {
                     public static void Main()
                     {" +
            csharpCode + @"
                     }
                  }"
        };

        // Compile the C# program
        CompilerParameters compilerParams = new CompilerParameters();
        compilerParams.GenerateInMemory = true;
        compilerParams.TempFiles = new TempFileCollection(".");
        compilerParams.ReferencedAssemblies.Add("System.dll");
        compilerParams.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
        CSharpCodeProvider csharpProvider = new CSharpCodeProvider();
        CompilerResults compile = csharpProvider.CompileAssemblyFromSource(
            compilerParams, csharpClass);

        // Check for compilation errors
        if (compile.Errors.HasErrors)
        {
            string errorMsg = "Compilation error: ";
            foreach (CompilerError ce in compile.Errors)
            {
                errorMsg += "\r\n" + ce.ToString();
            }
            throw new Exception(errorMsg);
        }

        // Invoke the Main() method of the compiled class
        Assembly assembly = compile.CompiledAssembly;
        Module module = assembly.GetModules()[0];
        Type type = module.GetType("RuntimeCompiledClass");
        MethodInfo methInfo = type.GetMethod("Main");
        methInfo.Invoke(null, null);
    }
示例#22
0
    public static bool CompileSource(string source, string outputAssembly)
    {
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();

        CompilerParameters compilerParameters = new CompilerParameters();

        // Add an assembly reference.
           		compilerParameters.ReferencedAssemblies.Add( "System.dll" );

        //compilerParams.ReferencedAssemblies.Add( "/Applications/Unity/Unity.app/Contents/Frameworks/Managed/UnityEngine.dll" );
        compilerParameters.ReferencedAssemblies.Add("C:/Program Files (x86)/Unity/Editor/Data/Managed/UnityEngine.dll" );

        compilerParameters.GenerateExecutable = false;
        compilerParameters.GenerateInMemory = false;

        compilerParameters.OutputAssembly = outputAssembly;

        CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, source);

        if (compilerResults.Errors.Count > 0)
           	{
           	// Display compilation errors.
            foreach (CompilerError compilerError in compilerResults.Errors)
            {
                Debug.LogError(compilerError);
            }
        }
        else
        {
            Debug.Log(outputAssembly + " built successfully.");
        }

        // Return the results of compilation.
        if (compilerResults.Errors.Count > 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
示例#23
0
		private static Type CreateFor(Type t, Dictionary<string, List<string>> influences)
		{
			var provider = new CSharpCodeProvider();
			CompilerParameters cp = new CompilerParameters();
			cp.GenerateInMemory = true;
			CodeCompileUnit cu = new CodeCompileUnit();
			AddAllAssemblyAsReference(cu);
			cu.Namespaces.Add(CreateNamespace(t, influences));
#if DEBUG
			StringWriter sw = new StringWriter();
			provider.GenerateCodeFromCompileUnit(cu, sw, new CodeGeneratorOptions() { BracingStyle = "C" });
			Trace.WriteLine(sw.GetStringBuilder());
#endif
			CompilerResults cr = provider.CompileAssemblyFromDom(cp, cu);
			if (cr.Errors.Count > 0)
			{
				ThrowErrors(cr.Errors);
			}
			return cr.CompiledAssembly.GetTypes()[0];
		}
示例#24
0
	static void createDLL()
	{
		var compileParams = new CompilerParameters();
		compileParams.OutputAssembly = Path.Combine( System.Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop ), kBuildTargetFilename );
		compileParams.CompilerOptions = "/optimize";
		compileParams.ReferencedAssemblies.Add( Path.Combine( EditorApplication.applicationContentsPath, "Frameworks/Managed/UnityEngine.dll" ) );

		var source = getSourceForStandardDLL( kSourcePath );

		var codeProvider = new CSharpCodeProvider( new Dictionary<string, string> { { "CompilerVersion", "v3.0" } } );
    	var compilerResults = codeProvider.CompileAssemblyFromSource( compileParams, source );

    	if( compilerResults.Errors.Count > 0 )
    	{
    		foreach( var error in compilerResults.Errors )
    			Debug.LogError( error.ToString() );
		}
		else
		{
			EditorUtility.DisplayDialog( "TouchKit", "TouchKit.dll should now be on your desktop. If you would like the in-editor support (multi-touch simulator and debug drawing of touch frames) copy the TouchKit/Editor/TouchKitEditor.cs file into your project along with the TouchKit.dll", "OK" );
		}
	}
示例#25
0
    /// <summary>
    /// Compiles a C# script as if it were a file in your project.
    /// </summary>
    /// <param name="scriptText">The text of the script.</param>
    /// <param name="errors">The compiler errors and warnings from compilation.</param>
    /// <param name="assemblyIfSucceeded">The compiled assembly if compilation succeeded.</param>
    /// <returns>True if compilation was a success, false otherwise.</returns>
    public static bool CompileCSharpScript(string scriptText, out CompilerErrorCollection errors, out Assembly assemblyIfSucceeded)
    {
        var codeProvider = new CSharpCodeProvider();
        var compilerOptions = new CompilerParameters();

        // we want a DLL and we want it in memory
        compilerOptions.GenerateExecutable = false;
        compilerOptions.GenerateInMemory = true;

        // add references to all currently loaded assemblies
        foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            compilerOptions.ReferencedAssemblies.Add(assembly.Location);
        }

        // default to null output parameters
        errors = null;
        assemblyIfSucceeded = null;

        // compile the assembly from the source script text
        CompilerResults result = codeProvider.CompileAssemblyFromSource(compilerOptions, scriptText);

        // store the errors for the caller. even on successful compilation, we may have warnings.
        errors = result.Errors;

        // see if any errors are actually errors. if so return false
        foreach (CompilerError e in errors)
        {
            if (!e.IsWarning)
            {
                return false;
            }
        }

        // otherwise we pass back the compiled assembly and return true
        assemblyIfSucceeded = result.CompiledAssembly;
        return true;
    }
示例#26
0
    bool TryCompile(string source, List<string> references, out string errors, out Assembly assembly)
    {
        bool result = false;
        assembly = null;
        errors = null;

        Dictionary<string, string> options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
        CSharpCodeProvider csc = new CSharpCodeProvider(options);
        CompilerParameters parameters = new CompilerParameters();
        parameters.GenerateInMemory = true;
        parameters.IncludeDebugInformation = debuggingEnabled;
        parameters.ReferencedAssemblies.AddRange(references.ToArray());
        parameters.ReferencedAssemblies.Add("System.dll");
        parameters.ReferencedAssemblies.Add("System.Core.dll");
        parameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
        if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("EDGE_CS_TEMP_DIR")))
        {
            parameters.TempFiles = new TempFileCollection(Environment.GetEnvironmentVariable("EDGE_CS_TEMP_DIR"));
        }
        CompilerResults results = csc.CompileAssemblyFromSource(parameters, source);
        if (results.Errors.HasErrors)
        {
            foreach (CompilerError error in results.Errors)
            {
                if (errors == null)
                {
                    errors = error.ToString();
                }
                else
                {
                    errors += "\n" + error.ToString();
                }
            }
        }
        else
        {
            assembly = results.CompiledAssembly;
            result = true;
        }

        return result;
    }
示例#27
0
        private static Assembly CompileCode(string code)
        {
            // Create a code provider
            // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones)
            // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that
            // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?)
            var csProvider = new CSharpCodeProvider();

            // Setup our options
            var options = new CompilerParameters();
            options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net)
            options.GenerateInMemory = true;
                // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile
            // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best!

            // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow
            // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows
            // thus they can only do the things you want them to.
            // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it)
            // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another
            // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to
            // the "script"
            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

            // Compile our code
            CompilerResults result;
            result = csProvider.CompileAssemblyFromSource(options, code);

            if (result.Errors.HasErrors)
            {
                // TODO: report back to the user that the script has errored
                Logger.Instance.Write("An error occured while compiling script code");

                return null;
            }

            if (result.Errors.HasWarnings)
            {
                // TODO: tell the user about the warnings, might want to prompt them if they want to continue
                // runnning the "script"

                Logger.Instance.Write("Script has warnings in compilations");
            }

            return result.CompiledAssembly;
        }
示例#28
0
        /// < summary>
        /// 动态调用web服务
        /// < /summary>
        /// < param name="url">WSDL服务地址< /param>
        /// < param name="classname">类名< /param>
        /// < param name="methodname">方法名< /param>
        /// < param name="args">参数< /param>
        /// < returns>< /returns>
        public static object InvokeWebService(string url, string classname, string methodname, object[] args)
        {
            string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = DynamicWeb.GetWsClassName(url);
            }

            try
            {
                //获取WSDL
                WebClient                  wc     = new WebClient();
                Stream                     stream = wc.OpenRead(url + "?WSDL");
                ServiceDescription         sd     = ServiceDescription.Read(stream);
                ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(@namespace);

                //生成客户端代理类代码
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider icc = new CSharpCodeProvider();

                //设定编译参数
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory   = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法
                System.Reflection.Assembly assembly = cr.CompiledAssembly;
                Type   t   = assembly.GetType(@namespace + "." + classname, true, true);
                object obj = Activator.CreateInstance(t);
                System.Reflection.MethodInfo mi = t.GetMethod(methodname);

                object d = mi.Invoke(obj, args);
                string f = d.ToString();
                return(d);

                /*
                 * PropertyInfo propertyInfo = type.GetProperty(propertyname);
                 * return propertyInfo.GetValue(obj, null);
                 */
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }
示例#29
0
 void CreateTestFile(String[] values)
   {
   StreamWriter sw = new StreamWriter("test.cs");
   CSharpCodeProvider cdp = new CSharpCodeProvider();
   ICodeGenerator cg = cdp.CreateGenerator();
   CodeNamespace cnspace = new CodeNamespace("N");
   cnspace.Imports.Add(new CodeNamespaceImport("System"));
   CodeTypeDeclaration co = new CodeTypeDeclaration ("C");
   co.IsClass = true;
   cnspace.Types.Add (co);
   co.TypeAttributes  = TypeAttributes.Public;
   CodeMemberMethod cmm = new CodeMemberMethod();
   cmm.Name = "Main";
   cmm.ReturnType = null;
   cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
   CodeVariableDeclarationStatement cvar = new CodeVariableDeclarationStatement(typeof(String[]), "args", new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Environment"), "GetCommandLineArgs"));
   cmm.Statements.Add(cvar);  
   cvar = new CodeVariableDeclarationStatement(typeof(Int32), "exitCode", new CodeSnippetExpression("0"));
   cmm.Statements.Add(cvar);
   String strArgLength = (values.Length + 1).ToString();
   CodeConditionStatement ccs1 = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("args.Length"), CodeBinaryOperatorType.IdentityInequality, new CodeSnippetExpression(strArgLength)), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   ccs1 = new CodeConditionStatement(new CodeSnippetExpression("!args[0].ToLower().EndsWith(\"test.exe\")"), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   for(int i=0; i<values.Length; i++){
   ccs1 = new CodeConditionStatement(new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("args[" + (i+1).ToString() + "]"), CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(values[i])), new CodeStatement []{new CodeAssignStatement(new CodeVariableReferenceExpression("exitCode"), new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("exitCode"), CodeBinaryOperatorType.Add, new CodeSnippetExpression("1")))});
   cmm.Statements.Add(ccs1);
   }
   cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("Environment.ExitCode"), new CodeVariableReferenceExpression("exitCode")));
   co.Members.Add(cmm);
   cg.GenerateCodeFromNamespace(cnspace, sw, null);
   sw.Flush();
   sw.Close();		
   }
示例#30
0
        public static void WriteEnum(TextWriter writer, string ns, string typeName, string[] fields, bool withFlagsAttribute = false, string zerothField = null, string allField = null)
        {
            var compileUnit = new CodeCompileUnit();


            // create namespace.
            var codeNamespace = new CodeNamespace(ns);

            compileUnit.Namespaces.Add(codeNamespace);

            // create enum type declaration
            var codeType = new CodeTypeDeclaration(typeName);

            codeNamespace.Types.Add(codeType);
            // is enum
            codeType.IsEnum = true;
            // optionally add [Flags] attribute
            if (withFlagsAttribute)
            {
                // using System;
                //codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
                // [Flags] attribute
                codeType.CustomAttributes.Add(new CodeAttributeDeclaration("System.Flags"));
            }

            var index = 0;

            // create the None field
            if (withFlagsAttribute && !string.IsNullOrEmpty(zerothField))
            {
                var codeField = new CodeMemberField(codeType.Name, zerothField);
                codeField.InitExpression = new CodePrimitiveExpression(0);
                codeType.Members.Add(codeField);
            }

            // creating enum fields
            foreach (var valueName in fields)
            {
                // create enum fields
                var codeField = new CodeMemberField(codeType.Name, valueName);

                if (withFlagsAttribute)
                {
                    // flags have values that are a power of 2 (each its own bit 1, 2, 4, 8, 16),
                    codeField.InitExpression = new CodePrimitiveExpression(1 << index++);// index is the index of the bit
                }
                else
                {
                    // just the default zero-based index (0, 1, 2, 4, 5)
                    codeField.InitExpression = new CodePrimitiveExpression(index++);
                }
                // add field to type
                codeType.Members.Add(codeField);
            }
            // create the All field. This is the total of all of the above combined
            if (withFlagsAttribute && !string.IsNullOrEmpty(allField))
            {
                var codeField = new CodeMemberField(codeType.Name, allField);
                codeField.InitExpression = new CodePrimitiveExpression((1 << index) - 1);
                codeType.Members.Add(codeField);
            }

            // write the code
            var provider = new CSharpCodeProvider();
            var options  = new CodeGeneratorOptions();

            options.BlankLinesBetweenMembers = false;

            provider.GenerateCodeFromCompileUnit(compileUnit, writer, options);
        }
        private void doCompile(_ScopeData sdata)
        {
            CSharpCodeProvider comp = new CSharpCodeProvider();

            CompilerParameters cp = new CompilerParameters();

            foreach (var ass in sdata.m_ReferencedAssemblies)
            {
                cp.ReferencedAssemblies.Add(ass);
            }
            cp.GenerateExecutable = false;
            cp.GenerateInMemory   = true;


            var ns = "NFX.Parsing.CompilingExpressionEvaluator." + m_Scope;

            StringBuilder code = new StringBuilder();

            foreach (var use in sdata.m_Usings)
            {
                code.AppendLine("using " + use + ";");
            }

            code.AppendLine("namespace " + ns + " { ");
            code.AppendLine("  public static class Evaluator { ");

            for (var i = 0; i < sdata.m_Expressions.Count; i++)
            {
                var expr = sdata.m_Expressions[i];

                code.AppendLine(
                    string.Format(" public static {0} DoEval_{1}({2} ctx, {3} arg)",
                                  tname(typeof(TResult)),
                                  i,
                                  tname(typeof(TContext)),
                                  tname(typeof(TArg))
                                  )
                    );

                code.AppendLine("  { ");

                code.AppendLine("       return (" + expr.m_Expression + ");");

                code.AppendLine("  } ");
                code.AppendLine();
            }  //for

            code.AppendLine("}");  //class
            code.AppendLine("}");  //namespace

            CompilerResults cr = comp.CompileAssemblyFromSource(cp, code.ToString());

            if (cr.Errors.HasErrors)
            {
                StringBuilder error = new StringBuilder();
                error.Append("Error Compiling Expression: ");
                foreach (CompilerError err in cr.Errors)
                {
                    error.AppendFormat("{0}\n", err.ErrorText);
                }

                sdata.CompileException = new NFXException(StringConsts.EXPRESSION_SCOPE_COMPILE_ERROR + error.ToString());
                return;
            }

            sdata.Assembly = cr.CompiledAssembly;

            for (var i = 0; i < sdata.m_Expressions.Count; i++)
            {
                var expr   = sdata.m_Expressions[i];
                var type   = sdata.Assembly.GetType(ns + ".Evaluator");
                var method = type.GetMethod("DoEval_" + i.ToString());

                expr.m_EvalMethod = method;
            }
        }
        ITaskItem GenerateCodeBehind(ITaskItem layoutFile, CodeGeneratorOptions generatorOptions)
        {
            string codeBehindFile = layoutFile.GetMetadata("CodeBehindFileName");

            if (string.IsNullOrEmpty(codeBehindFile))
            {
                Log.LogError($"Required MetaData 'CodeBehindFileName' for {layoutFile} was not found.");
                return(null);
            }
            string partialClassName = layoutFile.GetMetadata("ClassName");

            if (String.IsNullOrEmpty(partialClassName))
            {
                Log.LogError($"Required MetaData 'ClassName' for {layoutFile} was not found.");
                return(null);
            }
            int    idx = partialClassName.LastIndexOf('.');
            string className;
            string namespaceName;

            if (idx >= 0)
            {
                className     = partialClassName.Substring(idx + 1);
                namespaceName = partialClassName.Substring(0, idx);
            }
            else
            {
                className     = partialClassName;
                namespaceName = null;
            }

            if (String.IsNullOrEmpty(className))
            {
                Log.LogError($"Layout file {layoutFile.ItemSpec} doesn't specify a valid code-behind class name. It cannot be empty.");
                return(null);
            }

            var compileUnit = new CodeCompileUnit();
            var ns          = new CodeNamespace(namespaceName);

            compileUnit.Namespaces.Add(ns);
            foreach (string import in StandardImports)
            {
                ns.Imports.Add(new CodeNamespaceImport($"global::{import}"));
            }

            CodeTypeDeclaration mainClass = AddMainClass(layoutFile, ns, className);

            if (!GenerateLayoutMembers(mainClass, Path.GetFullPath(layoutFile.ItemSpec)))
            {
                Log.LogError($"Layout code-behind failed for '{layoutFile.ItemSpec}'");
            }
            else
            {
                var provider = new CSharpCodeProvider();
                using (var sw = new StreamWriter(Path.Combine(MonoAndroidCodeBehindDir, codeBehindFile), false, Encoding.UTF8)) {
                    using (var tw = new IndentedTextWriter(sw, "\t")) {
                        provider.GenerateCodeFromCompileUnit(compileUnit, tw, generatorOptions);
                    }
                }
            }

            return(new TaskItem(codeBehindFile));;
        }
示例#33
0
        public static bool CompileCSScripts(bool debug, bool cache, out Assembly assembly)
        {
            Utility.PushColor(ConsoleColor.Green);
            Console.Write("Scripts: Compiling C# scripts...");
            Utility.PopColor();
            string[] files = GetScripts("*.cs");

            if (files.Length == 0)
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.WriteLine("no files found.");
                Utility.PopColor();
                assembly = null;
                return(true);
            }

            if (File.Exists("Scripts/Output/Scripts.CS.dll"))
            {
                if (cache && File.Exists("Scripts/Output/Scripts.CS.hash"))
                {
                    try
                    {
                        byte[] hashCode = GetHashCode("Scripts/Output/Scripts.CS.dll", files, debug);

                        using (var fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            using (var bin = new BinaryReader(fs))
                            {
                                byte[] bytes = bin.ReadBytes(hashCode.Length);

                                if (bytes.Length == hashCode.Length)
                                {
                                    bool valid = true;

                                    for (int i = 0; i < bytes.Length; ++i)
                                    {
                                        if (bytes[i] != hashCode[i])
                                        {
                                            valid = false;
                                            break;
                                        }
                                    }

                                    if (valid)
                                    {
                                        assembly = Assembly.LoadFrom("Scripts/Output/Scripts.CS.dll");

                                        if (!m_AdditionalReferences.Contains(assembly.Location))
                                        {
                                            m_AdditionalReferences.Add(assembly.Location);
                                        }

                                        Utility.PushColor(ConsoleColor.Green);
                                        Console.WriteLine("done (cached)");
                                        Utility.PopColor();

                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                    catch
                    { }
                }
            }

            DeleteFiles("Scripts.CS*.dll");

            using (var provider = new CSharpCodeProvider())
            {
                string path = GetUnusedPath("Scripts.CS");

                var parms = new CompilerParameters(GetReferenceAssemblies(), path, debug);

                string options = GetCompilerOptions(debug);

                if (options != null)
                {
                    parms.CompilerOptions = options;
                }

                if (Core.HaltOnWarning)
                {
                    parms.WarningLevel = 4;
                }

#if !MONO
                CompilerResults results = provider.CompileAssemblyFromFile(parms, files);
#else
                parms.CompilerOptions = String.Format("{0} /nowarn:618,169,219,414,618,429,162,252,849,1717,612,108,109,649 /recurse:Scripts/*.cs", parms.CompilerOptions);
                CompilerResults results = provider.CompileAssemblyFromFile(parms, String.Empty);
#endif
                m_AdditionalReferences.Add(path);

                Display(results);

#if !MONO
                if (results.Errors.Count > 0)
                {
                    assembly = null;
                    return(false);
                }
#else
                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError err in results.Errors)
                    {
                        if (!err.IsWarning)
                        {
                            assembly = null;
                            return(false);
                        }
                    }
                }
                #endif

                if (cache && Path.GetFileName(path) == "Scripts.CS.dll")
                {
                    try
                    {
                        byte[] hashCode = GetHashCode(path, files, debug);

                        using (
                            var fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            using (var bin = new BinaryWriter(fs))
                            {
                                bin.Write(hashCode, 0, hashCode.Length);
                            }
                        }
                    }
                    catch
                    { }
                }

                assembly = results.CompiledAssembly;
                return(true);
            }
        }
示例#34
0
        /// <summary>
        /// 编译C#脚本文件
        /// </summary>
        /// <param name="path">脚本文件所在根目录</param>
        /// <param name="dllName">输出的dll文件名(包含.dll)</param>
        /// <param name="reflections">要引用的程序集名称列表</param>
        /// <returns></returns>
        public static Assembly CompileCS(string path, string dllName, string[] reflections)
        {
            if (!path.EndsWith(@"\") && !path.EndsWith(@"/"))
            {
                path += "/";
            }

            ArrayList files = ParseDirectory(new DirectoryInfo(path), "*.cs", true);

            if (files.Count == 0)
            {
                return(null);
            }

            if (File.Exists(dllName))
            {
                File.Delete(dllName);
            }

            try
            {
                CodeDomProvider compiler = new CSharpCodeProvider();

                CompilerParameters param = new CompilerParameters(reflections, dllName, true);

                param.GenerateExecutable = false;
                param.GenerateInMemory   = false;
                param.WarningLevel       = 2;
                param.CompilerOptions    = @"/lib:.";

                string[] filePaths = new string[files.Count];

                for (int i = 0; i < files.Count; i++)
                {
                    filePaths[i] = ((FileInfo)files[i]).FullName;
                }

                CompilerResults rlt = compiler.CompileAssemblyFromFile(param, filePaths);

                GC.Collect();

                if (rlt == null)
                {
                    return(null);
                }

                if (rlt.Errors.HasErrors)
                {
                    foreach (CompilerError err in rlt.Errors)
                    {
                        if (err.IsWarning)
                        {
                            continue;
                        }

                        StringBuilder sb = new StringBuilder();

                        sb.Append("    ");
                        sb.Append(err.FileName);
                        sb.Append(" 行:");
                        sb.Append(err.Line);
                        sb.Append(" 列:");
                        sb.Append(err.Column);

                        if (log.IsErrorEnabled)
                        {
                            log.Error("Compilation failed, because:");
                            log.Error(err.ErrorText);
                            log.Error(sb.ToString());
                        }
                    }
                    return(null);
                }

                return(rlt.CompiledAssembly);
            }
            catch (Exception ex)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("Compilation", ex);
                }

                return(null);
            }
        }
示例#35
0
        private bool Compile(string archivePath, string outputFile, ref string replacedFile, AssemblyInfo assemblyInfo)
        {
            bool allGood = false;

            #region Compile

            List <string> defines = new List <string>();
            Dictionary <string, string> replacements = new Dictionary <string, string>();

            #region Create the CodeDomProvider

            FileInfo fileInfo = new FileInfo(outputFile);

            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }

            CodeDomProvider    csc = new CSharpCodeProvider();
            CompilerParameters cp  = new CompilerParameters();

            cp.GenerateExecutable = true;
            cp.OutputAssembly     = outputFile;
            cp.CompilerOptions    = " /filealign:512 /optimize+ /platform:x86";

            if (Helper.IsNotNullOrEmpty(IconFile))
            {
                cp.CompilerOptions += string.Format(" /win32icon:\"{0}\"", IconFile);
            }

            if (Debug)
            {
                defines.Add("DEBUG");
                cp.CompilerOptions += " /debug+ /debug:full";
            }

            #endregion

            #region Defines

            defines.Add("RPX");

            string targetName;

            ConsoleThemeColor targetColour = ConsoleThemeColor.SubTextGood;

            switch (ExecutableType)
            {
            case ExecutableType.Console:
                cp.CompilerOptions += " /target:exe";
                targetName          = Rpx.Strings.Compiler_ConsoleApplication;
                break;

            case ExecutableType.Forms:
                cp.CompilerOptions += " /target:winexe";
                defines.Add("WinExec");
                targetName = Rpx.Strings.Compiler_FormsApplication;
                break;

            default:
                cp.CompilerOptions += " /target:exe";
                targetName          = Rpx.Strings.Compiler_DefaultApplication;
                targetColour        = ConsoleThemeColor.SubTextBad;
                break;
            }

            if (RC.ShouldWrite(ConsoleVerbosity.Verbose))
            {
                RC.WriteLine(ConsoleVerbosity.Verbose, targetColour, " - " + string.Format(Rpx.Strings.Compiler_AssemblyTarget, targetName));
            }
            else
            {
                RC.WriteLine(ConsoleVerbosity.Minimal, targetColour, " " + string.Format(Rpx.Strings.Compiler_AssemblyTarget, targetName));
            }

            if (Decorate)
            {
                defines.Add("Decorate");
            }

            if (Assemblys.Count > 1 || Tools.Count > 0)
            {
                defines.Add("HasAdditionalAssemblys");
            }

            if (Tools.Count > 0)
            {
                defines.Add("IsToolkit");
            }

            if (PassArguments)
            {
                defines.Add("PassArguments");
            }

            if (GetAssembyInfoFrom != AssemblyInfoMode.SourceFile)
            {
                defines.Add("ExpliciteInfo");

                replacements.Add("[Asm_Title]", Helper.MakeNonNull(assemblyInfo.Title));

                string description = Helper.MakeNonNull(assemblyInfo.Description);

                if (Helper.IsNotNullOrEmpty(description)) //  Asm_Description))
                {
                    description += "\n";
                }

                string watermark = "RPX " + typeof(CompileProcess).Assembly.GetName().Version.ToString();

                if (!description.Contains(watermark))
                {
                    description += watermark;
                }

                replacements.Add("[Asm_Description]", Helper.MakeNonNullAndEscape(description));
                replacements.Add("[Asm_Configuration]", Helper.MakeNonNullAndEscape(assemblyInfo.Configuration));
                replacements.Add("[Asm_Company]", Helper.MakeNonNullAndEscape(assemblyInfo.Company));
                replacements.Add("[Asm_Product]", Helper.MakeNonNullAndEscape(assemblyInfo.Product));
                replacements.Add("[Asm_Copyright]", Helper.MakeNonNullAndEscape(assemblyInfo.Copyright));
                replacements.Add("[Asm_Trademark]", Helper.MakeNonNullAndEscape(assemblyInfo.Trademark));
                replacements.Add("[Asm_Culture]", Helper.MakeNonNullAndEscape(assemblyInfo.Culture));
                replacements.Add("[Asm_Version]", Helper.MakeNonNullAndEscape(assemblyInfo.Version));
                replacements.Add("[Asm_FileVersion]", Helper.MakeNonNullAndEscape(assemblyInfo.FileVersion));

                //RC.WriteLine(ConsoleVerbosity.Normal, ConsoleColorExt.Gray, " " + Rpx.Strings.Compiler_AssemblyInfoHasBeenReflected);

                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Product.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Product));
                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Version.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Version));
                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_FileVersion.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.FileVersion));
                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Configuration.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Configuration));

                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Company.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Company));
                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Description.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Description));

                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Copyright.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Copyright));
                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Trademark.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Trademark));
                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + Rpx.Strings.AssemblyInfo_Culture.PadRight(16) + ": " + Helper.MakeNonNullAndEscape(assemblyInfo.Culture));
            }
            else
            {
                RC.WriteLine(ConsoleVerbosity.Normal, ConsoleThemeColor.Text, " " + Rpx.Strings.Compiler_AssemblyInfoFromFile);
                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.SubText, " - " + AssembyInfoSourceFilePath);
                //
            }


            if (Compression.Protected)
            {
                if (Helper.IsNotNullOrEmpty(Compression.Password))
                {
                    RC.WriteLine(ConsoleVerbosity.Normal, ConsoleThemeColor.Text, " " + Rpx.Strings.Compiler_IncludeCryptographyCode);

                    defines.Add("UseCryptography");
                }
                else
                {
                    RC.WriteLine(ConsoleVerbosity.Normal, ConsoleThemeColor.Text, " " + Rpx.Strings.Compiler_IncludeDisguiseCode);
                }

                defines.Add("Hidden");
            }

            foreach (string define in defines)
            {
                cp.CompilerOptions += " /define:" + define;
            }

            #endregion

            #region Include the Archive Resource

            string archiveName = "a.zip";

            if (Compression.Protected)
            {
                archiveName = "a";
            }

            #region Finalise Package

            Compression.FinalisePackage(Compression.OutputFile);

            #endregion

            cp.CompilerOptions += string.Format(" /resource:\"{0}\",{1}", archivePath, archiveName);

            #endregion

            #region Add Default Refrences

            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cp.CompilerOptions += string.Format(" /reference:\"{0}\"", typeof(Package).Assembly.Location);

            #endregion

            #region Define Remaining Code Template Replacements

            if (GetAssembyInfoFrom == AssemblyInfoMode.SourceFile)
            {
                replacements.Add("[#AssemblyInfo.cs#]", File.ReadAllText(AssembyInfoSourceFilePath).Replace("using System.Reflection;", ""));
            }

            replacements.Add("#ResourceLocation#", archiveName);

            if (Compression.Protected)
            {
                if (Helper.IsNotNullOrEmpty(Compression.Password))
                {
                    replacements.Add("[#PasswordVector#]", Helpers.EncryptHelper.InitVector);
                    replacements.Add("[#PasswordSalt#]", Compression.SaltValue);
                    replacements.Add("[#Password#]", Compression.Password);
                    replacements.Add("[#PasswordStrength#]", "2");
                }
            }

            List <Dictionary <string, string> > AssemblyReplacements = new List <Dictionary <string, string> >();
            List <Dictionary <string, string> > ToolReplacements     = new List <Dictionary <string, string> >();

            #region Build Assembly Code

            int asmId = 0;

            if (Assemblys.Count > 1)
            {
                foreach (string asm in Assemblys)
                {
                    string path = PackageHelper.MakeUriSafe(asm.Substring(asm.LastIndexOf("\\") + 1));

                    if (path != InitialAssemblyPath)
                    {
                        Dictionary <string, string> asmReplacements = new Dictionary <string, string>();

                        string idStr = "a" + (asmId++).ToString();

                        asmReplacements.Add("[#Asm_IdStr#]", idStr);
                        asmReplacements.Add("[#Asm_Path#]", PackageHelper.MakeUriSafe(path));
                        AssemblyReplacements.Add(asmReplacements);
                    }
                }
            }

            #endregion

            #region Build Tools Code

            if (Tools.Count > 0)
            {
                RC.WriteLine(ConsoleVerbosity.Verbose, ConsoleThemeColor.TitleText, "\n" + Rpx.Strings.Compiler_Toolkit);

                if (RC.ShouldWrite(ConsoleVerbosity.Normal))
                {
                    RC.WriteLine(ConsoleVerbosity.Minimal, ConsoleThemeColor.Text, " " + string.Format(Rpx.Strings.Compiler_Tools, Tools.Count.ToString()));
                }
                else if (RC.ShouldWrite(ConsoleVerbosity.Minimal))
                {
                    RC.Write(ConsoleVerbosity.Minimal, ConsoleThemeColor.TitleText, " " + string.Format(Rpx.Strings.Compiler_Tools, Tools.Count.ToString()));
                    RC.Write(ConsoleVerbosity.Minimal, ConsoleThemeColor.SubText, " (");
                }

                StringBuilder ToolsString = new StringBuilder();

                bool firstMenu = true;

                foreach (KeyValuePair <string, string> tool in Tools)
                {
                    string toolName = tool.Key;
                    string asm      = tool.Value;
                    string path     = PackageHelper.MakeUriSafe(asm.Substring(asm.LastIndexOf("\\") + 1));

                    if (path != InitialAssemblyPath)
                    {
                        Dictionary <string, string> asmReplacements  = new Dictionary <string, string>();
                        Dictionary <string, string> toolReplacements = new Dictionary <string, string>();

                        string idStr = "a" + (asmId++).ToString();

                        asmReplacements.Add("[#Asm_IdStr#]", idStr);
                        asmReplacements.Add("[#Asm_Path#]", PackageHelper.MakeUriSafe(path));

                        AssemblyReplacements.Add(asmReplacements);

                        toolReplacements.Add("[#Tool_Name#]", toolName);
                        toolReplacements.Add("[#Tool_Asm#]", idStr);

                        ToolReplacements.Add(toolReplacements);

                        if (RC.ShouldWrite(ConsoleVerbosity.Normal))
                        {
                            RC.Write(ConsoleVerbosity.Normal, ConsoleThemeColor.SubText, " - " + toolName.PadRight(15, ' ') + " ");
                            RC.WriteLine(ConsoleVerbosity.Normal, ConsoleThemeColor.SubText2, "(" + path + ")");
                        }
                        else if (RC.ShouldWrite(ConsoleVerbosity.Minimal))
                        {
                            if (!firstMenu)
                            {
                                RC.Write(ConsoleVerbosity.Minimal, ConsoleThemeColor.SubText, ", ");
                            }

                            RC.Write(ConsoleVerbosity.Minimal, ConsoleThemeColor.SubText2, toolName);

                            firstMenu = false;
                        }

                        ToolsString.Append("\\n  " + toolName);
                    }
                }

                if (!RC.ShouldWrite(ConsoleVerbosity.Normal) && RC.ShouldWrite(ConsoleVerbosity.Minimal))
                {
                    RC.WriteLine(ConsoleVerbosity.Minimal, ConsoleThemeColor.SubText, ")");
                }

                replacements.Add("[#ToolsString#]", ToolsString.ToString());
            }

            #endregion

            replacements.Add("#InitialAssemblyPath#", PackageHelper.MakeUriSafe(InitialAssemblyPath));

            #endregion

            #region Rename the Output File If It Exits So It Can Be Rolled Back

            if (File.Exists(outputFile))
            {
                RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.TitleText, "\n" + Rpx.Strings.Compiler_BackupAsm);

                string name = new FileInfo(outputFile).Name;

                replacedFile = Application.UserAppDataPath + @"\" + Guid.NewGuid().GetHashCode().ToString() + "_" + name + ".InUse";

                RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.Text, " " + replacedFile);

                File.Move(outputFile, replacedFile);
            }

            #endregion

            #region Compile Assembly From Code Template

            RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.TitleText, "\n" + Rpx.Strings.Compiler_Compiling);
            RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.Text, string.Format(" {0}: {1}", Rpx.Strings.Compiler_Options, cp.CompilerOptions.Replace("/", "\n    /")));

            CodeFileBuilder builder = GetCodeFileBuilderFromResource("Rpx.Packing.Embedded.RpxWrapperSource.xml");

            Dictionary <string, List <Dictionary <string, string> > > ObjReplacements = new Dictionary <string, List <Dictionary <string, string> > >();

            ObjReplacements.Add("Assemblys", AssemblyReplacements);
            ObjReplacements.Add("Tools", ToolReplacements);

            string source = builder.BuildCodeFile(replacements, ObjReplacements, defines);

            // Compile standalone executable with input files embedded as resource
            CompilerResults cr = csc.CompileAssemblyFromSource(cp, source);

            // yell if compilation error
            if (cr.Errors.Count > 0)
            {
                if (replacedFile != null)
                {
                    File.Move(replacedFile, outputFile);
                    replacedFile = null;
                }

                string msg = string.Format(Rpx.Strings.Compiler_BuildErrors, cr.PathToAssembly);

                foreach (CompilerError ce in cr.Errors)
                {
                    msg += Environment.NewLine + ce.ToString();
                }

                if (!LogToConsole)
                {
                    MessageBox.Show(msg);
                }
                else
                {
                    RC.WriteError(02, string.Format(Rpx.Strings.Compiler_CompileFailed, cr.Errors.Count));
                    RC.WriteLine(ConsoleThemeColor.ErrorColor2, msg);

                    if (RC.Verbosity == ConsoleVerbosity.Debug)
                    {
                        if (RC.IsBuildMode == false)
                        {
                            RC.Write(ConsoleThemeColor.SubTextBad, new string(ConsoleChars.GetShade(ConsoleShade.Dim), RC.BufferWidth));
                        }
                        else
                        {
                            RC.Write(ConsoleThemeColor.SubTextBad, new string('*', RC.BufferWidth));
                        }

                        RC.WriteLine();
                        RC.WriteLine(ConsoleThemeColor.Text, source.Replace("\t", "  "));
                        RC.WriteLine();

                        if (RC.IsBuildMode == false)
                        {
                            RC.Write(ConsoleThemeColor.SubTextBad, new string(ConsoleChars.GetShade(ConsoleShade.Dim), RC.BufferWidth));
                        }
                        else
                        {
                            RC.Write(ConsoleThemeColor.SubTextBad, new string('*', RC.BufferWidth));
                        }
                    }
                }
            }
            else
            {
                if (RC.Verbosity == ConsoleVerbosity.Debug)
                {
                    RC.Write(ConsoleThemeColor.SubTextGood, new string(ConsoleChars.GetShade(ConsoleShade.Dim), RC.BufferWidth));
                    RC.WriteLine();
                    RC.WriteLine(ConsoleThemeColor.Text, source.Replace("\t", "  "));
                    RC.WriteLine();
                    RC.Write(ConsoleThemeColor.SubTextGood, new string(ConsoleChars.GetShade(ConsoleShade.Dim), RC.BufferWidth));
                }

                FinalFileSize = new FileInfo(outputFile).Length;

                if (replacedFile != null)
                {
                    File.SetAttributes(replacedFile, FileAttributes.Temporary);

                    string junkFile = replacedFile.Substring(0, replacedFile.Length - 6) + ".junk";

                    RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.TitleText, "\n" + Rpx.Strings.Compiler_JunkingBackupAsm);
                    RC.WriteLine(ConsoleVerbosity.Debug, ConsoleThemeColor.Text, " " + junkFile);

                    File.Move(replacedFile, junkFile);
                    replacedFile = null;
                }

                allGood = true;
            }

            #endregion

            #endregion

            return(allGood);
        }
示例#36
0
        public string EjecutarCodigo(string entrada)
        {
            CompilerParameters compilerParameters = new CompilerParameters();

            compilerParameters.GenerateInMemory      = true;
            compilerParameters.TreatWarningsAsErrors = false;
            compilerParameters.GenerateExecutable    = false;
            compilerParameters.CompilerOptions       = "/optimize";

            string[] references = { "System.dll" };
            compilerParameters.ReferencedAssemblies.AddRange(references);

            StringBuilder stringBuilder = new StringBuilder("");

            stringBuilder.Append("using System;\n");
            stringBuilder.Append("using System.Collections.Generic;\n");
            stringBuilder.Append("using System.Text;\n");
            stringBuilder.Append("using System.Threading.Tasks;\n");

            stringBuilder.Append("namespace Proyecto2{ \n");
            stringBuilder.Append("}\n");
            stringBuilder.Append(entrada);
            stringBuilder.Replace("static", "static public");
            stringBuilder.Replace("string[] args", "");

            CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider();
            CompilerResults    compilerResults    = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, stringBuilder.ToString());

            if (compilerResults.Errors.HasErrors)
            {
                string text = "Compile error: ";
                foreach (CompilerError compilerError in compilerResults.Errors)
                {
                    text += "rn" + compilerError.ToString();
                }
                throw new Exception(text);
            }

            Module     module     = compilerResults.CompiledAssembly.GetModules()[0];
            Type       type       = null;
            MethodInfo methodInfo = null;

            if (module != null)
            {
                type = module.GetType("MyProgram");
            }

            if (type != null)
            {
                methodInfo = type.GetMethod("Main");
            }

            if (methodInfo != null)
            {
                StringWriter stringWriter = new StringWriter();
                Console.SetOut(stringWriter);

                Console.WriteLine(methodInfo.Invoke(null, null));
                string consoleOutput = stringWriter.ToString();

                return(consoleOutput);
            }

            return("");
        }
示例#37
0
        static void Main(string[] args)
        {
            var optionsDef = new CommandLineOptions <CommandOptions>();

            string[] restArgs;
            var      options = optionsDef.Parse(args, out restArgs);

            if (restArgs.Length == 0)
            {
                Console.Error.WriteLine("スクリプトファイルを指定してください");
                Environment.Exit(1);
            }

            var scriptSource = Path.GetFullPath(restArgs[0]);
            var scriptArgs   = (restArgs.Length > 1) ? restArgs.Slice(1) : Array.Empty <string>();

#if false
            var scriptOptions = ScriptOptions.Default
                                .WithReferences(Assembly.GetExecutingAssembly())
                                .WithFilePath(scriptSource)
                                .WithSourceResolver(
                ScriptSourceResolver.Default
                .WithSearchPaths(
                    options.LibraryRoots.Select(path => Environment.ExpandEnvironmentVariables(path))));
            Script script;
            using (var reader = new StreamReader(scriptSource))
            {
                script = CSharpScript.Create(reader.ReadToEnd(), scriptOptions);
            }

            ScriptContext.ScriptPath      = scriptSource;
            ScriptContext.CommandLineArgs = scriptArgs;

            var diags = script.Compile();
            if (diags.Length > 0)
            {
                foreach (var diag in diags)
                {
                    Console.Error.WriteLine(diag);
                }
                Environment.Exit(1);
            }

            var result = script.RunAsync().Result;
            Console.WriteLine(result.ReturnValue);
#elif true
            var scriptPath = Path.GetFullPath("TestScript.csx");

            var compilationOption = new CSharpCompilationOptions(
                OutputKind.ConsoleApplication,
                optimizationLevel: OptimizationLevel.Release,
                sourceReferenceResolver: ScriptSourceResolver.Default
                .WithSearchPaths(Environment.CurrentDirectory),
                metadataReferenceResolver: ScriptPathResolver.Default
                .WithSearchPaths(
                    Environment.CurrentDirectory,
                    RuntimeEnvironment.GetRuntimeDirectory()));

            string text;
            using (var reader = new StreamReader(scriptPath))
            {
                text = reader.ReadToEnd();
            }
            var tree = SyntaxFactory.ParseSyntaxTree(
                text,
                new CSharpParseOptions(
                    kind: SourceCodeKind.Script,
                    documentationMode: DocumentationMode.None),
                scriptPath,
                Encoding.UTF8);

            var references = Assembly.GetExecutingAssembly()
                             .GetReferencedAssemblies()
                             .Select(name => MetadataReference.CreateFromFile(Assembly.ReflectionOnlyLoad(name.FullName).Location));

            var compilation = CSharpCompilation.Create(
                "test", new[] { tree }, references, compilationOption);

            var emitResult = compilation.Emit("test.exe", "test.pdb");
            if (!emitResult.Success)
            {
                foreach (var diag in emitResult.Diagnostics)
                {
                    Console.WriteLine(diag);
                }
            }
#else
            var sourceText = new StringBuilder();
            using (var reader = new StreamReader("TestScript.csx"))
            {
                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine().Trim();
                    if (line.StartsWith("#load"))
                    {
                    }
                    else if (line.StartsWith("#r"))
                    {
                    }
                    else
                    {
                        sourceText.AppendLine(line);
                    }
                }
            }

            var provider = new CSharpCodeProvider();
            var options  = new CompilerParameters()
            {
                GenerateExecutable = true,
                OutputAssembly     = "test.exe",
                CompilerOptions    = "/define:hogehoge",
            };
            var result = provider.CompileAssemblyFromSource(options, sourceText.ToString());
            if (result.Output.Count > 0)
            {
                foreach (var output in result.Output)
                {
                    Console.WriteLine(output);
                }
            }
            if (result.Errors.Count > 0)
            {
                foreach (var error in result.Errors)
                {
                    Console.WriteLine(error);
                }
            }
#endif
            Console.Read();
        }
示例#38
0
        public static bool CompileCSScripts(bool debug, bool cache, out Assembly assembly)
        {
            if (Core.IgnoreCache)
            {
                Console.Write("Scripts: Ignoring cached scripts, using Scripts.CS.dll...");
                if (!File.Exists("Scripts/Output/Scripts.CS.dll"))
                {
                    Console.Write(" error: file not found");
                    assembly = null;
                    return(true);
                }
                try
                {
                    assembly = Assembly.LoadFrom("Scripts/Output/Scripts.CS.dll");

                    if (!m_AdditionalReferences.Contains(assembly.Location))
                    {
                        m_AdditionalReferences.Add(assembly.Location);
                    }

                    Console.WriteLine("done");

                    return(true);
                }
                catch
                {
                }
            }

            Console.Write("Scripts: Compiling C# scripts...");
            string[] files = GetScripts("*.cs");

            if (files.Length == 0)
            {
                Console.WriteLine("no files found.");
                assembly = null;
                return(true);
            }

            if (File.Exists("Scripts/Output/Scripts.CS.dll"))
            {
                if (cache && File.Exists("Scripts/Output/Scripts.CS.hash"))
                {
                    try
                    {
                        byte[] hashCode = GetHashCode("Scripts/Output/Scripts.CS.dll", files, debug);

                        using (FileStream fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            using (BinaryReader bin = new BinaryReader(fs))
                            {
                                byte[] bytes = bin.ReadBytes(hashCode.Length);

                                if (bytes.Length == hashCode.Length)
                                {
                                    bool valid = true;

                                    for (int i = 0; i < bytes.Length; ++i)
                                    {
                                        if (bytes[i] != hashCode[i])
                                        {
                                            valid = false;
                                            break;
                                        }
                                    }

                                    if (valid)
                                    {
                                        assembly = Assembly.LoadFrom("Scripts/Output/Scripts.CS.dll");

                                        if (!m_AdditionalReferences.Contains(assembly.Location))
                                        {
                                            m_AdditionalReferences.Add(assembly.Location);
                                        }

                                        Console.WriteLine("done (cached)");

                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                    catch
                    {
                    }
                }
            }

            DeleteFiles("Scripts.CS*.dll");

#if Framework_3_5
            using (CSharpCodeProvider provider = new CSharpCodeProvider(new Dictionary <string, string>()
            {
                { "CompilerVersion", "v3.5" }
            }))
#else
            using (CSharpCodeProvider provider = new CSharpCodeProvider())
#endif
            {
                string path = GetUnusedPath("Scripts.CS");

                CompilerParameters parms = new CompilerParameters(GetReferenceAssemblies(), path, debug);

                string options = GetCompilerOptions(debug);

                if (options != null)
                {
                    parms.CompilerOptions = options;
                }

                if (Core.HaltOnWarning)
                {
                    parms.WarningLevel = 4;
                }

#if !MONO
                CompilerResults results = provider.CompileAssemblyFromFile(parms, files);
#else
                parms.CompilerOptions = String.Format("{0} /nowarn:169,219,414 /recurse:Scripts/*.cs", parms.CompilerOptions);
                CompilerResults results = provider.CompileAssemblyFromFile(parms, "");
#endif
                m_AdditionalReferences.Add(path);

                Display(results);

#if !MONO
                if (results.Errors.Count > 0)
                {
                    assembly = null;
                    return(false);
                }
#else
                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError err in results.Errors)
                    {
                        if (!err.IsWarning)
                        {
                            assembly = null;
                            return(false);
                        }
                    }
                }
#endif


                if (cache && Path.GetFileName(path) == "Scripts.CS.dll")
                {
                    try
                    {
                        byte[] hashCode = GetHashCode(path, files, debug);

                        using (FileStream fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            using (BinaryWriter bin = new BinaryWriter(fs))
                            {
                                bin.Write(hashCode, 0, hashCode.Length);
                            }
                        }
                    }
                    catch
                    {
                    }
                }

                assembly = results.CompiledAssembly;
                return(true);
            }
        }
        private bool processProxy()
        {
            string targetFilename = string.Format(CultureInfo.InvariantCulture, "{0}.cs", Path.Combine(_prj.ProjectFolder, textBoxSourceFilename.Text));
            string configFilename = string.Format(CultureInfo.InvariantCulture, "{0}.config", Path.Combine(_prj.ProjectFolder, textBoxSourceFilename.Text));

            if (!System.IO.File.Exists(targetFilename))
            {
                MessageBox.Show(this, string.Format(System.Globalization.CultureInfo.InvariantCulture, "Proxy file not generated: [{0}].", targetFilename), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }
            string dllFilename = string.Format(CultureInfo.InvariantCulture, "{0}.dll", Path.Combine(_prj.ProjectFolder, textBoxSourceFilename.Text));

            if (System.IO.File.Exists(dllFilename))
            {
                File.Delete(dllFilename);
            }
            string targetFilename2 = string.Format(CultureInfo.InvariantCulture, "{0}2.cs", Path.Combine(_prj.ProjectFolder, textBoxSourceFilename.Text));

            if (File.Exists(targetFilename2))
            {
                File.Delete(targetFilename2);
            }
            string       className = null;
            StreamReader sr        = new StreamReader(targetFilename);

            while (!sr.EndOfStream && string.IsNullOrEmpty(className))
            {
                string line = sr.ReadLine();
                if (!string.IsNullOrEmpty(line))
                {
                    if (line.StartsWith("public partial class ", StringComparison.Ordinal))
                    {
                        int n = line.IndexOf(':');
                        if (n > 0)
                        {
                            string s = line.Substring(0, n).Trim();
                            n         = s.LastIndexOf(' ');
                            className = s.Substring(n).Trim();
                        }
                    }
                }
            }
            sr.Close();
            if (string.IsNullOrEmpty(className))
            {
                throw new DesignerException("WCF proxy class not found in {0}", targetFilename);
            }
            StreamWriter sw    = new StreamWriter(targetFilename2);
            string       code2 = Resources.CodeFileWcfProxy;

            code2 = code2.Replace("proxyName", className);
            sw.Write(code2);
            sw.Close();
            CompilerParameters cp = new CompilerParameters();
            StringCollection   sc = new StringCollection();
            string             sLoc;

            sLoc = typeof(System.ServiceModel.ServiceHost).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(Uri).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(Process).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(System.Xml.Serialization.IXmlSerializable).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(System.ComponentModel.AsyncOperation).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(System.Threading.SendOrPostCallback).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(System.Web.Services.Protocols.InvokeCompletedEventArgs).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(System.Data.DataSet).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(System.Windows.Forms.Form).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(UITypeEditor).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            sLoc = typeof(IWindowsFormsEditorService).Assembly.Location;
            if (!sc.Contains(sLoc))
            {
                sc.Add(sLoc);
            }
            foreach (string loc in sc)
            {
                cp.ReferencedAssemblies.Add(loc);
            }
            cp.CompilerOptions         = "/t:library";
            cp.GenerateExecutable      = false;
            cp.GenerateInMemory        = false;
            cp.IncludeDebugInformation = true;
            cp.OutputAssembly          = dllFilename;
            //
            string pdbFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(dllFilename), System.IO.Path.GetFileNameWithoutExtension(dllFilename)) + ".pdb";

            if (System.IO.File.Exists(pdbFile))
            {
                try
                {
                    System.IO.File.Delete(pdbFile);
                }
                catch (Exception err0)
                {
                    MessageBox.Show(this, string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                        "{0}\r\nCannot overwrite {1}. Please close Limnor Studio and all programs that may use this file. Then manually delete this file", err0.Message, pdbFile),
                                    this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                    return(false);
                }
            }
            //
            string[] sourceFiles = new string[] { targetFilename, targetFilename2 };
            //
            //use C# code provider
            CSharpCodeProvider ccp = new CSharpCodeProvider(new Dictionary <string, string>()
            {
                { "CompilerVersion", "v3.5" }
            });

            CompilerResults cr = ccp.CompileAssemblyFromFile(cp, sourceFiles);

            //
            if (cr.Errors.HasErrors)
            {
                FormStringList.ShowErrors("Error compiling the web service proxy", this, cr.Errors);
                return(false);
            }
            if (_prj != null)
            {
                string appDllFilename = string.Format(CultureInfo.InvariantCulture, "{0}.dll",
                                                      Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), textBoxSourceFilename.Text));
                List <WcfServiceProxy> proxyList = _prj.GetTypedProjectData <List <WcfServiceProxy> >();
                if (proxyList == null)
                {
                    proxyList = new List <WcfServiceProxy>();
                    _prj.SetTypedProjectData <List <WcfServiceProxy> >(proxyList);
                }
                try
                {
                    File.Copy(dllFilename, appDllFilename, true);
                }
                catch (Exception err)
                {
                    MessageBox.Show(this, string.Format(CultureInfo.InvariantCulture, "Error copying [{0}] to [{1}]. You may close Limnor Studio and manually copy the file. \r\n{2}",
                                                        dllFilename, appDllFilename, err.Message), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Assembly a = Assembly.LoadFile(appDllFilename);
                _proxy = new WcfServiceProxy(Path.GetFileName(dllFilename), a, textBoxServiceUrl.Text,
                                             string.Format(CultureInfo.InvariantCulture, "{0}.config", textBoxSourceFilename.Text));
                proxyList.Add(_proxy);
                MessageBox.Show(this, "The WCF Remoting Service proxy has been added to the Toolbox", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            return(true);
        }
        public void PopulateFromType(Type type)
        {
            this.Clear();
            if (type == null)
            {
                return;
            }
            var compiler = new CSharpCodeProvider();
            MethodAutocompleteItem last = null;

            if (type.IsEnum)
            {
                AddRange(type.GetEnumNames().Select(s => new MethodAutocompleteItem(s)
                {
                    ImageIndex = TabularIcons.ICON_ENUM
                }));
                Add(new MethodAutocompleteItem("HasFlag")
                {
                    ToolTipTitle = "bool Enum.HasFlag(Enum flag)",
                    ToolTipText  = "Determines whether one or more bits are set in the bit mask.",
                    ImageIndex   = TabularIcons.ICON_METHOD
                });
                // TODO: Add our own extensions to the "Types" enum?
                return;
            }

            //return methods
            foreach (var mi in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                     .Where(m => !m.IsSpecialName && m.DeclaringType != typeof(object)).AsEnumerable())
            {
                if (mi.GetCustomAttribute <IntelliSenseAttribute>() == null)
                {
                    continue;
                }
                switch (mi.Name)
                {
                case "GetEnumerator":
                    continue;
                }

                // Overloaded methods only show up once, but let's display all overrides in the tooltip.
                var    methodName = mi.Name;
                string returnTypeName;
                if (mi.ReturnType == typeof(void))
                {
                    returnTypeName = "void";
                }
                else
                {
                    var returnType = new CodeTypeReference(mi.ReturnType);
                    returnTypeName = compiler.GetTypeOutput(returnType).Replace("TabularEditor.UI.UISelectionList", "IEnumerable").Replace("TabularEditor.TOMWrapper.", "");
                }

                var methodSyntax = returnTypeName + " " + mi.Name + "(" + string.Join(", ", mi.GetParameters().Select(p => p.Name).ToArray()) + ")";

                if (last?.Text == methodName)
                {
                    last.ToolTipText = methodSyntax + Environment.NewLine + last.ToolTipText;
                }
                else
                {
                    last = new MethodAutocompleteItemParen(methodName)
                    {
                        ToolTipTitle = methodSyntax,
                        ToolTipText  = mi.GetCustomAttribute <IntelliSenseAttribute>()?.Description ?? string.Empty,
                        ImageIndex   = TabularIcons.ICON_METHOD
                    };
                    Add(last);
                }
            }

            // Type derives from IEnumerable, so let's add a few select LINQ methods:
            if (type.GetInterface("IEnumerable") != null)
            {
                Add(new MethodAutocompleteItemParen("Select")
                {
                    ToolTipTitle = "object Select(selector)",
                    ToolTipText  = "Projects each item of the collection into something else using a lambda expression.\nExample: .Select(Measure => Measure.Table)",
                    ImageIndex   = TabularIcons.ICON_EXMETHOD
                });
                Add(new MethodAutocompleteItemParen("Any")
                {
                    ToolTipTitle = "bool Any(predicate)",
                    ToolTipText  = "Determines if the collection contains any items. Specify a lambda expression to determine if the collection contains any items satisfying the given condition.\nExample: .Any(Measure => Measure.Description == \"\")",
                    ImageIndex   = TabularIcons.ICON_EXMETHOD
                });
                Add(new MethodAutocompleteItemParen("All")
                {
                    ToolTipTitle = "bool All(predicate)",
                    ToolTipText  = "Determines if all items in the collection satisfies the given condition.\nExample: .All(Measure => Measure.Description == \"\")",
                    ImageIndex   = TabularIcons.ICON_EXMETHOD
                });
                Add(new MethodAutocompleteItemParen("First")
                {
                    ToolTipTitle = type.Name + " First(predicate)",
                    ToolTipText  = "Returns the first element of the sequence, satisfying the (optionally) specified condition.",
                    ImageIndex   = TabularIcons.ICON_EXMETHOD
                });
                Add(new MethodAutocompleteItemParen("Last")
                {
                    ToolTipTitle = type.Name + " Last(predicate)",
                    ToolTipText  = "Returns the last element of the sequency, satisfying the (optionally) specified condition.",
                    ImageIndex   = TabularIcons.ICON_EXMETHOD
                });
                Add(new MethodAutocompleteItemParen("Take")
                {
                    ToolTipTitle = "IEnumerable<" + type.Name + "> Take(count)",
                    ToolTipText  = "Returns a specified number of contiguous elements from the start of a sequence.",
                    ImageIndex   = TabularIcons.ICON_EXMETHOD
                });
                Add(new MethodAutocompleteItemParen("Skip")
                {
                    ToolTipTitle = "IEnumerable<" + type.Name + "> Skip(count)",
                    ToolTipText  = "Bypasses a specified number of elements in a sequence and then returns the remaining elements.",
                    ImageIndex   = TabularIcons.ICON_EXMETHOD
                });

                // Below adds all LINQ methods, which may be overkill:

                /*foreach (var method in typeof(System.Linq.Enumerable)
                 *  .GetMethods(BindingFlags.Static | BindingFlags.Public).Select(m => m.Name).Distinct())
                 * {
                 *  yield return new MethodAutocompleteItem(method + "()")
                 *  {
                 *      ToolTipTitle = method,
                 *      ImageIndex = TabularIcons.ICON_METHOD
                 *  };
                 * }*/
            }

            //return static properties of the class
            foreach (var pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (pi.GetCustomAttribute <IntelliSenseAttribute>() == null &&
                    pi.GetCustomAttribute <DisplayNameAttribute>() == null &&
                    pi.GetCustomAttribute <BrowsableAttribute>() == null)
                {
                    continue;
                }
                var propType     = new CodeTypeReference(pi.PropertyType);
                var propTypeName = compiler.GetTypeOutput(propType).Replace("TabularEditor.UI.UISelectionList", "IEnumerable").Replace("TabularEditor.TOMWrapper.", "");

                var canRead  = pi.CanRead && pi.GetMethod.IsPublic;
                var canWrite = pi.CanWrite && pi.SetMethod.IsPublic;

                Add(new MethodAutocompleteItem(pi.Name)
                {
                    ToolTipTitle = string.Format("{0} {1} {{ {2}}}", propTypeName, pi.Name, (canRead ? "get; " : "") + (canWrite ? "set; " : "")),
                    ToolTipText  = pi.GetCustomAttribute <IntelliSenseAttribute>()?.Description ?? string.Empty,
                    ImageIndex   = TabularIcons.ICON_PROPERTY
                });
            }

            this.Sort((a, b) => a.Text.CompareTo(b.Text));
        }
 private void OnEnable()
 {
     _csharpCodeProvider = new CSharpCodeProvider();
     Entity      = null;
     _methodName = "<None>";
 }
示例#42
0
        private Assembly CompileCode(string code, string name)
        {
            CSharpCodeProvider csProvider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = false;
            parameters.OutputAssembly = "scripts\\" + name + ".dll";
            //TODO: Custom assembly list
            parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

            CompilerResults result;
            result = csProvider.CompileAssemblyFromSource(parameters, code);
            if (result.Errors.HasErrors)
            {
                foreach (CompilerError e in result.Errors)
                {
                    Messages.Add(name + ": " + (e.IsWarning == true ? "WARNING: " : "ERROR: ") + e.ErrorText + " -- Line: " + e.Line.ToString());
                }
                return null;
            }
            return result.CompiledAssembly;
        }
示例#43
0
        public static Byte[] CompileDll(String randString)
        {
            var options = new Dictionary <string, string>();// { { "CompilerVersion", "v3.5" } };// { { "CompilerVersion", "v4.0" } };
            CSharpCodeProvider codeProvider = new CSharpCodeProvider(options);
            //CodeDomProvider codeProvider2 = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            CompilerParameters compilerParameters = new CompilerParameters
            {
                GenerateExecutable = false,
#if DEBUG
                IncludeDebugInformation = true,
#endif
                GenerateInMemory = false,
                OutputAssembly   = randString + ".dll",
                CompilerOptions  = "/unsafe"
            };

            compilerParameters.ReferencedAssemblies.Clear();
            //compilerParameters.ReferencedAssemblies.Add("mscorlib.dll");
            var dlls = Directory.GetFiles(UnityDllPath, "*.dll", SearchOption.AllDirectories);

            foreach (var dll in dlls)
            {
                if (!dll.Contains("mscorlib"))
                {
                    compilerParameters.ReferencedAssemblies.Add(dll);
                }
            }

            /*compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "System.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "System.Core.dll"); // not sure which to use... prefer Linq...
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "netstandard.dll");
             * //compilerParameters.ReferencedAssemblies.Add(gamePath + "System.Drawing.dll");
             * //compilerParameters.ReferencedAssemblies.Add(gamePath + "System.Windows.Forms.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "Assembly-CSharp.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "UnityEngine.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "UnityEngine.UI.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "UnityEngine.UIElementsModule.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "UnityEngine.UIModule.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "UnityEngine.Networking.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "UnityEngine.CoreModule.dll");
             * compilerParameters.ReferencedAssemblies.Add(UnityDllPath + "UnityEngine.IMGUIModule.dll");
             * //compilerParameters.ReferencedAssemblies.Add(gamePath + "TextMeshPro-1.0.55.2017.1.0b11.dll");*/

            string[] sourceFiles;
            if (Directory.Exists($@"..\..\..\..\{ProjName}"))
            {
                sourceFiles = Directory.GetFiles($@"..\..\..\..\{ProjName}", "*.cs", SearchOption.AllDirectories);
            }
            else
            {
                sourceFiles = Directory.GetFiles($@"{ProjName}-master\{ProjName}\", "*.cs", SearchOption.AllDirectories);
            }
            var sources = new List <String>();

            foreach (var sourceFile in sourceFiles)
            {
                if (sourceFile.Contains(@"obj\\"))
                {
                    continue;
                }
                var source = File.ReadAllText(sourceFile);
                source = source.Replace(ProjName, randString);
                sources.Add(source);
            }
            //var result = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFiles);
            var result = codeProvider.CompileAssemblyFromSource(compilerParameters, sources.ToArray());

            if (result.Errors.Count > 0)
            {
                var sb = new StringBuilder();
                foreach (CompilerError error in result.Errors)
                {
                    sb.AppendLine(error.ToString());
                }
                throw new Exception(sb.ToString());
            }
            var dllBytes = File.ReadAllBytes(randString + ".dll");

            File.Delete(randString + ".dll");
            if (File.Exists(randString + ".pdb"))
            {
                File.Delete(randString + ".pdb");
            }
            return(dllBytes);

            /*using (MemoryStream stream = new MemoryStream())
             * {
             *  var formatter = new BinaryFormatter();
             *  formatter.Serialize(stream, result.CompiledAssembly);
             *  return stream.ToArray();
             * }*/
        }
示例#44
0
 public Interpreter()
 {
     AddNamespace("System");
     AddNamespace("System.Collections");
     AddReference("system.dll");
     SetValue("interpreter",this);
     SetValue("_",this);
     Utils.interpreter = this;
     AddReference(FullExecutablePath());
     //compiler = prov.CreateCompiler();
     compiler = prov;
 }
示例#45
0
 public RazorEngine(CSharpCodeProvider codeProvider) : base(codeProvider)
 {
 }
示例#46
0
        public static byte[] Pack(string outputPath, string inputPath, string encryptKey, bool erasePE, bool antiDebug)
        {
            byte[] assembly = File.ReadAllBytes(inputPath);
            string tmpfile;

            do
            {
                tmpfile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".exe";
            } while (System.IO.File.Exists(tmpfile));
            if (erasePE || antiDebug)
            {
                ModuleDefMD module = ModuleDefMD.Load(assembly);
                if (erasePE)
                {
                    InjectEraseMethod(module);
                }
                if (antiDebug)
                {
                    InjectAntiDebugMethod(module);
                }

                foreach (TypeDef type in module.GetTypes())
                {
                    if (type.IsGlobalModuleType)
                    {
                        continue;
                    }
                    foreach (MethodDef method in type.Methods)
                    {
                        if (!method.HasBody)
                        {
                            continue;
                        }
                        if (method.Name.Contains("Main"))
                        {
                            if (antiDebug)
                            {
                                method.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, debuggerMethod));
                            }
                            if (erasePE)
                            {
                                method.Body.Instructions.Insert(method.Body.Instructions.Count - 2, Instruction.Create(OpCodes.Call, eraseMethod));
                            }
                            //nop, ret
                        }
                    }
                }

                var opts = new ModuleWriterOptions(module);
                opts.Logger = DummyLogger.NoThrowInstance;
                module.Write(tmpfile, opts);
            }
            byte[] saltBytes = new byte[] { 5, 10, 15, 20, 25, 30, 35, 40 };
            byte[] fileBytes = null;
            if (erasePE)
            {
                fileBytes = File.ReadAllBytes(tmpfile);
            }
            else
            {
                fileBytes = assembly;
            }
            using MemoryStream memoryStream = new MemoryStream();
            RijndaelManaged aes = new RijndaelManaged();

            aes.KeySize   = 128;
            aes.BlockSize = 128;
            var key = new Rfc2898DeriveBytes(encryptKey, saltBytes, 1000);

            aes.Key  = key.GetBytes(aes.KeySize / 8);
            aes.IV   = key.GetBytes(aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;
            using var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
            cryptoStream.Write(fileBytes, 0, fileBytes.Length);
            cryptoStream.Close();
            fileBytes = memoryStream.ToArray();
            string compiledAssembly = Convert.ToBase64String(memoryStream.ToArray());
            string code             = CSharPacker.Properties.Resources.stub;

            code = code.Replace("%ASSEMBLY%", compiledAssembly);
            code = code.Replace("%KEY%", encryptKey);
            Assembly orig            = Assembly.Load(assembly);
            var      providerOptions = new Dictionary <string, string>();

            providerOptions.Add("CompilerVersion", "v4.0");
            CSharpCodeProvider codeProvider = new CSharpCodeProvider(providerOptions);
            CompilerParameters parameters   = new CompilerParameters();

            parameters.CompilerOptions    = "/target:winexe";
            parameters.GenerateExecutable = true;
            AssemblyName[] whitelisted = orig.GetReferencedAssemblies();
            foreach (AssemblyName name in whitelisted)
            {
                if (name.Name.Contains("System.") || name.Name.Contains("Microsoft."))
                {
                    parameters.ReferencedAssemblies.Add(name.Name + ".dll");
                }
            }
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code);
            FileStream      fs      = results.CompiledAssembly.GetFiles()[0];

            using (MemoryStream stream = new MemoryStream())
            {
                fs.CopyTo(stream);
                return(stream.ToArray());
            }
        }
示例#47
0
        public static void GenerateXObjects(
            XmlSchemaSet set,
            string csFileName,
            string configFileName,
            string assemblyName,
            bool xmlSerializable,
            bool nameMangler2)
        {
            var configSettings = new LinqToXsdSettings(nameMangler2);

            if (configFileName != null)
            {
                configSettings.Load(configFileName);
            }

            configSettings.EnableServiceReference = xmlSerializable;
            var xsdConverter  = new XsdToTypesConverter(configSettings);
            var mapping       = xsdConverter.GenerateMapping(set);
            var codeGenerator = new CodeDomTypesGenerator(configSettings);
            var ccu           = new CodeCompileUnit();

            foreach (var codeNs in codeGenerator.GenerateTypes(mapping))
            {
                ccu.Namespaces.Add(codeNs);
            }

            //Write to file
            var provider = new CSharpCodeProvider();

            if (!string.IsNullOrEmpty(csFileName))
            {
                using (var update =
                           new Update(csFileName, Encoding.UTF8))
                {
                    provider.GenerateCodeFromCompileUnit(
                        ccu,
                        update.Writer,
                        new CodeGeneratorOptions());
                }

                PrintMessage(csFileName);
            }

            if (assemblyName != string.Empty)
            {
                var options = new CompilerParameters
                {
                    OutputAssembly          = assemblyName,
                    IncludeDebugInformation = true,
                    TreatWarningsAsErrors   = true
                };
                options.TempFiles.KeepFiles = true;
                {
                    var r = options.ReferencedAssemblies;
                    r.Add(value: "System.dll");
                    r.Add(value: "System.Core.dll");
                    r.Add(value: "System.Xml.dll");
                    r.Add(value: "System.Xml.Linq.dll");
                    r.Add(value: "Xml.Schema.Linq.dll");
                }
                var results = provider.CompileAssemblyFromDom(options, ccu);
                if (results.Errors.Count > 0)
                {
                    PrintErrorMessage(e: "compilation error(s): ");
                    for (int i = 0; i < results.Errors.Count; i++)
                    {
                        PrintErrorMessage(results.Errors[i].ToString());
                    }

                    throw new Exception(message: "compilation error(s)");
                }

                PrintMessage(
                    "Generated Assembly: " +
                    results.CompiledAssembly);
            }
        }
示例#48
0
        // CompileExecutable method
        public static CompilerResults CompileExecutable(string[] Code, string Output, string Icon, string[] AssemblyInfo, string[] EmbeddedFiles, bool Uac, params string[] References)
        {
            // Create new instance & add references
            var parameters = new CompilerParameters(References, Output)
            {
                // Generate executable
                GenerateExecutable = true,

                // Dont include debug info
                IncludeDebugInformation = false
            };

            // Set replace parts array
            string[] AsmInfoReplace = new string[] { "%TITLE%", "%DESCRIPTION%", "%COMPANY%", "%PRODUCT%", "%COPYRIGHT%", "%TRADEMARK%", "1.0.0.0" };

            // Loop though and replace parts
            for (int i = 0; i < AsmInfoReplace.Length; i++)
            {
                // Replace parts
                FileSources.AssemblyInfo = FileSources.AssemblyInfo.Replace(AsmInfoReplace[i], AssemblyInfo[i]);
            }

            // Check if file exists
            if (!File.Exists("AssemblyInfo.cs"))
            {
                // Create AssemblyInfo.cs file
                File.WriteAllText("AssemblyInfo.cs", FileSources.AssemblyInfo);
            }

            // Set compiler parameters
            parameters.CompilerOptions = "/target:winexe /optimize AssemblyInfo.cs";

            // Check if user wants an icon
            if (Icon != null)
            {
                // Set icon
                parameters.CompilerOptions += @" /win32icon:" + "\"" + Icon + "\"";
            }

            // Check if user wants to embed files
            if (EmbeddedFiles != null)
            {
                // Loop though and embed all files spesificyed by the user
                for (int i = 0; i < EmbeddedFiles.Length; i++)
                {
                    // Embed files
                    parameters.EmbeddedResources.Add(EmbeddedFiles[i]);
                }
            }

            // Check if user wants Uac
            if (Uac == true)
            {
                // Check if file exists
                if (!File.Exists("app.manifest"))
                {
                    // Create app.manifest file
                    File.WriteAllText("app.manifest", FileSources.ManifestFile);
                }

                // Add manifest file to the compiler parameters
                parameters.CompilerOptions += @" /win32manifest:" + "app.manifest";
            }

            // Create new instance
            using (var provider = new CSharpCodeProvider())
            {
                // Check if there were any errors during compilation
                if (provider.CompileAssemblyFromSource(parameters, Code).Errors.Count == 0)
                {
                    MessageBox.Show("build successful");
                }
                else
                {
                    MessageBox.Show("Error compiling executable");
                }
            }

            // Delete AssemblyInfo.cs
            File.Delete("AssemblyInfo.cs");

            // Check if app.manifest exists
            if (File.Exists("app.manifest"))
            {
                // Delete app.manifest
                File.Delete("app.manifest");
            }

            // Return null
            return(null);
        }
示例#49
0
        public Program(params string[] args)
        {
            XmlSchemas xsds = new XmlSchemas();
            var        i    = 0;

            while (!args[i].StartsWith("/o:") || i >= args.Length)
            {
                xsds.Add(GetSchema(args[i]));
                i++;
            }

            var output = string.Empty;

            if (args[i].StartsWith("/o:"))
            {
                output = args[i].Substring(3);
            }

            xsds.Compile(null, true);
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds);

            // create the codedom
            var codeNamespace = new CodeNamespace("QbSync.QbXml.Objects");

            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            CodeCompileUnit compileUnit = new CodeCompileUnit();

            compileUnit.Namespaces.Add(codeNamespace);
            var codeExporter = new XmlCodeExporter(codeNamespace, compileUnit, CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateOrder);

            foreach (XmlSchema xsd in xsds)
            {
                ArrayList maps = new ArrayList();
                foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values)
                {
                    maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName));
                }
                foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
                {
                    maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName));
                }
                foreach (XmlTypeMapping map in maps)
                {
                    codeExporter.ExportTypeMapping(map);
                }
            }

            var typeEnhancer = new TypeEnhancer(codeNamespace, xsds);

            typeEnhancer.Enhance();

            // Add a comment at the top of the file
            var x = fileComment.Split('\n').Select(m => new CodeCommentStatement(m)).ToArray();

            codeNamespace.Comments.AddRange(x);

            // Check for invalid characters in identifiers
            CodeGenerator.ValidateIdentifiers(codeNamespace);

            // output the C# code
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();

            using (StringWriter writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions
                {
                    BlankLinesBetweenMembers = true,
                    BracingStyle             = "C",
                    ElseOnClosing            = true,
                    IndentString             = "    "
                });

                string content = writer.GetStringBuilder().ToString();
                if (string.IsNullOrEmpty(output))
                {
                    Console.WriteLine(content);
                    Console.ReadLine();
                }
                else
                {
                    File.WriteAllText(output, content);
                }
            }
        }
示例#50
0
        public static CompilerResults CompileCSharp(string sourceFileName, CompilerOptions flags = CompilerOptions.UseDebug, string outputFileName = null)
        {
            List <string> sourceFileNames = new List <string> {
                sourceFileName
            };

            foreach (Match match in Regex.Matches(File.ReadAllText(sourceFileName), @"#include ""([\w\d./]+)"""))
            {
                sourceFileNames.Add(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(sourceFileName), match.Groups[1].Value)));
            }

            var preprocessorSymbols = GetPreprocessorSymbols(flags);

            if (flags.HasFlag(CompilerOptions.UseRoslyn))
            {
                var parseOptions = new CSharpParseOptions(
                    preprocessorSymbols: preprocessorSymbols.ToArray(),
                    languageVersion: Microsoft.CodeAnalysis.CSharp.LanguageVersion.CSharp8
                    );
                var syntaxTrees = sourceFileNames.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, path: f));
                var references  = defaultReferences.Value;
                if (flags.HasFlag(CompilerOptions.ReferenceVisualBasic))
                {
                    references = references.Concat(visualBasic.Value);
                }
                var compilation = CSharpCompilation.Create(Path.GetFileNameWithoutExtension(sourceFileName),
                                                           syntaxTrees, references,
                                                           new CSharpCompilationOptions(
                                                               flags.HasFlag(CompilerOptions.Library) ? OutputKind.DynamicallyLinkedLibrary : OutputKind.ConsoleApplication,
                                                               platform: flags.HasFlag(CompilerOptions.Force32Bit) ? Platform.X86 : Platform.AnyCpu,
                                                               optimizationLevel: flags.HasFlag(CompilerOptions.Optimize) ? OptimizationLevel.Release : OptimizationLevel.Debug,
                                                               allowUnsafe: true,
                                                               deterministic: true
                                                               ));
                CompilerResults results = new CompilerResults(new TempFileCollection());
                results.PathToAssembly = outputFileName ?? Path.GetTempFileName();
                var emitResult = compilation.Emit(results.PathToAssembly);
                if (!emitResult.Success)
                {
                    StringBuilder b = new StringBuilder("Compiler error:");
                    foreach (var diag in emitResult.Diagnostics)
                    {
                        b.AppendLine(diag.ToString());
                    }
                    throw new Exception(b.ToString());
                }
                return(results);
            }
            else if (flags.HasFlag(CompilerOptions.UseMcs))
            {
                CompilerResults results = new CompilerResults(new TempFileCollection());
                results.PathToAssembly = outputFileName ?? Path.GetTempFileName();
                string testBasePath = RoundtripAssembly.TestDir;
                if (!Directory.Exists(testBasePath))
                {
                    Assert.Ignore($"Compilation with mcs ignored: test directory '{testBasePath}' needs to be checked out separately." + Environment.NewLine +
                                  $"git clone https://github.com/icsharpcode/ILSpy-tests \"{testBasePath}\"");
                }
                string mcsPath      = Path.Combine(testBasePath, @"mcs\2.6.4\bin\gmcs.bat");
                string otherOptions = " -unsafe -o" + (flags.HasFlag(CompilerOptions.Optimize) ? "+ " : "- ");

                if (flags.HasFlag(CompilerOptions.Library))
                {
                    otherOptions += "-t:library ";
                }
                else
                {
                    otherOptions += "-t:exe ";
                }

                if (flags.HasFlag(CompilerOptions.UseDebug))
                {
                    otherOptions += "-g ";
                }

                if (flags.HasFlag(CompilerOptions.Force32Bit))
                {
                    otherOptions += "-platform:x86 ";
                }
                else
                {
                    otherOptions += "-platform:anycpu ";
                }
                if (preprocessorSymbols.Count > 0)
                {
                    otherOptions += " \"-d:" + string.Join(";", preprocessorSymbols) + "\" ";
                }

                ProcessStartInfo info = new ProcessStartInfo(mcsPath);
                info.Arguments              = $"{otherOptions}-out:\"{Path.GetFullPath(results.PathToAssembly)}\" {string.Join(" ", sourceFileNames.Select(fn => '"' + Path.GetFullPath(fn) + '"'))}";
                info.RedirectStandardError  = true;
                info.RedirectStandardOutput = true;
                info.UseShellExecute        = false;

                Console.WriteLine($"\"{info.FileName}\" {info.Arguments}");

                Process process = Process.Start(info);

                var outputTask = process.StandardOutput.ReadToEndAsync();
                var errorTask  = process.StandardError.ReadToEndAsync();

                Task.WaitAll(outputTask, errorTask);
                process.WaitForExit();

                Console.WriteLine("output: " + outputTask.Result);
                Console.WriteLine("errors: " + errorTask.Result);
                Assert.AreEqual(0, process.ExitCode, "mcs failed");
                return(results);
            }
            else
            {
                var provider = new CSharpCodeProvider(new Dictionary <string, string> {
                    { "CompilerVersion", "v4.0" }
                });
                CompilerParameters options = new CompilerParameters();
                options.GenerateExecutable = !flags.HasFlag(CompilerOptions.Library);
                options.CompilerOptions    = "/unsafe /o" + (flags.HasFlag(CompilerOptions.Optimize) ? "+" : "-");
                options.CompilerOptions   += (flags.HasFlag(CompilerOptions.UseDebug) ? " /debug" : "");
                options.CompilerOptions   += (flags.HasFlag(CompilerOptions.Force32Bit) ? " /platform:anycpu32bitpreferred" : "");
                if (preprocessorSymbols.Count > 0)
                {
                    options.CompilerOptions += " /d:" + string.Join(";", preprocessorSymbols);
                }
                if (outputFileName != null)
                {
                    options.OutputAssembly = outputFileName;
                }

                options.ReferencedAssemblies.Add("System.dll");
                options.ReferencedAssemblies.Add("System.Core.dll");
                options.ReferencedAssemblies.Add("System.Xml.dll");
                options.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
                if (flags.HasFlag(CompilerOptions.ReferenceVisualBasic))
                {
                    options.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
                }
                CompilerResults results = provider.CompileAssemblyFromFile(options, sourceFileNames.ToArray());
                if (results.Errors.Cast <CompilerError>().Any(e => !e.IsWarning))
                {
                    StringBuilder b = new StringBuilder("Compiler error:");
                    foreach (var error in results.Errors)
                    {
                        b.AppendLine(error.ToString());
                    }
                    throw new Exception(b.ToString());
                }
                return(results);
            }
        }
示例#51
0
        private void Generate()
        {
            // check data...
            SetStatusBar("Checking data");
            Application.DoEvents();
            this.config.CheckData();

            // Build Xsd path & file name and take care of instances where
            // '\' is missing from path and where path is empty.
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(this.config.XsdExePath.TrimEnd('\\'));
            if (sb.Length > 0)
            {
                sb.Append(@"\");
            }
            sb.Append("xsd.exe");

            // call xsd.exe
            ProcessStartInfo info = new ProcessStartInfo(sb.ToString());

            Application.DoEvents();
            info.UseShellExecute = false;
            info.Arguments       = String.Format(
                "\"{0}\" /c /n:{1}",
                this.config.XsdFile,
                this.config.OutputNamespace
                );

            SetStatusBar("Launching Xsd.exe");
            Application.DoEvents();
            Process process = Process.Start(info);

            process.WaitForExit();

            if (process.ExitCode != 0)
            {
                throw new Exception("Xsd.exe failed");
            }

            // load and compile generated file
            string[] namePieces = this.config.XsdFile.Split('.', '/', '\\');
            string   fileName   = (namePieces[namePieces.Length - 2] + ".cs").ToLower();

            if (!File.Exists(fileName))
            {
                throw new Exception("File " + fileName + " does not exist");
            }

            // compile
            CSharpCodeProvider provider = new CSharpCodeProvider();

            // Obtain an ICodeGenerator from a CodeDomProvider class.
            ICodeCompiler      comp    = provider.CreateCompiler();
            CompilerParameters options = new CompilerParameters();

            options.GenerateInMemory        = true;
            options.IncludeDebugInformation = true;
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Xml.dll");

            SetStatusBar("Compiling result");
            CompilerResults result = comp.CompileAssemblyFromFile(options, fileName);

            if (result.Errors.HasErrors)
            {
                StringWriter sw = new StringWriter();
                foreach (CompilerError error in result.Errors)
                {
                    sw.WriteLine(error.ToString());
                }
                throw new Exception(sw.ToString());
            }

            SetStatusBar("Recfactoring output");
            XsdWrapperGenerator xsg = new XsdWrapperGenerator(this.config.OutputNamespace);

            xsg.Conformer.Camelize   = this.config.AutoCamelize;
            xsg.Conformer.Capitalize = this.config.AutoCapitalize;
            foreach (Type t in result.CompiledAssembly.GetExportedTypes())
            {
                xsg.Add(t);
            }
            xsg.Generate();

            // getting generator
            Refly.CodeDom.CodeGenerator gen = new Refly.CodeDom.CodeGenerator();

            SetStatusBar("Generating refactored classes");
            gen.CreateFolders = this.config.CreateNamespaceFolders;
            gen.GenerateCode(this.config.OutputPath, xsg.Ns);
            SetStatusBar("Generation finished successfully");
        }
示例#52
0
        public BotRuleCodeCompiler(string code, List <string> AssemblyReferences = null, List <string> NameSpaceUsings = null)
        {
            ClassName = "Program" + (Guid.NewGuid()).ToString("N"); // just set the pure ClassName

            this.Code =
                "using System;\n" +
                "using System.Text;\n" +
                "using System.Text.RegularExpressions;\n" +
                "using QXS.ChatBot;\n"

            ;
            if (NameSpaceUsings == null)
            {
                this.Code +=
                    "using System.Collections;\n" +
                    "using System.Collections.Generic;\n" +
                    "using System.Linq;\n" +
                    "using System.Reflection;\n"
                ;
            }
            else
            {
                Regex namspaceValidator = new Regex(@"^([a-z]+[a-z0-9]*)(\.[a-z]+[a-z0-9]*)*$", RegexOptions.IgnoreCase);
                foreach (string nspace in NameSpaceUsings)
                {
                    if (!namspaceValidator.IsMatch(nspace))
                    {
                        throw new ArgumentException("Invalid namespace using for value \"" + nspace + "\"!");
                    }
                    this.Code += "using " + nspace + ";\n";
                }
            }

            this.Code += @"
namespace " + DefaultNamspace + @"
{
    public class " + ClassName + @"
    {
        public static string Process(Match match, ChatSessionInterface session)
        {
            " + code.Replace("\n", "\n            ").TrimEnd() + @"
            return null;
        }
    }
}
";
            CSharpCodeProvider provider = new CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("mscorlib.dll");
            parameters.ReferencedAssemblies.Add("ChatBot.dll");
            if (AssemblyReferences == null)
            {
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                parameters.ReferencedAssemblies.Add("System.Data.dll");
                parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.dll");
                parameters.ReferencedAssemblies.Add("System.Xml.Linq.dll");
            }
            else
            {
                foreach (string aref in AssemblyReferences)
                {
                    parameters.ReferencedAssemblies.Add(aref);
                }
            }
            // True - memory generation, false - external file generation
            parameters.GenerateInMemory = true;
            // True - exe file generation, false - dll file generation
            parameters.GenerateExecutable = false;

            results = provider.CompileAssemblyFromSource(parameters, this.Code);

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }

            ClassName = DefaultNamspace + "." + ClassName; // set the full ClassName
            method    = results.CompiledAssembly.GetType(ClassName).GetMethod("Process");
        }
示例#53
0
        /// <summary>
        /// GetWsProxyType 获取目标Web服务对应的代理类型
        /// </summary>
        /// <param name="wsUrl">目标Web服务的url</param>
        /// <param name="classname">Web服务的class名称,如果不需要指定,则传入null</param>
        public static Type GetWsProxyType(string wsUrl, string classname)
        {
            string @namespace = "ESBasic.WebService.DynamicWebCalling";

            if ((classname == null) || (classname == ""))
            {
                classname = WebServiceHelper.GetWsClassName(wsUrl);
            }
            string cacheKey = wsUrl + "@" + classname;

            if (WebServiceHelper.WSProxyTypeDictionary.ContainsKey(cacheKey))
            {
                return(WebServiceHelper.WSProxyTypeDictionary[cacheKey]);
            }


            //获取WSDL
            WebClient                  wc     = new WebClient();
            Stream                     stream = wc.OpenRead(wsUrl + "?WSDL");
            ServiceDescription         sd     = ServiceDescription.Read(stream);
            ServiceDescriptionImporter sdi    = new ServiceDescriptionImporter();

            sdi.AddServiceDescription(sd, "", "");
            CodeNamespace cn = new CodeNamespace(@namespace);

            //生成客户端代理类代码
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            CSharpCodeProvider csc = new CSharpCodeProvider();
            ICodeCompiler      icc = csc.CreateCompiler();

            //设定编译参数
            CompilerParameters cplist = new CompilerParameters();

            cplist.GenerateExecutable = false;
            cplist.GenerateInMemory   = true;
            cplist.ReferencedAssemblies.Add("System.dll");
            cplist.ReferencedAssemblies.Add("System.XML.dll");
            cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
            cplist.ReferencedAssemblies.Add("System.Data.dll");

            //编译代理类
            CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);

            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
                throw new Exception(sb.ToString());
            }

            //生成代理实例,并调用方法
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            Type[] ts          = assembly.GetTypes();
            Type   wsProxyType = assembly.GetType(@namespace + "." + classname, true, true);


            lock (WebServiceHelper.WSProxyTypeDictionary)
            {
                if (!WebServiceHelper.WSProxyTypeDictionary.ContainsKey(cacheKey))
                {
                    WebServiceHelper.WSProxyTypeDictionary.Add(cacheKey, wsProxyType);
                }
            }
            return(wsProxyType);
        }
示例#54
0
        /// <summary>
        /// Parses and compiles a markup template into an assembly and returns
        /// an assembly name. The name is an ID that can be passed to
        /// ExecuteTemplateByAssembly which picks up a cached instance of the
        /// loaded assembly.
        ///
        /// </summary>
        /// <param name="referencedAssemblies">Any referenced assemblies by dll name only. Assemblies must be in execution path of host or in GAC.</param>
        /// <param name="templateSourceReader">Textreader that loads the template</param>
        /// <param name="generatedNamespace">The namespace of the class to generate from the template. null generates name.</param>
        /// <param name="generatedClassName">The name of the class to generate from the template. null generates name.</param>
        /// <remarks>
        /// The actual assembly isn't returned here to allow for cross-AppDomain
        /// operation. If the assembly was returned it would fail for cross-AppDomain
        /// calls.
        /// </remarks>
        /// <returns>An assembly Id. The Assembly is cached in memory and can be used with RenderFromAssembly.</returns>
        public string ParseAndCompileTemplate(
            string[] referencedAssemblies,
            TextReader templateSourceReader,
            string generatedNamespace,
            string generatedClassName)
        {
            if (string.IsNullOrEmpty(generatedNamespace))
            {
                generatedNamespace = "__RazorHost";
            }
            if (string.IsNullOrEmpty(generatedClassName))
            {
                generatedClassName = GetSafeClassName(null);
            }

            var engine = CreateHost(generatedNamespace, generatedClassName);

            // Generate the template class as CodeDom
            var razorResults = engine.GenerateCode(templateSourceReader);

            // Create code from the codeDom and compile
            var codeProvider = new CSharpCodeProvider();
            var options      = new CodeGeneratorOptions();

            // Capture Code Generated as a string for error info
            // and debugging
            LastGeneratedCode = null;
            using (var writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
                LastGeneratedCode = writer.ToString();
            }

            var compilerParameters = new CompilerParameters(referencedAssemblies);

            // Standard Assembly References
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll");             // dynamic support!

            // Also add the current assembly so RazorTemplateBase is available
            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().CodeBase.Substring(8));

            compilerParameters.GenerateInMemory = Configuration.CompileToMemory;
            if (!Configuration.CompileToMemory)
            {
                compilerParameters.OutputAssembly = Path.Combine(Configuration.TempAssemblyPath, "_" + Guid.NewGuid().ToString("n") + ".dll");
            }

            var compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);

            if (compilerResults.Errors.Count > 0)
            {
                var compileErrors = new StringBuilder();
                foreach (CompilerError compileError in compilerResults.Errors)
                {
                    compileErrors.Append(String.Format("LineX0TColX1TErrorX2RN", compileError.Line, compileError.Column, compileError.ErrorText));
                }

                SetError(compileErrors.ToString() + "\r\n" + LastGeneratedCode);
                return(null);
            }

            AssemblyCache.Add(compilerResults.CompiledAssembly.FullName, compilerResults.CompiledAssembly);

            return(compilerResults.CompiledAssembly.FullName);
        }
示例#55
0
    /// <summary>
    ///
    /// Compiles .cs script into dll/pdb, loads as assembly, and executes Main function.
    ///
    /// Assembly gets executed within same appDomain.
    ///
    /// If there is any compilation error - it will be thrown as exception.
    ///
    /// Any //css_ref referred file will be loaded into appDomain once, and will stay there until application shuts down.
    ///
    /// Unfortunately this function will collect .dll & .pdb compilations into %TEMP%\CSScriptHost.
    /// Use CleanupScScriptTempDir() on application startup to wipe out compilation folder.
    ///
    /// </summary>
    static public void RunScript(String scriptPath)
    {
        String tempDir = GetScriptTempDir();

        if (!Directory.Exists(tempDir))
        {
            Directory.CreateDirectory(tempDir);
        }

        String path = Path.GetFullPath(scriptPath);

        if (!File.Exists(path))
        {
            throw new Exception("Error: Could not load file '" + Path.GetFileName(path) + "': File does not exists.");
        }

        String dllBaseName = Path.GetFileNameWithoutExtension(path) + "_" + loadCounter.ToString();
        String basePath    = Path.Combine(tempDir, dllBaseName);

        String pdbPath = basePath + ".pdb";
        String dllPath = basePath + ".dll";

        try
        {
            List <String> filesToCompile = new List <string>();
            filesToCompile.Add(path);

            //---------------------------------------------------------------------------------------------------
            //  Get referenced .cs script file list, and from referenced files further other referenced files.
            //---------------------------------------------------------------------------------------------------
            CsScriptInfo csInfo = getCsFileInfo(filesToCompile[0], true);
            filesToCompile.AddRange(csInfo.csFiles);

            if (provider == null)
            {
                provider = new CSharpCodeProvider();
            }
#pragma warning disable 618
            if (compiler == null)
            {
                compiler = provider.CreateCompiler();
            }
#pragma warning restore 618
            CompilerParameters compilerparams = new CompilerParameters();
            compilerparams.GenerateExecutable = false;

#if NODEBUGTRACE
            // Currently it's not possible to generate in ram pdb debugging information.
            // Compiler option /debug:full should in theory allow that, but it does not work.
            compilerparams.GenerateInMemory = true;
#else
            compilerparams.GenerateInMemory        = false;
            compilerparams.IncludeDebugInformation = true;                // Needed to get line / column numbers
            compilerparams.OutputAssembly          = dllPath;
            compilerparams.CompilerOptions         = "/d:DEBUG /d:TRACE"; // /debug+ /debug:full /optimize-
#endif

            // Add assemblies from my domain - all which are not dynamic.
            if (refAssemblies == null)
            {
                var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location).ToList();

                for (int i = 0; i < assemblies.Count; i++)
                {
                    if (assemblies[i].EndsWith(".exe") && !assemblies[i].EndsWith("\\scriptStarter.exe"))
                    {
                        assemblies.RemoveAt(i);
                        i--;
                    }
                }

                refAssemblies = assemblies.ToArray();
            }

            compilerparams.ReferencedAssemblies.AddRange(refAssemblies);
            foreach (var f in csInfo.refFiles)
            {
                compilerparams.ReferencedAssemblies.Add(f);
            }

            // ----------------------------------------------------------------
            //  If compile errors - report and exit.
            // ----------------------------------------------------------------
            CompilerResults results = compiler.CompileAssemblyFromFileBatch(compilerparams, filesToCompile.ToArray());
            if (results.Errors.HasErrors)
            {
                // Mimic visual studio error handling.
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError error in results.Errors)
                {
                    // Missing reference file will not give any file or line information, we just use compilation
                    // script filename, and first line position. (Not exactly right, but something at least).

                    if (error.FileName == "")
                    {
                        sb.Append(Path.GetFileName(filesToCompile[0]));
                    }
                    else
                    {
                        sb.Append(Path.GetFileName(error.FileName));
                    }

                    if (error.Line == 0)
                    {
                        // error CS0006: Metadata file 'MystiqueDll.dll' could not be found
                        sb.Append("(1,1)");
                    }
                    else
                    {
                        sb.Append("(" + error.Line + "," + error.Column + ")");
                    }

                    sb.AppendFormat(": error {0}: {1}\r\n", error.ErrorNumber, error.ErrorText);
                }

                throw new Exception(sb.ToString());
            }
            loadCounter++;

            // ----------------------------------------------------------------
            //  Preload compiled .dll and it's debug information into ram.
            // ----------------------------------------------------------------
            MethodInfo entry    = null;
            String     funcName = "";
            Assembly   asm      = Assembly.LoadFrom(dllPath);

            // ----------------------------------------------------------------
            //  Locate entry point
            // ----------------------------------------------------------------
            BindingFlags flags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.IgnoreCase;

            foreach (Type type in asm.GetTypes())
            {
                funcName = "Main";
                entry    = type.GetMethod(funcName, flags);

                if (entry != null)
                {
                    break;
                }
            }

            if (entry == null)
            {
                throw new Exception(String.Format("{0}(1,1): error: Code does not have 'Main' function\r\n", Path.GetFileName(path)));
            }

            if (entry.GetParameters().Length != 0)
            {
                throw new Exception(String.Format("{0}(1,1): error: Function '{1}' is not expected to have no input parameters\r\n", Path.GetFileName(path), funcName));
            }

            String oldDir = Environment.CurrentDirectory;
            //
            // We set current directory to where script is, just so script can use Directory.GetFiles without specifying directory.
            //
            Directory.SetCurrentDirectory(Path.GetDirectoryName(scriptPath));

            // ----------------------------------------------------------------
            //  Run script
            // ----------------------------------------------------------------
            try
            {
                entry.Invoke(null, new object[] { });
                Directory.SetCurrentDirectory(oldDir);
            }
            catch (Exception ex)
            {
                Directory.SetCurrentDirectory(oldDir);

                String errors = "";

                try
                {
                    StackFrame[] stack    = new StackTrace(ex.InnerException, true).GetFrames();
                    StackFrame   lastCall = stack[0];

                    errors = String.Format("{0}({1},{2}): error: {3}\r\n", path,
                                           lastCall.GetFileLineNumber(), lastCall.GetFileColumnNumber(), ex.InnerException.Message);
                }
                catch (Exception ex3)
                {
                    errors = String.Format("{0}(1,1): error: Internal error - exception '{3}'\r\n", path, ex3.Message);
                }
                throw new Exception(errors);
            }
        }
        finally
        {
            // Currently all file deletes are disabled (otherwise throws exceptions)

            // Will work only if main was not possible to find.
            //try { File.Delete(dllPath); } catch { }

            // Works only when there is no debugger attached.
            //try { File.Delete(pdbPath); } catch { }
        }
    }
示例#56
0
        private static byte[] CompileMod(string modDir, BuildProperties properties, bool forWindows)
        {
            CompilerParameters compileOptions = new CompilerParameters();

            compileOptions.GenerateExecutable = false;
            compileOptions.GenerateInMemory   = false;
            string outFile = ModPath + Path.DirectorySeparatorChar + Path.GetFileName(modDir) + ".dll";

            compileOptions.OutputAssembly = outFile;
            bool flag = false;

            foreach (string reference in buildReferences)
            {
                if (forWindows)
                {
                    if (reference.IndexOf("FNA.dll") >= 0)
                    {
                        compileOptions.ReferencedAssemblies.Add("Microsoft.Xna.Framework.dll");
                        compileOptions.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Game.dll");
                        compileOptions.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Graphics.dll");
                        compileOptions.ReferencedAssemblies.Add("Microsoft.Xna.Framework.Xact.dll");
                        continue;
                    }
                    else if (!windows && reference.IndexOf("Terraria.exe") >= 0)
                    {
                        compileOptions.ReferencedAssemblies.Add("TerrariaWindows.exe");
                        continue;
                    }
                }
                else
                {
                    if (reference.IndexOf("Microsoft.Xna.Framework") >= 0)
                    {
                        if (!flag)
                        {
                            compileOptions.ReferencedAssemblies.Add("FNA.dll");
                            flag = true;
                        }
                        continue;
                    }
                    else if (windows && reference.IndexOf(System.AppDomain.CurrentDomain.FriendlyName) >= 0)
                    {
                        compileOptions.ReferencedAssemblies.Add("TerrariaMac.exe");
                        continue;
                    }
                }
                compileOptions.ReferencedAssemblies.Add(reference);
            }
            Directory.CreateDirectory(DllPath);
            foreach (string reference in properties.dllReferences)
            {
                compileOptions.ReferencedAssemblies.Add(DllPath + Path.DirectorySeparatorChar + reference + ".dll");
            }
            foreach (string reference in properties.modReferences)
            {
                string refFile     = ModSourcePath + Path.DirectorySeparatorChar + reference;
                string realRefFile = refFile + ".dll";
                refFile += forWindows ? "1.dll" : "2.dll";
                if (File.Exists(realRefFile))
                {
                    File.Delete(realRefFile);
                }
                File.Move(refFile, realRefFile);
                compileOptions.ReferencedAssemblies.Add(realRefFile);
            }
            var options = new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            };
            CodeDomProvider         codeProvider = new CSharpCodeProvider(options);
            CompilerResults         results      = codeProvider.CompileAssemblyFromFile(compileOptions, Directory.GetFiles(modDir, "*.cs", SearchOption.AllDirectories));
            CompilerErrorCollection errors       = results.Errors;

            foreach (string reference in properties.modReferences)
            {
                File.Delete(ModSourcePath + Path.DirectorySeparatorChar + reference + ".dll");
            }
            if (errors.HasErrors)
            {
                ErrorLogger.LogCompileErrors(errors);
                return(null);
            }
            byte[] data = File.ReadAllBytes(outFile);
            File.Delete(outFile);
            return(data);
        }
        public IEnumerator <AutocompleteItem> GetEnumerator()
        {
            var compiler = new CSharpCodeProvider();
            // Just to prove a point...

            //get current fragment of the text
            var text = tb.GetLineText(menu.Fragment.ToLine);

            //extract class name (part before dot)
            var parts = text.Split('.');

            if (parts.Length < 2)
            {
                yield break;
            }
            var  obj  = parts[0];
            Type type = null;

            if (obj == "Selected")
            {
                type = typeof(UITreeSelection);
            }
            else if (obj == "Model")
            {
                type = typeof(Model);
            }

            if (type == null)
            {
                yield break;
            }

            PropertyInfo prop;

            for (var i = 1; i < parts.Length - 1; i++)
            {
                var brackets = parts[i].IndexOf('[');
                if (brackets > 0)
                {
                    if (parts[i].IndexOf(']') > brackets + 1)
                    {
                        prop = type.GetProperty(parts[i].Substring(0, brackets));
                        if (prop != null)
                        {
                            var indexerType = prop.PropertyType.GetDefaultMembers().OfType <PropertyInfo>().FirstOrDefault()?.PropertyType;
                            if (indexerType != null)
                            {
                                type = indexerType;
                                continue;
                            }
                            else
                            {
                                yield break;
                            }
                        }
                        else
                        {
                            yield break;
                        }
                    }
                    else
                    {
                        yield break;
                    }
                }

                var parenthesis = parts[i].IndexOf('(');
                if (parenthesis > 0)
                {
                    if (parts[i].IndexOf(')') > brackets)
                    {
                        var method = type.GetMethod(parts[i].Substring(0, parenthesis));
                        if (method != null)
                        {
                            type = method.ReturnType; continue;
                        }
                        else
                        {
                            yield break;
                        }
                    }
                    else
                    {
                        yield break;
                    }
                }

                prop = type.GetProperty(parts[i]);
                if (prop != null)
                {
                    type = prop.PropertyType; continue;
                }
                else
                {
                    yield break;
                }
            }

            if (type == null)
            {
                yield break;
            }

            MethodAutocompleteItem last = null;

            //return methods
            foreach (var mi in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                     .Where(m => !m.IsSpecialName && m.DeclaringType != typeof(object)).AsEnumerable())
            {
                switch (mi.Name)
                {
                case "GetEnumerator":
                    continue;
                }

                // Overloaded methods only show up once, but let's display all overrides in the tooltip.
                var    methodName = mi.Name + "()";
                string returnTypeName;
                if (mi.ReturnType == typeof(void))
                {
                    returnTypeName = "void";
                }
                else
                {
                    var returnType = new CodeTypeReference(mi.ReturnType);
                    returnTypeName = compiler.GetTypeOutput(returnType).Replace("TabularEditor.UI.UISelectionList", "IEnumerable").Replace("TabularEditor.TOMWrapper.", "");
                }

                var methodSyntax = returnTypeName + " " + mi.Name + "(" + string.Join(", ", mi.GetParameters().Select(p => p.Name).ToArray()) + ")";

                if (last?.Text == methodName)
                {
                    last.ToolTipTitle += "\n" + methodSyntax;
                }
                else
                {
                    last = new MethodAutocompleteItem(methodName)
                    {
                        ToolTipTitle = methodSyntax,
                        ToolTipText  = mi.GetCustomAttribute <DescriptionAttribute>()?.Description ?? string.Empty,
                        ImageIndex   = TabularIcons.ICON_METHOD
                    };
                    yield return(last);
                }
            }

            // Type derives from IEnumerable, so let's add a few select LINQ methods:
            if (type.GetInterface("IEnumerable") != null)
            {
                yield return(new MethodAutocompleteItem("Select()")
                {
                    ToolTipTitle = "Select",
                    ToolTipText = "Projects each item of the collection into something else using a lambda expression.\nExample: .Select(Measure => Measure.Table)",
                    ImageIndex = TabularIcons.ICON_EXMETHOD
                });

                yield return(new MethodAutocompleteItem("Any()")
                {
                    ToolTipTitle = "Any",
                    ToolTipText = "Determines if the collection contains any items. Specify a lambda expression to determine if the collection contains any items satisfying the given criteria.\nExample: .Any(Measure => Measure.Description == \"\")",
                    ImageIndex = TabularIcons.ICON_EXMETHOD
                });

                yield return(new MethodAutocompleteItem("All()")
                {
                    ToolTipTitle = "All",
                    ToolTipText = "Determines if all items in the collection satisfies the given criteria.\nExample: .All(Measure => Measure.Description == \"\")",
                    ImageIndex = TabularIcons.ICON_EXMETHOD
                });

                // Below adds all LINQ methods, which may be overkill:

                /*foreach (var method in typeof(System.Linq.Enumerable)
                 *  .GetMethods(BindingFlags.Static | BindingFlags.Public).Select(m => m.Name).Distinct())
                 * {
                 *  yield return new MethodAutocompleteItem(method + "()")
                 *  {
                 *      ToolTipTitle = method,
                 *      ImageIndex = TabularIcons.ICON_METHOD
                 *  };
                 * }*/
            }

            //return static properties of the class
            foreach (var pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var propType     = new CodeTypeReference(pi.PropertyType);
                var propTypeName = compiler.GetTypeOutput(propType).Replace("TabularEditor.UI.UISelectionList", "IEnumerable").Replace("TabularEditor.TOMWrapper.", "");

                yield return(new MethodAutocompleteItem(pi.Name)
                {
                    ToolTipTitle = string.Format("{0} {1} {{ {2}}}", propTypeName, pi.Name, (pi.CanRead ? "get; " : "") + (pi.CanWrite ? "set; " : "")),
                    ToolTipText = pi.GetCustomAttribute <DescriptionAttribute>()?.Description ?? string.Empty,
                    ImageIndex = TabularIcons.ICON_PROPERTY
                });
            }
        }
示例#58
0
        public static CompilerResults CompileScript(string scriptSetup, string scriptSource, string outputDllFile)
        {
            var source  = @"# pragma warning disable 0168 // variable declared but not used.
# pragma warning disable 0219 // variable assigned but not used.
# pragma warning disable 0414 // private field assigned but not used.

{using}

namespace HomeGenie.Automation.Scripting
{
    [Serializable]
    public class ScriptingInstance : ScriptingHost
    {
        private void RunCode(string PROGRAM_OPTIONS_STRING)
        {
//////////////////////////////////////////////////////////////////
// NOTE: user code start line is 16 *** please add new code after this method, do not alter start line! ***
{source}
//////////////////////////////////////////////////////////////////
        }

        #pragma warning disable 0162
        private bool SetupCode()
        {
//////////////////////////////////////////////////////////////////
// NOTE: user code start line is ??? *** please add new code after this method, do not alter start line! ***
{setup}
//////////////////////////////////////////////////////////////////
            return false;
        }
        #pragma warning restore 0162

        private MethodRunResult Run(string PROGRAM_OPTIONS_STRING)
        {
            Exception ex = null;
            try
            {
                RunCode(PROGRAM_OPTIONS_STRING);
            }
            catch (Exception e)
            {
                ex = e;
            }
            return new MethodRunResult(){ Exception = ex, ReturnValue = null };
        }

        private MethodRunResult Setup()
        {
            Exception ex = null;
            bool retval = false;
            try
            {
                retval = SetupCode();
            }
            catch (Exception e)
            {
                ex = e;
            }
            return new MethodRunResult(){ Exception = ex, ReturnValue = retval };
        }

        public ScriptingHost hg { get { return (ScriptingHost)this; } }
    }
}";
            var usingNs = String.Join(" ", Includes.Select(x => String.Format("using {0};" + Environment.NewLine, x)));

            source = source
                     .Replace("{using}", usingNs)
                     .Replace("{source}", scriptSource)
                     .Replace("{setup}", scriptSetup);

            var providerOptions = new Dictionary <string, string>
            {
                //{ "CompilerVersion", "v4.0" }
            };
            var provider       = new CSharpCodeProvider(providerOptions);
            var compilerParams = new CompilerParameters
            {
                GenerateInMemory        = false,
                GenerateExecutable      = false,
                IncludeDebugInformation = true,
                TreatWarningsAsErrors   = false,
                OutputAssembly          = outputDllFile
                                          // *** Useful for debugging
                                          //,TempFiles = new TempFileCollection {KeepFiles = true}
            };

            // Mono runtime 2/3 compatibility fix
            // TODO: this may not be required anymore
            var relocateSystemAsm = false;
            var type = Type.GetType("Mono.Runtime");

            if (type != null)
            {
                MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
                if (displayName != null)
                {
                    int major;
                    if (Int32.TryParse(displayName.Invoke(null, null).ToString().Substring(0, 1), out major) && major > 2)
                    {
                        relocateSystemAsm = true;
                    }
                }
            }
            if (!relocateSystemAsm)
            {
                var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (var assembly in assemblies)
                {
                    var assemblyName = assembly.GetName();
                    switch (assemblyName.Name.ToLower())
                    {
                    case "system":
                        compilerParams.ReferencedAssemblies.Add(assembly.Location);
                        break;

                    case "system.core":
                        compilerParams.ReferencedAssemblies.Add(assembly.Location);
                        break;

                    case "microsoft.csharp":
                        compilerParams.ReferencedAssemblies.Add(assembly.Location);
                        break;
                    }
                }
            }
            else
            {
                compilerParams.ReferencedAssemblies.Add("System.dll");
                compilerParams.ReferencedAssemblies.Add("System.Core.dll");
                compilerParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            }

            compilerParams.ReferencedAssemblies.Add("HomeGenie.exe");
            compilerParams.ReferencedAssemblies.Add("MIG.dll");
            compilerParams.ReferencedAssemblies.Add(Path.Combine("lib", "mig", "CM19Lib.dll"));
            compilerParams.ReferencedAssemblies.Add("NLog.dll");
            compilerParams.ReferencedAssemblies.Add("Newtonsoft.Json.dll");

            compilerParams.ReferencedAssemblies.Add("SerialPortLib.dll");
            compilerParams.ReferencedAssemblies.Add("NetClientLib.dll");

            compilerParams.ReferencedAssemblies.Add("UPnP.dll");

            //if (Raspberry.Board.Current.IsRaspberryPi)
            {
                compilerParams.ReferencedAssemblies.Add("Raspberry.IO.dll");
                compilerParams.ReferencedAssemblies.Add("Raspberry.IO.Components.dll");
                compilerParams.ReferencedAssemblies.Add("Raspberry.IO.GeneralPurpose.dll");
                compilerParams.ReferencedAssemblies.Add("Raspberry.IO.InterIntegratedCircuit.dll");
                compilerParams.ReferencedAssemblies.Add("Raspberry.IO.SerialPeripheralInterface.dll");
                compilerParams.ReferencedAssemblies.Add("Raspberry.System.dll");
                compilerParams.ReferencedAssemblies.Add("UnitsNet.dll");
            }

            compilerParams.ReferencedAssemblies.Add(Path.Combine("lib", "shared", "Innovative.Geometry.dll"));
            compilerParams.ReferencedAssemblies.Add(Path.Combine("lib", "shared", "Innovative.SolarCalculator.dll"));

            // compile and generate script assembly
            return(provider.CompileAssemblyFromSource(compilerParams, source));
        }
示例#59
0
        private static void CompileComparisonMatchers()
        {
            for (int i = GraphMatchingState.candidatesForCompilation.Count - 1; i >= 0; --i)
            {
                LGSPGraph graph = GraphMatchingState.candidatesForCompilation[i];
                if (graph.matchingState.changesCounterAtInterpretationPlanBuilding != graph.ChangesCounter)
                {
                    GraphMatchingState.candidatesForCompilation.RemoveAt(i);
                }
            }

            SourceBuilder sourceCode = new SourceBuilder();

            sourceCode.AppendFront("using System;\n"
                                   + "using System.Collections.Generic;\n"
                                   + "using GRGEN_LIBGR = de.unika.ipd.grGen.libGr;\n"
                                   + "using GRGEN_LGSP = de.unika.ipd.grGen.lgsp;\n\n");
            sourceCode.AppendFront("namespace de.unika.ipd.grGen.lgspComparisonMatchers\n");
            sourceCode.AppendFront("{\n");
            sourceCode.Indent();

            foreach (LGSPGraph graph in GraphMatchingState.candidatesForCompilation)
            {
                ((InterpretationPlanStart)graph.matchingState.interpretationPlan).Emit(sourceCode);
            }

            sourceCode.Append("}");

#if DUMP_COMPILED_MATCHER
            using (StreamWriter sw = new StreamWriter("comparison_matcher_" + GraphMatchingState.candidatesForCompilation[0].GraphId + ".cs"))
                sw.Write(sourceCode.ToString());
#endif

            // set up compiler
            CSharpCodeProvider compiler   = new CSharpCodeProvider();
            CompilerParameters compParams = new CompilerParameters();
            compParams.ReferencedAssemblies.Add("System.dll");
            compParams.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(BaseGraph)).Location);
            compParams.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(LGSPGraph)).Location);
            compParams.GenerateInMemory = true;
            compParams.CompilerOptions  = "/optimize";

            // building methods with MSIL would be highly preferable, but is much harder of course
            CompilerResults compResults = compiler.CompileAssemblyFromSource(compParams, sourceCode.ToString());
            if (compResults.Errors.HasErrors)
            {
                String errorMsg = compResults.Errors.Count + " Errors:";
                foreach (CompilerError error in compResults.Errors)
                {
                    errorMsg += Environment.NewLine + "Line: " + error.Line + " - " + error.ErrorText;
                }
                throw new ArgumentException("Internal error: Illegal C# source code produced for graph comparison: " + errorMsg);
            }

            // create comparison matcher instances
            foreach (LGSPGraph graph in GraphMatchingState.candidatesForCompilation)
            {
                graph.matchingState.compiledMatcher = (GraphComparisonMatcher)compResults.CompiledAssembly.CreateInstance(
                    "de.unika.ipd.grGen.lgspComparisonMatchers.ComparisonMatcher_" + graph.GraphId);
                if (graph.matchingState.compiledMatcher == null)
                {
                    throw new ArgumentException("Internal error: Generated assembly does not contain comparison matcher 'ComparisonMatcher_" + graph.GraphId + "'!");
                }
                ++GraphMatchingState.numCompiledMatchers;
            }

            GraphMatchingState.candidatesForCompilation.Clear();
            ++GraphMatchingState.numCompilationPasses;
        }
示例#60
0
        //测试
        private void BtnTest_Click(object sender, RoutedEventArgs e)
        {
            TbTestResult.Text = "";
            RefreshCalculationText();

            Type dynamicCode = null;                                                       //获取编译后代码,调用该类用
            Dictionary <string, Dictionary <string, string> >
            FuncAndParamTagPKNO = new Dictionary <string, Dictionary <string, string> >(); //函数和对应参数的Tag的PKNO

            string className = "C" + Guid.NewGuid().ToString("N");

            try
            {
                Cursor = Cursors.Wait;

                #region 形成执行的代码

                string execCode = "using System; \r\n" +
                                  "using System.Text; \r\n" +
                                  "using System.Collections.Generic; \r\n" +
                                  "using BFM.Common.Base; \r\n\r\n";

                execCode += "public class " + className + "\r\n" +
                            "{ \r\n";

                string basicFuc = "AutoCalculation";

                int index = 1;
                FuncAndParamTagPKNO.Clear();

                string exp = CalculationText;                                             //表达式

                string funcname = basicFuc + index.ToString();                            //函数名称
                Dictionary <string, string> paramTas = new Dictionary <string, string>(); //参数对应的标签的PKNO, param名称

                List <string> funcParam = new List <string>();                            //带类型的参数

                string code = "";

                foreach (var line in exp.Split(new string[] { "\r\n" }, StringSplitOptions.None))
                {
                    string ret = line;

                    #region 替换标签值,将标签替换成参数名

                    string[] expTags = line.Split('{');

                    for (int i = 0; i < expTags.Length; i++)
                    {
                        string str    = expTags[i];
                        int    length = str.IndexOf('}');

                        if (length < 0) //没有找到  }
                        {
                            continue;
                        }

                        string tagPKNO = str.Substring(0, length); //{ } 内为PKNO

                        string param = "{" + tagPKNO + "}";

                        if (paramTas.ContainsKey(tagPKNO))  //已经添加了该参数
                        {
                            param = paramTas[tagPKNO];
                        }
                        else
                        {
                            FmsAssetTagSetting tag = DeviceTags.FirstOrDefault(s => s.PKNO == tagPKNO);
                            if (tag == null)
                            {
                                continue;
                            }

                            param = "param" + paramTas.Count;
                            paramTas.Add(tagPKNO, param);
                            string paramType = "string";
                            //string paramType = ((CalculationType == 2) || (tag.VALUE_TYPE > 0 && tag.VALUE_TYPE < 20))
                            //    ? "double"
                            //    : "string";
                            funcParam.Add(paramType + " " + param);
                        }

                        ret = ret.Replace("{" + tagPKNO + "}", param);
                    }

                    #endregion

                    if (string.IsNullOrEmpty(code))
                    {
                        code = "    " + ret;
                    }
                    else
                    {
                        code += Environment.NewLine + "    " + ret;
                    }
                }

                //C#脚本
                //支持C#语法,最后返回值(Double/String)
                string resultType = "string";

                //确定返回结果类型,将code语句转换成C#的语句
                if (CalculationType == 1) //逻辑运算
                {
                    //(结果为1,0):({标签1}==1)&&({标签2}==1)&&({标签3}==0||{标签4}==0)&&({标签5}==1)
                    code       = code.Replace("AND", "&&").Replace("and", "&&").Replace("OR", "||").Replace("or", "||");
                    resultType = "bool";
                }
                else if (CalculationType == 2) //数值运算
                {
                    //{标签1}+3+{标签2}+4
                    resultType = "double";
                }
                else if (CalculationType == 3) //字符运算
                {
                    //{标签1}+"123"
                }
                else if (CalculationType == 12) //条件数值运算
                {
                    //{标签1}==3:{标签2}+1;{标签1}==4:{标签2}+2;{标签1}==5:{标签2}+3
                    resultType = "double";
                    List <string> exps = code.Split(';').ToList();
                    string        temp = "";
                    foreach (var exp1 in exps)
                    {
                        if (exp1.Split(':').Length < 2)
                        {
                            continue;
                        }
                        temp += "        if (" + exp1.Split(':')[0] + ") { return (" + exp1.Split(':')[1] + "); } \r\n";
                    }

                    temp += "        return 0; \r\n";

                    code = temp;
                }
                else if (CalculationType == 13) //条件字符运算
                {
                    //{标签1}==3:{标签1}+"123";{标签1}==4:{标签1}+"123"
                    List <string> exps = code.Split(';').ToList();
                    string        temp = "";
                    foreach (var exp1 in exps)
                    {
                        if (exp1.Split(':').Length < 2)
                        {
                            continue;
                        }
                        temp += "        if (" + exp1.Split(':')[0] + ") { return (" + exp1.Split(':')[1] + ").ToString(); } \r\n";
                    }

                    temp += "        return \"\"; \r\n";

                    code = temp;
                }
                else if (CalculationType == 21)
                {
                    resultType = "string";//{标签1};3
                    List <string> exps = code.Split(';').ToList();
                    string        temp = "";
                    if (exps.Count >= 2)
                    {
                        int arrayIndex = SafeConverter.SafeToInt(exps[1].Trim(), 0);
                        temp += "            if ( " + exps[0].Trim() + ".Split('|').Length > " + arrayIndex + ") { return " + exps[0].Trim() + ".Split('|')[" + arrayIndex + "]; } \r\n";
                    }

                    temp += "        return \"\"; \r\n";

                    code = temp;
                }
                else if (CalculationType == 100) //C#脚本
                {
                    //支持C#语法,最后返回值(Double/String)
                    resultType = "string";
                }
                else  //不支持的类型
                {
                    code = $"        return \"计算类型[{CalculationType}],不支持的类型。\"; \r\n";
                }

                execCode += DynamicCode.BuildExecFunc(funcname, resultType, code, funcParam);

                FuncAndParamTagPKNO.Add(funcname, paramTas); //添加

                execCode += "}\r\n";

                #endregion

                #region 编译代码

                CodeDomProvider    compiler = new CSharpCodeProvider();
                CompilerParameters cp       = new CompilerParameters()
                {
                    GenerateExecutable = false, GenerateInMemory = true,
                };
                cp.ReferencedAssemblies.Add("BFM.Common.Base.dll");
                CompilerResults cr = compiler.CompileAssemblyFromSource(cp, execCode);
                if (cr.Errors.HasErrors)
                {
                    WPFMessageBox.ShowError("测试失败,语法错误.\r\n" + execCode, "测试");
                    return;
                }

                dynamicCode = cr.CompiledAssembly.GetType(className); //获取

                #endregion

                #region 获取值

                index = 0;
                string        funcName    = FuncAndParamTagPKNO.Keys.ToList()[index];
                var           tagParms    = FuncAndParamTagPKNO.Values.ToList()[index];
                List <object> paramValues = new List <object>(); //参数值

                foreach (var tagpkno in tagParms)                //参数
                {
                    object             value;
                    FmsAssetTagSetting tagParam = DeviceTags.FirstOrDefault(s => s.PKNO == tagpkno.Key);

                    if (tagParam != null)
                    {
                        value = SafeConverter.SafeToStr(tagParam.CUR_VALUE);
                        //if ((CalculationType == 2) || (tagParam.VALUE_TYPE > 0 && tagParam.VALUE_TYPE < 20))
                        //{
                        //    value = SafeConverter.SafeToDouble(tagParam.CUR_VALUE);
                        //}
                        //else
                        //{
                        //    value = SafeConverter.SafeToStr(tagParam.CUR_VALUE);
                        //}
                    }
                    else
                    {
                        value = "";
                    }

                    paramValues.Add(value);
                }

                object obj = dynamicCode.InvokeMember(funcName,
                                                      BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod,
                                                      System.Type.DefaultBinder, null, paramValues.ToArray());

                string newValue = "";     //新的计算结果

                if (CalculationType == 1) //逻辑运算
                {
                    newValue = SafeConverter.SafeToBool(obj) ? "1" : "0";
                }
                else
                {
                    newValue = SafeConverter.SafeToStr(obj);
                }

                Console.WriteLine("测试结果:" + newValue);

                TbTestResult.Text = newValue;

                #endregion

                WPFMessageBox.ShowInfo("测试成功. \r\n测试结果为:" + newValue, "测试");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                WPFMessageBox.ShowError("测试失败,错误为:" + ex.Message, "测试");
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }
        }