public void Main_O2_Gui_h2()
        {
            //CompileEngine.clearLocalScriptFileMappings();

            var scriptName = "Main O2 Gui.h2"; // this is the script used in ascx_Execute_Scripts.NEW_GUI_SCRIPT
            var file       = scriptName.local();
            var h2Code     = file.h2_SourceCode();

            //compile using internal methods

            var csharpCode = new CSharp_FastCompiler().createCSharpCodeWith_Class_Method_WithMethodText(h2Code);

            assert_Not_Null(scriptName);
            assert_Not_Null(file);
            assert_Not_Null(h2Code);
            assert_Not_Null(csharpCode);

            csharpCode.assert_Contains("public class", "DynamicType", "{", "}")
                      .assert_Contains("using System;","System.Linq;")
                      .assert_Contains("FluentSharp.REPL.Utils");

            var compileEngine = new CompileEngine();
            var assembly = compileEngine.compileSourceCode(csharpCode);

            assert_Is_Null(compileEngine.sbErrorMessage);
            assert_Not_Null(assembly);

            //check that we can also compile using the main wrapper methods
            assert_Not_Null(file.compile_H2Script());
        }
 public static string compileIntoDll_inFolder(this string fileToCompile, string targetFolder, string compilationVersion)
 {
     "Compiling file: {0} ".debug(fileToCompile);
     //var fileToCompile = currentFolder.pathCombine(file + ".cs");
     var filenameWithoutExtension = fileToCompile.fileName_WithoutExtension();
     var compiledDll = targetFolder.pathCombine(filenameWithoutExtension + ".dll");
     var mainClass = "";
     if (fileToCompile.fileExists().isFalse())
         "could not find file to compile: {0}".error(fileToCompile);
     else
     {
         var assembly = new CompileEngine(compilationVersion).compileSourceFiles(new List<string>().add(fileToCompile),
                                                               mainClass,
                                                               filenameWithoutExtension);
         if (assembly.isNull())
             "no compiled assembly object created for: {0}".error(fileToCompile);
         else
         {
             Files.copy(assembly.Location, compiledDll);
             "Copied: {0} to {1}".info(assembly.Location, compiledDll);
             if (compiledDll.fileExists().isFalse())
                 "compiled file not created in: {0}".error(compiledDll);
             else
                 return compiledDll;
         }
     }
     return null;
 }
		public bool injectIntoProcess(Process process, bool x64, bool runtime40, string sourceCodeFile)
		{
		 	//fixedCourceCode.showInCodeViewer();
		 	var compileEngine = new CompileEngine(runtime40 ? "v4.0" : "v3.5") { useCachedAssemblyIfAvailable = false };		 	
			//var compiledAssembly = compileEngine.compileSourceCode(fixedCourceCode);			
			var compiledAssembly = compileEngine.compileSourceFile(sourceCodeFile);			
			return injectIntoProcess(process,x64, runtime40,compiledAssembly);
		}
Esempio n. 4
0
        /*public O2_Start RegisterO2Extensions()
        {

            var versionName      = o2PlatformConfig.Version_Name;
            var h2Logo           = o2PlatformConfig.Folder_Scripts.pathCombine(@"_DataFiles\_Images\H2Logo.ico");
            var o2Logo           = o2PlatformConfig.Folder_Scripts.pathCombine(@"_DataFiles\_Images\O2Logo.ico");
            RegisterWindowsExtension_WinForms.register_CurrentApplication(".h2", versionName, h2Logo);
            RegisterWindowsExtension_WinForms.register_CurrentApplication(".o2", versionName, o2Logo);
            return this;
        }*/
        public Assembly compileScript(string o2Script)
        {
            var compileEngine = new CompileEngine();
            var assembly = compileEngine.compileSourceFile(o2Script.local());
            if (assembly.isNull())
                MessageBox.Show(compileEngine.sbErrorMessage.str(), @"Compilation error in Start_O2:");
            return assembly;
        }
 public void startWizard()
 {			
     var o2Wizard = new O2Wizard("Execute XRule",500,400);
     scriptToExecute = getClickOnceScriptPath();
     
     //scriptToExecute = @"C:\O2\XRulesDatabase\_Rules\HelloWorld.cs.o2";
     if (File.Exists(scriptToExecute))
     {           
    		var compiledAssembly = new CompileEngine().compileSourceFile(scriptToExecute);
    		if (compiledAssembly != null)
    		{
     		add_StepExecuteScript(o2Wizard,compiledAssembly);            
     		o2Wizard.start();
     		return;
     	}
     }
     
     addStep_SelectXRuleToExecute(o2Wizard);
     addStep_CompileScript(o2Wizard);            	
     o2Wizard.start();         
 }
        public static Assembly compileCodeSnippet(this string snippet, Action<string> onCompileOk, Action<string> onCompileFail)
        {
            try
            {
                var codeFile = createCSharpFileFromCodeSnippet(snippet);

                var compileEngine = new CompileEngine();
                var assembly = compileEngine.compileSourceFile(codeFile);
                if (assembly.notNull())
                {
                    onCompileOk("[compileAndExecuteCodeSnippet] Snippet assembly created OK: {0}".format(assembly.location()));
                    return assembly;
                }
                onCompileFail("[compileAndExecuteCodeSnippet] Compilation failed: ".line() + compileEngine.sbErrorMessage.str());
            }
            catch (Exception ex)
            {
                ex.log("[compileAndExecuteCodeSnippet]");
            }
            return null;
        }
Esempio n. 7
0
        public void CompileEngine_Ctor()
        {
            CompileEngine.clearCompilationCache();
            // call the static Ctor to reset the values
            typeof(CompileEngine).invoke_Ctor_Static();

            var compileEngine = new CompileEngine();
            assert_Is_True  (compileEngine.useCachedAssemblyIfAvailable);
            assert_Are_Equal(compileEngine.compilationVersion, "v4.0");
            assert_Not_Empty(CompileEngine.LocalReferenceFolders);

            assert_Not_Empty(CompileEngine.DefaultReferencedAssemblies);
            assert_Not_Empty(CompileEngine.DefaultUsingStatements);
            assert_Not_Empty(CompileEngine.CachedCompiledAssembliesMappingsFile);
            assert_Not_Empty(CompileEngine._specialO2Tag_ExtraReferences);

            assert_Is_Empty(CompileEngine.CachedCompiledAssemblies);
            assert_Is_Empty (CompileEngine.CompilationPathMappings);
            assert_Is_Empty (CompileEngine.LocalScriptFileMappings);
            assert_Is_Empty (CompileEngine.LocalFoldersToSearchForCodeFiles);
            assert_Is_Empty (CompileEngine.LocalFoldersToAddToFileMappings);
        }
Esempio n. 8
0
 private static string getMethodName(string arg0)
 {
     string[] splittedArg0 = arg0.Split('!');
     switch (splittedArg0.Length)
     {
         case 2:
             string file = splittedArg0[0];
             string methodName = splittedArg0[1];
             O2Cmd.log.write("Trying to load file {0} and execute method {1}", file, methodName);
             switch (Path.GetExtension(file))
             {
                 case ".cs":
                     O2Cmd.log.write("\n*.cs file provided, compiling code\n");
                     Assembly assembly = new CompileEngine().compileSourceFile(file);
                     if (assembly == null)
                         O2Cmd.log.write("Error: could not compile provided code");
                     else
                     {
                         O2Cmd.log.write("Source code successfully compiled, loading types\n");
                         foreach (Type typeToLoad in assembly.GetTypes())
                             O2CmdApi.typesWithCommands.Add(typeToLoad);
                         O2Cmd.log.write("\nHere is the updated list of available command line methods\n");
                         O2Cmd.help();
                         O2Cmd.log.write("\nExecuting method:{0}\n", methodName);
                         return methodName;
                     }
                     break;
                 case ".dll":
                     break;
                 default:
                     O2Cmd.log.error("ERROR: unsupported file extension (it must be *.cs or *.dll");
                     break;
             }
             return "";
         default:
             return arg0;
     }
     //return arg0;
 }
Esempio n. 9
0
        // we need to use CompileEngine (which is slower but supports multiple file compilation
        public void compileExtraSourceCodeReferencesAndUpdateReferencedAssemblies()
        {
            if (ExtraSourceCodeFilesToCompile.size() > 0)
            {
                "[CSharp Compiler] Compiling provided {0} external source code references".info(ExtraSourceCodeFilesToCompile.size());
                var assembly = new CompileEngine(UseCachedAssemblyIfAvailable).compileSourceFiles(ExtraSourceCodeFilesToCompile);
                if (assembly != null)
                {

                    ReferencedAssemblies.Add(assembly.Location);
                    CompileEngine.setCachedCompiledAssembly(ExtraSourceCodeFilesToCompile, assembly);
                    generateDebugSymbols = true;                // if there are extra assemblies we can't generate the assembly in memory
                }
            }
        }
Esempio n. 10
0
 public static string getCachedCompiledAssembly(string scriptOrFile, bool compileIfNotFound)
 {
     if (CachedCompiledAssemblies.hasKey(scriptOrFile))
     {
         var pathToDll = CachedCompiledAssemblies[scriptOrFile];
         if (scriptOrFile.isFile())
             "in getCachedCompiledAssembly, mapped file '{0}' to cached assembly '{1}'".debug(scriptOrFile, pathToDll);
         else
             "in getCachedCompiledAssembly, found cached assembly for script/md5hash with size '{0}' to cached assembly '{1}'".debug(scriptOrFile.size(), pathToDll);
         return pathToDll;
     }
     if (compileIfNotFound.isFalse())
         return null;
     var mappedFile = CompileEngine.findScriptOnLocalScriptFolder(scriptOrFile);
     //var sourceCode = mappedFile.fileContents();
     //if (sourceCode.contains("//generateDebugSymbols").isFalse())
         //sourceCode += "//generateDebugSymbols".lineBefore();
     var assembly = new CompileEngine().compileSourceFile(mappedFile);
     if (assembly != null && assembly.Location.fileExists())
     {
         var pathToDll = assembly.Location;
         //CachedCompiledAssemblies.add(scriptOrFile, pathToDll);
         //CachedCompiledAssemblies.add(assembly.GetName().Name, pathToDll);
         CompileEngine.setCachedCompiledAssembly(scriptOrFile, assembly);
         "in getCachedCompiledAssembly, compiled file '{0}' to assembly '{1}' (and added it to CachedCompiledAssembly)".debug(scriptOrFile, pathToDll);
         return assembly.Location;
     }
     return "";
 }
Esempio n. 11
0
        public static void handleReferencedAssembliesInstallRequirements(string fileOrCode)
        {
            var specialTag = "//Installer:";
            var code = (fileOrCode.isFile()) ? fileOrCode.fileContents() : fileOrCode;
            if (code.contains(specialTag))
            {
                foreach (var line in code.lines().containing(specialTag))
                {
                    var refs = line.remove(specialTag).split("!");
                    if (refs.size() != 2)
                        "[handleReferencedAssembliesInstallRequirements] there should be two values in the {0} reference (1st O2 script, 2nd: expected dll".error(specialTag);
                    else
                    {
                        var o2Script = refs.first();
                        var expectedFile = refs.second();
                        //if (expectedDll.assembly().isNull())
                        if (expectedFile.local().fileExists().isFalse()) //mapping it to the file instead of an assembly (to support unmanaged exes)
                        {
                            "[handleReferencedAssembliesInstallRequirements] expected assembly not found ('{0}'), so running installer script: '{1}'".info(expectedFile, o2Script);
                            var assembly = new CompileEngine().compileSourceFile(o2Script.local());
                            if (assembly.notNull())
                            {
                                var installType = assembly.type(o2Script.fileName_WithoutExtension());
                                if (installType.isNull())
                                    "[handleReferencedAssembliesInstallRequirements] could not find expected type: {0}".error(o2Script.fileName_WithoutExtension());
                                else
                                {
                                    installType.ctor(); // the installer is supposed to be triggered by the  constructor
                                    //if (expectedFile.assembly().isNull())
                                    if (expectedFile.local().fileExists().isFalse())
                                        "[handleReferencedAssembliesInstallRequirements] after install requested assembly still not found: '{0}'".error(expectedFile);
                                    else
                                        "[handleReferencedAssembliesInstallRequirements] after install requested assembly is now available: '{0}'".info(expectedFile);
                                }
                            }
                        }
                    }

                }
            }
        }
 public static List<String> compileAllFilesIndividually(List<String> filesToCompile, Action<string> currentTask, Action<int> numberOfStepsToPerform, Action onStepEvent)
 {
     currentTask("Compiling all rules individualy (one file at the time)");
     numberOfStepsToPerform(filesToCompile.Count);
     var compileEngine = new CompileEngine();
     PublicDI.log.info("Compiling All XRules source code files ONE at the time");
     var results = new List<String>();
     foreach (var fileToCompile in filesToCompile)
     {
         var assembly = compileEngine.compileSourceFile(fileToCompile);
         if (assembly != null)
             results.Add(assembly.Location);
         else
             PublicDI.log.error("In XRules_Execution.compileAllFilesIndividually, could not compile file: {0}", fileToCompile);
         onStepEvent();
     }
     return results;
 }
		public static API_CatNet_GUI scanCSharpFile(this API_CatNet_GUI catNetGui, string file)	
		{
			catNetGui.SolutionLoaded = "";
			catNetGui.TriggerOnSelectedEvent = false;
			var catNet = new API_CatNet().loadRules(); 
			var assembly = new CompileEngine().compileSourceFile(file);
			if (assembly.notNull())			
			{
				catNetGui.openReport(catNet.scan(assembly).savedReport());				
			}
			else
				catNetGui.CodeViewer.open(file);					
			return catNetGui;	
		}
        public void onCompileScript(IStep step)
        {
            O2Thread.mtaThread(
                ()=>
                    {
                        step.clear();
                        //var panel = step.FirstControl; 
                        step.add_Label("Compiling Script:" +  scriptToExecute);

                        var compileEngine = new CompileEngine();
                        var compiledAssembly = compileEngine.compileSourceFile(scriptToExecute);
                        if (compiledAssembly != null)					
                        {
                            var label = step.add_Label("Compilation was ok", 20);
                            label.ForeColor = Color.DarkGreen;
                            step.add_Label("Which method to you want to execute?", 40);
                            var top = 40;
                            foreach(var method in PublicDI.reflection.getMethods(compiledAssembly))
                            {
                                if (PublicDI.reflection.getParameters(method).Count ==0 && 
                                    method.Name.Contains(">b") == false)
                                {
                                    var methodToExecute = method;
                                    step.add_Link(method.Name , top+=20 ,10 ,
                                                  ()=> PublicDI.reflection.invoke(methodToExecute));
                                };
                            }							
                        }
                        else
                        {
                            var label = step.add_Label("Compilation Failed", 20);
                            label.ForeColor = Color.DarkRed;
                            step.add_Label(compileEngine.sbErrorMessage.ToString(), 40);                            
                        }
						
                    });			   
        }
    	public static bool compileAndOpen(this API_NUnit_Gui nUnitGui, string fileToCompile)
    	{
    		var assembly = new CompileEngine().compileSourceFile(fileToCompile);
			if (assembly.notNull())
			{
				var location = assembly.Location; 			
				nUnitGui.openProject(location);			
				return true;
			}
			return false;
    	}
 public static void mapUnitTestToXRules(string assemblyWithUnitTest, TreeView tvTarget_XLoadedRules)
 {
     if (Files.IsExtension(assemblyWithUnitTest,".cs"))
     {
         var compiledAssembly = new CompileEngine().compileSourceFile(assemblyWithUnitTest);
         if (compiledAssembly == null)
             DI.log.error("aborting mapUnitTestToXRules since could not compile CSharp file: {0}",
                          assemblyWithUnitTest);
         else
         {
             DI.log.info("Mapping dynamically compiled CSharp file: {0}", compiledAssembly.Location);
             mapAssembliesIntoXRules(new List<string>() {compiledAssembly.Location}, tvTarget_XLoadedRules);
         }
     }
     else
         mapAssembliesIntoXRules(new List<string>() { assemblyWithUnitTest }, tvTarget_XLoadedRules);
 }
        public Assembly compileCSSharpFile()
        {
            enableCodeComplete();
            compiledAssembly = null;
            var compileEngine = new CompileEngine();
            if (getSourceCode() != "")
            {
                saveSourceCode();
                // always save before compiling
                compileEngine.compileSourceFile(sPathToFileLoaded);
                compiledAssembly = compileEngine.compiledAssembly;
                if (compiledAssembly.notNull() && o2CodeCompletion.notNull() && compileEngine.cpCompilerParameters.notNull())
                    o2CodeCompletion.addReferences(compileEngine.cpCompilerParameters.ReferencedAssemblies.toList());
            }

            var state = compiledAssembly == null && compileEngine.sbErrorMessage != null;
            //btShowHideCompilationErrors.visible(state);
            //btShowHideCompilationErrors.prop("Visible",state);
            btShowHideCompilationErrors.visible(state);
            tvCompilationErrors.visible(state);
            lbCompilationErrors.visible(state);
            //lbCompilationErrors.prop("Visible", state);

            clearBookmarksAndMarkers();
            // if there isn't a compiledAssembly, show errors
            if (compiledAssembly == null)
            {
                CompileEngine_WinForms.addErrorsListToTreeView(tvCompilationErrors, compileEngine.sbErrorMessage);
                showErrorsInSourceCodeEditor(compileEngine.sbErrorMessage.str());
            }
             /*   else
            {
                if (compiledFileAstData.notNull())
                    compiledFileAstData.Dispose();
                compiledFileAstData = new O2MappedAstData(sPathToFileLoaded);
            }*/

            return compiledAssembly;
        }
        public object GetCurrentCSharpObjectModel()
        {
            var timer = new O2Timer("Calculated O2 Object Model for referencedAssesmblies").start();
            var signatures = new List<string>();
            var referencedAssemblies = new CompileEngine().getListOfReferencedAssembliesToUse();

            //compileEngine.lsGACExtraReferencesToAdd();
            foreach (var referencedAssesmbly in referencedAssemblies)
                if (File.Exists(referencedAssesmbly))
                    signatures.AddRange(PublicDI.reflection.getMethods(referencedAssesmbly)
                              .Select(method => new FilteredSignature(method).sSignature));
            timer.stop();
            return signatures;
        }