aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.Common/Scripting/CmdCommand.cs
blob: abae98f063b49e105d5937f08d0b324940e8c8c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core;

namespace Tango.PPC.Common.Scripting
{
    public class CmdCommand : ExtendedObject
    {
        private Process _process;

        public String Arguments { get; set; }

        public TimeSpan Timeout { get; set; }

        public CmdCommand(String processName, String arguments)
        {
            Timeout = TimeSpan.FromSeconds(5);

            _process = new Process();
            _process.StartInfo.CreateNoWindow = true;
            _process.StartInfo.FileName = processName;
            _process.StartInfo.UseShellExecute = false;
            _process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            _process.StartInfo.RedirectStandardError = true;
            _process.StartInfo.RedirectStandardOutput = true;
            _process.StartInfo.Arguments = arguments;
            _process.StartInfo.Verb = "runas";
            Arguments = arguments;
        }

        public Task Run()
        {
            return Task.Factory.StartNew(() =>
            {
                LogManager.Log($"Starting process {_process.StartInfo.FileName} with arguments {Arguments}...");
                _process.Start();
                _process.WaitForExit((int)Timeout.TotalMilliseconds);

                if (_process.HasExited)
                {
                    LogManager.Log($"Process exited with exit code {_process.ExitCode}.");
                    LogManager.Log($"Process Standard Output:\n{_process.StandardOutput.ReadToEnd()}");
                    LogManager.Log($"Process Standard Error:\n{_process.StandardError.ReadToEnd()}");
                    if (_process.ExitCode != 0)
                    {
                        throw new IOException($"The process {_process.StartInfo.FileName} has exited with the code {_process.ExitCode}.");
                    }
                }
                else
                {
                    throw new TimeoutException($"The process {_process.StartInfo.FileName} has not exited within the given timeout of {Timeout.TotalSeconds} seconds.");
                }
            });
        }
    }
}