public ManagedProjectReference(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, SolutionBase solution, TempFileCollection tfc, GacCache gacCache, DirectoryInfo outputDir) : base(referencesResolver, parent) { if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } if (solution == null) { throw new ArgumentNullException("solution"); } if (tfc == null) { throw new ArgumentNullException("tfc"); } if (gacCache == null) { throw new ArgumentNullException("gacCache"); } XmlAttribute privateAttribute = xmlDefinition.Attributes["Private"]; if (privateAttribute != null) { _isPrivateSpecified = true; _isPrivate = bool.Parse(privateAttribute.Value); } // determine path of project file string projectFile = solution.GetProjectFileFromGuid( xmlDefinition.GetAttribute("Project")); // load referenced project _project = LoadProject(solution, tfc, gacCache, outputDir, projectFile); }
/// <summary> /// Initializes a new instance of the <see cref="ProjectBase" /> class. /// </summary> protected ProjectBase(XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection temporaryFiles, GacCache gacCache, ReferencesResolver referencesResolver, DirectoryInfo outputDir) { if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } if (solutionTask == null) { throw new ArgumentNullException("solutionTask"); } if (temporaryFiles == null) { throw new ArgumentNullException("temporaryFiles"); } if (gacCache == null) { throw new ArgumentNullException("gacCache"); } if (referencesResolver == null) { throw new ArgumentNullException("referencesResolver"); } _projectConfigurations = new ConfigurationDictionary(); _buildConfigurations = new ConfigurationDictionary(); _extraOutputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); // ensure the specified project is actually supported by this project VerifyProjectXml(xmlDefinition); _solutionTask = solutionTask; _temporaryFiles = temporaryFiles; _outputDir = outputDir; _gacCache = gacCache; _refResolver = referencesResolver; _productVersion = DetermineProductVersion(xmlDefinition); }
public static StringCollection Execute(string strCmd) { string output = ""; string error = ""; TempFileCollection tf = new TempFileCollection(); Executor.ExecWaitWithCapture(strCmd, tf, ref output, ref error); StreamReader sr = File.OpenText(output); StringCollection coll = new StringCollection(); string strLine = null; sr.ReadLine(); // skip first line while (null != (strLine = sr.ReadLine())) { coll.Add(strLine); } sr.Close(); File.Delete(output); File.Delete(error); return coll; }
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 ViewLog() { TempFileCollection tempFiles = new TempFileCollection(); FileInfo msgFile = new FileInfo(tempFiles.AddExtension("txt")); File.WriteAllText(msgFile.FullName, Session.Log, Encoding.ASCII); Process.Start(msgFile.FullName); }
internal void Complete(string filename, bool success) { try { if (success) { if (File.Exists(filename)) { this.ValidateWriteAccess(filename); this.DuplicateFileAttributes(filename, this._tempNewFilename); } else if (this._templateFilename != null) { this.DuplicateTemplateAttributes(this._templateFilename, this._tempNewFilename); } this.ReplaceFile(this._tempNewFilename, filename); this._tempFiles.KeepFiles = true; } } finally { ((IDisposable) this._tempFiles).Dispose(); this._tempFiles = null; } }
// Complete // // Cleanup the WriteFileContext object based on either success // or failure // // Note: The current algorithm guarantess // 1) The file we are saving to will always be present // on the file system (ie. there will be no window // during saving in which there won't be a file there) // 2) It will always be available for reading from a // client and it will be complete and accurate. // // ... This means that writing is a bit more complicated, and may // have to be retried (because of reading lock), but I don't see // anyway to get around this given 1 and 2. // internal void Complete(string filename, bool success) { try { if (!success) return; if (File.Exists(filename)) { // Test that we can write to the file ValidateWriteAccess(filename); // Copy Attributes from original DuplicateFileAttributes(filename, TempNewFilename); } else { if (_templateFilename != null) { // Copy Acl from template file DuplicateTemplateAttributes(_templateFilename, TempNewFilename); } } ReplaceFile(TempNewFilename, filename); // Don't delete, since we just moved it. _tempFiles.KeepFiles = true; } finally { ((IDisposable)_tempFiles).Dispose(); _tempFiles = null; } }
public void FixtureSetUp () { // at full trust temps = new TempFileCollection (); assembly = Assembly.GetExecutingAssembly (); path = assembly.Location; }
[SecurityPermission (SecurityAction.Assert, ControlPrincipal = true)] // UnmanagedCode "covers" more than ControlPrincipal public static Int32 ExecWaitWithCapture (IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { // WindowsImpersonationContext implements IDisposable only in 2.0 using (WindowsImpersonationContext context = WindowsIdentity.Impersonate (userToken)) { return InternalExecWaitWithCapture (cmd, currentDir, tempFiles, ref outputName, ref errorName); } }
public void Ctor_Empty() { var collection = new TempFileCollection(); Assert.Equal(0, collection.Count); Assert.Empty(collection.TempDir); Assert.False(collection.KeepFiles); }
public void Ctor_String(string tempDir) { var collection = new TempFileCollection(tempDir); Assert.Equal(0, collection.Count); Assert.Equal(tempDir ?? string.Empty, collection.TempDir); Assert.False(collection.KeepFiles); }
public void Ctor_String_Bool(string tempDir, bool keepFiles) { var collection = new TempFileCollection(tempDir, keepFiles); Assert.Equal(0, collection.Count); Assert.Equal(tempDir ?? string.Empty, collection.TempDir); Assert.Equal(keepFiles, collection.KeepFiles); }
public static string Execute(string strCmd, bool bDropFirstLineOfOutput) { string output = ""; string error = ""; TempFileCollection tf = new TempFileCollection(); Executor.ExecWaitWithCapture(strCmd, tf, ref output, ref error); StreamReader sr = File.OpenText(output); StringBuilder strBuilder = new StringBuilder(); string strLine = null; bool bFirstLine = true; while (null != (strLine = sr.ReadLine())) { if ("" != strLine) { if (bFirstLine && bDropFirstLineOfOutput) { bFirstLine = false; continue; } strBuilder.Append(strLine); strBuilder.Append("\r\n"); } } sr.Close(); File.Delete(output); File.Delete(error); return strBuilder.ToString(); }
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 Compilador( string directorio, string nombre, string archivoSalida, string archivoError ) { archivosTemporales = new TempFileCollection(); this.directorio = directorio; this.nombre = nombre; this.archivoSalida = archivoSalida; this.archivoError = archivoError; }
private SolutionBase(TempFileCollection tfc, SolutionTask solutionTask) { _htOutputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); _projectEntries = new ProjectEntryCollection(); _htReferenceProjects = CollectionsUtil.CreateCaseInsensitiveHashtable(); _tfc = tfc; _solutionTask = solutionTask; _outputDir = solutionTask.OutputDir; _webMaps = solutionTask.WebMaps; }
protected SolutionBase(SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) : this(tfc, solutionTask) { if (solutionTask.SolutionFile != null) { _file = solutionTask.SolutionFile; } else { LoadProjectGuids(new ArrayList(solutionTask.Projects.FileNames), false); LoadProjectGuids(new ArrayList(solutionTask.ReferenceProjects.FileNames), true); LoadProjects(gacCache, refResolver, CollectionsUtil.CreateCaseInsensitiveHashtable()); } }
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 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 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"), }); } }
public MSBuildProject(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) : base(xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir) { string cfgname = solutionTask.Configuration; string platform = solutionTask.Platform; _msbuild = MSBuildEngine.CreateMSEngine(solutionTask); _msproj = new Microsoft.Build.BuildEngine.Project(_msbuild); _msproj.FullFileName = projectPath; _msproj.LoadXml(xmlDefinition.OuterXml); _msproj.GlobalProperties.SetProperty("Configuration", cfgname); SetPlatform (platform); if (outputDir != null) _msproj.GlobalProperties.SetProperty("OutputPath", outputDir.FullName); //evaluating _guid = _msproj.GetEvaluatedProperty("ProjectGuid"); _projectDirectory = new DirectoryInfo(_msproj.GetEvaluatedProperty("ProjectDir")); _projectPath = _msproj.GetEvaluatedProperty("ProjectPath"); ProjectEntry projectEntry = solution.ProjectEntries [_guid]; if (projectEntry != null && projectEntry.BuildConfigurations != null) { foreach (ConfigurationMapEntry ce in projectEntry.BuildConfigurations) { Configuration projectConfig = ce.Value; ProjectConfigurations[projectConfig] = new MSBuildConfiguration(this, _msproj, projectConfig); } } else { Configuration projectConfig = new Configuration (cfgname, platform); ProjectConfigurations[projectConfig] = new MSBuildConfiguration(this, _msproj, projectConfig); } //references _references = new ArrayList(); Microsoft.Build.BuildEngine.BuildItemGroup refs = _msproj.GetEvaluatedItemsByName("Reference"); foreach (Microsoft.Build.BuildEngine.BuildItem r in refs) { string rpath = r.FinalItemSpec; string priv = r.GetMetadata("Private"); string hintpath = r.GetMetadata("HintPath"); ReferenceBase reference = new MSBuildAssemblyReference( xmlDefinition, ReferencesResolver, this, gacCache, rpath, priv, hintpath); _references.Add(reference); } refs = _msproj.GetEvaluatedItemsByName("ProjectReference"); foreach (Microsoft.Build.BuildEngine.BuildItem r in refs) { string pguid = r.GetMetadata("Project"); string pname = r.GetMetadata("Name"); string rpath = r.FinalItemSpec; string priv = r.GetMetadata("Private"); ReferenceBase reference = new MSBuildProjectReference( ReferencesResolver, this, solution, tfc, gacCache, outputDir, pguid, pname, rpath, priv); _references.Add(reference); } }
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 MSBuildProjectReference( ReferencesResolver referencesResolver, ProjectBase parent, SolutionBase solution, TempFileCollection tfc, GacCache gacCache, DirectoryInfo outputDir, string pguid, string pname, string rpath, string priv) : base(referencesResolver, parent) { _helper = new MSBuildReferenceHelper(priv, true); string projectFile = solution.GetProjectFileFromGuid(pguid); _project = LoadProject(solution, tfc, gacCache, outputDir, projectFile); }
public void TestInit() { this.temporaryFiles = new TempFileCollection(this.TestContext.TestRunDirectory, keepFiles: false); this.serviceProvider = new ConfigurableServiceProvider(); this.fileSystem = new ConfigurableFileSystem(); this.serviceProvider.RegisterService(typeof(IFileSystem), this.fileSystem); this.testSubject = new RuleSetSerializer(this.serviceProvider); }
public void Constructor1_Deny_Unrestricted () { TempFileCollection tfc = new TempFileCollection (temp); Assert.AreEqual (0, tfc.Count, "Count"); Assert.IsFalse (tfc.KeepFiles, "KeepFiles"); Assert.AreEqual (temp, tfc.TempDir, "TempDir"); tfc.AddFile ("main.cs", false); tfc.CopyTo (array, 0); tfc.Delete (); (tfc as IDisposable).Dispose (); }
internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location, Evidence evidence) { CompilerParameters parameters = new CompilerParameters(); parameters.GenerateInMemory = true; TempFileCollection tempFiles = new TempFileCollection(location); parameters.TempFiles = tempFiles; assembly = GenerateAssembly(xmlMappings, types, defaultNamespace, evidence, parameters, null, assemblies); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (assembly == null) throw new InvalidOperationException(Res.GetString(Res.XmlInternalErrorDetails, "Failed to generate XmlSerializer assembly, but did not throw")); #endif InitAssemblyMethods(xmlMappings); }
public static void Ejecutar( string comando ) { TempFileCollection archivosTemporales = new TempFileCollection(); try { File.Delete( ArchivoSalida ); File.Delete( ArchivoError ); Executor.ExecWaitWithCapture( comando, archivosTemporales, ref ArchivoSalida, ref ArchivoError ); } catch( Exception e ) { throw new Exception( Mensajes.ErrorAlEjecutar( e ) ); } }
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; } }
private void AttachMessageToWorkItem(IIncomingEmailMessage message, int workItemId, string prefix) { using (var tfc = new TempFileCollection()) { var fileName = string.Format("{0}_{1}_{2}.eml", prefix, DateTime.Now.ToString("yyyyMMdd_hhmmss"), new Random().Next()); var filePath = Path.Combine(Path.GetTempPath(), fileName); message.SaveToFile(filePath); // Remove the file once we're done attaching it tfc.AddFile(filePath, false); _workItemManager.AttachFiles(workItemId, new List<string> { filePath }); } }
/// <summary> /// Take attachments from the current mail message and put them in a work item /// </summary> /// <param name="message"></param> private static TempFileCollection SaveAttachments(IIncomingEmailMessage message) { var attachmentFiles = new TempFileCollection(); foreach (var attachment in message.Attachments) { var filename = attachment.SaveAttachmentToFile(); if (filename != null) { attachmentFiles.AddFile(filename, false); Logger.InfoFormat("Attachment saved to file {0}", filename); } } return attachmentFiles; }
/// <summary> /// Initializes a new instance of the <see cref="VBProject"/> class. /// </summary> /// <param name="solution">The solution.</param> /// <param name="projectPath">The project path.</param> /// <param name="xmlDefinition">The XML definition.</param> /// <param name="solutionTask">The solution task.</param> /// <param name="tfc">The TFC.</param> /// <param name="gacCache">The gac cache.</param> /// <param name="refResolver">The reference resolver.</param> /// <param name="outputDir">The output dir.</param> public VBProject(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) : base(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir) { _imports = new NamespaceImportCollection(); // process namespace imports XmlNodeList imports = xmlDefinition.SelectNodes("//Imports/Import"); foreach (XmlElement import in imports) { XmlAttribute nsAttribute = import.Attributes["Namespace"]; if (nsAttribute != null) { string nameSpace = nsAttribute.Value.ToString( CultureInfo.InvariantCulture); _imports.Add(new NamespaceImport(nameSpace)); } } }
internal static int ExecWaitWithCapture(SafeUserTokenHandle userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName, string trueCmdLine) { int retValue = 0; // Undo any current impersonation, call ExecWaitWithCaptureUnimpersonated, and reimpersonate #if !FEATURE_PAL // the extra try-catch is here to mitigate exception filter injection attacks. try { WindowsImpersonationContext impersonation = RevertImpersonation(); try { #endif // Execute the process retValue = ExecWaitWithCaptureUnimpersonated(userToken, cmd, currentDir, tempFiles, ref outputName, ref errorName, trueCmdLine); #if !FEATURE_PAL } finally { ReImpersonate(impersonation); } } catch { throw; } #endif return(retValue); }
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 static int ExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return(ExecWaitWithCapture(null, cmd, currentDir, tempFiles, ref outputName, ref errorName, null)); }
public static int ExecWaitWithCapture(IntPtr userToken, string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return(ExecWaitWithCapture(new SafeUserTokenHandle(userToken, false), cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName, null)); }
[SecurityPermission(SecurityAction.Assert, ControlPrincipal = true)] // UnmanagedCode "covers" more than ControlPrincipal public static Int32 ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { #if NET_2_0 // WindowsImpersonationContext implements IDisposable only in 2.0 using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(userToken)) { return(InternalExecWaitWithCapture(cmd, currentDir, tempFiles, ref outputName, ref errorName)); } #else int result = -1; WindowsImpersonationContext context = WindowsIdentity.Impersonate(userToken); try { result = InternalExecWaitWithCapture(cmd, currentDir, tempFiles, ref outputName, ref errorName); } finally { context.Undo(); context = null; } return(result); #endif }
public static Int32 ExecWaitWithCapture(string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) { return(InternalExecWaitWithCapture(cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName)); }
public static void ExecWait(string cmd, TempFileCollection tempFiles) { string outputName = null, errorName = null; ExecWaitWithCapture(cmd, tempFiles, ref outputName, ref errorName); }
/// <devdoc> /// <para> /// Initializes a new instance of <see cref='System.CodeDom.Compiler.CompilerResults'/> /// that uses the specified /// temporary files. /// </para> /// </devdoc> public CompilerResults(TempFileCollection tempFiles) { _tempFiles = tempFiles; }
public static int ExecWaitWithCapture(string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) => ExecWaitWithCapture(IntPtr.Zero, cmd, currentDir, tempFiles, ref outputName, ref errorName);
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); }
public static int ExecWaitWithCapture(string cmd, TempFileCollection tempFiles, ref string outputName, ref string errorName) => ExecWaitWithCapture(IntPtr.Zero, cmd, Environment.CurrentDirectory, tempFiles, ref outputName, ref errorName);
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); } } }
[SecurityPermission(SecurityAction.Assert, ControlPrincipal = true)] // UnmanagedCode "covers" more than ControlPrincipal public static Int32 ExecWaitWithCapture(IntPtr userToken, string cmd, string currentDir, TempFileCollection tempFiles, ref string outputName, ref string errorName) { // WindowsImpersonationContext implements IDisposable only in 2.0 using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(userToken)) { return(InternalExecWaitWithCapture(cmd, currentDir, tempFiles, ref outputName, ref errorName)); } }