static void Main(string[] args)
 {         	
 	//AppDomain.CurrentDomain.UnhandledException += new  UnhandledExceptionEventHandler((sender,e)=> { Console.WriteLine(e.ExceptionObject); } );
 	 
     if (Control.ModifierKeys == Keys.Shift)
     	showLogViewer();       //.parentForm().width(1000).height(400);                
     var firstScript = AppDomain.CurrentDomain.BaseDirectory.pathCombine("AppScan_Standard_1st_Script.cs");           
     Console.WriteLine("Welcome to the O2 Platform ...");
     Console.WriteLine("Launching IBM AppScan Standard ...");
     
     "Current AppDomain: {0}".info(AppDomain.CurrentDomain.BaseDirectory);
    	
     //CompileEngine.lsGACExtraReferencesToAdd.Clear();
     var assembly = new CompileEngine().compileSourceFile(firstScript);
     if (assembly.notNull())           
     {
         Console.WriteLine("Executing script {0} from location {1}".info(firstScript, assembly.Location));
         if (assembly.methods().size()>0)
         {
             assembly.methods()[0].invoke();
             Console.WriteLine("Invocation complete".info());
         }
         else 
             Console.WriteLine("Error: there were no methods in compiled assembly".error());           
     }
     else
         Console.WriteLine("Error: could not find, compile or execute first script ({0})".error(firstScript));            
 
 }               
        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);
                "in getCachedCompiledAssembly, compiled file '{0}' to assembly '{1}' (and added it to CachedCompiledAssembly)".debug(scriptOrFile, pathToDll);
                return(assembly.Location);
            }
            return("");
        }
		public static string compileIntoDll_inFolder(this string fileToCompile, string targetFolder)
		{
			"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().compileSourceFiles(new List<string> {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);
		}
Exemple #5
0
 public string compileFileToExe()
 {   
     var assembly = new  CompileEngine().compileSourceFiles(new List<string> {scriptToInstrument} ,"O2_Scanner_DotNet._TestScripts.TestScript_MultipleCalls");
     Assert.That(assembly!= null);
     Assert.That(Path.GetExtension(assembly.Location) == ".exe");
     log.debug("File Successfully compiled: {0}", assembly.Location);    		
     log.info("compileFileToExe executed ok");
     return assembly.Location;
 } 
		public override void create()
		{
			this.ButtonText = "O2 Script - with Panel";			
			this.ToolTip = "Opens the O2 Script Guid (with a top panel)";
			this.TargetMenu = "O2 Platform";
			base.create();
			this.Execute = () =>
						{
							var script = "ascx_Quick_Development_GUI.cs.o2".local();
							var assembly = new CompileEngine().compileSourceFile(script);
							assembly.methods()[0].invoke(new object[] { });
							//assembly.executeFirstMethod();
						};
		}
 public static List<String> compileAllFilesIndividually(List<String> filesToCompile, O2Thread.FuncVoidT1<string> currentTask, O2Thread.FuncVoidT1<int> numberOfStepsToPerform, O2Thread.FuncVoid 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 bool isFileAReferenceARequestToUseThePrevioulsyCompiledVersion(string fileToResolve, List <string> ReferencedAssemblies)
        {
            if (fileToResolve.starts("Ref:"))
            {
                fileToResolve = fileToResolve.remove("Ref:");
                var fileRef = CompileEngine.getCachedCompiledAssembly(fileToResolve);

                if (fileRef.valid() && fileRef.fileExists())
                {
                    if (ReferencedAssemblies.contains(fileRef).isFalse())
                    {
                        ReferencedAssemblies.add(fileRef);
                    }
                }
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #9
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;
 }
		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 static Process console_Run(this API_NUnit nUnitApi, string target, string extraStartupOptions, Action<string> consoleOut)
    	{    		
    		if (target.extension(".cs"))
    		{
    			var assembly = new CompileEngine().compileSourceFile(target);
				if (assembly.isNull())
				{
					"[API_NUnit][console_Run] failed to compile C# file: {0}".error(target);
					return null;
				}
				target = assembly.Location;
    		}
    		var startUpOptions = "\"{0}\" {1}".format(target ?? "" , extraStartupOptions ?? "");
    		return nUnitApi.executeNUnitConsole(startUpOptions , consoleOut);
    	}	
        public void compileTestFileAndCheckIfAllIsStillThere()
        {
            if (false == compiledAssemblySettings.dontCompileIfFileExists ||
                false == File.Exists(compiledAssemblySettings.pathToCreatedAssemblyFile))
            {
                Assembly compiledExeFile = new CompileEngine().compileSourceCode(compiledAssemblySettings.sourceCode,
                                                                     compiledAssemblySettings.exeMainClass,
                                                                     compiledAssemblySettings.outputAssemblyName);
                // copy all dependentDlls to current directly (so that we can load this exe)

                Assert.That(compiledExeFile != null, "in MockObjects_CompiledExe.compileTestFileAndCheckIfAllIsStillThere Compiled Assembly was null");
                CecilAssemblyDependencies.copyAssemblyDependenciesToAssemblyDirectory(compiledExeFile.Location,
                                                                                      new List<string>
                                                                                          {
                                                                                              DI.config.
                                                                                                  hardCodedO2LocalBuildDir
                                                                                          });

                Assert.That(compiledExeFile != null, "Compilation failed");
                Assert.That(File.Exists(compiledExeFile.Location), "Could not find assembly on disk!");
                DI.log.info("test Assembly file compiled into: {0}", compiledExeFile);
                compiledAssemblySettings.pathToCreatedAssemblyFile = compiledExeFile.Location;
                Assert.That(compiledAssemblySettings.checkIfAssemblyWasCreatedOK(), "Created assembly was not OK");
            }
        }
        public static void addSourceFileOrFolderIncludedInSourceCode(List <string> sourceCodeFiles, List <string> referencedAssemblies)
        {
            var currentSourceDirectories = new List <string>(); // in case we need to resolve file names below

            foreach (var file in sourceCodeFiles)
            {
                if (file.valid())
                {
                    var directory = Path.GetDirectoryName(file);
                    if (false == currentSourceDirectories.Contains(directory))
                    {
                        currentSourceDirectories.Add(directory);
                    }
                }
            }

            var filesToAdd = new List <string>();

            // find the extra files to add
            foreach (var sourceCodeFile in sourceCodeFiles)
            {
                if (sourceCodeFile.valid() && sourceCodeFile.extension(".h2").isFalse())
                {
                    var fileLines = Files.getFileLines(sourceCodeFile);
                    foreach (var fileLine in fileLines)
                    {
                        var match = StringsAndLists.TextStartsWithStringListItem(fileLine, specialO2Tag_ExtraSourceFile);
                        if (match != "")
                        {
                            //   var file = fileLine.Replace(specialO2Tag_ExtraSourceFile, "").Trim();
                            var file = fileLine.Replace(match, "").Trim();
                            if (false == sourceCodeFiles.Contains(file) && false == filesToAdd.Contains(file))
                            {
                                //handle the File:xxx:Ref:xxx case
                                if (CompileEngine.isFileAReferenceARequestToUseThePrevioulsyCompiledVersion(file, referencedAssemblies)
                                    .isFalse())
                                {
                                    filesToAdd.Add(file);
                                }
                            }
                        }
                        //else if (fileLine.StartsWith(specialO2Tag_ExtraFolder))
                        else
                        {
                            match = StringsAndLists.TextStartsWithStringListItem(fileLine, specialO2Tag_ExtraFolder);
                            if (match != "")
                            {
                                var folder = fileLine.Replace(match, "").Trim();
                                if (false == Directory.Exists(folder))
                                {
                                    foreach (var path in currentSourceDirectories)
                                    {
                                        if (Directory.Exists(Path.Combine(path, folder)))
                                        {
                                            folder = Path.Combine(path, folder);
                                            break;
                                        }
                                    }
                                }
                                foreach (var file in Files.getFilesFromDir_returnFullPath(folder, "*.cs", true))
                                {
                                    if (false == sourceCodeFiles.Contains(file) && false == filesToAdd.Contains(file))
                                    {
                                        filesToAdd.Add(file);
                                    }
                                }
                            }

                            else
                            {
                                match = StringsAndLists.TextStartsWithStringListItem(fileLine, specialO2Tag_PathMapping);
                                if (match != "")
                                {
                                    addCompilationPathMappings(fileLine.remove(match));
                                }
                            }
                        }
                    }
                }
            }

            applyCompilationPathMappings(filesToAdd);

            // add them to the list (checking if the file exist)
            if (filesToAdd.Count > 0)
            {
                PublicDI.log.info("There are {0} extra files to add to the list of source code files to compile: {0}", filesToAdd.Count);
                foreach (var file in filesToAdd)
                {
                    var filePath = "";
                    if (File.Exists(file))
                    {
                        filePath = file;
                    }
                    else
                    {
                        // try to find the file in the current sourceCodeFiles directories
                        foreach (var directory in currentSourceDirectories)
                        {
                            if (File.Exists(Path.Combine(directory, file)))
                            {
                                filePath = Path.Combine(directory, file);
                                break;
                            }
                        }
                        if (filePath.fileExists().isFalse())
                        {
                            filePath = findScriptOnLocalScriptFolder(file);
                        }

                        if (filePath == "")
                        {
                            PublicDI.log.error("in addSourceFileOrFolderIncludedInSourceCode, could not file file to add: {0}", file);
                        }
                    }
                    if (filePath != "")
                    {
                        filePath = Path.GetFullPath(filePath);
                        if (false == sourceCodeFiles.lower().Contains(filePath.lower()))
                        {
                            sourceCodeFiles.Add(filePath);
                            addSourceFileOrFolderIncludedInSourceCode(sourceCodeFiles, referencedAssemblies); // we need to recursively add new new dependencies
                        }
                    }
                }
            }
        }
        private 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))
                    foreach (var method in PublicDI.reflection.getMethods(referencedAssesmbly))
                        signatures.Add(new FilteredSignature(method).sSignature);
            timer.stop();
            return signatures;
        }
        //public ascx_ScriptsFolder scriptsFolder;

/*        public void addCurrentAppDomainsDllsAsReferences()
        {
            foreach(var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var assemblyName = Path.GetFileName(assembly.Location);
                if (false == lsExtraReferenceAssembliesToAdd.Contains(assemblyName))
                    if (assemblyName.IndexOf("JetBrains")==-1 && 
                        assemblyName.IndexOf("VisualStudio") == -1 &&
                        assemblyName.IndexOf("SMDiagnostics") == -1) // don't add these assemblies
                        lsExtraReferenceAssembliesToAdd.Add(assemblyName);

            }
        }*/


        public void compileSourceCode()
        {
            if (sourceCodeEditor.partialFileViewMode == false)

                if (this.okThread(delegate { compileSourceCode(); }))
                {
                    var lsExtraReferencesToAdd = new List<string>(); //lsExtraReferenceAssembliesToAdd.ToArray());
                    String sErrorMessages = "";
                    var compileEngine = new CompileEngine();
                    Assembly aCompiledAssembly = null;
                    if (tbExtraReferencesToAdd.Text != "")
                        lsExtraReferencesToAdd.AddRange(tbExtraReferencesToAdd.Text.Split(new[] {Environment.NewLine},
                                                                                          StringSplitOptions.
                                                                                              RemoveEmptyEntries));

                    lbSourceCode_CompilationResult.Items.Clear();
                    var exeMainClass = (rbCreateExe.Checked) ? tbMainClass.Text : "";
                    var outputAssemblyName = ""; // todo expose outputAssemblyName on GUI        

                    //DI.config.addPathToCurrentExecutableEnvironmentPathVariable(DI.config.O2TempDir);

                    sourceCodeEditor.saveSourceCode();
                    var filesToCompile = new List<String> {sourceCodeEditor.sPathToFileLoaded};
                    if (compileEngine.compileSourceFiles(filesToCompile, lsExtraReferencesToAdd.ToArray(),
                                                         ref aCompiledAssembly, ref sErrorMessages, false /*verbose*/,
                                                         exeMainClass,
                                                         outputAssemblyName))
                    {
                        // if we only have 1 class in the completed code, set tbMainClass.Text to it
                        if (aCompiledAssembly.GetTypes().Length == 1)
                            tbMainClass.Text = aCompiledAssembly.GetTypes()[0].FullName;
                        lbSourceCode_CompilationResult.ForeColor = Color.Black;
                        lbSourceCode_CompilationResult.Items.Add("No errors");
                        O2Messages.dotNetAssemblyAvailable(aCompiledAssembly.Location);
                        //if (assemblyInvoke != null)
                        //    assemblyInvoke.loadAssembly(aCompiledAssembly, cbAutoExecuteOnMethodCompile.Checked);
                    }
                    else
                    {
                        //assemblyInvoke.setControlsEnableState(false);
                        lbSourceCode_CompilationResult.ForeColor = Color.Red;
                        CompileEngine_WinForms.addErrorsListToListBox(sErrorMessages, lbSourceCode_CompilationResult);
                    }
                    if (cbAutoSaveOnCompile.Checked)
                        sourceCodeEditor.saveSourceCode();
                }
        }
Exemple #16
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);
         "in getCachedCompiledAssembly, compiled file '{0}' to assembly '{1}' (and added it to CachedCompiledAssembly)".debug(scriptOrFile, pathToDll);
         return assembly.Location;
     }
     return "";
 }
Exemple #17
0
    	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 static bool compileAndOpen(this API_NUnit nUnitApi, string fileToCompile, string extraStartupOptions)
    	{
    		var assembly = new CompileEngine().compileSourceFile(fileToCompile);
			if (assembly.notNull()) 
			{
				var location = assembly.Location; 			
				nUnitApi.openNUnitGui(location, extraStartupOptions);			
				return true;
			}
			return false;
    	}
		public Assembly compileScript(string o2Script)
		{
			var assembly = new CompileEngine().compileSourceFile(o2Script.local());
			return assembly;
		}
        public Assembly compileCSSharpFile()
        {
            Assembly compiledAssembly = null;
            var compileEngine = new CompileEngine();            
            if (getSourceCode() != "")
            {
                saveSourceCode();
                // always save before compiling                                                
                compileEngine.compileSourceFile(sPathToFileLoaded);
                compiledAssembly = compileEngine.compiledAssembly ?? null;
                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);
            tvCompilationErrors.visible(state);
            lbCompilationErrors.prop("Visible", state);
                
            

            clearBookmarksAndMarkers();
            // if there isn't a compiledAssembly, show errors
            if (compiledAssembly == null)
            {
                compileEngine.addErrorsListToTreeView(tvCompilationErrors);
                showErrorsInSourceCodeEditor(compileEngine.sbErrorMessage.str());
            }
            else
            {
                if (compiledFileAstData.notNull())
                    compiledFileAstData.Dispose();
                compiledFileAstData = new O2MappedAstData(sPathToFileLoaded);
            }
            
            return compiledAssembly;
        }
 // we need to use CompileEngine (which is slower but supports multiple file compilation 
 public void compileExtraSourceCodeReferencesAndUpdateReferencedAssemblies()
 {            
     if (ExtraSourceCodeFilesToCompile.size() > 0)
     {                        
         var assembly = new CompileEngine().compileSourceFiles(ExtraSourceCodeFilesToCompile);                
         if (assembly != null)
         {
             ReferencedAssemblies.Add(assembly.Location);
             generateDebugSymbols = true;                // if there are extra assemblies we can't generate the assembly in memory                    
         }
     }
 }