summaryrefslogtreecommitdiff
path: root/DiscoBot/AppControll.cs
blob: c32f3a2b2e1c4d8f46642f9396f14145546c3440 (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DiscoBot
{
    public class ConsoleAppManager
    {
        private readonly string appName;
        private readonly Process process = new Process();
        private readonly object theLock = new object();
        private SynchronizationContext context;
        private string pendingWriteData;

        public ConsoleAppManager(string appName)
        {
            this.appName = appName;

            this.process.StartInfo.FileName = this.appName;
            this.process.StartInfo.RedirectStandardError = true;
            this.process.StartInfo.StandardErrorEncoding = Encoding.UTF8;

            this.process.StartInfo.RedirectStandardInput = true;
            this.process.StartInfo.RedirectStandardOutput = true;
            this.process.EnableRaisingEvents = true;
            this.process.StartInfo.CreateNoWindow = true;

            this.process.StartInfo.UseShellExecute = false;

            this.process.StartInfo.StandardOutputEncoding = Encoding.UTF8;

            this.process.Exited += this.ProcessOnExited;
        }

        public event EventHandler<string> ErrorTextReceived;
        public event EventHandler ProcessExited;
        public event EventHandler<string> StandartTextReceived;

        public int ExitCode
        {
            get { return this.process.ExitCode; }
        }

        public bool Running
        {
            get; private set;
        }

        public void ExecuteAsync(params string[] args)
        {
            if (this.Running)
            {
                throw new InvalidOperationException(
                    "Process is still Running. Please wait for the process to complete.");
            }

            string arguments = string.Join(" ", args);

            this.process.StartInfo.Arguments = arguments;

            this.context = SynchronizationContext.Current;

            this.process.Start();
            this.Running = true;

            new Task(this.ReadOutputAsync).Start();
            new Task(this.WriteInputTask).Start();
            new Task(this.ReadOutputErrorAsync).Start();
        }

        public void Write(string data)
        {
            if (data == null)
            {
                return;
            }

            lock (this.theLock)
            {
                this.pendingWriteData = data;
            }
        }

        public void WriteLine(string data)
        {
            this.Write(data + Environment.NewLine);
        }

        protected virtual void OnErrorTextReceived(string e)
        {
            EventHandler<string> handler = this.ErrorTextReceived;

            if (handler != null)
            {
                if (this.context != null)
                {
                    this.context.Post(delegate { handler(this, e); }, null);
                }
                else
                {
                    handler(this, e);
                }
            }
        }

        protected virtual void OnProcessExited()
        {
            EventHandler handler = this.ProcessExited;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        protected virtual void OnStandartTextReceived(string e)
        {
            EventHandler<string> handler = this.StandartTextReceived;

            if (handler != null)
            {
                if (this.context != null)
                {
                    this.context.Post(delegate { handler(this, e); }, null);
                }
                else
                {
                    handler(this, e);
                }
            }
        }

        private void ProcessOnExited(object sender, EventArgs eventArgs)
        {
            this.OnProcessExited();
        }

        private async void ReadOutputAsync()
        {
            var standart = new StringBuilder();
            char[] buff = new char[1024];
            int length;

            while (this.process.HasExited == false)
            {
                standart.Clear();

                length = await this.process.StandardOutput.ReadAsync(buff, 0, buff.Length);
                char[] temp = new char[1024];
                Array.Copy(buff, temp,  length);
                standart.Append(temp);
                this.OnStandartTextReceived(standart.ToString());
                Thread.Sleep(1);
            }

            this.Running = false;
        }

        private async void ReadOutputErrorAsync()
        {
            var sb = new StringBuilder();

            do
            {
                sb.Clear();
                var buff = new char[1024];
                int length = await this.process.StandardError.ReadAsync(buff, 0, buff.Length);
                char[] temp = new char[1024];
                Array.Copy(buff, temp, length);
                sb.Append(temp);
                this.OnErrorTextReceived(sb.ToString());
                Thread.Sleep(1);
            }
            while (this.process.HasExited == false);
        }

        private async void WriteInputTask()
        {
            while (this.process.HasExited == false)
            {
                Thread.Sleep(1);

                if (this.pendingWriteData != null)
                {
                    await this.process.StandardInput.WriteLineAsync(this.pendingWriteData);
                    await this.process.StandardInput.FlushAsync();

                    lock (this.theLock)
                    {
                        this.pendingWriteData = null;
                    }
                }
            }
        }
    }
}