Commit 37bf94ab2d820576a60b67904ab112779a12a4ec

Authored by Schwirg László
1 parent e76b5118

command mode kialakítása és beillesztése - egyenlőre csak - a ScheduledTaskManager modulba

Vrh.Log4Pro.MaintenanceConsole/App.config
1 1 <?xml version="1.0" encoding="utf-8"?>
2 2 <configuration>
3 3 <configSections>
4   - <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
5   - <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
6   - </configSections>
  4 + <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  5 + <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  6 + </configSections>
7 7 <startup>
8 8 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
9 9 </startup>
... ...
Vrh.Log4Pro.MaintenanceConsole/Config.xml
... ... @@ -187,4 +187,14 @@
187 187 <FolderToClean Directory="@DIR_BAKTMP@" Recurse="True" RemoveEmptyFolder="False" IncludeMask="*.*" />
188 188 </FileCleaner>
189 189  
  190 + <ScheduledTasks>
  191 + <ScheduledTask Name="CP_Archive_WEEKLY" Priority="7" Schedule="WEEKLY" StartTime="04:00" Enable="true" Run="false" Commandname="sc.exe" />
  192 + <ScheduledTask Name="CP_Archive_MONTHLY" Priority="7" Schedule="MONTHLY" StartTime="04:00" Enable="true" Run="false" Commandname="sc.exe" />
  193 + <ScheduledTask Name="CP_Archive_DAILY" Priority="7" Schedule="DAILY" StartTime="04:00" Enable="true" Run="false" Commandname="sc.exe" />
  194 + <ScheduledTask Name="CP_Backup_DAILY" Priority="7" Schedule="DAILY" StartTime="04:20" Enable="true" Run="false" Commandname="sc.exe" />
  195 + <ScheduledTask Name="CP_Backup_HOURLY" Priority="7" Schedule="HOURLY" StartTime="04:00" Enable="false" Run="false" Commandname="sc.exe" />
  196 + <ScheduledTask Name="CP_BackupDBOnly_DAILY" Priority="7" Schedule="DAILY" StartTime="04:40" Enable="true" Run="false" Commandname="sc.exe" />
  197 + <ScheduledTask Name="CP_PurgeFiles_DAILY" Priority="7" Schedule="DAILY" StartTime="05:00" Enable="true" Run="false" Commandname="sc.exe" />
  198 + </ScheduledTasks>
  199 +
190 200 </Configuration>
191 201 \ No newline at end of file
... ...
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - ColorConsole.cs
... ... @@ -16,6 +16,36 @@ namespace Vrh.Log4Pro.MaintenanceConsole
16 16 #region ColorConsole
17 17 public static class ColorConsole
18 18 {
  19 + private static bool silentMode = false;
  20 + private static string[] readlineList = null;
  21 +
  22 + /// Üzenet és utána Billentyűzet lenyomásra vár
  23 + /// </summary>
  24 + /// <param name="text"></param>
  25 + /// <returns></returns>
  26 + public static ConsoleKeyInfo PressAnykeyToContinue(string text = null)
  27 + {
  28 + ColorConsole.WriteLine(text ?? "Press any key to continue...", ConsoleColor.Yellow); return ColorConsole.ReadKey();
  29 + }
  30 +
  31 +
  32 + /// <summary>
  33 + /// Beállítja a command mode-ot, ami azt jelenti, hogy nem ír semmit a konzolra,
  34 + /// és a readline egy előre feltöltött bufferból olvassa az inputokat
  35 + /// </summary>
  36 + /// <param name="silentmode"></param>
  37 + public static void SetSilentMode(bool silentmode=true) { silentMode = silentmode; }
  38 + /// <summary>
  39 + /// Feltölti a command mode readline bufferét egy string tömbbel;
  40 + /// minden ColorConsole.ReadLine a tömb pillanatnyi első elemét adja vissza, amjd törli azt a tömbből
  41 + /// </summary>
  42 + /// <param name="readlinelist"></param>
  43 + public static void SetReadLineList(string[] readlinelist) { readlineList = readlinelist; }
  44 + /// <summary>
  45 + /// A megadott stringet szóközökkel ritkított formában adja vissza
  46 + /// </summary>
  47 + /// <param name="txt"></param>
  48 + /// <returns></returns>
19 49 public static string WideString(string txt)
20 50 {
21 51 if (txt == null) { return null; };
... ... @@ -25,18 +55,116 @@ namespace Vrh.Log4Pro.MaintenanceConsole
25 55 return widetxt.Substring(0, widetxt.Length - 1);
26 56 }
27 57  
  58 + /// <summary>
  59 + /// true, ha van lenyomott billentyű, illetve command mode-ban mindig false
  60 + /// </summary>
  61 + public static bool KeyAvailable { get { if (silentMode) { return false; } else { return Console.KeyAvailable; } } }
  62 +
  63 +
  64 + /// <summary>
  65 + /// Beállítja a console ablak méretét
  66 + /// </summary>
  67 + /// <param name="w"></param>
  68 + /// <param name="h"></param>
  69 + public static void SetWindowSize(int w, int h) { if (!silentMode) { Console.SetWindowSize(w, h); } }
  70 +
  71 + /// <summary>
  72 + /// Visszaadja a lenyomott billentyűt, ha van, commandmode-ban pedig az enter-t
  73 + /// </summary>
  74 + /// <returns></returns>
  75 + public static ConsoleKeyInfo ReadKey()
  76 + {
  77 + if (silentMode) { return GetConsoleKey(ConsoleKey.Enter); }
  78 + else { return Console.ReadKey(); }
  79 + }
  80 +
  81 + /// <summary>
  82 + /// Visszaadja a lenyomott billentyűt, ha van, commandmode-ban pedig az enter-t
  83 + /// </summary>
  84 + /// <returns></returns>
  85 + public static ConsoleKeyInfo GetConsoleKey(ConsoleKey ck, bool shift = false, bool alt=false,bool control=false)
  86 + {
  87 + switch (ck)
  88 + {
  89 + case ConsoleKey.Enter:
  90 + default:
  91 + return new ConsoleKeyInfo(keyChar: '\r', key: ConsoleKey.Enter, shift: shift, alt: alt, control: control);
  92 + }
  93 + }
  94 +
  95 + /// <summary>
  96 + /// Beolvas egy sort a consolról, vagy commandmode-ban a bufferból
  97 + /// </summary>
  98 + /// <param name="text"></param>
  99 + /// <param name="f"></param>
  100 + /// <param name="b"></param>
  101 + /// <param name="bracket"></param>
  102 + /// <param name="prefix"></param>
  103 + /// <returns></returns>
28 104 public static string ReadLine(string text = null, ConsoleColor? f = null, ConsoleColor? b = null, string bracket = null, string prefix = "")
29 105 {
30   - Write(text, f, b,bracket,prefix);
31   - return Console.ReadLine();
  106 + if (silentMode)
  107 + {
  108 + if (readlineList == null || readlineList.Length == 0) { return null; }
  109 + else
  110 + {
  111 + var nextreadline = readlineList[0];
  112 + readlineList = readlineList.Skip(1).ToArray();
  113 + return nextreadline;
  114 + }
  115 + }
  116 + else
  117 + {
  118 + Write(text, f, b, bracket, prefix);
  119 + return Console.ReadLine();
  120 + }
  121 + }
  122 +
  123 + /// <summary>
  124 + /// beállítja a cursor pozíciót
  125 + /// </summary>
  126 + /// <param name="remembercursorleft"></param>
  127 + /// <param name="remembercursortop"></param>
  128 + public static void SetCursorPosition(int remembercursorleft, int remembercursortop)
  129 + {
  130 + if (silentMode) { return; }
  131 + Console.SetCursorPosition(remembercursorleft, remembercursortop);
32 132 }
  133 +
  134 + public static int CursorLeft { get { return Console.CursorLeft; } }
  135 + public static int CursorTop { get { return Console.CursorTop; } }
  136 +
  137 + public static void Clear() { Console.Clear(); }
  138 +
  139 + /// <summary>
  140 + /// Kiír egy karaktersorozatot színesben a konzolra soremeléssel;
  141 + /// command mode-ban nem csinál semmit
  142 + /// </summary>
  143 + /// <param name="text"></param>
  144 + /// <param name="f"></param>
  145 + /// <param name="b"></param>
  146 + /// <param name="bracket"></param>
  147 + /// <param name="prefix"></param>
  148 + /// <param name="suffix"></param>
33 149 public static void WriteLine(string text = null, ConsoleColor? f = null, ConsoleColor? b = null, string bracket = null,string prefix="", string suffix = "")
34 150 {
  151 + if (silentMode) { return; }
35 152 Write(text, f, b, bracket,prefix,suffix);
36 153 Console.WriteLine();
37 154 }
  155 + /// <summary>
  156 + /// Kiír egy karaktersorozatot színesben a konzolra soremelés nélkül;
  157 + /// command mode-ban nem csinál semmit
  158 + /// </summary>
  159 + /// <param name="text"></param>
  160 + /// <param name="f"></param>
  161 + /// <param name="b"></param>
  162 + /// <param name="bracket"></param>
  163 + /// <param name="prefix"></param>
  164 + /// <param name="suffix"></param>
38 165 public static void Write(string text = null, ConsoleColor? f = null, ConsoleColor? b = null, string bracket = null, string prefix = "",string suffix="")
39 166 {
  167 + if (silentMode) { return; }
40 168 if (!string.IsNullOrEmpty(prefix)) { Write(prefix); }
41 169 if (!string.IsNullOrEmpty(bracket) && bracket.Length==1) { bracket = bracket + bracket; }
42 170 if (!string.IsNullOrEmpty(bracket)) { Console.Write($"{bracket[0]}"); }
... ...
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - CommandLineParser.cs
... ... @@ -135,8 +135,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole
135 135 Test(44,"this \"is a\" test", new[] { "this", "is a", "test" });
136 136 Test(45,"\"C:\\Program Files\"", new[] { "C:\\Program Files" });
137 137 Test(46,"\"He whispered to her \\\"I love you\\\".\"", new[] { "He whispered to her \"I love you\"." });
138   - Console.WriteLine("Press a key to continue....");
139   - Console.ReadKey();
  138 + ColorConsole.WriteLine("Press a key to continue....");
  139 + ColorConsole.ReadKey();
140 140 }
141 141 static void Test(int id,string cmd, string[] r)
142 142 {
... ... @@ -149,28 +149,28 @@ namespace Vrh.Log4Pro.MaintenanceConsole
149 149 if (r.Length != sr.Length)
150 150 {
151 151  
152   - Console.WriteLine($"ERROR:{id}");
153   - Console.WriteLine($" cmdline : {cmd}");
154   - Console.WriteLine($" splitted: {scmd}");
155   - Console.WriteLine($" expected: {sexp}");
  152 + ColorConsole.WriteLine($"ERROR:{id}");
  153 + ColorConsole.WriteLine($" cmdline : {cmd}");
  154 + ColorConsole.WriteLine($" splitted: {scmd}");
  155 + ColorConsole.WriteLine($" expected: {sexp}");
156 156 return;
157 157 }
158 158 for (int i = 0; i < r.Length; i++)
159 159 if (r[i] != sr[i])
160 160 {
161   - Console.WriteLine($"ERROR:{id}");
162   - Console.WriteLine($" cmdline : {cmd}");
163   - Console.WriteLine($" splitted: {scmd}");
164   - Console.WriteLine($" expected: {sexp}");
  161 + ColorConsole.WriteLine($"ERROR:{id}");
  162 + ColorConsole.WriteLine($" cmdline : {cmd}");
  163 + ColorConsole.WriteLine($" splitted: {scmd}");
  164 + ColorConsole.WriteLine($" expected: {sexp}");
165 165 return;
166 166 }
167 167 }
168 168 catch (Exception ex)
169 169 {
170   - Console.WriteLine($"EXCEP:{id}");
171   - Console.WriteLine($" cmdline : {cmd}");
172   - Console.WriteLine($" splitted: {scmd}");
173   - Console.WriteLine($" expected: {sexp}");
  170 + ColorConsole.WriteLine($"EXCEP:{id}");
  171 + ColorConsole.WriteLine($" cmdline : {cmd}");
  172 + ColorConsole.WriteLine($" splitted: {scmd}");
  173 + ColorConsole.WriteLine($" expected: {sexp}");
174 174 return;
175 175 }
176 176 }
... ...
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - Menu.cs
... ... @@ -11,11 +11,12 @@ using System.Management;
11 11 using System.Diagnostics;
12 12  
13 13 using Vrh.XmlProcessing;
  14 +using VRH.Common;
14 15 using System.Xml.Linq;
15 16  
16 17 namespace Vrh.Log4Pro.MaintenanceConsole
17 18 {
18   - public class Menu
  19 + public class Menu
19 20 {
20 21 public delegate Object MenuItemExecutorFunc(Object p, Object o);
21 22 public delegate Object MenuItemDisplayerFunc(Object p, int i);
... ... @@ -25,30 +26,71 @@ namespace Vrh.Log4Pro.MaintenanceConsole
25 26 private string Title { get { return ColorConsole.WideString(title); } set { title = value; } }
26 27 private MenuItemDisplayerFunc MenuItemDisplayer;
27 28 private SelectionMode selectionMode = Menu.SelectionMode.Multi;
  29 + private static bool commandModeAllMenus = false;
  30 + private bool commandMode = false;
28 31 private int HeaderWidth = 9;
29 32 private string SelectionPrompt = "Make Your selection!";
30 33 #endregion private fields
31 34  
32 35 #region public properties
33 36 public List<Item> MenuItemList { get; private set; } = new List<Item>();
34   - List<string> MenuKeyList { get { return MenuItemList.Where(x=> !x.Separator).Select(x => x.Key).ToList(); } }
  37 + List<string> MenuKeyList { get { return MenuItemList.Where(x => !x.Separator).Select(x => x.Key).ToList(); } }
35 38 #endregion public properties
36 39  
37 40 #region public tools
  41 +
  42 + /// <summary>
  43 + /// Incorrect selection console üzenet megjelenítése
  44 + /// </summary>
  45 + /// <param name="partxt"></param>
  46 + public static void IncorrectSelection(string partxt = "")
  47 + {
  48 + if (GetCommandModeAllMenus()) { return; }
  49 +
  50 + ColorConsole.WriteLine();
  51 + ColorConsole.WriteLine($"Incorrect selection! {partxt} Make a new selection!", ConsoleColor.Red);
  52 + Menu.PressAnykeyToContinue();
  53 + }
  54 +
  55 + /// <summary>
  56 + /// Üzenet és utána Billentyűzet lenyomásra vár
  57 + /// </summary>
  58 + /// <param name="text"></param>
  59 + /// <returns></returns>
  60 + public static ConsoleKeyInfo PressAnykeyToContinue(string text = null)
  61 + {
  62 + if (GetCommandModeAllMenus()) { return ColorConsole.GetConsoleKey(ConsoleKey.Enter); }
  63 +
  64 + ColorConsole.WriteLine(text ?? "Press any key to continue...", ConsoleColor.Yellow); return ColorConsole.ReadKey();
  65 + }
  66 +
  67 +
  68 + public static void SetCommandModeAllMenus() { commandModeAllMenus = true; }
  69 +
38 70 public Menu SetMenuItemDisplayer(MenuItemDisplayerFunc displayer)
39 71 {
40 72 MenuItemDisplayer = displayer;
41 73 return this;
42 74 }
43 75 public Menu SetSelectionMode(SelectionMode sm) { selectionMode = sm; return this; }
44   - public Menu SetHeaderWidth(int hw) { HeaderWidth= hw; return this; }
45   - public Menu AddMenuItem(Item mi)
46   - {
  76 + public Menu SetCommandMode(bool commandmode = false) { commandMode = true; return this; }
  77 + public static bool GetCommandModeAllMenus() { return commandModeAllMenus; }
  78 + public bool GetCommandMode() { return commandMode || commandModeAllMenus; }
  79 + public Menu SetHeaderWidth(int hw) { HeaderWidth = hw; return this; }
  80 + public Menu AddMenuItem(Item mi)
  81 + {
47 82 MenuItemList.Add(mi);
48 83 if (string.IsNullOrWhiteSpace(mi.Key)) { mi.Key = $"#$KEY{MenuItemList.IndexOf(mi)}"; }
49 84 return this;
50 85 }
51 86 public void ClearMenuItemList() { MenuItemList.Clear(); }
  87 + public void ExecuteCmd(string[] args)
  88 + {
  89 + var module = CommandLine.GetCommandLineArgument(args, "-MODULE");
  90 + var sr = new Menu.Selection(module, args);
  91 + ExecuteSelection(sr);
  92 + }
  93 +
52 94 public void ExecuteMenu()
53 95 {
54 96 try
... ... @@ -61,65 +103,69 @@ namespace Vrh.Log4Pro.MaintenanceConsole
61 103 if (sr.Result == Menu.SelectionResult.Exit) { return; }
62 104 else if (sr.Result == Menu.SelectionResult.None) { continue; }
63 105 else if (sr.Result == Menu.SelectionResult.Error) { continue; }
64   - Execute(sr.SelectedKeyList);
  106 + ExecuteSelection(sr.SelectedKeyList);
65 107 }
66 108 }
67   - catch (Exception ex)
68   - {
69   - ColorConsole.WriteLine(ex.Message,ConsoleColor.Red);
  109 + catch (Exception ex)
  110 + {
  111 + ColorConsole.WriteLine(ex.Message, ConsoleColor.Red);
70 112 if (ex.InnerException != null) { ColorConsole.WriteLine(ex.InnerException.Message, ConsoleColor.Red); }
71   - ColorConsole.WriteLine("Press any key to continue...");
  113 + Menu.PressAnykeyToContinue();
72 114 }
73 115 }
74 116 public void DisplayTitle()
75 117 {
76   - Console.Clear();
  118 + if (GetCommandMode()) { return; }
  119 +
  120 + ColorConsole.Clear();
77 121 ColorConsole.WriteLine(Title, ConsoleColor.White);
78 122 ColorConsole.WriteLine(new string('-', Title.Length));
79 123 }
80 124 public void DisplayItems(int columns = 1, int columnlength = 0)
81 125 {
  126 + if (GetCommandMode()) { return; }
  127 +
82 128 int columncounter = 0;
83 129 ColorConsole.WriteLine();
84 130 var i = 1;
85   - Console.SetCursorPosition(0, Console.CursorTop);
86   - foreach (var menuitem in MenuItemList)
  131 + ColorConsole.SetCursorPosition(0, ColorConsole.CursorTop);
  132 + foreach (var menuitem in MenuItemList)
87 133 {
88 134 if (menuitem.Separator && columns == 1)
89 135 {
90   - Console.SetCursorPosition(columnlength * columncounter + HeaderWidth, Console.CursorTop);
  136 + ColorConsole.SetCursorPosition(columnlength * columncounter + HeaderWidth, ColorConsole.CursorTop);
91 137 var seplen = menuitem.SeparatorLength;
92   - if (menuitem.SeparatorLength==0)
  138 + if (menuitem.SeparatorLength == 0)
93 139 {
94   - foreach (var mi in MenuItemList.Where(x=>!x.Separator)) { if (mi.Text.Length > seplen) { seplen = mi.Text.Length; } }
  140 + foreach (var mi in MenuItemList.Where(x => !x.Separator)) { if (mi.Text.Length > seplen) { seplen = mi.Text.Length; } }
95 141 }
96 142 ColorConsole.WriteLine(new string(menuitem.SeparatorChar, seplen));
97 143 continue;
98 144 }
99 145 ColorConsole.Write($"[");
100 146 ColorConsole.Write($"{i}");
101   - if (!string.IsNullOrEmpty(menuitem.Key) && !menuitem.Key.StartsWith("#$KEY"))
  147 + if (!string.IsNullOrEmpty(menuitem.Key) && !menuitem.Key.StartsWith("#$KEY"))
102 148 {
103 149 ColorConsole.Write($":");
104 150 ColorConsole.Write(menuitem.Key, ConsoleColor.Yellow);
105 151 }
106 152 ColorConsole.Write($"]");
107   - Console.SetCursorPosition(columnlength * columncounter+HeaderWidth, Console.CursorTop);
  153 + ColorConsole.SetCursorPosition(columnlength * columncounter + HeaderWidth, ColorConsole.CursorTop);
108 154  
109 155 if (!string.IsNullOrEmpty(menuitem.Text))
110 156 {
111   - ColorConsole.Write(menuitem.Text);
  157 + ColorConsole.Write(menuitem.Text);
112 158 }
113 159 if (columns == 1)
114 160 {
115 161 if (!string.IsNullOrEmpty(menuitem.Text)) { ColorConsole.WriteLine(); }
116   - if (MenuItemDisplayer != null)
  162 + if (MenuItemDisplayer != null)
117 163 {
118   - for (var li = 0; li < 100; li++)
119   - {
120   - if (li>0) { ColorConsole.Write(new string(' ',HeaderWidth)); }
  164 + for (var li = 0; li < 100; li++)
  165 + {
  166 + if (li > 0) { ColorConsole.Write(new string(' ', HeaderWidth)); }
121 167 var str = (string)MenuItemDisplayer(menuitem.Parameters, li);
122   - if (string.IsNullOrEmpty(str)) { Console.SetCursorPosition(0, Console.CursorTop); }
  168 + if (string.IsNullOrEmpty(str)) { ColorConsole.SetCursorPosition(0, ColorConsole.CursorTop); }
123 169 if (str == null) { break; }
124 170 }
125 171 }
... ... @@ -130,49 +176,63 @@ namespace Vrh.Log4Pro.MaintenanceConsole
130 176 if (columncounter == columns) { ColorConsole.WriteLine(); columncounter = 0; }
131 177 else
132 178 {
133   - Console.SetCursorPosition(columnlength * columncounter - 2, Console.CursorTop);
  179 + ColorConsole.SetCursorPosition(columnlength * columncounter - 2, ColorConsole.CursorTop);
134 180 ColorConsole.Write(" ");
135 181 }
136 182 }
137 183 i++;
138 184 }
139 185 if (columns != 1) { ColorConsole.WriteLine(); }
140   - if (selectionMode==SelectionMode.Multi)
  186 + if (selectionMode == SelectionMode.Multi)
141 187 {
142   - ColorConsole.Write("*", ConsoleColor.Red,bracket:"()");ColorConsole.WriteLine(" All");
  188 + ColorConsole.Write("*", ConsoleColor.Red, bracket: "()"); ColorConsole.WriteLine(" All");
143 189 }
144   - ColorConsole.Write("EX", ConsoleColor.Red,bracket:"()");ColorConsole.WriteLine(" Exit");
  190 + ColorConsole.Write("EX", ConsoleColor.Red, bracket: "()"); ColorConsole.WriteLine(" Exit");
145 191 }
146 192 public class Selection
147 193 {
  194 + public Selection() { }
  195 + public Selection(string selectedkey,object parameter)
  196 + {
  197 + Result = SelectionResult.Ok;
  198 + SelectedKeyList = new List<string>() { { selectedkey } };
  199 + SelectedParameterList = new List<object>() { { parameter } };
  200 + }
148 201 public List<string> SelectedKeyList = null;
149 202 public SelectionResult Result;
150 203 public List<object> SelectedParameterList;
151 204 }
152 205 public enum SelectionResult { Exit, None, Error, Ok, }
153 206 public enum SelectionMode { Single, Multi, }
154   - public Selection Select()
  207 + public Selection Select(string forcedselectionkeylist=null)
155 208 {
156   - List<string> selectionKeyList=null;
157   - List<object> selectionParList = null;
158   - var result = new Selection();
  209 + List<string> selectionKeyList;
  210 + List<object> selectionParList;
159 211 string selectionliststr;
160   - ColorConsole.Write(SelectionPrompt,ConsoleColor.Yellow);
161   - ColorConsole.Write(" --> ", ConsoleColor.White);
162   - var remembercursorleft = Console.CursorLeft;
163   - var remembercursortop = Console.CursorTop;
164   - if (selectionMode == SelectionMode.Multi)
  212 + var result = new Selection();
  213 + if (GetCommandMode())
165 214 {
166   - ColorConsole.WriteLine();
167   - ColorConsole.WriteLine("Multiple selections are separated with comma(,), enter asterisk(*) to select all)!");
  215 + selectionliststr = forcedselectionkeylist??"EX";
168 216 }
169   - var remembercursorleft2 = Console.CursorLeft;
170   - var remembercursortop2 = Console.CursorTop;
171   - Console.SetCursorPosition(remembercursorleft, remembercursortop);
172   - selectionliststr = Console.ReadLine().ToUpper();
173   - if (selectionMode == SelectionMode.Multi)
  217 + else
174 218 {
175   - Console.SetCursorPosition(remembercursorleft2, remembercursortop2);
  219 + ColorConsole.Write(SelectionPrompt, ConsoleColor.Yellow);
  220 + ColorConsole.Write(" --> ", ConsoleColor.White);
  221 + var remembercursorleft = ColorConsole.CursorLeft;
  222 + var remembercursortop = ColorConsole.CursorTop;
  223 + if (selectionMode == SelectionMode.Multi)
  224 + {
  225 + ColorConsole.WriteLine();
  226 + ColorConsole.WriteLine("Multiple selections are separated with comma(,), enter asterisk(*) to select all!");
  227 + }
  228 + var remembercursorleft2 = ColorConsole.CursorLeft;
  229 + var remembercursortop2 = ColorConsole.CursorTop;
  230 + ColorConsole.SetCursorPosition(remembercursorleft, remembercursortop);
  231 + selectionliststr = ColorConsole.ReadLine().ToUpper();
  232 + if (selectionMode == SelectionMode.Multi)
  233 + {
  234 + ColorConsole.SetCursorPosition(remembercursorleft2, remembercursortop2);
  235 + }
176 236 }
177 237 if (selectionliststr == "EX")
178 238 {
... ... @@ -186,37 +246,37 @@ namespace Vrh.Log4Pro.MaintenanceConsole
186 246 result.SelectedKeyList = null;
187 247 return result;
188 248 }
189   - else if (selectionMode == SelectionMode.Multi && selectionliststr == "*")
  249 + else if (selectionMode == SelectionMode.Multi && selectionliststr == "*")
190 250 {
191 251 selectionKeyList = new List<string>();
192 252 selectionParList = new List<object>();
193 253 var i = 1;
194   - foreach (var mi in MenuItemList)
195   - {
  254 + foreach (var mi in MenuItemList)
  255 + {
196 256 selectionKeyList.Add(mi.Key);
197 257 selectionParList.Add(mi.Parameters);
198 258 }
199 259 result.Result = SelectionResult.Ok;
200 260 result.SelectedKeyList = selectionKeyList;
201   - result.SelectedParameterList= selectionParList;
202   - return result;
  261 + result.SelectedParameterList = selectionParList;
  262 + return result;
203 263 }
204 264 selectionKeyList = new List<string>();
205 265 selectionParList = new List<object>();
206 266 foreach (var selection in selectionliststr.Split(',').ToList())
207 267 {
208 268 string _selection = selection;
209   - object _parameters=null;
  269 + object _parameters = null;
210 270 if (!MenuKeyList.Contains(_selection))
211 271 {
212 272 if (!int.TryParse(_selection, out int indexselection) || indexselection < 1 || indexselection > MenuItemList.Count())
213 273 {
214   - IncorrectSelection($"Selected item {_selection} is not valid!");
  274 + Menu.IncorrectSelection($"Selected item {_selection} is not valid!");
215 275 result.Result = SelectionResult.Error;
216 276 result.SelectedKeyList = null;
217 277 return result;
218 278 }
219   - _selection = GetItemKey(indexselection-1);
  279 + _selection = GetItemKey(indexselection - 1);
220 280 _parameters = GetItem(indexselection - 1).Parameters;
221 281 }
222 282 selectionKeyList.Add(_selection);
... ... @@ -227,15 +287,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole
227 287 result.SelectedParameterList = selectionParList;
228 288 return result;
229 289 }
230   - public static void IncorrectSelection(string partxt="")
231   - {
232   - ColorConsole.WriteLine();
233   - ColorConsole.WriteLine($"Incorrect selection! {partxt} Make a new selection!",ConsoleColor.Red);
234   - Console.WriteLine("Press a key to continue...");
235   - Console.ReadKey();
236   - }
237   -
238   - public void Execute(List<string> selectedkeylist)
  290 + public void ExecuteSelection(List<string> selectedkeylist)
239 291 {
240 292 object o = null;
241 293 foreach (var mi in MenuItemList)
... ... @@ -245,7 +297,20 @@ namespace Vrh.Log4Pro.MaintenanceConsole
245 297 o = mi.Executor(mi.Parameters, o);
246 298 }
247 299 }
248   - ColorConsole.WriteLine("Press any key to continue...", ConsoleColor.Yellow); Console.ReadKey();
  300 + Menu.PressAnykeyToContinue();
  301 + }
  302 +
  303 + public void ExecuteSelection(Menu.Selection sr)
  304 + {
  305 + object o = null;
  306 + foreach (var mi in MenuItemList)
  307 + {
  308 + if (sr.SelectedKeyList.Contains(mi.Key))
  309 + {
  310 + o = mi.Executor(sr.SelectedParameterList.ElementAt(sr.SelectedKeyList.IndexOf(mi.Key)), o);
  311 + }
  312 + }
  313 + Menu.PressAnykeyToContinue();
249 314 }
250 315 public MenuItemExecutorFunc GetExecutor(string key)
251 316 {
... ... @@ -278,7 +343,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole
278 343 {
279 344 return MenuKeyList.ElementAt(ix);
280 345 }
281   - public void SetParameters(Menu.Selection r, object p=null)
  346 + public void SetExecutorParameters(Menu.Selection r, object p=null)
282 347 {
283 348 foreach (var mi in this.MenuItemList)
284 349 {
... ...
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - Tools.cs 0 → 100644
... ... @@ -0,0 +1,76 @@
  1 +using System;
  2 +using System.IO;
  3 +using System.Collections.Generic;
  4 +using System.Linq;
  5 +using System.Security.Principal;
  6 +using System.Text;
  7 +using System.Threading.Tasks;
  8 +using System.Threading;
  9 +
  10 +using Microsoft.Web.Administration;
  11 +using System.Management;
  12 +using System.Diagnostics;
  13 +
  14 +using Vrh.XmlProcessing;
  15 +using System.Xml.Linq;
  16 +
  17 +namespace Vrh.Log4Pro.MaintenanceConsole
  18 +{
  19 + public static class Tools
  20 + {
  21 + public static bool IsElevated
  22 + {
  23 + get
  24 + {
  25 + return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
  26 + }
  27 + }
  28 + public static string ExecuteAndGetStdIo(string exepath, string args)
  29 + {
  30 + StringBuilder outputBuilder = new StringBuilder();
  31 + StringBuilder erroroutputBuilder = new StringBuilder();
  32 + ProcessStartInfo startInfo = new ProcessStartInfo() { };
  33 + using (Process exeProcess = new Process())
  34 + {
  35 + startInfo.CreateNoWindow = true;
  36 + startInfo.WindowStyle = ProcessWindowStyle.Hidden;
  37 + startInfo.RedirectStandardOutput = true;
  38 + startInfo.RedirectStandardError= true;
  39 + startInfo.RedirectStandardInput = true;
  40 + startInfo.UseShellExecute = false;
  41 + startInfo.FileName = exepath;
  42 + startInfo.Verb= "runas";
  43 + startInfo.Arguments = args;
  44 +
  45 + exeProcess.StartInfo = startInfo;
  46 + // enable raising events because Process does not raise events by default
  47 + exeProcess.EnableRaisingEvents = true;
  48 + exeProcess.OutputDataReceived += new DataReceivedEventHandler
  49 + (
  50 + delegate (object sender, DataReceivedEventArgs e)
  51 + {
  52 + // append the new data to the data already read-in
  53 + outputBuilder.Append(e.Data + "\r\n");
  54 + }
  55 + );
  56 + exeProcess.ErrorDataReceived += new DataReceivedEventHandler
  57 + (
  58 + delegate (object sender, DataReceivedEventArgs e)
  59 + {
  60 + // append the new data to the data already read-in
  61 + erroroutputBuilder.Append(e.Data + "\r\n");
  62 + }
  63 + );
  64 + // start the process
  65 + // then begin asynchronously reading the output
  66 + // then wait for the process to exit
  67 + // then cancel asynchronously reading the output
  68 + exeProcess.Start();
  69 + exeProcess.BeginOutputReadLine();
  70 + exeProcess.WaitForExit();
  71 + exeProcess.CancelOutputRead();
  72 + return outputBuilder.ToString();
  73 + }
  74 + }
  75 + }
  76 +}
... ...
Vrh.Log4Pro.MaintenanceConsole/Manager - FileCleanerManager.cs
... ... @@ -42,8 +42,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole
42 42 if (sr.Result == Menu.SelectionResult.Exit) { break; }
43 43 else if (sr.Result == Menu.SelectionResult.None) { continue; }
44 44 else if (sr.Result == Menu.SelectionResult.Error) { continue; }
45   - menufunctions.SetParameters(sr,config);
46   - menufunctions.Execute(sr.SelectedKeyList);
  45 + menufunctions.SetExecutorParameters(sr,config);
  46 + menufunctions.ExecuteSelection(sr.SelectedKeyList);
47 47 }
48 48 return null;
49 49 }
... ... @@ -309,7 +309,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole
309 309 #endregion GetDefinitionList
310 310 }
311 311 #endregion FileCleanerManagerCoreXmlProcessor class
312   - #region WindowsService class
  312 +
  313 + #region FolderToClean class
313 314 public class FolderToClean : XmlLinqBase
314 315 {
315 316 #region fields
... ... @@ -499,6 +500,5 @@ namespace Vrh.Log4Pro.MaintenanceConsole
499 500 }
500 501 #endregion XmlStructure
501 502 }
502   - #endregion WindowsService class
503   -
  503 + #endregion FolderToClean class
504 504 }
... ...
Vrh.Log4Pro.MaintenanceConsole/Manager - MaintenanceToolManager.cs
... ... @@ -43,8 +43,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole
43 43 if (sr.Result == Menu.SelectionResult.Exit) { break; }
44 44 else if (sr.Result == Menu.SelectionResult.None) { continue; }
45 45 else if (sr.Result == Menu.SelectionResult.Error) { continue; }
46   - menufunctions.SetParameters(sr,config);
47   - menufunctions.Execute(sr.SelectedKeyList);
  46 + menufunctions.SetExecutorParameters(sr,config);
  47 + menufunctions.ExecuteSelection(sr.SelectedKeyList);
48 48 }
49 49 return null;
50 50 }
... ... @@ -80,7 +80,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole
80 80 ColorConsole.WriteLine(regexmatch.Groups[groupname].Value, ConsoleColor.Yellow);
81 81 }
82 82 }
83   - ColorConsole.ReadLine($"Press any key to continue...");
  83 + ColorConsole.PressAnykeyToContinue();
84 84 }
85 85 return o;
86 86 }
... ...
Vrh.Log4Pro.MaintenanceConsole/Manager - ScheduledTaskManager.cs 0 → 100644
... ... @@ -0,0 +1,577 @@
  1 +using System;
  2 +using System.IO;
  3 +using System.Configuration.Install;
  4 +using System.Collections.Generic;
  5 +using System.Linq;
  6 +using System.ServiceProcess;
  7 +using System.Text;
  8 +using System.Threading;
  9 +using System.Threading.Tasks;
  10 +
  11 +using Microsoft.Web.Administration;
  12 +using System.Management;
  13 +using System.Diagnostics;
  14 +
  15 +using Vrh.XmlProcessing;
  16 +using VRH.Common;
  17 +using System.Xml.Linq;
  18 +using System.Text.RegularExpressions;
  19 +
  20 +namespace Vrh.Log4Pro.MaintenanceConsole
  21 +{
  22 + #region ScheduledTaskManager class
  23 + public static class ScheduledTaskmanagerManager
  24 + {
  25 + private const string XMLCONNECTIONSTRING = "file=Config.Xml;element=ScheduledTasks;";
  26 +
  27 + #region Execute
  28 + public static object Execute(object o1 = null, object o2 = null)
  29 + {
  30 + var args = o1 as string[];
  31 + var module = CommandLine.GetCommandLineArgument(args, "-MODULE");
  32 + var functionkey = CommandLine.GetCommandLineArgument(args, "-FUNCTION");
  33 +
  34 + string xmlcs = XMLCONNECTIONSTRING;
  35 + var config = new ScheduledTaskManagerCoreXmlProcessor(xmlcs, "", "hu-HU");
  36 + var menufunctions = new Menu("Manage Scheduled tasks", "Select the management function!")
  37 + .AddMenuItem(new Menu.Item("INS", "Install scheduled task", Install))
  38 + .AddMenuItem(new Menu.Item("UIN", "Uninstall scheduled task", Uninstall))
  39 + .AddMenuItem(new Menu.Item("RUN", "Start scheduled task", Run))
  40 + .AddMenuItem(new Menu.Item("END", "Stop scheduled task", End))
  41 + .AddMenuItem(new Menu.Item("ENA", "Enable scheduled task", Enable))
  42 + .AddMenuItem(new Menu.Item("DIS", "Disable scheduled task", Disable))
  43 + .AddMenuItem(new Menu.Item("CHP", "Change scheduled task priority", ChangePriority))
  44 + .SetSelectionMode(Menu.SelectionMode.Single);
  45 +
  46 + while (true)
  47 + {
  48 + Menu.Selection sr;
  49 +
  50 + menufunctions.DisplayTitle();
  51 + DisplayTasks(config);
  52 + menufunctions.DisplayItems();
  53 + sr = menufunctions.Select(functionkey);
  54 + if (sr.Result == Menu.SelectionResult.Exit) { break; }
  55 + else if (sr.Result == Menu.SelectionResult.None) { continue; }
  56 + else if (sr.Result == Menu.SelectionResult.Error) { continue; }
  57 + menufunctions.SetExecutorParameters(sr, new ScheduledTaskExecutorParameter (config,args));
  58 + menufunctions.ExecuteSelection(sr.SelectedKeyList);
  59 + if (menufunctions.GetCommandMode()) { break; }
  60 + }
  61 + return o2;
  62 + }
  63 + #endregion Execute
  64 + #region ScheduledTaskFunctionExecutorParameter
  65 + public class ScheduledTaskExecutorParameter
  66 + {
  67 + public ScheduledTaskExecutorParameter(ScheduledTaskManagerCoreXmlProcessor cfg, string[] args) { Config = cfg;Args = args; }
  68 + public ScheduledTaskManagerCoreXmlProcessor Config;
  69 + public string[] Args;
  70 + }
  71 + #endregion ScheduledTaskFunctionExecutorParameter
  72 + #region First level Executors with UI
  73 + private static object ChangePriority(object parameter, object o)
  74 + {
  75 + var config = (parameter as ScheduledTaskExecutorParameter).Config;
  76 + var args = (parameter as ScheduledTaskExecutorParameter).Args;
  77 +
  78 + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS");
  79 +
  80 + var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(ChangePriority)}'!");
  81 +
  82 + Menu.Selection sr = menufolders.Select(selectedtaskindexes);
  83 + if (sr.Result == Menu.SelectionResult.Exit) { return o; }
  84 + else if (sr.Result == Menu.SelectionResult.None) { return o; }
  85 + else if (sr.Result == Menu.SelectionResult.Error) { return o; }
  86 + else if (sr.Result == Menu.SelectionResult.Ok) { }
  87 + else { }
  88 + foreach (var p in sr.SelectedParameterList)
  89 + {
  90 + ScheduledTask st = p as ScheduledTask;
  91 + try
  92 + {
  93 + ScheduledTaskManagerCore.SetPriority(st.Xml_Name,st.Xml_Priority);
  94 + ColorConsole.WriteLine($"Priority changed for scheduled task. Name:{st.Xml_Name}", ConsoleColor.Green);
  95 + }
  96 + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); }
  97 + }
  98 + return o;
  99 + }
  100 + private static object Disable(object parameter, object o)
  101 + {
  102 + var config = (parameter as ScheduledTaskExecutorParameter).Config;
  103 + var args = (parameter as ScheduledTaskExecutorParameter).Args;
  104 +
  105 + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS");
  106 +
  107 + var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Disable)}'!");
  108 +
  109 + Menu.Selection sr = menufolders.Select(selectedtaskindexes);
  110 + if (sr.Result == Menu.SelectionResult.Exit) { return o; }
  111 + else if (sr.Result == Menu.SelectionResult.None) { return o; }
  112 + else if (sr.Result == Menu.SelectionResult.Error) { return o; }
  113 + else if (sr.Result == Menu.SelectionResult.Ok) { }
  114 + else { }
  115 + foreach (var p in sr.SelectedParameterList)
  116 + {
  117 + ScheduledTask st = p as ScheduledTask;
  118 + try
  119 + {
  120 + ScheduledTaskManagerCore.DisableTask(st.Xml_Name);
  121 + ColorConsole.WriteLine($"Scheduled task disabled. Name:{st.Xml_Name}", ConsoleColor.Green);
  122 + }
  123 + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); }
  124 + }
  125 + return o;
  126 + }
  127 + private static object Enable(object parameter, object o)
  128 + {
  129 + var config = (parameter as ScheduledTaskExecutorParameter).Config;
  130 + var args = (parameter as ScheduledTaskExecutorParameter).Args;
  131 +
  132 + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS");
  133 +
  134 + var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Enable)}'!");
  135 +
  136 + Menu.Selection sr = menufolders.Select(selectedtaskindexes);
  137 + if (sr.Result == Menu.SelectionResult.Exit) { return o; }
  138 + else if (sr.Result == Menu.SelectionResult.None) { return o; }
  139 + else if (sr.Result == Menu.SelectionResult.Error) { return o; }
  140 + else if (sr.Result == Menu.SelectionResult.Ok) { }
  141 + else { }
  142 + foreach (var p in sr.SelectedParameterList)
  143 + {
  144 + ScheduledTask st = p as ScheduledTask;
  145 + try
  146 + {
  147 + ScheduledTaskManagerCore.EnableTask(st.Xml_Name);
  148 + ColorConsole.WriteLine($"Scheduled task enabled. Name:{st.Xml_Name}", ConsoleColor.Green);
  149 + }
  150 + catch (Exception ex){ ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); }
  151 + }
  152 + return o;
  153 + }
  154 + private static object End(object parameter, object o)
  155 + {
  156 + var config = (parameter as ScheduledTaskExecutorParameter).Config;
  157 + var args = (parameter as ScheduledTaskExecutorParameter).Args;
  158 +
  159 + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS");
  160 +
  161 + var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(End)}'!");
  162 +
  163 + Menu.Selection sr = menufolders.Select(selectedtaskindexes);
  164 + if (sr.Result == Menu.SelectionResult.Exit) { return o; }
  165 + else if (sr.Result == Menu.SelectionResult.None) { return o; }
  166 + else if (sr.Result == Menu.SelectionResult.Error) { return o; }
  167 + else if (sr.Result == Menu.SelectionResult.Ok) { }
  168 + else { }
  169 + foreach (var p in sr.SelectedParameterList)
  170 + {
  171 + ScheduledTask st = p as ScheduledTask;
  172 + try
  173 + {
  174 + ScheduledTaskManagerCore.EndTask(st.Xml_Name);
  175 + ColorConsole.WriteLine($"Scheduled task stopped. Name:{st.Xml_Name}", ConsoleColor.Green);
  176 + }
  177 + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); }
  178 + }
  179 + return o;
  180 + }
  181 + private static object Run(object parameter, object o)
  182 + {
  183 + var config = (parameter as ScheduledTaskExecutorParameter).Config;
  184 + var args = (parameter as ScheduledTaskExecutorParameter).Args;
  185 +
  186 + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS");
  187 +
  188 + var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Run)}'!");
  189 +
  190 + Menu.Selection sr = menufolders.Select(selectedtaskindexes);
  191 + if (sr.Result == Menu.SelectionResult.Exit) { return o; }
  192 + else if (sr.Result == Menu.SelectionResult.None) { return o; }
  193 + else if (sr.Result == Menu.SelectionResult.Error) { return o; }
  194 + else if (sr.Result == Menu.SelectionResult.Ok) { }
  195 + else { }
  196 + foreach (var p in sr.SelectedParameterList)
  197 + {
  198 + ScheduledTask st = p as ScheduledTask;
  199 + try
  200 + {
  201 + ScheduledTaskManagerCore.RunTask(st.Xml_Name);
  202 + ColorConsole.WriteLine($"Scheduled task started. Name:{st.Xml_Name}", ConsoleColor.Green);
  203 + }
  204 + catch (Exception ex)
  205 + {
  206 + ColorConsole.WriteLine(ex.Message, ConsoleColor.Red);
  207 + }
  208 + }
  209 + return o;
  210 + }
  211 + private static object Uninstall(object parameter, object o)
  212 + {
  213 + var config = (parameter as ScheduledTaskExecutorParameter).Config;
  214 + var args = (parameter as ScheduledTaskExecutorParameter).Args;
  215 +
  216 + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS");
  217 +
  218 + var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Uninstall)}'!");
  219 +
  220 + Menu.Selection sr = menufolders.Select(selectedtaskindexes);
  221 + if (sr.Result == Menu.SelectionResult.Exit) { return o; }
  222 + else if (sr.Result == Menu.SelectionResult.None) { return o; }
  223 + else if (sr.Result == Menu.SelectionResult.Error) { return o; }
  224 + else if (sr.Result == Menu.SelectionResult.Ok) { }
  225 + else { }
  226 + foreach (var p in sr.SelectedParameterList)
  227 + {
  228 + ScheduledTask st = p as ScheduledTask;
  229 + try
  230 + {
  231 + ScheduledTaskManagerCore.EndTask(st.Xml_Name);
  232 + ScheduledTaskManagerCore.DeleteTask(st.Xml_Name);
  233 + ColorConsole.WriteLine($"Scheduled task uninstalled. Name:{st.Xml_Name}", ConsoleColor.Green);
  234 + }
  235 + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); }
  236 + }
  237 + return o;
  238 + }
  239 + private static object Install(object parameter, object o)
  240 + {
  241 + var config = (parameter as ScheduledTaskExecutorParameter).Config;
  242 + var args = (parameter as ScheduledTaskExecutorParameter).Args;
  243 +
  244 + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS");
  245 +
  246 + var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Install)}'!");
  247 +
  248 + Menu.Selection sr = menufolders.Select(selectedtaskindexes);
  249 + if (sr.Result == Menu.SelectionResult.Exit) { return o; }
  250 + else if (sr.Result == Menu.SelectionResult.None) { return o; }
  251 + else if (sr.Result == Menu.SelectionResult.Error) { return o; }
  252 + else if (sr.Result == Menu.SelectionResult.Ok) { }
  253 + else { }
  254 + foreach (var p in sr.SelectedParameterList)
  255 + {
  256 + ScheduledTask st = p as ScheduledTask;
  257 + try
  258 + {
  259 + ScheduledTaskManagerCore.EndTask(st.Xml_Name);
  260 + ScheduledTaskManagerCore.DeleteTask(st.Xml_Name);
  261 + ScheduledTaskManagerCore.CreateTask(st);
  262 + ColorConsole.WriteLine($"Scheduled task installed. Name:{st.Xml_Name}", ConsoleColor.Green);
  263 + }
  264 + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); }
  265 + }
  266 + return o;
  267 + }
  268 + #endregion First level Executors with UI
  269 +
  270 + #region private methods
  271 + #region private DisplayTasks
  272 + private static Menu DisplayTasks(ScheduledTaskManagerCoreXmlProcessor config,string prompt = null)
  273 + {
  274 + List<ScheduledTask> schtskdefList = config.GetDefinitionList();
  275 + var menufct = new Menu("Scheduled tasks",prompt)
  276 + .SetMenuItemDisplayer(DisplayTaskInfo)
  277 + .SetSelectionMode(Menu.SelectionMode.Multi)
  278 + .SetHeaderWidth(4);
  279 + menufct.ClearMenuItemList();
  280 + foreach (var schtskdef in schtskdefList)
  281 + {
  282 + var st = CollectTaskInfo(schtskdef);
  283 + menufct.AddMenuItem(new Menu.Item(null, null, null, st));
  284 + }
  285 + menufct.DisplayItems(1);
  286 + return menufct;
  287 + }
  288 + #endregion private DisplayTasks
  289 + #region private method: DisplayTaskInfo
  290 + private static object DisplayTaskInfo(object obj, int lineix)
  291 + {
  292 + ScheduledTask st = obj as ScheduledTask;
  293 + if (lineix == 0)
  294 + {
  295 + ColorConsole.Write($"{st.Xml_Name}", ConsoleColor.Black, ConsoleColor.White);
  296 + var statuscolor = st.Status == "Uninstalled" ? ConsoleColor.Red : ConsoleColor.Green;
  297 + ColorConsole.Write(st.Status, statuscolor, bracket: "[]", prefix: " ", suffix: ". ");
  298 + if (st.Status != "Uninstalled" && st.Status != "Disabled")
  299 + {
  300 + ColorConsole.Write(st.PriorityText(st.Priority), statuscolor, prefix: "Effective priority ", suffix: ". ");
  301 + ColorConsole.Write($"{st.Xml_Commandname}", ConsoleColor.Yellow, prefix: "Command: ");
  302 + }
  303 + ColorConsole.WriteLine();
  304 + return " ";
  305 + }
  306 + else if (lineix == 1)
  307 + {
  308 + ColorConsole.Write($"{st.Xml_Schedule}",ConsoleColor.Yellow,prefix:"Scheduled ",suffix:" ");
  309 + ColorConsole.Write($"{st.Xml_StartTime}", ConsoleColor.Yellow, prefix: "at ", suffix: ", ");
  310 + ColorConsole.Write(st.PriorityText(st.Xml_Priority), ConsoleColor.Yellow, prefix: "with priority ", suffix: ". ");
  311 + ColorConsole.Write($"{st.Xml_Enable}", ConsoleColor.Yellow, prefix: "After install ", suffix: " ");
  312 + ColorConsole.Write($"{st.Xml_Run}", ConsoleColor.Yellow, prefix: "and run ", suffix: ". ");
  313 + ColorConsole.WriteLine(" ");
  314 + return " ";
  315 + }
  316 + return null;
  317 + }
  318 + #endregion private method: DisplayTaskInfo
  319 + #region private CollectTaskInfo
  320 + private static ScheduledTask CollectTaskInfo(ScheduledTask schtsk)
  321 + {
  322 + string status = Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Query /FO TABLE /TN {schtsk.Xml_Name}");
  323 +
  324 + try
  325 + {
  326 + var statuslines = status.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
  327 + var statussplitted = statuslines[3]
  328 + .Split(new string[] { " ", "+" }, StringSplitOptions.RemoveEmptyEntries);
  329 + if (statussplitted[1]=="N/A")
  330 + {
  331 + schtsk.NextRun = "";
  332 + schtsk.Priority = -1;
  333 + schtsk.Status = statussplitted[2];
  334 + }
  335 + else
  336 + {
  337 + var nextrunTS = statussplitted[1] + " " + statussplitted[2];
  338 + var statusinfo = statussplitted[3];
  339 + if (statusinfo == "AM" || statusinfo == "PM")
  340 + {
  341 + statusinfo = statussplitted[4];
  342 + nextrunTS += statusinfo;
  343 + }
  344 + schtsk.Status = statusinfo;
  345 + schtsk.NextRun += nextrunTS;
  346 + schtsk.Priority = ScheduledTaskManagerCore.GetPriority(schtsk.Xml_Name);
  347 + }
  348 + }
  349 + catch
  350 + {
  351 + schtsk.Status = "Uninstalled";
  352 + schtsk.NextRun = "";
  353 + schtsk.Priority = -1;
  354 + }
  355 + return schtsk;
  356 + }
  357 + #endregion private CollectTaskInfo
  358 + #endregion private methods
  359 + }
  360 + #endregion ScheduledTaskManager class
  361 +
  362 + #region class ScheduledTaskManagerCore
  363 + public static class ScheduledTaskManagerCore
  364 + {
  365 + public static int GetPriority(string taskname)
  366 + {
  367 + try
  368 + {
  369 + return int.Parse(ScheduledTaskManagerCore.GetXml(taskname).Element(XName.Get("Settings")).Element(XName.Get("Priority")).Value);
  370 + }
  371 + catch
  372 + {
  373 + return ScheduledTask.XmlStructure.ScheduledTask.Attributes.Priority.Values.DEFAULT;
  374 + }
  375 + }
  376 + public static void SetPriority(string taskname,int priority)
  377 + {
  378 + var schtskXml = ScheduledTaskManagerCore.GetXml(taskname);
  379 + schtskXml.Element(XName.Get("Settings")).Element(XName.Get("Priority")).Value= priority.ToString();
  380 + ScheduledTaskManagerCore.SetXml(taskname, schtskXml);
  381 + }
  382 + public static XElement GetXml(string taskname) { return XElement.Parse(Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Query /XML /TN {taskname}")); }
  383 + public static void SetXml(string taskname,XElement schtskXml)
  384 + {
  385 + EndTask(taskname);
  386 + DeleteTask(taskname);
  387 + CreateTask(taskname, schtskXml);
  388 + }
  389 + public static void EndTask(string taskname) { Tools.ExecuteAndGetStdIo("schtasks.exe", $"/End /TN {taskname}"); }
  390 + public static void RunTask(string taskname) { Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Run /TN {taskname}"); }
  391 + public static void EnableTask(string taskname)
  392 + {
  393 + Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Change /ENABLE /TN {taskname}");
  394 + }
  395 + public static void DisableTask(string taskname)
  396 + {
  397 + EndTask(taskname);
  398 + Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Change /DISABLE /TN {taskname}");
  399 + }
  400 + public static void DeleteTask(string taskname) { Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Delete /TN {taskname} /F"); }
  401 + public static void CreateTask(string taskname, XElement schtskXml)
  402 + {
  403 + var tmpfilename = $"TMP_{taskname}_{DateTime.Now.ToString("yyyyMMddHHmmss")}.xml";
  404 + if (File.Exists(tmpfilename)) { File.Delete(tmpfilename); }
  405 + schtskXml.Save(tmpfilename);
  406 + Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Create /XML {tmpfilename} /TN {taskname}");
  407 + if (File.Exists(tmpfilename)) { File.Delete(tmpfilename); }
  408 + }
  409 + public static void CreateTask(ScheduledTask st)
  410 + {
  411 + string taskname = st.Xml_Name;
  412 + string tasktorunpars = st.Xml_Commandname;
  413 +
  414 + string schedulepars = "";
  415 + if (st.Xml_Schedule==nameof(ScheduledTask.XmlStructure.ScheduledTask.Attributes.Schedule.Values.MONTHLY)) { schedulepars += "/SC MONTHLY /D 1"; }
  416 + else if (st.Xml_Schedule == nameof(ScheduledTask.XmlStructure.ScheduledTask.Attributes.Schedule.Values.WEEKLY)) { schedulepars += "/SC WEEKLY /D MON"; }
  417 + else if (st.Xml_Schedule == nameof(ScheduledTask.XmlStructure.ScheduledTask.Attributes.Schedule.Values.DAILY)) { schedulepars += "/SC DAILY"; }
  418 + else if (st.Xml_Schedule == nameof(ScheduledTask.XmlStructure.ScheduledTask.Attributes.Schedule.Values.HOURLY)) { schedulepars += "/SC DAILY /RI 60 /DU 24:00 /K"; }
  419 + else if (st.Xml_Schedule == nameof(ScheduledTask.XmlStructure.ScheduledTask.Attributes.Schedule.Values.CONTINOUS)) { schedulepars += "/SC DAILY /RI 5 /DU 24:00 /K"; }
  420 + var sst = st.Xml_StartTime.ToString("HH:mm:ss");
  421 + string starttimepars = $"/ST {sst}";
  422 + string passwordpars = "/NP";
  423 + string forcecreatepars = "/F";
  424 + string prioritypars = "/RL HIGHEST";
  425 +
  426 + var args = $"/Create /TR {tasktorunpars} {schedulepars} {starttimepars} {passwordpars} {forcecreatepars} {prioritypars} /TN {taskname}";
  427 + var result = Tools.ExecuteAndGetStdIo("schtasks.exe", args);
  428 +
  429 + if (st.Xml_Enable) { EnableTask(taskname); } else { DisableTask(taskname); }
  430 + if (st.Xml_Run) { RunTask(taskname); } else { EndTask(taskname); }
  431 + }
  432 + }
  433 + #endregion class ScheduledTaskManagerCore
  434 +
  435 + #region ScheduledTaskManagerCoreXmlProcessor class
  436 + public class ScheduledTaskManagerCoreXmlProcessor : XmlParser
  437 + {
  438 + private List<ScheduledTask> _scheduledtasklist;
  439 + #region constructor
  440 + public ScheduledTaskManagerCoreXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null)
  441 + {
  442 + _scheduledtasklist = new List<ScheduledTask>();
  443 + var schtskxmllist = GetAllXElements(nameof(ScheduledTask.XmlStructure.ScheduledTask));
  444 + if (schtskxmllist != null && schtskxmllist.Any())
  445 + {
  446 + foreach (var schtskxml in schtskxmllist) { var st = new ScheduledTask(schtskxml); if (st.Valid) { _scheduledtasklist.Add(st); } }
  447 + }
  448 + }
  449 + #endregion constructor
  450 + #region GetDefinitionList
  451 + public List<ScheduledTask> GetDefinitionList() { return _scheduledtasklist; }
  452 + #endregion GetDefinitionList
  453 + }
  454 + #endregion ScheduledTaskManagerCoreXmlProcessor class
  455 +
  456 + #region ScheduledTask class
  457 + public class ScheduledTask : XmlLinqBase
  458 + {
  459 + #region fields
  460 + public bool Valid = true;
  461 + public string Xml_Name;
  462 + public int Xml_Priority;
  463 + public string Xml_Schedule;
  464 + public DateTime Xml_StartTime;
  465 + public bool Xml_Enable = XmlStructure.ScheduledTask.Attributes.Enable.Values.DEFAULT;
  466 + public bool Xml_Run=XmlStructure.ScheduledTask.Attributes.Run.Values.DEFAULT;
  467 + public string Xml_Commandname;
  468 +
  469 + public string Status;
  470 + public string NextRun;
  471 + public int Priority;
  472 + #endregion fields
  473 +
  474 + #region basic constructor
  475 + public ScheduledTask() { }
  476 + #endregion basic constructor
  477 + #region xml constructor
  478 + public string PriorityText(int pri)
  479 + {
  480 + return
  481 + (pri == 0 ? "Realtime"
  482 + : pri == 1 ? "High"
  483 + : pri == 2 ? "High"
  484 + : pri == 3 ? "Normal"
  485 + : pri == 4 ? "Normal"
  486 + : pri == 5 ? "Normal"
  487 + : pri == 6 ? "Normal"
  488 + : pri == 7 ? "Low"
  489 + : pri == 8 ? "Low"
  490 + : pri == 9 ? "Idle"
  491 + : pri == 10 ? "Idle"
  492 + : "Idle")+$"({pri})";
  493 + }
  494 + public ScheduledTask(XElement scheduledtaskxml)
  495 + {
  496 + Valid = true;
  497 + string ATTRIBUTEMANDATORY = nameof(XmlStructure.ScheduledTask) + " attribute is mandatory! Name: {0}";
  498 + Xml_Name = scheduledtaskxml.Attribute(XName.Get(nameof(XmlStructure.ScheduledTask.Attributes.Name)))?.Value;
  499 + if (string.IsNullOrWhiteSpace(Xml_Name)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, nameof(XmlStructure.ScheduledTask.Attributes.Name))); }
  500 + Xml_Priority = GetValue(nameof(XmlStructure.ScheduledTask.Attributes.Priority), scheduledtaskxml, XmlStructure.ScheduledTask.Attributes.Priority.Values.DEFAULT);
  501 + Xml_Schedule = GetValue(nameof(XmlStructure.ScheduledTask.Attributes.Schedule), scheduledtaskxml, XmlStructure.ScheduledTask.Attributes.Schedule.Values.DEFAULT);
  502 + Xml_StartTime = DateTime.Parse(GetValue(nameof(XmlStructure.ScheduledTask.Attributes.StartTime), scheduledtaskxml, XmlStructure.ScheduledTask.Attributes.StartTime.Values.DEFAULT));
  503 + Xml_Enable = GetValue(nameof(XmlStructure.ScheduledTask.Attributes.Enable), scheduledtaskxml, XmlStructure.ScheduledTask.Attributes.Enable.Values.DEFAULT);
  504 + Xml_Run = GetValue(nameof(XmlStructure.ScheduledTask.Attributes.Run), scheduledtaskxml, XmlStructure.ScheduledTask.Attributes.Run.Values.DEFAULT);
  505 + Xml_Commandname = GetValue(nameof(XmlStructure.ScheduledTask.Attributes.Commandname), scheduledtaskxml, "");
  506 + //var conditionxmlList = GetAllXElements(foldertocleanxml, nameof(XmlStructure.FolderToClean.Conditions), nameof(XmlStructure.FolderToClean.Conditions.Condition));
  507 + }
  508 + #endregion xml constructor
  509 + #region cloner constructor
  510 + public ScheduledTask(ScheduledTask ftc)
  511 + {
  512 + Valid = ftc.Valid;
  513 + Xml_Name = ftc.Xml_Name;
  514 + Xml_Priority = ftc.Xml_Priority;
  515 + Xml_Schedule = ftc.Xml_Schedule;
  516 + Xml_StartTime = ftc.Xml_StartTime;
  517 + Xml_Enable = ftc.Xml_Enable;
  518 + Xml_Run = ftc.Xml_Run;
  519 + Xml_Commandname = ftc.Xml_Commandname;
  520 + }
  521 + #endregion cloner constructor
  522 + #region XmlStructure
  523 + public static class XmlStructure
  524 + {
  525 + public static class ScheduledTask
  526 + {
  527 + public static class Attributes
  528 + {
  529 + public static class Name { }
  530 + public static class StartTime
  531 + {
  532 + public static class Values
  533 + {
  534 + public const string DEFAULT = "04:00";
  535 + }
  536 + }
  537 + public static class Priority
  538 + {
  539 + public static class Values
  540 + {
  541 + public const int DEFAULT = 7;
  542 + }
  543 + }
  544 + public static class Schedule
  545 + {
  546 + public static class Values
  547 + {
  548 + public static class WEEKLY { }
  549 + public static class MONTHLY { }
  550 + public static class DAILY { }
  551 + public static class HOURLY { }
  552 + public static class CONTINOUS { }
  553 + public const string DEFAULT = nameof(DAILY);
  554 + }
  555 + }
  556 + public static class Enable
  557 + {
  558 + public static class Values
  559 + {
  560 + public const bool DEFAULT = true;
  561 + }
  562 + }
  563 + public static class Run
  564 + {
  565 + public static class Values
  566 + {
  567 + public const bool DEFAULT = false;
  568 + }
  569 + }
  570 + public static class Commandname { }
  571 + }
  572 + }
  573 + }
  574 + #endregion XmlStructure
  575 + }
  576 + #endregion ScheduledTask class
  577 +}
... ...
Vrh.Log4Pro.MaintenanceConsole/Manager - WebApplicationManager.cs
... ... @@ -76,7 +76,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole
76 76 else if (sr.Result == Menu.SelectionResult.Error) { continue; }
77 77 else if (sr.Result == Menu.SelectionResult.Ok) { }
78 78 else { }
79   - menuapplications.Execute(sr.SelectedKeyList);
  79 + menuapplications.ExecuteSelection(sr.SelectedKeyList);
80 80 }
81 81 return null;
82 82 }
... ... @@ -149,14 +149,14 @@ namespace Vrh.Log4Pro.MaintenanceConsole
149 149 WebApplication d = dobj as WebApplication;
150 150 using (ServerManager sm = new ServerManager())
151 151 {
152   - try { WebApplicationManagerCore.GetPool(sm, d.Xml_PoolName)?.Stop(); } catch { Console.WriteLine($"Pool {d.Xml_PoolName} already stopped."); }
153   - try { WebApplicationManagerCore.GetSite(sm, d.Xml_SiteName)?.Stop(); } catch { Console.WriteLine($"Site {d.Xml_SiteName} already stopped."); }
  152 + try { WebApplicationManagerCore.GetPool(sm, d.Xml_PoolName)?.Stop(); } catch { ColorConsole.WriteLine($"Pool {d.Xml_PoolName} already stopped."); }
  153 + try { WebApplicationManagerCore.GetSite(sm, d.Xml_SiteName)?.Stop(); } catch { ColorConsole.WriteLine($"Site {d.Xml_SiteName} already stopped."); }
154 154  
155 155 SiteStart(d, parameters);
156 156 PoolStart(d, parameters);
157 157 PoolRecycle(d, parameters);
158 158  
159   - Console.WriteLine($"Pool {d.Xml_PoolName} and site {d.Xml_SiteName} restarted.");
  159 + ColorConsole.WriteLine($"Pool {d.Xml_PoolName} and site {d.Xml_SiteName} restarted.");
160 160 return parameters;
161 161 }
162 162 }
... ... @@ -173,14 +173,14 @@ namespace Vrh.Log4Pro.MaintenanceConsole
173 173 if (p != null && p.State == ObjectState.Stopped) { p.Start(); success = true; break; }
174 174 else
175 175 {
176   - Console.WriteLine($"Trying to start pool {d.Xml_PoolName} ... Press key 'X' to exit...");
177   - if (Console.KeyAvailable) { if (Console.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
  176 + ColorConsole.WriteLine($"Trying to start pool {d.Xml_PoolName} ... Press key 'X' to exit...");
  177 + if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
178 178  
179 179 Thread.Sleep(1000);
180 180 }
181 181 }
182 182 var successstr = success ? "started" : "NOT started";
183   - Console.WriteLine($"{d.Xml_PoolName} {successstr}.");
  183 + ColorConsole.WriteLine($"{d.Xml_PoolName} {successstr}.");
184 184 return parameters;
185 185 }
186 186 }
... ... @@ -196,13 +196,13 @@ namespace Vrh.Log4Pro.MaintenanceConsole
196 196 if (p != null && p.State == ObjectState.Started) { p.Recycle(); success = true; break; }
197 197 else
198 198 {
199   - Console.WriteLine($"Trying to recycle pool {d.Xml_PoolName} ... Press key 'X' to exit...");
200   - if (Console.KeyAvailable) { if (Console.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
  199 + ColorConsole.WriteLine($"Trying to recycle pool {d.Xml_PoolName} ... Press key 'X' to exit...");
  200 + if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
201 201 Thread.Sleep(1000);
202 202 }
203 203 }
204 204 var successstr = success ? "recycled" : "NOT recycled";
205   - Console.WriteLine($"{d.Xml_PoolName} {successstr}.");
  205 + ColorConsole.WriteLine($"{d.Xml_PoolName} {successstr}.");
206 206 return parameters;
207 207 }
208 208 }
... ... @@ -218,14 +218,14 @@ namespace Vrh.Log4Pro.MaintenanceConsole
218 218 if (p != null && p.State == ObjectState.Started) { p.Stop(); success = true; break; }
219 219 else
220 220 {
221   - Console.WriteLine($"Trying to stop pool {d.Xml_PoolName} ... Press key 'X' to exit...");
222   - if (Console.KeyAvailable) { if (Console.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
  221 + ColorConsole.WriteLine($"Trying to stop pool {d.Xml_PoolName} ... Press key 'X' to exit...");
  222 + if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
223 223  
224 224 Thread.Sleep(1000);
225 225 }
226 226 }
227 227 var successstr = success ? "stopped" : "NOT stopped";
228   - Console.WriteLine($"{d.Xml_PoolName} {successstr}.");
  228 + ColorConsole.WriteLine($"{d.Xml_PoolName} {successstr}.");
229 229 return parameters;
230 230 }
231 231 }
... ... @@ -241,13 +241,13 @@ namespace Vrh.Log4Pro.MaintenanceConsole
241 241 if (s != null && s.State == ObjectState.Stopped) { s.Start(); success = true; break; }
242 242 else
243 243 {
244   - Console.WriteLine($"Trying to start site {d.Xml_SiteName} ... Press key 'X' to exit...");
245   - if (Console.KeyAvailable) { if (Console.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
  244 + ColorConsole.WriteLine($"Trying to start site {d.Xml_SiteName} ... Press key 'X' to exit...");
  245 + if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
246 246 Thread.Sleep(1000);
247 247 }
248 248 }
249 249 var successstr = success ? "started" : "NOT started";
250   - Console.WriteLine($"{d.Xml_SiteName} {successstr}.");
  250 + ColorConsole.WriteLine($"{d.Xml_SiteName} {successstr}.");
251 251 return parameters;
252 252 }
253 253 }
... ... @@ -263,13 +263,13 @@ namespace Vrh.Log4Pro.MaintenanceConsole
263 263 if (s != null && s.State == ObjectState.Started) { s.Stop(); success = true; break; }
264 264 else
265 265 {
266   - Console.WriteLine($"Trying to stop site {d.Xml_SiteName} ... Press key 'X' to exit...");
267   - if (Console.KeyAvailable) { if (Console.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
  266 + ColorConsole.WriteLine($"Trying to stop site {d.Xml_SiteName} ... Press key 'X' to exit...");
  267 + if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } }
268 268 Thread.Sleep(1000);
269 269 }
270 270 }
271 271 var successstr = success ? "stopped" : "NOT stopped";
272   - Console.WriteLine($"{d.Xml_SiteName} {successstr}.");
  272 + ColorConsole.WriteLine($"{d.Xml_SiteName} {successstr}.");
273 273 return parameters;
274 274 }
275 275 }
... ... @@ -277,14 +277,14 @@ namespace Vrh.Log4Pro.MaintenanceConsole
277 277 {
278 278 WebApplication d = dobj as WebApplication;
279 279 WebApplicationManagerCore.RegisterWebApplication(d.Xml_SiteName, d.Xml_PoolName, d.Xml_AppName, d.Xml_AppPhysicalPath, d.Xml_SitePhysicalPath, 8080, d.Xml_RecreatePool, d.Xml_RecreateSite, d.Xml_RecreateApp, d.Xml_PoolPipeLineMode);
280   - Console.WriteLine($"{d.Xml_AppName} is registered in site {d.Xml_SiteName} using pool {d.Xml_PoolName}.");
  280 + ColorConsole.WriteLine($"{d.Xml_AppName} is registered in site {d.Xml_SiteName} using pool {d.Xml_PoolName}.");
281 281 return parameters;
282 282 }
283 283 private static object Unregister(object dobj, object parameters)
284 284 {
285 285 WebApplication d = dobj as WebApplication;
286 286 WebApplicationManagerCore.UnRegisterWebApplication(d.Xml_AppName, d.Xml_PoolName, d.Xml_SiteName, d.Xml_ForceRemovePool, d.Xml_ForceRemoveSite);
287   - Console.WriteLine($"{d.Xml_AppName} is unregistered from site {d.Xml_SiteName} and from pool {d.Xml_PoolName}.");
  287 + ColorConsole.WriteLine($"{d.Xml_AppName} is unregistered from site {d.Xml_SiteName} and from pool {d.Xml_PoolName}.");
288 288 return parameters;
289 289 }
290 290 private static object SetImpersonateIdentity(object dobj, object parameters)
... ... @@ -304,22 +304,22 @@ namespace Vrh.Log4Pro.MaintenanceConsole
304 304 while(true)
305 305 {
306 306  
307   - Console.WriteLine($"Current user info: {olduserinfo}");
308   - Console.WriteLine("Set impersonate-on status (true/false), then [Enter], EX=exit.");
309   - impersonate = Console.ReadLine().ToUpper();
  307 + ColorConsole.WriteLine($"Current user info: {olduserinfo}");
  308 + ColorConsole.WriteLine("Set impersonate-on status (true/false), then [Enter], EX=exit.");
  309 + impersonate = ColorConsole.ReadLine().ToUpper();
310 310 if (impersonate == "EX") { return null; }
311 311 else if (impersonate == "FALSE") { break; }
312 312 else if (impersonate == "TRUE")
313 313 {
314   - Console.WriteLine("Enter username, then [Enter].");
  314 + ColorConsole.WriteLine("Enter username, then [Enter].");
315 315 var un = !string.IsNullOrWhiteSpace(d.Xml_PoolUsername) ? $"empty={d.Xml_PoolUsername }," : "";
316   - Console.WriteLine($"{un}EX=exit");
317   - username = Console.ReadLine().ToUpper();
  316 + ColorConsole.WriteLine($"{un}EX=exit");
  317 + username = ColorConsole.ReadLine().ToUpper();
318 318 if (impersonate == "EX") { return null; }
319   - Console.WriteLine("Enter password, then [Enter]");
  319 + ColorConsole.WriteLine("Enter password, then [Enter]");
320 320 var pw = !string.IsNullOrWhiteSpace(d.Xml_PoolPassword) ? $"empty={d.Xml_PoolPassword}," : "";
321   - Console.WriteLine($"{pw}EX=exit");
322   - password = Console.ReadLine().ToUpper();
  321 + ColorConsole.WriteLine($"{pw}EX=exit");
  322 + password = ColorConsole.ReadLine().ToUpper();
323 323 if (impersonate == "EX") { return null; }
324 324 break;
325 325 //bool valid = System.Web.ApplicationSerices.AuthenticationService.ValidateUser(username, password, mull);
... ... @@ -333,8 +333,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole
333 333 parameters = new Dictionary<string, string> { { "impersonate", impersonate }, { "username", username }, { "password", password }, };
334 334 }
335 335 WebApplicationManagerCore.SetImpersonateIdentity(d.Xml_IdentityConfigFile, impersonate, username, password);
336   - Console.WriteLine($"Impersonate identity changed for webapp {d.Xml_AppName}.");
337   - Console.WriteLine($"From '{olduserinfo}' to '{WebApplicationManagerCore.GetImpersonateIdentityInfo(d.Xml_IdentityConfigFile)}'");
  336 + ColorConsole.WriteLine($"Impersonate identity changed for webapp {d.Xml_AppName}.");
  337 + ColorConsole.WriteLine($"From '{olduserinfo}' to '{WebApplicationManagerCore.GetImpersonateIdentityInfo(d.Xml_IdentityConfigFile)}'");
338 338  
339 339 return parameters;
340 340 }
... ... @@ -351,16 +351,16 @@ namespace Vrh.Log4Pro.MaintenanceConsole
351 351 }
352 352 else
353 353 {
354   - Console.WriteLine($"Current user info: {olduserinfo}");
355   - Console.WriteLine("Enter username, then [Enter].");
356   - Console.WriteLine("Special usernames are: (Empty=API) ");
357   - Console.WriteLine($" (API) {nameof(ProcessModelIdentityType.ApplicationPoolIdentity)}");
358   - Console.WriteLine($" (LSE) {nameof(ProcessModelIdentityType.LocalService)}");
359   - Console.WriteLine($" (LSY) {nameof(ProcessModelIdentityType.LocalSystem)}");
360   - Console.WriteLine($" (NSE) {nameof(ProcessModelIdentityType.NetworkService)}");
  354 + ColorConsole.WriteLine($"Current user info: {olduserinfo}");
  355 + ColorConsole.WriteLine("Enter username, then [Enter].");
  356 + ColorConsole.WriteLine("Special usernames are: (Empty=API) ");
  357 + ColorConsole.WriteLine($" (API) {nameof(ProcessModelIdentityType.ApplicationPoolIdentity)}");
  358 + ColorConsole.WriteLine($" (LSE) {nameof(ProcessModelIdentityType.LocalService)}");
  359 + ColorConsole.WriteLine($" (LSY) {nameof(ProcessModelIdentityType.LocalSystem)}");
  360 + ColorConsole.WriteLine($" (NSE) {nameof(ProcessModelIdentityType.NetworkService)}");
361 361 ColorConsole.WriteLine();
362 362 ColorConsole.Write(" (EX) ", ConsoleColor.Red); ColorConsole.WriteLine("Exit");
363   - username = Console.ReadLine().ToUpper();
  363 + username = ColorConsole.ReadLine().ToUpper();
364 364 if (username == "EX") { return null; }
365 365 if (string.IsNullOrEmpty(username)) { username = nameof(ProcessModelIdentityType.ApplicationPoolIdentity); };
366 366 if (username == "API" || username == nameof(ProcessModelIdentityType.ApplicationPoolIdentity)) { username = nameof(ProcessModelIdentityType.ApplicationPoolIdentity); }
... ... @@ -369,14 +369,14 @@ namespace Vrh.Log4Pro.MaintenanceConsole
369 369 else if (username == "NSE" || username == nameof(ProcessModelIdentityType.NetworkService)) { username = nameof(ProcessModelIdentityType.NetworkService); }
370 370 else
371 371 {
372   - Console.WriteLine("Enter password, then [Enter]");
373   - password = Console.ReadLine().ToUpper();
  372 + ColorConsole.WriteLine("Enter password, then [Enter]");
  373 + password = ColorConsole.ReadLine().ToUpper();
374 374 //bool valid = System.Web.ApplicationSerices.AuthenticationService.ValidateUser(username, password, mull);
375 375 }
376 376 parameters = new Dictionary<string, string> { { "username", username }, { "password", password }, };
377 377 }
378 378 WebApplicationManagerCore.SetPoolUserAccount(d.Xml_AppName, d.Xml_SiteName, username, password);
379   - Console.WriteLine($"Pool user changed from {olduserinfo} to {WebApplicationManagerCore.GetUserInfo(d.Xml_PoolName)} for pool {d.Xml_PoolName}.");
  379 + ColorConsole.WriteLine($"Pool user changed from {olduserinfo} to {WebApplicationManagerCore.GetUserInfo(d.Xml_PoolName)} for pool {d.Xml_PoolName}.");
380 380 return parameters;
381 381 }
382 382 #endregion
... ...
Vrh.Log4Pro.MaintenanceConsole/Manager - WindowsServiceManager.cs
... ... @@ -48,8 +48,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole
48 48 if (sr.Result == Menu.SelectionResult.Exit) { break; }
49 49 else if (sr.Result == Menu.SelectionResult.None) { continue; }
50 50 else if (sr.Result == Menu.SelectionResult.Error) { continue; }
51   - menufunctions.SetParameters(sr,config);
52   - menufunctions.Execute(sr.SelectedKeyList);
  51 + menufunctions.SetExecutorParameters(sr,config);
  52 + menufunctions.ExecuteSelection(sr.SelectedKeyList);
53 53 }
54 54 return null;
55 55 }
... ...
Vrh.Log4Pro.MaintenanceConsole/Program.cs
... ... @@ -9,6 +9,7 @@ using System.Management;
9 9 using System.Diagnostics;
10 10  
11 11 using Vrh.XmlProcessing;
  12 +using VRH.Common;
12 13 using System.Xml.Linq;
13 14  
14 15 namespace Vrh.Log4Pro.MaintenanceConsole
... ... @@ -17,11 +18,21 @@ namespace Vrh.Log4Pro.MaintenanceConsole
17 18 {
18 19 static void Main(string[] args)
19 20 {
20   - try { Console.SetWindowSize(120, 64); }
  21 + ColorConsole.ReadLine("Press a key to start...");
  22 + var appconfigpath = CommandLine.GetCommandLineArgument(args, "-APPCONFIG");
  23 + CommandLine.SetAppConfigFile(appconfigpath);
  24 +
  25 + try { ColorConsole.SetWindowSize(120, 64); }
21 26 catch (Exception ex)
22 27 {
23   - ColorConsole.WriteLine("Change the size of the console fonts smaller!");
24   - Console.ReadKey();
  28 + ColorConsole.WriteLine("Change the size of the console fonts smaller!");
  29 + ColorConsole.ReadKey();
  30 + return;
  31 + }
  32 + if (!Tools.IsElevated)
  33 + {
  34 + ColorConsole.WriteLine("Run as administartor!");
  35 + ColorConsole.ReadKey();
25 36 return;
26 37 }
27 38  
... ... @@ -29,12 +40,24 @@ namespace Vrh.Log4Pro.MaintenanceConsole
29 40 .AddMenuItem(new Menu.Item("WAM", "Web Application Manager", WebApplicationManager.Execute))
30 41 .AddMenuItem(new Menu.Item("WSM", "Windows Service Manager", WindowsServiceManager.Execute))
31 42 .AddMenuItem(new Menu.Item("FCL", "File Cleaner Manager", FileCleanerManager.Execute))
  43 + .AddMenuItem(new Menu.Item("SCH", "Scheduled Task Manager", ScheduledTaskmanagerManager.Execute))
32 44 .AddMenuItem(new Menu.ItemSeparator('-'))
33 45 .AddMenuItem(new Menu.Item("TOL", "Maintenance tools", MaintenanceToolManager.Execute))
34 46 .SetSelectionMode(Menu.SelectionMode.Single);
35 47  
36   - mm.ExecuteMenu();
37   - ColorConsole.WriteLine("Press any key to exit..."); Console.ReadKey();
  48 + var commandmode = !string.IsNullOrEmpty(CommandLine.GetCommandLineArgument(args, "-MODULE"));
  49 + if (commandmode)
  50 + {
  51 + var silentmode = !string.IsNullOrEmpty(CommandLine.GetCommandLineArgument(args, "-SILENT", switchtype: true));
  52 + ColorConsole.SetSilentMode(silentmode);
  53 + Menu.SetCommandModeAllMenus();
  54 + mm.ExecuteCmd(args);
  55 + }
  56 + else
  57 + {
  58 + mm.ExecuteMenu();
  59 + ColorConsole.PressAnykeyToContinue();
  60 + }
38 61 }
39 62 }
40 63 }
... ...
Vrh.Log4Pro.MaintenanceConsole/Vrh.Log4Pro.MaintenanceConsole.csproj
1 1 <?xml version="1.0" encoding="utf-8"?>
2 2 <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3   - <Import Project="..\packages\EntityFramework.6.4.0\build\EntityFramework.props" Condition="Exists('..\packages\EntityFramework.6.4.0\build\EntityFramework.props')" />
  3 + <Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.props" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.props')" />
4 4 <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
5 5 <PropertyGroup>
6 6 <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
... ... @@ -37,10 +37,10 @@
37 37 </PropertyGroup>
38 38 <ItemGroup>
39 39 <Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
40   - <HintPath>..\packages\EntityFramework.6.4.0\lib\net45\EntityFramework.dll</HintPath>
  40 + <HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll</HintPath>
41 41 </Reference>
42 42 <Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
43   - <HintPath>..\packages\EntityFramework.6.4.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
  43 + <HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll</HintPath>
44 44 </Reference>
45 45 <Reference Include="Microsoft.Web.Administration, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
46 46 <HintPath>..\packages\Microsoft.Web.Administration.11.1.0\lib\netstandard1.5\Microsoft.Web.Administration.dll</HintPath>
... ... @@ -145,8 +145,8 @@
145 145 <Reference Include="Microsoft.CSharp" />
146 146 <Reference Include="System.Data" />
147 147 <Reference Include="System.Xml" />
148   - <Reference Include="VRH.Common, Version=2.19.0.0, Culture=neutral, processorArchitecture=MSIL">
149   - <HintPath>..\packages\VRH.Common.2.19.0\lib\net45\VRH.Common.dll</HintPath>
  148 + <Reference Include="VRH.Common, Version=2.19.1.0, Culture=neutral, processorArchitecture=MSIL">
  149 + <HintPath>..\packages\VRH.Common.2.19.1\lib\net45\VRH.Common.dll</HintPath>
150 150 </Reference>
151 151 <Reference Include="Vrh.XmlProcessing, Version=1.23.0.0, Culture=neutral, processorArchitecture=MSIL">
152 152 <HintPath>..\packages\Vrh.XmlProcessing.1.23.0\lib\net45\Vrh.XmlProcessing.dll</HintPath>
... ... @@ -156,6 +156,8 @@
156 156 <Compile Include="ConsoleFunction - CommandLineParser.cs" />
157 157 <Compile Include="ConsoleFunction - ColorConsole.cs" />
158 158 <Compile Include="ConsoleFunction - Menu.cs" />
  159 + <Compile Include="ConsoleFunction - Tools.cs" />
  160 + <Compile Include="Manager - ScheduledTaskManager.cs" />
159 161 <Compile Include="Manager - WindowsServiceManager.cs" />
160 162 <Compile Include="Manager - FileCleanerManager.cs" />
161 163 <Compile Include="Manager - MaintenanceToolManager.cs" />
... ... @@ -179,13 +181,14 @@
179 181 <CopyToOutputDirectory>Always</CopyToOutputDirectory>
180 182 </Content>
181 183 </ItemGroup>
  184 + <ItemGroup />
182 185 <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
183 186 <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
184 187 <PropertyGroup>
185 188 <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
186 189 </PropertyGroup>
187   - <Error Condition="!Exists('..\packages\EntityFramework.6.4.0\build\EntityFramework.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.0\build\EntityFramework.props'))" />
188   - <Error Condition="!Exists('..\packages\EntityFramework.6.4.0\build\EntityFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.0\build\EntityFramework.targets'))" />
  190 + <Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.props'))" />
  191 + <Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.targets'))" />
189 192 </Target>
190   - <Import Project="..\packages\EntityFramework.6.4.0\build\EntityFramework.targets" Condition="Exists('..\packages\EntityFramework.6.4.0\build\EntityFramework.targets')" />
  193 + <Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.targets" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" />
191 194 </Project>
192 195 \ No newline at end of file
... ...
Vrh.Log4Pro.MaintenanceConsole/packages.config
1 1 <?xml version="1.0" encoding="utf-8"?>
2 2 <packages>
3   - <package id="EntityFramework" version="6.4.0" targetFramework="net462" />
  3 + <package id="EntityFramework" version="6.4.4" targetFramework="net462" />
4 4 <package id="Microsoft.NETCore.Platforms" version="1.0.1" targetFramework="net462" />
5 5 <package id="Microsoft.Web.Administration" version="11.1.0" targetFramework="net462" />
6 6 <package id="Microsoft.Win32.Primitives" version="4.0.1" targetFramework="net462" />
... ... @@ -55,6 +55,6 @@
55 55 <package id="System.Threading.Timer" version="4.0.1" targetFramework="net462" />
56 56 <package id="System.Xml.ReaderWriter" version="4.0.11" targetFramework="net462" />
57 57 <package id="System.Xml.XDocument" version="4.0.11" targetFramework="net462" />
58   - <package id="VRH.Common" version="2.19.0" targetFramework="net462" />
  58 + <package id="VRH.Common" version="2.19.1" targetFramework="net462" />
59 59 <package id="Vrh.XmlProcessing" version="1.23.0" targetFramework="net462" />
60 60 </packages>
61 61 \ No newline at end of file
... ...