private static int InternalExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { if ((cmd == null) || (cmd.Length == 0)) { throw new ExternalException(Locale.GetText("No command provided for execution.")); } if (outputName == null) { outputName = tempFiles.AddExtension("out"); } if (errorName == null) { errorName = tempFiles.AddExtension("err"); } int exit_code = -1; Process proc = new Process(); proc.StartInfo.FileName = cmd; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.WorkingDirectory = currentDir; try { proc.Start(); ProcessResultReader outReader = new ProcessResultReader(proc.StandardOutput, outputName); ProcessResultReader errReader = new ProcessResultReader(proc.StandardError, errorName); Thread t = new Thread(new ThreadStart(errReader.Read)); t.Start(); outReader.Read(); t.Join(); proc.WaitForExit(); } finally { exit_code = proc.ExitCode; // the handle is cleared in Close (so no ExitCode) proc.Close(); } return(exit_code); }
public void ViewLog() { TempFileCollection tempFiles = new TempFileCollection(); FileInfo msgFile = new FileInfo(tempFiles.AddExtension("txt")); File.WriteAllText(msgFile.FullName, Session.Log, Encoding.ASCII); Process.Start(msgFile.FullName); }
public void FileLoggerTest() { var tfc = new TempFileCollection(); var fileName = tfc.AddExtension("txt"); var logger = LoggerFactory.Instance.GetLogger(LogType.File, fileName); logger.Log(TEST_LOG); }
public void FileSerializeMatchesLength() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension(".txt"); File.WriteAllText(file, "sometext"); var part = MultipartPostPart.CreateFormFilePart("someformname", file, "text/plain"); VerifyLength(part); } }
public void MetaData() { string SAVfilename; using (System.CodeDom.Compiler.TempFileCollection tfc = new System.CodeDom.Compiler.TempFileCollection()) { SAVfilename = tfc.AddExtension("sav", true); SpssConvert.ToFile(tblTest, tblTest.Select(), SAVfilename, FillInMetaData); Console.WriteLine("The file with metadata is stored at: " + SAVfilename); } }
public void MultiPartPostMultiByteCharacters() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension("txt"); File.WriteAllText(file, "\x1020\x818"); this.VerifyFullPost(new List<MultipartPostPart> { MultipartPostPart.CreateFormPart("a", "\x987"), MultipartPostPart.CreateFormFilePart("SomeFormField", file, "text/plain"), }); } }
public void MultiPartPostAscii() { using (TempFileCollection tfc = new TempFileCollection()) { string file = tfc.AddExtension("txt"); File.WriteAllText(file, "sometext"); this.VerifyFullPost(new List<MultipartPostPart> { MultipartPostPart.CreateFormPart("a", "b"), MultipartPostPart.CreateFormFilePart("SomeFormField", file, "text/plain"), }); } }
internal WriteFileContext(string filename, string templateFilename) { string directoryname = UrlPath.GetDirectoryOrRootName(filename); _templateFilename = templateFilename; _tempFiles = new TempFileCollection(directoryname); try { _tempNewFilename = _tempFiles.AddExtension("newcfg"); } catch { ((IDisposable)_tempFiles).Dispose(); _tempFiles = null; throw; } }
public static string CreateTemporaryFile() { TempFileCollection tfc = new TempFileCollection(); string fileName = tfc.AddExtension("txt"); // Create and use the tmp file using (FileStream fs1 = File.OpenWrite(fileName)) { using (StreamWriter sw1 = new StreamWriter(fs1)) { sw1.WriteLine("Test string " +DateTime.Now); } } return fileName; }
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; }
public void AddAddressNoteWithFile(string routeId, int addressId) { // Create the manager with the api key Route4MeManager route4Me = new Route4MeManager(c_ApiKey); NoteParameters noteParameters = new NoteParameters() { RouteId = routeId, AddressId = addressId, Latitude = 33.132675170898, Longitude = -83.244743347168, DeviceType = DeviceType.Web.Description(), ActivityType = StatusUpdateType.DropOff.Description() }; string tempFilePath = null; using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Route4MeSDKTest.Resources.test.png")) { var tempFiles = new TempFileCollection(); { tempFilePath = tempFiles.AddExtension("png"); System.Console.WriteLine(tempFilePath); using (Stream fileStream = File.OpenWrite(tempFilePath)) { stream.CopyTo(fileStream); } } } // Run the query string errorString; string contents = "Test Note Contents with Attachment " + DateTime.Now.ToString(); AddressNote note = route4Me.AddAddressNote(noteParameters, contents, tempFilePath, out errorString); Console.WriteLine(""); if (note != null) { Console.WriteLine("AddAddressNoteWithFile executed successfully"); Console.WriteLine("Note ID: {0}", note.NoteId); } else { Console.WriteLine("AddAddressNoteWithFile error: {0}", errorString); } }
public override bool Execute() { #if DEBUG DumpInputParameters(); #endif // Validate the input parameters for the task. if (!this.ValidateParameters()) return false; // If no .xoml files were specified, return success. if (this.WorkflowMarkupFiles == null) this.Log.LogMessageFromResources(MessageImportance.Normal, "NoXomlFiles"); // Check if there are any referenced assemblies. if (this.ReferenceFiles == null || this.ReferenceFiles.Length == 0) this.Log.LogMessageFromResources(MessageImportance.Normal, "NoReferenceFiles"); // Check if there are any souce code files (cs/vb). if (this.SourceCodeFiles == null || this.SourceCodeFiles.Length == 0) this.Log.LogMessageFromResources(MessageImportance.Normal, "NoSourceCodeFiles"); // we return early if this is not invoked during the build phase of the project (eg project load) IWorkflowBuildHostProperties workflowBuildHostProperty = this.HostObject as IWorkflowBuildHostProperties; if (!this.BuildingProject || (workflowBuildHostProperty != null && workflowBuildHostProperty.SkipWorkflowCompilation)) { return true; } // Create an instance of WorkflowCompilerParameters. int errorCount = 0, warningCount = 0; WorkflowCompilerParameters compilerParameters = new WorkflowCompilerParameters(); // set the service provider IWorkflowCompilerErrorLogger workflowErrorLogger = null; IServiceProvider externalServiceProvider = null; if (this.HostObject is IOleServiceProvider) { externalServiceProvider = new ServiceProvider(this.HostObject as IOleServiceProvider); workflowErrorLogger = externalServiceProvider.GetService(typeof(IWorkflowCompilerErrorLogger)) as IWorkflowCompilerErrorLogger; } string[] userCodeFiles = GetFiles(this.SourceCodeFiles, this.ProjectDirectory); foreach (ITaskItem referenceFile in this.ReferenceFiles) compilerParameters.ReferencedAssemblies.Add(referenceFile.ItemSpec); if (string.IsNullOrEmpty(this.targetFramework)) { string defaultFrameworkName = null; const string NDPSetupRegistryBranch = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"; const string NetFrameworkIdentifier = ".NETFramework"; RegistryKey ndpSetupKey = null; try { ndpSetupKey = Registry.LocalMachine.OpenSubKey(NDPSetupRegistryBranch); if (ndpSetupKey != null) { string[] installedNetFxs = ndpSetupKey.GetSubKeyNames(); if (installedNetFxs != null) { char[] splitChars = new char[] { '.' }; for (int i = 0; i < installedNetFxs.Length; i++) { string framework = installedNetFxs[i]; if (framework.Length > 0) { string frameworkVersion = framework.TrimStart('v', 'V'); if (!string.IsNullOrEmpty(frameworkVersion)) { string[] parts = frameworkVersion.Split(splitChars); string normalizedVersion = null; if (parts.Length > 1) { normalizedVersion = string.Format(CultureInfo.InvariantCulture, "v{0}.{1}", parts[0], parts[1]); } else { normalizedVersion = string.Format(CultureInfo.InvariantCulture, "v{0}.0", parts[0]); } if (string.Compare(normalizedVersion, "v3.5", StringComparison.OrdinalIgnoreCase) == 0) { defaultFrameworkName = new FrameworkName(NetFrameworkIdentifier, new Version(3, 5)).ToString(); break; } } } } } } } catch (SecurityException) { } catch (UnauthorizedAccessException) { } catch (IOException) { } finally { if (ndpSetupKey != null) { ndpSetupKey.Close(); } } if (defaultFrameworkName == null) { defaultFrameworkName = new FrameworkName(NetFrameworkIdentifier, new Version(2, 0)).ToString(); } compilerParameters.MultiTargetingInformation = new MultiTargetingInfo(defaultFrameworkName); } else { compilerParameters.MultiTargetingInformation = new MultiTargetingInfo(this.targetFramework); } CompilerOptionsBuilder optionsBuilder; switch (this.ProjectType) { case SupportedLanguages.VB: switch (compilerParameters.CompilerVersion) { case MultiTargetingInfo.TargetFramework30CompilerVersion: optionsBuilder = new WhidbeyVBCompilerOptionsBuilder(); break; case MultiTargetingInfo.TargetFramework35CompilerVersion: optionsBuilder = new OrcasVBCompilerOptionsBuilder(); break; default: optionsBuilder = new CompilerOptionsBuilder(); break; } break; default: optionsBuilder = new CompilerOptionsBuilder(); break; } compilerParameters.CompilerOptions = this.PrepareCompilerOptions(optionsBuilder); compilerParameters.GenerateCodeCompileUnitOnly = true; compilerParameters.LanguageToUse = this.ProjectType.ToString(); compilerParameters.TempFiles.KeepFiles = ShouldKeepTempFiles(); compilerParameters.OutputAssembly = AssemblyName; if (!string.IsNullOrEmpty(assemblyName)) { // Normalizing the assembly name. // The codeDomProvider expects the proper extension to be set. string extension = (compilerParameters.GenerateExecutable) ? ".exe" : ".dll"; compilerParameters.OutputAssembly += extension; } CodeDomProvider codeProvider = null; if (this.ProjectType == SupportedLanguages.VB) codeProvider = CompilerHelpers.CreateCodeProviderInstance(typeof(VBCodeProvider), compilerParameters.CompilerVersion); else codeProvider = CompilerHelpers.CreateCodeProviderInstance(typeof(CSharpCodeProvider), compilerParameters.CompilerVersion); using (TempFileCollection tempFileCollection = new TempFileCollection(Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.User), true)) { this.outputFiles = new TaskItem[1]; // Compile and generate a temporary code file for each xoml file. string[] xomlFilesPaths; if (this.WorkflowMarkupFiles != null) { xomlFilesPaths = new string[WorkflowMarkupFiles.GetLength(0) + userCodeFiles.Length]; int index = 0; for (; index < this.WorkflowMarkupFiles.GetLength(0); index++) xomlFilesPaths[index] = Path.Combine(ProjectDirectory, this.WorkflowMarkupFiles[index].ItemSpec); userCodeFiles.CopyTo(xomlFilesPaths, index); } else { xomlFilesPaths = new string[userCodeFiles.Length]; userCodeFiles.CopyTo(xomlFilesPaths, 0); } WorkflowCompilerResults compilerResults = new CompilerWrapper().Compile(compilerParameters, xomlFilesPaths); foreach (WorkflowCompilerError error in compilerResults.Errors) { if (error.IsWarning) { warningCount++; if (workflowErrorLogger != null) { error.FileName = Path.Combine(this.ProjectDirectory, error.FileName); workflowErrorLogger.LogError(error); workflowErrorLogger.LogMessage(error.ToString() + "\n"); } else this.Log.LogWarning(error.ErrorText, error.ErrorNumber, error.FileName, error.Line, error.Column); } else { errorCount++; if (workflowErrorLogger != null) { error.FileName = Path.Combine(this.ProjectDirectory, error.FileName); workflowErrorLogger.LogError(error); workflowErrorLogger.LogMessage(error.ToString() + "\n"); } else this.Log.LogError(error.ErrorText, error.ErrorNumber, error.FileName, error.Line, error.Column); } } if (!compilerResults.Errors.HasErrors) { CodeCompileUnit ccu = compilerResults.CompiledUnit; if (ccu != null) { // Fix standard namespaces and root namespace. WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(ccu.Namespaces, this.RootNamespace, CompilerHelpers.GetSupportedLanguage(this.ProjectType.ToString())); //just add the standard namespaces string tempFile = tempFileCollection.AddExtension(codeProvider.FileExtension); using (StreamWriter fileStream = new StreamWriter(new FileStream(tempFile, FileMode.Create, FileAccess.Write), Encoding.UTF8)) { CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; codeProvider.GenerateCodeFromCompileUnit(ccu, fileStream, options); } this.outputFiles[0] = new TaskItem(tempFile); this.temporaryFiles.Add(tempFile); this.Log.LogMessageFromResources(MessageImportance.Normal, "TempCodeFile", tempFile); } } } if ((errorCount > 0 || warningCount > 0) && workflowErrorLogger != null) workflowErrorLogger.LogMessage(string.Format(CultureInfo.CurrentCulture, "\nCompile complete -- {0} errors, {1} warnings \n", new object[] { errorCount, warningCount })); #if DEBUG DumpOutputParameters(); #endif this.Log.LogMessageFromResources(MessageImportance.Normal, "XomlValidationCompleted", errorCount, warningCount); return (errorCount == 0); }
/// <include file='doc\Executor.uex' path='docs/doc[@for="Executor.ExecWaitWithCapture3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { IntSecurity.UnmanagedCode.Demand(); IntPtr output; IntPtr error; int retValue = 0; if (outputName == null || outputName.Length == 0) { outputName = tempFiles.AddExtension("out"); } if (errorName == null || errorName.Length == 0) { errorName = tempFiles.AddExtension("err"); } // Create the files output = CreateInheritedFile(outputName); error = CreateInheritedFile(errorName); bool success = false; NativeMethods.PROCESS_INFORMATION pi = new NativeMethods.PROCESS_INFORMATION(); IntPtr primaryToken = IntPtr.Zero; GCHandle environmentHandle = new GCHandle(); try { // Output the command line... // Make sure the FileStream doesn't own the handle FileStream outputStream = new FileStream(output, FileAccess.ReadWrite, false /*ownsHandle*/); StreamWriter sw = new StreamWriter(outputStream, Encoding.UTF8); sw.Write(currentDir); sw.Write("> "); // 'true' command line is used in case the command line points to // a response file sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd); sw.WriteLine(); sw.WriteLine(); sw.Flush(); outputStream.Close(); NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.dwFlags = NativeMethods.STARTF_USESTDHANDLES; si.hStdOutput = output; si.hStdError = error; si.hStdInput = UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE); // // Prepare the environment // Hashtable environment = new Hashtable(); // Add the current environment foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) { environment.Add((string)entry.Key, (string)entry.Value); } // Add the flag to indicate restricted security in the process environment.Add("_ClrRestrictSecAttributes", "1"); // set up the environment block parameter IntPtr environmentPtr = (IntPtr)0; byte[] environmentBytes = EnvironmentToByteArray(environment); environmentHandle = GCHandle.Alloc(environmentBytes, GCHandleType.Pinned); environmentPtr = environmentHandle.AddrOfPinnedObject(); if (userToken == IntPtr.Zero) { success = UnsafeNativeMethods.CreateProcess( null, // String lpApplicationName, new StringBuilder(cmd), // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, environmentPtr, // int lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); } else { throw new NotSupportedException(); } } finally { // free environment block if (environmentHandle.IsAllocated) { environmentHandle.Free(); } // Close the file handles UnsafeNativeMethods.CloseHandle(output); UnsafeNativeMethods.CloseHandle(error); } if (success) { try { int ret = SafeNativeMethods.WaitForSingleObject(pi.hProcess, ProcessTimeOut); // Check for timeout if (ret == NativeMethods.WAIT_TIMEOUT) { throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT); } if (ret != NativeMethods.WAIT_OBJECT_0) { throw new ExternalException(SR.GetString(SR.ExecBadreturn, cmd), Marshal.GetLastWin32Error()); } // Check the process's exit code int status = NativeMethods.STILL_ACTIVE; if (!UnsafeNativeMethods.GetExitCodeProcess(pi.hProcess, ref status)) { throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error()); } retValue = status; } finally { UnsafeNativeMethods.CloseHandle(pi.hThread); UnsafeNativeMethods.CloseHandle(pi.hProcess); if (primaryToken != IntPtr.Zero) { UnsafeNativeMethods.CloseHandle(primaryToken); } } } else { throw new ExternalException(SR.GetString(SR.ExecCantExec, cmd), Marshal.GetLastWin32Error()); } return(retValue); }
/// <summary> /// Loads an output from a path on disk. /// </summary> /// <param name="stream">Stream containing the output file.</param> /// <param name="uri">Uri for finding this stream.</param> /// <param name="suppressVersionCheck">Suppresses wix.dll version mismatch check.</param> /// <param name="suppressSchema">Suppress xml schema validation while loading.</param> /// <returns>Returns the loaded output.</returns> /// <remarks>This method will set the Path and SourcePath properties to the appropriate values on successful load.</remarks> internal static Output Load(Stream stream, Uri uri, bool suppressVersionCheck, bool suppressSchema) { XmlReader reader = null; TempFileCollection tempFileCollection = null; string cabPath = null; // look for the Microsoft cabinet file header and save the cabinet data if found if ('M' == stream.ReadByte() && 'S' == stream.ReadByte() && 'C' == stream.ReadByte() && 'F' == stream.ReadByte()) { long cabFileSize = 0; byte[] offsetBuffer = new byte[4]; tempFileCollection = new TempFileCollection(); cabPath = tempFileCollection.AddExtension("cab", false); // skip the header checksum stream.Seek(4, SeekOrigin.Current); // get the cabinet file size stream.Read(offsetBuffer, 0, 4); cabFileSize = BitConverter.ToInt32(offsetBuffer, 0); stream.Seek(0, SeekOrigin.Begin); // Create the cab file from stream using (FileStream fs = File.Create(cabPath)) { for (int i = 0; i < cabFileSize; i++) { fs.WriteByte((byte)stream.ReadByte()); } } } else // plain xml file - start reading xml at the beginning of the stream { stream.Seek(0, SeekOrigin.Begin); } // read the xml try { reader = new XmlTextReader(uri.AbsoluteUri, stream); if (!suppressSchema) { reader = new XmlValidatingReader(reader); ((XmlValidatingReader)reader).Schemas.Add(GetSchemas()); } reader.MoveToContent(); if ("wixOutput" != reader.LocalName) { throw new WixNotOutputException(WixErrors.InvalidDocumentElement(SourceLineNumberCollection.FromUri(reader.BaseURI), reader.Name, "output", "wixOutput")); } Output output = Parse(reader, suppressVersionCheck); output.tempFileCollection = tempFileCollection; output.cabPath = cabPath; return output; } catch (XmlException xe) { throw new WixException(WixErrors.InvalidXml(SourceLineNumberCollection.FromUri(reader.BaseURI), "output", xe.Message)); } catch (XmlSchemaException xse) { throw new WixException(WixErrors.SchemaValidationFailed(SourceLineNumberCollection.FromUri(reader.BaseURI), xse.Message, xse.LineNumber, xse.LinePosition)); } finally { if (null != reader) { reader.Close(); } } }
public static CompilerResults Compile (string language, string key, string file, ArrayList assemblies, bool debug) { Cache cache = HttpRuntime.InternalCache; CompilerResults results = (CompilerResults) cache [cachePrefix + key]; if (results != null) return results; if (!Directory.Exists (dynamicBase)) Directory.CreateDirectory (dynamicBase); object ticket; bool acquired = AcquireCompilationTicket (cachePrefix + key, out ticket); try { Monitor.Enter (ticket); results = (CompilerResults) cache [cachePrefix + key]; if (results != null) return results; CodeDomProvider provider = null; int warningLevel; string compilerOptions; string tempdir; provider = BaseCompiler.CreateProvider (language, out compilerOptions, out warningLevel, out tempdir); if (provider == null) throw new HttpException ("Configuration error. Language not supported: " + language, 500); CodeDomProvider compiler = provider; CompilerParameters options = GetOptions (assemblies); options.IncludeDebugInformation = debug; options.WarningLevel = warningLevel; options.CompilerOptions = compilerOptions; TempFileCollection tempcoll = new TempFileCollection (tempdir, true); string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true)); options.OutputAssembly = Path.Combine (dynamicBase, dllfilename); results = compiler.CompileAssemblyFromFile (options, file); ArrayList realdeps = new ArrayList (assemblies.Count + 1); realdeps.Add (file); for (int i = assemblies.Count - 1; i >= 0; i--) { string current = (string) assemblies [i]; if (Path.IsPathRooted (current)) realdeps.Add (current); } string [] deps = (string []) realdeps.ToArray (typeof (string)); cache.Insert (cachePrefix + key, results, new CacheDependency (deps)); } finally { Monitor.Exit (ticket); if (acquired) ReleaseCompilationTicket (cachePrefix + key); } return results; }
public override bool Execute() { CompilerOptionsBuilder builder; if (!this.ValidateParameters()) { return false; } if (this.WorkflowMarkupFiles == null) { base.Log.LogMessageFromResources(MessageImportance.Normal, "NoXomlFiles", new object[0]); } if ((this.ReferenceFiles == null) || (this.ReferenceFiles.Length == 0)) { base.Log.LogMessageFromResources(MessageImportance.Normal, "NoReferenceFiles", new object[0]); } if ((this.SourceCodeFiles == null) || (this.SourceCodeFiles.Length == 0)) { base.Log.LogMessageFromResources(MessageImportance.Normal, "NoSourceCodeFiles", new object[0]); } if (((this.HostObject == null) || ((this.HostObject is IWorkflowBuildHostProperties) && ((IWorkflowBuildHostProperties) this.HostObject).SkipWorkflowCompilation)) && (string.Compare(Process.GetCurrentProcess().ProcessName, "devenv", StringComparison.OrdinalIgnoreCase) == 0)) { return true; } int num = 0; int num2 = 0; WorkflowCompilerParameters parameters = new WorkflowCompilerParameters(); IWorkflowCompilerErrorLogger service = null; IServiceProvider provider = null; if (this.HostObject is IOleServiceProvider) { provider = new ServiceProvider(this.HostObject as IOleServiceProvider); service = provider.GetService(typeof(IWorkflowCompilerErrorLogger)) as IWorkflowCompilerErrorLogger; } string[] strArray = GetFiles(this.SourceCodeFiles, this.ProjectDirectory); foreach (ITaskItem item in this.ReferenceFiles) { parameters.ReferencedAssemblies.Add(item.ItemSpec); } if (!string.IsNullOrEmpty(this.targetFramework)) { parameters.MultiTargetingInformation = new MultiTargetingInfo(this.targetFramework); } if (this.ProjectType != SupportedLanguages.VB) { builder = new CompilerOptionsBuilder(); } else { string compilerVersion = parameters.CompilerVersion; if (compilerVersion != null) { if (!(compilerVersion == "v2.0")) { if (compilerVersion == "v3.5") { builder = new OrcasVBCompilerOptionsBuilder(); goto Label_01BE; } } else { builder = new WhidbeyVBCompilerOptionsBuilder(); goto Label_01BE; } } builder = new CompilerOptionsBuilder(); } Label_01BE: parameters.CompilerOptions = this.PrepareCompilerOptions(builder); parameters.GenerateCodeCompileUnitOnly = true; parameters.LanguageToUse = this.ProjectType.ToString(); parameters.TempFiles.KeepFiles = this.ShouldKeepTempFiles(); parameters.OutputAssembly = this.AssemblyName; if (!string.IsNullOrEmpty(this.assemblyName)) { string str = parameters.GenerateExecutable ? ".exe" : ".dll"; parameters.OutputAssembly = parameters.OutputAssembly + str; } CodeDomProvider provider2 = null; if (this.ProjectType == SupportedLanguages.VB) { provider2 = CompilerHelpers.CreateCodeProviderInstance(typeof(VBCodeProvider), parameters.CompilerVersion); } else { provider2 = CompilerHelpers.CreateCodeProviderInstance(typeof(CSharpCodeProvider), parameters.CompilerVersion); } using (TempFileCollection files = new TempFileCollection(Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.User), true)) { string[] strArray2; this.outputFiles = new TaskItem[1]; if (this.WorkflowMarkupFiles != null) { strArray2 = new string[this.WorkflowMarkupFiles.GetLength(0) + strArray.Length]; int index = 0; while (index < this.WorkflowMarkupFiles.GetLength(0)) { strArray2[index] = Path.Combine(this.ProjectDirectory, this.WorkflowMarkupFiles[index].ItemSpec); index++; } strArray.CopyTo(strArray2, index); } else { strArray2 = new string[strArray.Length]; strArray.CopyTo(strArray2, 0); } WorkflowCompilerResults results = new CompilerWrapper().Compile(parameters, strArray2); foreach (WorkflowCompilerError error in results.Errors) { if (error.IsWarning) { num2++; if (service != null) { error.FileName = Path.Combine(this.ProjectDirectory, error.FileName); service.LogError(error); service.LogMessage(error.ToString() + "\n"); } else { base.Log.LogWarning(error.ErrorText, new object[] { error.ErrorNumber, error.FileName, error.Line, error.Column }); } } else { num++; if (service != null) { error.FileName = Path.Combine(this.ProjectDirectory, error.FileName); service.LogError(error); service.LogMessage(error.ToString() + "\n"); } else { base.Log.LogError(error.ErrorText, new object[] { error.ErrorNumber, error.FileName, error.Line, error.Column }); } } } if (!results.Errors.HasErrors) { CodeCompileUnit compiledUnit = results.CompiledUnit; if (compiledUnit != null) { WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(compiledUnit.Namespaces, this.RootNamespace, CompilerHelpers.GetSupportedLanguage(this.ProjectType.ToString())); string path = files.AddExtension(provider2.FileExtension); using (StreamWriter writer = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write), Encoding.UTF8)) { CodeGeneratorOptions options = new CodeGeneratorOptions { BracingStyle = "C" }; provider2.GenerateCodeFromCompileUnit(compiledUnit, writer, options); } this.outputFiles[0] = new TaskItem(path); this.temporaryFiles.Add(path); base.Log.LogMessageFromResources(MessageImportance.Normal, "TempCodeFile", new object[] { path }); } } } if (((num > 0) || (num2 > 0)) && (service != null)) { service.LogMessage(string.Format(CultureInfo.CurrentCulture, "\nCompile complete -- {0} errors, {1} warnings \n", new object[] { num, num2 })); } base.Log.LogMessageFromResources(MessageImportance.Normal, "XomlValidationCompleted", new object[] { num, num2 }); return (num == 0); }
private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { IntSecurity.UnmanagedCode.Demand(); FileStream output; FileStream error; int retValue = 0; if (outputName == null || outputName.Length == 0) { outputName = tempFiles.AddExtension("out"); } if (errorName == null || errorName.Length == 0) { errorName = tempFiles.AddExtension("err"); } // Create the files output = CreateInheritedFile(outputName); error = CreateInheritedFile(errorName); bool success = false; SafeNativeMethods.PROCESS_INFORMATION pi = new SafeNativeMethods.PROCESS_INFORMATION(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); SafeUserTokenHandle primaryToken = null; try { // Output the command line... StreamWriter sw = new StreamWriter(output, Encoding.UTF8); sw.Write(currentDir); sw.Write("> "); // 'true' command line is used in case the command line points to // a response file sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd); sw.WriteLine(); sw.WriteLine(); sw.Flush(); NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.dwFlags = NativeMethods.STARTF_USESTDHANDLES; si.hStdOutput = output.SafeFileHandle; si.hStdError = error.SafeFileHandle; si.hStdInput = new SafeFileHandle(UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false); // // Prepare the environment // #if PLATFORM_UNIX StringDictionary environment = new CaseSensitiveStringDictionary(); #else StringDictionary environment = new StringDictionary(); #endif // PLATFORM_UNIX // Add the current environment foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) { environment.Add((string)entry.Key, (string)entry.Value); } // Add the flag to indicate restricted security in the process environment["_ClrRestrictSecAttributes"] = "1"; #if DEBUG environment["OANOCACHE"] = "1"; #endif // set up the environment block parameter byte[] environmentBytes = EnvironmentBlock.ToByteArray(environment, false); fixed(byte *environmentBytesPtr = environmentBytes) { IntPtr environmentPtr = new IntPtr((void *)environmentBytesPtr); if (userToken == null || userToken.IsInvalid) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcess( null, // String lpApplicationName, new StringBuilder(cmd), // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, environmentPtr, // int lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if (pi.hProcess != (IntPtr)0 && pi.hProcess != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) { procSH.InitialSetHandle(pi.hProcess); } if (pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) { threadSH.InitialSetHandle(pi.hThread); } } } else { throw new NotSupportedException(); } } } finally { // Close the file handles if (!success && (primaryToken != null && !primaryToken.IsInvalid)) { primaryToken.Close(); primaryToken = null; } output.Close(); error.Close(); } if (success) { try { int ret = NativeMethods.WaitForSingleObject(procSH, ProcessTimeOut); // Check for timeout if (ret == NativeMethods.WAIT_TIMEOUT) { throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT); } if (ret != NativeMethods.WAIT_OBJECT_0) { throw new ExternalException(SR.GetString(SR.ExecBadreturn, cmd), Marshal.GetLastWin32Error()); } // Check the process's exit code int status = NativeMethods.STILL_ACTIVE; if (!NativeMethods.GetExitCodeProcess(procSH, out status)) { throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error()); } retValue = status; } finally { procSH.Close(); threadSH.Close(); if (primaryToken != null && !primaryToken.IsInvalid) { primaryToken.Close(); } } } else { throw new ExternalException(SR.GetString(SR.ExecCantExec, cmd), Marshal.GetLastWin32Error()); } return(retValue); }
[ResourceConsumption(ResourceScope.Machine)] // temp file creation, and passing to InternalGenerateCode public IList<EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target, Version targetEntityFrameworkVersion) { EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema"); EDesignUtil.CheckArgumentNull(target, "target"); EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion"); Version schemaVersion; if (!IsValidSchema(sourceEdmSchema, out schemaVersion)) { return new List<EdmSchemaError>() { CreateSourceEdmSchemaNotValidError() }; } using (TempFileCollection collection = new TempFileCollection()) { string tempSourceEdmSchemaPath = collection.AddExtension(XmlConstants.CSpaceSchemaExtension); SaveXmlReaderToFile(sourceEdmSchema, tempSourceEdmSchemaPath); return InternalGenerateCode(tempSourceEdmSchemaPath, schemaVersion, new LazyTextWriterCreator(target), null, targetEntityFrameworkVersion); } }
public void ToFile() { DataTable dt = new DataTable(); dt.Columns.Add("var1", typeof(int)); dt.Columns.Add("var2", typeof(string)); dt.Rows.Add(new object[] { 1, "hi" }); using (TempFileCollection tfc = new TempFileCollection()) { tfc.KeepFiles = false; string filename = tfc.AddExtension("sav"); SpssConvert.ToFile(dt, dt.Select(), filename, null); } }
private void ViewMessage(MessageViewModel message) { TempFileCollection tempFiles = new TempFileCollection(); FileInfo msgFile = new FileInfo(tempFiles.AddExtension("eml")); message.SaveToFile(msgFile); if (Registry.ClassesRoot.OpenSubKey(".eml", false) == null || string.IsNullOrEmpty((string)Registry.ClassesRoot.OpenSubKey(".eml", false).GetValue(null))) { switch (MessageBox.Show(this, "You don't appear to have a viewer application associated with .eml files!\nWould you like to download Windows Live Mail (free from live.com website)?", "View Message", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)) { case DialogResult.Yes: Process.Start("http://download.live.com/wlmail"); return; break; case DialogResult.Cancel: return; break; } } Process.Start(msgFile.FullName); messageGrid.Refresh(); }
public void View() { var mp = _part as MimePart; if (mp != null) { string extn = Path.GetExtension(mp.FileName ?? "Unnamed"); if (string.IsNullOrEmpty(extn)) { extn = MIMEDatabase.GetExtension(MimeType) ?? ".part"; } var tempFiles = new TempFileCollection(); var msgFile = new FileInfo(tempFiles.AddExtension(extn.TrimStart('.'))); using (FileStream stream = msgFile.OpenWrite()) { mp.ContentObject.DecodeTo(stream); } Process.Start(msgFile.FullName); } }
public void AddExtension_InvalidFileExtension_ThrowsArgumentException(string fileExtension) { using (var collection = new TempFileCollection()) { Assert.Throws<ArgumentException>("fileExtension", () => collection.AddExtension(fileExtension)); Assert.Throws<ArgumentException>("fileExtension", () => collection.AddExtension(fileExtension, keepFile: false)); } }
[ResourceConsumption(ResourceScope.Machine)] //Temp file creation, and passing to InternalGenerateCode public IList<EdmSchemaError> GenerateCode(XmlReader sourceEdmSchema, TextWriter target, IEnumerable<XmlReader> additionalEdmSchemas, Version targetEntityFrameworkVersion) { EDesignUtil.CheckArgumentNull(sourceEdmSchema, "sourceEdmSchema"); EDesignUtil.CheckArgumentNull(additionalEdmSchemas, "additionalEdmSchemas"); EDesignUtil.CheckArgumentNull(target, "target"); EDesignUtil.CheckTargetEntityFrameworkVersionArgument(targetEntityFrameworkVersion, "targetEntityFrameworkVersion"); Version schemaVersion; if (!IsValidSchema(sourceEdmSchema, out schemaVersion)) { return new List<EdmSchemaError>() { CreateSourceEdmSchemaNotValidError() }; } using (TempFileCollection collection = new TempFileCollection()) { string tempSourceEdmSchemaPath = collection.AddExtension(XmlConstants.CSpaceSchemaExtension); SaveXmlReaderToFile(sourceEdmSchema, tempSourceEdmSchemaPath); List<string> additionalTempPaths = new List<string>(); foreach (XmlReader reader in additionalEdmSchemas) { string temp = Path.GetTempFileName() + XmlConstants.CSpaceSchemaExtension; SaveXmlReaderToFile(reader, temp); additionalTempPaths.Add(temp); collection.AddFile(temp, false); } return InternalGenerateCode(tempSourceEdmSchemaPath, schemaVersion, new LazyTextWriterCreator(target), additionalTempPaths, targetEntityFrameworkVersion); } }
private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { IntSecurity.UnmanagedCode.Demand(); if ((outputName == null) || (outputName.Length == 0)) { outputName = tempFiles.AddExtension("out"); } if ((errorName == null) || (errorName.Length == 0)) { errorName = tempFiles.AddExtension("err"); } FileStream stream = CreateInheritedFile(outputName); FileStream stream2 = CreateInheritedFile(errorName); bool flag = false; Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new Microsoft.Win32.SafeNativeMethods.PROCESS_INFORMATION(); Microsoft.Win32.SafeHandles.SafeProcessHandle processHandle = new Microsoft.Win32.SafeHandles.SafeProcessHandle(); Microsoft.Win32.SafeHandles.SafeThreadHandle handle2 = new Microsoft.Win32.SafeHandles.SafeThreadHandle(); SafeUserTokenHandle hNewToken = null; try { Microsoft.Win32.NativeMethods.STARTUPINFO startupinfo; StreamWriter writer = new StreamWriter(stream, Encoding.UTF8); writer.Write(currentDir); writer.Write("> "); writer.WriteLine((trueCmdLine != null) ? trueCmdLine : cmd); writer.WriteLine(); writer.WriteLine(); writer.Flush(); startupinfo = new Microsoft.Win32.NativeMethods.STARTUPINFO { cb = Marshal.SizeOf(startupinfo), dwFlags = 0x101, wShowWindow = 0, hStdOutput = stream.SafeFileHandle, hStdError = stream2.SafeFileHandle, hStdInput = new SafeFileHandle(Microsoft.Win32.UnsafeNativeMethods.GetStdHandle(-10), false) }; StringDictionary sd = new StringDictionary(); foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) { sd[(string)entry.Key] = (string)entry.Value; } sd["_ClrRestrictSecAttributes"] = "1"; byte[] buffer = EnvironmentBlock.ToByteArray(sd, false); try { fixed(byte *numRef = buffer) { IntPtr lpEnvironment = new IntPtr((void *)numRef); if ((userToken == null) || userToken.IsInvalid) { RuntimeHelpers.PrepareConstrainedRegions(); try { goto Label_0325; } finally { flag = Microsoft.Win32.NativeMethods.CreateProcess(null, new StringBuilder(cmd), null, null, true, 0, lpEnvironment, currentDir, startupinfo, lpProcessInformation); if ((lpProcessInformation.hProcess != IntPtr.Zero) && (lpProcessInformation.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)) { processHandle.InitialSetHandle(lpProcessInformation.hProcess); } if ((lpProcessInformation.hThread != IntPtr.Zero) && (lpProcessInformation.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)) { handle2.InitialSetHandle(lpProcessInformation.hThread); } } } flag = SafeUserTokenHandle.DuplicateTokenEx(userToken, 0xf01ff, null, 2, 1, out hNewToken); if (flag) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { flag = Microsoft.Win32.NativeMethods.CreateProcessAsUser(hNewToken, null, cmd, null, null, true, 0, new HandleRef(null, lpEnvironment), currentDir, startupinfo, lpProcessInformation); if ((lpProcessInformation.hProcess != IntPtr.Zero) && (lpProcessInformation.hProcess != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)) { processHandle.InitialSetHandle(lpProcessInformation.hProcess); } if ((lpProcessInformation.hThread != IntPtr.Zero) && (lpProcessInformation.hThread != Microsoft.Win32.NativeMethods.INVALID_HANDLE_VALUE)) { handle2.InitialSetHandle(lpProcessInformation.hThread); } } } } } finally { numRef = null; } } finally { if ((!flag && (hNewToken != null)) && !hNewToken.IsInvalid) { hNewToken.Close(); hNewToken = null; } stream.Close(); stream2.Close(); } Label_0325: if (flag) { try { bool flag2; ProcessWaitHandle handle4 = null; try { handle4 = new ProcessWaitHandle(processHandle); flag2 = handle4.WaitOne(0x927c0, false); } finally { if (handle4 != null) { handle4.Close(); } } if (!flag2) { throw new ExternalException(SR.GetString("ExecTimeout", new object[] { cmd }), 0x102); } int exitCode = 0x103; if (!Microsoft.Win32.NativeMethods.GetExitCodeProcess(processHandle, out exitCode)) { throw new ExternalException(SR.GetString("ExecCantGetRetCode", new object[] { cmd }), Marshal.GetLastWin32Error()); } return(exitCode); } finally { processHandle.Close(); handle2.Close(); if ((hNewToken != null) && !hNewToken.IsInvalid) { hNewToken.Close(); } } } int error = Marshal.GetLastWin32Error(); if (error == 8) { throw new OutOfMemoryException(); } Win32Exception inner = new Win32Exception(error); ExternalException exception2 = new ExternalException(SR.GetString("ExecCantExec", new object[] { cmd }), inner); throw exception2; }
/// <include file='doc\Executor.uex' path='docs/doc[@for="Executor.ExecWaitWithCapture3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { IntSecurity.UnmanagedCode.Demand(); IntPtr output; IntPtr error; int retValue = 0; if (outputName == null || outputName.Length == 0) outputName = tempFiles.AddExtension("out"); if (errorName == null || errorName.Length == 0) errorName = tempFiles.AddExtension("err"); // Create the files output = CreateInheritedFile(outputName); error = CreateInheritedFile(errorName); bool success = false; NativeMethods.PROCESS_INFORMATION pi = new NativeMethods.PROCESS_INFORMATION(); IntPtr primaryToken = IntPtr.Zero; GCHandle environmentHandle = new GCHandle(); try { // Output the command line... // Make sure the FileStream doesn't own the handle FileStream outputStream = new FileStream(output, FileAccess.ReadWrite, false /*ownsHandle*/); StreamWriter sw = new StreamWriter(outputStream, Encoding.UTF8); sw.Write(currentDir); sw.Write("> "); // 'true' command line is used in case the command line points to // a response file sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd); sw.WriteLine(); sw.WriteLine(); sw.Flush(); outputStream.Close(); NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.dwFlags = NativeMethods.STARTF_USESTDHANDLES; si.hStdOutput = output; si.hStdError = error; si.hStdInput = UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE); // // Prepare the environment // Hashtable environment = new Hashtable(); // Add the current environment foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables()) environment.Add((string)entry.Key, (string)entry.Value); // Add the flag to indicate restricted security in the process environment.Add("_ClrRestrictSecAttributes", "1"); // set up the environment block parameter IntPtr environmentPtr = (IntPtr)0; byte[] environmentBytes = EnvironmentToByteArray(environment); environmentHandle = GCHandle.Alloc(environmentBytes, GCHandleType.Pinned); environmentPtr = environmentHandle.AddrOfPinnedObject(); if (userToken == IntPtr.Zero) { success = UnsafeNativeMethods.CreateProcess( null, // String lpApplicationName, new StringBuilder(cmd), // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, environmentPtr, // int lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); } else { throw new NotSupportedException(); } } finally { // free environment block if (environmentHandle.IsAllocated) environmentHandle.Free(); // Close the file handles UnsafeNativeMethods.CloseHandle(output); UnsafeNativeMethods.CloseHandle(error); } if (success) { try { int ret = SafeNativeMethods.WaitForSingleObject(pi.hProcess, ProcessTimeOut); // Check for timeout if (ret == NativeMethods.WAIT_TIMEOUT) { throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT); } if (ret != NativeMethods.WAIT_OBJECT_0) { throw new ExternalException(SR.GetString(SR.ExecBadreturn, cmd), Marshal.GetLastWin32Error()); } // Check the process's exit code int status = NativeMethods.STILL_ACTIVE; if (!UnsafeNativeMethods.GetExitCodeProcess(pi.hProcess, ref status)) { throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error()); } retValue = status; } finally { UnsafeNativeMethods.CloseHandle(pi.hThread); UnsafeNativeMethods.CloseHandle(pi.hProcess); if (primaryToken != IntPtr.Zero) UnsafeNativeMethods.CloseHandle(primaryToken); } } else { throw new ExternalException(SR.GetString(SR.ExecCantExec, cmd), Marshal.GetLastWin32Error()); } return retValue; }
public void AddFileExtension() { string tempDirectory = TempDirectory(); using (var collection = new TempFileCollection(tempDirectory)) { string file = collection.AddExtension("txt"); Assert.False(File.Exists(file)); Assert.Equal(collection.BasePath + "." + "txt", file); } }
public static int ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { if (userToken != IntPtr.Zero) { throw new PlatformNotSupportedException(); } if (string.IsNullOrEmpty(outputName)) { outputName = tempFiles.AddExtension("out"); } if (string.IsNullOrEmpty(errorName)) { errorName = tempFiles.AddExtension("err"); } using (var outputWriter = new StreamWriter(CreateInheritedFile(outputName), Encoding.UTF8)) using (var errorWriter = new StreamWriter(CreateInheritedFile(errorName), Encoding.UTF8)) { // Output the command line... outputWriter.Write(currentDir); outputWriter.Write("> "); outputWriter.WriteLine(cmd); outputWriter.WriteLine(); outputWriter.WriteLine(); var psi = new ProcessStartInfo(cmd) { WorkingDirectory = currentDir, RedirectStandardOutput = true, RedirectStandardError = true }; using (Process p = Process.Start(psi)) { p.OutputDataReceived += (s, e) => { if (e.Data != null) { outputWriter.WriteLine(e.Data); } }; p.ErrorDataReceived += (s, e) => { if (e.Data != null) { errorWriter.WriteLine(e.Data); } }; p.BeginOutputReadLine(); p.BeginErrorReadLine(); if (!p.WaitForExit(ProcessTimeOut)) { const int WAIT_TIMEOUT = 0x102; throw new ExternalException(SR.Format(SR.ExecTimeout, cmd), WAIT_TIMEOUT); } p.WaitForExit(); return(p.ExitCode); } } }
public override Type GetCompiledType () { Type type = CachingCompiler.GetTypeFromCache (parser.PhysicalPath); if (type != null) return type; if (parser.Program.Trim () == "") { type = Type.GetType (parser.ClassName, false); if (type == null) type = parser.GetTypeFromBin (parser.ClassName); CachingCompiler.InsertTypeFileDep (type, parser.PhysicalPath); return type; } string lang = parser.Language; string compilerOptions; string tempdir; int warningLevel; CodeDomProvider provider; Provider = provider = CreateProvider (parser.Context, lang, out compilerOptions, out warningLevel, out tempdir); if (Provider == null) throw new HttpException ("Configuration error. Language not supported: " + lang, 500); #if !NET_2_0 Compiler = provider.CreateCompiler (); #endif CompilerParameters compilerParameters; CompilerParameters = compilerParameters = CachingCompiler.GetOptions (parser.Assemblies); compilerParameters.IncludeDebugInformation = parser.Debug; compilerParameters.CompilerOptions = compilerOptions; compilerParameters.WarningLevel = warningLevel; bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null); TempFileCollection tempcoll; tempcoll = new TempFileCollection (tempdir, keepFiles); compilerParameters.TempFiles = tempcoll; inputFile = tempcoll.AddExtension (provider.FileExtension); Stream st = File.OpenWrite (inputFile); StreamWriter sw = new StreamWriter (st); sw.WriteLine (parser.Program); sw.Close (); string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true)); compilerParameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename); CompilerResults results = CachingCompiler.Compile (this); CheckCompilerErrors (results); Assembly assembly = results.CompiledAssembly; if (assembly == null) { if (!File.Exists (compilerParameters.OutputAssembly)) throw new CompilationException (inputFile, results.Errors, "No assembly returned after compilation!?"); assembly = Assembly.LoadFrom (compilerParameters.OutputAssembly); } results.TempFiles.Delete (); type = assembly.GetType (parser.ClassName, true); CachingCompiler.InsertTypeFileDep (type, parser.PhysicalPath); return type; }
/// <summary> /// Run a Taudem V5 executable /// </summary> /// <param name="command">Taudem executable file name</param> /// <param name="parameters">Parameters for Taudem executable. Parameters containing spaces must be quoted.</param> /// <param name="numProc">Maximum number of threads (ignored if MPICH2 not running)</param> /// <param name="showOutput">Standard output and standard error from Taudem executable are shown iff this flag is true or there is an error in the Taudem run.</param> /// <returns> /// Return code from Taudem executable /// </returns> public static int RunTaudem(string command, string parameters, int numProc, bool showOutput) { var tfc = new TempFileCollection(); var tempFile = tfc.AddExtension("txt"); var taudemProcess = new Process { StartInfo = { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Minimized, WorkingDirectory = TaudemExeDir(), FileName = "runtaudem.bat", Arguments = Quote(tempFile) + " mpiexec -n " + numProc.ToString(CultureInfo.InvariantCulture) + " " + command + " " + parameters } }; taudemProcess.Start(); taudemProcess.WaitForExit(); var needOutput = showOutput || ((taudemProcess.ExitCode != 0) && (MessageBox.Show( @"Taudem error. Do you want to see the details?", string.Empty, MessageBoxButtons.YesNo) == DialogResult.Yes)); if (needOutput) { var proc = new Process { StartInfo = { FileName = Path.GetFileName(tempFile), WorkingDirectory = Path.GetDirectoryName(tempFile) } }; proc.Start(); // Paul Meems, 23-aug-2011: Don't wait for exit but continue the proces: // cwg 13/9/2011 do wait - else get a confusing stack of outputs proc.WaitForExit(); } // Paul Meems, 23-aug-2011 // tfc.Delete(); return taudemProcess.ExitCode; }
public virtual Type GetCompiledType () { Type type = CachingCompiler.GetTypeFromCache (parser.InputFile); if (type != null) return type; ConstructType (); string lang = parser.Language; string tempdir; string compilerOptions; int warningLevel; Provider = CreateProvider (parser.Context, lang, out compilerOptions, out warningLevel, out tempdir); if (Provider == null) throw new HttpException ("Configuration error. Language not supported: " + lang, 500); CompilerParameters parameters = CompilerParameters; parameters.IncludeDebugInformation = parser.Debug; parameters.CompilerOptions = compilerOptions + " " + parser.CompilerOptions; parameters.WarningLevel = warningLevel; bool keepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null); if (tempdir == null || tempdir == "") tempdir = DynamicDir (); TempFileCollection tempcoll = new TempFileCollection (tempdir, keepFiles); parameters.TempFiles = tempcoll; string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true)); parameters.OutputAssembly = Path.Combine (DynamicDir (), dllfilename); CompilerResults results = CachingCompiler.Compile (this); CheckCompilerErrors (results); Assembly assembly = results.CompiledAssembly; if (assembly == null) { if (!File.Exists (parameters.OutputAssembly)) { results.TempFiles.Delete (); throw new CompilationException (parser.InputFile, results.Errors, "No assembly returned after compilation!?"); } assembly = Assembly.LoadFrom (parameters.OutputAssembly); } results.TempFiles.Delete (); Type mainClassType = assembly.GetType (MainClassType, true); if (parser.IsPartial) { // With the partial classes, we need to make sure we // don't have any methods that should have not been // created (because they are accessible from the base // types). We cannot do this normally because the // codebehind file is actually a partial class and we // have no way of identifying the partial class' base // type until now. if (!isRebuilding && CheckPartialBaseType (mainClassType)) { isRebuilding = true; parser.RootBuilder.ResetState (); return GetCompiledType (); } } return mainClassType; }
private static unsafe int ExecWaitWithCaptureUnimpersonated(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { IntSecurity.UnmanagedCode.Demand(); FileStream output; FileStream error; int retValue = 0; if (outputName == null || outputName.Length == 0) outputName = tempFiles.AddExtension("out"); if (errorName == null || errorName.Length == 0) errorName = tempFiles.AddExtension("err"); // Create the files output = CreateInheritedFile(outputName); error = CreateInheritedFile(errorName); bool success = false; SafeNativeMethods.PROCESS_INFORMATION pi = new SafeNativeMethods.PROCESS_INFORMATION(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); SafeUserTokenHandle primaryToken = null; try { // Output the command line... StreamWriter sw = new StreamWriter(output, Encoding.UTF8); sw.Write(currentDir); sw.Write("> "); // 'true' command line is used in case the command line points to // a response file sw.WriteLine(trueCmdLine != null ? trueCmdLine : cmd); sw.WriteLine(); sw.WriteLine(); sw.Flush(); NativeMethods.STARTUPINFO si = new NativeMethods.STARTUPINFO(); si.cb = Marshal.SizeOf(si); #if FEATURE_PAL si.dwFlags = NativeMethods.STARTF_USESTDHANDLES; #else //!FEATURE_PAL si.dwFlags = NativeMethods.STARTF_USESTDHANDLES | NativeMethods.STARTF_USESHOWWINDOW; si.wShowWindow = NativeMethods.SW_HIDE; #endif //!FEATURE_PAL si.hStdOutput = output.SafeFileHandle; si.hStdError = error.SafeFileHandle; si.hStdInput = new SafeFileHandle(UnsafeNativeMethods.GetStdHandle(NativeMethods.STD_INPUT_HANDLE), false); // // Prepare the environment // #if PLATFORM_UNIX StringDictionary environment = new CaseSensitiveStringDictionary(); #else StringDictionary environment = new StringDictionary (); #endif // PLATFORM_UNIX // Add the current environment foreach ( DictionaryEntry entry in Environment.GetEnvironmentVariables () ) environment[(string) entry.Key] = (string) entry.Value; // Add the flag to indicate restricted security in the process environment["_ClrRestrictSecAttributes"] = "1"; #if DEBUG environment["OANOCACHE"] = "1"; #endif // set up the environment block parameter byte[] environmentBytes = EnvironmentBlock.ToByteArray(environment, false); fixed (byte* environmentBytesPtr = environmentBytes) { IntPtr environmentPtr = new IntPtr((void*)environmentBytesPtr); if (userToken == null || userToken.IsInvalid) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcess( null, // String lpApplicationName, new StringBuilder(cmd), // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, environmentPtr, // IntPtr lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) procSH.InitialSetHandle(pi.hProcess); if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(pi.hThread); } } else { #if FEATURE_PAL throw new NotSupportedException(); #else success = SafeUserTokenHandle.DuplicateTokenEx( userToken, NativeMethods.TOKEN_ALL_ACCESS, null, NativeMethods.IMPERSONATION_LEVEL_SecurityImpersonation, NativeMethods.TOKEN_TYPE_TokenPrimary, out primaryToken ); if (success) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { success = NativeMethods.CreateProcessAsUser( primaryToken, // int token, null, // String lpApplicationName, cmd, // String lpCommandLine, null, // SECURITY_ATTRIBUTES lpProcessAttributes, null, // SECURITY_ATTRIBUTES lpThreadAttributes, true, // bool bInheritHandles, 0, // int dwCreationFlags, new HandleRef(null, environmentPtr), // IntPtr lpEnvironment, currentDir, // String lpCurrentDirectory, si, // STARTUPINFO lpStartupInfo, pi); // PROCESS_INFORMATION lpProcessInformation); if ( pi.hProcess!= (IntPtr)0 && pi.hProcess!= (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) procSH.InitialSetHandle(pi.hProcess); if ( pi.hThread != (IntPtr)0 && pi.hThread != (IntPtr)NativeMethods.INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(pi.hThread); } } #endif // !FEATURE_PAL } } } finally { // Close the file handles if (!success && (primaryToken != null && !primaryToken.IsInvalid)) { primaryToken.Close(); primaryToken = null; } output.Close(); error.Close(); } if (success) { try { bool signaled; ProcessWaitHandle pwh = null; try { pwh = new ProcessWaitHandle(procSH); signaled = pwh.WaitOne(ProcessTimeOut, false); } finally { if (pwh != null) pwh.Close(); } // Check for timeout if (!signaled) { throw new ExternalException(SR.GetString(SR.ExecTimeout, cmd), NativeMethods.WAIT_TIMEOUT); } // Check the process's exit code int status = NativeMethods.STILL_ACTIVE; if (!NativeMethods.GetExitCodeProcess(procSH, out status)) { throw new ExternalException(SR.GetString(SR.ExecCantGetRetCode, cmd), Marshal.GetLastWin32Error()); } retValue = status; } finally { procSH.Close(); threadSH.Close(); if (primaryToken != null && !primaryToken.IsInvalid) primaryToken.Close(); } } else { int err = Marshal.GetLastWin32Error(); if (err == NativeMethods.ERROR_NOT_ENOUGH_MEMORY) throw new OutOfMemoryException(); Win32Exception win32Exception = new Win32Exception(err); ExternalException ex = new ExternalException(SR.GetString(SR.ExecCantExec, cmd), win32Exception); throw ex; } return retValue; }
/// <summary> /// Creates a temp xml file to the default Windows temp directory and stores the file name. /// </summary> /// <returns>True if the file was created successfuly.</returns> private bool WriteFile() { bool returnValue = false; if (!(fileName != null && fileName.Length > 0 && xmlData != null && xmlData.Length > 0)) { TempFileCollection tempFiles = new TempFileCollection(); fileName = tempFiles.AddExtension("xml"); } using (FileStream fileStream = new FileStream(fileName, FileMode.Create)) { byte[] info = new UTF8Encoding(true).GetBytes(xmlData); fileStream.Write(info, 0, info.Length); returnValue = true; } return returnValue; }
internal TempFile() { // suspend the impersonation for the file creation using (new ApplicationImpersonationContext()) { String tempDir = Path.Combine(HttpRuntime.CodegenDirInternal, "uploads"); // Assert IO access to the temporary directory new FileIOPermission(FileIOPermissionAccess.AllAccess, tempDir).Assert(); if (!Directory.Exists(tempDir)) { try { Directory.CreateDirectory(tempDir); } catch { } } _tempFiles = new TempFileCollection(tempDir, false /*keepFiles*/); _filename = _tempFiles.AddExtension("post", false /*keepFiles*/); //using 4096 as the buffer size, same as the BCL _filestream = new FileStream(_filename, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose); } }
private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension) { return temp_files.AddExtension (extension); }
private static int InternalExecWaitWithCapture (string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { if ((cmd == null) || (cmd.Length == 0)) throw new ExternalException (Locale.GetText ("No command provided for execution.")); if (outputName == null) outputName = tempFiles.AddExtension ("out"); if (errorName == null) errorName = tempFiles.AddExtension ("err"); int exit_code = -1; Process proc = new Process (); proc.StartInfo.FileName = cmd; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.WorkingDirectory = currentDir; try { proc.Start(); ProcessResultReader outReader = new ProcessResultReader (proc.StandardOutput, outputName); ProcessResultReader errReader = new ProcessResultReader (proc.StandardError, errorName); Thread t = new Thread (new ThreadStart (errReader.Read)); t.Start (); outReader.Read (); t.Join (); proc.WaitForExit(); } finally { exit_code = proc.ExitCode; // the handle is cleared in Close (so no ExitCode) proc.Close (); } return exit_code; }