public void Constructor0_Deny_Unrestricted () { TempFileCollection tfc = new TempFileCollection (); Assert.AreEqual (0, tfc.Count, "Count"); Assert.IsFalse (tfc.KeepFiles, "KeepFiles"); Assert.AreEqual (String.Empty, tfc.TempDir, "TempDir"); tfc.AddFile ("main.cs", false); tfc.CopyTo (array, 0); tfc.Delete (); (tfc as IDisposable).Dispose (); }
CompilerResults CompileAssemblyFromReader(CompilerParameters options, params TextReader[] readers) { var tempFiles = new TempFileCollection(Path.GetTempPath(), false); for (int i = 0; i < readers.Length; i++) { string file = tempFiles.AddExtension(FileExtension, false); File.WriteAllText(file, readers[i].ReadToEnd()); } var fileNames = new string[tempFiles.Count]; tempFiles.CopyTo(fileNames, 0); var results = CompileAssemblyFromFile(options, fileNames); tempFiles.Delete(); return results; }
/// <summary> /// Generates XmlSerializers assembly for this assembly, allowing faster startup with xml serialization. /// </summary> public static void SGenThisAssembly() { var xmlRootTypes = new List<Type>(); var assembly = typeof(Utilities).Assembly; var mappings = new List<XmlMapping>(); var allXmlTypeToSerialize = new List<Type>(); var importer = new XmlReflectionImporter(); foreach (var type in assembly.GetTypes()) { if (type.GetCustomAttributes(typeof(XmlRootAttribute), true).Length > 0) { xmlRootTypes.Add(type); ImportXmlTypes(type, mappings, allXmlTypeToSerialize, importer); } } if (allXmlTypeToSerialize.Count == 0) return; string assemblySerializer = XmlSerializer.GetXmlSerializerAssemblyName(allXmlTypeToSerialize[0], null) + ".dll"; var assemblySerializerTime = File.GetLastWriteTime(assemblySerializer); if (!File.Exists(assemblySerializer) || File.GetLastWriteTime(typeof(Utilities).Assembly.Location) > assemblySerializerTime) { // Delete previous assembly File.Delete(assemblySerializer); // Regenerate assembly var parameters = new CompilerParameters(); string codePath = Path.GetDirectoryName(assembly.Location); var files = new TempFileCollection(codePath, false); parameters.TempFiles = files; parameters.GenerateInMemory = false; parameters.IncludeDebugInformation = true; parameters.GenerateInMemory = false; XmlSerializer.GenerateSerializer(allXmlTypeToSerialize.ToArray(), mappings.ToArray(), parameters); files.Delete(); } else { Assembly.LoadFrom(assemblySerializer); } }
/* * Compiles an assembly from source files */ private static Assembly CompileAssembly(string OutputAssemblyPath, List<string> SourceFileNames, List<string> ReferencedAssembies, List<string> PreprocessorDefines = null, bool TreatWarningsAsErrors = false) { var TemporaryFiles = new TempFileCollection(); // Setup compile parameters var CompileParams = new CompilerParameters(); { // Always compile the assembly to a file on disk, so that we can load a cached version later if we have one CompileParams.GenerateInMemory = false; // This is the full path to the assembly file we're generating CompileParams.OutputAssembly = OutputAssemblyPath; // We always want to generate a class library, not an executable CompileParams.GenerateExecutable = false; // Always fail compiles for warnings CompileParams.TreatWarningsAsErrors = true; // Always generate debug information as it takes minimal time CompileParams.IncludeDebugInformation = true; #if !DEBUG // Optimise the managed code in Development CompileParams.CompilerOptions += " /optimize"; #endif Log.TraceVerbose("Compiling " + OutputAssemblyPath); // Keep track of temporary files emitted by the compiler so we can clean them up later CompileParams.TempFiles = TemporaryFiles; // Warnings as errors if desired CompileParams.TreatWarningsAsErrors = TreatWarningsAsErrors; // Add assembly references { if (ReferencedAssembies == null) { // Always depend on the CLR System assembly CompileParams.ReferencedAssemblies.Add("System.dll"); } else { // Add in the set of passed in referenced assemblies CompileParams.ReferencedAssemblies.AddRange(ReferencedAssembies.ToArray()); } // The assembly will depend on this application var UnrealBuildToolAssembly = Assembly.GetExecutingAssembly(); CompileParams.ReferencedAssemblies.Add(UnrealBuildToolAssembly.Location); } // Add preprocessor definitions if (PreprocessorDefines != null && PreprocessorDefines.Count > 0) { CompileParams.CompilerOptions += " /define:"; for (int DefinitionIndex = 0; DefinitionIndex < PreprocessorDefines.Count; ++DefinitionIndex) { if (DefinitionIndex > 0) { CompileParams.CompilerOptions += ";"; } CompileParams.CompilerOptions += PreprocessorDefines[DefinitionIndex]; } } // @todo: Consider embedding resources in generated assembly file (version/copyright/signing) } // Create the output directory if it doesn't exist already DirectoryInfo DirInfo = new DirectoryInfo( Path.GetDirectoryName( OutputAssemblyPath ) ); if( !DirInfo.Exists ) { try { DirInfo.Create(); } catch( Exception Ex ) { throw new BuildException( Ex, "Unable to create directory '{0}' for intermediate assemblies (Exception: {1})", OutputAssemblyPath, Ex.Message ); } } // Compile the code CompilerResults CompileResults; try { // Enable .NET 4.0 as we want modern language features like 'var' var ProviderOptions = new Dictionary<string, string>() { { "CompilerVersion", "v4.0" } }; var Compiler = new CSharpCodeProvider( ProviderOptions ); CompileResults = Compiler.CompileAssemblyFromFile( CompileParams, SourceFileNames.ToArray() ); } catch( Exception Ex ) { throw new BuildException( Ex, "Failed to launch compiler to compile assembly from source files '{0}' (Exception: {1})", SourceFileNames.ToString(), Ex.Message ); } // Display compilation errors if( CompileResults.Errors.Count > 0 ) { Log.TraceInformation("Errors detected while compiling {0}:", OutputAssemblyPath); foreach( var CurError in CompileResults.Errors ) { Log.TraceInformation( CurError.ToString() ); } throw new BuildException( "UnrealBuildTool encountered an error while compiling source files" ); } // Grab the generated assembly Assembly CompiledAssembly = CompileResults.CompiledAssembly; if( CompiledAssembly == null ) { throw new BuildException( "UnrealBuildTool was unable to compile an assembly for '{0}'", SourceFileNames.ToString() ); } // Clean up temporary files that the compiler saved TemporaryFiles.Delete(); return CompiledAssembly; }
string CompileAndGetOutput(string fileContent) { TempFileCollection tf = new TempFileCollection (); string path = Path.Combine(tf.BasePath, tf.TempDir); Directory.CreateDirectory(path); string generatedScript = Path.Combine(path, "InternalGeneratedScript.cs"); string generatedDLL = Path.Combine(path, "A.DLL"); tf.AddFile(generatedScript, false); tf.AddFile(generatedDLL, false); StreamWriter sw = new StreamWriter(generatedScript); sw.Write(fileContent); sw.Close(); string output = String.Empty; string error = String.Empty; Executor.ExecWaitWithCapture(GetCompilerName() + " /target:library \"/out:" + generatedDLL + "\" \"" + generatedScript +"\"", tf, ref output, ref error); if (!File.Exists(generatedDLL)) { StreamReader sr = File.OpenText(output); string errorMessage = sr.ReadToEnd(); sr.Close(); MessageService.ShowMessage(errorMessage); return ">>>>ERROR IN CODE GENERATION GENERATED SCRIPT WAS:\n" + fileContent + "\n>>>>END"; } Assembly asm = Assembly.Load(GetBytes(generatedDLL)); object templateInstance = asm.CreateInstance("Template"); foreach (TemplateProperty property in item.Properties) { FieldInfo fieldInfo = templateInstance.GetType().GetField(property.Name); fieldInfo.SetValue(templateInstance, Convert.ChangeType(StringParser.Properties["Properties." + property.Name], property.Type.StartsWith("Types:") ? typeof(string): Type.GetType(property.Type))); } MethodInfo methodInfo = templateInstance.GetType().GetMethod("GenerateOutput"); string ret = methodInfo.Invoke(templateInstance, null).ToString(); tf.Delete(); return ret; }
//TODO: Image type needs to be more dynamically chosen... public static DeckModel OpenPPT(FileInfo file, BackgroundWorker worker, DoWorkEventArgs progress) { //Start the progress bar if (worker != null) { worker.ReportProgress(0, " Initializing..."); } //Make the default flat tree representation of the PPT //Try to detect if powerpoint is already running (powerpnt.exe) bool pptAlreadyRunning = false; Process[] processes = Process.GetProcesses(); for (int i = 0; i < processes.Length; i++) { string currentProcess = processes[i].ProcessName.ToLower(); if (currentProcess == "powerpnt") { pptAlreadyRunning = true; break; } } //Open PowerPoint + open file PowerPoint.Application pptapp = null; try { pptapp = new PowerPoint.Application(); } catch (Exception e) { throw new PPTNotInstalledException("Failed to create PowerPoint Application. See InnerException for details.", e); } PowerPoint._Presentation presentation; try { presentation = pptapp.Presentations.Open(file.FullName, Core.MsoTriState.msoTrue, Core.MsoTriState.msoFalse, Core.MsoTriState.msoFalse); } catch (Exception e) { throw new PPTFileOpenException("Failed to open PowerPoint file. See InnerException for details.", e); } //Initialize the PPT Shape tag reader PPTPaneManagement.PPTPaneManager pptpm = new PPTPaneManagement.PPTPaneManager(); //Create a new DeckModel Guid deckGuid = Guid.Empty; try { string g = presentation.Tags["WEBEXPORTGUID"]; if (g == "") { deckGuid = Guid.NewGuid(); } else { deckGuid = new Guid(g); } } catch { deckGuid = Guid.NewGuid(); } DeckModel deck = new DeckModel(deckGuid, DeckDisposition.Empty, file.Name); //Initialize a temporary file collection that will be where slide images are exported to TempFileCollection tempFileCollection = new TempFileCollection(); string dirpath = tempFileCollection.BasePath; if (!Directory.Exists(dirpath)) { Directory.CreateDirectory(dirpath); } else { Directory.Delete(dirpath, true); Directory.CreateDirectory(dirpath); } //Lock it using(Synchronizer.Lock(deck.SyncRoot)) { //Iterate over all slides for (int i = 1; i <= presentation.Slides.Count; i++) { if (progress != null && progress.Cancel) break; //Get the slide PowerPoint._Slide currentSlide= presentation.Slides[i]; if (currentSlide.SlideShowTransition.Hidden == Core.MsoTriState.msoTrue) continue; SlideModel newSlideModel = CreateSlide(presentation.PageSetup, pptpm, deck, tempFileCollection, dirpath, currentSlide); //Create a new Entry + reference SlideModel TableOfContentsModel.Entry newEntry = new TableOfContentsModel.Entry(Guid.NewGuid(), deck.TableOfContents, newSlideModel); //Lock the TOC using(Synchronizer.Lock(deck.TableOfContents.SyncRoot)) { //Add Entry to TOC deck.TableOfContents.Entries.Add(newEntry); } //Increment the ProgressBarForm if (worker != null) { worker.ReportProgress((i * 100) / presentation.Slides.Count, " Reading slide " + i + " of " + presentation.Slides.Count); } } } //Close the presentation presentation.Close(); presentation = null; //If PowerPoint was not open before, close PowerPoint if (!pptAlreadyRunning) { pptapp.Quit(); pptapp = null; } GC.Collect(); //Delete temp directory tempFileCollection.Delete(); Directory.Delete(dirpath); if (worker != null) worker.ReportProgress(100, " Done!"); //Return the deck if (progress != null) progress.Result = deck; return deck; }
/// <summary> /// Executes the alphabetize operation on the set of RESX files. /// </summary> /// <param name="filename"> /// The name of the RESX file to alphabetize. /// </param> /// <seealso cref="Paraesthesia.Tools.NAntTasks.AlphaResx.AlphaResxTask" /> protected virtual void AlphabetizeResxFile(string filename) { TempFileCollection tempFiles = null; try { tempFiles = new TempFileCollection(); tempFiles.KeepFiles = false; if (!Directory.Exists(tempFiles.BasePath)) { Directory.CreateDirectory(tempFiles.BasePath); } string tfName = Path.Combine(tempFiles.BasePath, Path.GetFileName(filename)); using (ResXResourceReader reader = new ResXResourceReader(filename)) { // Add the resources to a dictionary that will be sorted later. Dictionary<string, object> resources = new Dictionary<string, object>(); IDictionaryEnumerator id = reader.GetEnumerator(); foreach (DictionaryEntry d in reader) { resources.Add(d.Key.ToString(), d.Value); } // Write the resources to a temporary file in alpha order by key. using (ResXResourceWriter writer = new ResXResourceWriter(tfName)) { List<string> resourceKeys = new List<string>(); resourceKeys.AddRange(resources.Keys); resourceKeys.Sort(); foreach (string key in resourceKeys) { writer.AddResource(key, resources[key]); } writer.Generate(); writer.Close(); } } // Copy temp file over original file if (File.Exists(tfName)) { File.Copy(tfName, filename, true); this.Log(Level.Info, "Alphabetized RESX file {0}", filename); } else { if (this.FailOnError) { throw new BuildException(String.Format(CultureInfo.InvariantCulture, "Unable to alphabetize RESX file {0}", filename), this.Location); } else { this.Log(Level.Error, "Unable to alphabetize RESX file {0}", filename); } } } finally { if (tempFiles != null) { tempFiles.Delete(); if (Directory.Exists(tempFiles.BasePath)) { Directory.Delete(tempFiles.BasePath, true); } tempFiles = null; } } }