This repository was archived by the owner on Dec 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsoleHelper.cs
More file actions
458 lines (405 loc) · 17.9 KB
/
ConsoleHelper.cs
File metadata and controls
458 lines (405 loc) · 17.9 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
using WinClean.resources;
using System;
using System.Threading;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
namespace WinClean {
/// <summary>
/// The ConsoleHelper class is used for many things. Mainly for reading and writing to console but also to run commands on a command line intepreter (like cmd.exe). Also has some other functions.
/// Use this class instead of the System.Console class as much as possible.
/// </summary>
public class ConsoleHelper {
// === Console Output ===
/// <summary>
/// Writes to the Console with the name "WinClean"
/// </summary>
/// <param name="text">The text to write</param>
public void Write(string text) {
Console.WriteLine(" [WinClean] " + text);
}
/// <summary>
/// Writes to the Console with the specified name
/// </summary>
/// <param name="name">The name to write as</param>
/// <param name="text">The text to write</param>
public void Write(string name, string text) {
if (name != null) {
if (name.Length <= 0) {
Console.WriteLine(" " + text);
} else {
Console.WriteLine(" [" + name + "] " + text);
}
} else {
Write(text);
}
}
/// <summary>
/// Writes to the Console with the name "WinClean" in the specified color
/// </summary>
/// <param name="text">The text to write</param>
/// <param name="color">The color to write in</param>
public void Write(string text, ConsoleColor color) {
Console.ForegroundColor = color;
Write(text);
Console.ForegroundColor = ConsoleColor.White;
}
/// <summary>
/// Writes to the Console with the specified name and in the specified color
/// </summary>
/// <param name="name">The name to write as</param>
/// <param name="text">The text to write</param>
/// <param name="color">The color to write in</param>
public void Write(string name, string text, ConsoleColor color) {
Console.ForegroundColor = color;
Write(name, text);
Console.ForegroundColor = ConsoleColor.White;
}
/// <summary>
/// Writes to the Console in the color red with the name "ERROR"
/// </summary>
/// <param name="text">The text to write</param>
public void WriteError(string text) {
Write("ERROR", text, ConsoleColor.Red);
}
/// <summary>
/// Writes to the Console in ogre with the name "WARN"
/// </summary>
/// <param name="text">The text to write</param>
public void WriteWarn(string text) {
Write("WARN", text, ConsoleColor.DarkYellow);
}
/// <summary>
/// Exits WinClean with a FATAL error message with the specified reason.
/// </summary>
/// <param name="exitCode">The exit code</param>
/// <param name="reason">The reason for the fatal error</param>
public void FatalExit(int exitCode, string reason) {
Write("FATAL", Strings.FatalErrorOccured + " | Reason: " + reason, ConsoleColor.Red);
Exit(exitCode, true);
}
/// <summary>
/// Changes the title of the Window
/// </summary>
/// <example>WinClean v0.0.0 | Example Title</example>
/// <param name="title"></param>
public void Title(string title) {
Console.Title = "WinClean " + WinClean.Version + " | " + title;
}
/// <summary>
/// Clears the console
/// </summary>
public void Clear() {
Console.Clear();
}
/// <summary>
/// Exits WinClean with the specified exit code.
/// </summary>
/// <param name="exitCode">The exit code</param>
/// <param name="message">If a message should be displayed</param>
/// <param name="clearOnExit">If the console should be cleared on exit</param>
public void Exit(int exitCode, bool message = false, bool clearOnExit = true) {
if (message) {
Write(Strings.ExitingWithExitCode.Replace("{exitCode}", exitCode.ToString()));
Thread.Sleep(GetReadingTime(Strings.ExitingWithExitCode.Replace("{exitCode}", exitCode.ToString())));
}
if (clearOnExit) {
Console.Clear();
}
Environment.Exit(exitCode);
}
// === Console Input ===
/// <summary>
/// An option for a selection
/// </summary>
public struct SelectionOption {
/// <summary>
/// The associated number with the option
/// </summary>
public int Number { get; }
/// <summary>
/// The associated text with the option
/// </summary>
public string OptionText { get; }
public SelectionOption(int number, string optionText) {
Number = number;
OptionText = optionText;
}
}
/// <summary>
/// Waits for enter with a default message
/// </summary>
public void EnterToContinue() {
EnterToContinue(Strings.EnterToContinue);
}
/// <summary>
/// Waits for enter with a specified message
/// </summary>
/// <param name="message">The message to write</param>
public void EnterToContinue(string message) {
Write(message);
ConsoleKey key = Console.ReadKey().Key;
while (key != ConsoleKey.Enter) {
key = Console.ReadKey().Key;
}
}
/// <summary>
/// Gets the reading time for a specified text
/// </summary>
/// <param name="text">The text to get the reading time from</param>
/// <returns>The reading time in milliseconds</returns>
public int GetReadingTime(string text) {
string[] words = text.Split(" ");
int wordCount = 0;
foreach (string word in words) {
if (word.Length > 12) {
wordCount++;
}
wordCount++;
}
if (wordCount < 3) {
return Convert.ToInt32(((((float) wordCount / 200 * 60) * 2) + 1) * 1000);
} else {
return Convert.ToInt32((float)wordCount / 200 * 60 * 1000);
}
}
/// <summary>
/// Gets the reading time for multiple texts
/// </summary>
/// <param name="texts">The list ôf texts to get the reading time from</param>
/// <returns>The reading time in milliseconds</returns>
public int GetReadingTime(List<string> texts) {
int readingTime = 0;
foreach (string text in texts) {
readingTime += GetReadingTime(text);
}
return readingTime;
}
/// <summary>
/// Cretes a new selection for the user with the specified question and options
/// </summary>
/// <param name="question">The question the user should answer</param>
/// <param name="options">The options the user has</param>
/// <returns>The selected option</returns>
public SelectionOption CreateSelection(string question, List<SelectionOption> options) {
Write("", "");
Write(question);
foreach (SelectionOption option in options) {
Write("", " " + option.Number + " - " + option.OptionText);
}
Console.Write(" " + Strings.Select + " (" + options.Min(option => option.Number) + "-" + options.Max(option => option.Number) + ") > "); string input = Console.ReadLine();
while (true) {
if (String.IsNullOrWhiteSpace(input)) {
WriteError(Strings.SelectionEmpty);
} else {
if (!int.TryParse(input, out int selectionNum)) {
WriteError(Strings.SelectionNotNumerical);
} else {
if (selectionNum >= options.Min(option => option.Number) && selectionNum <= options.Max(option => option.Number)) {
Write("", "");
return options.Find(option => option.Number == selectionNum);
} else {
WriteError(Strings.SelectionNotInRange);
}
}
}
Console.Write(" " + Strings.Select + " (" + options.Min(option => option.Number) + "-" + options.Max(option => option.Number) + ") > "); input = Console.ReadLine();
}
}
// === Console Run ===
/// <summary>
/// Runs a command on cmd.exe (without showing any window)
/// </summary>
/// <param name="command">The command to run</param>
/// <param name="admin">If the command should be runned as an admin</param>
/// <param name="showOut">If the output of the command should be shown</param>
/// <returns>The exit code of the command line</returns>
public int RunCommand(string command, bool admin = false, bool showOut = false) {
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
if (admin) {
cmd.StartInfo.Verb = "runas";
}
cmd.Start();
cmd.StandardInput.WriteLine(command);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
if (!cmd.WaitForExit(10000)) {
cmd.Kill();
}
if (showOut) {
Write("Console", cmd.StandardOutput.ReadToEnd());
}
return cmd.ExitCode;
}
/// <summary>
/// Runs a command on cmd.exe (without showing any window) and searches the output for strings to check.
/// </summary>
/// <param name="command">The command to run</param>
/// <param name="checks">A list of strings to check the output with</param>
/// <param name="admin">If the command should be runned as an admin</param>
/// <param name="showOut">If the output of the command should be shown</param>
/// <returns>
/// The exit code of the command line and a list of all the checks that have been found in the output.
/// </returns>
public (int, List<string>) RunCommandWithChecks(string command, List<string> checks, bool admin = false, bool showOut = false) {
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
if (admin) {
cmd.StartInfo.Verb = "runas";
}
cmd.Start();
cmd.StandardInput.WriteLine(command);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
if (!cmd.WaitForExit(10000)) {
cmd.Kill();
}
string output = cmd.StandardOutput.ReadToEnd();
if (showOut) {
Write("Console", output);
}
List<string> hits = new List<string>();
foreach (string check in checks) {
if (output.Contains(check)) {
hits.Add(check);
}
}
return (cmd.ExitCode, hits);
}
/// <summary>
/// Runs a command on powershell.exe (without showing any window)
/// </summary>
/// <param name="command">The command to run</param>
/// <param name="admin">If the command should be runned as an admin</param>
/// <param name="showOut">If the output of the command should be shown</param>
/// <returns>The exit code of the command line</returns>
public int RunCommandInPowerShell(string command, bool admin = false, bool showOut = false) {
Process ps = new Process();
ps.StartInfo.FileName = "powershell.exe";
ps.StartInfo.RedirectStandardInput = true;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.CreateNoWindow = true;
ps.StartInfo.UseShellExecute = false;
if (admin) {
ps.StartInfo.Verb = "runas";
}
ps.Start();
ps.StandardInput.WriteLine(command);
ps.StandardInput.Flush();
ps.StandardInput.Close();
if (!ps.WaitForExit(10000)) {
ps.Kill();
}
if (showOut) {
Write("Console", ps.StandardOutput.ReadToEnd());
}
return ps.ExitCode;
}
/// <summary>
/// Runs a command on powershell.exe (without showing any window) and searches the output for strings to check.
/// </summary>
/// <param name="command">The command to run</param>
/// <param name="checks">A list of strings to check the output with</param>
/// <param name="admin">If the command should be runned as an admin</param>
/// <param name="showOut">If the output of the command should be shown</param>
/// <returns>
/// The exit code of the command line and a list of all the checks that have been found in the output.
/// </returns>
public (int, List<string>) RunCommandInPowerShellWithChecks(string command, List<string> checks, bool admin = false, bool showOut = false) {
Process ps = new Process();
ps.StartInfo.FileName = "powershell.exe";
ps.StartInfo.RedirectStandardInput = true;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.CreateNoWindow = true;
ps.StartInfo.UseShellExecute = false;
if (admin) {
ps.StartInfo.Verb = "runas";
}
ps.Start();
ps.StandardInput.WriteLine(command);
ps.StandardInput.Flush();
ps.StandardInput.Close();
if (!ps.WaitForExit(10000)) {
ps.Kill();
}
string output = ps.StandardOutput.ReadToEnd();
if (showOut) {
Write("Console", output);
}
List<string> hits = new List<string>();
foreach (string check in checks) {
if (output.Contains(check)) {
hits.Add(check);
}
}
return (ps.ExitCode, hits);
}
// === Console Font ===
private const int FixedWidthTrueType = 54;
private const int StandardOutputHandle = -11;
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetStdHandle(int nStdHandle);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool SetCurrentConsoleFontEx(IntPtr hConsoleOutput, bool MaximumWindow, ref FontInfo ConsoleCurrentFontEx);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool GetCurrentConsoleFontEx(IntPtr hConsoleOutput, bool MaximumWindow, ref FontInfo ConsoleCurrentFontEx);
private static readonly IntPtr ConsoleOutputHandle = GetStdHandle(StandardOutputHandle);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FontInfo {
internal int cbSize;
internal int FontIndex;
internal short FontWidth;
public short FontSize;
public int FontFamily;
public int FontWeight;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
//[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.wc, SizeConst = 32)]
public string FontName;
}
/// <summary>
/// Changes the font of the console
/// </summary>
/// <param name="font">The font to change to</param>
/// <param name="fontSize">The size of the font. If 0 the previous font size will stay</param>
public FontInfo[] Font(string font, short fontSize = 0) {
Write("Set Current Font: " + font);
FontInfo before = new FontInfo {
cbSize = Marshal.SizeOf<FontInfo>()
};
if (GetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref before)) {
FontInfo set = new FontInfo {
cbSize = Marshal.SizeOf<FontInfo>(),
FontIndex = 0,
FontFamily = FixedWidthTrueType,
FontName = font,
FontWeight = 400,
FontSize = fontSize > 0 ? fontSize : before.FontSize
};
// Get some settings from current font.
if (!SetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref set)) {
WriteError(new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message);
}
FontInfo after = new FontInfo {
cbSize = Marshal.SizeOf<FontInfo>()
};
GetCurrentConsoleFontEx(ConsoleOutputHandle, false, ref after);
return new[] { before, set, after };
} else {
WriteError(new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()).Message);
return null;
}
}
}
}