Esempio n. 1
0
        private void InternalStart(params string[] arguments)
        {
            if (IsRunning)
            {
                throw new InvalidOperationException("The running process must first exit.");
            }


            _isRunning = true;

            _mreProcessExit.Reset();
            _mreOutputDone.Reset();
            _mreErrorDone.Reset();
            _exitCode = 0;
            _stdIn    = null;
            _running  = new Process();

            string stringArgs = "";

            if (_autoEscape)
            {
                stringArgs = ArgumentList.EscapeArguments(arguments);
            }
            else
            {
                stringArgs = ArgumentList.DoNotEscapeArguments(arguments);
            }

            ProcessStartInfo psi = new ProcessStartInfo(_executable, stringArgs);

            psi.WorkingDirectory = this.WorkingDirectory;

            psi.RedirectStandardInput  = true;
            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;
            psi.CreateNoWindow         = true;
            psi.UseShellExecute        = false;
            psi.ErrorDialog            = false;

            _running.StartInfo = psi;

            _running.Exited             += process_Exited;
            _running.OutputDataReceived += process_OutputDataReceived;
            _running.ErrorDataReceived  += process_ErrorDataReceived;

            _running.EnableRaisingEvents = true;
            Trace.TraceInformation("EXEC: {0} {1}", _running.StartInfo.FileName, _running.StartInfo.Arguments);
            _running.Start();

            _stdIn = _running.StandardInput;
            _running.BeginOutputReadLine();
            _running.BeginErrorReadLine();
        }
Esempio n. 2
0
        /// <summary> Returns a debug-view string of process/arguments to execute </summary>
        public override string ToString()
        {
            string stringArguments = "";

            if (_autoEscape)
            {
                stringArguments = ArgumentList.EscapeArguments(_arguments);
            }
            else
            {
                stringArguments = ArgumentList.DoNotEscapeArguments(_arguments);
            }

            return(String.Format("{0} {1}", _executable, stringArguments));
        }
        /// <summary>
        /// Changes the service's executable and arguments
        /// </summary>
        public void SetServiceExeArgs(string exePath, string[] arguments)
        {
            exePath = ArgumentList.EscapeArguments(new string[] { Check.NotEmpty(exePath) });
            if (arguments != null && arguments.Length > 0)
            {
                exePath = String.Format("{0} {1}", exePath, ArgumentList.EscapeArguments(arguments));
            }

            WithServiceHandle(
                ServiceAccessRights.GENERIC_READ | ServiceAccessRights.GENERIC_WRITE,
                delegate(IntPtr svcHandle)
            {
                const int notChanged = -1;
                if (0 ==
                    Win32.ChangeServiceConfig(svcHandle, notChanged, notChanged, notChanged, exePath,
                                              null, IntPtr.Zero, null, null, null, null))
                {
                    throw new Win32Exception();
                }
            }
                );
        }
        /// <summary> Creates the specified service and returns a SvcControlManager for the service created </summary>
        public static SvcControlManager Create(string serviceName, string displayName, bool interactive,
                                               ServiceStartMode startupType, string exePath, string[] arguments,
                                               string accountName, string password)
        {
            exePath = ArgumentList.EscapeArguments(new string[] { Check.NotEmpty(exePath) });
            if (arguments != null && arguments.Length > 0)
            {
                exePath = String.Format("{0} {1}", exePath, ArgumentList.EscapeArguments(arguments));
            }

            using (SCMHandle hScm = new SCMHandle(SCM_ACCESS.SC_MANAGER_CREATE_SERVICE))
            {
                IntPtr hSvc = Win32.CreateService(
                    hScm,
                    serviceName,
                    displayName ?? serviceName,
                    ServiceAccessRights.SERVICE_ALL_ACCESS,
                    SC_SERVICE_TYPE.SERVICE_WIN32_OWN_PROCESS |
                    (interactive ? SC_SERVICE_TYPE.SERVICE_INTERACTIVE_PROCESS : 0),
                    startupType,
                    SC_SERVICE_ERROR_CONTROL.SERVICE_ERROR_NORMAL,
                    exePath,
                    null,
                    null,
                    null,
                    accountName,
                    password);

                if (hSvc == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }

                Win32.CloseServiceHandle(hSvc);
            }

            return(new SvcControlManager(serviceName));
        }
Esempio n. 5
0
 /// <summary> Returns a debug-view string of process/arguments to execute </summary>
 public override string ToString()
 {
     return(String.Format("{0} {1}", _executable, ArgumentList.EscapeArguments(_arguments)));
 }
        public void Generate(IGeneratorArguments input)
        {
            Encoding encoding;

            //auto-convert input encoding to the correct type
            if (_config.InputEncoding != FileEncoding.Default)
            {
                encoding = _config.InputEncoding == FileEncoding.Ascii ? Encoding.ASCII : Encoding.UTF8;
                using (var r = new StreamReader(input.InputPath, detectEncodingFromByteOrderMarks: true))
                {
                    if (encoding.EncodingName != r.CurrentEncoding.EncodingName)
                    {
                        string text = r.ReadToEnd();
                        r.Dispose();
                        File.WriteAllText(input.InputPath, text, encoding);
                    }
                }
            }

            encoding = _config.OutputEncoding == FileEncoding.Ascii ? Encoding.ASCII : Encoding.UTF8;

            //Couple of assertions about PowerShell
            if (_config.Script.Type == ScriptEngine.Language.PowerShell &&
                (_config.StandardInput.Redirect || _config.Arguments.Length > 0))
            {
                throw new ApplicationException(
                          @"Currently PowerShell integration does not support input streams or arguments.
Primarily this is due to circumventing the script-signing requirements. By 
using the '-Command -' argument we avoid signing or setting ExecutionPolicy.");
            }

            using (DebuggingOutput debug = new DebuggingOutput(_config.Debug, input.WriteLine))
            {
                debug.WriteLine("ConfigDir = {0}", _config.BaseDirectory);
                input.ConfigDir = _config.BaseDirectory;

                //Inject arguments into the script
                string script = input.ReplaceVariables(Check.NotNull(_config.Script).Text.Trim());

                if (!String.IsNullOrEmpty(_config.Script.Include))
                {
                    script = File.ReadAllText(CreateFullPath(_config.Script.Include));
                }
                if (_config.Script.Type == ScriptEngine.Language.Exe)
                {
                    script = CreateFullPath(script);
                }

                StringWriter swOutput = new StringWriter();

                List <string> arguments = new List <string>();
                foreach (GeneratorArgument arg in _config.Arguments)
                {
                    arguments.Add(input.ReplaceVariables(arg.Text ?? String.Empty));
                }

                debug.WriteLine("Prepared Script:{0}{1}{0}{2}{0}{1}",
                                Environment.NewLine,
                                "---------------------------------------------",
                                script
                                );

                using (ScriptRunner scriptEngine = new ScriptRunner(_config.Script.Type, script))
                {
                    IRunner runner = scriptEngine;
                    if (input.AllowAppDomains && _config.Script.InvokeAssembly)
                    {
                        runner = AssemblyRunnerCache.Fetch(scriptEngine.ScriptEngine.Executable);
                        arguments.InsertRange(0, scriptEngine.ScriptArguments);
                    }

                    runner.WorkingDirectory = _config.BaseDirectory;
                    string lastErrorMessage           = null;
                    ProcessOutputEventHandler handler =
                        delegate(object o, ProcessOutputEventArgs args)
                    {
                        if (args.Error)
                        {
                            input.WriteLine(lastErrorMessage = args.Data);
                        }
                        else if (_config.StandardOut != null)
                        {
                            debug.WriteLine("std::out: {0}", args.Data);
                            swOutput.WriteLine(args.Data);
                        }
                        else
                        {
                            input.WriteLine(args.Data);
                        }
                    };

                    int exitCode = -1;
                    debug.WriteLine("Executing {0} {1}", runner, ArgumentList.EscapeArguments(arguments.ToArray()));
                    try
                    {
                        runner.OutputReceived += handler;
                        if (_config.StandardInput.Redirect)
                        {
                            exitCode = runner.Run(new StringReader(File.ReadAllText(input.InputPath)), arguments.ToArray());
                        }
                        else
                        {
                            exitCode = runner.Run(arguments.ToArray());
                        }
                    }
                    finally
                    {
                        debug.WriteLine("Exited = {0}", exitCode);
                        runner.OutputReceived -= handler;
                    }

                    if (_config.StandardOut != null)
                    {
                        string target = Path.ChangeExtension(input.InputPath, _config.StandardOut.Extension);
                        using (TempFile file = TempFile.FromExtension(_config.StandardOut.Extension))
                        {
                            File.WriteAllText(file.TempPath, swOutput.ToString(), encoding);
                            File.Copy(file.TempPath, target, true);
                            input.AddOutputFile(target);
                        }
                    }

                    if (exitCode != 0)
                    {
                        string message = "The script returned a non-zero result: " + exitCode;
                        input.WriteLine(message);
                        throw new ApplicationException(String.IsNullOrEmpty(lastErrorMessage) ? message : lastErrorMessage);
                    }
                }

                EnumOutputFiles(input, input.AddOutputFile);
            }
        }