Commit 8e8a7bf0599696f5cfbbbefcc547a9a03a41edef
1 parent
37bf94ab
jelentős fejleszetések
Showing
23 changed files
with
4869 additions
and
1027 deletions
Show diff stats
Vrh.Log4Pro.MaintenanceConsole/App.config
@@ -5,7 +5,7 @@ | @@ -5,7 +5,7 @@ | ||
5 | <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> | 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> | 6 | </configSections> |
7 | <startup> | 7 | <startup> |
8 | - <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" /> | 8 | + <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> |
9 | </startup> | 9 | </startup> |
10 | <appSettings> | 10 | <appSettings> |
11 | <add key="VRH.XmlParser:root" value="XmlParser.xml" /> | 11 | <add key="VRH.XmlParser:root" value="XmlParser.xml" /> |
@@ -16,11 +16,19 @@ | @@ -16,11 +16,19 @@ | ||
16 | <assemblyIdentity name="System.Reflection.TypeExtensions" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> | 16 | <assemblyIdentity name="System.Reflection.TypeExtensions" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> |
17 | <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0" /> | 17 | <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0" /> |
18 | </dependentAssembly> | 18 | </dependentAssembly> |
19 | + <dependentAssembly> | ||
20 | + <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> | ||
21 | + <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" /> | ||
22 | + </dependentAssembly> | ||
19 | </assemblyBinding> | 23 | </assemblyBinding> |
20 | </runtime> | 24 | </runtime> |
21 | - <entityFramework> | 25 | + <system.web> |
26 | + <membership configSource="system.web.membership.config"/> | ||
27 | + <roleManager configSource="system.web.roleManager.config"/> | ||
28 | + </system.web> | ||
29 | + <entityFramework> | ||
22 | <providers> | 30 | <providers> |
23 | <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> | 31 | <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> |
24 | </providers> | 32 | </providers> |
25 | </entityFramework> | 33 | </entityFramework> |
26 | -</configuration> | ||
27 | \ No newline at end of file | 34 | \ No newline at end of file |
35 | +</configuration> |
Vrh.Log4Pro.MaintenanceConsole/Config.xml
@@ -152,10 +152,10 @@ | @@ -152,10 +152,10 @@ | ||
152 | </WindowsServices> | 152 | </WindowsServices> |
153 | 153 | ||
154 | <WebApplications> | 154 | <WebApplications> |
155 | - <WebApplication Id="WEBAPP_ANDON" Name="WebAndon" Description="@WEBANDONDESC@" AppPool="WebAndon" Website="Default Web Site" InstallDir="@DIR_WEBAPPWEBANDON@" SiteRootDir="@DIR_WEBAPPWEBANDON@" IdentityConfigFile="@WEBANDONIDENTITYCONFIG@" AppPoolUsername="" AppPoolPassword="" AppPoolPipeLineMode="" RecreateSite="false" RecreatePool="true" RecreateApp="true"/> | ||
156 | - <WebApplication Id="WEBAPP_ALM" Name="WebALM" Description="@WEBALMDESC@" AppPool="WebALM" Website="Default Web Site" InstallDir="@DIR_WEBAPPWEBALM@" SiteRootDir="@DIR_WEBAPPWEBALM@" IdentityConfigFile="@WEBALMIDENTITYCONFIG@" AppPoolUsername="" AppPoolPassword="" AppPoolPipeLineMode="" RecreateSite="false" RecreatePool="true" RecreateApp="true"/> | ||
157 | - <WebApplication Id="WEBAPP_CP" Name="WebPack" Description="@WEBPACKDESC@" AppPool="WebPack" Website="Default Web Site" InstallDir="@DIR_WEBAPPWEBPACK@" SiteRootDir="@DIR_WEBAPPWEBPACK@" IdentityConfigFile="@WEBPACKIDENTITYCONFIG@" AppPoolUsername="" AppPoolPassword="" AppPoolPipeLineMode="" RecreateSite="false" RecreatePool="true" RecreateApp="true"/> | ||
158 | - <WebApplication Id="WEBAPP_LOG4PROIS" Name="Log4ProIS" Description="@WEBLOG4PROISDESC@" AppPool="Log4ProIS" Website="Default Web Site" InstallDir="@DIR_WEBAPPLOG4PROIS@" SiteRootDir="@DIR_WEBAPPLOG4PROIS@" IdentityConfigFile="@LOG4PROISIDENTITYCONFIG@" AppPoolUsername="" AppPoolPassword="" AppPoolPipeLineMode="" RecreateSite="false" RecreatePool="true" RecreateApp="true"/> | 155 | + <WebApplication Id="WEBAPP_ANDON" Name="WebAndon" Description="@WEBANDONDESC@" AppPool="WebAndon" Website="Default Web Site" InstallDir="@DIR_WEBAPPWEBANDON@" SiteRootDir="@DIR_WEBAPPWEBANDON@" ImpersonateIdentityConfigFile="@WEBANDONIDENTITYCONFIG@" AppPoolUsername="" AppPoolPassword="" AppPoolPipeLineMode="" RecreateSite="false" RecreatePool="true" RecreateApp="true"/> |
156 | + <WebApplication Id="WEBAPP_ALM" Name="WebALM" Description="@WEBALMDESC@" AppPool="WebALM" Website="Default Web Site" InstallDir="@DIR_WEBAPPWEBALM@" SiteRootDir="@DIR_WEBAPPWEBALM@" ImpersonateIdentityConfigFile="@WEBALMIDENTITYCONFIG@" AppPoolUsername="" AppPoolPassword="" AppPoolPipeLineMode="" RecreateSite="false" RecreatePool="true" RecreateApp="true"/> | ||
157 | + <WebApplication Id="WEBAPP_CP" Name="WebPack" Description="@WEBPACKDESC@" AppPool="WebPack" Website="Default Web Site" InstallDir="@DIR_WEBAPPWEBPACK@" SiteRootDir="@DIR_WEBAPPWEBPACK@" ImpersonateIdentityConfigFile="@WEBPACKIDENTITYCONFIG@" AppPoolUsername="" AppPoolPassword="" AppPoolPipeLineMode="" RecreateSite="false" RecreatePool="true" RecreateApp="true"/> | ||
158 | + <WebApplication Id="WEBAPP_LOG4PROIS" Name="Log4ProIS" Description="@WEBLOG4PROISDESC@" AppPool="Log4ProIS" Website="Default Web Site" InstallDir="@DIR_WEBAPPLOG4PROIS@" SiteRootDir="@DIR_WEBAPPLOG4PROIS@" ImpersonateIdentityConfigFile="@LOG4PROISIDENTITYCONFIG@" AppPoolUsername="" AppPoolPassword="" AppPoolPipeLineMode="" RecreateSite="false" RecreatePool="true" RecreateApp="true"/> | ||
159 | </WebApplications> | 159 | </WebApplications> |
160 | 160 | ||
161 | <FileCleaner CleanupDays="7"> | 161 | <FileCleaner CleanupDays="7"> |
@@ -197,4 +197,18 @@ | @@ -197,4 +197,18 @@ | ||
197 | <ScheduledTask Name="CP_PurgeFiles_DAILY" Priority="7" Schedule="DAILY" StartTime="05:00" 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> | 198 | </ScheduledTasks> |
199 | 199 | ||
200 | + <BackupPackages> | ||
201 | + <BackupPackage Name="FULL" Description="Full backup package" IncludeFilenameMaskList="*.zip" PackageFilePath="{APPLICATION}_{SITE}_BackupPackage_{TIMESTAMP}_{PACKAGENAME}" CreateExe="true"> | ||
202 | + <BackupFolder Path="" Description="1" BackupToFile="1.zip" IncludeNameMask="*.bin" IncludePathRegexp=".*"/> | ||
203 | + <BackupFolder Path="" Description="2" BackupToFile="2.zip" IncludeNameMask="*.xml" IncludePathRegexp=".*"/> | ||
204 | + </BackupPackage> | ||
205 | + </BackupPackages> | ||
206 | + | ||
207 | + <Log4ProUserManager SQLConnectionString="MAINDBLOG4PRO" PredefinedUsernameList="Admin,Administrator,Operator,Manager,Supervisor,lschwirg,imolnar"> | ||
208 | + <UserGroups> | ||
209 | + <UserGroup Id="TEST" Displayname="All test users">^(T|t)est.*$</UserGroup> | ||
210 | + <UserGroup Id="OL" Displayname="Operator and Lineleader">^(Operator|Lineleader)$</UserGroup> | ||
211 | + <UserGroup Id="ALL" Displayname="All users except predefined" /> | ||
212 | + </UserGroups> | ||
213 | + </Log4ProUserManager> | ||
200 | </Configuration> | 214 | </Configuration> |
201 | \ No newline at end of file | 215 | \ No newline at end of file |
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - ColorConsole.cs
@@ -11,7 +11,7 @@ using System.Diagnostics; | @@ -11,7 +11,7 @@ using System.Diagnostics; | ||
11 | using Vrh.XmlProcessing; | 11 | using Vrh.XmlProcessing; |
12 | using System.Xml.Linq; | 12 | using System.Xml.Linq; |
13 | 13 | ||
14 | -namespace Vrh.Log4Pro.MaintenanceConsole | 14 | +namespace Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS |
15 | { | 15 | { |
16 | #region ColorConsole | 16 | #region ColorConsole |
17 | public static class ColorConsole | 17 | public static class ColorConsole |
@@ -101,7 +101,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -101,7 +101,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
101 | /// <param name="bracket"></param> | 101 | /// <param name="bracket"></param> |
102 | /// <param name="prefix"></param> | 102 | /// <param name="prefix"></param> |
103 | /// <returns></returns> | 103 | /// <returns></returns> |
104 | - public static string ReadLine(string text = null, ConsoleColor? f = null, ConsoleColor? b = null, string bracket = null, string prefix = "") | 104 | + public static string ReadLine(string text = null, ConsoleColor? f = null, ConsoleColor? b = null, string bracket = null, string prefix = "",string suffix = "") |
105 | { | 105 | { |
106 | if (silentMode) | 106 | if (silentMode) |
107 | { | 107 | { |
@@ -115,7 +115,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -115,7 +115,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
115 | } | 115 | } |
116 | else | 116 | else |
117 | { | 117 | { |
118 | - Write(text, f, b, bracket, prefix); | 118 | + Write(text, f, b, bracket, prefix,suffix); |
119 | return Console.ReadLine(); | 119 | return Console.ReadLine(); |
120 | } | 120 | } |
121 | } | 121 | } |
@@ -133,6 +133,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -133,6 +133,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
133 | 133 | ||
134 | public static int CursorLeft { get { return Console.CursorLeft; } } | 134 | public static int CursorLeft { get { return Console.CursorLeft; } } |
135 | public static int CursorTop { get { return Console.CursorTop; } } | 135 | public static int CursorTop { get { return Console.CursorTop; } } |
136 | + public static int WindowWidth { get { return Console.WindowWidth; } } | ||
137 | + public static int BufferWidth { get { return Console.BufferWidth; } } | ||
138 | + public static int WindowHeight { get { return Console.WindowHeight; } } | ||
139 | + public static int BufferHeight { get { return Console.BufferHeight; } } | ||
140 | + public static int WindowLeft { get { return Console.WindowLeft; } } | ||
141 | + public static int WindowTop { get { return Console.WindowTop; } } | ||
136 | 142 | ||
137 | public static void Clear() { Console.Clear(); } | 143 | public static void Clear() { Console.Clear(); } |
138 | 144 |
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - CommandLineParser.cs
@@ -8,10 +8,12 @@ using Microsoft.Web.Administration; | @@ -8,10 +8,12 @@ using Microsoft.Web.Administration; | ||
8 | using System.Management; | 8 | using System.Management; |
9 | using System.Diagnostics; | 9 | using System.Diagnostics; |
10 | 10 | ||
11 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
12 | + | ||
11 | using Vrh.XmlProcessing; | 13 | using Vrh.XmlProcessing; |
12 | using System.Xml.Linq; | 14 | using System.Xml.Linq; |
13 | 15 | ||
14 | -namespace Vrh.Log4Pro.MaintenanceConsole | 16 | +namespace Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS |
15 | { | 17 | { |
16 | #region CommandLineParser | 18 | #region CommandLineParser |
17 | public static class CommandLineParser | 19 | public static class CommandLineParser |
@@ -74,7 +76,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -74,7 +76,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
74 | } | 76 | } |
75 | else if (chr == ' ' && !quoted) | 77 | else if (chr == ' ' && !quoted) |
76 | { | 78 | { |
77 | - if (started) yield return result.ToString(); | 79 | + if (started) { yield return result.ToString(); } |
78 | result.Clear(); | 80 | result.Clear(); |
79 | started = false; | 81 | started = false; |
80 | } | 82 | } |
@@ -85,7 +87,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -85,7 +87,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
85 | } | 87 | } |
86 | } | 88 | } |
87 | 89 | ||
88 | - if (started) yield return result.ToString(); | 90 | + if (started) { yield return result.ToString(); } |
89 | } | 91 | } |
90 | public static void UnitTest() | 92 | public static void UnitTest() |
91 | { | 93 | { |
@@ -156,6 +158,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -156,6 +158,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
156 | return; | 158 | return; |
157 | } | 159 | } |
158 | for (int i = 0; i < r.Length; i++) | 160 | for (int i = 0; i < r.Length; i++) |
161 | + { | ||
159 | if (r[i] != sr[i]) | 162 | if (r[i] != sr[i]) |
160 | { | 163 | { |
161 | ColorConsole.WriteLine($"ERROR:{id}"); | 164 | ColorConsole.WriteLine($"ERROR:{id}"); |
@@ -164,8 +167,9 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -164,8 +167,9 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
164 | ColorConsole.WriteLine($" expected: {sexp}"); | 167 | ColorConsole.WriteLine($" expected: {sexp}"); |
165 | return; | 168 | return; |
166 | } | 169 | } |
170 | + } | ||
167 | } | 171 | } |
168 | - catch (Exception ex) | 172 | + catch |
169 | { | 173 | { |
170 | ColorConsole.WriteLine($"EXCEP:{id}"); | 174 | ColorConsole.WriteLine($"EXCEP:{id}"); |
171 | ColorConsole.WriteLine($" cmdline : {cmd}"); | 175 | ColorConsole.WriteLine($" cmdline : {cmd}"); |
@@ -176,4 +180,119 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -176,4 +180,119 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
176 | } | 180 | } |
177 | } | 181 | } |
178 | #endregion CommandLineParser | 182 | #endregion CommandLineParser |
183 | + #region Commandline parameter definition class | ||
184 | + public static class CLP | ||
185 | + { | ||
186 | + public const string CMD_MODULE = "-MODULE"; | ||
187 | + public const string CMD_FUNCTION = "-FUNCTION"; | ||
188 | + public const string CMD_SILENT = "-SILENT"; | ||
189 | + public const string CMD_APPCONFIG = "-APPCONFIG"; | ||
190 | + public static class Module | ||
191 | + { | ||
192 | + public static class Log4ProUserManager | ||
193 | + { | ||
194 | + public const string KEY = "LUM"; | ||
195 | + public static class Functions | ||
196 | + { | ||
197 | + public static class CreateSuperuser { public const string KEY = "CSU"; } | ||
198 | + public static class CreateAdminusers { public const string KEY = "CAU"; } | ||
199 | + public static class DeleteUsers { public const string KEY = "DEU"; } | ||
200 | + } | ||
201 | + } | ||
202 | + public static class WebApplicationManager | ||
203 | + { | ||
204 | + public const string KEY = "WAM"; | ||
205 | + public static class Function | ||
206 | + { | ||
207 | + public const string CMD_WEBAPPS = "-WEBAPPS"; | ||
208 | + public static class Register { public const string KEY = "WAR"; } | ||
209 | + public static class Unregister { public const string KEY = "WAU"; } | ||
210 | + public static class SetImpersonateIdentity { public const string KEY = "WAI"; } | ||
211 | + public static class PoolStart { public const string KEY = "APS"; } | ||
212 | + public static class PoolStop { public const string KEY = "APF"; } | ||
213 | + public static class PoolRecycle { public const string KEY = "APR"; } | ||
214 | + public static class SiteStart { public const string KEY = "WSS"; } | ||
215 | + public static class SiteStop { public const string KEY = "WSF"; } | ||
216 | + public static class PoolSetUserAccount { public const string KEY = "APU"; } | ||
217 | + public static class Restart { public const string KEY = "R"; } | ||
218 | + } | ||
219 | + } | ||
220 | + public static class WindowsServiceManager | ||
221 | + { | ||
222 | + public const string KEY = "WSM"; | ||
223 | + public static class Function | ||
224 | + { | ||
225 | + public const string CMD_SERVICES = "-SERVICES"; | ||
226 | + public static class Register { public const string KEY = "WSR"; } | ||
227 | + public static class Unregister { public const string KEY = "WSU"; } | ||
228 | + public static class SetUserAccount { public const string KEY = "WSA"; } | ||
229 | + public static class Start { public const string KEY = "WSS"; } | ||
230 | + public static class Stop { public const string KEY = "WSX"; } | ||
231 | + public static class Kill { public const string KEY = "WSK"; } | ||
232 | + public static class Purge { public const string KEY = "WSP"; } | ||
233 | + } | ||
234 | + } | ||
235 | + public static class FileCleanerManager | ||
236 | + { | ||
237 | + public const string KEY = "FCL"; | ||
238 | + public static class Functions | ||
239 | + { | ||
240 | + public const string CMD_FOLDERS = "-FOLDERS"; | ||
241 | + public static class FolderClean { public const string KEY = "CLN"; } | ||
242 | + } | ||
243 | + } | ||
244 | + public static class ScheduledTaskManager | ||
245 | + { | ||
246 | + public const string KEY = "SCH"; | ||
247 | + public static class Function | ||
248 | + { | ||
249 | + public const string CMD_TASKS = "-TASKS"; | ||
250 | + public static class Install { public const string KEY = "INS"; } | ||
251 | + public static class Uninstall { public const string KEY = "UIN"; } | ||
252 | + public static class Run { public const string KEY = "RUN"; } | ||
253 | + public static class End { public const string KEY = "END"; } | ||
254 | + public static class Enable { public const string KEY = "ENA"; } | ||
255 | + public static class Disable { public const string KEY = "DIS"; } | ||
256 | + public static class ChangePriority { public const string KEY = "CHP"; } | ||
257 | + } | ||
258 | + } | ||
259 | + public static class BackupPackageManager | ||
260 | + { | ||
261 | + public const string KEY = "BAK"; | ||
262 | + public static class Functions | ||
263 | + { | ||
264 | + public const string CMD_PACKAGES = "-PACKAGES"; | ||
265 | + public static class CreateBackupPackage | ||
266 | + { | ||
267 | + public const string KEY = "CRE"; | ||
268 | + } | ||
269 | + } | ||
270 | + } | ||
271 | + public static class SQLDataBaseManager | ||
272 | + { | ||
273 | + public const string KEY = "SQL"; | ||
274 | + public static class Function | ||
275 | + { | ||
276 | + public const string CMD_DATABASES = "-DATABASES"; | ||
277 | + public static class BackupDataBase { public const string KEY = "BAK"; } | ||
278 | + public static class CreateCodeScripts { public const string KEY = "CCS"; } | ||
279 | + public static class CreateDataScripts { public const string KEY = "CDS"; } | ||
280 | + public static class RestoreDataBase { public const string KEY = "RES"; public const string CMD_RESTOREFIRST = "-RESTOREFIRST"; | ||
281 | + } | ||
282 | + public static class RelocatePhysicalFiles { public const string KEY = "COP"; } | ||
283 | + } | ||
284 | + } | ||
285 | + public static class MaintenanceToolManager | ||
286 | + { | ||
287 | + public const string KEY = "TOL"; | ||
288 | + public static class Functions | ||
289 | + { | ||
290 | + public static class RegexTester { public const string KEY = "RGX"; } | ||
291 | + public static class Tool1 { public const string KEY = "TL1"; } | ||
292 | + public static class Tool2 { public const string KEY = "TL2"; } | ||
293 | + } | ||
294 | + } | ||
295 | + } | ||
296 | + } | ||
297 | + #endregion Commandline parameter definition class | ||
179 | } | 298 | } |
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - Menu.cs
@@ -10,31 +10,44 @@ using Microsoft.Web.Administration; | @@ -10,31 +10,44 @@ using Microsoft.Web.Administration; | ||
10 | using System.Management; | 10 | using System.Management; |
11 | using System.Diagnostics; | 11 | using System.Diagnostics; |
12 | 12 | ||
13 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
14 | + | ||
13 | using Vrh.XmlProcessing; | 15 | using Vrh.XmlProcessing; |
14 | using VRH.Common; | 16 | using VRH.Common; |
15 | using System.Xml.Linq; | 17 | using System.Xml.Linq; |
16 | 18 | ||
17 | -namespace Vrh.Log4Pro.MaintenanceConsole | 19 | +namespace Vrh.Log4Pro.MaintenanceConsole.MenuNS |
18 | { | 20 | { |
19 | public class Menu | 21 | public class Menu |
20 | { | 22 | { |
21 | - public delegate Object MenuItemExecutorFunc(Object p, Object o); | 23 | + /// <summary> |
24 | + /// Egy menupont executor függvény prototípusa | ||
25 | + /// </summary> | ||
26 | + /// <param name="p">az executor paramétereit tartalmazó osztály</param> | ||
27 | + /// <param name="o"> | ||
28 | + /// több menupont kiválasztásakor ezt a paramétert az első menuponthoz tartozó executor tölti fel, | ||
29 | + /// majd ezt az értéket megkapja a második, aki módosíthatja, majd megkapja a harmadik, és így tovább... | ||
30 | + /// </param> | ||
31 | + /// <returns></returns> | ||
32 | + public delegate Object MenuItemExecutorFunc(Menu.ExecutorParameter p, Object o); | ||
22 | public delegate Object MenuItemDisplayerFunc(Object p, int i); | 33 | public delegate Object MenuItemDisplayerFunc(Object p, int i); |
34 | + public delegate void MenuHeaderDisplayerFunc(); | ||
35 | + | ||
23 | public Menu(string title, string selectionprompt = null) { Title = title; if (!string.IsNullOrWhiteSpace(selectionprompt)) { SelectionPrompt = selectionprompt; } } | 36 | public Menu(string title, string selectionprompt = null) { Title = title; if (!string.IsNullOrWhiteSpace(selectionprompt)) { SelectionPrompt = selectionprompt; } } |
24 | #region private fields | 37 | #region private fields |
25 | private string title; | 38 | private string title; |
26 | private string Title { get { return ColorConsole.WideString(title); } set { title = value; } } | 39 | private string Title { get { return ColorConsole.WideString(title); } set { title = value; } } |
27 | private MenuItemDisplayerFunc MenuItemDisplayer; | 40 | private MenuItemDisplayerFunc MenuItemDisplayer; |
41 | + private MenuHeaderDisplayerFunc MenuHeaderDisplayer; | ||
28 | private SelectionMode selectionMode = Menu.SelectionMode.Multi; | 42 | private SelectionMode selectionMode = Menu.SelectionMode.Multi; |
29 | - private static bool commandModeAllMenus = false; | ||
30 | - private bool commandMode = false; | ||
31 | - private int HeaderWidth = 9; | 43 | + private static bool commandMode = false; |
44 | + private int MenuItemIndentWidth = 0; | ||
32 | private string SelectionPrompt = "Make Your selection!"; | 45 | private string SelectionPrompt = "Make Your selection!"; |
33 | #endregion private fields | 46 | #endregion private fields |
34 | 47 | ||
35 | #region public properties | 48 | #region public properties |
36 | public List<Item> MenuItemList { get; private set; } = new List<Item>(); | 49 | public List<Item> MenuItemList { get; private set; } = new List<Item>(); |
37 | - List<string> MenuKeyList { get { return MenuItemList.Where(x => !x.Separator).Select(x => x.Key).ToList(); } } | 50 | + List<string> MenuItemKeyList { get { return MenuItemList.Where(x => !x.Separator).Select(x => x.Key).ToList(); } } |
38 | #endregion public properties | 51 | #endregion public properties |
39 | 52 | ||
40 | #region public tools | 53 | #region public tools |
@@ -45,7 +58,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -45,7 +58,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
45 | /// <param name="partxt"></param> | 58 | /// <param name="partxt"></param> |
46 | public static void IncorrectSelection(string partxt = "") | 59 | public static void IncorrectSelection(string partxt = "") |
47 | { | 60 | { |
48 | - if (GetCommandModeAllMenus()) { return; } | 61 | + if (IsCommandMode()) { return; } |
49 | 62 | ||
50 | ColorConsole.WriteLine(); | 63 | ColorConsole.WriteLine(); |
51 | ColorConsole.WriteLine($"Incorrect selection! {partxt} Make a new selection!", ConsoleColor.Red); | 64 | ColorConsole.WriteLine($"Incorrect selection! {partxt} Make a new selection!", ConsoleColor.Red); |
@@ -59,51 +72,90 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -59,51 +72,90 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
59 | /// <returns></returns> | 72 | /// <returns></returns> |
60 | public static ConsoleKeyInfo PressAnykeyToContinue(string text = null) | 73 | public static ConsoleKeyInfo PressAnykeyToContinue(string text = null) |
61 | { | 74 | { |
62 | - if (GetCommandModeAllMenus()) { return ColorConsole.GetConsoleKey(ConsoleKey.Enter); } | 75 | + if (IsCommandMode()) { return ColorConsole.GetConsoleKey(ConsoleKey.Enter); } |
63 | 76 | ||
64 | ColorConsole.WriteLine(text ?? "Press any key to continue...", ConsoleColor.Yellow); return ColorConsole.ReadKey(); | 77 | ColorConsole.WriteLine(text ?? "Press any key to continue...", ConsoleColor.Yellow); return ColorConsole.ReadKey(); |
65 | } | 78 | } |
66 | 79 | ||
80 | + /// <summary> | ||
81 | + /// Beállítja a parancs módot a menükezelő számára | ||
82 | + /// </summary> | ||
83 | + /// <param name="commandmode"></param> | ||
84 | + public static void SetCommandMode(bool commandmode=true) { commandMode = commandmode; } | ||
67 | 85 | ||
68 | - public static void SetCommandModeAllMenus() { commandModeAllMenus = true; } | 86 | + /// <summary> |
87 | + /// true= a menükezelő parancs módban van | ||
88 | + /// </summary> | ||
89 | + /// <returns></returns> | ||
90 | + public static bool IsCommandMode() { return commandMode; } | ||
69 | 91 | ||
92 | + /// <summary> | ||
93 | + /// Beállítja a menükezelő számára a displayer metódust, amelynek feladata | ||
94 | + /// az egyes menüpontok információjának soronkénti előállítása | ||
95 | + /// </summary> | ||
96 | + /// <param name="displayer"></param> | ||
97 | + /// <returns></returns> | ||
70 | public Menu SetMenuItemDisplayer(MenuItemDisplayerFunc displayer) | 98 | public Menu SetMenuItemDisplayer(MenuItemDisplayerFunc displayer) |
71 | { | 99 | { |
72 | MenuItemDisplayer = displayer; | 100 | MenuItemDisplayer = displayer; |
73 | return this; | 101 | return this; |
74 | } | 102 | } |
103 | + | ||
104 | + /// <summary> | ||
105 | + /// Beállítja a menükezelő számára a header displayer metódust, amelynek feladata | ||
106 | + /// a menu címe alatti terület információjának előállítása | ||
107 | + /// </summary> | ||
108 | + /// <param name="displayer"></param> | ||
109 | + /// <returns></returns> | ||
110 | + public Menu SetMenuHeaderDisplayer(MenuHeaderDisplayerFunc displayer) | ||
111 | + { | ||
112 | + MenuHeaderDisplayer = displayer; | ||
113 | + return this; | ||
114 | + } | ||
115 | + | ||
116 | + /// <summary> | ||
117 | + /// Beállítja, hogy egy, vagy több menüpont választható | ||
118 | + /// </summary> | ||
119 | + /// <param name="sm"></param> | ||
120 | + /// <returns></returns> | ||
75 | public Menu SetSelectionMode(SelectionMode sm) { selectionMode = sm; return this; } | 121 | public Menu SetSelectionMode(SelectionMode sm) { selectionMode = sm; return this; } |
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; } | 122 | + |
123 | + /// <summary> | ||
124 | + /// Létrehoz egy menüpontot | ||
125 | + /// </summary> | ||
126 | + /// <param name="mi"></param> | ||
127 | + /// <returns></returns> | ||
80 | public Menu AddMenuItem(Item mi) | 128 | public Menu AddMenuItem(Item mi) |
81 | { | 129 | { |
82 | MenuItemList.Add(mi); | 130 | MenuItemList.Add(mi); |
83 | if (string.IsNullOrWhiteSpace(mi.Key)) { mi.Key = $"#$KEY{MenuItemList.IndexOf(mi)}"; } | 131 | if (string.IsNullOrWhiteSpace(mi.Key)) { mi.Key = $"#$KEY{MenuItemList.IndexOf(mi)}"; } |
84 | return this; | 132 | return this; |
85 | } | 133 | } |
134 | + | ||
135 | + /// <summary> | ||
136 | + /// Törli a menüpontok listáját | ||
137 | + /// </summary> | ||
86 | public void ClearMenuItemList() { MenuItemList.Clear(); } | 138 | 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 | 139 | ||
94 | - public void ExecuteMenu() | 140 | + /// <summary> |
141 | + /// Végrehajtja a menüt, azaz választási lehetőséget biztosít, majd végrehajtja a kiválasztott menupontokhoz tartozó executor metódusokat | ||
142 | + /// </summary> | ||
143 | + /// <param name="forcedselectionkeylist"></param> | ||
144 | + public void ExecuteMenu(string forcedselectionkeylist=null) | ||
95 | { | 145 | { |
96 | try | 146 | try |
97 | { | 147 | { |
98 | while (true) | 148 | while (true) |
99 | { | 149 | { |
100 | DisplayTitle(); | 150 | DisplayTitle(); |
151 | + MenuHeaderDisplayer?.Invoke(); | ||
101 | DisplayItems(); | 152 | DisplayItems(); |
102 | - var sr = Select(); | 153 | + var sr = Select(forcedselectionkeylist); |
103 | if (sr.Result == Menu.SelectionResult.Exit) { return; } | 154 | if (sr.Result == Menu.SelectionResult.Exit) { return; } |
104 | else if (sr.Result == Menu.SelectionResult.None) { continue; } | 155 | else if (sr.Result == Menu.SelectionResult.None) { continue; } |
105 | else if (sr.Result == Menu.SelectionResult.Error) { continue; } | 156 | else if (sr.Result == Menu.SelectionResult.Error) { continue; } |
106 | ExecuteSelection(sr.SelectedKeyList); | 157 | ExecuteSelection(sr.SelectedKeyList); |
158 | + if (Menu.IsCommandMode()) { return; } | ||
107 | } | 159 | } |
108 | } | 160 | } |
109 | catch (Exception ex) | 161 | catch (Exception ex) |
@@ -113,33 +165,70 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -113,33 +165,70 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
113 | Menu.PressAnykeyToContinue(); | 165 | Menu.PressAnykeyToContinue(); |
114 | } | 166 | } |
115 | } | 167 | } |
168 | + | ||
169 | + | ||
170 | + /// <summary> | ||
171 | + /// Megjeleníti a menő fejlécét | ||
172 | + /// </summary> | ||
116 | public void DisplayTitle() | 173 | public void DisplayTitle() |
117 | { | 174 | { |
118 | - if (GetCommandMode()) { return; } | 175 | + if (Menu.IsCommandMode()) { return; } |
119 | 176 | ||
120 | ColorConsole.Clear(); | 177 | ColorConsole.Clear(); |
121 | ColorConsole.WriteLine(Title, ConsoleColor.White); | 178 | ColorConsole.WriteLine(Title, ConsoleColor.White); |
122 | ColorConsole.WriteLine(new string('-', Title.Length)); | 179 | ColorConsole.WriteLine(new string('-', Title.Length)); |
123 | } | 180 | } |
181 | + | ||
182 | + private static int SetMenuItemHeaderWidth(List<Item> MenuItemList,int columns) | ||
183 | + { | ||
184 | + var menuItemmaxwidth = 0; | ||
185 | + var i = 1; | ||
186 | + foreach (var menuitem in MenuItemList) | ||
187 | + { | ||
188 | + var len = 0; | ||
189 | + len += 1;//ColorConsole.Write($"["); | ||
190 | + len += $"{i}".Length;// ColorConsole.Write($"{i}"); | ||
191 | + if (menuitem.Separator) { continue; } | ||
192 | + if (!string.IsNullOrEmpty(menuitem.Key) && !menuitem.Key.StartsWith("#$KEY")) | ||
193 | + { | ||
194 | + len += 1;//ColorConsole.Write($":"); | ||
195 | + len += $"{menuitem.Key}".Length;//ColorConsole.Write(menuitem.Key, ConsoleColor.Yellow); | ||
196 | + } | ||
197 | + len += 1;//ColorConsole.Write($"]"); | ||
198 | + if (columns == 1) | ||
199 | + { | ||
200 | + if (menuItemmaxwidth == 0 || len > menuItemmaxwidth) { menuItemmaxwidth = len+1; } | ||
201 | + } | ||
202 | + i++; | ||
203 | + } | ||
204 | + return menuItemmaxwidth; | ||
205 | + } | ||
206 | + | ||
207 | + /// <summary> | ||
208 | + /// Megjeleníti a menüpontokat | ||
209 | + /// </summary> | ||
210 | + /// <param name="columns"></param> | ||
211 | + /// <param name="columnlength"></param> | ||
124 | public void DisplayItems(int columns = 1, int columnlength = 0) | 212 | public void DisplayItems(int columns = 1, int columnlength = 0) |
125 | { | 213 | { |
126 | - if (GetCommandMode()) { return; } | 214 | + if (Menu.IsCommandMode()) { return; } |
127 | 215 | ||
128 | int columncounter = 0; | 216 | int columncounter = 0; |
129 | ColorConsole.WriteLine(); | 217 | ColorConsole.WriteLine(); |
130 | var i = 1; | 218 | var i = 1; |
131 | ColorConsole.SetCursorPosition(0, ColorConsole.CursorTop); | 219 | ColorConsole.SetCursorPosition(0, ColorConsole.CursorTop); |
220 | + MenuItemIndentWidth = SetMenuItemHeaderWidth(MenuItemList, columns); | ||
132 | foreach (var menuitem in MenuItemList) | 221 | foreach (var menuitem in MenuItemList) |
133 | { | 222 | { |
134 | if (menuitem.Separator && columns == 1) | 223 | if (menuitem.Separator && columns == 1) |
135 | { | 224 | { |
136 | - ColorConsole.SetCursorPosition(columnlength * columncounter + HeaderWidth, ColorConsole.CursorTop); | 225 | + ColorConsole.SetCursorPosition(MenuItemIndentWidth, ColorConsole.CursorTop); |
137 | var seplen = menuitem.SeparatorLength; | 226 | var seplen = menuitem.SeparatorLength; |
138 | if (menuitem.SeparatorLength == 0) | 227 | if (menuitem.SeparatorLength == 0) |
139 | { | 228 | { |
140 | - foreach (var mi in MenuItemList.Where(x => !x.Separator)) { if (mi.Text.Length > seplen) { seplen = mi.Text.Length; } } | 229 | + foreach (var mi in MenuItemList.Where(x => !x.Separator)) { if (!string.IsNullOrWhiteSpace(mi.Text) && mi.Text.Length > seplen) { seplen = mi.Text.Length; } } |
141 | } | 230 | } |
142 | - ColorConsole.WriteLine(new string(menuitem.SeparatorChar, seplen)); | 231 | + ColorConsole.WriteLine(new string(menuitem.SeparatorChar, seplen==0?20:seplen)); |
143 | continue; | 232 | continue; |
144 | } | 233 | } |
145 | ColorConsole.Write($"["); | 234 | ColorConsole.Write($"["); |
@@ -150,21 +239,18 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -150,21 +239,18 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
150 | ColorConsole.Write(menuitem.Key, ConsoleColor.Yellow); | 239 | ColorConsole.Write(menuitem.Key, ConsoleColor.Yellow); |
151 | } | 240 | } |
152 | ColorConsole.Write($"]"); | 241 | ColorConsole.Write($"]"); |
153 | - ColorConsole.SetCursorPosition(columnlength * columncounter + HeaderWidth, ColorConsole.CursorTop); | ||
154 | - | ||
155 | - if (!string.IsNullOrEmpty(menuitem.Text)) | ||
156 | - { | ||
157 | - ColorConsole.Write(menuitem.Text); | ||
158 | - } | ||
159 | - if (columns == 1) | 242 | + if (columns == 1) |
160 | { | 243 | { |
244 | + if (MenuItemIndentWidth == 0) { MenuItemIndentWidth = ColorConsole.CursorLeft + 1; } | ||
245 | + ColorConsole.SetCursorPosition(MenuItemIndentWidth, ColorConsole.CursorTop); | ||
246 | + if (!string.IsNullOrEmpty(menuitem.Text)) { ColorConsole.Write(menuitem.Text); } | ||
161 | if (!string.IsNullOrEmpty(menuitem.Text)) { ColorConsole.WriteLine(); } | 247 | if (!string.IsNullOrEmpty(menuitem.Text)) { ColorConsole.WriteLine(); } |
162 | if (MenuItemDisplayer != null) | 248 | if (MenuItemDisplayer != null) |
163 | { | 249 | { |
164 | for (var li = 0; li < 100; li++) | 250 | for (var li = 0; li < 100; li++) |
165 | { | 251 | { |
166 | - if (li > 0) { ColorConsole.Write(new string(' ', HeaderWidth)); } | ||
167 | - var str = (string)MenuItemDisplayer(menuitem.Parameters, li); | 252 | + if (li > 0) { ColorConsole.Write(new string(' ', MenuItemIndentWidth)); } |
253 | + var str = (string)MenuItemDisplayer.Invoke(menuitem.Parameters, li); | ||
168 | if (string.IsNullOrEmpty(str)) { ColorConsole.SetCursorPosition(0, ColorConsole.CursorTop); } | 254 | if (string.IsNullOrEmpty(str)) { ColorConsole.SetCursorPosition(0, ColorConsole.CursorTop); } |
169 | if (str == null) { break; } | 255 | if (str == null) { break; } |
170 | } | 256 | } |
@@ -172,6 +258,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -172,6 +258,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
172 | } | 258 | } |
173 | else | 259 | else |
174 | { | 260 | { |
261 | + ColorConsole.SetCursorPosition(columnlength * columncounter, ColorConsole.CursorTop); | ||
262 | + if (!string.IsNullOrEmpty(menuitem.Text)) { ColorConsole.Write(menuitem.Text); } | ||
175 | columncounter++; | 263 | columncounter++; |
176 | if (columncounter == columns) { ColorConsole.WriteLine(); columncounter = 0; } | 264 | if (columncounter == columns) { ColorConsole.WriteLine(); columncounter = 0; } |
177 | else | 265 | else |
@@ -189,28 +277,61 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -189,28 +277,61 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
189 | } | 277 | } |
190 | ColorConsole.Write("EX", ConsoleColor.Red, bracket: "()"); ColorConsole.WriteLine(" Exit"); | 278 | ColorConsole.Write("EX", ConsoleColor.Red, bracket: "()"); ColorConsole.WriteLine(" Exit"); |
191 | } | 279 | } |
280 | + public static Selection SelectFromItemList(string listtitle, string selectionprompt, Dictionary<string, string> items, Menu.SelectionMode mode = SelectionMode.Single,bool getconfirmation=false) | ||
281 | + { | ||
282 | + var menubackupfiles = new Menu(listtitle, selectionprompt) | ||
283 | + .SetSelectionMode(mode); | ||
284 | + | ||
285 | + foreach (var i in items) | ||
286 | + { | ||
287 | + menubackupfiles.AddMenuItem(new Item(null, i.Key, null, new ExecutorParameter(pars: i.Value))); | ||
288 | + } | ||
289 | + Menu.Selection ms; | ||
290 | + while (true) | ||
291 | + { | ||
292 | + menubackupfiles.DisplayItems(1); | ||
293 | + ms = menubackupfiles.Select(); | ||
294 | + if (ms.Result == SelectionResult.None) { continue; } | ||
295 | + else if (ms.Result == SelectionResult.Error) { continue; } | ||
296 | + else if (ms.Result == SelectionResult.Exit) { return null; } | ||
297 | + else | ||
298 | + { | ||
299 | + if (!getconfirmation || getconfirmation && ColorConsole.ReadLine("Enter [CONFIRM] to confirm!", ConsoleColor.Yellow,suffix:" --> ").ToUpper() == "CONFIRM") { return ms; } | ||
300 | + else { continue; } | ||
301 | + } | ||
302 | + } | ||
303 | + } | ||
304 | + | ||
305 | + | ||
306 | + /// <summary> | ||
307 | + /// A Menuből való választás eredményét tartalmazza | ||
308 | + /// </summary> | ||
192 | public class Selection | 309 | public class Selection |
193 | { | 310 | { |
194 | public Selection() { } | 311 | public Selection() { } |
195 | - public Selection(string selectedkey,object parameter) | 312 | + public Selection(string selectedkey, Menu.ExecutorParameter parameter) |
196 | { | 313 | { |
197 | Result = SelectionResult.Ok; | 314 | Result = SelectionResult.Ok; |
198 | SelectedKeyList = new List<string>() { { selectedkey } }; | 315 | SelectedKeyList = new List<string>() { { selectedkey } }; |
199 | - SelectedParameterList = new List<object>() { { parameter } }; | 316 | + SelectedParameterList = new List<Menu.ExecutorParameter>() { { parameter } }; |
200 | } | 317 | } |
201 | public List<string> SelectedKeyList = null; | 318 | public List<string> SelectedKeyList = null; |
202 | public SelectionResult Result; | 319 | public SelectionResult Result; |
203 | - public List<object> SelectedParameterList; | 320 | + public List<Menu.ExecutorParameter> SelectedParameterList; |
204 | } | 321 | } |
205 | public enum SelectionResult { Exit, None, Error, Ok, } | 322 | public enum SelectionResult { Exit, None, Error, Ok, } |
206 | public enum SelectionMode { Single, Multi, } | 323 | public enum SelectionMode { Single, Multi, } |
324 | + | ||
325 | + /// <summary> | ||
326 | + /// A menüből való választás lebonyolítása | ||
327 | + /// </summary> | ||
328 | + /// <param name="forcedselectionkeylist"></param> | ||
329 | + /// <returns></returns> | ||
207 | public Selection Select(string forcedselectionkeylist=null) | 330 | public Selection Select(string forcedselectionkeylist=null) |
208 | { | 331 | { |
209 | - List<string> selectionKeyList; | ||
210 | - List<object> selectionParList; | ||
211 | string selectionliststr; | 332 | string selectionliststr; |
212 | var result = new Selection(); | 333 | var result = new Selection(); |
213 | - if (GetCommandMode()) | 334 | + if (Menu.IsCommandMode()) |
214 | { | 335 | { |
215 | selectionliststr = forcedselectionkeylist??"EX"; | 336 | selectionliststr = forcedselectionkeylist??"EX"; |
216 | } | 337 | } |
@@ -246,47 +367,81 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -246,47 +367,81 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
246 | result.SelectedKeyList = null; | 367 | result.SelectedKeyList = null; |
247 | return result; | 368 | return result; |
248 | } | 369 | } |
249 | - else if (selectionMode == SelectionMode.Multi && selectionliststr == "*") | 370 | + else if (selectionMode == SelectionMode.Single && selectionliststr == "*") |
250 | { | 371 | { |
251 | - selectionKeyList = new List<string>(); | ||
252 | - selectionParList = new List<object>(); | ||
253 | - var i = 1; | ||
254 | - foreach (var mi in MenuItemList) | ||
255 | - { | ||
256 | - selectionKeyList.Add(mi.Key); | ||
257 | - selectionParList.Add(mi.Parameters); | ||
258 | - } | ||
259 | - result.Result = SelectionResult.Ok; | ||
260 | - result.SelectedKeyList = selectionKeyList; | ||
261 | - result.SelectedParameterList = selectionParList; | 372 | + result.Result = SelectionResult.Error; |
373 | + result.SelectedKeyList = null; | ||
262 | return result; | 374 | return result; |
263 | } | 375 | } |
264 | - selectionKeyList = new List<string>(); | ||
265 | - selectionParList = new List<object>(); | ||
266 | - foreach (var selection in selectionliststr.Split(',').ToList()) | 376 | + else if (selectionliststr == "*") { return ProcessOKSelection(MenuItemKeyList); } // all keys |
377 | + else { return ProcessOKSelection(selectionliststr.Split(',').ToList()); } // selected list list | ||
378 | + } | ||
379 | + #region ProcessOKSelection | ||
380 | + private Selection ProcessOKSelection(List<string> selectionKeyList) | ||
381 | + { | ||
382 | + var result = new Selection(); | ||
383 | + var return_selectionParList = new List<Menu.ExecutorParameter>(); | ||
384 | + List<string> return_selectionKeyList = new List<string>(); | ||
385 | + foreach (var selectedkeyorindex in selectionKeyList) | ||
267 | { | 386 | { |
268 | - string _selection = selection; | ||
269 | - object _parameters = null; | ||
270 | - if (!MenuKeyList.Contains(_selection)) | 387 | + string _selectedkey; |
388 | + Item _selectedmenuitem; | ||
389 | + if (MenuItemKeyList.Contains(selectedkeyorindex)) { _selectedkey = selectedkeyorindex; } | ||
390 | + else | ||
271 | { | 391 | { |
272 | - if (!int.TryParse(_selection, out int indexselection) || indexselection < 1 || indexselection > MenuItemList.Count()) | 392 | + if (!int.TryParse(selectedkeyorindex, out int _selectedindex) || _selectedindex < 1 || _selectedindex > MenuItemList.Count()) |
273 | { | 393 | { |
274 | - Menu.IncorrectSelection($"Selected item {_selection} is not valid!"); | 394 | + Menu.IncorrectSelection($"Selected item {selectedkeyorindex} is not valid!"); |
275 | result.Result = SelectionResult.Error; | 395 | result.Result = SelectionResult.Error; |
276 | result.SelectedKeyList = null; | 396 | result.SelectedKeyList = null; |
277 | return result; | 397 | return result; |
278 | } | 398 | } |
279 | - _selection = GetItemKey(indexselection - 1); | ||
280 | - _parameters = GetItem(indexselection - 1).Parameters; | 399 | + _selectedkey = GetItemKey(_selectedindex - 1); |
281 | } | 400 | } |
282 | - selectionKeyList.Add(_selection); | ||
283 | - selectionParList.Add(_parameters); | 401 | + _selectedmenuitem = GetItem(_selectedkey); |
402 | + ResolvemenuItemGroup(_selectedmenuitem, return_selectionKeyList, return_selectionParList); | ||
284 | } | 403 | } |
285 | result.Result = SelectionResult.Ok; | 404 | result.Result = SelectionResult.Ok; |
286 | - result.SelectedKeyList = selectionKeyList; | ||
287 | - result.SelectedParameterList = selectionParList; | 405 | + result.SelectedKeyList = return_selectionKeyList; |
406 | + result.SelectedParameterList = return_selectionParList; | ||
288 | return result; | 407 | return result; |
289 | } | 408 | } |
409 | + #endregion ProcessOKSelection | ||
410 | + #region ResolveGroup | ||
411 | + private void ResolvemenuItemGroup(Menu.Item _selectedmenuitem,List<string> selectionKeyList,List<ExecutorParameter> selectionParList) | ||
412 | + { | ||
413 | + if (_selectedmenuitem.Group) | ||
414 | + { | ||
415 | + List<string> keysinmenuitemgroup; | ||
416 | + if (_selectedmenuitem.GroupKeyList.Contains("*")) { keysinmenuitemgroup = MenuItemList.Where(x=>!x.Group && !x.Separator).Select(x=>x.Key).ToList(); } | ||
417 | + else { keysinmenuitemgroup = _selectedmenuitem.GroupKeyList.Select(x => x).ToList(); } | ||
418 | + | ||
419 | + foreach (var ikey in keysinmenuitemgroup) | ||
420 | + { | ||
421 | + var mikey = GetItem(ikey); | ||
422 | + if (mikey!=null && !mikey.Group) | ||
423 | + { | ||
424 | + if (selectionKeyList.Contains(ikey)) { continue; } | ||
425 | + selectionKeyList.Add(ikey); | ||
426 | + selectionParList.Add(mikey.Parameters); | ||
427 | + } | ||
428 | + else | ||
429 | + { | ||
430 | + throw new Exception($"MenuItem '{ikey}' referred by MenuItemGroup '{_selectedmenuitem.Key}' does not exist or is a group!"); | ||
431 | + } | ||
432 | + } | ||
433 | + } | ||
434 | + else | ||
435 | + { | ||
436 | + selectionKeyList.Add(_selectedmenuitem.Key); | ||
437 | + selectionParList.Add(_selectedmenuitem.Parameters); | ||
438 | + } | ||
439 | + } | ||
440 | + #endregion ResolveGroup | ||
441 | + /// <summary> | ||
442 | + /// A menuből való választás alapján végrehajtja a kiválasztott menüpontokhoz rendelt executorokat | ||
443 | + /// </summary> | ||
444 | + /// <param name="selectedkeylist"></param> | ||
290 | public void ExecuteSelection(List<string> selectedkeylist) | 445 | public void ExecuteSelection(List<string> selectedkeylist) |
291 | { | 446 | { |
292 | object o = null; | 447 | object o = null; |
@@ -300,18 +455,11 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -300,18 +455,11 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
300 | Menu.PressAnykeyToContinue(); | 455 | Menu.PressAnykeyToContinue(); |
301 | } | 456 | } |
302 | 457 | ||
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(); | ||
314 | - } | 458 | + /// <summary> |
459 | + /// Visszadja a menupont kulcsához tartozó executor metódust | ||
460 | + /// </summary> | ||
461 | + /// <param name="key"></param> | ||
462 | + /// <returns></returns> | ||
315 | public MenuItemExecutorFunc GetExecutor(string key) | 463 | public MenuItemExecutorFunc GetExecutor(string key) |
316 | { | 464 | { |
317 | return MenuItemList.ElementAt(GetItemIx(key)).Executor; | 465 | return MenuItemList.ElementAt(GetItemIx(key)).Executor; |
@@ -319,31 +467,57 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -319,31 +467,57 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
319 | #endregion public tools | 467 | #endregion public tools |
320 | 468 | ||
321 | #region private tools | 469 | #region private tools |
470 | + /// <summary> | ||
471 | + /// visszadja a megadott kulcsú menupont leíróját | ||
472 | + /// </summary> | ||
473 | + /// <param name="itemkey"></param> | ||
474 | + /// <returns></returns> | ||
322 | private Menu.Item GetItem(string itemkey) | 475 | private Menu.Item GetItem(string itemkey) |
323 | { | 476 | { |
324 | return MenuItemList.FirstOrDefault(x => x.Key == itemkey); | 477 | return MenuItemList.FirstOrDefault(x => x.Key == itemkey); |
325 | } | 478 | } |
479 | + /// <summary> | ||
480 | + /// visszadja a megadott indexű menupont leíróját | ||
481 | + /// </summary> | ||
482 | + /// <param name="ix"></param> | ||
483 | + /// <returns></returns> | ||
326 | private Menu.Item GetItem(int ix) | 484 | private Menu.Item GetItem(int ix) |
327 | { | 485 | { |
328 | var i = 0; | 486 | var i = 0; |
329 | foreach (var mi in MenuItemList) | 487 | foreach (var mi in MenuItemList) |
330 | { | 488 | { |
331 | if (mi.Separator) { continue; } | 489 | if (mi.Separator) { continue; } |
332 | - if (i == ix) return mi; | 490 | + if (i == ix) { return mi; } |
333 | i++; | 491 | i++; |
334 | } | 492 | } |
335 | return null; | 493 | return null; |
336 | //return MenuItemList.ElementAt(ix); | 494 | //return MenuItemList.ElementAt(ix); |
337 | } | 495 | } |
496 | + /// <summary> | ||
497 | + /// Visszadja a megadott kulcsú menüpont indexét | ||
498 | + /// </summary> | ||
499 | + /// <param name="itemkey"></param> | ||
500 | + /// <returns></returns> | ||
338 | private int GetItemIx(string itemkey) | 501 | private int GetItemIx(string itemkey) |
339 | { | 502 | { |
340 | - return MenuKeyList.IndexOf(itemkey); | 503 | + return MenuItemKeyList.IndexOf(itemkey); |
341 | } | 504 | } |
342 | - private string GetItemKey(int ix) | 505 | + /// <summary> |
506 | + /// Visszadja a megadott indexű menüpont kulcsát | ||
507 | + /// </summary> | ||
508 | + /// <param name="ix"></param> | ||
509 | + /// <returns></returns> | ||
510 | + string GetItemKey(int ix) | ||
343 | { | 511 | { |
344 | - return MenuKeyList.ElementAt(ix); | 512 | + return MenuItemKeyList.ElementAt(ix); |
345 | } | 513 | } |
346 | - public void SetExecutorParameters(Menu.Selection r, object p=null) | 514 | + /// <summary> |
515 | + /// A kiválasztott menupontokhoz beállítja a megadott paramétereket a metódus paramétereként megadott paraméterre, | ||
516 | + /// vagy ennek híján a Selection objektumban levő paraméterekre | ||
517 | + /// </summary> | ||
518 | + /// <param name="r">a Selection objektum</param> | ||
519 | + /// <param name="p">a beállítandó paraméter</param> | ||
520 | + public void SetExecutorParameters(Menu.Selection r, ExecutorParameter p =null) | ||
347 | { | 521 | { |
348 | foreach (var mi in this.MenuItemList) | 522 | foreach (var mi in this.MenuItemList) |
349 | { | 523 | { |
@@ -355,6 +529,33 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -355,6 +529,33 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
355 | } | 529 | } |
356 | } | 530 | } |
357 | #endregion private tools | 531 | #endregion private tools |
532 | + | ||
533 | + public class ExecutorParameter | ||
534 | + { | ||
535 | + public ExecutorParameter(object cfg=null, string[] args=null, object pars=null) | ||
536 | + { | ||
537 | + _config = cfg; Args = args;Parameters = pars; | ||
538 | + } | ||
539 | + public TXMLPROCESSORTYPE GetConfig<TXMLPROCESSORTYPE>() | ||
540 | + where TXMLPROCESSORTYPE : XmlParser | ||
541 | + { | ||
542 | + return _config as TXMLPROCESSORTYPE; | ||
543 | + } | ||
544 | + | ||
545 | + private object _config; | ||
546 | + public object Parameters; | ||
547 | + public string[] Args { get; set; } | ||
548 | + } | ||
549 | + public class ItemGroup: Item | ||
550 | + { | ||
551 | + public ItemGroup(string key, string text, List<string> keylist) : base() | ||
552 | + { | ||
553 | + Key = key; | ||
554 | + Text = text; | ||
555 | + Group = true; | ||
556 | + GroupKeyList = keylist; | ||
557 | + } | ||
558 | + } | ||
358 | public class ItemSeparator : Item | 559 | public class ItemSeparator : Item |
359 | { | 560 | { |
360 | public ItemSeparator(char c = '-', int length = 0) : base() | 561 | public ItemSeparator(char c = '-', int length = 0) : base() |
@@ -367,7 +568,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -367,7 +568,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
367 | public class Item | 568 | public class Item |
368 | { | 569 | { |
369 | public Item() { } | 570 | public Item() { } |
370 | - public Item(string key, string text, MenuItemExecutorFunc executor = null, object parameters = null) | 571 | + public Item(string key, string text, MenuItemExecutorFunc executor = null, Menu.ExecutorParameter parameters = null) |
371 | { | 572 | { |
372 | Key = key; | 573 | Key = key; |
373 | Text = text; | 574 | Text = text; |
@@ -377,7 +578,10 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -377,7 +578,10 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
377 | public string Key; | 578 | public string Key; |
378 | public string Text; | 579 | public string Text; |
379 | public MenuItemExecutorFunc Executor; | 580 | public MenuItemExecutorFunc Executor; |
380 | - public object Parameters; | 581 | + public Menu.ExecutorParameter Parameters; |
582 | + | ||
583 | + public bool Group = false; | ||
584 | + public List<string> GroupKeyList; | ||
381 | 585 | ||
382 | public bool Separator = false; | 586 | public bool Separator = false; |
383 | public char SeparatorChar = '-'; | 587 | public char SeparatorChar = '-'; |
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - Tools - Membership.cs
0 → 100644
@@ -0,0 +1,1081 @@ | @@ -0,0 +1,1081 @@ | ||
1 | +using System; | ||
2 | +using System.Data.Linq.SqlClient; | ||
3 | +using System.IO; | ||
4 | +using System.IO.Compression; | ||
5 | +using System.Collections.Generic; | ||
6 | +using System.Linq; | ||
7 | +using System.Security.Principal; | ||
8 | +using System.Text; | ||
9 | +using System.Text.RegularExpressions; | ||
10 | +using System.Threading.Tasks; | ||
11 | +using System.Threading; | ||
12 | + | ||
13 | +using Microsoft.Web.Administration; | ||
14 | +using System.Management; | ||
15 | +using System.Diagnostics; | ||
16 | + | ||
17 | +using Vrh.XmlProcessing; | ||
18 | +using System.Xml.Linq; | ||
19 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
20 | +using VRH.Common; | ||
21 | + | ||
22 | +using System.Data.Entity; | ||
23 | +using System.ComponentModel.DataAnnotations; | ||
24 | +using System.ComponentModel.DataAnnotations.Schema; | ||
25 | + | ||
26 | +namespace Vrh.Log4Pro.MaintenanceConsole.ToolsNS | ||
27 | +{ | ||
28 | + using System.Web.Security; | ||
29 | + | ||
30 | + public static class MembershipTools | ||
31 | + { | ||
32 | + public static void SetConnectionString(string sqlcs) | ||
33 | + { | ||
34 | + MembershipDBContext = new DAL.MembershipContext(sqlcs); | ||
35 | + m_MembershipProvider = System.Web.Security.Membership.Provider; | ||
36 | + m_roleProvider = System.Web.Security.Roles.Provider; | ||
37 | + } | ||
38 | + private static MembershipProvider m_MembershipProvider; | ||
39 | + private static RoleProvider m_roleProvider; | ||
40 | + private static DAL.MembershipContext MembershipDBContext; | ||
41 | + | ||
42 | + #region Constants | ||
43 | + public class Constants | ||
44 | + { | ||
45 | + public const string SCHEMA_NAME = "UAdmin"; | ||
46 | + | ||
47 | + public const string ROLENAME_ADMINISTRATOR = "Administrator"; | ||
48 | + public const string ROLENAME_ADMIN = "Admin"; | ||
49 | + public const string USERNAME_ADMINISTRATOR = "Administrator"; | ||
50 | + public const string PASSWORD_ADMINISTRATOR = "Admin123"; | ||
51 | + public const string USERNAME_ADMIN = "Admin"; | ||
52 | + public const string PASSWORD_ADMIN = "Admin123"; | ||
53 | + public static readonly string[] SYSTEMUSERNAMELIST = new string[] { ROLENAME_ADMIN, USERNAME_ADMINISTRATOR }; | ||
54 | + public static readonly DateTime NEVERONLINE = new DateTime(2000, 1, 1); | ||
55 | + } | ||
56 | + #endregion Constants | ||
57 | + | ||
58 | + #region Users | ||
59 | + public static class Users | ||
60 | + { | ||
61 | + #region IsSecondaryUser | ||
62 | + /// <summary> | ||
63 | + /// true-val tér vissza, ha léteznek ehhez az elsődleges userhez másodlagos user-ek | ||
64 | + /// </summary> | ||
65 | + /// <param name="primaryusername"></param> | ||
66 | + /// <returns></returns> | ||
67 | + public static bool IsSecondaryUserOfUser(string primaryusername) | ||
68 | + { | ||
69 | + var sUserList = MembershipDBContext.SecondaryUsers.Where(x => x.User != null && x.User.UserName == primaryusername); | ||
70 | + return (sUserList != null && sUserList.Any()); | ||
71 | + } | ||
72 | + #endregion IsSecondaryUser | ||
73 | + #region DeleteSecondaryUsersOfUser methods | ||
74 | + /// <summary> | ||
75 | + /// Másodlagos felhasználó törlése a funkció nevének és a felhasználó nevének megadásával. | ||
76 | + /// </summary> | ||
77 | + /// <param name="primaryusername">Elsődleges felhasználó neve.</param> | ||
78 | + /// <exception cref="ApplicationException">Ha nem található a törlendő másodlagos felhasználó.</exception> | ||
79 | + public static void DeleteSecondaryUsersOfUser(string primaryusername) | ||
80 | + { | ||
81 | + var sUserList = MembershipDBContext.SecondaryUsers.Where(x => x.User!=null && x.User.UserName == primaryusername); | ||
82 | + if (sUserList == null || !sUserList.Any()) | ||
83 | + { | ||
84 | + throw new ApplicationException($"Secondary users for primary user '{primaryusername}' not found!"); | ||
85 | + } | ||
86 | + else | ||
87 | + { | ||
88 | + foreach (var suser in sUserList) | ||
89 | + { | ||
90 | + var sllist = MembershipDBContext.SecondaryLogins.Where(sl => sl.SecondaryUserId == suser.Id); | ||
91 | + if (sllist != null && sllist.Any()) { foreach (var sl in sllist) { MembershipDBContext.SecondaryLogins.Remove(sl); } } | ||
92 | + MembershipDBContext.SecondaryUsers.Remove(suser); | ||
93 | + } | ||
94 | + MembershipDBContext.SaveChanges(); | ||
95 | + } | ||
96 | + } | ||
97 | + #endregion DeleteSecondaryUsersOfUser methods | ||
98 | + #region Create | ||
99 | + /// <summary> | ||
100 | + /// Felhasználó létrehozása a paraméterlistában felsorolt paraméterek megadásával. | ||
101 | + /// </summary> | ||
102 | + /// <param name="username">Felhasználó neve.</param> | ||
103 | + /// <param name="password">Felhasználó jelszava.</param> | ||
104 | + /// <param name="administrator">hozzárendeli a usert az Admin és az Administrator szerepekhez</param> | ||
105 | + /// <param name="superuser">hozzárendeli a usert minden létező szerephez és szerepkörhöz</param> | ||
106 | + /// <param name="rolenames">a felhasználóhoz hozzárendelendő role nevek listája; ha a lista tartalmazza a * tagot, akkor minden role.</param> | ||
107 | + /// <param name="rolegroupnames">a felhasználóhoz hozzárendelendő rolegroup nevek listája; ha a lista tartalmazza a * tagot, akkor minden rolegroup.</param> | ||
108 | + /// <returns> A létrehozott felhasználó <c>MembershipUser</c> objektuma.</returns> | ||
109 | + public static MembershipUser Create(string username, string password, bool administrator=false,bool superuser=false, string[] rolenames=null,string[]rolegroupnames=null) | ||
110 | + { | ||
111 | + #region ellenőrzések | ||
112 | + if (String.IsNullOrWhiteSpace(username)) { throw new MembershipCreateUserException("Username is required!"); } | ||
113 | + | ||
114 | + string wrPrefix = "WebReq_"; | ||
115 | + string adPrefix = "AD_"; | ||
116 | + if (username.StartsWith(wrPrefix, StringComparison.OrdinalIgnoreCase) || username.StartsWith(adPrefix, StringComparison.OrdinalIgnoreCase)) | ||
117 | + { | ||
118 | + throw new MembershipCreateUserException($"Username format is incorrect, it can not start with {wrPrefix}, {adPrefix}"); | ||
119 | + } | ||
120 | + #endregion ellenőrzések | ||
121 | + | ||
122 | + CreateAdminRolesAndUsers(); | ||
123 | + MembershipUser user = Membership.GetUser(username); | ||
124 | + if (user == null) | ||
125 | + { | ||
126 | + user = Membership.CreateUser(username, password); | ||
127 | + user.LastActivityDate = Constants.NEVERONLINE; | ||
128 | + user.LastLoginDate = Constants.NEVERONLINE; | ||
129 | + user.Comment = ""; | ||
130 | + user.Email = ""; | ||
131 | + user.IsApproved = true; | ||
132 | + Membership.UpdateUser(user); | ||
133 | + //user.ChangePasswordQuestionAndAnswer(password, "", ""); | ||
134 | + } | ||
135 | + if (superuser) | ||
136 | + { | ||
137 | + string rgnamelist = string.Join(",", MembershipDBContext.RoleGroups.Select(rg => rg.Name).ToArray()); | ||
138 | + if (!string.IsNullOrWhiteSpace(rgnamelist)) { Assign.RoleGroupsToUsers(rgnamelist, username); } | ||
139 | + foreach (var rn in Roles.GetAllRoles()) | ||
140 | + { | ||
141 | + if (!Users.IsInRole(username, rn)) { Roles.AddUserToRole(username, rn); } | ||
142 | + } | ||
143 | + } | ||
144 | + else if (administrator) | ||
145 | + { | ||
146 | + if (!Roles.IsUserInRole(username, Constants.ROLENAME_ADMINISTRATOR)) { Roles.AddUserToRole(username, Constants.ROLENAME_ADMINISTRATOR); } | ||
147 | + if (!Roles.IsUserInRole(username, Constants.ROLENAME_ADMIN)) { Roles.AddUserToRole(username, Constants.ROLENAME_ADMIN); } | ||
148 | + } | ||
149 | + | ||
150 | + string[] selectedrolenames; | ||
151 | + if (rolenames != null) | ||
152 | + { | ||
153 | + selectedrolenames = rolenames.Contains("*") ? Roles.GetAllRoles() : rolenames; | ||
154 | + if (selectedrolenames != null && selectedrolenames.Any()) | ||
155 | + { | ||
156 | + foreach (var rname in selectedrolenames) { if (!Roles.IsUserInRole(username, rname)) { Roles.AddUserToRole(username, rname); } } | ||
157 | + } | ||
158 | + } | ||
159 | + string[] selectedrolegroupnames; | ||
160 | + if (rolegroupnames != null) | ||
161 | + { | ||
162 | + selectedrolegroupnames = rolegroupnames.Contains("*") ? RoleGroups.GetAllNames().ToArray() : rolegroupnames; | ||
163 | + if (selectedrolegroupnames != null && selectedrolegroupnames.Any()) | ||
164 | + { | ||
165 | + foreach (var rgname in selectedrolegroupnames) { if (!RoleGroups.IsUserInRoleGroup(username, rgname)) { Assign.RoleGroupsToUsers(rgname, username); } } | ||
166 | + } | ||
167 | + } | ||
168 | + return user; | ||
169 | + } | ||
170 | + #endregion Create | ||
171 | + #region CreateAdminRolesAndUsers | ||
172 | + public static void CreateAdminRolesAndUsers() | ||
173 | + { | ||
174 | + MembershipUser user; | ||
175 | + if (!Roles.RoleExists(Constants.ROLENAME_ADMINISTRATOR)) { Roles.CreateRole(Constants.ROLENAME_ADMINISTRATOR); } | ||
176 | + if (!Roles.RoleExists(Constants.ROLENAME_ADMIN)) { Roles.CreateRole(Constants.ROLENAME_ADMIN); } | ||
177 | + | ||
178 | + user = Membership.GetUser(Constants.USERNAME_ADMIN); | ||
179 | + if (user == null) | ||
180 | + { | ||
181 | + user = Membership.CreateUser(Constants.USERNAME_ADMIN, Constants.PASSWORD_ADMIN); | ||
182 | + } | ||
183 | + if (!Roles.IsUserInRole(Constants.USERNAME_ADMIN, Constants.ROLENAME_ADMINISTRATOR)) { Roles.AddUserToRole(Constants.USERNAME_ADMIN, Constants.ROLENAME_ADMINISTRATOR); } | ||
184 | + if (!Roles.IsUserInRole(Constants.USERNAME_ADMIN, Constants.ROLENAME_ADMIN)) { Roles.AddUserToRole(Constants.USERNAME_ADMIN, Constants.ROLENAME_ADMIN); } | ||
185 | + | ||
186 | + user = Membership.GetUser(Constants.USERNAME_ADMINISTRATOR); | ||
187 | + if (user == null) | ||
188 | + { | ||
189 | + user = Membership.CreateUser(Constants.USERNAME_ADMINISTRATOR, Constants.PASSWORD_ADMINISTRATOR); | ||
190 | + } | ||
191 | + if (!Roles.IsUserInRole(Constants.USERNAME_ADMINISTRATOR, Constants.ROLENAME_ADMINISTRATOR)) { Roles.AddUserToRole(Constants.USERNAME_ADMINISTRATOR, Constants.ROLENAME_ADMINISTRATOR); } | ||
192 | + if (!Roles.IsUserInRole(Constants.USERNAME_ADMINISTRATOR, Constants.ROLENAME_ADMIN)) { Roles.AddUserToRole(Constants.USERNAME_ADMINISTRATOR, Constants.ROLENAME_ADMIN); } | ||
193 | + } | ||
194 | + #endregion CreateAdminRolesAndUsers | ||
195 | + #region IsInRole public method | ||
196 | + /// <summary> | ||
197 | + /// Annak jelzése, hogy a <paramref name="userName"/>-ben megadott nevű felhasználó | ||
198 | + /// rendelkezik-e a <paramref name="roleName"/>-ben megadott nevű szereppel. | ||
199 | + /// </summary> | ||
200 | + /// <param name="userName">A felhasználó neve.</param> | ||
201 | + /// <param name="roleName">A szerep neve.</param> | ||
202 | + /// <returns>Igaz, ha a felhasználó rendelekezik a megadott szereppel.</returns> | ||
203 | + public static bool IsInRole(string userName, string roleName) | ||
204 | + { | ||
205 | + return m_roleProvider.IsUserInRole(userName, roleName); | ||
206 | + } | ||
207 | + #endregion IsInRole public method | ||
208 | + #region Get | ||
209 | + public static MembershipUser Get(string userName) | ||
210 | + { | ||
211 | + return m_MembershipProvider.GetUser(userName, false); | ||
212 | + } | ||
213 | + #endregion Get | ||
214 | + #region GetNameList | ||
215 | + /// <summary> | ||
216 | + /// A maszknak megfelelő felhasználónevek listáját adja vissza. | ||
217 | + /// </summary> | ||
218 | + /// <param name="usernamemask">SQL LIKE-ba illeszhető maszk</param> | ||
219 | + /// <returns></returns> | ||
220 | + public static List<string> GetNameList(string usernamemask) | ||
221 | + { | ||
222 | + if (usernamemask == null) { usernamemask = "%"; } | ||
223 | + usernamemask = usernamemask.Replace("%", ".*").Replace("?", "."); | ||
224 | + return MembershipDBContext.Users | ||
225 | + .Select(u=>u.UserName) | ||
226 | + .ToList() | ||
227 | + .Where(un => Regex.Match(un, usernamemask).Success) | ||
228 | + .ToList(); | ||
229 | + } | ||
230 | + #endregion GetNameList | ||
231 | + #region GetList | ||
232 | + /// <summary> | ||
233 | + /// Az összes felhasználót tartalmazó listát ad vissza. | ||
234 | + /// </summary> | ||
235 | + /// <param name="includetempuser">Ha hamis, akkor az ideiglenes felhasználók nincsenek a listában.</param> | ||
236 | + /// <returns></returns> | ||
237 | + public static List<MembershipUser> GetList(string usernamemask,bool includetempuser = false) | ||
238 | + { | ||
239 | + var result = new List<MembershipUser>(); | ||
240 | + if (!includetempuser) | ||
241 | + { // az ideiglenes felhasználók nélkül | ||
242 | + var qry = MembershipDBContext.Users // primary | ||
243 | + .Where(u => SqlMethods.Like(u.UserName, usernamemask)) | ||
244 | + .GroupJoin(MembershipDBContext.UserSupplements, //foreign | ||
245 | + pk => pk.UserId, // primary key | ||
246 | + fk => fk.UserId, // foreign key | ||
247 | + (pka, fkb) => new { u = pka, us = fkb }) | ||
248 | + .SelectMany(sm => sm.us.DefaultIfEmpty(), (sm, d) => new { User = sm.u, UserSupplement = d }) | ||
249 | + .Where(x => x.UserSupplement == null || x.UserSupplement.IsTemporary == false) | ||
250 | + .Select(s => s.User); | ||
251 | + if (qry != null && qry.Any()) | ||
252 | + { | ||
253 | + foreach (var dbuser in qry) | ||
254 | + { | ||
255 | + MembershipUser user = m_MembershipProvider.GetUser(dbuser.UserId, false); | ||
256 | + if (user != null) | ||
257 | + { | ||
258 | + result.Add(user); | ||
259 | + } | ||
260 | + } | ||
261 | + } | ||
262 | + } | ||
263 | + else | ||
264 | + { // itt mehet mind, nem kell szűrögetni | ||
265 | + foreach (MembershipUser user in m_MembershipProvider.GetAllUsers(0, int.MaxValue, out int totalRecords)) | ||
266 | + { | ||
267 | + result.Add(user); | ||
268 | + } | ||
269 | + } | ||
270 | + return result; | ||
271 | + } | ||
272 | + #endregion GetList | ||
273 | + #region CheckPassword | ||
274 | + public static bool CheckPassword(string username, string userpassword) | ||
275 | + { | ||
276 | + var user = Membership.GetUser(username); | ||
277 | + return user.GetPassword()==userpassword; | ||
278 | + } | ||
279 | + #endregion CheckPassword | ||
280 | + #region Remove | ||
281 | + /// <summary> | ||
282 | + /// Törli a megadott nevű user-t és minden kapcsolatát | ||
283 | + /// </summary> | ||
284 | + /// <param name="sqlcs"></param> | ||
285 | + /// <param name="username"></param> | ||
286 | + /// <param name="userpsw"></param> | ||
287 | + /// <returns></returns> | ||
288 | + public static void Remove(string username) | ||
289 | + { | ||
290 | + if (string.IsNullOrWhiteSpace(username)) { throw new Exception("Username can not be null or empty or whitespace!"); } | ||
291 | + if (Get(username) == null) { throw new ApplicationException($"User {username} does not exist!"); } | ||
292 | + if (Constants.SYSTEMUSERNAMELIST.Contains(username)) { throw new MembershipCreateUserException($"System user {username} are not allowed to delete!"); } | ||
293 | + Assign.RemoveOfUser(username); | ||
294 | + if (Users.IsSecondaryUserOfUser(username)) { Users.DeleteSecondaryUsersOfUser(username); } | ||
295 | + m_MembershipProvider.DeleteUser(username, true); | ||
296 | + } | ||
297 | + #endregion Remove | ||
298 | + } | ||
299 | + #endregion Users | ||
300 | + #region RoleGroups | ||
301 | + public static class RoleGroups | ||
302 | + { | ||
303 | + #region Get methods | ||
304 | + /// <summary> | ||
305 | + /// Szerepkör lekérése az egyedi azonosítója alapján. | ||
306 | + /// </summary> | ||
307 | + /// <param name="id">A keresett funkció azonosítója.</param> | ||
308 | + /// <returns>A kért szerepkör, egyébként null.</returns> | ||
309 | + public static DAL.RoleGroup Get(int id) | ||
310 | + { | ||
311 | + return MembershipDBContext.RoleGroups.FirstOrDefault(x => x.Id == id); | ||
312 | + } | ||
313 | + /// <summary> | ||
314 | + /// Szerepkör lekérése az egyedi neve alapján. | ||
315 | + /// </summary> | ||
316 | + /// <param name="name">A keresett szerepkör egyedi neve.</param> | ||
317 | + /// <returns>A kért szerepkör, egyébként null.</returns> | ||
318 | + public static DAL.RoleGroup Get(string name) | ||
319 | + { | ||
320 | + return MembershipDBContext.RoleGroups.FirstOrDefault(x => x.Name == name); | ||
321 | + } | ||
322 | + /// <summary> | ||
323 | + /// Szerepkör lekérése az egyedi neve alapján. | ||
324 | + /// </summary> | ||
325 | + /// <param name="name">A keresett szerepkör egyedi neve.</param> | ||
326 | + /// <returns>A kért szerepkör, egyébként null.</returns> | ||
327 | + public static List<string> GetAllNames() | ||
328 | + { | ||
329 | + return MembershipDBContext.RoleGroups.Select(rg=>rg.Name).ToList(); | ||
330 | + } | ||
331 | + public static bool IsUserInRoleGroup(string username,string rolegroupname) | ||
332 | + { | ||
333 | + return MembershipDBContext.RoleGroupUsers.Select(rguass => rguass.User.UserName == username && rguass.RoleGroup.Name == rolegroupname).ToList().Any(); | ||
334 | + } | ||
335 | + #endregion Get methods | ||
336 | + | ||
337 | + #region Create method | ||
338 | + /// <summary> | ||
339 | + /// Szerepkör létrehozása. | ||
340 | + /// </summary> | ||
341 | + /// <param name="roleGroup">A létrehozandó szerepkör.</param> | ||
342 | + /// <exception cref="ApplicationException"> | ||
343 | + /// Ha üres vagy null a szerepkör neve. | ||
344 | + /// Ha már létezik a megadott név. | ||
345 | + /// </exception> | ||
346 | + public static void Create(DAL.RoleGroup roleGroup) | ||
347 | + { | ||
348 | + if (String.IsNullOrWhiteSpace(roleGroup.Name)) { throw new ApplicationException("RoleGroup név megadása kötelező!"); } | ||
349 | + | ||
350 | + if (MembershipDBContext.RoleGroups.Any(x => x.Name == roleGroup.Name)) { throw new ApplicationException($"RoleGroup {roleGroup.Name} already exist!"); } | ||
351 | + | ||
352 | + MembershipDBContext.RoleGroups.Add(roleGroup); | ||
353 | + MembershipDBContext.SaveChanges(); | ||
354 | + } | ||
355 | + /// <summary> | ||
356 | + /// Szerepkör létrehozása. | ||
357 | + /// </summary> | ||
358 | + /// <param name="name">A létrehozandó szerepkör.</param> | ||
359 | + /// <exception cref="ApplicationException"> | ||
360 | + /// Ha üres vagy null a szerepkör neve. | ||
361 | + /// Ha már létezik a megadott név. | ||
362 | + /// </exception> | ||
363 | + public static void Create(string name) | ||
364 | + { | ||
365 | + if (String.IsNullOrWhiteSpace(name)) { throw new ApplicationException("RoleGroup név megadása kötelező!"); } | ||
366 | + if (MembershipDBContext.RoleGroups.Any(x => x.Name == name)) { throw new ApplicationException($"RoleGroup {name} already exist!"); } | ||
367 | + MembershipDBContext.RoleGroups.Add(new DAL.RoleGroup { Name = name, }); | ||
368 | + MembershipDBContext.SaveChanges(); | ||
369 | + } | ||
370 | + #endregion Create method | ||
371 | + | ||
372 | + #region Remove methods | ||
373 | + /// <summary> | ||
374 | + /// Szerepkör törlése az egyedi azonosítója megadásával. | ||
375 | + /// A szerepkörhöz tartozó összerendelések is megszűnnek! | ||
376 | + /// </summary> | ||
377 | + /// <param name="id">Törlendő szerep egyedi azonosítója.</param> | ||
378 | + /// <exception cref="ApplicationException">Ha nem található a törlendő szerepkör.</exception> | ||
379 | + public static void Remove(int id) | ||
380 | + { | ||
381 | + var row = MembershipDBContext.RoleGroups.Find(id); | ||
382 | + if (row == null) { throw new ApplicationException("RoleGroup does not exist!!"); } | ||
383 | + else { MembershipDBContext.RoleGroups.Remove(row); MembershipDBContext.SaveChanges(); } | ||
384 | + } | ||
385 | + /// <summary> | ||
386 | + /// Szerepkör törlése az egyedi név megadásával. | ||
387 | + /// A szerepkörhöz tartozó összerendelések is megszűnnek! | ||
388 | + /// </summary> | ||
389 | + /// <param name="name">Törlendő szerepkör egyedi neve.</param> | ||
390 | + /// <exception cref="ApplicationException">Ha nem található a törlendő szerepkör.</exception> | ||
391 | + public static void Remove(string name) | ||
392 | + { | ||
393 | + var row = MembershipDBContext.RoleGroups.FirstOrDefault(x => x.Name == name); | ||
394 | + if (row == null) { Remove(-1); } | ||
395 | + else { Remove(row.Id); } | ||
396 | + } | ||
397 | + #endregion Remove methods | ||
398 | + } | ||
399 | + #endregion RoleGroups | ||
400 | + #region Assign | ||
401 | + public static class Assign | ||
402 | + { | ||
403 | + #region RemoveOfUser | ||
404 | + public static void RemoveOfUser(string username) | ||
405 | + { | ||
406 | + if (string.IsNullOrWhiteSpace(username)) { throw new Exception("Username can not be empty!"); } | ||
407 | + var user = MembershipDBContext.Users.FirstOrDefault(u => u.UserName == username); | ||
408 | + if (user==null) { throw new Exception($"User '{username}' does not exist!"); } | ||
409 | + var rguasslist = MembershipDBContext.RoleGroupUsers.Where(rg => rg.UserId == user.UserId); | ||
410 | + if (rguasslist == null || !rguasslist.Any()) { return; } | ||
411 | + foreach (var rguass in rguasslist) { MembershipDBContext.RoleGroupUsers.Remove(rguass); } | ||
412 | + } | ||
413 | + #endregion RemoveOfUser | ||
414 | + #region RolesToUser public method | ||
415 | + /// <summary> | ||
416 | + /// Role-RoleGroup-User összerendelések | ||
417 | + /// </summary> | ||
418 | + /// <param name="mode">az összerendelés módját határozza meg</param> | ||
419 | + /// <param name="rolenamecommalist">ezeket kell összerendelni...</param> | ||
420 | + /// <param name="usernamecommalist">...ezekkel</param> | ||
421 | + /// <returns></returns> | ||
422 | + public static VRH.Common.ReturnInfoJSON RolesToUser(string rolenamecommalist, string usernamecommalist) | ||
423 | + { | ||
424 | + DAL.RoleGroup urg; | ||
425 | + ReturnInfoJSON result = new ReturnInfoJSON() { ReturnMessage = "Assignment was successful!" }; | ||
426 | + try | ||
427 | + { | ||
428 | + if (m_roleProvider != null) { throw new Exception("RoleService is not enabled!"); } | ||
429 | + var rolenamelist = rolenamecommalist != null ? new List<string>(rolenamecommalist.Split(',')) : new List<string>(); | ||
430 | + var usernamelist = usernamecommalist != null ? new List<string>(usernamecommalist.Split(',')) : new List<string>(); | ||
431 | + foreach (var rolename in rolenamelist) | ||
432 | + { | ||
433 | + CheckRoleExists(rolename); | ||
434 | + foreach (var username in usernamelist) | ||
435 | + { | ||
436 | + CheckUsersExists(username); | ||
437 | + if (!Users.IsInRole(username, rolename)) { Roles.AddUserToRole(username, rolename); } | ||
438 | + } | ||
439 | + } | ||
440 | + } | ||
441 | + catch (Exception ex) | ||
442 | + { | ||
443 | + result.ReturnValue = -1; | ||
444 | + result.ReturnMessage = ex.Message; | ||
445 | + } | ||
446 | + return result; | ||
447 | + } | ||
448 | + #endregion RolesToUser public method | ||
449 | + #region RolesToRoleGroups public method | ||
450 | + public static VRH.Common.ReturnInfoJSON RolesToRoleGroups(string rolenamecommalist, string rolegroupnamecommalist) | ||
451 | + { | ||
452 | + DAL.RoleGroup urg; | ||
453 | + ReturnInfoJSON result = new ReturnInfoJSON() { ReturnMessage = "Assignment was successful!" }; | ||
454 | + try | ||
455 | + { | ||
456 | + if (m_roleProvider != null) { throw new Exception("RoleService is not enabled!"); } | ||
457 | + var rolenamelist = rolenamecommalist != null ? new List<string>(rolenamecommalist.Split(',')) : new List<string>(); | ||
458 | + var rolegroupnamelist = rolegroupnamecommalist != null ? new List<string>(rolegroupnamecommalist.Split(',')) : new List<string>(); | ||
459 | + foreach (var rolename in rolenamelist) | ||
460 | + { | ||
461 | + CheckRoleExists(rolename); | ||
462 | + foreach (var rolegroupname in rolegroupnamelist) | ||
463 | + { | ||
464 | + CheckRoleGroupExists(rolegroupname); | ||
465 | + DAL.Role role = MembershipDBContext.Roles.FirstOrDefault(x => x.RoleName == rolename); | ||
466 | + urg = MembershipDBContext.RoleGroups.FirstOrDefault(x => x.Name == rolegroupname); | ||
467 | + if (role != null && urg != null) | ||
468 | + { | ||
469 | + if (!urg.Roles.Any(x => x.Role.RoleName == rolename)) | ||
470 | + { | ||
471 | + urg.Roles.Add(new DAL.RoleGroupRole { Role = role }); | ||
472 | + MembershipDBContext.SaveChanges(); | ||
473 | + UpdateUsersForUserRoleGroup(urg.Id); | ||
474 | + } | ||
475 | + } | ||
476 | + } | ||
477 | + } | ||
478 | + } | ||
479 | + catch (Exception ex) | ||
480 | + { | ||
481 | + result.ReturnValue = -1; | ||
482 | + result.ReturnMessage = ex.Message; | ||
483 | + } | ||
484 | + return result; | ||
485 | + } | ||
486 | + #endregion RolesToRoleGroups public method | ||
487 | + #region RoleGroupsToUsers public method | ||
488 | + public static VRH.Common.ReturnInfoJSON RoleGroupsToUsers(string rolegroupnamecommalist, string usernamecommalist) | ||
489 | + { | ||
490 | + DAL.RoleGroup urg; | ||
491 | + ReturnInfoJSON result = new ReturnInfoJSON() { ReturnMessage = "Assignment was successful!" }; | ||
492 | + try | ||
493 | + { | ||
494 | + if (m_roleProvider != null) { throw new Exception("RoleService is not enabled!"); } | ||
495 | + var rolegroupnamelist = rolegroupnamecommalist != null ? new List<string>(rolegroupnamecommalist.Split(',')) : new List<string>(); | ||
496 | + var usernamelist = usernamecommalist != null ? new List<string>(usernamecommalist.Split(',')) : new List<string>(); | ||
497 | + foreach (var rolegroupname in rolegroupnamelist) | ||
498 | + { | ||
499 | + CheckRoleGroupExists(rolegroupname); | ||
500 | + foreach (var username in usernamelist) | ||
501 | + { | ||
502 | + CheckUsersExists(username); | ||
503 | + Guid userId = Guid.Empty; | ||
504 | + if (Guid.TryParse(Users.Get(username).ProviderUserKey.ToString(), out userId)) | ||
505 | + { | ||
506 | + urg = MembershipDBContext.RoleGroups.FirstOrDefault(x => x.Name == rolegroupname); | ||
507 | + DAL.User u = MembershipDBContext.Users.FirstOrDefault(x => x.UserId == userId); | ||
508 | + if (u != null && urg != null) | ||
509 | + { | ||
510 | + if (!urg.Users.Any(x => x.UserId == userId)) | ||
511 | + { | ||
512 | + urg.Users.Add(new DAL.RoleGroupUser { User = u }); | ||
513 | + MembershipDBContext.SaveChanges(); | ||
514 | + UpdateRolesForUser(u.UserId); | ||
515 | + } | ||
516 | + } | ||
517 | + } | ||
518 | + } | ||
519 | + } | ||
520 | + } | ||
521 | + catch (Exception ex) | ||
522 | + { | ||
523 | + result.ReturnValue = -1; | ||
524 | + result.ReturnMessage = ex.Message; | ||
525 | + } | ||
526 | + return result; | ||
527 | + } | ||
528 | + #endregion RoleGroupsToUsers public method | ||
529 | + #region private CheckRoleGroupExists,CheckRoleExists,CheckUsersExists | ||
530 | + /// <summary> | ||
531 | + /// Ellenőrzi, van-e ilyen role group | ||
532 | + /// </summary> | ||
533 | + /// <param name="roleGroup">ellenőrizendő role group</param> | ||
534 | + private static void CheckRoleGroupExists(string roleGroup) | ||
535 | + { | ||
536 | + if (!MembershipDBContext.RoleGroups.Any(x => x.Name == roleGroup)) { throw new Exception($"RoleGroup {roleGroup} does not exist!"); } | ||
537 | + } | ||
538 | + /// <summary> | ||
539 | + /// Ellenőrzi, van-e ilyen role | ||
540 | + /// </summary> | ||
541 | + /// <param name="role">az ellenőrizendő role</param> | ||
542 | + private static void CheckRoleExists(string role) | ||
543 | + { | ||
544 | + if (!System.Web.Security.Roles.GetAllRoles().ToList().ConvertAll(r => r.ToUpper()).Contains(role.ToUpper())) | ||
545 | + { | ||
546 | + throw new Exception($"Role {role} does not exist!"); | ||
547 | + } | ||
548 | + } | ||
549 | + /// <summary> | ||
550 | + /// Ellenőrzi van-e ilyen usernevű user | ||
551 | + /// </summary> | ||
552 | + /// <param name="userName">Ellenőrizendő user userneve</param> | ||
553 | + private static void CheckUsersExists(string userName) | ||
554 | + { | ||
555 | + bool exists = false; | ||
556 | + foreach (MembershipUser user in System.Web.Security.Membership.GetAllUsers()) | ||
557 | + { | ||
558 | + if (user.UserName.ToUpper() == userName.ToUpper()) { exists = true; break; } | ||
559 | + } | ||
560 | + if (!exists) { throw new Exception($"User {userName} does not exist!"); } | ||
561 | + } | ||
562 | + #endregion private CheckRoleGroupExists,CheckRoleExists,CheckUsersExists | ||
563 | + | ||
564 | + #region private UpdateRolesForUser | ||
565 | + /// <summary> | ||
566 | + /// Frissíti a megadott felhasználó szerepeit a felhasználó szerepkörei alapján | ||
567 | + /// </summary> | ||
568 | + /// <param name="userId">felhasználó UserID-ja</param> | ||
569 | + private static void UpdateRolesForUser(Guid userId) | ||
570 | + { | ||
571 | + MembershipUser user = System.Web.Security.Membership.GetUser(userId, false); | ||
572 | + if (user != null) | ||
573 | + { | ||
574 | + // eltávolítjuk az összes szerepkörét a felhasználónak, majd a felhasználóhoz tartozó UserRoleGroup-okban lévő Roles-okat adjuk hozzá a felhasználóhoz | ||
575 | + if (Roles.GetRolesForUser(user.UserName).Any()) | ||
576 | + { | ||
577 | + Roles.RemoveUserFromRoles(user.UserName, Roles.GetRolesForUser(user.UserName)); | ||
578 | + } | ||
579 | + foreach (DAL.RoleGroup urg in MembershipDBContext.RoleGroups.Where(x => x.Users.Any(y => y.UserId == userId))) | ||
580 | + { | ||
581 | + foreach (string roleName in urg.Roles.Select(x => x.Role.RoleName)) | ||
582 | + { | ||
583 | + if (!Roles.IsUserInRole(user.UserName, roleName)) | ||
584 | + { | ||
585 | + Roles.AddUserToRole(user.UserName, roleName); | ||
586 | + } | ||
587 | + } | ||
588 | + } | ||
589 | + } | ||
590 | + } | ||
591 | + #endregion private UpdateRolesForUser | ||
592 | + #region private UpdateUsersForUserRoleGroup | ||
593 | + /// <summary> | ||
594 | + /// Frissíti a megadott szerepkörhöz tartozó felhasználók szerepeit a szerepkörök alapján | ||
595 | + /// </summary> | ||
596 | + /// <param name="userRoleGroupId">UserRoleGroup Id-ja</param> | ||
597 | + private static void UpdateUsersForUserRoleGroup(int userRoleGroupId) | ||
598 | + { | ||
599 | + DAL.RoleGroup urg = MembershipDBContext.RoleGroups.SingleOrDefault(x => x.Id == userRoleGroupId); | ||
600 | + if (urg != null) | ||
601 | + { | ||
602 | + foreach (Guid userId in urg.Users.Select(x => x.UserId)) | ||
603 | + { | ||
604 | + UpdateRolesForUser(userId); | ||
605 | + } | ||
606 | + } | ||
607 | + } | ||
608 | + #endregion private UpdateUsersForUserRoleGroup | ||
609 | + } | ||
610 | + #endregion Assign | ||
611 | + #region DAL | ||
612 | + public static class DAL | ||
613 | + { | ||
614 | + #region tables | ||
615 | + #region table-User | ||
616 | + /// <summary> | ||
617 | + /// DefaultMembershipProvider által létrehozott User tábla. | ||
618 | + /// Ha változik az aktuális verzió, és emiatt a tábla szerkezete, akkor ezt módosítani kell. | ||
619 | + /// </summary> | ||
620 | + [Table("Users", Schema = "dbo")] | ||
621 | + public partial class User | ||
622 | + { | ||
623 | + /// <summary> | ||
624 | + /// Felhasználó egyedi azonosítója. | ||
625 | + /// </summary> | ||
626 | + [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] | ||
627 | + public Guid UserId { get; set; } | ||
628 | + | ||
629 | + /// <summary> | ||
630 | + /// Melyik alkalmazás felhasználója. | ||
631 | + /// </summary> | ||
632 | + public Guid ApplicationId { get; set; } | ||
633 | + | ||
634 | + /// <summary> | ||
635 | + /// Felhasználó neve. | ||
636 | + /// </summary> | ||
637 | + [Required, MaxLength(50)] | ||
638 | + public string UserName { get; set; } | ||
639 | + | ||
640 | + /// <summary> | ||
641 | + /// Felhasználó névtelenül bejelentjezhet-e. | ||
642 | + /// </summary> | ||
643 | + public bool IsAnonymous { get; set; } | ||
644 | + | ||
645 | + /// <summary> | ||
646 | + /// Felhasználó utolsó aktivitésénak időpontja. | ||
647 | + /// </summary> | ||
648 | + public DateTime LastActivityDate { get; set; } | ||
649 | + | ||
650 | + #region Virtual Collections | ||
651 | + | ||
652 | + /// <summary> | ||
653 | + /// A felhasználó szerepkörei. | ||
654 | + /// </summary> | ||
655 | + public virtual ICollection<RoleGroupUser> UserRoleGroupUsers { get; set; } | ||
656 | + | ||
657 | + #endregion Virtual Collections | ||
658 | + | ||
659 | + } | ||
660 | + #endregion table-User | ||
661 | + #region table-RoleGroupUser | ||
662 | + /// <summary> | ||
663 | + /// Szerepkörök és felhasználók összerendelése. | ||
664 | + /// </summary> | ||
665 | + [Table(nameof(MembershipContext.RoleGroupUsers), Schema = Constants.SCHEMA_NAME)] | ||
666 | + public partial class RoleGroupUser | ||
667 | + { | ||
668 | + /// <summary> | ||
669 | + /// Szerepkör egyedi azonosítója. | ||
670 | + /// </summary> | ||
671 | + [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.None)] | ||
672 | + public int RoleGroupId { get; set; } | ||
673 | + | ||
674 | + /// <summary> | ||
675 | + /// Felhasználó egyedi azonosítója. | ||
676 | + /// </summary> | ||
677 | + [Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.None)] | ||
678 | + public Guid UserId { get; set; } | ||
679 | + | ||
680 | + #region Virtual foreignkeys | ||
681 | + | ||
682 | + [ForeignKey(nameof(RoleGroupId))] | ||
683 | + public virtual RoleGroup RoleGroup { get; set; } | ||
684 | + | ||
685 | + [ForeignKey(nameof(UserId))] | ||
686 | + public virtual User User { get; set; } | ||
687 | + | ||
688 | + #endregion Virtual foreignkeys | ||
689 | + } | ||
690 | + #endregion table-RoleGroupUser | ||
691 | + #region table-RoleGroupRole | ||
692 | + /// <summary> | ||
693 | + /// Szerepkörök és szerepek összerendelése. | ||
694 | + /// </summary> | ||
695 | + [Table(nameof(MembershipContext.RoleGroupRoles), Schema = Constants.SCHEMA_NAME)] | ||
696 | + public partial class RoleGroupRole | ||
697 | + { | ||
698 | + /// <summary> | ||
699 | + /// Szerepkör egyedi azonosítója. | ||
700 | + /// </summary> | ||
701 | + [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.None)] | ||
702 | + public int RoleGroupId { get; set; } | ||
703 | + | ||
704 | + /// <summary> | ||
705 | + /// Szerep egyedi azonosítója. | ||
706 | + /// </summary> | ||
707 | + [Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.None)] | ||
708 | + public Guid RoleId { get; set; } | ||
709 | + | ||
710 | + #region Virtual foreignkeys | ||
711 | + | ||
712 | + [ForeignKey(nameof(RoleGroupId))] | ||
713 | + public virtual RoleGroup RoleGroup { get; set; } | ||
714 | + | ||
715 | + [ForeignKey(nameof(RoleId))] | ||
716 | + public virtual Role Role { get; set; } | ||
717 | + | ||
718 | + #endregion Virtual foreignkeys | ||
719 | + } | ||
720 | + #endregion table-RoleGroupRole | ||
721 | + #region table-RoleGroup | ||
722 | + /// <summary> | ||
723 | + /// Szerepkörök táblázata. | ||
724 | + /// </summary> | ||
725 | + [Table(nameof(MembershipContext.RoleGroups), Schema = Constants.SCHEMA_NAME)] | ||
726 | + public partial class RoleGroup | ||
727 | + { | ||
728 | + #region Properties | ||
729 | + | ||
730 | + /// <summary> | ||
731 | + /// Szerepkör egyedi azonosítója. | ||
732 | + /// </summary> | ||
733 | + [Key] | ||
734 | + public int Id { get; set; } | ||
735 | + | ||
736 | + /// <summary> | ||
737 | + /// Szerepkör egyedi megnevezése. | ||
738 | + /// </summary> | ||
739 | + [Required, MaxLength(256), Index(IsUnique = true)] | ||
740 | + public string Name { get; set; } | ||
741 | + | ||
742 | + #endregion Properties | ||
743 | + | ||
744 | + #region Virtual Collections | ||
745 | + | ||
746 | + /// <summary> | ||
747 | + /// A szerepkörhöz ezek a szerepek tartoznak. | ||
748 | + /// </summary> | ||
749 | + public virtual ICollection<RoleGroupRole> Roles { get; set; } | ||
750 | + | ||
751 | + /// <summary> | ||
752 | + /// A szerepkörhöz ezek a felhasználók tartoznak. | ||
753 | + /// </summary> | ||
754 | + public virtual ICollection<RoleGroupUser> Users { get; set; } | ||
755 | + | ||
756 | + #endregion Virtual Collections | ||
757 | + | ||
758 | + #region Constructor | ||
759 | + public RoleGroup() | ||
760 | + { | ||
761 | + Roles = new HashSet<RoleGroupRole>(); | ||
762 | + Users = new HashSet<RoleGroupUser>(); | ||
763 | + } | ||
764 | + #endregion Constructor | ||
765 | + } | ||
766 | + #endregion table-RoleGroup | ||
767 | + #region table-Role | ||
768 | + /// <summary> | ||
769 | + /// DefaultMembershipProvider által létrehozott User tábla. | ||
770 | + /// </summary> | ||
771 | + [Table("Roles", Schema = "dbo")] | ||
772 | + public partial class Role | ||
773 | + { | ||
774 | + /// <summary> | ||
775 | + /// Szerep egyedi azonosítója. | ||
776 | + /// </summary> | ||
777 | + [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] | ||
778 | + public Guid RoleId { get; set; } | ||
779 | + | ||
780 | + /// <summary> | ||
781 | + /// Melyik alkalmazás szerepe. | ||
782 | + /// </summary> | ||
783 | + public Guid ApplicationId { get; set; } | ||
784 | + | ||
785 | + /// <summary> | ||
786 | + /// Szerep neve. | ||
787 | + /// </summary> | ||
788 | + [Required, MaxLength(256)] | ||
789 | + public string RoleName { get; set; } | ||
790 | + | ||
791 | + /// <summary> | ||
792 | + /// Alkalmazás rövid leírása. | ||
793 | + /// </summary> | ||
794 | + [MaxLength(256)] | ||
795 | + public string Description { get; set; } | ||
796 | + } | ||
797 | + #endregion table-Role | ||
798 | + #region table-SecondaryFunction | ||
799 | + /// <summary> | ||
800 | + /// Lehetséges funkciókat tartalmazó táblázat, mely funkciókhoz | ||
801 | + /// tartozhat a másodlagos felhasználó. | ||
802 | + /// </summary> | ||
803 | + [Table(nameof(MembershipContext.SecondaryFunctions), Schema = Constants.SCHEMA_NAME)] | ||
804 | + public partial class SecondaryFunction | ||
805 | + { | ||
806 | + #region Properties | ||
807 | + | ||
808 | + /// <summary> | ||
809 | + /// A funkció egyedi azonosítója. | ||
810 | + /// </summary> | ||
811 | + [Key] | ||
812 | + public int Id { get; set; } | ||
813 | + | ||
814 | + /// <summary> | ||
815 | + /// A funkció egyedi megnevezése. | ||
816 | + /// </summary> | ||
817 | + [Required, MaxLength(30), Index(IsUnique = true)] | ||
818 | + public string Name { get; set; } | ||
819 | + | ||
820 | + #endregion Properties | ||
821 | + | ||
822 | + #region Virtual Collections | ||
823 | + | ||
824 | + /// <summary> | ||
825 | + /// A funkcióhoz ezek a másodlagos felhasználók tartoznak tartoznak. | ||
826 | + /// </summary> | ||
827 | + public virtual ICollection<SecondaryUser> SecondaryUsers { get; set; } | ||
828 | + | ||
829 | + #endregion Virtual Collections | ||
830 | + | ||
831 | + #region Constructor | ||
832 | + public SecondaryFunction() | ||
833 | + { | ||
834 | + SecondaryUsers = new HashSet<SecondaryUser>(); | ||
835 | + } | ||
836 | + #endregion Constructor | ||
837 | + } | ||
838 | + #endregion table-SecondaryFunction | ||
839 | + #region table-SecondaryUser | ||
840 | + /// <summary> | ||
841 | + /// Másodlagos felhasználók adatait tartalmazó táblázat. | ||
842 | + /// </summary> | ||
843 | + [Table(nameof(MembershipContext.SecondaryUsers), Schema = Constants.SCHEMA_NAME)] | ||
844 | + public partial class SecondaryUser | ||
845 | + { | ||
846 | + private const string INDEX_FUNCTION_NAME = "IX_SecondaryUser_SecondaryFunctionId_Name"; | ||
847 | + | ||
848 | + #region Properties | ||
849 | + | ||
850 | + /// <summary> | ||
851 | + /// Másodlagos felhasználó belső egyedi azonosítója. | ||
852 | + /// </summary> | ||
853 | + [Key, Index(IsClustered = false)] | ||
854 | + public int Id { get; set; } | ||
855 | + | ||
856 | + /// <summary> | ||
857 | + /// Az elsődleges felhasználó egyedi azonosítója a dbo.Users táblából. | ||
858 | + /// Ő hozzá tartozik a másodlagos felhasználó. | ||
859 | + /// </summary> | ||
860 | + public Guid UserId { get; set; } | ||
861 | + | ||
862 | + /// <summary> | ||
863 | + /// Melyik funkcióhoz tartozik a másodlagos felhasználó. | ||
864 | + /// </summary> | ||
865 | + [Index(INDEX_FUNCTION_NAME, 1, IsUnique = true, IsClustered = true)] | ||
866 | + public int SecondaryFunctionId { get; set; } | ||
867 | + | ||
868 | + /// <summary> | ||
869 | + /// Másodlagos felhasználó neve. | ||
870 | + /// </summary> | ||
871 | + [Required, MaxLength(255)] | ||
872 | + [Index(INDEX_FUNCTION_NAME, 2, IsUnique = true, IsClustered = true)] | ||
873 | + public string Name { get; set; } | ||
874 | + | ||
875 | + /// <summary> | ||
876 | + /// Másodlagos felhasználó jelszava. | ||
877 | + /// </summary> | ||
878 | + [MaxLength(255)] | ||
879 | + public string Password { get; set; } | ||
880 | + | ||
881 | + /// <summary> | ||
882 | + /// Másodlagos felhasználó érvényes-e jelenleg. | ||
883 | + /// </summary> | ||
884 | + public bool Active { get; set; } = true; | ||
885 | + | ||
886 | + #endregion Properties | ||
887 | + | ||
888 | + #region Virtual foreignkeys | ||
889 | + | ||
890 | + /// <summary> | ||
891 | + /// A másodlagos felhasználó ehhez az elsődleges felhasználóhoz tartozik. | ||
892 | + /// </summary> | ||
893 | + [ForeignKey(nameof(UserId))] | ||
894 | + public virtual User User { get; set; } | ||
895 | + | ||
896 | + /// <summary> | ||
897 | + /// A másodlagos felhasználó ehhez a funkcióhoz tartozik. | ||
898 | + /// </summary> | ||
899 | + [ForeignKey(nameof(SecondaryFunctionId))] | ||
900 | + public virtual SecondaryFunction SecondaryFunction { get; set; } | ||
901 | + | ||
902 | + #endregion Virtual foreignkeys | ||
903 | + | ||
904 | + #region Constructor | ||
905 | + public SecondaryUser() | ||
906 | + { | ||
907 | + } | ||
908 | + #endregion Constructor | ||
909 | + | ||
910 | + public override string ToString() | ||
911 | + { | ||
912 | + return String.Concat("{", | ||
913 | + nameof(Id), "=", this.Id.ToString(), "; ", | ||
914 | + nameof(UserId), "=", this.UserId, "; ", | ||
915 | + nameof(SecondaryFunctionId), "=", this.SecondaryFunctionId.ToString(), "; ", | ||
916 | + nameof(Name), "=", this.Name, "; ", | ||
917 | + nameof(Password), "=", this.Password, "; ", | ||
918 | + nameof(Active), "=", this.Active.ToString(), | ||
919 | + "}" | ||
920 | + ); | ||
921 | + } | ||
922 | + } | ||
923 | + #endregion table-SecondaryUser | ||
924 | + #region table-SecondaryLogin | ||
925 | + /// <summary> | ||
926 | + /// Másodlagos felhasználók bejelentkezéseit nyilvántartó táblázat. | ||
927 | + /// Egy másodlagos felhasználónak egy bejelentkezése tartozhat egy célhoz. | ||
928 | + /// Vagyis a UserID+TargetId együtt egyedi kulcsot alkot. | ||
929 | + /// </summary> | ||
930 | + [Table(nameof(MembershipContext.SecondaryLogins), Schema = Constants.SCHEMA_NAME)] | ||
931 | + public partial class SecondaryLogin | ||
932 | + { | ||
933 | + private const string INDEX_USER_TARGET = "IX_SecondaryLogin_UserId_TargetKey"; | ||
934 | + | ||
935 | + #region Properties | ||
936 | + | ||
937 | + /// <summary> | ||
938 | + /// A bejelentkezés belső egyedi azonosítója. | ||
939 | + /// </summary> | ||
940 | + [Key] | ||
941 | + public int Id { get; set; } | ||
942 | + | ||
943 | + /// <summary> | ||
944 | + /// Másodlagos felhasználó azonosítója, akinek a nevében történt a bejelentkezés. | ||
945 | + /// </summary> | ||
946 | + [Index(INDEX_USER_TARGET, 1, IsUnique = true)] | ||
947 | + public int SecondaryUserId { get; set; } | ||
948 | + | ||
949 | + /// <summary> | ||
950 | + /// A bejelentkezéshez tartozó azonosító. Értelmezése: | ||
951 | + /// Mi célból történt a bejelentkezés? | ||
952 | + /// </summary> | ||
953 | + [MaxLength(20), Index(INDEX_USER_TARGET, 2, IsUnique = true)] | ||
954 | + public string TargetKey { get; set; } | ||
955 | + | ||
956 | + /// <summary> | ||
957 | + /// Bejelentkezés időpontja. | ||
958 | + /// </summary> | ||
959 | + public DateTime LoginTime { get; set; } | ||
960 | + | ||
961 | + /// <summary> | ||
962 | + /// A legutóbbi aktivitás időpontja. | ||
963 | + /// </summary> | ||
964 | + public DateTime LastActivityTime { get; set; } | ||
965 | + | ||
966 | + #endregion Properties | ||
967 | + | ||
968 | + #region Virtual foreignkeys | ||
969 | + | ||
970 | + /// <summary> | ||
971 | + /// A másodlagos felhasználóra mutató tulajdonság. | ||
972 | + /// </summary> | ||
973 | + [ForeignKey(nameof(SecondaryUserId))] | ||
974 | + public virtual SecondaryUser SecondaryUser { get; set; } | ||
975 | + | ||
976 | + #endregion Virtual foreignkeys | ||
977 | + | ||
978 | + public override string ToString() | ||
979 | + { | ||
980 | + return String.Concat("{", | ||
981 | + nameof(Id), "=", this.Id.ToString(), "; ", | ||
982 | + nameof(SecondaryUserId), "=", this.SecondaryUserId.ToString(), "; ", | ||
983 | + nameof(DAL.SecondaryUser.Name), "=", this.SecondaryUser.Name, "; ", | ||
984 | + nameof(TargetKey), "=", this.TargetKey ?? "null", "; ", | ||
985 | + nameof(LoginTime), "=", this.LoginTime.ToString("G"), "; ", | ||
986 | + nameof(LastActivityTime), "=", this.LastActivityTime.ToString("G"), | ||
987 | + "}" | ||
988 | + ); | ||
989 | + } | ||
990 | + | ||
991 | + } | ||
992 | + #endregion table-SecondaryLogin | ||
993 | + #region table-UserSupplement | ||
994 | + /// <summary> | ||
995 | + /// A DefaultMembershipProvider 'User' táblájában nem szabad változtatásokat eszközölni | ||
996 | + /// a jövőbeni esetleges Microsoft fejlesztések miatt. | ||
997 | + /// Ez a tábla arra való, hogy a felhasználóra vonatkozó egyéb kiegészítő adatokat | ||
998 | + /// legyen hol tárolni. | ||
999 | + /// </summary> | ||
1000 | + /// <remarks> | ||
1001 | + /// Ha nincsenek a felhasználónak kiegészítő adatai akkor nem lesz itt rekordja. | ||
1002 | + /// </remarks> | ||
1003 | + [Table(nameof(MembershipContext.UserSupplements), Schema = Constants.SCHEMA_NAME)] | ||
1004 | + public partial class UserSupplement | ||
1005 | + { | ||
1006 | + #region Properties | ||
1007 | + | ||
1008 | + /// <summary> | ||
1009 | + /// A felhasználó egyedi azonosítója a 'User' táblából. | ||
1010 | + /// Itt is csak 1 db azonosító lehet. | ||
1011 | + /// </summary> | ||
1012 | + [Key, DatabaseGenerated(DatabaseGeneratedOption.None)] | ||
1013 | + public Guid UserId { get; set; } | ||
1014 | + | ||
1015 | + /// <summary> | ||
1016 | + /// Annak jelzése, hogy a felhasználó ideiglenesen létrehozott felhasználó. | ||
1017 | + /// Ha igaz, akkor ideiglenes, egyébként hamis. Ha nem létezik a felhasználónak | ||
1018 | + /// itt rekordja, akkor nem ideiglenes felhasználó. | ||
1019 | + /// Alapértelmezett érték: true. | ||
1020 | + /// </summary> | ||
1021 | + public bool IsTemporary { get; set; } = true; | ||
1022 | + | ||
1023 | + #endregion Properties | ||
1024 | + | ||
1025 | + #region Virtual foreignkeys | ||
1026 | + | ||
1027 | + [ForeignKey(nameof(UserId))] | ||
1028 | + public virtual User User { get; set; } | ||
1029 | + | ||
1030 | + #endregion Virtual foreignkeys | ||
1031 | + } | ||
1032 | + #endregion table-UserSupplement | ||
1033 | + #endregion tables | ||
1034 | + | ||
1035 | + #region MembershipContext | ||
1036 | + public class MembershipContext : DbContext | ||
1037 | + { | ||
1038 | + #region Constructors | ||
1039 | + // Your context has been configured to use a 'VrhWebMembership' connection string from your application's | ||
1040 | + // configuration file (App.config or Web.config). | ||
1041 | + public MembershipContext(string sqlcs) : base(sqlcs) | ||
1042 | + { | ||
1043 | + } | ||
1044 | + #endregion Constructors | ||
1045 | + | ||
1046 | + #region DbSets | ||
1047 | + | ||
1048 | + #region !!! A migrációból kivett két tábla. Ezeket a DefaultMembershipProvider kezeli és hozza létre. !!! | ||
1049 | + public virtual DbSet<Role> Roles { get; set; } | ||
1050 | + public virtual DbSet<User> Users { get; set; } | ||
1051 | + #endregion !!! A migrációból kivett két tábla. Ezeket a DefaultMembershipProvider kezeli és hozza létre. !!! | ||
1052 | + | ||
1053 | + // Saját táblák, melyek a Global.SCHEMA_NAME állandó szerinti sémában vannak. | ||
1054 | + public virtual DbSet<RoleGroup> RoleGroups { get; set; } | ||
1055 | + public virtual DbSet<RoleGroupRole> RoleGroupRoles { get; set; } | ||
1056 | + public virtual DbSet<RoleGroupUser> RoleGroupUsers { get; set; } | ||
1057 | + public virtual DbSet<SecondaryFunction> SecondaryFunctions { get; set; } | ||
1058 | + public virtual DbSet<SecondaryLogin> SecondaryLogins { get; set; } | ||
1059 | + public virtual DbSet<SecondaryUser> SecondaryUsers { get; set; } | ||
1060 | + public virtual DbSet<UserSupplement> UserSupplements { get; set; } | ||
1061 | + #endregion DbSets | ||
1062 | + | ||
1063 | + #region OnModelCreating | ||
1064 | + protected override void OnModelCreating(DbModelBuilder modelBuilder) | ||
1065 | + { | ||
1066 | + //modelBuilder.HasDefaultSchema("GoodBill"); | ||
1067 | + | ||
1068 | + //WA20160124: Sajnos az EF a kötelező idegen kulcsnál alapértelmezésként cascadeDelete értékét true-ra állítja, | ||
1069 | + // ami sok esetben nem megfelelő (nem is értem, miért true a default :(( ) | ||
1070 | + // Ahol ez előfordul, ott a ForeignKey-eket itt kell definiálni. | ||
1071 | + // HasRequired = many oldal virtual property | ||
1072 | + // WithMany = ha a one oldalon lett definiálva ICollection a many-ra, akkor azt kell ide írni, egyébként üres | ||
1073 | + // HasForeignKey = many oldalon a foreign key mező | ||
1074 | + } | ||
1075 | + #endregion OnModelCreating | ||
1076 | + } | ||
1077 | + #endregion MembershipContext | ||
1078 | + } | ||
1079 | + #endregion DAL | ||
1080 | + } | ||
1081 | +} | ||
0 | \ No newline at end of file | 1082 | \ No newline at end of file |
Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - Tools.cs
1 | using System; | 1 | using System; |
2 | using System.IO; | 2 | using System.IO; |
3 | +using System.IO.Compression; | ||
3 | using System.Collections.Generic; | 4 | using System.Collections.Generic; |
4 | using System.Linq; | 5 | using System.Linq; |
5 | using System.Security.Principal; | 6 | using System.Security.Principal; |
6 | using System.Text; | 7 | using System.Text; |
8 | +using System.Text.RegularExpressions; | ||
7 | using System.Threading.Tasks; | 9 | using System.Threading.Tasks; |
8 | using System.Threading; | 10 | using System.Threading; |
9 | 11 | ||
@@ -13,11 +15,101 @@ using System.Diagnostics; | @@ -13,11 +15,101 @@ using System.Diagnostics; | ||
13 | 15 | ||
14 | using Vrh.XmlProcessing; | 16 | using Vrh.XmlProcessing; |
15 | using System.Xml.Linq; | 17 | using System.Xml.Linq; |
18 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
19 | +using VRH.Common; | ||
16 | 20 | ||
17 | -namespace Vrh.Log4Pro.MaintenanceConsole | 21 | +namespace Vrh.Log4Pro.MaintenanceConsole.ToolsNS |
18 | { | 22 | { |
23 | + public static class ZipTools | ||
24 | + { | ||
25 | + public static void Extract1stFileFromZIP(string targetfilefullpath, string ZIPfilefullpath) | ||
26 | + { | ||
27 | + if (File.Exists(targetfilefullpath)) { File.Delete(targetfilefullpath); } | ||
28 | + using (ZipArchive archive = ZipFile.Open(ZIPfilefullpath, ZipArchiveMode.Read)) | ||
29 | + { | ||
30 | + foreach (var zipentry in archive.Entries) | ||
31 | + { | ||
32 | + zipentry.ExtractToFile(targetfilefullpath); | ||
33 | + return; | ||
34 | + } | ||
35 | + } | ||
36 | + } | ||
37 | + public static void ExtractAllFileFromZIP(string targetdirectorypath, string ZIPfilefullpath) | ||
38 | + { | ||
39 | + if (!Directory.Exists(targetdirectorypath)) { Directory.CreateDirectory(targetdirectorypath); } | ||
40 | + using (ZipArchive archive = ZipFile.Open(ZIPfilefullpath, ZipArchiveMode.Read)) | ||
41 | + { | ||
42 | + foreach (var zipentry in archive.Entries) | ||
43 | + { | ||
44 | + zipentry.ExtractToFile(Path.Combine(targetdirectorypath, zipentry.FullName)); | ||
45 | + } | ||
46 | + } | ||
47 | + } | ||
48 | + | ||
49 | + public static void CreateEntriesFromDirectoryContent(string sourcefolderpath, string ZIPfilefullpath, string includefilenamemask, string includefullpathregex, bool removearchivedfiles = false,bool storepathinzip = true) | ||
50 | + { | ||
51 | + if (File.Exists(ZIPfilefullpath)) { File.Delete(ZIPfilefullpath); } | ||
52 | + DirectoryInfo di = new DirectoryInfo(sourcefolderpath); | ||
53 | + var rgx = new Regex(includefullpathregex??""); | ||
54 | + var archivedfiles = new List<string>(); | ||
55 | + using (ZipArchive archive = ZipFile.Open(ZIPfilefullpath, ZipArchiveMode.Create)) | ||
56 | + { | ||
57 | + ColorConsole.WriteLine($"ZIP-ping directory '{sourcefolderpath}'...", ConsoleColor.Yellow); | ||
58 | + FileInfo[] fis = di.GetFiles(includefilenamemask, SearchOption.AllDirectories); | ||
59 | + int maxfilefullpathlength = 0; | ||
60 | + int cpt = ColorConsole.CursorTop; | ||
61 | + int cpl = ColorConsole.CursorLeft; | ||
62 | + foreach (var fi in fis) | ||
63 | + { | ||
64 | + var entryname = storepathinzip | ||
65 | + ? fi.FullName.Substring((Path.GetPathRoot(fi.FullName)?.Length) ?? 0) | ||
66 | + : fi.Name; | ||
67 | + if (rgx.Match(fi.FullName).Success) | ||
68 | + { | ||
69 | + try | ||
70 | + { | ||
71 | + archive.CreateEntryFromFile(fi.FullName, entryname, CompressionLevel.Optimal); | ||
72 | + ColorConsole.Write(fi.FullName, ConsoleColor.Yellow); | ||
73 | + if (maxfilefullpathlength > fi.FullName.Length) | ||
74 | + { | ||
75 | + ColorConsole.Write(new string(' ', maxfilefullpathlength - fi.FullName.Length)); | ||
76 | + } | ||
77 | + else { maxfilefullpathlength = fi.FullName.Length; } | ||
78 | + ColorConsole.SetCursorPosition(cpl, cpt); | ||
79 | + archivedfiles.Add(fi.FullName); | ||
80 | + } | ||
81 | + catch (Exception ex) | ||
82 | + { | ||
83 | + ColorConsole.WriteLine($"Error when accessing/zipping file '{fi.FullName}'!", ConsoleColor.Red); | ||
84 | + ColorConsole.WriteLine(ex.Message, ConsoleColor.Red,prefix: "Exception message: ", bracket:"[]"); | ||
85 | + } | ||
86 | + } | ||
87 | + cpt = ColorConsole.CursorTop; | ||
88 | + cpl = ColorConsole.CursorLeft; | ||
89 | + } | ||
90 | + ColorConsole.Write(new string(' ', maxfilefullpathlength)); | ||
91 | + ColorConsole.SetCursorPosition(cpl, cpt); | ||
92 | + } | ||
93 | + if (removearchivedfiles) | ||
94 | + { | ||
95 | + archivedfiles.ForEach(x => File.Delete(x)); | ||
96 | + string[] dirs = System.IO.Directory.GetDirectories(sourcefolderpath); | ||
97 | + string[] files = System.IO.Directory.GetFiles(sourcefolderpath); | ||
98 | + if (dirs.Length + files.Length == 0) { Directory.Delete(sourcefolderpath); } | ||
99 | + } | ||
100 | + } | ||
101 | + } | ||
19 | public static class Tools | 102 | public static class Tools |
20 | { | 103 | { |
104 | + public static T GetPropertyValue<T>(object obj, string propName) { return (T)obj.GetType().GetProperty(propName).GetValue(obj, null); } | ||
105 | + | ||
106 | + public static Dictionary<K, V> Merge<K, V>(IEnumerable<Dictionary<K, V>> dictionaries) | ||
107 | + { | ||
108 | + return dictionaries.SelectMany(x => x) | ||
109 | + .GroupBy(d => d.Key) | ||
110 | + .ToDictionary(x => x.Key, y => y.First().Value); | ||
111 | + } | ||
112 | + | ||
21 | public static bool IsElevated | 113 | public static bool IsElevated |
22 | { | 114 | { |
23 | get | 115 | get |
@@ -72,5 +164,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -72,5 +164,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
72 | return outputBuilder.ToString(); | 164 | return outputBuilder.ToString(); |
73 | } | 165 | } |
74 | } | 166 | } |
167 | + | ||
168 | + public static string GetTemporaryFoldername(string directorypath) | ||
169 | + { | ||
170 | + return Path.Combine(directorypath, DateTime.Now.ToString($"TMP_yyyyMMddHHmmssfffffff")); | ||
171 | + } | ||
172 | + public static string GetTemporaryfilename(string directorypath, string extension) | ||
173 | + { | ||
174 | + if (extension == null) { extension = ".tmp"; } | ||
175 | + return Path.Combine(directorypath, DateTime.Now.ToString($"TMP_yyyyMMddHHmmssfffffff.{extension}")); | ||
176 | + } | ||
75 | } | 177 | } |
76 | } | 178 | } |
No preview for this file type
Vrh.Log4Pro.MaintenanceConsole/Manager - BackupPackageManager.cs
0 → 100644
@@ -0,0 +1,513 @@ | @@ -0,0 +1,513 @@ | ||
1 | +using System; | ||
2 | +using System.IO; | ||
3 | +using System.IO.Compression; | ||
4 | +using System.Configuration.Install; | ||
5 | +using System.Collections.Generic; | ||
6 | +using System.Linq; | ||
7 | +using System.ServiceProcess; | ||
8 | +using System.Text; | ||
9 | +using System.Threading; | ||
10 | +using System.Threading.Tasks; | ||
11 | + | ||
12 | +using Microsoft.Web.Administration; | ||
13 | +using System.Management; | ||
14 | +using System.Diagnostics; | ||
15 | + | ||
16 | +using Vrh.Log4Pro.MaintenanceConsole.MenuNS; | ||
17 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
18 | +using Vrh.Log4Pro.MaintenanceConsole.ToolsNS; | ||
19 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
20 | + | ||
21 | +using Vrh.XmlProcessing; | ||
22 | +using VRH.Common; | ||
23 | +using System.Xml.Linq; | ||
24 | +using System.Text.RegularExpressions; | ||
25 | + | ||
26 | +namespace Vrh.Log4Pro.MaintenanceConsole.BackupPackageManagerNS | ||
27 | +{ | ||
28 | + #region BackupPackageManager class | ||
29 | + public static class BackupPackageManager | ||
30 | + { | ||
31 | + private const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE_BACKUPMANAGER;"; | ||
32 | + private const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;element=BackupPackages;"; | ||
33 | + private const string PACKAGESELECTIONPROMPT = "Select the backup package(s) to manage with function '{0}'!"; | ||
34 | + | ||
35 | + #region Execute | ||
36 | + public static object Execute(object o1 = null, object o2 = null) | ||
37 | + { | ||
38 | + var args = (o1 as Menu.ExecutorParameter).Args; | ||
39 | + var functionkey = CommandLine.GetCommandLineArgument(args, CLP.CMD_FUNCTION); | ||
40 | + var config = new BackupPackageManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); | ||
41 | + var ep = new Menu.ExecutorParameter(config, args); | ||
42 | + | ||
43 | + var menufunctions = new Menu("Manage Backup Packages", "Select the management function!") | ||
44 | + .AddMenuItem(new Menu.Item(CLP.Module.BackupPackageManager.Functions.CreateBackupPackage.KEY, "Create backup package", CreateBackupPackage,ep)) | ||
45 | + .SetSelectionMode(Menu.SelectionMode.Single) | ||
46 | + .SetMenuHeaderDisplayer(BackupPackageListDisplayer); | ||
47 | + menufunctions.ExecuteMenu(functionkey); | ||
48 | + return o2; | ||
49 | + } | ||
50 | + #endregion Execute | ||
51 | + | ||
52 | + #region First level Executors with UI | ||
53 | + private static object CreateBackupPackage(object parameter, object o) | ||
54 | + { | ||
55 | + var config = (parameter as Menu.ExecutorParameter).GetConfig< BackupPackageManagerXmlProcessor>(); | ||
56 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
57 | + | ||
58 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.BackupPackageManager.Functions.CMD_PACKAGES); | ||
59 | + | ||
60 | + var menufolders = DisplayBackupPackageMenu(config, string.Format(PACKAGESELECTIONPROMPT,nameof(CreateBackupPackage)), silent:true); | ||
61 | + | ||
62 | + Menu.Selection sr = menufolders.Select(selectedtaskindexes); | ||
63 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
64 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
65 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
66 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
67 | + else { } | ||
68 | + | ||
69 | + var TS = DateTime.Now; | ||
70 | + foreach (var p in sr.SelectedParameterList) { OnePackageToCreate(p.Parameters as BackupPackage,TS); } | ||
71 | + return o; | ||
72 | + } | ||
73 | + private static void OnePackageToCreate(BackupPackage bp,DateTime? timestamp=null) | ||
74 | + { | ||
75 | + try | ||
76 | + { | ||
77 | + //packaget | ||
78 | + var packagets = (timestamp.HasValue ? timestamp.Value : DateTime.Now).ToString("yyyyMMddHHmmss"); | ||
79 | + var vars = new Dictionary<string, string>(); | ||
80 | + vars.Add("PACKAGENAME", bp.Xml_PackageName); | ||
81 | + vars.Add("PACKAGETS", packagets); | ||
82 | + | ||
83 | + var destinationfolder = Path.GetDirectoryName(bp.Xml_PackageFilePath); | ||
84 | + if (!Path.IsPathRooted(destinationfolder)) { destinationfolder = Path.Combine(Directory.GetCurrentDirectory(), destinationfolder); } | ||
85 | + if (!Directory.Exists(destinationfolder)) { Directory.CreateDirectory(destinationfolder); } | ||
86 | + | ||
87 | + var destinationfilename = Path.GetFileNameWithoutExtension(bp.Xml_PackageFilePath); | ||
88 | + //string tempfolderpath = Tools.GetTemporaryFoldername(destinationfolder); | ||
89 | + string tempfolderpath = StringConstructor.ResolveConstructor(vars, Path.Combine(destinationfolder,destinationfilename), "{}@@"); | ||
90 | + if (Directory.Exists(tempfolderpath)) { Directory.Delete(tempfolderpath, true); } | ||
91 | + | ||
92 | + if (!Directory.Exists(tempfolderpath)) { Directory.CreateDirectory(tempfolderpath); } | ||
93 | + | ||
94 | + foreach (var bf in bp.Xml_BackupFolderList) | ||
95 | + { | ||
96 | + BackupPackageManagerCore.FolderZipBackup(bf, tempfolderpath, vars); | ||
97 | + } | ||
98 | + foreach (var sqldb in bp.Xml_BackupSQLDataBaseList) | ||
99 | + { | ||
100 | + SQLDataBaseManagerNS.SQLDataBaseManager.Execute(sqldb.Xml_Key,sqldb.Xml_DBBackup,sqldb.Xml_ScriptBackup,sqldb.Xml_TableDataBackup, tempfolderpath, timestamp); | ||
101 | + } | ||
102 | + | ||
103 | + BackupPackageManagerCore.CreatePackageFile(bp, tempfolderpath, vars); | ||
104 | + if (Directory.Exists(tempfolderpath)) { Directory.Delete(tempfolderpath,true); } | ||
105 | + } | ||
106 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
107 | + } | ||
108 | + #endregion First level Executors with UI | ||
109 | + | ||
110 | + #region private methods | ||
111 | + #region private DisplayBackupPackages | ||
112 | + private static void BackupPackageListDisplayer() { DisplayBackupPackageMenu(); } | ||
113 | + private static Menu DisplayBackupPackageMenu(BackupPackageManagerXmlProcessor config=null, string prompt=null, bool silent=false) | ||
114 | + { | ||
115 | + if (config==null) { config = new BackupPackageManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); } | ||
116 | + List<BackupPackage> bfdefList = config.GetDefinitionList(); | ||
117 | + var menubp = new Menu("Backup packages",prompt) | ||
118 | + .SetMenuItemDisplayer(DisplayBackupPackageInfo) | ||
119 | + .SetSelectionMode(Menu.SelectionMode.Multi); | ||
120 | + menubp.ClearMenuItemList(); | ||
121 | + foreach (var bfdef in bfdefList) | ||
122 | + { | ||
123 | + var fi = CollectBackupPackageInfo(bfdef); | ||
124 | + menubp.AddMenuItem(new Menu.Item(bfdef.Xml_Key, null, null, new Menu.ExecutorParameter(pars:fi))); | ||
125 | + } | ||
126 | + if (!silent) { menubp.DisplayItems(1); } | ||
127 | + return menubp; | ||
128 | + } | ||
129 | + #endregion private DisplayBackupPackages | ||
130 | + | ||
131 | + #region private method: DisplayBackupPackageInfo | ||
132 | + private static object DisplayBackupPackageInfo(object obj, int lineix) | ||
133 | + { | ||
134 | + BackupPackage bp = ((obj as Menu.ExecutorParameter).Parameters as BackupPackage); | ||
135 | + if (lineix == 0) | ||
136 | + { | ||
137 | + ColorConsole.Write($"{bp.Xml_PackageName}", ConsoleColor.Black, ConsoleColor.White); | ||
138 | + ColorConsole.Write($"{bp.Xml_Description}", ConsoleColor.White,prefix:", "); | ||
139 | + ColorConsole.WriteLine(""); | ||
140 | + return " "; | ||
141 | + } | ||
142 | + if (lineix == 1) | ||
143 | + { | ||
144 | + ColorConsole.Write($"{bp.Xml_PackageFilePath}", ConsoleColor.White, prefix: "Package:"); | ||
145 | + ColorConsole.WriteLine(""); | ||
146 | + return " "; | ||
147 | + } | ||
148 | + if (lineix == 2) | ||
149 | + { | ||
150 | + ColorConsole.Write($"{bp.Xml_SourceIncludeFilenameMaskList}", ConsoleColor.White, prefix: "Mask:"); | ||
151 | + ColorConsole.Write($"{bp.SizePackageTotal}", ConsoleColor.White, prefix: ", Bytes to include:"); | ||
152 | + ColorConsole.WriteLine(""); | ||
153 | + return " "; | ||
154 | + } | ||
155 | + return null; | ||
156 | + } | ||
157 | + #endregion private method: DisplayBackupPackageInfo | ||
158 | + | ||
159 | + #region private CollectBackupPackageInfo | ||
160 | + private static BackupPackage CollectBackupPackageInfo(BackupPackage bp) | ||
161 | + { | ||
162 | + bp.SizePackageTotal= 0; | ||
163 | + foreach (var bf in bp.Xml_BackupFolderList) | ||
164 | + { | ||
165 | + bf.FolderExists = Directory.Exists(bf.Xml_Path); | ||
166 | + if (bf.FolderExists) | ||
167 | + { | ||
168 | + var di = new DirectoryInfo(bf.Xml_Path); | ||
169 | + bp.SizePackageTotal += Vrh.Log4Pro.MaintenanceConsole.FileCleanerManagerNS.FileCleanerManagerCore.DirSize(di, bf.Xml_IncludeFileNameMask, bf.Xml_IncludeFileFullPathRegex, recurse: true); | ||
170 | + } | ||
171 | + } | ||
172 | + return bp; | ||
173 | + } | ||
174 | + #endregion private CollectBackupPackageInfo | ||
175 | + #endregion private methods | ||
176 | + } | ||
177 | + #endregion BackupPackageManager class | ||
178 | + | ||
179 | + #region class BackupPackageManagerCore | ||
180 | + public static class BackupPackageManagerCore | ||
181 | + { | ||
182 | + /// <summary> | ||
183 | + /// Create zip package content file | ||
184 | + /// </summary> | ||
185 | + /// <param name="bf">BackupFolder descriptor</param> | ||
186 | + /// <param name="destinationfolderpath">the target directory path where the zip file is created</param> | ||
187 | + /// <param name="vars">filename substitution variables</param> | ||
188 | + public static void FolderZipBackup(BackupPackage.BackupFolder bf, string destinationfolderpath, Dictionary<string, string> vars) | ||
189 | + { | ||
190 | + string foldertobackuppath = bf.Xml_Path; | ||
191 | + | ||
192 | + string destinationbackupfile = bf.Xml_BackupToFile; | ||
193 | + if (string.IsNullOrEmpty(destinationbackupfile)) { destinationbackupfile = (new DirectoryInfo(foldertobackuppath)).Name + ".zip"; } | ||
194 | + string includefilenamemask = bf.Xml_IncludeFileNameMask; | ||
195 | + string includefullpathregex = bf.Xml_IncludeFileFullPathRegex; | ||
196 | + | ||
197 | + var destinationfile = Path.GetFileNameWithoutExtension(destinationbackupfile); | ||
198 | + var destinationext = Path.GetExtension(destinationbackupfile); if (string.IsNullOrWhiteSpace(destinationext)) { destinationext = ".zip"; } | ||
199 | + destinationbackupfile = Path.Combine(destinationfolderpath, destinationfile+destinationext); | ||
200 | + | ||
201 | + destinationbackupfile = VRH.Common.StringConstructor.ResolveConstructor(vars, destinationbackupfile, "{}@@"); | ||
202 | + | ||
203 | + if (File.Exists(destinationbackupfile)) { File.Delete(destinationbackupfile); } | ||
204 | + | ||
205 | + if (!Path.IsPathRooted(foldertobackuppath)) { foldertobackuppath = Path.Combine(Directory.GetCurrentDirectory(), foldertobackuppath); } | ||
206 | + ZipTools.CreateEntriesFromDirectoryContent(foldertobackuppath, destinationbackupfile, includefilenamemask,includefullpathregex); | ||
207 | + ColorConsole.WriteLine($"Folder backup created. Name:{foldertobackuppath}", ConsoleColor.DarkGreen); | ||
208 | + } | ||
209 | + /// <summary> | ||
210 | + /// Create package compressed file | ||
211 | + /// </summary> | ||
212 | + /// <param name="bp">package descriptor</param> | ||
213 | + /// <param name="sourcedirectorypath">source directory, where the package content files are located; | ||
214 | + /// the package file will be created with the same name with zip or exe extension in its parent directory</param> | ||
215 | + /// <param name="vars">substitution vars</param> | ||
216 | + public static void CreatePackageFile(BackupPackage bp,string sourcedirectorypath, Dictionary<string,string> vars) | ||
217 | + { | ||
218 | + string[] sourceincludefilenamemasklist = bp.Xml_SourceIncludeFilenameMaskList.Split(','); | ||
219 | + bool createselfextractor = bp.Xml_CreateExe; | ||
220 | + | ||
221 | + if (!Path.IsPathRooted(sourcedirectorypath)) { sourcedirectorypath = Path.Combine(Directory.GetCurrentDirectory(), sourcedirectorypath); } | ||
222 | + | ||
223 | + var destinationfolder = Path.GetDirectoryName(sourcedirectorypath); | ||
224 | + if (!Path.IsPathRooted(destinationfolder)) { destinationfolder = Path.Combine(Directory.GetCurrentDirectory(), destinationfolder); } | ||
225 | + var destinationfile = Path.GetFileNameWithoutExtension(sourcedirectorypath); | ||
226 | + | ||
227 | + string package___filepath = Path.Combine(destinationfolder, destinationfile); | ||
228 | + package___filepath=VRH.Common.StringConstructor.ResolveConstructor(vars, package___filepath, "{}@@"); | ||
229 | + | ||
230 | + string packageEXEfilepath = package___filepath + ".exe"; | ||
231 | + string packageZIPfilepath = package___filepath + ".zip"; | ||
232 | + if (File.Exists(packageEXEfilepath)) { File.Delete(packageEXEfilepath); } | ||
233 | + if (File.Exists(packageZIPfilepath)) { File.Delete(packageZIPfilepath); } | ||
234 | + | ||
235 | + List<string> includefilepathlist = new List<string>(); | ||
236 | + foreach (var includefilenamemask in sourceincludefilenamemasklist) { includefilepathlist.Add(Path.Combine(sourcedirectorypath, includefilenamemask)); } | ||
237 | + | ||
238 | + string includeliststr = String.Join(" ", includefilepathlist.ToArray()); | ||
239 | + string recursesubdirs = "-r"; | ||
240 | + string addfilecommand = "a"; | ||
241 | + string response; | ||
242 | + string packagefile; | ||
243 | + if (createselfextractor) | ||
244 | + { | ||
245 | + string archivetype_7z = "-t7z"; | ||
246 | + string createsfx = "-sfx"; | ||
247 | + packagefile = packageEXEfilepath; | ||
248 | + response = Tools.ExecuteAndGetStdIo("7z.exe", $"{addfilecommand} {packagefile} {includeliststr} {recursesubdirs} {archivetype_7z} {createsfx}"); | ||
249 | + } | ||
250 | + else | ||
251 | + { | ||
252 | + string archivetype_zip = "-tzip"; | ||
253 | + packagefile = packageZIPfilepath; | ||
254 | + response = Tools.ExecuteAndGetStdIo("7z.exe", $"{addfilecommand} {packagefile} {includeliststr} {recursesubdirs} {archivetype_zip}"); | ||
255 | + } | ||
256 | + ColorConsole.WriteLine($"Backup package created. Package name:{bp.Xml_PackageName}, package file: {packagefile}", ConsoleColor.Green); | ||
257 | + | ||
258 | + | ||
259 | + // 7 - Zip[64] 16.04 : Copyright(c) 1999 - 2016 Igor Pavlov : 2016 - 10 - 04 | ||
260 | + // | ||
261 | + // Usage: 7z<command>[< switches > ...] < archive_name > [< file_names > ...] [< @listfiles...>] | ||
262 | + // Sample: | ||
263 | + // 7z a -t7z -sfx __7zTESTTXT.EXE *.txt -- create __7zTESTTXT.EXE self extracting archive of all files of current directory with txt extension | ||
264 | + // 7z a -tzip __7zTESTTXT.ZIP *.txt -- create __7zTESTTXT.ZIP archive of all files of current directory with txt extension | ||
265 | + // | ||
266 | + // <Commands> | ||
267 | + // a : Add files to archive | ||
268 | + // b : Benchmark | ||
269 | + // d : Delete files from archive | ||
270 | + // e : Extract files from archive (without using directory names) | ||
271 | + // h : Calculate hash values for files | ||
272 | + // i : Show information about supported formats | ||
273 | + // l : List contents of archive | ||
274 | + // rn: Rename files in archive | ||
275 | + // t : Test integrity of archive | ||
276 | + // u : Update files to archive | ||
277 | + // x : eXtract files with full paths | ||
278 | + // | ||
279 | + // <Switches> | ||
280 | + // -- : Stop switches parsing | ||
281 | + // -ai[r[-| 0]]{ @listfile | !wildcard} : Include archives | ||
282 | + // -ax[r[-| 0]]{ @listfile | !wildcard} : eXclude archives | ||
283 | + // -ao{ a | s | t | u} : set Overwrite mode | ||
284 | + // -an : disable archive_name field | ||
285 | + // -bb[0 - 3] : set output log level | ||
286 | + // -bd : disable progress indicator | ||
287 | + // -bs{ o | e | p} { 0 | 1 | 2} : set output stream for output / error / progress line | ||
288 | + // -bt : show execution time statistics | ||
289 | + // -i[r[-| 0]]{ @listfile | !wildcard} : Include filenames | ||
290 | + // -m{ Parameters} : set compression Method | ||
291 | + // -mmt[N] : set number of CPU threads | ||
292 | + // -o{ Directory} : set Output directory | ||
293 | + // -p{ Password} : set Password | ||
294 | + // -r[-| 0] : Recurse subdirectories | ||
295 | + // -sa{ a | e | s} : set Archive name mode | ||
296 | + // -scc{ UTF - 8 | WIN | DOS} : set charset for for console input/ output | ||
297 | + // -scs{ UTF - 8 | UTF - 16LE | UTF - 16BE | WIN | DOS |{ id} } : set charset for list files | ||
298 | + // -scrc[CRC32 | CRC64 | SHA1 | SHA256 | *] : set hash function for x, e, h commands | ||
299 | + // -sdel : delete files after compression | ||
300 | + // -seml[.] : send archive by email | ||
301 | + // -sfx[{ name}] : Create SFX archive | ||
302 | + // -si[{ name}] : read data from stdin | ||
303 | + // -slp : set Large Pages mode | ||
304 | + // -slt : show technical information for l(List) command | ||
305 | + // -snh : store hard links as links | ||
306 | + // -snl : store symbolic links as links | ||
307 | + // -sni : store NT security information | ||
308 | + // -sns[-] : store NTFS alternate streams | ||
309 | + // -so : write data to stdout | ||
310 | + // -spd : disable wildcard matching for file names | ||
311 | + // -spe : eliminate duplication of root folder for extract command | ||
312 | + // -spf : use fully qualified file paths | ||
313 | + // -ssc[-] : set sensitive case mode | ||
314 | + // -ssw : compress shared files | ||
315 | + // -stl : set archive timestamp from the most recently modified file | ||
316 | + // -stm{HexMask} : set CPU thread affinity mask(hexadecimal number) | ||
317 | + // -stx{Type} : exclude archive type | ||
318 | + // -t{Type} : Set type of archive | ||
319 | + // -u[-][p#][q#][r#][x#][y#][z#][!newArchiveName] : Update options | ||
320 | + // -v{ Size} [b| k | m | g] : Create volumes | ||
321 | + // -w[{ path}] : assign Work directory.Empty path means a temporary directory | ||
322 | + // -x[r[-| 0]]{ @listfile | !wildcard} : eXclude filenames | ||
323 | + // -y : assume Yes on all queries | ||
324 | + | ||
325 | + } | ||
326 | + } | ||
327 | + #endregion class BackupPackageManagerCore | ||
328 | + | ||
329 | + #region BackupPackageManagerXmlProcessor class | ||
330 | + public class BackupPackageManagerXmlProcessor : XmlParser | ||
331 | + { | ||
332 | + private List<BackupPackage> _backuppackagelist; | ||
333 | + #region constructor | ||
334 | + public BackupPackageManagerXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) | ||
335 | + { | ||
336 | + _backuppackagelist = new List<BackupPackage>(); | ||
337 | + var bpxmllist = GetAllXElements(nameof(BackupPackage.XmlStructure.BackupPackage)); | ||
338 | + if (bpxmllist != null && bpxmllist.Any()) | ||
339 | + { | ||
340 | + foreach (var bpxml in bpxmllist) { var bp = new BackupPackage(bpxml); if (bp.Valid) { _backuppackagelist.Add(bp); } } | ||
341 | + } | ||
342 | + } | ||
343 | + #endregion constructor | ||
344 | + #region GetDefinitionList | ||
345 | + public List<BackupPackage> GetDefinitionList() { return _backuppackagelist; } | ||
346 | + #endregion GetDefinitionList | ||
347 | + } | ||
348 | + #endregion BackupPackageManagerXmlProcessor class | ||
349 | + | ||
350 | + #region BackupPackage class | ||
351 | + public class BackupPackage : XmlLinqBase | ||
352 | + { | ||
353 | + #region fields | ||
354 | + public bool Valid = true; | ||
355 | + public string Xml_Key; | ||
356 | + public string Xml_PackageName; | ||
357 | + public string Xml_Description; | ||
358 | + public string Xml_PackageFilePath; | ||
359 | + public string Xml_SourceIncludeFilenameMaskList; | ||
360 | + public bool Xml_CreateExe; | ||
361 | + public List<BackupFolder> Xml_BackupFolderList; | ||
362 | + public List<BackupSQLDataBase> Xml_BackupSQLDataBaseList; | ||
363 | + | ||
364 | + public long SizePackageTotal; | ||
365 | + #endregion fields | ||
366 | + | ||
367 | + #region basic constructor | ||
368 | + public BackupPackage() { } | ||
369 | + #endregion basic constructor | ||
370 | + | ||
371 | + #region xml constructor | ||
372 | + public BackupPackage(XElement backupackagexml) | ||
373 | + { | ||
374 | + Valid = true; | ||
375 | + string ATTRIBUTEMANDATORY = nameof(XmlStructure.BackupPackage) + " attribute is mandatory! Name: {0}"; | ||
376 | + Xml_Key = GetValue(nameof(XmlStructure.BackupPackage.Attributes.Key), backupackagexml, XmlStructure.BackupPackage.Attributes.Key.Values.DEFAULT); | ||
377 | + Xml_PackageName = backupackagexml.Attribute(XName.Get(nameof(XmlStructure.BackupPackage.Attributes.Name)))?.Value; | ||
378 | + if (string.IsNullOrWhiteSpace(Xml_PackageName)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, nameof(XmlStructure.BackupPackage.Attributes.Name))); } | ||
379 | + Xml_Description = GetValue(nameof(XmlStructure.BackupPackage.Attributes.Description), backupackagexml, Xml_PackageName); | ||
380 | + Xml_PackageFilePath = GetValue(nameof(XmlStructure.BackupPackage.Attributes.PackageFilePath), backupackagexml, ""); | ||
381 | + if (string.IsNullOrWhiteSpace(Xml_PackageFilePath)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, XmlStructure.BackupPackage.Attributes.PackageFilePath.Values.DEFAULT)); } | ||
382 | + | ||
383 | + Xml_SourceIncludeFilenameMaskList = GetValue(nameof(XmlStructure.BackupPackage.Attributes.IncludeFilenameMaskList), backupackagexml, XmlStructure.BackupPackage.Attributes.IncludeFilenameMaskList.Values.DEFAULT); | ||
384 | + | ||
385 | + string XmlCreateExestring = GetValue(nameof(XmlStructure.BackupPackage.Attributes.CreateExe), backupackagexml, XmlStructure.BackupPackage.Attributes.CreateExe.Values.DEFAULT.ToString()); | ||
386 | + if (string.IsNullOrWhiteSpace(XmlCreateExestring)) { XmlCreateExestring = XmlStructure.BackupPackage.Attributes.CreateExe.Values.DEFAULT.ToString(); } | ||
387 | + Xml_CreateExe = bool.Parse(XmlCreateExestring); | ||
388 | + | ||
389 | + Xml_BackupFolderList = new List<BackupFolder>(); | ||
390 | + //var conditionxmlList = GetAllXElements(foldertocleanxml, nameof(XmlStructure.FolderToClean.Conditions), nameof(XmlStructure.FolderToClean.Conditions.Condition)); | ||
391 | + var backupfolderxmlList = backupackagexml.Elements(XName.Get(nameof(XmlStructure.BackupPackage.BackupFolder))); | ||
392 | + if (backupfolderxmlList!=null && backupfolderxmlList.Any()) | ||
393 | + { | ||
394 | + foreach (var backupfolderxml in backupfolderxmlList) { Xml_BackupFolderList.Add(new BackupFolder(backupfolderxml)); } | ||
395 | + } | ||
396 | + Xml_BackupSQLDataBaseList = new List<BackupSQLDataBase>(); | ||
397 | + //var conditionxmlList = GetAllXElements(foldertocleanxml, nameof(XmlStructure.FolderToClean.Conditions), nameof(XmlStructure.FolderToClean.Conditions.Condition)); | ||
398 | + var backupsqldbxmlList = backupackagexml.Elements(XName.Get(nameof(XmlStructure.BackupPackage.BackupSQLDataBase))); | ||
399 | + if (backupsqldbxmlList != null && backupsqldbxmlList.Any()) | ||
400 | + { | ||
401 | + foreach (var backupsqldbxml in backupsqldbxmlList) { Xml_BackupSQLDataBaseList.Add(new BackupSQLDataBase(backupsqldbxml)); } | ||
402 | + } | ||
403 | + } | ||
404 | + #endregion xml constructor | ||
405 | + | ||
406 | + #region cloner constructor | ||
407 | + public BackupPackage(BackupPackage bp) | ||
408 | + { | ||
409 | + Valid = bp.Valid; | ||
410 | + Xml_Key = bp.Xml_Key; | ||
411 | + Xml_PackageName = bp.Xml_PackageName; | ||
412 | + Xml_Description = bp.Xml_Description; | ||
413 | + Xml_BackupFolderList = bp.Xml_BackupFolderList.Select(c=>new BackupFolder(c)).ToList(); ; | ||
414 | + Xml_PackageFilePath=bp.Xml_PackageFilePath; | ||
415 | + Xml_BackupSQLDataBaseList = bp.Xml_BackupSQLDataBaseList.Select(c => new BackupSQLDataBase(c)).ToList(); ; | ||
416 | + Xml_SourceIncludeFilenameMaskList = bp.Xml_SourceIncludeFilenameMaskList; | ||
417 | + } | ||
418 | + #endregion cloner constructor | ||
419 | + | ||
420 | + #region XmlStructure | ||
421 | + public static class XmlStructure | ||
422 | + { | ||
423 | + public static class BackupPackage | ||
424 | + { | ||
425 | + public static class Attributes | ||
426 | + { | ||
427 | + public static class Key { public static class Values { public const string DEFAULT = ""; } } | ||
428 | + public static class Name { } | ||
429 | + public static class Description { } | ||
430 | + public static class CreateExe { public static class Values { public const bool DEFAULT = true; } } | ||
431 | + public static class IncludeFilenameMaskList { public static class Values { public const string DEFAULT = "*"; } } | ||
432 | + public static class PackageFilePath{ public static class Values { public const string DEFAULT = "BackupPackage_{TIMESTAMP}_{PACKAGENAME}"; } } | ||
433 | + } | ||
434 | + public static class BackupFolder | ||
435 | + { | ||
436 | + public static class Attributes | ||
437 | + { | ||
438 | + public static class Path { public static class Values { public const string DEFAULT = ""; } } | ||
439 | + public static class Description { } | ||
440 | + public static class BackupToFile { } | ||
441 | + public static class IncludeNameMask { public class Values { public const string DEFAULT = "*"; } } | ||
442 | + public static class IncludePathRegexp { public class Values { public const string DEFAULT = ".*"; } } | ||
443 | + } | ||
444 | + } | ||
445 | + public static class BackupSQLDataBase | ||
446 | + { | ||
447 | + public static class Attributes | ||
448 | + { | ||
449 | + public static class DBBackup { public static class Values { public const bool DEFAULT = true; } } | ||
450 | + public static class ScriptBackup { public static class Values { public const bool DEFAULT = true; } } | ||
451 | + public static class TableDataBackup { public static class Values { public const bool DEFAULT = true; } } | ||
452 | + public static class Key { public static class Values { public const string DEFAULT = ""; } } | ||
453 | + } | ||
454 | + } | ||
455 | + } | ||
456 | + } | ||
457 | + #endregion XmlStructure | ||
458 | + | ||
459 | + #region BackupFolder class | ||
460 | + public class BackupFolder : XmlLinqBase | ||
461 | + { | ||
462 | + public BackupFolder(XElement backupfolderxml) | ||
463 | + { | ||
464 | + Xml_Path = GetValue(nameof(XmlStructure.BackupPackage.BackupFolder.Attributes.Path), backupfolderxml, XmlStructure.BackupPackage.BackupFolder.Attributes.Path.Values.DEFAULT); | ||
465 | + Xml_Description = GetValue(nameof(XmlStructure.BackupPackage.BackupFolder.Attributes.Description), backupfolderxml, Xml_Path); | ||
466 | + Xml_BackupToFile = GetValue(nameof(XmlStructure.BackupPackage.BackupFolder.Attributes.BackupToFile), backupfolderxml, ""); | ||
467 | + Xml_IncludeFileNameMask = GetValue(nameof(XmlStructure.BackupPackage.BackupFolder.Attributes.IncludeNameMask), backupfolderxml, XmlStructure.BackupPackage.BackupFolder.Attributes.IncludeNameMask.Values.DEFAULT); | ||
468 | + Xml_IncludeFileFullPathRegex = GetValue(nameof(XmlStructure.BackupPackage.BackupFolder.Attributes.IncludePathRegexp), backupfolderxml, XmlStructure.BackupPackage.BackupFolder.Attributes.IncludePathRegexp.Values.DEFAULT); | ||
469 | + } | ||
470 | + public BackupFolder(BackupFolder bf) | ||
471 | + { | ||
472 | + Xml_Path = bf.Xml_Path; | ||
473 | + Xml_Description = bf.Xml_Description; | ||
474 | + Xml_BackupToFile = bf.Xml_BackupToFile; | ||
475 | + FolderExists = bf.FolderExists; | ||
476 | + Xml_IncludeFileNameMask = bf.Xml_IncludeFileNameMask; | ||
477 | + Xml_IncludeFileFullPathRegex = bf.Xml_IncludeFileFullPathRegex; | ||
478 | + } | ||
479 | + public string Xml_Path; | ||
480 | + public string Xml_Description; | ||
481 | + public string Xml_BackupToFile; | ||
482 | + public string Xml_IncludeFileNameMask; | ||
483 | + public string Xml_IncludeFileFullPathRegex; | ||
484 | + public bool FolderExists; | ||
485 | + } | ||
486 | + #endregion BackupFolder class | ||
487 | + #region BackupSQLDataBase class | ||
488 | + public class BackupSQLDataBase : XmlLinqBase | ||
489 | + { | ||
490 | + public BackupSQLDataBase(XElement backupfolderxml) | ||
491 | + { | ||
492 | + Xml_Key = GetValue(nameof(XmlStructure.BackupPackage.BackupSQLDataBase.Attributes.Key), backupfolderxml, XmlStructure.BackupPackage.BackupSQLDataBase.Attributes.Key.Values.DEFAULT); | ||
493 | + Xml_DBBackup = GetValue(nameof(XmlStructure.BackupPackage.BackupSQLDataBase.Attributes.DBBackup), backupfolderxml, XmlStructure.BackupPackage.BackupSQLDataBase.Attributes.DBBackup.Values.DEFAULT); | ||
494 | + Xml_ScriptBackup = GetValue(nameof(XmlStructure.BackupPackage.BackupSQLDataBase.Attributes.ScriptBackup), backupfolderxml, XmlStructure.BackupPackage.BackupSQLDataBase.Attributes.ScriptBackup.Values.DEFAULT); | ||
495 | + Xml_TableDataBackup = GetValue(nameof(XmlStructure.BackupPackage.BackupSQLDataBase.Attributes.TableDataBackup), backupfolderxml, XmlStructure.BackupPackage.BackupSQLDataBase.Attributes.TableDataBackup.Values.DEFAULT); | ||
496 | + } | ||
497 | + public BackupSQLDataBase(BackupSQLDataBase bf) | ||
498 | + { | ||
499 | + Xml_Key = bf.Xml_Key; | ||
500 | + Xml_DBBackup = bf.Xml_DBBackup; | ||
501 | + Xml_ScriptBackup = bf.Xml_ScriptBackup; | ||
502 | + Xml_TableDataBackup = bf.Xml_TableDataBackup; | ||
503 | + } | ||
504 | + public string Xml_Key; | ||
505 | + public bool Xml_DBBackup; | ||
506 | + public bool Xml_ScriptBackup; | ||
507 | + public bool Xml_TableDataBackup; | ||
508 | + } | ||
509 | + #endregion BackupSQLDataBase class | ||
510 | + | ||
511 | + } | ||
512 | + #endregion BackupPackage class | ||
513 | +} |
Vrh.Log4Pro.MaintenanceConsole/Manager - FileCleanerManager.cs
1 | using System; | 1 | using System; |
2 | using System.IO; | 2 | using System.IO; |
3 | +using System.IO.Compression; | ||
3 | using System.Configuration.Install; | 4 | using System.Configuration.Install; |
4 | using System.Collections.Generic; | 5 | using System.Collections.Generic; |
5 | using System.Linq; | 6 | using System.Linq; |
@@ -12,97 +13,95 @@ using Microsoft.Web.Administration; | @@ -12,97 +13,95 @@ using Microsoft.Web.Administration; | ||
12 | using System.Management; | 13 | using System.Management; |
13 | using System.Diagnostics; | 14 | using System.Diagnostics; |
14 | 15 | ||
16 | +using Vrh.Log4Pro.MaintenanceConsole.MenuNS; | ||
17 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
18 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
19 | + | ||
15 | using Vrh.XmlProcessing; | 20 | using Vrh.XmlProcessing; |
21 | +using VRH.Common; | ||
16 | using System.Xml.Linq; | 22 | using System.Xml.Linq; |
17 | using System.Text.RegularExpressions; | 23 | using System.Text.RegularExpressions; |
18 | 24 | ||
19 | -namespace Vrh.Log4Pro.MaintenanceConsole | 25 | +namespace Vrh.Log4Pro.MaintenanceConsole.FileCleanerManagerNS |
20 | { | 26 | { |
21 | #region FileCleanerManager class | 27 | #region FileCleanerManager class |
22 | public static class FileCleanerManager | 28 | public static class FileCleanerManager |
23 | { | 29 | { |
30 | + private const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE_FILECLEANERMANAGER;"; | ||
31 | + private const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;element=FileCleaner;"; | ||
32 | + | ||
24 | #region Execute | 33 | #region Execute |
25 | public static object Execute(object o1 = null, object o2 = null) | 34 | public static object Execute(object o1 = null, object o2 = null) |
26 | { | 35 | { |
27 | - string xmlcs = "file=Config.Xml;element=FileCleaner;"; | ||
28 | - var config = new FileCleanerManagerCoreXmlProcessor(xmlcs, "", "hu-HU"); | 36 | + var args = (o1 as Menu.ExecutorParameter).Args; |
37 | + var functionkey = CommandLine.GetCommandLineArgument(args, CLP.CMD_FUNCTION); | ||
38 | + var config = new FileCleanerManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); | ||
39 | + var ep = new Menu.ExecutorParameter(config, args); | ||
29 | 40 | ||
30 | var menufunctions = new Menu("Manage Folders To Clean", "Select the management function!") | 41 | var menufunctions = new Menu("Manage Folders To Clean", "Select the management function!") |
31 | - .AddMenuItem(new Menu.Item("CLN", "Clean folder", CleanFolder)) | ||
32 | - .SetSelectionMode(Menu.SelectionMode.Single); | ||
33 | - | ||
34 | - while (true) | ||
35 | - { | ||
36 | - Menu.Selection sr; | ||
37 | - | ||
38 | - menufunctions.DisplayTitle(); | ||
39 | - var menuservices = DisplayFolders(config); | ||
40 | - menufunctions.DisplayItems(); | ||
41 | - sr = menufunctions.Select(); | ||
42 | - if (sr.Result == Menu.SelectionResult.Exit) { break; } | ||
43 | - else if (sr.Result == Menu.SelectionResult.None) { continue; } | ||
44 | - else if (sr.Result == Menu.SelectionResult.Error) { continue; } | ||
45 | - menufunctions.SetExecutorParameters(sr,config); | ||
46 | - menufunctions.ExecuteSelection(sr.SelectedKeyList); | ||
47 | - } | ||
48 | - return null; | 42 | + .AddMenuItem(new Menu.Item(CLP.Module.FileCleanerManager.Functions.FolderClean.KEY, "Clean folder", FolderClean, ep)) |
43 | + .SetSelectionMode(Menu.SelectionMode.Single) | ||
44 | + .SetMenuHeaderDisplayer(FolderToCleanListDisplayer); | ||
45 | + menufunctions.ExecuteMenu(functionkey); | ||
46 | + return o2; | ||
49 | } | 47 | } |
50 | #endregion Execute | 48 | #endregion Execute |
51 | 49 | ||
52 | #region First level Executors with UI | 50 | #region First level Executors with UI |
53 | - private static object CleanFolder(object parameter, object o) | 51 | + private static object FolderClean(object parameter, object o) |
54 | { | 52 | { |
55 | - var config = parameter as FileCleanerManagerCoreXmlProcessor; | 53 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<FileCleanerManagerXmlProcessor>(); |
54 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
56 | 55 | ||
57 | - var menufolders = DisplayFolders(config, $"Select the folder(s) to manage with function '{nameof(CleanFolder)}'!", silent: true); | 56 | + var selectedftcindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.FileCleanerManager.Functions.CMD_FOLDERS); |
58 | 57 | ||
59 | - Menu.Selection sr = menufolders.Select(); | 58 | + var menufolders = DisplayFolderMenu(config, $"Select the folder(s) to manage with function '{nameof(FolderClean)}'!", silent: true); |
59 | + | ||
60 | + Menu.Selection sr = menufolders.Select(selectedftcindexes); | ||
60 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 61 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
61 | else if (sr.Result == Menu.SelectionResult.None) { return o; } | 62 | else if (sr.Result == Menu.SelectionResult.None) { return o; } |
62 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } | 63 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } |
63 | else if (sr.Result == Menu.SelectionResult.Ok) { } | 64 | else if (sr.Result == Menu.SelectionResult.Ok) { } |
64 | else { } | 65 | else { } |
65 | - foreach (var p in sr.SelectedParameterList) | 66 | + foreach (var p in sr.SelectedParameterList) { OneFolderClean(p.Parameters as FolderToClean); } |
67 | + return o; | ||
68 | + } | ||
69 | + private static void OneFolderClean(FolderToClean ftc) | ||
70 | + { | ||
71 | + try | ||
66 | { | 72 | { |
67 | - FolderToClean ftc = p as FolderToClean; | ||
68 | - try | ||
69 | - { | ||
70 | - var di = new DirectoryInfo(ftc.Xml_DirectoryPath); | ||
71 | - var success = FileCleanerManagerCore.CleanFolderFiles(di,ftc, delete: true); | ||
72 | - ColorConsole.WriteLine($"Folder cleaned. Name:{ftc.Xml_DirectoryPath}", ConsoleColor.Green); | ||
73 | - } | ||
74 | - catch (Exception ex) | ||
75 | - { | ||
76 | - ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); | ||
77 | - } | 73 | + var di = new DirectoryInfo(ftc.Xml_DirectoryPath); |
74 | + var success = FileCleanerManagerCore.CleanFolderFiles(di, ftc, delete: true); | ||
75 | + ColorConsole.WriteLine($"Folder cleaned. Name:{ftc.Xml_DirectoryPath}", ConsoleColor.Green); | ||
78 | } | 76 | } |
79 | - return o; | 77 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } |
80 | } | 78 | } |
81 | #endregion First level Executors with UI | 79 | #endregion First level Executors with UI |
82 | 80 | ||
83 | #region private methods | 81 | #region private methods |
84 | - #region private DisplayFolders | ||
85 | - private static Menu DisplayFolders(FileCleanerManagerCoreXmlProcessor config,string prompt = null,bool silent=false) | 82 | + #region private DisplayFolderMenu |
83 | + private static void FolderToCleanListDisplayer() { DisplayFolderMenu(); } | ||
84 | + private static Menu DisplayFolderMenu(FileCleanerManagerXmlProcessor config=null,string prompt = null,bool silent=false) | ||
86 | { | 85 | { |
86 | + if (config==null) { config = new FileCleanerManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); } | ||
87 | List<FolderToClean> fctdefList = config.GetDefinitionList(); | 87 | List<FolderToClean> fctdefList = config.GetDefinitionList(); |
88 | var menufct = new Menu("Folder to clean",prompt) | 88 | var menufct = new Menu("Folder to clean",prompt) |
89 | .SetMenuItemDisplayer(DisplayFolderInfo) | 89 | .SetMenuItemDisplayer(DisplayFolderInfo) |
90 | - .SetSelectionMode(Menu.SelectionMode.Multi) | ||
91 | - .SetHeaderWidth(4); | 90 | + .SetSelectionMode(Menu.SelectionMode.Multi); |
92 | menufct.ClearMenuItemList(); | 91 | menufct.ClearMenuItemList(); |
93 | foreach (var fctdef in fctdefList) | 92 | foreach (var fctdef in fctdefList) |
94 | { | 93 | { |
95 | var fi = CollectFolderInfo(fctdef); | 94 | var fi = CollectFolderInfo(fctdef); |
96 | - menufct.AddMenuItem(new Menu.Item(null, null, null, fi)); | 95 | + menufct.AddMenuItem(new Menu.Item(fctdef.Xml_Key, null, null, new Menu.ExecutorParameter(pars:fi))); |
97 | } | 96 | } |
98 | if (!silent) { menufct.DisplayItems(1); } | 97 | if (!silent) { menufct.DisplayItems(1); } |
99 | return menufct; | 98 | return menufct; |
100 | } | 99 | } |
101 | - #endregion private DisplayFolders | 100 | + #endregion private DisplayFolderMenu |
102 | #region private method: DisplayFolderInfo | 101 | #region private method: DisplayFolderInfo |
103 | private static object DisplayFolderInfo(object obj, int lineix) | 102 | private static object DisplayFolderInfo(object obj, int lineix) |
104 | { | 103 | { |
105 | - FolderToClean ws = obj as FolderToClean; | 104 | + FolderToClean ws = (obj as Menu.ExecutorParameter).Parameters as FolderToClean; |
106 | if (lineix == 0) | 105 | if (lineix == 0) |
107 | { | 106 | { |
108 | ColorConsole.Write($"{ws.Xml_DirectoryPath}", ConsoleColor.Black, ConsoleColor.White); | 107 | ColorConsole.Write($"{ws.Xml_DirectoryPath}", ConsoleColor.Black, ConsoleColor.White); |
@@ -214,7 +213,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -214,7 +213,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
214 | bool conditionresult = false; | 213 | bool conditionresult = false; |
215 | if (c.Type == FolderToClean.ConditionType.TimeStampInName) | 214 | if (c.Type == FolderToClean.ConditionType.TimeStampInName) |
216 | { | 215 | { |
217 | - var fileTSstr = VRH.Common.StringConstructor.ResolveConstructor<string>(groupnamevalues, c.TimestampConstructor, "{}"); | 216 | + var fileTSstr = VRH.Common.StringConstructor.ResolveConstructor<string>(groupnamevalues, c.TimestampConstructor, "{}@@"); |
217 | + | ||
218 | try { var fileTS = DateTime.Parse(fileTSstr); conditionresult = DateTime.Now.Subtract(fileTS).TotalDays > c.Limit; } | 218 | try { var fileTS = DateTime.Parse(fileTSstr); conditionresult = DateTime.Now.Subtract(fileTS).TotalDays > c.Limit; } |
219 | catch | 219 | catch |
220 | { | 220 | { |
@@ -288,12 +288,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -288,12 +288,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
288 | #endregion class FileCleanerManagerCore | 288 | #endregion class FileCleanerManagerCore |
289 | 289 | ||
290 | #region FileCleanerManagerCoreXmlProcessor class | 290 | #region FileCleanerManagerCoreXmlProcessor class |
291 | - public class FileCleanerManagerCoreXmlProcessor : XmlParser | 291 | + public class FileCleanerManagerXmlProcessor : XmlParser |
292 | { | 292 | { |
293 | private List<FolderToClean> _foldertocleanlist; | 293 | private List<FolderToClean> _foldertocleanlist; |
294 | private int commoncleanupdays; | 294 | private int commoncleanupdays; |
295 | #region constructor | 295 | #region constructor |
296 | - public FileCleanerManagerCoreXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) | 296 | + public FileCleanerManagerXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) |
297 | { | 297 | { |
298 | _foldertocleanlist = new List<FolderToClean>(); | 298 | _foldertocleanlist = new List<FolderToClean>(); |
299 | commoncleanupdays = GetValue(nameof(FolderToClean.XmlStructure.Attributes.CleanupDays),this.RootElement, FolderToClean.XmlStructure.Attributes.CleanupDays.Values.DEFAULT); | 299 | commoncleanupdays = GetValue(nameof(FolderToClean.XmlStructure.Attributes.CleanupDays),this.RootElement, FolderToClean.XmlStructure.Attributes.CleanupDays.Values.DEFAULT); |
@@ -315,6 +315,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -315,6 +315,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
315 | { | 315 | { |
316 | #region fields | 316 | #region fields |
317 | public bool Valid = true; | 317 | public bool Valid = true; |
318 | + public string Xml_Key; | ||
318 | public string Xml_DirectoryPath; | 319 | public string Xml_DirectoryPath; |
319 | public bool Xml_Recurse; | 320 | public bool Xml_Recurse; |
320 | public bool Xml_RemoveEmptyFolder; | 321 | public bool Xml_RemoveEmptyFolder; |
@@ -339,6 +340,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -339,6 +340,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
339 | { | 340 | { |
340 | Valid = true; | 341 | Valid = true; |
341 | string ATTRIBUTEMANDATORY = nameof(XmlStructure.FolderToClean) + " attribute is mandatory! Name: {0}"; | 342 | string ATTRIBUTEMANDATORY = nameof(XmlStructure.FolderToClean) + " attribute is mandatory! Name: {0}"; |
343 | + Xml_Key = GetValue(nameof(XmlStructure.FolderToClean.Attributes.Key), foldertocleanxml, XmlStructure.FolderToClean.Attributes.Key.Values.DEFAULT); | ||
342 | Xml_DirectoryPath = foldertocleanxml.Attribute(XName.Get(nameof(XmlStructure.FolderToClean.Attributes.Directory)))?.Value; | 344 | Xml_DirectoryPath = foldertocleanxml.Attribute(XName.Get(nameof(XmlStructure.FolderToClean.Attributes.Directory)))?.Value; |
343 | if (string.IsNullOrWhiteSpace(Xml_DirectoryPath)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, nameof(XmlStructure.FolderToClean.Attributes.Directory))); } | 345 | if (string.IsNullOrWhiteSpace(Xml_DirectoryPath)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, nameof(XmlStructure.FolderToClean.Attributes.Directory))); } |
344 | Xml_Recurse = GetValue(nameof(XmlStructure.FolderToClean.Attributes.Recurse), foldertocleanxml, XmlStructure.FolderToClean.Attributes.Recurse.Values.DEFAULT); | 346 | Xml_Recurse = GetValue(nameof(XmlStructure.FolderToClean.Attributes.Recurse), foldertocleanxml, XmlStructure.FolderToClean.Attributes.Recurse.Values.DEFAULT); |
@@ -361,6 +363,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -361,6 +363,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
361 | public FolderToClean(FolderToClean ftc) | 363 | public FolderToClean(FolderToClean ftc) |
362 | { | 364 | { |
363 | Valid = ftc.Valid; | 365 | Valid = ftc.Valid; |
366 | + Xml_Key= ftc.Xml_Key; | ||
364 | Xml_DirectoryPath = ftc.Xml_DirectoryPath; | 367 | Xml_DirectoryPath = ftc.Xml_DirectoryPath; |
365 | Xml_Recurse = ftc.Xml_Recurse; | 368 | Xml_Recurse = ftc.Xml_Recurse; |
366 | Xml_RemoveEmptyFolder = ftc.Xml_RemoveEmptyFolder; | 369 | Xml_RemoveEmptyFolder = ftc.Xml_RemoveEmptyFolder; |
@@ -414,6 +417,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -414,6 +417,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
414 | { | 417 | { |
415 | public static class Attributes | 418 | public static class Attributes |
416 | { | 419 | { |
420 | + public static class Key { public static class Values { public const string DEFAULT = ""; } } | ||
417 | public static class Directory { } | 421 | public static class Directory { } |
418 | public static class CleanupDays | 422 | public static class CleanupDays |
419 | { | 423 | { |
Vrh.Log4Pro.MaintenanceConsole/Manager - MaintenanceToolManager.cs
@@ -12,40 +12,35 @@ using Microsoft.Web.Administration; | @@ -12,40 +12,35 @@ using Microsoft.Web.Administration; | ||
12 | using System.Management; | 12 | using System.Management; |
13 | using System.Diagnostics; | 13 | using System.Diagnostics; |
14 | 14 | ||
15 | +using Vrh.Log4Pro.MaintenanceConsole.MenuNS; | ||
16 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
17 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
18 | + | ||
15 | using Vrh.XmlProcessing; | 19 | using Vrh.XmlProcessing; |
16 | using System.Xml.Linq; | 20 | using System.Xml.Linq; |
17 | using System.Text.RegularExpressions; | 21 | using System.Text.RegularExpressions; |
18 | 22 | ||
19 | -namespace Vrh.Log4Pro.MaintenanceConsole | 23 | +namespace Vrh.Log4Pro.MaintenanceConsole.MaintenanceToolManagerNS |
20 | { | 24 | { |
21 | #region MaintenanceTools class | 25 | #region MaintenanceTools class |
22 | public static class MaintenanceToolManager | 26 | public static class MaintenanceToolManager |
23 | { | 27 | { |
28 | + private const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE_MAINTENANCETOOLMANAGER;"; | ||
29 | + private const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;element=MaintenanceTools;"; | ||
30 | + | ||
24 | #region Execute | 31 | #region Execute |
25 | public static object Execute(object o1 = null, object o2 = null) | 32 | public static object Execute(object o1 = null, object o2 = null) |
26 | { | 33 | { |
27 | - string xmlcs = "file=Config.Xml;element=WindowsServices;"; | 34 | + var args = (o1 as Menu.ExecutorParameter).Args; |
35 | + string xmlcs = XMLCONNECTIONSTRING; | ||
28 | var config = new MaintenanceToolsXmlProcessor(xmlcs, "", "hu-HU"); | 36 | var config = new MaintenanceToolsXmlProcessor(xmlcs, "", "hu-HU"); |
29 | 37 | ||
30 | var menufunctions = new Menu("Maintenance Tools", "Select function!") | 38 | var menufunctions = new Menu("Maintenance Tools", "Select function!") |
31 | - .AddMenuItem(new Menu.Item("RGX", "Regex tester", RegexTester)) | ||
32 | - .AddMenuItem(new Menu.Item("TL1", "Tool #1", Tool1)) | ||
33 | - .AddMenuItem(new Menu.Item("TL2", "Tool #2", Tool2)) | 39 | + .AddMenuItem(new Menu.Item(CLP.Module.MaintenanceToolManager.Functions.RegexTester.KEY, "Regex tester", RegexTester,new Menu.ExecutorParameter(cfg:config))) |
40 | + .AddMenuItem(new Menu.Item(CLP.Module.MaintenanceToolManager.Functions.Tool1.KEY, "Tool #1", Tool1, new Menu.ExecutorParameter(cfg: config, null))) | ||
41 | + .AddMenuItem(new Menu.Item(CLP.Module.MaintenanceToolManager.Functions.Tool2.KEY, "Tool #2", Tool2, new Menu.ExecutorParameter(cfg: config, null))) | ||
34 | .SetSelectionMode(Menu.SelectionMode.Single); | 42 | .SetSelectionMode(Menu.SelectionMode.Single); |
35 | - | ||
36 | - while (true) | ||
37 | - { | ||
38 | - Menu.Selection sr; | ||
39 | - | ||
40 | - menufunctions.DisplayTitle(); | ||
41 | - menufunctions.DisplayItems(); | ||
42 | - sr = menufunctions.Select(); | ||
43 | - if (sr.Result == Menu.SelectionResult.Exit) { break; } | ||
44 | - else if (sr.Result == Menu.SelectionResult.None) { continue; } | ||
45 | - else if (sr.Result == Menu.SelectionResult.Error) { continue; } | ||
46 | - menufunctions.SetExecutorParameters(sr,config); | ||
47 | - menufunctions.ExecuteSelection(sr.SelectedKeyList); | ||
48 | - } | 43 | + menufunctions.ExecuteMenu(); |
49 | return null; | 44 | return null; |
50 | } | 45 | } |
51 | #endregion Execute | 46 | #endregion Execute |
@@ -54,7 +49,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -54,7 +49,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
54 | #region RegexTester | 49 | #region RegexTester |
55 | private static object RegexTester(object parameter, object o) | 50 | private static object RegexTester(object parameter, object o) |
56 | { | 51 | { |
57 | - var config = parameter as MaintenanceToolsXmlProcessor; | 52 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<MaintenanceToolsXmlProcessor>(); |
58 | var regexptesterconfig = config.RegexpTesterConfig; | 53 | var regexptesterconfig = config.RegexpTesterConfig; |
59 | while(true) | 54 | while(true) |
60 | { | 55 | { |
Vrh.Log4Pro.MaintenanceConsole/Manager - SQLDataBaseManager.cs
0 → 100644
@@ -0,0 +1,1113 @@ | @@ -0,0 +1,1113 @@ | ||
1 | +using System; | ||
2 | +using System.IO; | ||
3 | +using System.IO.Compression; | ||
4 | +using System.Configuration.Install; | ||
5 | +using System.Collections.Generic; | ||
6 | +using System.Linq; | ||
7 | +using System.ServiceProcess; | ||
8 | +using System.Text; | ||
9 | +using System.Threading; | ||
10 | +using System.Threading.Tasks; | ||
11 | + | ||
12 | +using Microsoft.Web.Administration; | ||
13 | +using System.Management; | ||
14 | +using System.Diagnostics; | ||
15 | + | ||
16 | +using Vrh.Log4Pro.MaintenanceConsole.MenuNS; | ||
17 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
18 | +using Vrh.Log4Pro.MaintenanceConsole.ToolsNS; | ||
19 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
20 | + | ||
21 | +using Vrh.XmlProcessing; | ||
22 | +using VRH.Common; | ||
23 | +using System.Xml.Linq; | ||
24 | +using System.Text.RegularExpressions; | ||
25 | + | ||
26 | +using Microsoft.SqlServer.Management.Common; | ||
27 | +using Microsoft.SqlServer.Management.Smo; | ||
28 | + | ||
29 | +namespace Vrh.Log4Pro.MaintenanceConsole.SQLDataBaseManagerNS | ||
30 | +{ | ||
31 | + #region SQLDataBaseManager class | ||
32 | + public static class SQLDataBaseManager | ||
33 | + { | ||
34 | + private const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE_SQLDATABASEMANAGER;"; | ||
35 | + private const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;element=SQLDataBases;"; | ||
36 | + | ||
37 | + #region Execute | ||
38 | + public static object Execute(object o1 = null, object o2 = null) | ||
39 | + { | ||
40 | + var args = (o1 as Menu.ExecutorParameter).Args; | ||
41 | + var functionkey = CommandLine.GetCommandLineArgument(args, CLP.CMD_FUNCTION); | ||
42 | + | ||
43 | + var config = new SQLDataBaseManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); | ||
44 | + var ep = new Menu.ExecutorParameter(config, args); | ||
45 | + var menufunctions = new Menu("Manage Scheduled tasks", "Select the management function!") | ||
46 | + .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.BackupDataBase.KEY, "Backup database", BackupDataBase, ep)) | ||
47 | + .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.CreateCodeScripts.KEY, "Create code scripts", CreateCodeScripts, ep)) | ||
48 | + .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.CreateDataScripts.KEY, "Create data scripts", CreateDataScripts, ep)) | ||
49 | + .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.RestoreDataBase.KEY, "Restore database backup", RestoreDataBase, ep)) | ||
50 | + .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.RelocatePhysicalFiles.KEY, "Copy database and or relocate its physical files", RelocatePhysicalFiles, ep)) | ||
51 | + .SetSelectionMode(Menu.SelectionMode.Single) | ||
52 | + .SetMenuHeaderDisplayer(DataBaseListDisplayer); | ||
53 | + menufunctions.ExecuteMenu(functionkey); | ||
54 | + return o2; | ||
55 | + } | ||
56 | + public static void Execute(string key, bool enabledbbackup, bool enablescriptbackup, bool enabletabledatabackup, string targetfolder=null,DateTime? timestamp = null) | ||
57 | + { | ||
58 | + var packagets = (timestamp.HasValue ? timestamp.Value : DateTime.Now).ToString("yyyyMMddHHmmss"); | ||
59 | + var config = new SQLDataBaseManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); | ||
60 | + var origsqld = config.GetDefinitionList().FirstOrDefault(x => x.Xml_Key == key); | ||
61 | + if (origsqld != null) | ||
62 | + { | ||
63 | + var sqld = new SQLDataBase(origsqld); | ||
64 | + if (!string.IsNullOrWhiteSpace(targetfolder)) { sqld.Xml_BackupTargetDirectoryPath = targetfolder; } | ||
65 | + if (enabledbbackup) { SQLDataBaseManagerCore.CreateBackup(sqld.Xml_BackupTargetDirectoryPath, sqld.SQLCS, sqld.Xml_BackupFileNameMask, sqld.Xml_CreateZip, timestamp); } | ||
66 | + if (enablescriptbackup) { SQLDataBaseManagerCore.BackupSqlScripts(sqld.Xml_BackupTargetDirectoryPath, sqld.Xml_BackupFileNameMask, sqld.SQLCS, sqld.Xml_CreateZip, timestamp); } | ||
67 | + if (enabletabledatabackup) { SQLDataBaseManagerCore.BackupSqlData(sqld, timestamp); } | ||
68 | + } | ||
69 | + } | ||
70 | + #endregion Execute | ||
71 | + | ||
72 | + #region First level Executors with UI | ||
73 | + private static object CreateDataScripts(object parameter, object o) | ||
74 | + { | ||
75 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<SQLDataBaseManagerXmlProcessor>(); | ||
76 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
77 | + | ||
78 | + var selectedsqldbindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.SQLDataBaseManager.Function.CMD_DATABASES); | ||
79 | + | ||
80 | + var menufolders = DisplaySQLDataBaseMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(CreateDataScripts)}'!", silent: true); | ||
81 | + | ||
82 | + Menu.Selection sr = menufolders.Select(selectedsqldbindexes); | ||
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 | + | ||
89 | + DateTime TS = DateTime.Now; | ||
90 | + foreach (var p in sr.SelectedParameterList) | ||
91 | + { | ||
92 | + SQLDataBase sqld = p.Parameters as SQLDataBase; | ||
93 | + try | ||
94 | + { | ||
95 | + SQLDataBaseManagerCore.BackupSqlData(sqld,TS); | ||
96 | + ColorConsole.WriteLine($"SQLDB data scripts created. Name:{sqld.Xml_Description}", ConsoleColor.Green); | ||
97 | + } | ||
98 | + catch (Exception ex) | ||
99 | + { | ||
100 | + ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); | ||
101 | + } | ||
102 | + } | ||
103 | + return o; | ||
104 | + } | ||
105 | + private static object CreateCodeScripts(object parameter, object o) | ||
106 | + { | ||
107 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<SQLDataBaseManagerXmlProcessor>(); | ||
108 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
109 | + | ||
110 | + var selectedsqldbindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.SQLDataBaseManager.Function.CMD_DATABASES); | ||
111 | + | ||
112 | + var menufolders = DisplaySQLDataBaseMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(CreateCodeScripts)}'!", silent: true); | ||
113 | + | ||
114 | + Menu.Selection sr = menufolders.Select(selectedsqldbindexes); | ||
115 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
116 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
117 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
118 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
119 | + else { } | ||
120 | + | ||
121 | + DateTime TS = DateTime.Now; | ||
122 | + foreach (var p in sr.SelectedParameterList) | ||
123 | + { | ||
124 | + SQLDataBase sqld = p.Parameters as SQLDataBase; | ||
125 | + try | ||
126 | + { | ||
127 | + | ||
128 | + SQLDataBaseManagerCore.BackupSqlScripts(sqld.Xml_BackupTargetDirectoryPath, sqld.Xml_BackupFileNameMask,sqld.SQLCS,sqld.Xml_CreateZip,TS); | ||
129 | + ColorConsole.WriteLine($"SQLDB code scripts created. Name:{sqld.Xml_Description}", ConsoleColor.Green); | ||
130 | + } | ||
131 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
132 | + } | ||
133 | + return o; | ||
134 | + } | ||
135 | + private static object BackupDataBase(object parameter, object o) | ||
136 | + { | ||
137 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<SQLDataBaseManagerXmlProcessor>(); | ||
138 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
139 | + | ||
140 | + var selectedsqldbindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.SQLDataBaseManager.Function.CMD_DATABASES); | ||
141 | + | ||
142 | + var menufolders = DisplaySQLDataBaseMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(BackupDataBase)}'!", silent: true); | ||
143 | + | ||
144 | + Menu.Selection sr = menufolders.Select(selectedsqldbindexes); | ||
145 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
146 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
147 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
148 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
149 | + else { } | ||
150 | + | ||
151 | + var TS = DateTime.Now; | ||
152 | + foreach (var p in sr.SelectedParameterList) | ||
153 | + { | ||
154 | + SQLDataBase ssqldb = p.Parameters as SQLDataBase; | ||
155 | + try | ||
156 | + { | ||
157 | + SQLDataBaseManagerCore.CreateBackup(ssqldb.Xml_BackupTargetDirectoryPath, ssqldb.SQLCS, ssqldb.Xml_BackupFileNameMask, ssqldb.Xml_CreateZip,TS); | ||
158 | + ColorConsole.WriteLine($"Database backup created. Name:{ssqldb.DBName}", ConsoleColor.Green); | ||
159 | + } | ||
160 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
161 | + } | ||
162 | + return o; | ||
163 | + } | ||
164 | + private static object RestoreDataBase(object parameter, object o) | ||
165 | + { | ||
166 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<SQLDataBaseManagerXmlProcessor>(); | ||
167 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
168 | + | ||
169 | + var selectedsqldbindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.SQLDataBaseManager.Function.CMD_DATABASES); | ||
170 | + bool restorefirst = CommandLine.GetCommandLineArgument(args, CLP.Module.SQLDataBaseManager.Function.RestoreDataBase.CMD_RESTOREFIRST,switchtype:true)!=null; | ||
171 | + | ||
172 | + var menufolders = DisplaySQLDataBaseMenu(config, $"Select the sql database(s) to manage with function '{nameof(RestoreDataBase)}'!", silent: true); | ||
173 | + | ||
174 | + Menu.Selection sr = menufolders.Select(selectedsqldbindexes); | ||
175 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
176 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
177 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
178 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
179 | + else { } | ||
180 | + foreach (var p in sr.SelectedParameterList) | ||
181 | + { | ||
182 | + SQLDataBase st = p.Parameters as SQLDataBase; | ||
183 | + try | ||
184 | + { | ||
185 | + var targetdirectorypath = st.Xml_PhysicalFilesDirectoryPath; | ||
186 | + var targetdbname= st.DBName; | ||
187 | + bool restorefromzip = st.Xml_CreateZip; | ||
188 | + var backupfilelist = SQLDataBaseManagerCore.GetBackupFilePathList(st); | ||
189 | + if (backupfilelist != null && backupfilelist.Any()) | ||
190 | + { | ||
191 | + string selectedbackupfilepath; | ||
192 | + if (restorefirst) | ||
193 | + { | ||
194 | + selectedbackupfilepath = backupfilelist.First().FullName; | ||
195 | + } | ||
196 | + else | ||
197 | + { | ||
198 | + var selectionlist = backupfilelist | ||
199 | + .Select(x => new KeyValuePair<string,string>($"{x.Name}({x.Length}bytes,created:{x.CreationTime})", x.FullName)) | ||
200 | + .ToDictionary(x=>x.Key,x=>x.Value); | ||
201 | + var ms = Menu.SelectFromItemList($"Backup files of {st.DBName}", "Select the backup file to restore! First is the newest!", selectionlist,Menu.SelectionMode.Single,getconfirmation:true); | ||
202 | + if (ms == null) { continue; } | ||
203 | + selectedbackupfilepath = ms.SelectedParameterList.First().Parameters.ToString(); | ||
204 | + } | ||
205 | + SQLDataBaseManagerCore.RestoreBackup(st.SQLCS, selectedbackupfilepath, targetdirectorypath, restorefromzip, targetdbname); | ||
206 | + ColorConsole.WriteLine($"Database '{st.DBName}' restored to '{targetdbname}' into directory '{targetdirectorypath}'.", ConsoleColor.Green); | ||
207 | + } | ||
208 | + else | ||
209 | + { | ||
210 | + ColorConsole.WriteLine($"Database '{st.DBName}' restore FAILED, as no backup to restore!", ConsoleColor.Red); | ||
211 | + } | ||
212 | + } | ||
213 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
214 | + } | ||
215 | + return o; | ||
216 | + } | ||
217 | + private static object RelocatePhysicalFiles(object parameter, object o) | ||
218 | + { | ||
219 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<SQLDataBaseManagerXmlProcessor>(); | ||
220 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
221 | + | ||
222 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); | ||
223 | + | ||
224 | + var menufolders = DisplaySQLDataBaseMenu(config, $"Select the sql database(s) to manage with function '{nameof(RelocatePhysicalFiles)}'!", silent: true); | ||
225 | + | ||
226 | + Menu.Selection sr = menufolders.Select(selectedtaskindexes); | ||
227 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
228 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
229 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
230 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
231 | + else { } | ||
232 | + foreach (var p in sr.SelectedParameterList) | ||
233 | + { | ||
234 | + SQLDataBase sqld = p.Parameters as SQLDataBase; | ||
235 | + try | ||
236 | + { | ||
237 | + var restoredbname = ColorConsole.ReadLine($"Enter the name of the DB to copy '{sqld.DBName}' to. Empty={sqld.DBName}. EX=exit.", ConsoleColor.Yellow, suffix: " --> "); | ||
238 | + if (restoredbname == "EX") { continue; } | ||
239 | + else if (string.IsNullOrWhiteSpace(restoredbname)) { restoredbname = sqld.DBName; } | ||
240 | + ColorConsole.WriteLine("Enter the path for the DB physical files.", ConsoleColor.Yellow); | ||
241 | + ColorConsole.WriteLine(sqld.PhysicalFilesDirectoryPath, ConsoleColor.Yellow, prefix: $" Empty=current location of source DB: ", bracket: "[]"); | ||
242 | + ColorConsole.WriteLine(SQLDataBaseManagerCore.GetServerDefaultPhysicalDATFileLocation(sqld.SQLCS), ConsoleColor.Yellow,prefix: $" DEFAULT= sql server default location.",bracket:"[]"); | ||
243 | + var targetdirectory = ColorConsole.ReadLine($"Enter the target path.EX=exit.", ConsoleColor.Yellow, suffix: " --> "); | ||
244 | + if (targetdirectory == "EX") { continue; } | ||
245 | + else if (targetdirectory == "DEFAULT") { targetdirectory = null; ; } | ||
246 | + else if (string.IsNullOrWhiteSpace(targetdirectory)) { targetdirectory = sqld.PhysicalFilesDirectoryPath; } | ||
247 | + | ||
248 | + if (restoredbname == sqld.DBName && targetdirectory == sqld.PhysicalFilesDirectoryPath) { continue; } | ||
249 | + | ||
250 | + SQLDataBaseManagerCore.RelocatePhysicalFiles(sqld, targetdirectory, restoredbname); | ||
251 | + ColorConsole.WriteLine($"Database physical files relocated. Name:{sqld.DBName}", ConsoleColor.Green); | ||
252 | + } | ||
253 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
254 | + } | ||
255 | + return o; | ||
256 | + } | ||
257 | + #endregion First level Executors with UI | ||
258 | + | ||
259 | + #region private methods | ||
260 | + #region private DisplaySQLDataBaseMenu | ||
261 | + private static void DataBaseListDisplayer() { DisplaySQLDataBaseMenu(); } | ||
262 | + private static Menu DisplaySQLDataBaseMenu(SQLDataBaseManagerXmlProcessor config = null, string prompt = null, bool silent = false) | ||
263 | + { | ||
264 | + if (config == null) { config = new SQLDataBaseManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); } | ||
265 | + List<SQLDataBase> schtskdefList = config.GetDefinitionList(); | ||
266 | + var menufct = new Menu("SQL Databases", prompt) | ||
267 | + .SetMenuItemDisplayer(DisplayDataBaseInfo) | ||
268 | + .SetSelectionMode(Menu.SelectionMode.Multi); | ||
269 | + menufct.ClearMenuItemList(); | ||
270 | + foreach (var schtskdef in schtskdefList) | ||
271 | + { | ||
272 | + var st = SQLDataBaseManagerCore.CollectDataBaseInfo(schtskdef); | ||
273 | + menufct.AddMenuItem(new Menu.Item(schtskdef.Xml_Key, null, null, new Menu.ExecutorParameter(pars: st))); | ||
274 | + } | ||
275 | + if (!silent) { menufct.DisplayItems(1); } | ||
276 | + return menufct; | ||
277 | + } | ||
278 | + #endregion private DisplaySQLDataBaseMenu | ||
279 | + #region private method: DisplayDataBaseInfo | ||
280 | + private static object DisplayDataBaseInfo(object obj, int lineix) | ||
281 | + { | ||
282 | + SQLDataBase st = (obj as Menu.ExecutorParameter).Parameters as SQLDataBase; | ||
283 | + if (lineix == 0) | ||
284 | + { | ||
285 | + ColorConsole.Write($"{st.Xml_Description}", ConsoleColor.Black, ConsoleColor.White); | ||
286 | + var statuscolor = st.Status == SQLDataBaseManagerCore.SQLDBStatus.NoAccess ? ConsoleColor.Red:ConsoleColor.Green; | ||
287 | + ColorConsole.Write(st.Status.ToString(), statuscolor, bracket: "[]", prefix: " ", suffix: ". "); | ||
288 | + if (st.Status != SQLDataBaseManagerCore.SQLDBStatus.NoAccess) | ||
289 | + { | ||
290 | + ColorConsole.Write(st.DBName, statuscolor, bracket: "[]", prefix: "Database ", suffix: ". "); | ||
291 | + ColorConsole.Write(st.DataSource, statuscolor, bracket: "[]", prefix: "from server ", suffix: ". "); | ||
292 | + } | ||
293 | + ColorConsole.WriteLine(); | ||
294 | + return " "; | ||
295 | + } | ||
296 | + else if (lineix == 1) | ||
297 | + { | ||
298 | + ColorConsole.Write($"{st.Xml_BackupFileNameMask}", ConsoleColor.Yellow, prefix: "Backup to:", suffix: ".xxx"); | ||
299 | + ColorConsole.WriteLine(); | ||
300 | + return ""; | ||
301 | + } | ||
302 | + else if (lineix == 2) | ||
303 | + { | ||
304 | + ColorConsole.Write($"{st.SQLCS}", ConsoleColor.Yellow, prefix: "SQL DB connection:", suffix: ", "); | ||
305 | + ColorConsole.WriteLine(" "); | ||
306 | + return " "; | ||
307 | + } | ||
308 | + else if (lineix == 3) | ||
309 | + { | ||
310 | + var phypath = SQLDataBaseManagerCore.GetPhysicalFilesLocation(st.SQLCS); | ||
311 | + ColorConsole.Write($"{phypath}", ConsoleColor.Yellow, prefix: "DB files physical location:", suffix: " "); | ||
312 | + ColorConsole.WriteLine(" "); | ||
313 | + return " "; | ||
314 | + } | ||
315 | + return null; | ||
316 | + } | ||
317 | + #endregion private method: DisplayDataBaseInfo | ||
318 | + #endregion private methods | ||
319 | + } | ||
320 | + #endregion SQLDataBaseManager class | ||
321 | + | ||
322 | + #region class SQLDataBaseManager | ||
323 | + public static class SQLDataBaseManagerCore | ||
324 | + { | ||
325 | + #region public CollectDataBaseInfo | ||
326 | + public static SQLDataBase CollectDataBaseInfo(SQLDataBase sqld) | ||
327 | + { | ||
328 | + sqld.Status = GetStatus(sqld.SQLCS); | ||
329 | + sqld.PhysicalFilesDirectoryPath = GetPhysicalFilesLocation(sqld.SQLCS); | ||
330 | + sqld.DBName = GetDBName(sqld.SQLCS); | ||
331 | + sqld.DataSource = GetDataSource(sqld.SQLCS); | ||
332 | + return sqld; | ||
333 | + } | ||
334 | + #endregion public CollectDataBaseInfo | ||
335 | + | ||
336 | + public static void RelocatePhysicalFiles(SQLDataBase sqld, string targetdirectory, string restoredbname) | ||
337 | + { | ||
338 | + var dbbackupfilepath = CreateBackup(sqld.Xml_BackupTargetDirectoryPath, sqld.SQLCS, sqld.Xml_BackupFileNameMask, false); | ||
339 | + RestoreBackup(sqld.SQLCS, dbbackupfilepath, targetdirectory, false, restoredbname); | ||
340 | + if (File.Exists(dbbackupfilepath)) { File.Delete(dbbackupfilepath); } | ||
341 | + } | ||
342 | + public static void RestoreBackup(string sqlcs, string sourcesqlbackupfilepath, string targetdbphysicalfilesdirectorypath, bool restorefromZIP = false, string restoretodbname = null) | ||
343 | + { | ||
344 | + string backupfilepath; | ||
345 | + if (restorefromZIP) | ||
346 | + { | ||
347 | + backupfilepath = Path.Combine(Path.GetDirectoryName(sourcesqlbackupfilepath), Path.GetFileNameWithoutExtension(sourcesqlbackupfilepath) + ".bak"); | ||
348 | + ZipTools.Extract1stFileFromZIP(backupfilepath, sourcesqlbackupfilepath); | ||
349 | + var starttime = DateTime.Now; | ||
350 | + while (DateTime.Now.Subtract(starttime).TotalSeconds > 5) { if (File.Exists(backupfilepath)) { break; } Thread.Sleep(500); } | ||
351 | + } | ||
352 | + else { backupfilepath = sourcesqlbackupfilepath; } | ||
353 | + var sqlserver = SQLServerConnect(sqlcs); | ||
354 | + | ||
355 | + var smoRestore = new Restore(); | ||
356 | + smoRestore.NoRecovery = false; | ||
357 | + smoRestore.ReplaceDatabase = true; | ||
358 | + smoRestore.Action = RestoreActionType.Database; | ||
359 | + smoRestore.PercentCompleteNotification = 5; | ||
360 | + var backupdevice = new BackupDeviceItem(backupfilepath, DeviceType.File); | ||
361 | + smoRestore.Devices.Add(backupdevice); | ||
362 | + smoRestore.Database = string.IsNullOrWhiteSpace(restoretodbname) | ||
363 | + ? smoRestore.ReadBackupHeader(sqlserver).Rows[0]["DatabaseName"].ToString() | ||
364 | + : restoretodbname; | ||
365 | + | ||
366 | + var dbfilelist = smoRestore.ReadFileList(sqlserver); | ||
367 | + var smorestoreDATfile = new RelocateFile(); | ||
368 | + string targetdbphysicalfilesdirectorypathDAT = targetdbphysicalfilesdirectorypath; | ||
369 | + if (string.IsNullOrEmpty(targetdbphysicalfilesdirectorypathDAT)) { targetdbphysicalfilesdirectorypathDAT = sqlserver.DefaultFile; } | ||
370 | + if (string.IsNullOrEmpty(targetdbphysicalfilesdirectorypathDAT)) { targetdbphysicalfilesdirectorypathDAT = sqlserver.MasterDBPath; } | ||
371 | + smorestoreDATfile.PhysicalFileName = Path.Combine(targetdbphysicalfilesdirectorypathDAT, smoRestore.Database + "_Data.mdf"); | ||
372 | + smorestoreDATfile.LogicalFileName = dbfilelist.Select("Type='D'")[0]["LogicalName"].ToString(); | ||
373 | + smoRestore.RelocateFiles.Add(smorestoreDATfile); | ||
374 | + | ||
375 | + var smorestoreLOGfile = new RelocateFile(); | ||
376 | + string targetdbphysicalfilesdirectorypathLOG = targetdbphysicalfilesdirectorypath; | ||
377 | + if (string.IsNullOrEmpty(targetdbphysicalfilesdirectorypathLOG)) { targetdbphysicalfilesdirectorypathLOG = sqlserver.DefaultLog; } | ||
378 | + if (string.IsNullOrEmpty(targetdbphysicalfilesdirectorypathLOG)) { targetdbphysicalfilesdirectorypathLOG = sqlserver.MasterDBLogPath; } | ||
379 | + smorestoreLOGfile.PhysicalFileName = Path.Combine(targetdbphysicalfilesdirectorypathLOG, smoRestore.Database + "_Log.ldf"); | ||
380 | + smorestoreLOGfile.LogicalFileName = dbfilelist.Select("Type='L'")[0]["LogicalName"].ToString(); | ||
381 | + smoRestore.RelocateFiles.Add(smorestoreLOGfile); | ||
382 | + | ||
383 | + sqlserver.KillAllProcesses(smoRestore.Database); | ||
384 | + | ||
385 | + smoRestore.SqlRestore(sqlserver); | ||
386 | + if (restorefromZIP) | ||
387 | + { | ||
388 | + if (File.Exists(backupfilepath)) { File.Delete(backupfilepath); } | ||
389 | + } | ||
390 | + } | ||
391 | + public static string CreateBackup(string backupdirectorypath, string sqlconnectionstring, string backupfilenamemask, bool createzip = false,DateTime? timestamp=null) | ||
392 | + { | ||
393 | + var sqlserver = SQLServerConnect(sqlconnectionstring); | ||
394 | + | ||
395 | + var backupts = (timestamp.HasValue ? timestamp.Value : DateTime.Now).ToString("yyyyMMddHHmmss"); | ||
396 | + | ||
397 | + string backupfileNameOnly = Path.GetFileNameWithoutExtension(backupfilenamemask); | ||
398 | + var vars = new Dictionary<string, string>(); | ||
399 | + vars.Add(nameof(DBSubstitutionName.DATABASE), GetDBName(sqlconnectionstring)); | ||
400 | + vars.Add(nameof(DBSubstitutionName.DATASOURCE), GetDataSource(sqlconnectionstring)); | ||
401 | + vars.Add(nameof(DBSubstitutionName.DBOTYPE), "DBBACKUP"); | ||
402 | + vars.Add(nameof(DBSubstitutionName.DBONAME), ""); | ||
403 | + vars.Add(nameof(DBSubstitutionName.DBDATAGROUP), ""); | ||
404 | + vars.Add(nameof(DBSubstitutionName.BACKUPTS), backupts); | ||
405 | + | ||
406 | + backupfileNameOnly = VRH.Common.StringConstructor.ResolveConstructor(vars, backupfileNameOnly, "{}@@"); | ||
407 | + | ||
408 | + string backupfilename = backupfileNameOnly + ".bak"; | ||
409 | + string backupFullName = Path.Combine(backupdirectorypath, backupfileNameOnly); | ||
410 | + if (File.Exists(backupFullName)) { File.Delete(backupFullName); } | ||
411 | + | ||
412 | + var smoBackup = new Backup(); | ||
413 | + smoBackup.Action = BackupActionType.Database; | ||
414 | + smoBackup.BackupSetDescription = $"Full Backup of {sqlserver.ConnectionContext.DatabaseName}"; | ||
415 | + smoBackup.BackupSetName = sqlserver.ConnectionContext.DatabaseName + " Backup"; | ||
416 | + smoBackup.Database = sqlserver.ConnectionContext.DatabaseName; | ||
417 | + smoBackup.MediaDescription = "Disk"; | ||
418 | + smoBackup.Devices.AddDevice(backupFullName, DeviceType.File); | ||
419 | + smoBackup.SqlBackup(sqlserver); | ||
420 | + | ||
421 | + if (createzip) | ||
422 | + { | ||
423 | + string ZIPbackupfilename = backupfileNameOnly + ".zip"; | ||
424 | + string ZIPbackupFullName = Path.Combine(backupdirectorypath, ZIPbackupfilename); | ||
425 | + if (File.Exists(ZIPbackupFullName)) { File.Delete(ZIPbackupFullName); } | ||
426 | + | ||
427 | + ZipTools.CreateEntriesFromDirectoryContent(backupdirectorypath, ZIPbackupFullName, backupfilename, "", removearchivedfiles: false, storepathinzip: false); | ||
428 | + if (File.Exists(backupFullName)) { File.Delete(backupFullName); } | ||
429 | + return ZIPbackupFullName; | ||
430 | + | ||
431 | + } | ||
432 | + return backupFullName; | ||
433 | + } | ||
434 | + | ||
435 | + #region private methods | ||
436 | + public static List<FileInfo> GetBackupFilePathList(SQLDataBase sqld) | ||
437 | + { | ||
438 | + var filenamemask = Path.GetFileNameWithoutExtension(sqld.Xml_BackupFileNameMask); | ||
439 | + var vars = new Dictionary<string, string>(); | ||
440 | + vars.Add(nameof(DBSubstitutionName.DATABASE), sqld.DBName); | ||
441 | + vars.Add(nameof(DBSubstitutionName.DATASOURCE), ""); | ||
442 | + vars.Add(nameof(DBSubstitutionName.DBOTYPE), "DBBACKUP"); | ||
443 | + vars.Add(nameof(DBSubstitutionName.DBONAME), ""); | ||
444 | + vars.Add(nameof(DBSubstitutionName.DBDATAGROUP), ""); | ||
445 | + vars.Add(nameof(DBSubstitutionName.BACKUPTS), "*"); | ||
446 | + filenamemask = VRH.Common.StringConstructor.ResolveConstructor(vars, filenamemask, "{}@@"); | ||
447 | + var filelist = new DirectoryInfo(sqld.Xml_BackupTargetDirectoryPath)?.GetFiles(filenamemask)?.ToList(); | ||
448 | + var filelistordered = filelist?.OrderByDescending(x => x.CreationTime).ToList(); | ||
449 | + return filelistordered; | ||
450 | + } | ||
451 | + | ||
452 | + /// <summary> | ||
453 | + /// Enable sa user and set/change its password | ||
454 | + /// </summary> | ||
455 | + /// <param name="cs"></param> | ||
456 | + /// <param name="password"></param> | ||
457 | + /// <param name="newsapassword"></param> | ||
458 | + /// <returns></returns> | ||
459 | + public static string ConfigureSaUser(string cs,string password, string newsapassword) | ||
460 | + { | ||
461 | + var sqlserver = SQLServerConnect(cs); | ||
462 | + sqlserver.Settings.LoginMode= ServerLoginMode.Mixed; | ||
463 | + sqlserver.Logins["sa"].Enable(); | ||
464 | + sqlserver.Logins.ItemById(10).Enable(); | ||
465 | + sqlserver.Logins["sa"].ChangePassword(newsapassword); | ||
466 | + sqlserver.Alter(); | ||
467 | + sqlserver.Logins["a"].Refresh(); | ||
468 | + return SQLServerConnect(cs).ConnectionContext.ConnectionString; | ||
469 | + } | ||
470 | + public static void ConfigureWindowsUser(string cs, string sapassword, string databasename, string windowsfullusername,string windowsuserpassword,List<string> rolenamelist) | ||
471 | + { | ||
472 | + var sqlserver = SQLServerConnect(cs); | ||
473 | + if (!sqlserver.Logins.Contains(windowsfullusername)) | ||
474 | + { | ||
475 | + var wul = new Microsoft.SqlServer.Management.Smo.Login(sqlserver, windowsfullusername); | ||
476 | + wul.LoginType = LoginType.WindowsUser; | ||
477 | + wul.Create(windowsuserpassword,LoginCreateOptions.None); | ||
478 | + if (!string.IsNullOrWhiteSpace(databasename)) | ||
479 | + { | ||
480 | + var dbobject = sqlserver.Databases[databasename]; | ||
481 | + if (dbobject==null) { throw new Exception($"Specified databas '{databasename}' does not exist!"); } | ||
482 | + if (dbobject.Users.Contains(windowsfullusername)) { dbobject.Users[windowsfullusername].Drop(); } | ||
483 | + var dbuser = new Microsoft.SqlServer.Management.Smo.User(dbobject, windowsfullusername); | ||
484 | + dbuser.Login = windowsfullusername; | ||
485 | + dbuser.Create(windowsuserpassword); | ||
486 | + foreach (var rn in rolenamelist) | ||
487 | + { | ||
488 | + var dbrole = dbobject.Roles[rn]; | ||
489 | + dbrole.AddMember(windowsfullusername); | ||
490 | + dbrole.Alter(); | ||
491 | + } | ||
492 | + } | ||
493 | + } | ||
494 | + } | ||
495 | + public static void DropDatabase(string cs,string databasename,string sapassword) | ||
496 | + { | ||
497 | + var sqlserver = SQLServerConnect(cs); | ||
498 | + if (sqlserver.Databases.Contains(databasename)) | ||
499 | + { | ||
500 | + sqlserver.KillAllProcesses(databasename); | ||
501 | + sqlserver.Databases[databasename].Drop(); | ||
502 | + } | ||
503 | + else { throw new Exception($"Specified databas '{databasename}' does not exist!"); } | ||
504 | + } | ||
505 | + public static string GetServerDefaultPhysicalDATFileLocation(string cs) | ||
506 | + { | ||
507 | + var sqlserver = SQLDataBaseManagerCore.SQLServerConnect(cs); | ||
508 | + return string.IsNullOrEmpty(sqlserver.DefaultFile) ? sqlserver.MasterDBPath : sqlserver.DefaultFile; | ||
509 | + } | ||
510 | + public static string GetServerDefaultPhysicalLOGFileLocation(string cs) | ||
511 | + { | ||
512 | + var sqlserver = SQLDataBaseManagerCore.SQLServerConnect(cs); | ||
513 | + return string.IsNullOrEmpty(sqlserver.DefaultLog) ? sqlserver.MasterDBLogPath : sqlserver.DefaultLog; | ||
514 | + } | ||
515 | + public static string GetDBName(string cs) | ||
516 | + { | ||
517 | + var sqlc = new Microsoft.Data.SqlClient.SqlConnection(cs); | ||
518 | + return sqlc.Database; | ||
519 | + } | ||
520 | + public static string GetDataSource(string cs) | ||
521 | + { | ||
522 | + var sqlc = new Microsoft.Data.SqlClient.SqlConnection(cs); | ||
523 | + return sqlc.DataSource; | ||
524 | + } | ||
525 | + public enum SQLDBStatus { NoAccess, OK, } | ||
526 | + public static SQLDBStatus GetStatus(string cs) | ||
527 | + { | ||
528 | + try { var s = GetPhysicalFilesLocation(cs); if (s == null) { throw new Exception(); }; return SQLDBStatus.OK; } catch { return SQLDBStatus.NoAccess; } | ||
529 | + } | ||
530 | + public static Server SQLServerConnect(string sqlconnectionstring) | ||
531 | + { | ||
532 | + try | ||
533 | + { | ||
534 | + var sqlconnection = new Microsoft.Data.SqlClient.SqlConnection(sqlconnectionstring); | ||
535 | + var serverconnection = new ServerConnection(sqlconnection); | ||
536 | + var sqlserver = new Server(serverconnection); | ||
537 | + if (string.IsNullOrEmpty(sqlserver.Information.Version.ToString())) { throw new Exception("Connection not established!"); } | ||
538 | + return sqlserver; | ||
539 | + } | ||
540 | + catch (Exception ex) { throw ex; } | ||
541 | + } | ||
542 | + #region GetPhysicalFilesLocation | ||
543 | + /// <summary> | ||
544 | + /// Returns the physical path to the directory that holds the files of the database | ||
545 | + /// </summary> | ||
546 | + /// <param name="sqlconnectionstring"></param> | ||
547 | + /// <returns>the path, or null, if any error occurs</returns> | ||
548 | + public static string GetPhysicalFilesLocation(string sqlconnectionstring) | ||
549 | + { | ||
550 | + int commandtimeout = 5000; | ||
551 | + string scripttext = ""; | ||
552 | + scripttext += " DECLARE @physicalpath varchar(1000) = NULL;"; | ||
553 | + scripttext += " SELECT @physicalpath = f.physical_name"; | ||
554 | + scripttext += " FROM sys.master_files as f inner join sys.databases as d on f.database_id = d.database_id"; | ||
555 | + scripttext += " where d.name = '{DATABASE}' and f.type_desc = 'ROWS';"; | ||
556 | + scripttext += " SELECT 1 AS RETURNCODE, @physicalpath AS RETURNMESSAGE;"; | ||
557 | + var vars = new Dictionary<string, string>(); | ||
558 | + vars.Add(nameof(DBSubstitutionName.DATABASE), GetDBName(sqlconnectionstring)); | ||
559 | + vars.Add(nameof(DBSubstitutionName.DATASOURCE), ""); | ||
560 | + var result = ExecuteSQLScript(sqlconnectionstring, scripttext, commandtimeout, vars); | ||
561 | + if (result.ReturnValue != 0) { return Path.GetDirectoryName(result.ReturnMessage); } else { return null; }; | ||
562 | + } | ||
563 | + #endregion GetPhysicalFilesLocation | ||
564 | + #region DBSubstitution | ||
565 | + public enum DBSubstitutionName | ||
566 | + { | ||
567 | + DATABASE,DATASOURCE,DBOTYPE,DBONAME,DBDATAGROUP,BACKUPTS, | ||
568 | + } | ||
569 | + #endregion DBSubstitution | ||
570 | + #region ExecuteSQLScript | ||
571 | + /// <summary> | ||
572 | + /// Egy SQL script végrehajtása (GO-val lezárt batch-eket tartalmazhat) | ||
573 | + /// </summary> | ||
574 | + /// <param name="sqlconnectionstring">sql connection string</param> | ||
575 | + /// <param name="sqltxt">a script</param> | ||
576 | + /// <param name="commandtimeout">az egyes batch-ek végrehajtási időzítése</param> | ||
577 | + /// <param name="vars"> | ||
578 | + /// behelyettesítendő változók (a scriptben ezek nevei {} között kell legyenek) | ||
579 | + /// a következő neveket felismeri akkor is, ha nincsenek benne a sztótárban: | ||
580 | + /// DATASOURCE: a sql server neve domain/név formában | ||
581 | + /// DATABASE: az aadatbázis neve | ||
582 | + /// </param> | ||
583 | + /// <returns> | ||
584 | + /// egy ReturnInfoJSON struktúrát, amiben a ReturnValue és ReturnMessage a script által előállított két | ||
585 | + /// (egy int és egy string) értéket tartalmazza pl. egy ilyen eredményt: SELECT @returncode, @returnmessage; | ||
586 | + /// Ha a végrehajtás nem ad vissza eredményt, akkor az első érték 0, a második pedig null; | ||
587 | + /// | ||
588 | + /// </returns> | ||
589 | + public static ReturnInfoJSON ExecuteSQLScript(string sqlconnectionstring, string sqltxt, int commandtimeout, Dictionary<string, string> vars) | ||
590 | + { | ||
591 | + var sqlc = new Microsoft.Data.SqlClient.SqlConnection(sqlconnectionstring); | ||
592 | + | ||
593 | + sqltxt = VRH.Common.StringConstructor.ResolveConstructor(vars, sqltxt, "{}@@"); | ||
594 | + | ||
595 | + sqlc.Open(); | ||
596 | + string SQLBatchTxt = ""; // ebben lesznek az sql script-en belüli batch-ek összerakva | ||
597 | + int SQLBatchIndex = 0; // az aktuális batch indexe | ||
598 | + int scriptlineindex = 0; // az aktuális script sor indexe | ||
599 | + System.Data.DataSet DataSet = null; // ebben lesz az eredmény (az utolsó batch eredménye) | ||
600 | + sqltxt += "\r\nGO";// ha esetleg nem lenne, odatesszük a végére az utolsó batch-et lezáró GO-t | ||
601 | + foreach (var scriptline in sqltxt.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) | ||
602 | + { | ||
603 | + scriptlineindex += 1; | ||
604 | + if (Regex.Match(scriptline, @"^GO$").Success)// a batch utolső sora | ||
605 | + { | ||
606 | + if (!string.IsNullOrWhiteSpace(SQLBatchTxt)) | ||
607 | + { | ||
608 | + SQLBatchIndex += 1; | ||
609 | + DataSet = ExecuteSQLScriptBatch(sqlc, SQLBatchTxt, commandtimeout); | ||
610 | + SQLBatchTxt = ""; | ||
611 | + } | ||
612 | + } | ||
613 | + else if (!string.IsNullOrWhiteSpace(scriptline)) | ||
614 | + { | ||
615 | + SQLBatchTxt += scriptline + "\r\n"; | ||
616 | + } | ||
617 | + } | ||
618 | + sqlc.Close(); | ||
619 | + if (DataSet != null && DataSet.Tables != null) | ||
620 | + { | ||
621 | + var firstreturnedtable = DataSet.Tables[0]; | ||
622 | + var firstreturnedrow = firstreturnedtable.Rows[0]; | ||
623 | + var firstreturnedvalue = firstreturnedrow[0]; | ||
624 | + var secondreturnedvalue = firstreturnedrow[1]; | ||
625 | + var rv = Convert.ToInt32(firstreturnedvalue); | ||
626 | + var rm = Convert.ToString(secondreturnedvalue); | ||
627 | + return new ReturnInfoJSON() { ReturnValue = rv, ReturnMessage = rm, }; | ||
628 | + } | ||
629 | + else { return new ReturnInfoJSON() { ReturnValue = 0, ReturnMessage = null, }; } | ||
630 | + } | ||
631 | + private static System.Data.DataSet ExecuteSQLScriptBatch(Microsoft.Data.SqlClient.SqlConnection sqlc, string sqlbatchtxt, int commandtimeout) | ||
632 | + { | ||
633 | + var sqlcommand = sqlc.CreateCommand(); | ||
634 | + sqlcommand.CommandText = sqlbatchtxt; | ||
635 | + sqlcommand.CommandTimeout = commandtimeout; | ||
636 | + var DataAdapter = new Microsoft.Data.SqlClient.SqlDataAdapter(sqlcommand); | ||
637 | + var DataSet = new System.Data.DataSet(); | ||
638 | + DataAdapter.Fill(DataSet); | ||
639 | + return DataSet; | ||
640 | + } | ||
641 | + #endregion ExecuteSQLScript | ||
642 | + #region ExecuteSQLStoredProcedure | ||
643 | + /// <summary> | ||
644 | + /// Egy SQL script végrehajtása (GO-val lezárt batch-eket tartalmazhat) | ||
645 | + /// </summary> | ||
646 | + /// <param name="sqlconnectionstring">sql connection string</param> | ||
647 | + /// <param name="sqltxt">a script</param> | ||
648 | + /// <param name="commandtimeout">az egyes batch-ek végrehajtási időzítése</param> | ||
649 | + /// <param name="vars"> | ||
650 | + /// behelyettesítendő változók (a scriptben ezek nevei {} között kell legyenek) | ||
651 | + /// a következő neveket felismeri akkor is, ha nincsenek benne a sztótárban: | ||
652 | + /// DATASOURCE: a sql server neve domain/név formában | ||
653 | + /// DATABASE: az aadatbázis neve | ||
654 | + /// </param> | ||
655 | + /// <returns> | ||
656 | + /// egy ReturnInfoJSON struktúrát, amiben a ReturnValue és ReturnMessage a script által előállított két | ||
657 | + /// (egy int és egy string) értéket tartalmazza pl. egy ilyen eredményt: SELECT @returncode, @returnmessage; | ||
658 | + /// Ha a végrehajtás nem ad vissza eredményt, akkor az első érték 0, a második pedig null; | ||
659 | + /// | ||
660 | + /// </returns> | ||
661 | + public class SPparameter | ||
662 | + { | ||
663 | + public string Name; | ||
664 | + public object Value; | ||
665 | + public System.Data.SqlDbType Type; | ||
666 | + public int Typepar; | ||
667 | + public System.Data.ParameterDirection Direction; | ||
668 | + public SPparameter() { } | ||
669 | + public SPparameter(Microsoft.Data.SqlClient.SqlParameter p) | ||
670 | + { | ||
671 | + Name = p.ParameterName; | ||
672 | + Value = p.Value; | ||
673 | + Type = p.SqlDbType; | ||
674 | + Typepar = p.Size; | ||
675 | + Direction = p.Direction; | ||
676 | + } | ||
677 | + } | ||
678 | + | ||
679 | + public static List<SPparameter> ExecuteSQLStoredProcedure(string sqlconnectionstring, string storedprocedurename, int commandtimeout, List<SPparameter> SPparameters) | ||
680 | + { | ||
681 | + var sqlc = new Microsoft.Data.SqlClient.SqlConnection(sqlconnectionstring); | ||
682 | + var sqlcommand = sqlc.CreateCommand(); | ||
683 | + sqlcommand.Connection = sqlc; | ||
684 | + sqlcommand.CommandText = storedprocedurename; | ||
685 | + sqlcommand.CommandTimeout = commandtimeout; | ||
686 | + sqlcommand.CommandType= System.Data.CommandType.StoredProcedure; | ||
687 | + //var DataAdapter = new Microsoft.Data.SqlClient.SqlDataAdapter(sqlcommand); | ||
688 | + sqlc.Open(); | ||
689 | + foreach (var p in SPparameters) | ||
690 | + { | ||
691 | + var sqlparameter = new Microsoft.Data.SqlClient.SqlParameter() | ||
692 | + { | ||
693 | + ParameterName = p.Name, | ||
694 | + SqlDbType = p.Type, | ||
695 | + Size = p.Typepar, | ||
696 | + Direction = p.Direction, | ||
697 | + Value = p.Value, | ||
698 | + }; | ||
699 | + sqlcommand.Parameters.Add(sqlparameter); | ||
700 | + } | ||
701 | + sqlcommand.ExecuteNonQuery(); | ||
702 | + | ||
703 | + var sqlresult = new List<SPparameter>(); | ||
704 | + foreach (var p in SPparameters) | ||
705 | + { | ||
706 | + if (p.Direction == System.Data.ParameterDirection.Output) | ||
707 | + { | ||
708 | + sqlresult.Add(new SPparameter(sqlcommand.Parameters[p.Name])); | ||
709 | + } | ||
710 | + } | ||
711 | + sqlc.Close(); | ||
712 | + return sqlresult; | ||
713 | + } | ||
714 | + #endregion ExecuteSQLStoredProcedure | ||
715 | + #region BackupSqlScripts | ||
716 | + public static void BackupSqlScripts(string backupdirectorypath,string backupfilenamemask,string sqlcs,bool createZip, DateTime? timestamp=null) | ||
717 | + { | ||
718 | + var sqlserver = SQLServerConnect(sqlcs); | ||
719 | + if (sqlserver!=null) | ||
720 | + { | ||
721 | + string backupts = (timestamp.HasValue? timestamp.Value:DateTime.Now).ToString("yyyyMMddHHmmss"); | ||
722 | + var vars = new Dictionary<string, string>(); | ||
723 | + vars.Add(nameof(DBSubstitutionName.DATABASE), GetDBName(sqlcs)); | ||
724 | + vars.Add(nameof(DBSubstitutionName.DATASOURCE), GetDataSource(sqlcs)); | ||
725 | + vars.Add(nameof(DBSubstitutionName.BACKUPTS), backupts); | ||
726 | + vars.Add(nameof(DBSubstitutionName.DBOTYPE), "Scripts"); | ||
727 | + | ||
728 | + string zipfilefullpath = null; | ||
729 | + string tempbackupdirectorypath; | ||
730 | + if (createZip) | ||
731 | + { | ||
732 | + vars[nameof(DBSubstitutionName.DBONAME)] = ""; | ||
733 | + vars[nameof(DBSubstitutionName.DBDATAGROUP)] = ""; | ||
734 | + string zipfilename = VRH.Common.StringConstructor.ResolveConstructor(vars, backupfilenamemask, "{}@@") + ".zip"; | ||
735 | + zipfilefullpath = Path.Combine(backupdirectorypath, zipfilename); | ||
736 | + tempbackupdirectorypath = Path.Combine(backupdirectorypath, "TEMP_" + Path.GetFileNameWithoutExtension(zipfilename)); | ||
737 | + if (Directory.Exists(tempbackupdirectorypath)) { Directory.Delete(tempbackupdirectorypath, recursive: true); } | ||
738 | + if (!Directory.Exists(tempbackupdirectorypath)) { Directory.CreateDirectory(tempbackupdirectorypath); } | ||
739 | + } | ||
740 | + else { tempbackupdirectorypath = backupdirectorypath; } | ||
741 | + | ||
742 | + if (!Directory.Exists(backupdirectorypath)) { Directory.CreateDirectory(backupdirectorypath); } | ||
743 | + var directorynameonly = new DirectoryInfo(backupdirectorypath).Name; | ||
744 | + var backupfilenameext = Path.GetExtension(backupfilenamemask); if (string.IsNullOrWhiteSpace(backupfilenameext)) { backupfilenameext = ".sql"; } | ||
745 | + backupfilenamemask = Path.GetFileNameWithoutExtension(backupfilenamemask); | ||
746 | + var sqldatabase = sqlserver.Databases[sqlserver.ConnectionContext.DatabaseName]; | ||
747 | + | ||
748 | + ScriptOneObject(sqlserver, tempbackupdirectorypath, backupfilenamemask + backupfilenameext, new List<SqlSmoObject> { sqldatabase }, vars); | ||
749 | + ScriptOneObject(sqlserver, tempbackupdirectorypath, backupfilenamemask + backupfilenameext, sqldatabase.UserDefinedFunctions.Cast<SqlSmoObject>().ToList(), vars); | ||
750 | + ScriptOneObject(sqlserver, tempbackupdirectorypath, backupfilenamemask + backupfilenameext, sqldatabase.StoredProcedures.Cast<SqlSmoObject>().ToList(), vars); | ||
751 | + ScriptOneObject(sqlserver, tempbackupdirectorypath, backupfilenamemask + backupfilenameext, sqldatabase.Views.Cast<SqlSmoObject>().ToList(), vars); | ||
752 | + ScriptOneObject(sqlserver, tempbackupdirectorypath, backupfilenamemask + backupfilenameext, sqldatabase.Tables.Cast<SqlSmoObject>().ToList(), vars); | ||
753 | + ScriptOneObject(sqlserver, tempbackupdirectorypath, backupfilenamemask + backupfilenameext, sqldatabase.Triggers.Cast<SqlSmoObject>().ToList(), vars); | ||
754 | + if (createZip) | ||
755 | + { | ||
756 | + ZipTools.CreateEntriesFromDirectoryContent(tempbackupdirectorypath, zipfilefullpath, "*.sql", backupts,removearchivedfiles:true, storepathinzip: false); | ||
757 | + } | ||
758 | + } | ||
759 | + | ||
760 | + } | ||
761 | + private static void ScriptOneObject(Server sqlserver,string backupdirectory,string backupfilenamemask,List<SqlSmoObject> sqldbobjects,Dictionary<string, string> vars) | ||
762 | + { | ||
763 | + var sqldbname = sqlserver.ConnectionContext.DatabaseName; | ||
764 | + string lastfilename = null; | ||
765 | + foreach (var sqldbobj in sqldbobjects) | ||
766 | + { | ||
767 | + bool systemobject = true; | ||
768 | + try { systemobject = sqldbobj.Properties["IsSystemObject"].Value.ToString().ToUpper() == bool.TrueString.ToUpper(); } catch { } | ||
769 | + if (systemobject) { continue; } | ||
770 | + | ||
771 | + string namevalue=null; | ||
772 | + if (namevalue == null) { try { namevalue = Tools.GetPropertyValue<string>(sqldbobj, "Name"); } catch { namevalue = null; } } | ||
773 | + if (namevalue == null) { try { namevalue = sqldbobj.Properties["Name"].Value.ToString(); } catch { namevalue = null; } } | ||
774 | + if (namevalue == null) { namevalue = "UNDEFINED"; } | ||
775 | + | ||
776 | + vars[nameof(DBSubstitutionName.DBONAME)]=namevalue; | ||
777 | + vars[nameof(DBSubstitutionName.DBDATAGROUP)]=sqldbobj.GetType().Name; | ||
778 | + | ||
779 | + string filename = VRH.Common.StringConstructor.ResolveConstructor(vars, backupfilenamemask, "{}@@"); | ||
780 | + if (lastfilename!=filename) | ||
781 | + { | ||
782 | + var i = 2; | ||
783 | + string filenamesav = filename; | ||
784 | + while (true) | ||
785 | + { | ||
786 | + if (!File.Exists(filename)) { break; } | ||
787 | + filename = filenamesav + $" ({i})"; | ||
788 | + i++; | ||
789 | + } | ||
790 | + using (var sw = File.AppendText(Path.Combine(backupdirectory, filename))) | ||
791 | + { | ||
792 | + sw.WriteLine($"use [{sqldbname}]"); | ||
793 | + } | ||
794 | + lastfilename = filename; | ||
795 | + } | ||
796 | + var myscripter = new Microsoft.SqlServer.Management.Smo.Scripter(); | ||
797 | + myscripter.Server = sqlserver; | ||
798 | + myscripter.Options.FileName = Path.Combine(backupdirectory, filename); | ||
799 | + myscripter.Options.AppendToFile = true; | ||
800 | + myscripter.Options.ScriptSchema = true; | ||
801 | + myscripter.Options.ScriptData = false; | ||
802 | + myscripter.Options.SchemaQualify = true; | ||
803 | + myscripter.Options.AllowSystemObjects = false; | ||
804 | + myscripter.Options.IncludeHeaders = true; | ||
805 | + myscripter.Options.IncludeIfNotExists = true; | ||
806 | + myscripter.Options.ClusteredIndexes = true; | ||
807 | + myscripter.Options.DriAll = true; | ||
808 | + myscripter.Options.ToFileOnly = true; | ||
809 | + myscripter.Options.Indexes = true; | ||
810 | + myscripter.Options.Permissions = true; | ||
811 | + myscripter.Options.WithDependencies = false; | ||
812 | + myscripter.Options.AnsiFile=true; | ||
813 | + | ||
814 | + var o = new SqlSmoObject[] { sqldbobj }; | ||
815 | + //create the drop statement | ||
816 | + myscripter.Options.ScriptDrops = true; | ||
817 | + List<string> scripttexts = myscripter.Script(o).Cast<string>().ToList(); | ||
818 | + //create the create statement | ||
819 | + myscripter.Options.ScriptDrops = false; | ||
820 | + List<string> scripttexts2 = myscripter.Script(o).Cast<string>().ToList(); | ||
821 | + } | ||
822 | + return; | ||
823 | + } | ||
824 | + #endregion BackupSqlScripts | ||
825 | + #region BackupSqlData | ||
826 | + public static void BackupSqlData(SQLDataBase sqld,DateTime? timestamp=null) | ||
827 | + { | ||
828 | + string sqlcs = sqld.SQLCS; | ||
829 | + var sqlserver = SQLServerConnect(sqlcs); | ||
830 | + if (sqlserver != null) | ||
831 | + { | ||
832 | + string backupts = (timestamp.HasValue ? timestamp.Value : DateTime.Now).ToString("yyyyMMddHHmmss"); | ||
833 | + bool createZip = sqld.Xml_CreateZip; | ||
834 | + string backupdirectorypath = sqld.Xml_BackupTargetDirectoryPath; | ||
835 | + string backupfilenamemask = sqld.Xml_BackupFileNameMask; | ||
836 | + | ||
837 | + var backupfilenameext = Path.GetExtension(backupfilenamemask); if (string.IsNullOrWhiteSpace(backupfilenameext)) { backupfilenameext = ".sql"; } | ||
838 | + backupfilenamemask = Path.GetFileNameWithoutExtension(backupfilenamemask); | ||
839 | + | ||
840 | + var vars = new Dictionary<string, string>(); | ||
841 | + vars.Add(nameof(DBSubstitutionName.DATABASE), GetDBName(sqlcs)); | ||
842 | + vars.Add(nameof(DBSubstitutionName.DATASOURCE), GetDataSource(sqlcs)); | ||
843 | + vars.Add(nameof(DBSubstitutionName.BACKUPTS), backupts); | ||
844 | + vars.Add(nameof(DBSubstitutionName.DBOTYPE), "TableData"); | ||
845 | + | ||
846 | + string zipfilefullpath=null; | ||
847 | + string tempbackupdirectorypath; | ||
848 | + if (createZip) | ||
849 | + { | ||
850 | + vars[nameof(DBSubstitutionName.DBONAME)] = ""; | ||
851 | + vars[nameof(DBSubstitutionName.DBDATAGROUP)] = ""; | ||
852 | + string zipfilename = VRH.Common.StringConstructor.ResolveConstructor(vars, backupfilenamemask, "{}@@") + ".zip"; | ||
853 | + tempbackupdirectorypath = Path.Combine(backupdirectorypath, "TEMP_"+Path.GetFileNameWithoutExtension(zipfilename)); | ||
854 | + zipfilefullpath = Path.Combine(backupdirectorypath, zipfilename); | ||
855 | + if (Directory.Exists(tempbackupdirectorypath)) { Directory.Delete(tempbackupdirectorypath, recursive: true); } | ||
856 | + if (!Directory.Exists(tempbackupdirectorypath)) { Directory.CreateDirectory(tempbackupdirectorypath); } | ||
857 | + } | ||
858 | + else { tempbackupdirectorypath = backupdirectorypath; } | ||
859 | + | ||
860 | + | ||
861 | + if (!Directory.Exists(backupdirectorypath)) { Directory.CreateDirectory(backupdirectorypath); } | ||
862 | + | ||
863 | + | ||
864 | + List<string> backupfilepathlist = new List<string>(); | ||
865 | + foreach (var sqldata in sqld.Xml_SQLDataList) | ||
866 | + { | ||
867 | + vars[nameof(DBSubstitutionName.DBDATAGROUP)] = sqldata.Group; | ||
868 | + var sqlfilescreated = ScriptOneDataGroup(sqlserver, tempbackupdirectorypath, backupfilenamemask + backupfilenameext, sqldata.TableNameList, vars); | ||
869 | + backupfilepathlist.AddRange(sqlfilescreated); | ||
870 | + } | ||
871 | + | ||
872 | + if (createZip) | ||
873 | + { | ||
874 | + string fullpathregex = Regex.Escape(string.Join(";",backupfilepathlist)).Replace(';','|'); | ||
875 | + ZipTools.CreateEntriesFromDirectoryContent(tempbackupdirectorypath, zipfilefullpath, "*.sql", fullpathregex, removearchivedfiles: true, storepathinzip: false); | ||
876 | + } | ||
877 | + } | ||
878 | + } | ||
879 | + private static List<string> ScriptOneDataGroup(Server sqlserver, string backupdirectorypath, string backupfilenamemask, List<string> tablenamelist, Dictionary<string, string> vars) | ||
880 | + { | ||
881 | + string filename =null , filefullname=null, lastfilefullname = null; | ||
882 | + var myscripter = new Microsoft.SqlServer.Management.Smo.Scripter(); | ||
883 | + myscripter.Server = sqlserver; | ||
884 | + myscripter.Options.ScriptSchema = false; | ||
885 | + myscripter.Options.ScriptData = true; | ||
886 | + myscripter.Options.NoCommandTerminator = true; | ||
887 | + myscripter.Options.FileName = null; | ||
888 | + myscripter.Options.ToFileOnly = true; | ||
889 | + myscripter.Options.AnsiFile = true; | ||
890 | + //myscripter.Options.AppendToFile = true; | ||
891 | + //myscripter.Options.SchemaQualify = true; | ||
892 | + //myscripter.Options.AllowSystemObjects = false; | ||
893 | + //myscripter.Options.IncludeHeaders = true; | ||
894 | + //myscripter.Options.IncludeIfNotExists = true; | ||
895 | + //myscripter.Options.ClusteredIndexes = true; | ||
896 | + //myscripter.Options.DriAll = true; | ||
897 | + //myscripter.Options.Indexes = true; | ||
898 | + //myscripter.Options.Permissions = true; | ||
899 | + //myscripter.Options.WithDependencies = false; | ||
900 | + var backupfilelist = new List<string>(); | ||
901 | + var urnstoscript = new UrnCollection(); | ||
902 | + var deletefromlist = new List<string>(); | ||
903 | + foreach (var tn in tablenamelist) | ||
904 | + { | ||
905 | + string tn_dbname = tn.Split('.')[0]; | ||
906 | + tn_dbname = sqlserver.ConnectionContext.DatabaseName; | ||
907 | + string tn_schemaname = tn.Split('.')[1]; | ||
908 | + string tn_name = tn.Split('.')[2]; | ||
909 | + vars[nameof(DBSubstitutionName.DBONAME)] = $"{tn_schemaname}.{tn_name}"; | ||
910 | + filename = VRH.Common.StringConstructor.ResolveConstructor(vars, backupfilenamemask, "{}@@"); | ||
911 | + filefullname = Path.Combine(backupdirectorypath, filename); | ||
912 | + if (lastfilefullname!=filefullname && lastfilefullname!=null) | ||
913 | + { | ||
914 | + backupfilelist.Add(CreateOneSqlFile(urnstoscript, deletefromlist,sqlserver, myscripter, lastfilefullname)); | ||
915 | + lastfilefullname = filefullname; | ||
916 | + deletefromlist.Clear(); | ||
917 | + urnstoscript.Clear(); | ||
918 | + } | ||
919 | + //powershell: $Urn = "$($sqlserver.Urn)/Database[@Name='$($tuple.Database)']/Table[@Name='$($tuple.Table)' and @Schema='$($tuple.Schema)']"; | ||
920 | + string urnstring = $"{sqlserver.Urn}/Database[@Name='{tn_dbname}']/Table[@Name='{tn_name}' and @Schema='{tn_schemaname}']"; | ||
921 | + deletefromlist=deletefromlist.Prepend($"DELETE FROM [{tn_dbname}].[{tn_schemaname}].[{tn_name}]\r\nGO").ToList();// törlés sorrendje fordított a létrehozáséhoz képest! | ||
922 | + urnstoscript.Add(new Microsoft.SqlServer.Management.Sdk.Sfc.Urn(urnstring)); | ||
923 | + lastfilefullname = filefullname; | ||
924 | + } | ||
925 | + backupfilelist.Add(CreateOneSqlFile(urnstoscript, deletefromlist,sqlserver,myscripter,filefullname)); | ||
926 | + return backupfilelist; | ||
927 | + } | ||
928 | + private static string CreateOneSqlFile( UrnCollection urnstoscript,List<string> deletefromlist,Server sqlserver,Scripter myscripter, string sqlfilefullname) | ||
929 | + { | ||
930 | + myscripter.Options.FileName = sqlfilefullname; | ||
931 | + if (urnstoscript.Any()) { myscripter.EnumScript(urnstoscript); } | ||
932 | + var scripttext = File.ReadAllText(sqlfilefullname); | ||
933 | + deletefromlist = deletefromlist.Prepend($"use [{sqlserver.ConnectionContext.DatabaseName}]").ToList(); | ||
934 | + File.WriteAllText(sqlfilefullname, string.Join("\r\n",deletefromlist) +"\r\n\r\n" + scripttext, Encoding.UTF8);//???????????????? | ||
935 | + return sqlfilefullname; | ||
936 | + } | ||
937 | + #endregion BackupSqlData | ||
938 | + #endregion private methods | ||
939 | + } | ||
940 | + #endregion class SQLDataBaseManager | ||
941 | + | ||
942 | + #region SQLDataBaseManager class | ||
943 | + public class SQLDataBaseManagerXmlProcessor : XmlParser | ||
944 | + { | ||
945 | + #region fields | ||
946 | + private List<SQLDataBase> _sqldatabaselist; | ||
947 | + #endregion fields | ||
948 | + #region constructor | ||
949 | + public SQLDataBaseManagerXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) | ||
950 | + { | ||
951 | + _sqldatabaselist = new List<SQLDataBase>(); | ||
952 | + var schtskxmllist = GetAllXElements(nameof(SQLDataBase.XmlStructure.SQLDataBase)); | ||
953 | + var common = new SQLDataBase() | ||
954 | + { | ||
955 | + Xml_CreateZip = GetValue(nameof(SQLDataBase.XmlStructure.Attributes.CreateZip), this.RootElement, SQLDataBase.XmlStructure.Attributes.CreateZip.Values.DEFAULT), | ||
956 | + Xml_BackupFileNameMask = GetValue(nameof(SQLDataBase.XmlStructure.Attributes.BackupFileNameMask), this.RootElement, SQLDataBase.XmlStructure.Attributes.BackupFileNameMask.Values.DEFAULT), | ||
957 | + Xml_RestoreFileNameMask = GetValue(nameof(SQLDataBase.XmlStructure.Attributes.RestoreFileNameMask), this.RootElement, SQLDataBase.XmlStructure.Attributes.RestoreFileNameMask.Values.DEFAULT), | ||
958 | + Xml_BackupTargetDirectoryPath = GetValue(nameof(SQLDataBase.XmlStructure.Attributes.BackupTargetDirectoryPath), this.RootElement, SQLDataBase.XmlStructure.Attributes.BackupTargetDirectoryPath.Values.DEFAULT), | ||
959 | + Xml_PhysicalFilesDirectoryPath = GetValue(nameof(SQLDataBase.XmlStructure.Attributes.PhysicalFilesDirectoryPath), this.RootElement, SQLDataBase.XmlStructure.Attributes.PhysicalFilesDirectoryPath.Values.DEFAULT), | ||
960 | + | ||
961 | + }; | ||
962 | + if (schtskxmllist != null && schtskxmllist.Any()) | ||
963 | + { | ||
964 | + foreach (var schtskxml in schtskxmllist) { var st = new SQLDataBase(schtskxml,common); if (st.Valid) { _sqldatabaselist.Add(st); } } | ||
965 | + } | ||
966 | + } | ||
967 | + #endregion constructor | ||
968 | + #region GetDefinitionList | ||
969 | + public List<SQLDataBase> GetDefinitionList() { return _sqldatabaselist; } | ||
970 | + #endregion GetDefinitionList | ||
971 | + } | ||
972 | + #endregion SQLDataBaseManager class | ||
973 | + | ||
974 | + #region SQLDataBase class | ||
975 | + public class SQLDataBase : XmlLinqBase | ||
976 | + { | ||
977 | + #region fields | ||
978 | + public bool Valid = true; | ||
979 | + public bool Xml_CreateZip= true; | ||
980 | + public string Xml_Key; | ||
981 | + public string Xml_Description; | ||
982 | + public string Xml_BackupFileNameMask; | ||
983 | + public string Xml_RestoreFileNameMask; | ||
984 | + public string Xml_BackupTargetDirectoryPath; | ||
985 | + public string Xml_SQLConnectionString; | ||
986 | + public string Xml_PhysicalFilesDirectoryPath; | ||
987 | + public List<SQLData> Xml_SQLDataList; | ||
988 | + | ||
989 | + public string DBName; | ||
990 | + public string DataSource; | ||
991 | + public SQLDataBaseManagerCore.SQLDBStatus Status; | ||
992 | + public string PhysicalFilesDirectoryPath; | ||
993 | + public string SQLCS | ||
994 | + { | ||
995 | + get { return XmlProcessing.ConnectionStringStore.GetSQL(this.Xml_SQLConnectionString); } | ||
996 | + } | ||
997 | + #endregion fields | ||
998 | + | ||
999 | + #region basic constructor | ||
1000 | + public SQLDataBase() { } | ||
1001 | + #endregion basic constructor | ||
1002 | + #region xml constructor | ||
1003 | + public SQLDataBase(XElement sqldatabasexml, SQLDataBase common) | ||
1004 | + { | ||
1005 | + Valid = true; | ||
1006 | + string ATTRIBUTEMANDATORY = nameof(XmlStructure.SQLDataBase) + " attribute is mandatory! Name: {0}"; | ||
1007 | + Xml_Key= GetValue(nameof(XmlStructure.SQLDataBase.Attributes.Key), sqldatabasexml, XmlStructure.SQLDataBase.Attributes.Key.Values.DEFAULT); | ||
1008 | + Xml_Description = sqldatabasexml.Attribute(XName.Get(nameof(XmlStructure.SQLDataBase.Attributes.Description)))?.Value; | ||
1009 | + if (string.IsNullOrWhiteSpace(Xml_Description)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, nameof(XmlStructure.SQLDataBase.Attributes.Description))); } | ||
1010 | + Xml_BackupFileNameMask = GetValue(nameof(XmlStructure.SQLDataBase.Attributes.BackupFileNameMask), sqldatabasexml, common.Xml_BackupFileNameMask); | ||
1011 | + Xml_RestoreFileNameMask = GetValue(nameof(XmlStructure.SQLDataBase.Attributes.RestoreFileNameMask), sqldatabasexml, common.Xml_RestoreFileNameMask); | ||
1012 | + Xml_BackupTargetDirectoryPath = GetValue(nameof(XmlStructure.SQLDataBase.Attributes.BackupTargetDirectoryPath), sqldatabasexml, common.Xml_BackupTargetDirectoryPath); | ||
1013 | + Xml_SQLConnectionString = GetValue(nameof(XmlStructure.SQLDataBase.Attributes.SQLConnectionString), sqldatabasexml, XmlStructure.SQLDataBase.Attributes.SQLConnectionString.Values.DEFAULT); | ||
1014 | + | ||
1015 | + var sqldataXmlList = GetAllXElements(sqldatabasexml, nameof(XmlStructure.SQLDataBase.SQLData)); | ||
1016 | + Xml_CreateZip = GetValue(nameof(XmlStructure.SQLDataBase.Attributes.CreateZip), sqldatabasexml, common.Xml_CreateZip); | ||
1017 | + Xml_PhysicalFilesDirectoryPath = GetValue(nameof(XmlStructure.SQLDataBase.Attributes.PhysicalFilesDirectoryPath), sqldatabasexml, common.Xml_PhysicalFilesDirectoryPath); | ||
1018 | + Xml_SQLDataList = new List<SQLData>(); | ||
1019 | + if (sqldataXmlList!=null) { foreach (var sqldataXml in sqldataXmlList) { Xml_SQLDataList.Add(new SQLData(sqldataXml)); } } | ||
1020 | + } | ||
1021 | + #endregion xml constructor | ||
1022 | + #region cloner constructor | ||
1023 | + public SQLDataBase(SQLDataBase sqld) | ||
1024 | + { | ||
1025 | + Valid = sqld.Valid; | ||
1026 | + Xml_CreateZip = sqld.Xml_CreateZip; | ||
1027 | + Xml_Key = sqld.Xml_Key; | ||
1028 | + Xml_Description = sqld.Xml_Description; | ||
1029 | + Xml_BackupFileNameMask = sqld.Xml_BackupFileNameMask; | ||
1030 | + Xml_RestoreFileNameMask = sqld.Xml_RestoreFileNameMask; | ||
1031 | + Xml_BackupTargetDirectoryPath = sqld.Xml_BackupTargetDirectoryPath; | ||
1032 | + Xml_SQLConnectionString = sqld.Xml_SQLConnectionString; | ||
1033 | + Xml_PhysicalFilesDirectoryPath = sqld.Xml_PhysicalFilesDirectoryPath; | ||
1034 | + Xml_SQLDataList = sqld.Xml_SQLDataList.Select(x => x).ToList(); | ||
1035 | + } | ||
1036 | + #endregion cloner constructor | ||
1037 | + #region XmlStructure | ||
1038 | + public static class XmlStructure | ||
1039 | + { | ||
1040 | + public static class Attributes | ||
1041 | + { | ||
1042 | + public static class BackupFileNameMask { public static class Values { public const string DEFAULT = ""; } } | ||
1043 | + public static class RestoreFileNameMask { public static class Values { public const string DEFAULT = ""; } } | ||
1044 | + public static class BackupTargetDirectoryPath { public static class Values { public const string DEFAULT = ""; } } | ||
1045 | + public static class PhysicalFilesDirectoryPath { public static class Values { public const string DEFAULT = ""; } } | ||
1046 | + | ||
1047 | + | ||
1048 | + public static class CreateZip{ public static class Values { public const bool DEFAULT = true; } } | ||
1049 | + } | ||
1050 | + public static class SQLDataBase | ||
1051 | + { | ||
1052 | + public static class Attributes | ||
1053 | + { | ||
1054 | + public static class Key { public static class Values { public const string DEFAULT = ""; } } | ||
1055 | + public static class Description { } | ||
1056 | + public static class SQLConnectionString { public static class Values { public const string DEFAULT = ""; } } | ||
1057 | + public static class BackupFileNameMask { } | ||
1058 | + public static class RestoreFileNameMask { } | ||
1059 | + public static class BackupTargetDirectoryPath { } | ||
1060 | + public static class CreateZip { } | ||
1061 | + public static class PhysicalFilesDirectoryPath { } | ||
1062 | + } | ||
1063 | + public static class SQLData | ||
1064 | + { | ||
1065 | + public static class Values { public const string DEFAULT = ""; } | ||
1066 | + public static class Attributes | ||
1067 | + { | ||
1068 | + public static class Group { public static class Values { public const string DEFAULT = ""; } } | ||
1069 | + } | ||
1070 | + } | ||
1071 | + } | ||
1072 | + } | ||
1073 | + #endregion XmlStructure | ||
1074 | + #region SQLData class | ||
1075 | + public class SQLData : XmlLinqBase | ||
1076 | + { | ||
1077 | + #region fields | ||
1078 | + public string Group = ""; | ||
1079 | + public List<string> TableNameList; | ||
1080 | + #endregion fields | ||
1081 | + #region constructors | ||
1082 | + public SQLData() { } | ||
1083 | + public SQLData(SQLData sqld) { Group = sqld.Group; TableNameList = sqld.TableNameList.Select(x => x).ToList(); } | ||
1084 | + public SQLData(XElement sqldXml) | ||
1085 | + { | ||
1086 | + Group = GetValue(nameof(XmlStructure.SQLDataBase.SQLData.Attributes.Group), sqldXml, XmlStructure.SQLDataBase.SQLData.Attributes.Group.Values.DEFAULT); | ||
1087 | + string tablenamecommalist = GetValue(sqldXml, XmlStructure.SQLDataBase.SQLData.Values.DEFAULT); | ||
1088 | + if (string.IsNullOrWhiteSpace(tablenamecommalist)) { TableNameList = new List<string>(); } | ||
1089 | + else | ||
1090 | + { | ||
1091 | + var temptablenamelist = tablenamecommalist.Split(new char[]{ ','},StringSplitOptions.RemoveEmptyEntries).ToList(); | ||
1092 | + TableNameList = new List<string>(); | ||
1093 | + foreach (string tn in temptablenamelist) | ||
1094 | + { | ||
1095 | + var tnparts = tn.Split('.'); | ||
1096 | + string fullqualifiedname = null; | ||
1097 | + switch (tnparts.Length) | ||
1098 | + { | ||
1099 | + case 1: fullqualifiedname = $"{{DBNAME}}.dbo.{tnparts[0]}"; break; | ||
1100 | + case 2: fullqualifiedname = $"{{DBNAME}}.{tnparts[0]}.{tnparts[1]}"; break; | ||
1101 | + case 3: fullqualifiedname = tn; break; | ||
1102 | + default: throw new Exception($"Table name is incorrect! {nameof(SQLData)} Type:{Group}, table name:{tn}."); | ||
1103 | + } | ||
1104 | + TableNameList.Add(fullqualifiedname); | ||
1105 | + } | ||
1106 | + } | ||
1107 | + } | ||
1108 | + #endregion constructors | ||
1109 | + } | ||
1110 | + #endregion SQLData class | ||
1111 | + } | ||
1112 | + #endregion SQLDataBase class | ||
1113 | +} |
Vrh.Log4Pro.MaintenanceConsole/Manager - ScheduledTaskManager.cs
@@ -12,72 +12,56 @@ using Microsoft.Web.Administration; | @@ -12,72 +12,56 @@ using Microsoft.Web.Administration; | ||
12 | using System.Management; | 12 | using System.Management; |
13 | using System.Diagnostics; | 13 | using System.Diagnostics; |
14 | 14 | ||
15 | +using Vrh.Log4Pro.MaintenanceConsole.MenuNS; | ||
16 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
17 | +using Vrh.Log4Pro.MaintenanceConsole.ToolsNS; | ||
18 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
19 | + | ||
15 | using Vrh.XmlProcessing; | 20 | using Vrh.XmlProcessing; |
16 | using VRH.Common; | 21 | using VRH.Common; |
17 | using System.Xml.Linq; | 22 | using System.Xml.Linq; |
18 | using System.Text.RegularExpressions; | 23 | using System.Text.RegularExpressions; |
19 | 24 | ||
20 | -namespace Vrh.Log4Pro.MaintenanceConsole | 25 | +namespace Vrh.Log4Pro.MaintenanceConsole.ScheduledTaskManagerNS |
21 | { | 26 | { |
22 | #region ScheduledTaskManager class | 27 | #region ScheduledTaskManager class |
23 | - public static class ScheduledTaskmanagerManager | 28 | + public static class ScheduledTaskManager |
24 | { | 29 | { |
25 | - private const string XMLCONNECTIONSTRING = "file=Config.Xml;element=ScheduledTasks;"; | 30 | + private const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE_SCHEDULEDTASKMANAGER;"; |
31 | + private const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;element=ScheduledTasks;"; | ||
26 | 32 | ||
27 | #region Execute | 33 | #region Execute |
28 | public static object Execute(object o1 = null, object o2 = null) | 34 | public static object Execute(object o1 = null, object o2 = null) |
29 | { | 35 | { |
30 | - var args = o1 as string[]; | ||
31 | - var module = CommandLine.GetCommandLineArgument(args, "-MODULE"); | ||
32 | - var functionkey = CommandLine.GetCommandLineArgument(args, "-FUNCTION"); | 36 | + var args = (o1 as Menu.ExecutorParameter).Args; |
37 | + var functionkey = CommandLine.GetCommandLineArgument(args, CLP.CMD_FUNCTION); | ||
33 | 38 | ||
34 | - string xmlcs = XMLCONNECTIONSTRING; | ||
35 | - var config = new ScheduledTaskManagerCoreXmlProcessor(xmlcs, "", "hu-HU"); | 39 | + var config = new ScheduledTaskManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); |
40 | + var ep = new Menu.ExecutorParameter(config, args); | ||
36 | var menufunctions = new Menu("Manage Scheduled tasks", "Select the management function!") | 41 | 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 | - } | 42 | + .AddMenuItem(new Menu.Item(CLP.Module.ScheduledTaskManager.Function.Install.KEY, "Install scheduled task", Install, ep)) |
43 | + .AddMenuItem(new Menu.Item(CLP.Module.ScheduledTaskManager.Function.Install.KEY, "Uninstall scheduled task", Uninstall, ep)) | ||
44 | + .AddMenuItem(new Menu.Item(CLP.Module.ScheduledTaskManager.Function.Install.KEY, "Start scheduled task", Run, ep)) | ||
45 | + .AddMenuItem(new Menu.Item(CLP.Module.ScheduledTaskManager.Function.Install.KEY, "Stop scheduled task", End, ep)) | ||
46 | + .AddMenuItem(new Menu.Item(CLP.Module.ScheduledTaskManager.Function.Install.KEY, "Enable scheduled task", Enable, ep)) | ||
47 | + .AddMenuItem(new Menu.Item(CLP.Module.ScheduledTaskManager.Function.Install.KEY, "Disable scheduled task", Disable, ep)) | ||
48 | + .AddMenuItem(new Menu.Item(CLP.Module.ScheduledTaskManager.Function.Install.KEY, "Change scheduled task priority", ChangePriority, ep)) | ||
49 | + .SetSelectionMode(Menu.SelectionMode.Single) | ||
50 | + .SetMenuHeaderDisplayer(ScheduledTaskListDisplayer); | ||
51 | + menufunctions.ExecuteMenu(functionkey); | ||
61 | return o2; | 52 | return o2; |
62 | } | 53 | } |
63 | #endregion Execute | 54 | #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 | 55 | + |
72 | #region First level Executors with UI | 56 | #region First level Executors with UI |
73 | private static object ChangePriority(object parameter, object o) | 57 | private static object ChangePriority(object parameter, object o) |
74 | { | 58 | { |
75 | - var config = (parameter as ScheduledTaskExecutorParameter).Config; | ||
76 | - var args = (parameter as ScheduledTaskExecutorParameter).Args; | 59 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<ScheduledTaskManagerXmlProcessor>(); |
60 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
77 | 61 | ||
78 | - var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS"); | 62 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); |
79 | 63 | ||
80 | - var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(ChangePriority)}'!"); | 64 | + var menufolders = DisplayScheduledTaskMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(ChangePriority)}'!",silent:true); |
81 | 65 | ||
82 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); | 66 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); |
83 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 67 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
@@ -87,7 +71,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -87,7 +71,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
87 | else { } | 71 | else { } |
88 | foreach (var p in sr.SelectedParameterList) | 72 | foreach (var p in sr.SelectedParameterList) |
89 | { | 73 | { |
90 | - ScheduledTask st = p as ScheduledTask; | 74 | + ScheduledTask st = p.Parameters as ScheduledTask; |
91 | try | 75 | try |
92 | { | 76 | { |
93 | ScheduledTaskManagerCore.SetPriority(st.Xml_Name,st.Xml_Priority); | 77 | ScheduledTaskManagerCore.SetPriority(st.Xml_Name,st.Xml_Priority); |
@@ -99,12 +83,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -99,12 +83,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
99 | } | 83 | } |
100 | private static object Disable(object parameter, object o) | 84 | private static object Disable(object parameter, object o) |
101 | { | 85 | { |
102 | - var config = (parameter as ScheduledTaskExecutorParameter).Config; | ||
103 | - var args = (parameter as ScheduledTaskExecutorParameter).Args; | 86 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<ScheduledTaskManagerXmlProcessor>(); |
87 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
104 | 88 | ||
105 | - var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS"); | 89 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); |
106 | 90 | ||
107 | - var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Disable)}'!"); | 91 | + var menufolders = DisplayScheduledTaskMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(Disable)}'!", silent:true); |
108 | 92 | ||
109 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); | 93 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); |
110 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 94 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
@@ -114,7 +98,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -114,7 +98,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
114 | else { } | 98 | else { } |
115 | foreach (var p in sr.SelectedParameterList) | 99 | foreach (var p in sr.SelectedParameterList) |
116 | { | 100 | { |
117 | - ScheduledTask st = p as ScheduledTask; | 101 | + ScheduledTask st = p.Parameters as ScheduledTask; |
118 | try | 102 | try |
119 | { | 103 | { |
120 | ScheduledTaskManagerCore.DisableTask(st.Xml_Name); | 104 | ScheduledTaskManagerCore.DisableTask(st.Xml_Name); |
@@ -126,12 +110,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -126,12 +110,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
126 | } | 110 | } |
127 | private static object Enable(object parameter, object o) | 111 | private static object Enable(object parameter, object o) |
128 | { | 112 | { |
129 | - var config = (parameter as ScheduledTaskExecutorParameter).Config; | ||
130 | - var args = (parameter as ScheduledTaskExecutorParameter).Args; | 113 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<ScheduledTaskManagerXmlProcessor>(); |
114 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
131 | 115 | ||
132 | - var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS"); | 116 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); |
133 | 117 | ||
134 | - var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Enable)}'!"); | 118 | + var menufolders = DisplayScheduledTaskMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(Enable)}'!", silent: true); |
135 | 119 | ||
136 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); | 120 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); |
137 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 121 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
@@ -141,7 +125,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -141,7 +125,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
141 | else { } | 125 | else { } |
142 | foreach (var p in sr.SelectedParameterList) | 126 | foreach (var p in sr.SelectedParameterList) |
143 | { | 127 | { |
144 | - ScheduledTask st = p as ScheduledTask; | 128 | + ScheduledTask st = p.Parameters as ScheduledTask; |
145 | try | 129 | try |
146 | { | 130 | { |
147 | ScheduledTaskManagerCore.EnableTask(st.Xml_Name); | 131 | ScheduledTaskManagerCore.EnableTask(st.Xml_Name); |
@@ -153,12 +137,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -153,12 +137,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
153 | } | 137 | } |
154 | private static object End(object parameter, object o) | 138 | private static object End(object parameter, object o) |
155 | { | 139 | { |
156 | - var config = (parameter as ScheduledTaskExecutorParameter).Config; | ||
157 | - var args = (parameter as ScheduledTaskExecutorParameter).Args; | 140 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<ScheduledTaskManagerXmlProcessor>(); |
141 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
158 | 142 | ||
159 | - var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS"); | 143 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); |
160 | 144 | ||
161 | - var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(End)}'!"); | 145 | + var menufolders = DisplayScheduledTaskMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(End)}'!", silent: true); |
162 | 146 | ||
163 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); | 147 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); |
164 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 148 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
@@ -168,7 +152,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -168,7 +152,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
168 | else { } | 152 | else { } |
169 | foreach (var p in sr.SelectedParameterList) | 153 | foreach (var p in sr.SelectedParameterList) |
170 | { | 154 | { |
171 | - ScheduledTask st = p as ScheduledTask; | 155 | + ScheduledTask st = p.Parameters as ScheduledTask; |
172 | try | 156 | try |
173 | { | 157 | { |
174 | ScheduledTaskManagerCore.EndTask(st.Xml_Name); | 158 | ScheduledTaskManagerCore.EndTask(st.Xml_Name); |
@@ -180,12 +164,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -180,12 +164,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
180 | } | 164 | } |
181 | private static object Run(object parameter, object o) | 165 | private static object Run(object parameter, object o) |
182 | { | 166 | { |
183 | - var config = (parameter as ScheduledTaskExecutorParameter).Config; | ||
184 | - var args = (parameter as ScheduledTaskExecutorParameter).Args; | 167 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<ScheduledTaskManagerXmlProcessor>(); |
168 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
185 | 169 | ||
186 | - var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS"); | 170 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); |
187 | 171 | ||
188 | - var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Run)}'!"); | 172 | + var menufolders = DisplayScheduledTaskMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(Run)}'!", silent: true); |
189 | 173 | ||
190 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); | 174 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); |
191 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 175 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
@@ -195,7 +179,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -195,7 +179,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
195 | else { } | 179 | else { } |
196 | foreach (var p in sr.SelectedParameterList) | 180 | foreach (var p in sr.SelectedParameterList) |
197 | { | 181 | { |
198 | - ScheduledTask st = p as ScheduledTask; | 182 | + ScheduledTask st = p.Parameters as ScheduledTask; |
199 | try | 183 | try |
200 | { | 184 | { |
201 | ScheduledTaskManagerCore.RunTask(st.Xml_Name); | 185 | ScheduledTaskManagerCore.RunTask(st.Xml_Name); |
@@ -210,12 +194,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -210,12 +194,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
210 | } | 194 | } |
211 | private static object Uninstall(object parameter, object o) | 195 | private static object Uninstall(object parameter, object o) |
212 | { | 196 | { |
213 | - var config = (parameter as ScheduledTaskExecutorParameter).Config; | ||
214 | - var args = (parameter as ScheduledTaskExecutorParameter).Args; | 197 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<ScheduledTaskManagerXmlProcessor>(); |
198 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
215 | 199 | ||
216 | - var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS"); | 200 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); |
217 | 201 | ||
218 | - var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Uninstall)}'!"); | 202 | + var menufolders = DisplayScheduledTaskMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(Uninstall)}'!", silent: true); |
219 | 203 | ||
220 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); | 204 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); |
221 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 205 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
@@ -225,7 +209,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -225,7 +209,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
225 | else { } | 209 | else { } |
226 | foreach (var p in sr.SelectedParameterList) | 210 | foreach (var p in sr.SelectedParameterList) |
227 | { | 211 | { |
228 | - ScheduledTask st = p as ScheduledTask; | 212 | + ScheduledTask st = p.Parameters as ScheduledTask; |
229 | try | 213 | try |
230 | { | 214 | { |
231 | ScheduledTaskManagerCore.EndTask(st.Xml_Name); | 215 | ScheduledTaskManagerCore.EndTask(st.Xml_Name); |
@@ -238,12 +222,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -238,12 +222,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
238 | } | 222 | } |
239 | private static object Install(object parameter, object o) | 223 | private static object Install(object parameter, object o) |
240 | { | 224 | { |
241 | - var config = (parameter as ScheduledTaskExecutorParameter).Config; | ||
242 | - var args = (parameter as ScheduledTaskExecutorParameter).Args; | 225 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<ScheduledTaskManagerXmlProcessor>(); |
226 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
243 | 227 | ||
244 | - var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, "-TASKS"); | 228 | + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); |
245 | 229 | ||
246 | - var menufolders = DisplayTasks(config, $"Select the scheduled task(s) to manage with function '{nameof(Install)}'!"); | 230 | + var menufolders = DisplayScheduledTaskMenu(config, $"Select the scheduled task(s) to manage with function '{nameof(Install)}'!", silent: true); |
247 | 231 | ||
248 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); | 232 | Menu.Selection sr = menufolders.Select(selectedtaskindexes); |
249 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 233 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
@@ -253,7 +237,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -253,7 +237,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
253 | else { } | 237 | else { } |
254 | foreach (var p in sr.SelectedParameterList) | 238 | foreach (var p in sr.SelectedParameterList) |
255 | { | 239 | { |
256 | - ScheduledTask st = p as ScheduledTask; | 240 | + ScheduledTask st = p.Parameters as ScheduledTask; |
257 | try | 241 | try |
258 | { | 242 | { |
259 | ScheduledTaskManagerCore.EndTask(st.Xml_Name); | 243 | ScheduledTaskManagerCore.EndTask(st.Xml_Name); |
@@ -269,27 +253,28 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -269,27 +253,28 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
269 | 253 | ||
270 | #region private methods | 254 | #region private methods |
271 | #region private DisplayTasks | 255 | #region private DisplayTasks |
272 | - private static Menu DisplayTasks(ScheduledTaskManagerCoreXmlProcessor config,string prompt = null) | 256 | + private static void ScheduledTaskListDisplayer() { DisplayScheduledTaskMenu(); } |
257 | + private static Menu DisplayScheduledTaskMenu(ScheduledTaskManagerXmlProcessor config = null, string prompt = null, bool silent = false) | ||
273 | { | 258 | { |
259 | + if (config == null) { config = new ScheduledTaskManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); } | ||
274 | List<ScheduledTask> schtskdefList = config.GetDefinitionList(); | 260 | List<ScheduledTask> schtskdefList = config.GetDefinitionList(); |
275 | - var menufct = new Menu("Scheduled tasks",prompt) | 261 | + var menufct = new Menu("Scheduled tasks", prompt) |
276 | .SetMenuItemDisplayer(DisplayTaskInfo) | 262 | .SetMenuItemDisplayer(DisplayTaskInfo) |
277 | - .SetSelectionMode(Menu.SelectionMode.Multi) | ||
278 | - .SetHeaderWidth(4); | 263 | + .SetSelectionMode(Menu.SelectionMode.Multi); |
279 | menufct.ClearMenuItemList(); | 264 | menufct.ClearMenuItemList(); |
280 | foreach (var schtskdef in schtskdefList) | 265 | foreach (var schtskdef in schtskdefList) |
281 | { | 266 | { |
282 | - var st = CollectTaskInfo(schtskdef); | ||
283 | - menufct.AddMenuItem(new Menu.Item(null, null, null, st)); | 267 | + var st = ScheduledTaskManagerCore.CollectTaskInfo(schtskdef); |
268 | + menufct.AddMenuItem(new Menu.Item(schtskdef.Xml_Key, null, null, new Menu.ExecutorParameter(pars: st))); | ||
284 | } | 269 | } |
285 | - menufct.DisplayItems(1); | 270 | + if (!silent) { menufct.DisplayItems(1); } |
286 | return menufct; | 271 | return menufct; |
287 | } | 272 | } |
288 | #endregion private DisplayTasks | 273 | #endregion private DisplayTasks |
289 | #region private method: DisplayTaskInfo | 274 | #region private method: DisplayTaskInfo |
290 | private static object DisplayTaskInfo(object obj, int lineix) | 275 | private static object DisplayTaskInfo(object obj, int lineix) |
291 | { | 276 | { |
292 | - ScheduledTask st = obj as ScheduledTask; | 277 | + ScheduledTask st = (obj as Menu.ExecutorParameter).Parameters as ScheduledTask; |
293 | if (lineix == 0) | 278 | if (lineix == 0) |
294 | { | 279 | { |
295 | ColorConsole.Write($"{st.Xml_Name}", ConsoleColor.Black, ConsoleColor.White); | 280 | ColorConsole.Write($"{st.Xml_Name}", ConsoleColor.Black, ConsoleColor.White); |
@@ -316,8 +301,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -316,8 +301,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
316 | return null; | 301 | return null; |
317 | } | 302 | } |
318 | #endregion private method: DisplayTaskInfo | 303 | #endregion private method: DisplayTaskInfo |
319 | - #region private CollectTaskInfo | ||
320 | - private static ScheduledTask CollectTaskInfo(ScheduledTask schtsk) | 304 | + #endregion private methods |
305 | + } | ||
306 | + #endregion ScheduledTaskManager class | ||
307 | + | ||
308 | + #region class ScheduledTaskManagerCore | ||
309 | + public static class ScheduledTaskManagerCore | ||
310 | + { | ||
311 | + #region public CollectTaskInfo | ||
312 | + public static ScheduledTask CollectTaskInfo(ScheduledTask schtsk) | ||
321 | { | 313 | { |
322 | string status = Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Query /FO TABLE /TN {schtsk.Xml_Name}"); | 314 | string status = Tools.ExecuteAndGetStdIo("schtasks.exe", $"/Query /FO TABLE /TN {schtsk.Xml_Name}"); |
323 | 315 | ||
@@ -326,7 +318,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -326,7 +318,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
326 | var statuslines = status.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); | 318 | var statuslines = status.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); |
327 | var statussplitted = statuslines[3] | 319 | var statussplitted = statuslines[3] |
328 | .Split(new string[] { " ", "+" }, StringSplitOptions.RemoveEmptyEntries); | 320 | .Split(new string[] { " ", "+" }, StringSplitOptions.RemoveEmptyEntries); |
329 | - if (statussplitted[1]=="N/A") | 321 | + if (statussplitted[1] == "N/A") |
330 | { | 322 | { |
331 | schtsk.NextRun = ""; | 323 | schtsk.NextRun = ""; |
332 | schtsk.Priority = -1; | 324 | schtsk.Priority = -1; |
@@ -354,14 +346,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -354,14 +346,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
354 | } | 346 | } |
355 | return schtsk; | 347 | return schtsk; |
356 | } | 348 | } |
357 | - #endregion private CollectTaskInfo | ||
358 | - #endregion private methods | ||
359 | - } | ||
360 | - #endregion ScheduledTaskManager class | 349 | + #endregion public CollectTaskInfo |
361 | 350 | ||
362 | - #region class ScheduledTaskManagerCore | ||
363 | - public static class ScheduledTaskManagerCore | ||
364 | - { | ||
365 | public static int GetPriority(string taskname) | 351 | public static int GetPriority(string taskname) |
366 | { | 352 | { |
367 | try | 353 | try |
@@ -409,7 +395,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -409,7 +395,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
409 | public static void CreateTask(ScheduledTask st) | 395 | public static void CreateTask(ScheduledTask st) |
410 | { | 396 | { |
411 | string taskname = st.Xml_Name; | 397 | string taskname = st.Xml_Name; |
412 | - string tasktorunpars = st.Xml_Commandname; | 398 | + string tasktorunpars = st.Xml_Commandname.Quote(); |
413 | 399 | ||
414 | string schedulepars = ""; | 400 | string schedulepars = ""; |
415 | if (st.Xml_Schedule==nameof(ScheduledTask.XmlStructure.ScheduledTask.Attributes.Schedule.Values.MONTHLY)) { schedulepars += "/SC MONTHLY /D 1"; } | 401 | if (st.Xml_Schedule==nameof(ScheduledTask.XmlStructure.ScheduledTask.Attributes.Schedule.Values.MONTHLY)) { schedulepars += "/SC MONTHLY /D 1"; } |
@@ -424,6 +410,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -424,6 +410,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
424 | string prioritypars = "/RL HIGHEST"; | 410 | string prioritypars = "/RL HIGHEST"; |
425 | 411 | ||
426 | var args = $"/Create /TR {tasktorunpars} {schedulepars} {starttimepars} {passwordpars} {forcecreatepars} {prioritypars} /TN {taskname}"; | 412 | var args = $"/Create /TR {tasktorunpars} {schedulepars} {starttimepars} {passwordpars} {forcecreatepars} {prioritypars} /TN {taskname}"; |
413 | + | ||
427 | var result = Tools.ExecuteAndGetStdIo("schtasks.exe", args); | 414 | var result = Tools.ExecuteAndGetStdIo("schtasks.exe", args); |
428 | 415 | ||
429 | if (st.Xml_Enable) { EnableTask(taskname); } else { DisableTask(taskname); } | 416 | if (st.Xml_Enable) { EnableTask(taskname); } else { DisableTask(taskname); } |
@@ -433,11 +420,11 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -433,11 +420,11 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
433 | #endregion class ScheduledTaskManagerCore | 420 | #endregion class ScheduledTaskManagerCore |
434 | 421 | ||
435 | #region ScheduledTaskManagerCoreXmlProcessor class | 422 | #region ScheduledTaskManagerCoreXmlProcessor class |
436 | - public class ScheduledTaskManagerCoreXmlProcessor : XmlParser | 423 | + public class ScheduledTaskManagerXmlProcessor : XmlParser |
437 | { | 424 | { |
438 | private List<ScheduledTask> _scheduledtasklist; | 425 | private List<ScheduledTask> _scheduledtasklist; |
439 | #region constructor | 426 | #region constructor |
440 | - public ScheduledTaskManagerCoreXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) | 427 | + public ScheduledTaskManagerXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) |
441 | { | 428 | { |
442 | _scheduledtasklist = new List<ScheduledTask>(); | 429 | _scheduledtasklist = new List<ScheduledTask>(); |
443 | var schtskxmllist = GetAllXElements(nameof(ScheduledTask.XmlStructure.ScheduledTask)); | 430 | var schtskxmllist = GetAllXElements(nameof(ScheduledTask.XmlStructure.ScheduledTask)); |
@@ -458,6 +445,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -458,6 +445,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
458 | { | 445 | { |
459 | #region fields | 446 | #region fields |
460 | public bool Valid = true; | 447 | public bool Valid = true; |
448 | + public string Xml_Key; | ||
461 | public string Xml_Name; | 449 | public string Xml_Name; |
462 | public int Xml_Priority; | 450 | public int Xml_Priority; |
463 | public string Xml_Schedule; | 451 | public string Xml_Schedule; |
@@ -495,6 +483,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -495,6 +483,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
495 | { | 483 | { |
496 | Valid = true; | 484 | Valid = true; |
497 | string ATTRIBUTEMANDATORY = nameof(XmlStructure.ScheduledTask) + " attribute is mandatory! Name: {0}"; | 485 | string ATTRIBUTEMANDATORY = nameof(XmlStructure.ScheduledTask) + " attribute is mandatory! Name: {0}"; |
486 | + Xml_Key= GetValue(nameof(XmlStructure.ScheduledTask.Attributes.Key), scheduledtaskxml, XmlStructure.ScheduledTask.Attributes.Key.Values.DEFAULT); | ||
498 | Xml_Name = scheduledtaskxml.Attribute(XName.Get(nameof(XmlStructure.ScheduledTask.Attributes.Name)))?.Value; | 487 | 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))); } | 488 | 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); | 489 | Xml_Priority = GetValue(nameof(XmlStructure.ScheduledTask.Attributes.Priority), scheduledtaskxml, XmlStructure.ScheduledTask.Attributes.Priority.Values.DEFAULT); |
@@ -502,7 +491,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -502,7 +491,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
502 | Xml_StartTime = DateTime.Parse(GetValue(nameof(XmlStructure.ScheduledTask.Attributes.StartTime), scheduledtaskxml, XmlStructure.ScheduledTask.Attributes.StartTime.Values.DEFAULT)); | 491 | 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); | 492 | 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); | 493 | 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, ""); | 494 | + Xml_Commandname = GetValue(nameof(XmlStructure.ScheduledTask.Attributes.Command), scheduledtaskxml, ""); |
506 | //var conditionxmlList = GetAllXElements(foldertocleanxml, nameof(XmlStructure.FolderToClean.Conditions), nameof(XmlStructure.FolderToClean.Conditions.Condition)); | 495 | //var conditionxmlList = GetAllXElements(foldertocleanxml, nameof(XmlStructure.FolderToClean.Conditions), nameof(XmlStructure.FolderToClean.Conditions.Condition)); |
507 | } | 496 | } |
508 | #endregion xml constructor | 497 | #endregion xml constructor |
@@ -510,6 +499,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -510,6 +499,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
510 | public ScheduledTask(ScheduledTask ftc) | 499 | public ScheduledTask(ScheduledTask ftc) |
511 | { | 500 | { |
512 | Valid = ftc.Valid; | 501 | Valid = ftc.Valid; |
502 | + Xml_Key= ftc.Xml_Key; | ||
513 | Xml_Name = ftc.Xml_Name; | 503 | Xml_Name = ftc.Xml_Name; |
514 | Xml_Priority = ftc.Xml_Priority; | 504 | Xml_Priority = ftc.Xml_Priority; |
515 | Xml_Schedule = ftc.Xml_Schedule; | 505 | Xml_Schedule = ftc.Xml_Schedule; |
@@ -526,14 +516,9 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -526,14 +516,9 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
526 | { | 516 | { |
527 | public static class Attributes | 517 | public static class Attributes |
528 | { | 518 | { |
519 | + public static class Key { public static class Values { public const string DEFAULT = ""; } } | ||
529 | public static class Name { } | 520 | 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 | - } | 521 | + public static class StartTime { public static class Values { public const string DEFAULT = "04:00"; } } |
537 | public static class Priority | 522 | public static class Priority |
538 | { | 523 | { |
539 | public static class Values | 524 | public static class Values |
@@ -567,7 +552,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -567,7 +552,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
567 | public const bool DEFAULT = false; | 552 | public const bool DEFAULT = false; |
568 | } | 553 | } |
569 | } | 554 | } |
570 | - public static class Commandname { } | 555 | + public static class Command { } |
571 | } | 556 | } |
572 | } | 557 | } |
573 | } | 558 | } |
Vrh.Log4Pro.MaintenanceConsole/Manager - UserManager.cs
0 → 100644
@@ -0,0 +1,236 @@ | @@ -0,0 +1,236 @@ | ||
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.Log4Pro.MaintenanceConsole.MenuNS; | ||
16 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
17 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
18 | +using Vrh.Log4Pro.MaintenanceConsole.ToolsNS; | ||
19 | + | ||
20 | +using Vrh.XmlProcessing; | ||
21 | +using System.Xml.Linq; | ||
22 | +using System.Text.RegularExpressions; | ||
23 | + | ||
24 | +namespace Vrh.Log4Pro.MaintenanceConsole.UserManagerNS | ||
25 | +{ | ||
26 | + #region MaintenanceTools class | ||
27 | + public static class UserManager | ||
28 | + { | ||
29 | + private static Log4ProUserManagerXmlProcessor Config; | ||
30 | + private const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE_LOG4PROUSERMANAGER;"; | ||
31 | + private const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;element=Log4ProUserManager;"; | ||
32 | + | ||
33 | + #region Execute | ||
34 | + public static object Execute(object o1 = null, object o2 = null) | ||
35 | + { | ||
36 | + var args = (o1 as Menu.ExecutorParameter).Args; | ||
37 | + string xmlcs = XMLCONNECTIONSTRING; | ||
38 | + var config = new Log4ProUserManagerXmlProcessor(xmlcs, "", "hu-HU"); | ||
39 | + Config = config; | ||
40 | + var sqlcs = XmlProcessing.ConnectionStringStore.GetSQL(config.Xml_SQLConnectionString); | ||
41 | + MembershipTools.SetConnectionString(sqlcs); | ||
42 | + | ||
43 | + var menufunctions = new Menu("Log4Pro User Manager", "Select function!") | ||
44 | + .AddMenuItem(new Menu.Item(CLP.Module.Log4ProUserManager.Functions.CreateSuperuser.KEY, "Create superuser", CreateSuperuser, new Menu.ExecutorParameter(cfg: config))) | ||
45 | + .AddMenuItem(new Menu.Item(CLP.Module.Log4ProUserManager.Functions.CreateAdminusers.KEY, "Create Admin and Administrator roles and users", CreateAdminusers, new Menu.ExecutorParameter(cfg: config, null))) | ||
46 | + .AddMenuItem(new Menu.Item(CLP.Module.Log4ProUserManager.Functions.DeleteUsers.KEY, "Remove user", DeleteUsers, new Menu.ExecutorParameter(cfg: config, null))) | ||
47 | + .SetMenuHeaderDisplayer(UserListDisplayer) | ||
48 | + .SetSelectionMode(Menu.SelectionMode.Single); | ||
49 | + menufunctions.ExecuteMenu(); | ||
50 | + return null; | ||
51 | + } | ||
52 | + #endregion Execute | ||
53 | + #region private UserListDisplayer | ||
54 | + private static void UserListDisplayer() | ||
55 | + { | ||
56 | + int totallinelength = 0; | ||
57 | + ColorConsole.Write("", ConsoleColor.Yellow, prefix: "Usernames:"); | ||
58 | + foreach (var un in MembershipTools.Users.GetNameList(null)) | ||
59 | + { | ||
60 | + var predefined = Config.ProtectedUser(un); | ||
61 | + totallinelength += un.Length + (predefined?3:2); | ||
62 | + if (totallinelength > ColorConsole.BufferWidth) { ColorConsole.WriteLine(""); } | ||
63 | + ColorConsole.Write("["); | ||
64 | + if (predefined) { ColorConsole.Write("*", ConsoleColor.Red); } | ||
65 | + ColorConsole.Write(un, ConsoleColor.Yellow); | ||
66 | + ColorConsole.Write("]"); | ||
67 | + } | ||
68 | + ColorConsole.WriteLine(""); | ||
69 | + } | ||
70 | + #endregion private UserListDisplayer | ||
71 | + | ||
72 | + #region First level Executors with UI | ||
73 | + #region CreateSuperuser | ||
74 | + private static object CreateSuperuser(object parameter, object o) | ||
75 | + { | ||
76 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<Log4ProUserManagerXmlProcessor>(); | ||
77 | + var suname = ColorConsole.ReadLine($"Enter Superuser name:", ConsoleColor.Yellow); | ||
78 | + if (suname == "EX") { return null; } | ||
79 | + var supsw = ColorConsole.ReadLine($"Enter Superuser password:", ConsoleColor.Yellow); | ||
80 | + if (supsw == "EX") { return null; } | ||
81 | + | ||
82 | + try | ||
83 | + { | ||
84 | + MembershipTools.Users.Create(suname, supsw, superuser: true); | ||
85 | + ColorConsole.WriteLine($"Creating superuser '{suname}' was successful!", ConsoleColor.Green); | ||
86 | + } | ||
87 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
88 | + return o; | ||
89 | + } | ||
90 | + #endregion CreateSuperuser | ||
91 | + #region CreateAdminusers | ||
92 | + private static object CreateAdminusers(object parameter, object o) | ||
93 | + { | ||
94 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<Log4ProUserManagerXmlProcessor>(); | ||
95 | + try | ||
96 | + { | ||
97 | + MembershipTools.Users.CreateAdminRolesAndUsers(); | ||
98 | + ColorConsole.WriteLine($"Creating admin users was successful!", ConsoleColor.Green); | ||
99 | + } | ||
100 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
101 | + return o; | ||
102 | + } | ||
103 | + #endregion CreateAdminusers | ||
104 | + #region DeleteUsers | ||
105 | + private static object DeleteUsers(object parameter, object o) | ||
106 | + { | ||
107 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<Log4ProUserManagerXmlProcessor>(); | ||
108 | + var uname = ColorConsole.ReadLine($"Enter username:", ConsoleColor.Yellow); | ||
109 | + if (uname == "EX") { return null; } | ||
110 | + | ||
111 | + try | ||
112 | + { | ||
113 | + if (!config.ProtectedUser(uname)) | ||
114 | + { | ||
115 | + MembershipTools.Users.Remove(uname); | ||
116 | + ColorConsole.WriteLine($"Deleting user '{uname}' was successwful!", ConsoleColor.Green); | ||
117 | + } | ||
118 | + else { throw new Exception($"User '{uname}' is protected, can not be deleted!"); } | ||
119 | + } | ||
120 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
121 | + return o; | ||
122 | + } | ||
123 | + #endregion DeleteUsers | ||
124 | + #endregion First level Executors with UI | ||
125 | + } | ||
126 | + #endregion MaintenanceTools class | ||
127 | + #region MaintenanceToolsXmlProcessor class | ||
128 | + public class Log4ProUserManagerXmlProcessor : XmlParser | ||
129 | + { | ||
130 | + #region fields | ||
131 | + public string Xml_SQLConnectionString; | ||
132 | + public string Xml_ProtectedUserNameCommaList; | ||
133 | + public List<UserGroup> UserGroupList; | ||
134 | + public List<string> ProtectedUserNameList; | ||
135 | + #endregion fields | ||
136 | + #region constructor | ||
137 | + public Log4ProUserManagerXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) | ||
138 | + { | ||
139 | + Xml_SQLConnectionString = RootElement.Attribute(XName.Get(nameof(XmlStructure.Attributes.SQLConnectionString)))?.Value; | ||
140 | + if (string.IsNullOrEmpty(Xml_SQLConnectionString)) { Xml_SQLConnectionString = XmlStructure.Attributes.SQLConnectionString.Values.DEFAULT; } | ||
141 | + | ||
142 | + Xml_ProtectedUserNameCommaList = RootElement.Attribute(XName.Get(nameof(XmlStructure.Attributes.ProtectedUsernameList)))?.Value; | ||
143 | + if (string.IsNullOrEmpty(Xml_ProtectedUserNameCommaList)) { Xml_ProtectedUserNameCommaList = XmlStructure.Attributes.ProtectedUsernameList.Values.DEFAULT; } | ||
144 | + ProtectedUserNameList = Xml_ProtectedUserNameCommaList.Split(',').ToList(); | ||
145 | + UserGroupList = new List<UserGroup>(); | ||
146 | + var ugxmllist = RootElement.Element(XName.Get(nameof(XmlStructure.UserGroups))).Elements(XName.Get(nameof(XmlStructure.UserGroups.UserGroup))); | ||
147 | + if (ugxmllist!=null && ugxmllist.Any()) | ||
148 | + { | ||
149 | + foreach (var ugxml in ugxmllist) | ||
150 | + { | ||
151 | + UserGroupList.Add(new UserGroup(ugxml)); | ||
152 | + }; | ||
153 | + } | ||
154 | + } | ||
155 | + #region ProtectedUser | ||
156 | + /// <summary> | ||
157 | + /// Igazzal tésr vissza, ha a user benne van a protected listában | ||
158 | + /// </summary> | ||
159 | + /// <param name="uname"></param> | ||
160 | + /// <returns></returns> | ||
161 | + public bool ProtectedUser(string uname) | ||
162 | + { | ||
163 | + return ProtectedUserNameList.Select(un=>un.ToUpper()).Contains(uname.ToUpper()); | ||
164 | + } | ||
165 | + #endregion ProtectedUser | ||
166 | + #endregion constructor | ||
167 | + #region XmlStructure | ||
168 | + public static class XmlStructure | ||
169 | + { | ||
170 | + public static class Attributes | ||
171 | + { | ||
172 | + public static class SQLConnectionString { public static class Values { public const string DEFAULT = ""; } } | ||
173 | + public static class ProtectedUsernameList { public static class Values { public const string DEFAULT = "Admin,Administrator"; } } | ||
174 | + | ||
175 | + } | ||
176 | + public static class UserGroups | ||
177 | + { | ||
178 | + public static class UserGroup | ||
179 | + { | ||
180 | + public static class Values | ||
181 | + { | ||
182 | + public const string DEFAULT = ".*"; | ||
183 | + } | ||
184 | + public static class Attributes | ||
185 | + { | ||
186 | + public static class Id {} | ||
187 | + public static class DisplayName {} | ||
188 | + public static class GroupType | ||
189 | + { | ||
190 | + public static class Values | ||
191 | + { | ||
192 | + public const UserGroupType DEFAULT = UserGroupType.UserName; | ||
193 | + } | ||
194 | + } | ||
195 | + } | ||
196 | + | ||
197 | + } | ||
198 | + public static class Values { public const string DEFAULT = "Admin,Administrator"; } | ||
199 | + } | ||
200 | + } | ||
201 | + #endregion XmlStructure | ||
202 | + #region UserGroup | ||
203 | + public class UserGroup:XmlLinqBase | ||
204 | + { | ||
205 | + public UserGroup() { } | ||
206 | + public UserGroup(XElement ugxml) | ||
207 | + { | ||
208 | + Id = ugxml.Attribute(XName.Get(nameof(XmlStructure.UserGroups.UserGroup.Attributes.Id)))?.Value; | ||
209 | + if (string.IsNullOrEmpty(Id)) { throw new Exception ($"Attribute is mandatory! Name {nameof(XmlStructure.UserGroups.UserGroup.Attributes.Id)}."); } | ||
210 | + | ||
211 | + Displayname = ugxml.Attribute(XName.Get(nameof(XmlStructure.UserGroups.UserGroup.Attributes.DisplayName)))?.Value; | ||
212 | + if (string.IsNullOrEmpty(Displayname)) { Displayname = Id; } | ||
213 | + | ||
214 | + string grouptypestring = ugxml.Attribute(XName.Get(nameof(XmlStructure.UserGroups.UserGroup.Attributes.GroupType)))?.Value; | ||
215 | + if (string.IsNullOrEmpty(grouptypestring)) { GroupType = XmlStructure.UserGroups.UserGroup.Attributes.GroupType.Values.DEFAULT; } | ||
216 | + else | ||
217 | + { | ||
218 | + try { GroupType = (UserGroupType)Enum.Parse(typeof(UserGroupType), grouptypestring); } | ||
219 | + catch { throw new Exception($"Attribute value is incorrect! Name {nameof(XmlStructure.UserGroups.UserGroup.Attributes.GroupType)}, Value: {grouptypestring}."); } | ||
220 | + } | ||
221 | + | ||
222 | + Regex = ugxml.Value; | ||
223 | + if (Regex==null) { Regex = XmlStructure.UserGroups.UserGroup.Values.DEFAULT; } | ||
224 | + } | ||
225 | + public UserGroup(UserGroup ug) { Id = ug.Id;Displayname = ug.Displayname;GroupType = ug.GroupType;Regex = ug.Regex; } | ||
226 | + public string Id; | ||
227 | + public string Displayname; | ||
228 | + public UserGroupType GroupType; | ||
229 | + public string Regex; | ||
230 | + } | ||
231 | + public enum UserGroupType { RoleName,RoleGroupName,UserName,} | ||
232 | + | ||
233 | + #endregion UserGroup | ||
234 | + } | ||
235 | + #endregion MaintenanceToolsXmlProcessor class | ||
236 | +} |
Vrh.Log4Pro.MaintenanceConsole/Manager - WebApplicationManager.cs
@@ -10,160 +10,118 @@ using Microsoft.Web.Administration; | @@ -10,160 +10,118 @@ using Microsoft.Web.Administration; | ||
10 | using System.Management; | 10 | using System.Management; |
11 | using System.Diagnostics; | 11 | using System.Diagnostics; |
12 | 12 | ||
13 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
14 | +using Vrh.Log4Pro.MaintenanceConsole.MenuNS; | ||
15 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
16 | + | ||
13 | using Vrh.XmlProcessing; | 17 | using Vrh.XmlProcessing; |
18 | +using VRH.Common; | ||
14 | using System.Xml.Linq; | 19 | using System.Xml.Linq; |
15 | 20 | ||
16 | -namespace Vrh.Log4Pro.MaintenanceConsole | 21 | +namespace Vrh.Log4Pro.MaintenanceConsole.WebApplicationManagerNS |
17 | { | 22 | { |
18 | #region WebApplicationManager | 23 | #region WebApplicationManager |
19 | public static class WebApplicationManager | 24 | public static class WebApplicationManager |
20 | { | 25 | { |
26 | + private const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE_WEBAPPLICATIONMANAGER;"; | ||
27 | + private const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;element=WebApplications;"; | ||
28 | + | ||
21 | #region public method: Execute | 29 | #region public method: Execute |
22 | public static object Execute(object o1=null,object o2=null) | 30 | public static object Execute(object o1=null,object o2=null) |
23 | { | 31 | { |
24 | - string xmlcs = "file=Config.xml;element=WebApplications;"; | ||
25 | - var config = new WebApplicationManagerXmlProcessor(xmlcs, "", "hu-HU"); | 32 | + var args = (o1 as Menu.ExecutorParameter).Args; |
33 | + var functionkey = CommandLine.GetCommandLineArgument(args, CLP.CMD_FUNCTION); | ||
34 | + var config = new WebApplicationManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); | ||
35 | + var ep = new Menu.ExecutorParameter(config, args); | ||
26 | 36 | ||
27 | var menufunctions = new Menu("Manage Web Applications","Select the management function!") | 37 | var menufunctions = new Menu("Manage Web Applications","Select the management function!") |
28 | - .AddMenuItem(new Menu.Item("WAR", "Register WebApplication",Register)) | ||
29 | - .AddMenuItem(new Menu.Item("WAU", "Unregister WebApplication",Unregister)) | ||
30 | - .AddMenuItem(new Menu.Item("WAI", "Set impersonate identity",SetImpersonateIdentity)) | ||
31 | - .AddMenuItem(new Menu.Item("APS", "Start application Pool",PoolStart)) | ||
32 | - .AddMenuItem(new Menu.Item("APF", "Stop application Pool",PoolStop)) | ||
33 | - .AddMenuItem(new Menu.Item("APR", "Recycle application Pool",PoolRecycle)) | ||
34 | - .AddMenuItem(new Menu.Item("WSS", "Start website",SiteStart)) | ||
35 | - .AddMenuItem(new Menu.Item("WSF", "Stop website",SiteStop)) | ||
36 | - .AddMenuItem(new Menu.Item("APU", "Set pool user account",PoolSetUserAccount)) | ||
37 | - .AddMenuItem(new Menu.Item("R", "Restart website and pool",Restart)) | ||
38 | - .SetSelectionMode(Menu.SelectionMode.Single); | ||
39 | - | ||
40 | - var menuapplications = new Menu("Web applications","Select the web application(s) to manage!") | ||
41 | - .SetMenuItemDisplayer(DisplayWebAppInfo) | ||
42 | - .SetSelectionMode(Menu.SelectionMode.Multi) | ||
43 | - .SetHeaderWidth(4); | ||
44 | - | ||
45 | - while (true) | ||
46 | - { | ||
47 | - List<WebApplication> wadefList = config.GetDefinitionList(); | ||
48 | - Menu.Selection sr; | ||
49 | - using (ServerManager sm = new ServerManager()) | ||
50 | - { | ||
51 | - var sites = sm.Sites; | ||
52 | - var pools = sm.ApplicationPools; | ||
53 | - menufunctions.DisplayTitle(); | 38 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.Register.KEY, "Register WebApplication",Register,ep)) |
39 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.Unregister.KEY, "Unregister WebApplication",Unregister, ep)) | ||
40 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.SetImpersonateIdentity.KEY, "Set impersonate identity",SetImpersonateIdentity, ep)) | ||
41 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.PoolStart.KEY, "Start application Pool",PoolStart, ep)) | ||
42 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.PoolStop.KEY, "Stop application Pool",PoolStop, ep)) | ||
43 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.PoolRecycle.KEY, "Recycle application Pool",PoolRecycle, ep)) | ||
44 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.SiteStart.KEY, "Start website",SiteStart, ep)) | ||
45 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.SiteStop.KEY, "Stop website",SiteStop, ep)) | ||
46 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.PoolSetUserAccount.KEY, "Set pool user account",PoolSetUserAccount, ep)) | ||
47 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.Function.Restart.KEY, "Restart website and pool",Restart, ep)) | ||
48 | + .SetSelectionMode(Menu.SelectionMode.Single) | ||
49 | + .SetMenuHeaderDisplayer(WebApplicationListDisplayer); | ||
54 | 50 | ||
55 | - menuapplications.ClearMenuItemList(); | ||
56 | - foreach (var wadef in wadefList) | ||
57 | - { | ||
58 | - var w = WebApplicationManagerCore.CollectWebAppInfo(sites, pools, wadef); | ||
59 | - menuapplications.AddMenuItem(new Menu.Item(null, null, null, w)); | ||
60 | - } | ||
61 | - } | ||
62 | - menuapplications.DisplayItems(1); | ||
63 | - | ||
64 | - menufunctions.DisplayItems(3,35); | ||
65 | - sr = menufunctions.Select(); | ||
66 | - if (sr.Result == Menu.SelectionResult.Exit) { break; } | ||
67 | - else if (sr.Result == Menu.SelectionResult.None) { continue; } | ||
68 | - else if (sr.Result == Menu.SelectionResult.Error) { continue; } | ||
69 | - var functionexecutor = menufunctions.GetExecutor(sr.SelectedKeyList.First()); | ||
70 | - | ||
71 | - foreach (var mi in menuapplications.MenuItemList) { mi.Executor=functionexecutor; } | ||
72 | - | ||
73 | - sr = menuapplications.Select(); | ||
74 | - if (sr.Result == Menu.SelectionResult.Exit) { break; } | ||
75 | - else if (sr.Result == Menu.SelectionResult.None) { continue; } | ||
76 | - else if (sr.Result == Menu.SelectionResult.Error) { continue; } | ||
77 | - else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
78 | - else { } | ||
79 | - menuapplications.ExecuteSelection(sr.SelectedKeyList); | ||
80 | - } | ||
81 | - return null; | 51 | + menufunctions.ExecuteMenu(functionkey); |
52 | + return o2; | ||
82 | } | 53 | } |
83 | #endregion public method: Execute | 54 | #endregion public method: Execute |
84 | - #region private method: DisplayWebAppInfo | ||
85 | - private static object DisplayWebAppInfo(object waobj,int lineix) | 55 | + |
56 | + #region private DisplayWebApplicationMenu | ||
57 | + private static void WebApplicationListDisplayer() { DisplayWebApplicationMenu(); } | ||
58 | + private static Menu DisplayWebApplicationMenu(WebApplicationManagerXmlProcessor config= null, string prompt = null, bool silent=false) | ||
86 | { | 59 | { |
87 | - WebApplication wa = waobj as WebApplication; | ||
88 | - if (lineix==0) | ||
89 | - { | ||
90 | - ColorConsole.WriteLine($"{wa.Xml_Description}", ConsoleColor.Black, ConsoleColor.White); | ||
91 | - } | ||
92 | - else if (lineix == 1) | ||
93 | - { | ||
94 | - ColorConsole.Write($"Web app:"); | ||
95 | - ColorConsole.Write($"{wa.Xml_AppName}", ConsoleColor.Cyan); | ||
96 | - var fc2 = wa.ApplicationState.Contains("Unregistered") ? ConsoleColor.Red : ConsoleColor.Green; | ||
97 | - ColorConsole.Write($"{wa.ApplicationState}", fc2, bracket: "()"); | ||
98 | - ColorConsole.Write($", Log.path:"); | ||
99 | - ColorConsole.Write($"{wa.ApplicationPath}", ConsoleColor.White); | ||
100 | - ColorConsole.Write($", Phy.path:"); | ||
101 | - ColorConsole.WriteLine($"{wa.Xml_AppPhysicalPath}", ConsoleColor.White); | ||
102 | - } | ||
103 | - else if (lineix == 2) | ||
104 | - { | ||
105 | - ColorConsole.Write($"impersonate identity:"); | ||
106 | - ColorConsole.WriteLine($"{wa.AppImpersonateIdentity}", ConsoleColor.White); | ||
107 | - } | ||
108 | - else if (lineix == 3) | ||
109 | - { | ||
110 | - ColorConsole.Write($"Site:"); | ||
111 | - ColorConsole.Write($"{wa.Xml_SiteName}", ConsoleColor.Cyan); | ||
112 | - var fc0 = | ||
113 | - wa.SiteState.Contains("Started") ? ConsoleColor.Green | ||
114 | - : wa.SiteState.Contains("Unregistered") ? ConsoleColor.Red | ||
115 | - : ConsoleColor.Yellow; | ||
116 | - ColorConsole.Write($"{wa.SiteState}", fc0, bracket: "()"); | ||
117 | - ColorConsole.Write($", Ports:"); | ||
118 | - ColorConsole.Write($"{wa.SitePortList}", ConsoleColor.White); | ||
119 | - ColorConsole.Write($", Phy.path:"); | ||
120 | - ColorConsole.WriteLine($"{wa.Xml_SitePhysicalPath}", ConsoleColor.White); | ||
121 | - } | ||
122 | - else if (lineix == 4) | ||
123 | - { | ||
124 | - ColorConsole.Write($"Pool:"); | ||
125 | - ColorConsole.Write($"{wa.Xml_PoolName}", ConsoleColor.Cyan); | ||
126 | - var fc1 = wa.PoolState == null ? ConsoleColor.Red | ||
127 | - : wa.PoolState.Contains("Started") ? ConsoleColor.Green | ||
128 | - : wa.PoolState.Contains("Unregistered") ? ConsoleColor.Red | ||
129 | - : ConsoleColor.Yellow; | ||
130 | - string waps = wa.PoolState == null ? "Unregistered/Unknown" : wa.PoolState; | ||
131 | - ColorConsole.Write($"{waps}", fc1, bracket: "()"); | ||
132 | - ColorConsole.Write($", identity:"); | ||
133 | - ColorConsole.WriteLine($"{wa.PoolAccount}", ConsoleColor.White); | ||
134 | - } | ||
135 | - else if (lineix==5) | ||
136 | - { | ||
137 | - ColorConsole.WriteLine(); | ||
138 | - } | ||
139 | - else | 60 | + if (config == null) { config = new WebApplicationManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); } |
61 | + List<WebApplication> wadefList = config.GetDefinitionList(); | ||
62 | + var menuwa = new Menu("Web applications", prompt) | ||
63 | + .SetMenuItemDisplayer(DisplayWebAppInfo) | ||
64 | + .SetSelectionMode(Menu.SelectionMode.Multi); | ||
65 | + menuwa.ClearMenuItemList(); | ||
66 | + foreach (var wadef in wadefList) | ||
140 | { | 67 | { |
141 | - return null; | 68 | + var wa = WebApplicationManagerCore.CollectWebAppInfo(wadef); |
69 | + menuwa.AddMenuItem(new Menu.Item(wadef.Xml_Key, null, null, new Menu.ExecutorParameter(pars: wa))); | ||
142 | } | 70 | } |
143 | - return ""; | 71 | + if (!silent) { menuwa.DisplayItems(1); } |
72 | + return menuwa; | ||
144 | } | 73 | } |
145 | - #endregion private method: DisplayWebAppInfo | ||
146 | - #region | ||
147 | - private static object Restart(object dobj, object parameters) | 74 | + #endregion private DisplayWebApplicationMenu |
75 | + | ||
76 | + #region 1st level Executors | ||
77 | + private static object Restart(object parameters, object o) | ||
148 | { | 78 | { |
149 | - WebApplication d = dobj as WebApplication; | ||
150 | - using (ServerManager sm = new ServerManager()) | 79 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); |
80 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
81 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
82 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!",silent:true); | ||
83 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
84 | + | ||
85 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
86 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
87 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
88 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
89 | + else { } | ||
90 | + foreach (var p in sr.SelectedParameterList) | ||
151 | { | 91 | { |
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."); } | 92 | + WebApplication wa = p.Parameters as WebApplication; |
93 | + using (ServerManager sm = new ServerManager()) | ||
94 | + { | ||
95 | + try { WebApplicationManagerCore.GetPool(sm, wa.Xml_PoolName)?.Stop(); } catch { ColorConsole.WriteLine($"Pool {wa.Xml_PoolName} already stopped."); } | ||
96 | + try { WebApplicationManagerCore.GetSite(sm, wa.Xml_SiteName)?.Stop(); } catch { ColorConsole.WriteLine($"Site {wa.Xml_SiteName} already stopped."); } | ||
154 | 97 | ||
155 | - SiteStart(d, parameters); | ||
156 | - PoolStart(d, parameters); | ||
157 | - PoolRecycle(d, parameters); | 98 | + SiteStart(wa, o); |
99 | + PoolStart(wa, o); | ||
100 | + PoolRecycle(wa, o); | ||
158 | 101 | ||
159 | - ColorConsole.WriteLine($"Pool {d.Xml_PoolName} and site {d.Xml_SiteName} restarted."); | ||
160 | - return parameters; | 102 | + ColorConsole.WriteLine($"Pool {wa.Xml_PoolName} and site {wa.Xml_SiteName} restarted."); |
103 | + } | ||
161 | } | 104 | } |
105 | + return o; | ||
106 | + } | ||
107 | + private static object PoolStart(object parameters, object o) | ||
108 | + { | ||
109 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); | ||
110 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
111 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
112 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
113 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
114 | + | ||
115 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
116 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
117 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
118 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
119 | + else { } | ||
120 | + foreach (var wa in sr.SelectedParameterList) { OnePoolStart(wa.Parameters as WebApplication); } | ||
121 | + return o; | ||
162 | } | 122 | } |
163 | - private | ||
164 | - static object PoolStart(object dobj, object parameters) | 123 | + private static void OnePoolStart(WebApplication d) |
165 | { | 124 | { |
166 | - WebApplication d = dobj as WebApplication; | ||
167 | using (ServerManager sm = new ServerManager()) | 125 | using (ServerManager sm = new ServerManager()) |
168 | { | 126 | { |
169 | bool success = false; | 127 | bool success = false; |
@@ -181,12 +139,26 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -181,12 +139,26 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
181 | } | 139 | } |
182 | var successstr = success ? "started" : "NOT started"; | 140 | var successstr = success ? "started" : "NOT started"; |
183 | ColorConsole.WriteLine($"{d.Xml_PoolName} {successstr}."); | 141 | ColorConsole.WriteLine($"{d.Xml_PoolName} {successstr}."); |
184 | - return parameters; | ||
185 | } | 142 | } |
186 | } | 143 | } |
187 | - private static object PoolRecycle(object dobj, object parameters) | 144 | + private static object PoolRecycle(object parameters, object o) |
145 | + { | ||
146 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); | ||
147 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
148 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
149 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
150 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
151 | + | ||
152 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
153 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
154 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
155 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
156 | + else { } | ||
157 | + foreach (var wa in sr.SelectedParameterList) { OnePoolRecycle(wa.Parameters as WebApplication); } | ||
158 | + return o; | ||
159 | + } | ||
160 | + private static void OnePoolRecycle(WebApplication d) | ||
188 | { | 161 | { |
189 | - WebApplication d = dobj as WebApplication; | ||
190 | using (ServerManager sm = new ServerManager()) | 162 | using (ServerManager sm = new ServerManager()) |
191 | { | 163 | { |
192 | bool success = false; | 164 | bool success = false; |
@@ -203,58 +175,100 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -203,58 +175,100 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
203 | } | 175 | } |
204 | var successstr = success ? "recycled" : "NOT recycled"; | 176 | var successstr = success ? "recycled" : "NOT recycled"; |
205 | ColorConsole.WriteLine($"{d.Xml_PoolName} {successstr}."); | 177 | ColorConsole.WriteLine($"{d.Xml_PoolName} {successstr}."); |
206 | - return parameters; | ||
207 | } | 178 | } |
208 | } | 179 | } |
209 | - private static object PoolStop(object dobj, object parameters) | 180 | + private static object PoolStop(object parameters, object o) |
181 | + { | ||
182 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); | ||
183 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
184 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
185 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
186 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
187 | + | ||
188 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
189 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
190 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
191 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
192 | + else { } | ||
193 | + foreach (var wa in sr.SelectedParameterList) { OnePoolStop(wa.Parameters as WebApplication); } | ||
194 | + return o; | ||
195 | + } | ||
196 | + private static void OnePoolStop(WebApplication wa) | ||
210 | { | 197 | { |
211 | using (ServerManager sm = new ServerManager()) | 198 | using (ServerManager sm = new ServerManager()) |
212 | { | 199 | { |
213 | - WebApplication d = dobj as WebApplication; | ||
214 | bool success = false; | 200 | bool success = false; |
215 | for (var i = 1; i <= 10; i++) | 201 | for (var i = 1; i <= 10; i++) |
216 | { | 202 | { |
217 | - var p = WebApplicationManagerCore.GetPool(sm, d.Xml_PoolName); | 203 | + var p = WebApplicationManagerCore.GetPool(sm, wa.Xml_PoolName); |
218 | if (p != null && p.State == ObjectState.Started) { p.Stop(); success = true; break; } | 204 | if (p != null && p.State == ObjectState.Started) { p.Stop(); success = true; break; } |
219 | else | 205 | else |
220 | { | 206 | { |
221 | - ColorConsole.WriteLine($"Trying to stop pool {d.Xml_PoolName} ... Press key 'X' to exit..."); | 207 | + ColorConsole.WriteLine($"Trying to stop pool {wa.Xml_PoolName} ... Press key 'X' to exit..."); |
222 | if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } } | 208 | if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } } |
223 | 209 | ||
224 | Thread.Sleep(1000); | 210 | Thread.Sleep(1000); |
225 | } | 211 | } |
226 | } | 212 | } |
227 | var successstr = success ? "stopped" : "NOT stopped"; | 213 | var successstr = success ? "stopped" : "NOT stopped"; |
228 | - ColorConsole.WriteLine($"{d.Xml_PoolName} {successstr}."); | ||
229 | - return parameters; | 214 | + ColorConsole.WriteLine($"{wa.Xml_PoolName} {successstr}."); |
230 | } | 215 | } |
231 | } | 216 | } |
232 | - private static object SiteStart(object dobj, object parameters) | 217 | + private static object SiteStart(object parameters, object o) |
233 | { | 218 | { |
234 | - WebApplication d = dobj as WebApplication; | ||
235 | - using (ServerManager sm = new ServerManager()) | 219 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); |
220 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
221 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
222 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
223 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
224 | + | ||
225 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
226 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
227 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
228 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
229 | + else { } | ||
230 | + foreach (var wa in sr.SelectedParameterList) { OneSiteStart(wa.Parameters as WebApplication); } | ||
231 | + return o; | ||
232 | + } | ||
233 | + private static void OneSiteStart(WebApplication wa) | ||
234 | + { | ||
235 | + using (ServerManager sm = new ServerManager()) | ||
236 | { | 236 | { |
237 | bool success = false; | 237 | bool success = false; |
238 | for (var i = 1; i < 4; i++) | 238 | for (var i = 1; i < 4; i++) |
239 | { | 239 | { |
240 | - var s = WebApplicationManagerCore.GetSite(sm, d.Xml_SiteName); | 240 | + var s = WebApplicationManagerCore.GetSite(sm, wa.Xml_SiteName); |
241 | if (s != null && s.State == ObjectState.Stopped) { s.Start(); success = true; break; } | 241 | if (s != null && s.State == ObjectState.Stopped) { s.Start(); success = true; break; } |
242 | else | 242 | else |
243 | { | 243 | { |
244 | - ColorConsole.WriteLine($"Trying to start site {d.Xml_SiteName} ... Press key 'X' to exit..."); | 244 | + ColorConsole.WriteLine($"Trying to start site {wa.Xml_SiteName} ... Press key 'X' to exit..."); |
245 | if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } } | 245 | if (ColorConsole.KeyAvailable) { if (ColorConsole.ReadKey().KeyChar.ToString().ToUpper() == "X") { break; } } |
246 | Thread.Sleep(1000); | 246 | Thread.Sleep(1000); |
247 | } | 247 | } |
248 | } | 248 | } |
249 | var successstr = success ? "started" : "NOT started"; | 249 | var successstr = success ? "started" : "NOT started"; |
250 | - ColorConsole.WriteLine($"{d.Xml_SiteName} {successstr}."); | ||
251 | - return parameters; | 250 | + ColorConsole.WriteLine($"{wa.Xml_SiteName} {successstr}."); |
252 | } | 251 | } |
253 | } | 252 | } |
254 | - private static object SiteStop(object dobj, object parameters) | 253 | + private static object SiteStop(object parameters, object o) |
255 | { | 254 | { |
256 | - WebApplication d = dobj as WebApplication; | ||
257 | - using (ServerManager sm = new ServerManager()) | 255 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); |
256 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
257 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
258 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
259 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
260 | + | ||
261 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
262 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
263 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
264 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
265 | + else { } | ||
266 | + foreach (var wa in sr.SelectedParameterList) { OneSiteStop(wa.Parameters as WebApplication); } | ||
267 | + return o; | ||
268 | + } | ||
269 | + private static void OneSiteStop(WebApplication d) | ||
270 | + { | ||
271 | + using (ServerManager sm = new ServerManager()) | ||
258 | { | 272 | { |
259 | bool success = false; | 273 | bool success = false; |
260 | for (var i = 1; i < 4; i++) | 274 | for (var i = 1; i < 4; i++) |
@@ -270,57 +284,120 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -270,57 +284,120 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
270 | } | 284 | } |
271 | var successstr = success ? "stopped" : "NOT stopped"; | 285 | var successstr = success ? "stopped" : "NOT stopped"; |
272 | ColorConsole.WriteLine($"{d.Xml_SiteName} {successstr}."); | 286 | ColorConsole.WriteLine($"{d.Xml_SiteName} {successstr}."); |
273 | - return parameters; | ||
274 | } | 287 | } |
275 | } | 288 | } |
276 | - private static object Register(object dobj, object parameters) | 289 | + private static object Register(object parameters, object o) |
277 | { | 290 | { |
278 | - WebApplication d = dobj as WebApplication; | ||
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 | - ColorConsole.WriteLine($"{d.Xml_AppName} is registered in site {d.Xml_SiteName} using pool {d.Xml_PoolName}."); | ||
281 | - return parameters; | 291 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); |
292 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
293 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
294 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
295 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
296 | + | ||
297 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
298 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
299 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
300 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
301 | + else { } | ||
302 | + foreach (var p in sr.SelectedParameterList) | ||
303 | + { | ||
304 | + WebApplication wa=p.Parameters as WebApplication; | ||
305 | + WebApplicationManagerCore.RegisterWebApplication(wa.Xml_SiteName, wa.Xml_PoolName, wa.Xml_AppName, wa.Xml_AppPhysicalPath, wa.Xml_SitePhysicalPath, 8080, wa.Xml_RecreatePool, wa.Xml_RecreateSite, wa.Xml_RecreateApp, wa.Xml_PoolPipeLineMode); | ||
306 | + ColorConsole.WriteLine($"{wa.Xml_AppName} is registered in site {wa.Xml_SiteName} using pool {wa.Xml_PoolName}."); | ||
307 | + } | ||
308 | + return o; | ||
309 | + } | ||
310 | + private static object Unregister(object parameters, object o) | ||
311 | + { | ||
312 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); | ||
313 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
314 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
315 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
316 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
317 | + | ||
318 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
319 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
320 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
321 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
322 | + else { } | ||
323 | + foreach (var p in sr.SelectedParameterList) | ||
324 | + { | ||
325 | + WebApplication wa = p.Parameters as WebApplication; | ||
326 | + WebApplicationManagerCore.UnRegisterWebApplication(wa.Xml_AppName, wa.Xml_PoolName, wa.Xml_SiteName, wa.Xml_ForceRemovePool, wa.Xml_ForceRemoveSite); | ||
327 | + ColorConsole.WriteLine($"{wa.Xml_AppName} is unregistered from site {wa.Xml_SiteName} and from pool {wa.Xml_PoolName}."); | ||
328 | + } | ||
329 | + return o; | ||
282 | } | 330 | } |
283 | - private static object Unregister(object dobj, object parameters) | 331 | + private static object SetImpersonateIdentity(object parameters, object o) |
284 | { | 332 | { |
285 | - WebApplication d = dobj as WebApplication; | ||
286 | - WebApplicationManagerCore.UnRegisterWebApplication(d.Xml_AppName, d.Xml_PoolName, d.Xml_SiteName, d.Xml_ForceRemovePool, d.Xml_ForceRemoveSite); | ||
287 | - ColorConsole.WriteLine($"{d.Xml_AppName} is unregistered from site {d.Xml_SiteName} and from pool {d.Xml_PoolName}."); | ||
288 | - return parameters; | 333 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); |
334 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
335 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
336 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
337 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
338 | + | ||
339 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
340 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
341 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
342 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
343 | + else { } | ||
344 | + foreach (var p in sr.SelectedParameterList) | ||
345 | + { | ||
346 | + var wa = p.Parameters as WebApplication; | ||
347 | + GetImpersonateInfo(wa, out string username, out string password, out string impersonate); | ||
348 | + if (username == "EX" || password == "EX" || impersonate == "EX") { return o; } | ||
349 | + string olduserinfo = WebApplicationManagerCore.GetCurrentImpersonateIdentityInfo(wa); | ||
350 | + WebApplicationManagerCore.SetImpersonateIdentity(wa.Xml_ImpersonateIdentityConfigFile, impersonate, username, password); | ||
351 | + ColorConsole.WriteLine($"Impersonate identity changed for webapp {wa.Xml_AppName}."); | ||
352 | + ColorConsole.WriteLine($"From '{olduserinfo}' to '{WebApplicationManagerCore.GetCurrentImpersonateIdentityInfo(wa)}'"); | ||
353 | + } | ||
354 | + return o; | ||
289 | } | 355 | } |
290 | - private static object SetImpersonateIdentity(object dobj, object parameters) | 356 | + private static void GetImpersonateInfo(WebApplication wa,out string username, out string password, out string impersonate) |
291 | { | 357 | { |
292 | - WebApplication d = dobj as WebApplication; | ||
293 | - string username="", password = "",impersonate="FALSE"; | ||
294 | - bool parametersarealreadyset = parameters != null; | ||
295 | - string olduserinfo = WebApplicationManagerCore.GetImpersonateIdentityInfo(d.Xml_IdentityConfigFile); | ||
296 | - if (parametersarealreadyset) | 358 | + username = ""; password = ""; impersonate = bool.FalseString.ToUpper(); |
359 | + if (Menu.IsCommandMode()) | ||
297 | { | 360 | { |
298 | - impersonate = ((Dictionary<string, string>)parameters)["impersonate"]; | ||
299 | - username = ((Dictionary<string, string>)parameters)["username"]; | ||
300 | - password = ((Dictionary<string, string>)parameters)["password"]; | 361 | + impersonate = wa.Xml_ImpersonateIdentity.ToString(); |
362 | + username = wa.Xml_ImpersonateIdentityUsername; | ||
363 | + password = wa.Xml_ImpersonateIdentityPassword; | ||
301 | } | 364 | } |
302 | else | 365 | else |
303 | { | 366 | { |
304 | - while(true) | 367 | + string olduserinfo = WebApplicationManagerCore.GetCurrentImpersonateIdentityInfo(wa); |
368 | + while (true) | ||
305 | { | 369 | { |
306 | - | 370 | + var defaultinxml = WebApplicationManagerCore.GetDefaultImpersonateIdentityInfo(wa); |
307 | ColorConsole.WriteLine($"Current user info: {olduserinfo}"); | 371 | ColorConsole.WriteLine($"Current user info: {olduserinfo}"); |
308 | - ColorConsole.WriteLine("Set impersonate-on status (true/false), then [Enter], EX=exit."); | 372 | + ColorConsole.WriteLine($"Set impersonate-on status (true/false).[Enter]=finish input.EX=exit"); |
373 | + ColorConsole.WriteLine($"Empty in XML={defaultinxml}"); | ||
309 | impersonate = ColorConsole.ReadLine().ToUpper(); | 374 | impersonate = ColorConsole.ReadLine().ToUpper(); |
310 | - if (impersonate == "EX") { return null; } | ||
311 | - else if (impersonate == "FALSE") { break; } | ||
312 | - else if (impersonate == "TRUE") | 375 | + if (impersonate == "EX") { return; } |
376 | + else if (impersonate == "") | ||
377 | + { | ||
378 | + username = wa.Xml_ImpersonateIdentityUsername; | ||
379 | + password = wa.Xml_ImpersonateIdentityPassword; | ||
380 | + impersonate = wa.Xml_ImpersonateIdentity.ToString(); | ||
381 | + return; | ||
382 | + } | ||
383 | + else if (impersonate == bool.FalseString.ToUpper()) | ||
384 | + { | ||
385 | + username = ""; | ||
386 | + password = ""; | ||
387 | + return; | ||
388 | + } | ||
389 | + else if (impersonate == bool.TrueString.ToUpper()) | ||
313 | { | 390 | { |
314 | - ColorConsole.WriteLine("Enter username, then [Enter]."); | ||
315 | - var un = !string.IsNullOrWhiteSpace(d.Xml_PoolUsername) ? $"empty={d.Xml_PoolUsername }," : ""; | ||
316 | - ColorConsole.WriteLine($"{un}EX=exit"); | 391 | + ColorConsole.WriteLine($"Enter username.[Enter]=finish input.EX=exit"); |
392 | + if (wa.Xml_ImpersonateIdentity) { ColorConsole.WriteLine(defaultinxml); } | ||
317 | username = ColorConsole.ReadLine().ToUpper(); | 393 | username = ColorConsole.ReadLine().ToUpper(); |
318 | - if (impersonate == "EX") { return null; } | ||
319 | - ColorConsole.WriteLine("Enter password, then [Enter]"); | ||
320 | - var pw = !string.IsNullOrWhiteSpace(d.Xml_PoolPassword) ? $"empty={d.Xml_PoolPassword}," : ""; | ||
321 | - ColorConsole.WriteLine($"{pw}EX=exit"); | 394 | + if (username == "EX") { return; } |
395 | + else if (wa.Xml_ImpersonateIdentity && username == "") | ||
396 | + { | ||
397 | + } | ||
398 | + ColorConsole.WriteLine($"Enter password.[Enter]=finish input.Empty=no password.EX=exit"); | ||
322 | password = ColorConsole.ReadLine().ToUpper(); | 399 | password = ColorConsole.ReadLine().ToUpper(); |
323 | - if (impersonate == "EX") { return null; } | 400 | + if (password == "EX") { return; } |
324 | break; | 401 | break; |
325 | //bool valid = System.Web.ApplicationSerices.AuthenticationService.ValidateUser(username, password, mull); | 402 | //bool valid = System.Web.ApplicationSerices.AuthenticationService.ValidateUser(username, password, mull); |
326 | } | 403 | } |
@@ -330,126 +407,209 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -330,126 +407,209 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
330 | continue; | 407 | continue; |
331 | } | 408 | } |
332 | } | 409 | } |
333 | - parameters = new Dictionary<string, string> { { "impersonate", impersonate }, { "username", username }, { "password", password }, }; | ||
334 | } | 410 | } |
335 | - WebApplicationManagerCore.SetImpersonateIdentity(d.Xml_IdentityConfigFile, impersonate, username, password); | ||
336 | - ColorConsole.WriteLine($"Impersonate identity changed for webapp {d.Xml_AppName}."); | ||
337 | - ColorConsole.WriteLine($"From '{olduserinfo}' to '{WebApplicationManagerCore.GetImpersonateIdentityInfo(d.Xml_IdentityConfigFile)}'"); | ||
338 | - | ||
339 | - return parameters; | ||
340 | } | 411 | } |
341 | - private static object PoolSetUserAccount(object dobj, object parameters) | 412 | + private static object PoolSetUserAccount(object parameters, object o) |
342 | { | 413 | { |
343 | - WebApplication d = dobj as WebApplication; | ||
344 | - string username, password = ""; | ||
345 | - bool parametersarealreadyset = parameters != null; | ||
346 | - string olduserinfo = WebApplicationManagerCore.GetUserInfo(d.Xml_PoolName); | ||
347 | - if (parametersarealreadyset) | 414 | + var config = (parameters as Menu.ExecutorParameter).GetConfig<WebApplicationManagerXmlProcessor>(); |
415 | + var args = (parameters as Menu.ExecutorParameter).Args; | ||
416 | + var selectedwaindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WebApplicationManager.Function.CMD_WEBAPPS); | ||
417 | + var menuwapps = DisplayWebApplicationMenu(config, "Select the web application(s) to manage!", silent: true); | ||
418 | + Menu.Selection sr = menuwapps.Select(selectedwaindexes); | ||
419 | + | ||
420 | + if (sr.Result == Menu.SelectionResult.Exit) { return o; } | ||
421 | + else if (sr.Result == Menu.SelectionResult.None) { return o; } | ||
422 | + else if (sr.Result == Menu.SelectionResult.Error) { return o; } | ||
423 | + else if (sr.Result == Menu.SelectionResult.Ok) { } | ||
424 | + else { } | ||
425 | + foreach (var p in sr.SelectedParameterList) | ||
348 | { | 426 | { |
349 | - username = ((Dictionary<string, string>)parameters)["username"]; | ||
350 | - password = ((Dictionary<string, string>)parameters)["password"]; | 427 | + var wa = p.Parameters as WebApplication; |
428 | + GetPoolIdentityInfo(wa, out string username, out string password); | ||
429 | + if (username == "EX" || password == "EX") { return o; } | ||
430 | + string olduserinfo = WebApplicationManagerCore.GetCurrentPoolIdentityInfo(wa); | ||
431 | + WebApplicationManagerCore.SetPoolUserAccount(wa.Xml_AppName, wa.Xml_SiteName, username, password); | ||
432 | + ColorConsole.WriteLine($"Pool identity changed for webapp {wa.Xml_AppName}."); | ||
433 | + ColorConsole.WriteLine($"From '{olduserinfo}' to '{WebApplicationManagerCore.GetCurrentPoolIdentityInfo(wa)}'"); | ||
434 | + } | ||
435 | + return o; | ||
436 | + } | ||
437 | + private static void GetPoolIdentityInfo(WebApplication wa, out string username, out string password) | ||
438 | + { | ||
439 | + username = ""; password = ""; | ||
440 | + if (Menu.IsCommandMode()) | ||
441 | + { | ||
442 | + username = wa.Xml_PoolName; | ||
443 | + password = wa.Xml_PoolPassword; | ||
351 | } | 444 | } |
352 | else | 445 | else |
353 | { | 446 | { |
447 | + var defaultinxml = WebApplicationManagerCore.GetDefaultPoolIdentityInfo(wa); | ||
448 | + username=""; password = ""; | ||
449 | + string olduserinfo = WebApplicationManagerCore.GetCurrentPoolIdentityInfo(wa); | ||
354 | ColorConsole.WriteLine($"Current user info: {olduserinfo}"); | 450 | ColorConsole.WriteLine($"Current user info: {olduserinfo}"); |
355 | - ColorConsole.WriteLine("Enter username, then [Enter]."); | ||
356 | - ColorConsole.WriteLine("Special usernames are: (Empty=API) "); | 451 | + var un = $"Empty from XML={defaultinxml}."; |
452 | + ColorConsole.WriteLine($"Enter username.[Enter]=finish input.{un}EX=exit."); | ||
453 | + ColorConsole.WriteLine("Special usernames are:"); | ||
357 | ColorConsole.WriteLine($" (API) {nameof(ProcessModelIdentityType.ApplicationPoolIdentity)}"); | 454 | ColorConsole.WriteLine($" (API) {nameof(ProcessModelIdentityType.ApplicationPoolIdentity)}"); |
358 | ColorConsole.WriteLine($" (LSE) {nameof(ProcessModelIdentityType.LocalService)}"); | 455 | ColorConsole.WriteLine($" (LSE) {nameof(ProcessModelIdentityType.LocalService)}"); |
359 | ColorConsole.WriteLine($" (LSY) {nameof(ProcessModelIdentityType.LocalSystem)}"); | 456 | ColorConsole.WriteLine($" (LSY) {nameof(ProcessModelIdentityType.LocalSystem)}"); |
360 | ColorConsole.WriteLine($" (NSE) {nameof(ProcessModelIdentityType.NetworkService)}"); | 457 | ColorConsole.WriteLine($" (NSE) {nameof(ProcessModelIdentityType.NetworkService)}"); |
361 | - ColorConsole.WriteLine(); | ||
362 | - ColorConsole.Write(" (EX) ", ConsoleColor.Red); ColorConsole.WriteLine("Exit"); | ||
363 | username = ColorConsole.ReadLine().ToUpper(); | 458 | username = ColorConsole.ReadLine().ToUpper(); |
364 | - if (username == "EX") { return null; } | ||
365 | - if (string.IsNullOrEmpty(username)) { username = nameof(ProcessModelIdentityType.ApplicationPoolIdentity); }; | ||
366 | - if (username == "API" || username == nameof(ProcessModelIdentityType.ApplicationPoolIdentity)) { username = nameof(ProcessModelIdentityType.ApplicationPoolIdentity); } | 459 | + if (username == "EX") { return; } |
460 | + else if (string.IsNullOrEmpty(username)) { username=wa.Xml_PoolUsername; password = wa.Xml_PoolPassword; } | ||
461 | + else if (username == "API" || username == nameof(ProcessModelIdentityType.ApplicationPoolIdentity)) { username = nameof(ProcessModelIdentityType.ApplicationPoolIdentity); } | ||
367 | else if (username == "LSE" || username == nameof(ProcessModelIdentityType.LocalService)) { username = nameof(ProcessModelIdentityType.LocalService); } | 462 | else if (username == "LSE" || username == nameof(ProcessModelIdentityType.LocalService)) { username = nameof(ProcessModelIdentityType.LocalService); } |
368 | else if (username == "LSY" || username == nameof(ProcessModelIdentityType.LocalSystem)) { username = nameof(ProcessModelIdentityType.LocalSystem); } | 463 | else if (username == "LSY" || username == nameof(ProcessModelIdentityType.LocalSystem)) { username = nameof(ProcessModelIdentityType.LocalSystem); } |
369 | else if (username == "NSE" || username == nameof(ProcessModelIdentityType.NetworkService)) { username = nameof(ProcessModelIdentityType.NetworkService); } | 464 | else if (username == "NSE" || username == nameof(ProcessModelIdentityType.NetworkService)) { username = nameof(ProcessModelIdentityType.NetworkService); } |
370 | else | 465 | else |
371 | { | 466 | { |
372 | - ColorConsole.WriteLine("Enter password, then [Enter]"); | 467 | + ColorConsole.WriteLine("Enter password.[Enter]=finish input.Empty=no password.EX=exit"); |
373 | password = ColorConsole.ReadLine().ToUpper(); | 468 | password = ColorConsole.ReadLine().ToUpper(); |
374 | //bool valid = System.Web.ApplicationSerices.AuthenticationService.ValidateUser(username, password, mull); | 469 | //bool valid = System.Web.ApplicationSerices.AuthenticationService.ValidateUser(username, password, mull); |
375 | } | 470 | } |
376 | - parameters = new Dictionary<string, string> { { "username", username }, { "password", password }, }; | ||
377 | } | 471 | } |
378 | - WebApplicationManagerCore.SetPoolUserAccount(d.Xml_AppName, d.Xml_SiteName, username, password); | ||
379 | - ColorConsole.WriteLine($"Pool user changed from {olduserinfo} to {WebApplicationManagerCore.GetUserInfo(d.Xml_PoolName)} for pool {d.Xml_PoolName}."); | ||
380 | - return parameters; | ||
381 | } | 472 | } |
382 | - #endregion | 473 | + #endregion 1st level Executors |
474 | + | ||
475 | + #region private method: DisplayWebAppInfo | ||
476 | + private static object DisplayWebAppInfo(object obj, int lineix) | ||
477 | + { | ||
478 | + WebApplication wa = (obj as Menu.ExecutorParameter).Parameters as WebApplication; | ||
479 | + if (lineix == 0) | ||
480 | + { | ||
481 | + ColorConsole.WriteLine($"{wa.Xml_Description}", ConsoleColor.Black, ConsoleColor.White); | ||
482 | + } | ||
483 | + else if (lineix == 1) | ||
484 | + { | ||
485 | + ColorConsole.Write($"Web app:"); | ||
486 | + ColorConsole.Write($"{wa.Xml_AppName}", ConsoleColor.Cyan); | ||
487 | + var fc2 = wa.ApplicationState.Contains("Unregistered") ? ConsoleColor.Red : ConsoleColor.Green; | ||
488 | + ColorConsole.Write($"{wa.ApplicationState}", fc2, bracket: "()"); | ||
489 | + ColorConsole.Write($", Log.path:"); | ||
490 | + ColorConsole.Write($"{wa.ApplicationPath}", ConsoleColor.White); | ||
491 | + ColorConsole.Write($", Phy.path:"); | ||
492 | + ColorConsole.WriteLine($"{wa.Xml_AppPhysicalPath}", ConsoleColor.White); | ||
493 | + } | ||
494 | + else if (lineix == 2) | ||
495 | + { | ||
496 | + ColorConsole.Write($"impersonate identity:"); | ||
497 | + ColorConsole.WriteLine($"{wa.AppImpersonateIdentity}", ConsoleColor.White); | ||
498 | + } | ||
499 | + else if (lineix == 3) | ||
500 | + { | ||
501 | + ColorConsole.Write($"Site:"); | ||
502 | + ColorConsole.Write($"{wa.Xml_SiteName}", ConsoleColor.Cyan); | ||
503 | + var fc0 = | ||
504 | + wa.SiteState.Contains("Started") ? ConsoleColor.Green | ||
505 | + : wa.SiteState.Contains("Unregistered") ? ConsoleColor.Red | ||
506 | + : ConsoleColor.Yellow; | ||
507 | + ColorConsole.Write($"{wa.SiteState}", fc0, bracket: "()"); | ||
508 | + ColorConsole.Write($", Ports:"); | ||
509 | + ColorConsole.Write($"{wa.SitePortList}", ConsoleColor.White); | ||
510 | + ColorConsole.Write($", Phy.path:"); | ||
511 | + ColorConsole.WriteLine($"{wa.Xml_SitePhysicalPath}", ConsoleColor.White); | ||
512 | + } | ||
513 | + else if (lineix == 4) | ||
514 | + { | ||
515 | + ColorConsole.Write($"Pool:"); | ||
516 | + ColorConsole.Write($"{wa.Xml_PoolName}", ConsoleColor.Cyan); | ||
517 | + var fc1 = wa.PoolState == null ? ConsoleColor.Red | ||
518 | + : wa.PoolState.Contains("Started") ? ConsoleColor.Green | ||
519 | + : wa.PoolState.Contains("Unregistered") ? ConsoleColor.Red | ||
520 | + : ConsoleColor.Yellow; | ||
521 | + string waps = wa.PoolState == null ? "Unregistered/Unknown" : wa.PoolState; | ||
522 | + ColorConsole.Write($"{waps}", fc1, bracket: "()"); | ||
523 | + ColorConsole.Write($", identity:"); | ||
524 | + ColorConsole.WriteLine($"{wa.PoolAccount}", ConsoleColor.White); | ||
525 | + } | ||
526 | + else if (lineix == 5) | ||
527 | + { | ||
528 | + ColorConsole.WriteLine(); | ||
529 | + } | ||
530 | + else | ||
531 | + { | ||
532 | + return null; | ||
533 | + } | ||
534 | + return ""; | ||
535 | + } | ||
536 | + #endregion private method: DisplayWebAppInfo | ||
383 | } | 537 | } |
384 | 538 | ||
385 | public static class WebApplicationManagerCore | 539 | public static class WebApplicationManagerCore |
386 | { | 540 | { |
387 | #region private method: CollectWebAppInfo | 541 | #region private method: CollectWebAppInfo |
388 | - public static WebApplication CollectWebAppInfo(SiteCollection sites,ApplicationPoolCollection pools, WebApplication wadef) | 542 | + public static WebApplication CollectWebAppInfo(WebApplication wadef) |
389 | { | 543 | { |
390 | - var wa = new WebApplication(wadef); | ||
391 | - try | 544 | + using (ServerManager sm = new ServerManager()) |
392 | { | 545 | { |
393 | - wa.Site = sites[wa.Xml_SiteName]; | ||
394 | - if (wa.Site == null) { throw new Exception(); } | ||
395 | - else | 546 | + var sites = sm.Sites; |
547 | + var pools = sm.ApplicationPools; | ||
548 | + | ||
549 | + var wa = new WebApplication(wadef); | ||
550 | + try | ||
396 | { | 551 | { |
397 | - var ss = wa.Site.State; | ||
398 | - wa.SiteState = ss.ToString(); | ||
399 | - wa.SitePortList = ""; | ||
400 | - foreach (var binding in wa.Site.Bindings) | ||
401 | - { | ||
402 | - if (binding?.EndPoint?.Port != null) { wa.SitePortList += $"[{binding.EndPoint.Port}]"; } | ||
403 | - } | ||
404 | - var wn = Path.Combine("/", wa.Xml_AppName); | ||
405 | - var _wa = wa.Site.Applications[wn]; | ||
406 | - if (_wa == null) | 552 | + wa.Site = sites[wa.Xml_SiteName]; |
553 | + if (wa.Site == null) { throw new Exception(); } | ||
554 | + else | ||
407 | { | 555 | { |
408 | - wa.ApplicationState = "Unregistered/Unknown"; | ||
409 | - wa.ApplicationPath = ""; | ||
410 | - wa.Application = null; | ||
411 | - wa.AppImpersonateIdentity = ""; | 556 | + var ss = wa.Site.State; |
557 | + wa.SiteState = ss.ToString(); | ||
558 | + wa.SitePortList = ""; | ||
559 | + foreach (var binding in wa.Site.Bindings) | ||
560 | + { | ||
561 | + if (binding?.EndPoint?.Port != null) { wa.SitePortList += $"[{binding.EndPoint.Port}]"; } | ||
562 | + } | ||
563 | + var wn = Path.Combine("/", wa.Xml_AppName); | ||
564 | + var _wa = wa.Site.Applications[wn]; | ||
565 | + if (_wa == null) | ||
566 | + { | ||
567 | + wa.ApplicationState = "Unregistered/Unknown"; | ||
568 | + wa.ApplicationPath = ""; | ||
569 | + wa.Application = null; | ||
570 | + wa.AppImpersonateIdentity = ""; | ||
571 | + } | ||
572 | + else | ||
573 | + { | ||
574 | + wa.ApplicationState = "Registered"; | ||
575 | + wa.ApplicationPath = _wa.Path; | ||
576 | + wa.Application = _wa; | ||
577 | + wa.AppImpersonateIdentity = GetCurrentImpersonateIdentityInfo(wa); | ||
578 | + } | ||
412 | } | 579 | } |
580 | + } | ||
581 | + catch | ||
582 | + { | ||
583 | + wa.Site = null; | ||
584 | + wa.SiteState = "Unregistered/Unknown"; | ||
585 | + wa.SitePortList = ""; | ||
586 | + wa.Application = null; | ||
587 | + wa.ApplicationState = "Unregistered/Unknown"; | ||
588 | + wa.ApplicationPath = ""; | ||
589 | + }; | ||
590 | + try | ||
591 | + { | ||
592 | + wa.ApplicationPool = pools[wa.Xml_PoolName]; | ||
593 | + if (wa.ApplicationPool == null) { throw new Exception(); } | ||
413 | else | 594 | else |
414 | { | 595 | { |
415 | - wa.ApplicationState = "Registered"; | ||
416 | - wa.ApplicationPath = _wa.Path; | ||
417 | - wa.Application = _wa; | ||
418 | - wa.AppImpersonateIdentity = GetImpersonateIdentityInfo(wa.Xml_IdentityConfigFile); | 596 | + wa.PoolState = wa.ApplicationPool.State.ToString(); |
597 | + string pa = $"{wa.ApplicationPool.ProcessModel.IdentityType}"; | ||
598 | + if (wa.ApplicationPool.ProcessModel.IdentityType == ProcessModelIdentityType.SpecificUser) | ||
599 | + { | ||
600 | + pa += $"({wa.ApplicationPool.ProcessModel.UserName}[{wa.ApplicationPool.ProcessModel.Password}])"; | ||
601 | + } | ||
602 | + wa.PoolAccount = pa; | ||
419 | } | 603 | } |
420 | } | 604 | } |
421 | - } | ||
422 | - catch (Exception ex) | ||
423 | - { | ||
424 | - wa.Site = null; | ||
425 | - wa.SiteState = "Unregistered/Unknown"; | ||
426 | - wa.SitePortList = ""; | ||
427 | - wa.Application = null; | ||
428 | - wa.ApplicationState = "Unregistered/Unknown"; | ||
429 | - wa.ApplicationPath = ""; | ||
430 | - }; | ||
431 | - try | ||
432 | - { | ||
433 | - wa.ApplicationPool = pools[wa.Xml_PoolName]; | ||
434 | - if (wa.ApplicationPool == null) { throw new Exception(); } | ||
435 | - else | 605 | + catch |
436 | { | 606 | { |
437 | - wa.PoolState = wa.ApplicationPool.State.ToString(); | ||
438 | - string pa = $"{wa.ApplicationPool.ProcessModel.IdentityType}"; | ||
439 | - if (wa.ApplicationPool.ProcessModel.IdentityType == ProcessModelIdentityType.SpecificUser) | ||
440 | - { | ||
441 | - pa += $"({wa.ApplicationPool.ProcessModel.UserName}[{wa.ApplicationPool.ProcessModel.Password}])"; | ||
442 | - } | ||
443 | - wa.PoolAccount = pa; | 607 | + wa.ApplicationPool = null; |
608 | + wa.PoolState = "Unregistered/Unknown"; | ||
609 | + wa.PoolAccount = ""; | ||
444 | } | 610 | } |
611 | + return wa; | ||
445 | } | 612 | } |
446 | - catch | ||
447 | - { | ||
448 | - wa.ApplicationPool = null; | ||
449 | - wa.PoolState = "Unregistered/Unknown"; | ||
450 | - wa.PoolAccount = ""; | ||
451 | - } | ||
452 | - return wa; | ||
453 | } | 613 | } |
454 | #endregion private method: CollectWebAppInfo | 614 | #endregion private method: CollectWebAppInfo |
455 | 615 | ||
@@ -541,8 +701,9 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -541,8 +701,9 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
541 | #endregion private method:CommitChanges | 701 | #endregion private method:CommitChanges |
542 | 702 | ||
543 | #region private methods: Get information (with no ServerManager parameter) | 703 | #region private methods: Get information (with no ServerManager parameter) |
544 | - public static string GetImpersonateIdentityInfo(string filepath) | 704 | + public static string GetCurrentImpersonateIdentityInfo(WebApplication wa) |
545 | { | 705 | { |
706 | + var filepath = wa.Xml_ImpersonateIdentityConfigFile; | ||
546 | try | 707 | try |
547 | { | 708 | { |
548 | var xml = XElement.Load(filepath); | 709 | var xml = XElement.Load(filepath); |
@@ -553,6 +714,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -553,6 +714,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
553 | var impersonate = identityXml.Attribute(XName.Get("impersonate"))?.Value; | 714 | var impersonate = identityXml.Attribute(XName.Get("impersonate"))?.Value; |
554 | var username = identityXml.Attribute(XName.Get("userName"))?.Value; | 715 | var username = identityXml.Attribute(XName.Get("userName"))?.Value; |
555 | var password = identityXml.Attribute(XName.Get("password"))?.Value; | 716 | var password = identityXml.Attribute(XName.Get("password"))?.Value; |
717 | + | ||
556 | string unpswinfo = $", username[password]: {username}[{password}]"; | 718 | string unpswinfo = $", username[password]: {username}[{password}]"; |
557 | var userinfo = impersonate.ToLower() == "true" && !string.IsNullOrWhiteSpace(username) ? unpswinfo : ""; | 719 | var userinfo = impersonate.ToLower() == "true" && !string.IsNullOrWhiteSpace(username) ? unpswinfo : ""; |
558 | var retinfo = $"Impersonate={impersonate}{userinfo}"; | 720 | var retinfo = $"Impersonate={impersonate}{userinfo}"; |
@@ -561,22 +723,40 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -561,22 +723,40 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
561 | } | 723 | } |
562 | catch { return "no info (exception)"; } | 724 | catch { return "no info (exception)"; } |
563 | } | 725 | } |
564 | - public static string GetUserInfo(string poolname) | 726 | + public static string GetDefaultImpersonateIdentityInfo(WebApplication wa) |
727 | + { | ||
728 | + var impersonate = wa.Xml_ImpersonateIdentity; | ||
729 | + var username = wa.Xml_ImpersonateIdentityUsername; | ||
730 | + var password = wa.Xml_ImpersonateIdentityPassword; | ||
731 | + | ||
732 | + string unpswinfo = $", username[password]: {username}[{password}]"; | ||
733 | + var userinfo = impersonate && !string.IsNullOrWhiteSpace(username) ? unpswinfo : ""; | ||
734 | + var retinfo = $"Impersonate={impersonate}{userinfo}"; | ||
735 | + return retinfo; | ||
736 | + } | ||
737 | + public static string GetDefaultPoolIdentityInfo(WebApplication wa) | ||
738 | + { | ||
739 | + var pit = wa.Xml_PoolIdentitytype; | ||
740 | + var pun = wa.Xml_PoolUsername; | ||
741 | + var ppw = wa.Xml_PoolPassword; | ||
742 | + string userinfo = $"Identity type:{pit}"; | ||
743 | + if (pit == ProcessModelIdentityType.SpecificUser) { userinfo += $", username[password]:{pun}[{ppw}]"; } | ||
744 | + return userinfo; | ||
745 | + } | ||
746 | + public static string GetCurrentPoolIdentityInfo(WebApplication wa) | ||
565 | { | 747 | { |
748 | + string poolname = wa.Xml_PoolName; | ||
566 | using (var sm2 = new ServerManager()) | 749 | using (var sm2 = new ServerManager()) |
567 | { | 750 | { |
568 | - var pool = sm2.ApplicationPools[poolname]; | ||
569 | string userinfo = ""; | 751 | string userinfo = ""; |
752 | + var pool = sm2.ApplicationPools[poolname]; | ||
570 | if (pool != null) | 753 | if (pool != null) |
571 | { | 754 | { |
572 | - if (pool.ProcessModel.IdentityType == ProcessModelIdentityType.SpecificUser) | ||
573 | - { | ||
574 | - userinfo = $"{pool.ProcessModel.UserName}({pool.ProcessModel.Password})"; | ||
575 | - } | ||
576 | - else | ||
577 | - { | ||
578 | - userinfo = $"{pool.ProcessModel.IdentityType}"; | ||
579 | - } | 755 | + var pit = pool.ProcessModel.IdentityType; |
756 | + var pun = pool.ProcessModel.UserName; | ||
757 | + var ppw = pool.ProcessModel.IdentityType; | ||
758 | + userinfo = $"Identity type:{pit}"; | ||
759 | + if (pit == ProcessModelIdentityType.SpecificUser) { userinfo += $", username[password]:{pun}[{ppw}]"; } | ||
580 | } | 760 | } |
581 | return userinfo; | 761 | return userinfo; |
582 | } | 762 | } |
@@ -824,6 +1004,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -824,6 +1004,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
824 | public class WebApplication : XmlLinqBase | 1004 | public class WebApplication : XmlLinqBase |
825 | { | 1005 | { |
826 | #region properties from Xml definition | 1006 | #region properties from Xml definition |
1007 | + public string Xml_Key; | ||
827 | public string Xml_AppName; | 1008 | public string Xml_AppName; |
828 | public string Xml_Description; | 1009 | public string Xml_Description; |
829 | public string Xml_PoolName; | 1010 | public string Xml_PoolName; |
@@ -831,10 +1012,13 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -831,10 +1012,13 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
831 | public string Xml_AppPhysicalPath; | 1012 | public string Xml_AppPhysicalPath; |
832 | public ManagedPipelineMode Xml_PoolPipeLineMode; | 1013 | public ManagedPipelineMode Xml_PoolPipeLineMode; |
833 | public string Xml_SitePhysicalPath; | 1014 | public string Xml_SitePhysicalPath; |
834 | - public string Xml_IdentityConfigFile; | 1015 | + public string Xml_ImpersonateIdentityConfigFile; |
835 | public ProcessModelIdentityType Xml_PoolIdentitytype; | 1016 | public ProcessModelIdentityType Xml_PoolIdentitytype; |
836 | public string Xml_PoolUsername; | 1017 | public string Xml_PoolUsername; |
837 | public string Xml_PoolPassword; | 1018 | public string Xml_PoolPassword; |
1019 | + public string Xml_ImpersonateIdentityUsername; | ||
1020 | + public string Xml_ImpersonateIdentityPassword; | ||
1021 | + public bool Xml_ImpersonateIdentity; | ||
838 | public bool Xml_RecreatePool; | 1022 | public bool Xml_RecreatePool; |
839 | public bool Xml_RecreateSite; | 1023 | public bool Xml_RecreateSite; |
840 | public bool Xml_RecreateApp; | 1024 | public bool Xml_RecreateApp; |
@@ -859,6 +1043,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -859,6 +1043,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
859 | { | 1043 | { |
860 | string ATTRIBUTEMANDATORY = nameof(XmlStructure.WebApplication) + " attribute is mandatory! Name: {0}"; | 1044 | string ATTRIBUTEMANDATORY = nameof(XmlStructure.WebApplication) + " attribute is mandatory! Name: {0}"; |
861 | 1045 | ||
1046 | + Xml_Key= GetValue(nameof(XmlStructure.WebApplication.Attributes.Key), webappXml, XmlStructure.WebApplication.Attributes.Key.Values.DEFAULT); | ||
862 | Xml_AppName = webappXml.Attribute(XName.Get(nameof(XmlStructure.WebApplication.Attributes.Name)))?.Value; | 1047 | Xml_AppName = webappXml.Attribute(XName.Get(nameof(XmlStructure.WebApplication.Attributes.Name)))?.Value; |
863 | if (string.IsNullOrWhiteSpace(Xml_AppName)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, nameof(XmlStructure.WebApplication.Attributes.Name))); } | 1048 | if (string.IsNullOrWhiteSpace(Xml_AppName)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, nameof(XmlStructure.WebApplication.Attributes.Name))); } |
864 | 1049 | ||
@@ -876,7 +1061,6 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -876,7 +1061,6 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
876 | Xml_PoolPipeLineMode = GetValue(nameof(XmlStructure.WebApplication.Attributes.AppPoolPipeLineMode), webappXml, ManagedPipelineMode.Integrated); | 1061 | Xml_PoolPipeLineMode = GetValue(nameof(XmlStructure.WebApplication.Attributes.AppPoolPipeLineMode), webappXml, ManagedPipelineMode.Integrated); |
877 | } | 1062 | } |
878 | Xml_SitePhysicalPath = GetValue(nameof(XmlStructure.WebApplication.Attributes.SiteRootDir), webappXml, Xml_AppPhysicalPath); | 1063 | Xml_SitePhysicalPath = GetValue(nameof(XmlStructure.WebApplication.Attributes.SiteRootDir), webappXml, Xml_AppPhysicalPath); |
879 | - Xml_IdentityConfigFile = webappXml.Attribute(XName.Get(nameof(XmlStructure.WebApplication.Attributes.IdentityConfigFile)))?.Value; | ||
880 | 1064 | ||
881 | Xml_PoolUsername = GetValue(nameof(XmlStructure.WebApplication.Attributes.AppPoolUsername), webappXml, nameof(ProcessModelIdentityType.ApplicationPoolIdentity)); | 1065 | Xml_PoolUsername = GetValue(nameof(XmlStructure.WebApplication.Attributes.AppPoolUsername), webappXml, nameof(ProcessModelIdentityType.ApplicationPoolIdentity)); |
882 | Xml_PoolPassword = GetValue(nameof(XmlStructure.WebApplication.Attributes.AppPoolPassword), webappXml, ""); | 1066 | Xml_PoolPassword = GetValue(nameof(XmlStructure.WebApplication.Attributes.AppPoolPassword), webappXml, ""); |
@@ -884,6 +1068,11 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -884,6 +1068,11 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
884 | catch { Xml_PoolIdentitytype = ProcessModelIdentityType.SpecificUser; } | 1068 | catch { Xml_PoolIdentitytype = ProcessModelIdentityType.SpecificUser; } |
885 | if (Xml_PoolIdentitytype != ProcessModelIdentityType.SpecificUser) { Xml_PoolPassword = ""; Xml_PoolUsername = ""; } | 1069 | if (Xml_PoolIdentitytype != ProcessModelIdentityType.SpecificUser) { Xml_PoolPassword = ""; Xml_PoolUsername = ""; } |
886 | 1070 | ||
1071 | + Xml_ImpersonateIdentityConfigFile = webappXml.Attribute(XName.Get(nameof(XmlStructure.WebApplication.Attributes.ImpersonateIdentityConfigFile)))?.Value; | ||
1072 | + Xml_ImpersonateIdentity = GetValue(nameof(XmlStructure.WebApplication.Attributes.ImpersonateIdentity), webappXml, XmlStructure.WebApplication.Attributes.ImpersonateIdentity.Values.DEFAULT); | ||
1073 | + Xml_ImpersonateIdentityUsername = GetValue(nameof(XmlStructure.WebApplication.Attributes.ImpersonateIdentityUsername), webappXml, ""); | ||
1074 | + Xml_ImpersonateIdentityPassword= GetValue(nameof(XmlStructure.WebApplication.Attributes.ImpersonateIdentityPassword), webappXml, ""); | ||
1075 | + | ||
887 | Xml_RecreatePool = GetValue(nameof(XmlStructure.WebApplication.Attributes.RecreatePool), webappXml, false); | 1076 | Xml_RecreatePool = GetValue(nameof(XmlStructure.WebApplication.Attributes.RecreatePool), webappXml, false); |
888 | Xml_RecreateSite = GetValue(nameof(XmlStructure.WebApplication.Attributes.RecreateSite), webappXml, false); | 1077 | Xml_RecreateSite = GetValue(nameof(XmlStructure.WebApplication.Attributes.RecreateSite), webappXml, false); |
889 | Xml_RecreateApp = GetValue(nameof(XmlStructure.WebApplication.Attributes.RecreateApp), webappXml, true); | 1078 | Xml_RecreateApp = GetValue(nameof(XmlStructure.WebApplication.Attributes.RecreateApp), webappXml, true); |
@@ -893,19 +1082,27 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -893,19 +1082,27 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
893 | } | 1082 | } |
894 | public WebApplication(WebApplication wadef) | 1083 | public WebApplication(WebApplication wadef) |
895 | { | 1084 | { |
1085 | + Xml_Key = wadef.Xml_Key; | ||
896 | Xml_AppName = wadef.Xml_AppName; | 1086 | Xml_AppName = wadef.Xml_AppName; |
897 | Xml_Description = wadef.Xml_Description; | 1087 | Xml_Description = wadef.Xml_Description; |
898 | Xml_PoolName = wadef.Xml_PoolName; | 1088 | Xml_PoolName = wadef.Xml_PoolName; |
899 | Xml_SiteName = wadef.Xml_SiteName; | 1089 | Xml_SiteName = wadef.Xml_SiteName; |
900 | Xml_AppPhysicalPath = wadef.Xml_AppPhysicalPath; | 1090 | Xml_AppPhysicalPath = wadef.Xml_AppPhysicalPath; |
901 | Xml_SitePhysicalPath = wadef.Xml_SitePhysicalPath; | 1091 | Xml_SitePhysicalPath = wadef.Xml_SitePhysicalPath; |
902 | - Xml_IdentityConfigFile = wadef.Xml_IdentityConfigFile; | 1092 | + Xml_PoolPipeLineMode = wadef.Xml_PoolPipeLineMode; |
903 | Xml_PoolIdentitytype = wadef.Xml_PoolIdentitytype; | 1093 | Xml_PoolIdentitytype = wadef.Xml_PoolIdentitytype; |
1094 | + Xml_PoolUsername = wadef.Xml_PoolUsername; | ||
1095 | + Xml_PoolPassword = wadef.Xml_PoolPassword; | ||
904 | Xml_RecreateSite = wadef.Xml_RecreateSite; | 1096 | Xml_RecreateSite = wadef.Xml_RecreateSite; |
905 | Xml_RecreatePool = wadef.Xml_RecreatePool; | 1097 | Xml_RecreatePool = wadef.Xml_RecreatePool; |
906 | Xml_RecreateApp = wadef.Xml_RecreateApp; | 1098 | Xml_RecreateApp = wadef.Xml_RecreateApp; |
907 | Xml_ForceRemovePool = wadef.Xml_ForceRemovePool; | 1099 | Xml_ForceRemovePool = wadef.Xml_ForceRemovePool; |
908 | Xml_ForceRemoveSite = wadef.Xml_ForceRemoveSite; | 1100 | Xml_ForceRemoveSite = wadef.Xml_ForceRemoveSite; |
1101 | + | ||
1102 | + Xml_ImpersonateIdentityConfigFile = wadef.Xml_ImpersonateIdentityConfigFile; | ||
1103 | + Xml_ImpersonateIdentity = wadef.Xml_ImpersonateIdentity; | ||
1104 | + Xml_ImpersonateIdentityUsername = wadef.Xml_ImpersonateIdentityUsername; | ||
1105 | + Xml_ImpersonateIdentityPassword = wadef.Xml_ImpersonateIdentityPassword; | ||
909 | } | 1106 | } |
910 | #region XmlStructure | 1107 | #region XmlStructure |
911 | public static class XmlStructure | 1108 | public static class XmlStructure |
@@ -914,15 +1111,19 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -914,15 +1111,19 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
914 | { | 1111 | { |
915 | public static class Attributes | 1112 | public static class Attributes |
916 | { | 1113 | { |
1114 | + public static class Key { public static class Values { public const string DEFAULT = ""; } } | ||
917 | public static class Name { } | 1115 | public static class Name { } |
918 | public static class Description { } | 1116 | public static class Description { } |
919 | public static class AppPool { public static class Values { public const string DEFAULT = "DefaultAppPool"; } } | 1117 | public static class AppPool { public static class Values { public const string DEFAULT = "DefaultAppPool"; } } |
920 | public static class WebSite { public static class Values { public const string DEFAULT = "Default Web Site"; } } | 1118 | public static class WebSite { public static class Values { public const string DEFAULT = "Default Web Site"; } } |
921 | public static class InstallDir { } | 1119 | public static class InstallDir { } |
922 | public static class SiteRootDir { } | 1120 | public static class SiteRootDir { } |
923 | - public static class IdentityConfigFile { } | 1121 | + public static class ImpersonateIdentityConfigFile { } |
924 | public static class AppPoolUsername { } | 1122 | public static class AppPoolUsername { } |
925 | public static class AppPoolPassword { } | 1123 | public static class AppPoolPassword { } |
1124 | + public static class ImpersonateIdentityUsername { } | ||
1125 | + public static class ImpersonateIdentityPassword { } | ||
1126 | + public static class ImpersonateIdentity { public static class Values { public const bool DEFAULT = false; } } | ||
926 | public static class AppPoolPipeLineMode { } | 1127 | public static class AppPoolPipeLineMode { } |
927 | public static class RecreatePool { } | 1128 | public static class RecreatePool { } |
928 | public static class RecreateSite { } | 1129 | public static class RecreateSite { } |
Vrh.Log4Pro.MaintenanceConsole/Manager - WindowsServiceManager.cs
@@ -12,232 +12,54 @@ using Microsoft.Web.Administration; | @@ -12,232 +12,54 @@ using Microsoft.Web.Administration; | ||
12 | using System.Management; | 12 | using System.Management; |
13 | using System.Diagnostics; | 13 | using System.Diagnostics; |
14 | 14 | ||
15 | +using Vrh.Log4Pro.MaintenanceConsole.MenuNS; | ||
16 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
17 | +using Vrh.Log4Pro.MaintenanceConsole.ToolsNS; | ||
18 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
19 | + | ||
15 | using Vrh.XmlProcessing; | 20 | using Vrh.XmlProcessing; |
21 | +using VRH.Common; | ||
16 | using System.Xml.Linq; | 22 | using System.Xml.Linq; |
17 | using System.Text.RegularExpressions; | 23 | using System.Text.RegularExpressions; |
18 | 24 | ||
19 | -namespace Vrh.Log4Pro.MaintenanceConsole | 25 | +namespace Vrh.Log4Pro.MaintenanceConsole.WindowsServiceManagerNS |
20 | { | 26 | { |
21 | #region WindowsServiceManager class | 27 | #region WindowsServiceManager class |
22 | public static class WindowsServiceManager | 28 | public static class WindowsServiceManager |
23 | { | 29 | { |
30 | + private const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE_WINDOWSSERVICEMANAGER;"; | ||
31 | + private const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;element=WindowsServices;"; | ||
32 | + | ||
24 | #region Execute | 33 | #region Execute |
25 | public static object Execute(object o1 = null, object o2 = null) | 34 | public static object Execute(object o1 = null, object o2 = null) |
26 | { | 35 | { |
27 | - string xmlcs = "file=Config.Xml;element=WindowsServices;"; | ||
28 | - var config = new WindowsServiceManagerXmlProcessor(xmlcs, "", "hu-HU"); | 36 | + var args = (o1 as Menu.ExecutorParameter).Args; |
37 | + var functionkey = CommandLine.GetCommandLineArgument(args, CLP.CMD_FUNCTION); | ||
29 | 38 | ||
39 | + var config = new WindowsServiceManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); | ||
40 | + var ep = new Menu.ExecutorParameter(config, args); | ||
30 | var menufunctions = new Menu("Manage Windows Services", "Select the management function!") | 41 | var menufunctions = new Menu("Manage Windows Services", "Select the management function!") |
31 | - .AddMenuItem(new Menu.Item("WSR", "Register", Register)) | ||
32 | - .AddMenuItem(new Menu.Item("WSU", "Unregister", Unregister)) | ||
33 | - .AddMenuItem(new Menu.Item("WSS", "Start", Start)) | ||
34 | - .AddMenuItem(new Menu.Item("WSX", "Stop", Stop)) | ||
35 | - .AddMenuItem(new Menu.Item("WSK", "Kill", Kill)) | ||
36 | - .AddMenuItem(new Menu.Item("WSP", "Purge", Purge)) | ||
37 | - .AddMenuItem(new Menu.Item("WSA", "Set user account", SetUserAccount)) | ||
38 | - .SetSelectionMode(Menu.SelectionMode.Single); | ||
39 | - | ||
40 | - while (true) | ||
41 | - { | ||
42 | - Menu.Selection sr; | ||
43 | - | ||
44 | - menufunctions.DisplayTitle(); | ||
45 | - var menuservices = DisplayServices(config); | ||
46 | - menufunctions.DisplayItems(3, 35); | ||
47 | - sr = menufunctions.Select(); | ||
48 | - if (sr.Result == Menu.SelectionResult.Exit) { break; } | ||
49 | - else if (sr.Result == Menu.SelectionResult.None) { continue; } | ||
50 | - else if (sr.Result == Menu.SelectionResult.Error) { continue; } | ||
51 | - menufunctions.SetExecutorParameters(sr,config); | ||
52 | - menufunctions.ExecuteSelection(sr.SelectedKeyList); | ||
53 | - } | 42 | + .AddMenuItem(new Menu.Item(CLP.Module.WindowsServiceManager.Function.Register.KEY, "Register", Register,ep)) |
43 | + .AddMenuItem(new Menu.Item(CLP.Module.WindowsServiceManager.Function.Unregister.KEY, "Unregister", Unregister, ep)) | ||
44 | + .AddMenuItem(new Menu.Item(CLP.Module.WindowsServiceManager.Function.Start.KEY, "Start", Start, ep)) | ||
45 | + .AddMenuItem(new Menu.Item(CLP.Module.WindowsServiceManager.Function.Stop.KEY, "Stop", Stop, ep)) | ||
46 | + .AddMenuItem(new Menu.Item(CLP.Module.WindowsServiceManager.Function.Kill.KEY, "Kill", Kill, ep)) | ||
47 | + .AddMenuItem(new Menu.Item(CLP.Module.WindowsServiceManager.Function.Purge.KEY, "Purge", Purge, ep)) | ||
48 | + .AddMenuItem(new Menu.Item(CLP.Module.WindowsServiceManager.Function.SetUserAccount.KEY, "Set user account", SetUserAccount, ep)) | ||
49 | + .SetSelectionMode(Menu.SelectionMode.Single) | ||
50 | + .SetMenuHeaderDisplayer(ServiceListDisplayer); | ||
51 | + menufunctions.ExecuteMenu(functionkey); | ||
54 | return null; | 52 | return null; |
55 | } | 53 | } |
56 | #endregion Execute | 54 | #endregion Execute |
57 | 55 | ||
58 | - public static Menu DisplayServices(WindowsServiceManagerXmlProcessor config,string prompt = null,bool silent=false) | ||
59 | - { | ||
60 | - List<WindowsService> wsdefList = config.GetDefinitionList(); | ||
61 | - var menuservices = new Menu("Windows services",prompt) | ||
62 | - .SetMenuItemDisplayer(DisplayServiceInfo) | ||
63 | - .SetSelectionMode(Menu.SelectionMode.Multi) | ||
64 | - .SetHeaderWidth(4); | ||
65 | - menuservices.ClearMenuItemList(); | ||
66 | - foreach (var wsdef in wsdefList) | ||
67 | - { | ||
68 | - var w = CollectWindowsServiceInfo(wsdef); | ||
69 | - menuservices.AddMenuItem(new Menu.Item(null, null, null, w)); | ||
70 | - } | ||
71 | - if (!silent) { menuservices.DisplayItems(1); } | ||
72 | - return menuservices; | ||
73 | - } | ||
74 | - | ||
75 | - #region private method: DisplayServiceInfo | ||
76 | - private static object DisplayServiceInfo(object wsobj, int lineix) | ||
77 | - { | ||
78 | - WindowsService ws = wsobj as WindowsService; | ||
79 | - if (lineix == 0) | ||
80 | - { | ||
81 | - ColorConsole.Write($"{ws.Description}", ConsoleColor.Black, ConsoleColor.White); | ||
82 | - ColorConsole.WriteLine($"{ws.DisplayName}", bracket: "()"); | ||
83 | - return ws.DisplayName+ws.Description; | ||
84 | - } | ||
85 | - else if (lineix == 1) | ||
86 | - { | ||
87 | - ColorConsole.Write($"Win service:"); | ||
88 | - ColorConsole.Write($"{ws.Name}", ConsoleColor.Cyan); | ||
89 | - var fc2 = | ||
90 | - ws.Status.Contains(nameof(WmiServiceStatus.OK)) ? ConsoleColor.Green | ||
91 | - : ws.Status.Contains(nameof(WmiServiceStatus.Unknown)) ? ConsoleColor.Red | ||
92 | - : ws.Status.Contains(nameof(WmiServiceStatus.Error)) ? ConsoleColor.Red | ||
93 | - : ConsoleColor.Yellow; | ||
94 | - ColorConsole.Write($"("); | ||
95 | - ColorConsole.Write($"{ws.Status}", fc2); | ||
96 | - var fc0 = | ||
97 | - ws.State.Contains(nameof(WmiServiceState.Running)) ? ConsoleColor.Green | ||
98 | - : ws.State.Contains(nameof(WmiServiceState.Unknown)) ? ConsoleColor.Red | ||
99 | - : ws.State.Contains(nameof(WmiServiceState.Unregistered)) ? ConsoleColor.Red | ||
100 | - : ConsoleColor.Yellow; | ||
101 | - ColorConsole.Write($" / "); | ||
102 | - ColorConsole.Write($"{ws.State}", fc0); | ||
103 | - ColorConsole.Write($")"); | ||
104 | - ColorConsole.Write($", StartMode:"); | ||
105 | - ColorConsole.Write($"{ws.StartMode}", ConsoleColor.Cyan); | ||
106 | - if(ws.Status==nameof(WmiServiceStatus.OK) && ws.State != nameof(WmiServiceState.Stopped) && ws.State != nameof(WmiServiceState.Unknown)) | ||
107 | - { | ||
108 | - ColorConsole.Write($", Priority:"); | ||
109 | - ColorConsole.Write($"{ws.PriorityClass}", ConsoleColor.White); | ||
110 | - ColorConsole.Write($", ProcessId:"); | ||
111 | - ColorConsole.Write($"{ws.ProcessId}", ConsoleColor.White); | ||
112 | - } | ||
113 | - ColorConsole.WriteLine(); | ||
114 | - return ws.Name; | ||
115 | - } | ||
116 | - else if (lineix == 2) | ||
117 | - { | ||
118 | - if (string.IsNullOrEmpty(ws.PathName)) { return ""; } | ||
119 | - var cmdarray = CommandLineParser.SplitArgs(ws.PathName).ToArray(); | ||
120 | - ColorConsole.Write($"Start command:"); | ||
121 | - ColorConsole.WriteLine($"{cmdarray[0]}", ConsoleColor.White); | ||
122 | - return ws.PathName; | ||
123 | - } | ||
124 | - else if (lineix == 3) | ||
125 | - { | ||
126 | - if (string.IsNullOrEmpty(ws.PathName)) { return ""; } | ||
127 | - var cmdparams = CommandLineParser.SplitArgs(ws.PathName).Skip(1).ToArray(); | ||
128 | - if (cmdparams.Length==0) { return ""; } | ||
129 | - var cmdparamsstr = string.Join("][", cmdparams); | ||
130 | - ColorConsole.Write($"Start arguments:"); | ||
131 | - ColorConsole.WriteLine($"[{cmdparamsstr}]", ConsoleColor.White); | ||
132 | - return cmdparamsstr; | ||
133 | - } | ||
134 | - else if (lineix == 4) | ||
135 | - { | ||
136 | - ColorConsole.Write($"User:"); | ||
137 | - ColorConsole.WriteLine($"{ws.StartName}", ConsoleColor.White); | ||
138 | - return ws.StartName; | ||
139 | - } | ||
140 | - else if (lineix == 5) | ||
141 | - { | ||
142 | - ColorConsole.WriteLine(); | ||
143 | - return " "; | ||
144 | - } | ||
145 | - return null; | ||
146 | - } | ||
147 | - private enum WmiServiceState | ||
148 | - { | ||
149 | - StartPending, | ||
150 | - Running, | ||
151 | - Paused, | ||
152 | - PausedPending, | ||
153 | - Stopped, | ||
154 | - StopPending, | ||
155 | - Unknown, | ||
156 | - Unregistered, | ||
157 | - } | ||
158 | - private enum WmiServiceStatus | ||
159 | - { | ||
160 | - OK, | ||
161 | - Error, | ||
162 | - Degraded, | ||
163 | - Unknown, | ||
164 | - Pred_Fail, | ||
165 | - Starting, | ||
166 | - Stopping, | ||
167 | - Service, | ||
168 | - Stressed, | ||
169 | - NonRecover, | ||
170 | - No_Contact, | ||
171 | - Lost_Comm, | ||
172 | - Unregistered, | ||
173 | - } | ||
174 | - #endregion private method: DisplayServiceInfo | ||
175 | - | ||
176 | - #region private CollectWindowsServiceInfo | ||
177 | - private static WindowsService CollectWindowsServiceInfo(WindowsService ws) | ||
178 | - { | ||
179 | - using (var wmiService = WindowsServiceManagerCore.GetServiceObject(ws.Name)) | ||
180 | - { | ||
181 | - using (var service = WindowsServiceManagerCore.GetServiceController(ws.Name)) | ||
182 | - { | ||
183 | - var wmiserviceproblem = false; | ||
184 | - try { wmiService.Get();}catch { wmiserviceproblem = true; } | ||
185 | - if (wmiService == null || service == null || wmiserviceproblem) | ||
186 | - { | ||
187 | - ws.DisplayName = ws.Xml_DisplayName; | ||
188 | - ws.Description = ws.Xml_Description; | ||
189 | - ws.ThisDependsOn = ws.Xml_Dependon; | ||
190 | - ws.ServicesDependOnThis = new string[] { "???" }; | ||
191 | - ws.PathName = $"\"{ws.Xml_Exe}\" {ws.Xml_Arguments}"; | ||
192 | - ws.StartMode = ws.Xml_StartMode; | ||
193 | - ws.State = nameof(WmiServiceState.Unregistered); | ||
194 | - ws.Status = nameof(WmiServiceStatus.Unregistered); | ||
195 | - if (ws.Xml_IdentityType== ServiceAccount.User) { ws.StartName = ws.Xml_Username + $"({ws.Xml_Password})"; } | ||
196 | - else { ws.StartName = ws.Xml_IdentityType.ToString(); } | ||
197 | - ws.ProcessId = 0; | ||
198 | - ws.PriorityClass = ws.Xml_Priority; | ||
199 | - } | ||
200 | - else | ||
201 | - { | ||
202 | - ws.DisplayName = (string)wmiService[nameof(WindowsService.DisplayName)]; | ||
203 | - ws.Description = (string)wmiService[nameof(WindowsService.Description)]; | ||
204 | - if (string.IsNullOrEmpty(ws.Description)) { ws.Description = ws.DisplayName; } | ||
205 | - if (string.IsNullOrEmpty(ws.DisplayName)) { ws.DisplayName = ws.Description; } | ||
206 | - ws.ServicesDependOnThis = service.DependentServices.Select(s => s.ServiceName).ToArray(); | ||
207 | - try { ws.ThisDependsOn = service.ServicesDependedOn.Select(s => s.ServiceName).ToArray(); } catch { ws.ThisDependsOn = new string[] { "???" }; } | ||
208 | - ws.PathName = (string)wmiService[nameof(WindowsService.PathName)];if (ws.PathName == null) { ws.PathName = ""; } | ||
209 | - var sm = (string)wmiService[nameof(WindowsService.StartMode)]; | ||
210 | - ws.StartMode = | ||
211 | - sm == "Auto" ? ServiceStartMode.Automatic | ||
212 | - : sm == "Auto" ? ServiceStartMode.Manual | ||
213 | - : sm == "Auto" ? ServiceStartMode.Disabled | ||
214 | - : sm == "Auto" ? ServiceStartMode.Boot | ||
215 | - : sm == "Auto" ? ServiceStartMode.System | ||
216 | - : ServiceStartMode.Manual; | ||
217 | - ws.State = (string)wmiService[nameof(WindowsService.State)]; | ||
218 | - ws.Status = (string)wmiService[nameof(WindowsService.Status)]; | ||
219 | - ws.StartName = (string)wmiService[nameof(WindowsService.StartName)]; | ||
220 | - ws.ProcessId = 0; | ||
221 | - ws.PriorityClass = "-"; | ||
222 | - if (ws.State != nameof(WmiServiceState.Stopped)) | ||
223 | - { | ||
224 | - ws.ProcessId = Convert.ToInt32(wmiService[nameof(WindowsService.ProcessId)]); | ||
225 | - ws.PriorityClass = Process.GetProcessById(ws.ProcessId).PriorityClass.ToString(); | ||
226 | - } | ||
227 | - } | ||
228 | - } | ||
229 | - } | ||
230 | - return ws; | ||
231 | - } | ||
232 | - #endregion private CollectWindowsServiceInfo | ||
233 | - | ||
234 | #region First level Executors with UI | 56 | #region First level Executors with UI |
235 | - private static object Purge(object parameter,object o) | 57 | + private static object Purge(object parameter, object o) |
236 | { | 58 | { |
237 | - var config = parameter as WindowsServiceManagerXmlProcessor; | 59 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<WindowsServiceManagerXmlProcessor>(); |
238 | while (true) | 60 | while (true) |
239 | { | 61 | { |
240 | - ColorConsole.Write($"Enter servicename mask (% and ? are wildchars)!",ConsoleColor.Yellow); | 62 | + ColorConsole.Write($"Enter servicename mask (% and ? are wildchars)!", ConsoleColor.Yellow); |
241 | var mask = ColorConsole.ReadLine($" ---> ", ConsoleColor.Yellow).ToUpper(); | 63 | var mask = ColorConsole.ReadLine($" ---> ", ConsoleColor.Yellow).ToUpper(); |
242 | if (mask == "EX") { return o; } | 64 | if (mask == "EX") { return o; } |
243 | else if (mask == "") { continue; } | 65 | else if (mask == "") { continue; } |
@@ -245,12 +67,11 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -245,12 +67,11 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
245 | if (sl.Length > 10) { sl = sl.Take(10).ToArray(); } | 67 | if (sl.Length > 10) { sl = sl.Take(10).ToArray(); } |
246 | 68 | ||
247 | var menuservices = new Menu("Windows services", "Select the windows service(es) to delete (max 10 in one run)!") | 69 | var menuservices = new Menu("Windows services", "Select the windows service(es) to delete (max 10 in one run)!") |
248 | - .SetSelectionMode(Menu.SelectionMode.Multi) | ||
249 | - .SetHeaderWidth(4); | 70 | + .SetSelectionMode(Menu.SelectionMode.Multi); |
250 | 71 | ||
251 | for (var i = 0; i < sl.Length; i++) | 72 | for (var i = 0; i < sl.Length; i++) |
252 | { | 73 | { |
253 | - menuservices.AddMenuItem(new Menu.Item(null, $"{sl[i].ServiceName} ({sl[i].DisplayName})", null, sl[i].ServiceName)); | 74 | + menuservices.AddMenuItem(new Menu.Item(null, $"{sl[i].ServiceName} ({sl[i].DisplayName})", null, new Menu.ExecutorParameter(pars:sl[i].ServiceName))); |
254 | } | 75 | } |
255 | menuservices.DisplayItems(1); | 76 | menuservices.DisplayItems(1); |
256 | var ms = menuservices.Select(); | 77 | var ms = menuservices.Select(); |
@@ -259,21 +80,21 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -259,21 +80,21 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
259 | else if (ms.Result == Menu.SelectionResult.Exit) { break; } | 80 | else if (ms.Result == Menu.SelectionResult.Exit) { break; } |
260 | else | 81 | else |
261 | { | 82 | { |
262 | - foreach (var p in ms.SelectedParameterList) | 83 | + foreach (var p in ms.SelectedParameterList) |
263 | { | 84 | { |
264 | ColorConsole.Write($"Enter CONFIRM to delete service ", ConsoleColor.Yellow); | 85 | ColorConsole.Write($"Enter CONFIRM to delete service ", ConsoleColor.Yellow); |
265 | - ColorConsole.Write($"{p}", ConsoleColor.White,bracket:"''"); | 86 | + ColorConsole.Write($"{p}", ConsoleColor.White, bracket: "''"); |
266 | ColorConsole.Write($"!", ConsoleColor.Yellow); | 87 | ColorConsole.Write($"!", ConsoleColor.Yellow); |
267 | var confirmation = ColorConsole.ReadLine(prefix: " ---> ").ToUpper(); | 88 | var confirmation = ColorConsole.ReadLine(prefix: " ---> ").ToUpper(); |
268 | if (confirmation == "EX") { return o; } | 89 | if (confirmation == "EX") { return o; } |
269 | - else if (confirmation == "") | 90 | + else if (confirmation == "") |
270 | { | 91 | { |
271 | ColorConsole.WriteLine($"Service '{p}' skipped!", ConsoleColor.Green); | 92 | ColorConsole.WriteLine($"Service '{p}' skipped!", ConsoleColor.Green); |
272 | - continue; | 93 | + continue; |
273 | } | 94 | } |
274 | else if (confirmation == "CONFIRM") | 95 | else if (confirmation == "CONFIRM") |
275 | { | 96 | { |
276 | - WindowsServiceManagerCore.Unregister((string)p); | 97 | + WindowsServiceManagerCore.Unregister((string)(p.Parameters)); |
277 | ColorConsole.WriteLine($"Service '{p}' deleted!", ConsoleColor.Green); | 98 | ColorConsole.WriteLine($"Service '{p}' deleted!", ConsoleColor.Green); |
278 | } | 99 | } |
279 | } | 100 | } |
@@ -281,12 +102,16 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -281,12 +102,16 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
281 | } | 102 | } |
282 | return o; | 103 | return o; |
283 | } | 104 | } |
284 | - private static object Kill(object parameter,object o) | 105 | + private static object Kill(object parameter, object o) |
285 | { | 106 | { |
286 | - var config = parameter as WindowsServiceManagerXmlProcessor; | ||
287 | - var menuservices = DisplayServices(config, $"Select the windows service(es) to manage with function '{nameof(Kill)}'!", silent:true); | 107 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<WindowsServiceManagerXmlProcessor>(); |
108 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
288 | 109 | ||
289 | - Menu.Selection sr = menuservices.Select(); | 110 | + var selectedserviceindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WindowsServiceManager.Function.CMD_SERVICES); |
111 | + | ||
112 | + var menuservices = DisplayWindowsServiceMenu(config, $"Select the windows service(es) to manage with function '{nameof(Kill)}'!", silent: true); | ||
113 | + | ||
114 | + Menu.Selection sr = menuservices.Select(selectedserviceindexes); | ||
290 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 115 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
291 | else if (sr.Result == Menu.SelectionResult.None) { return o; } | 116 | else if (sr.Result == Menu.SelectionResult.None) { return o; } |
292 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } | 117 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } |
@@ -294,25 +119,26 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -294,25 +119,26 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
294 | else { } | 119 | else { } |
295 | foreach (var p in sr.SelectedParameterList) | 120 | foreach (var p in sr.SelectedParameterList) |
296 | { | 121 | { |
297 | - WindowsService ws = p as WindowsService; | 122 | + WindowsService ws = p.Parameters as WindowsService; |
298 | try | 123 | try |
299 | { | 124 | { |
300 | var success = WindowsServiceManagerCore.Kill(ws.Name); | 125 | var success = WindowsServiceManagerCore.Kill(ws.Name); |
301 | ColorConsole.WriteLine($"Service killed. Name:{ws.Name}", ConsoleColor.Green); | 126 | ColorConsole.WriteLine($"Service killed. Name:{ws.Name}", ConsoleColor.Green); |
302 | } | 127 | } |
303 | - catch (Exception ex) | ||
304 | - { | ||
305 | - ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); | ||
306 | - } | 128 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } |
307 | } | 129 | } |
308 | return o; | 130 | return o; |
309 | } | 131 | } |
310 | - private static object Register(object parameter, object o) | 132 | + private static object Register(object parameter, object o) |
311 | { | 133 | { |
312 | - var config = parameter as WindowsServiceManagerXmlProcessor; | ||
313 | - var menuservices = DisplayServices(config, $"Select the windows service(es) to manage with function '{nameof(Register)}'!", silent: true); | 134 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<WindowsServiceManagerXmlProcessor>(); |
135 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
314 | 136 | ||
315 | - Menu.Selection sr = menuservices.Select(); | 137 | + var selectedserviceindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WindowsServiceManager.Function.CMD_SERVICES); |
138 | + | ||
139 | + var menuservices = DisplayWindowsServiceMenu(config, $"Select the windows service(es) to manage with function '{nameof(Register)}'!", silent: true); | ||
140 | + | ||
141 | + Menu.Selection sr = menuservices.Select(selectedserviceindexes); | ||
316 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 142 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
317 | else if (sr.Result == Menu.SelectionResult.None) { return o; } | 143 | else if (sr.Result == Menu.SelectionResult.None) { return o; } |
318 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } | 144 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } |
@@ -320,25 +146,25 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -320,25 +146,25 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
320 | else { } | 146 | else { } |
321 | foreach (var p in sr.SelectedParameterList) | 147 | foreach (var p in sr.SelectedParameterList) |
322 | { | 148 | { |
323 | - WindowsService ws = p as WindowsService; | 149 | + WindowsService ws = p.Parameters as WindowsService; |
324 | try | 150 | try |
325 | { | 151 | { |
326 | - var success = WindowsServiceManagerCore.Register(ws); | ||
327 | - ColorConsole.WriteLine($"Service registered. Name:{ws.Name}", ConsoleColor.Green); | ||
328 | - } | ||
329 | - catch (Exception ex) | ||
330 | - { | ||
331 | - ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); | 152 | + var success = WindowsServiceManagerCore.Register(ws, sr.SelectedParameterList.Select(x => (x.Parameters as WindowsService).Name).ToList()); |
153 | + ColorConsole.WriteLine($"Service unregistered. Name:{ws.Name}", ConsoleColor.Green); | ||
332 | } | 154 | } |
155 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } | ||
333 | } | 156 | } |
334 | return o; | 157 | return o; |
335 | } | 158 | } |
336 | - private static object Unregister(object parameter,object o) | 159 | + private static object Unregister(object parameter, object o) |
337 | { | 160 | { |
338 | - var config = parameter as WindowsServiceManagerXmlProcessor; | ||
339 | - var menuservices = DisplayServices(config, $"Select the windows service(es) to manage with function '{nameof(Unregister)}'!", silent: true); | 161 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<WindowsServiceManagerXmlProcessor>(); |
162 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
163 | + var selectedserviceindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WindowsServiceManager.Function.CMD_SERVICES); | ||
164 | + | ||
165 | + var menuservices = DisplayWindowsServiceMenu(config, $"Select the windows service(es) to manage with function '{nameof(Unregister)}'!", silent: true); | ||
340 | 166 | ||
341 | - Menu.Selection sr = menuservices.Select(); | 167 | + Menu.Selection sr = menuservices.Select(selectedserviceindexes); |
342 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 168 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
343 | else if (sr.Result == Menu.SelectionResult.None) { return o; } | 169 | else if (sr.Result == Menu.SelectionResult.None) { return o; } |
344 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } | 170 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } |
@@ -346,25 +172,25 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -346,25 +172,25 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
346 | else { } | 172 | else { } |
347 | foreach (var p in sr.SelectedParameterList) | 173 | foreach (var p in sr.SelectedParameterList) |
348 | { | 174 | { |
349 | - WindowsService ws = p as WindowsService; | 175 | + WindowsService ws = p.Parameters as WindowsService; |
350 | try | 176 | try |
351 | { | 177 | { |
352 | var success = WindowsServiceManagerCore.Unregister(ws); | 178 | var success = WindowsServiceManagerCore.Unregister(ws); |
353 | ColorConsole.WriteLine($"Service unregistered. Name:{ws.Name}", ConsoleColor.Green); | 179 | ColorConsole.WriteLine($"Service unregistered. Name:{ws.Name}", ConsoleColor.Green); |
354 | } | 180 | } |
355 | - catch (Exception ex) | ||
356 | - { | ||
357 | - ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); | ||
358 | - } | 181 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } |
359 | } | 182 | } |
360 | return o; | 183 | return o; |
361 | } | 184 | } |
362 | - private static object Start(object parameter,object o) | 185 | + private static object Start(object parameter, object o) |
363 | { | 186 | { |
364 | - var config = parameter as WindowsServiceManagerXmlProcessor; | ||
365 | - var menuservices = DisplayServices(config, $"Select the windows service(es) to manage with function '{nameof(Start)}'!", silent: true); | 187 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<WindowsServiceManagerXmlProcessor>(); |
188 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
189 | + var selectedserviceindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WindowsServiceManager.Function.CMD_SERVICES); | ||
366 | 190 | ||
367 | - Menu.Selection sr = menuservices.Select(); | 191 | + var menuservices = DisplayWindowsServiceMenu(config, $"Select the windows service(es) to manage with function '{nameof(Start)}'!", silent: true); |
192 | + | ||
193 | + Menu.Selection sr = menuservices.Select(selectedserviceindexes); | ||
368 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 194 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
369 | else if (sr.Result == Menu.SelectionResult.None) { return o; } | 195 | else if (sr.Result == Menu.SelectionResult.None) { return o; } |
370 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } | 196 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } |
@@ -372,25 +198,25 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -372,25 +198,25 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
372 | else { } | 198 | else { } |
373 | foreach (var p in sr.SelectedParameterList) | 199 | foreach (var p in sr.SelectedParameterList) |
374 | { | 200 | { |
375 | - WindowsService ws = p as WindowsService; | 201 | + WindowsService ws = p.Parameters as WindowsService; |
376 | try | 202 | try |
377 | { | 203 | { |
378 | var success = WindowsServiceManagerCore.Start(ws.Name, ws.Xml_StartTimeout); | 204 | var success = WindowsServiceManagerCore.Start(ws.Name, ws.Xml_StartTimeout); |
379 | ColorConsole.WriteLine($"Service started. Name:{ws.Name}", ConsoleColor.Green); | 205 | ColorConsole.WriteLine($"Service started. Name:{ws.Name}", ConsoleColor.Green); |
380 | } | 206 | } |
381 | - catch (Exception ex) | ||
382 | - { | ||
383 | - ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); | ||
384 | - } | 207 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } |
385 | } | 208 | } |
386 | return o; | 209 | return o; |
387 | } | 210 | } |
388 | - private static object Stop(object parameter,object o) | 211 | + private static object Stop(object parameter, object o) |
389 | { | 212 | { |
390 | - var config = parameter as WindowsServiceManagerXmlProcessor; | ||
391 | - var menuservices = DisplayServices(config, $"Select the windows service(es) to manage with function '{nameof(Kill)}'!", silent: true); | 213 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<WindowsServiceManagerXmlProcessor>(); |
214 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
215 | + var selectedserviceindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WindowsServiceManager.Function.CMD_SERVICES); | ||
216 | + | ||
217 | + var menuservices = DisplayWindowsServiceMenu(config, $"Select the windows service(es) to manage with function '{nameof(Kill)}'!", silent: true); | ||
392 | 218 | ||
393 | - Menu.Selection sr = menuservices.Select(); | 219 | + Menu.Selection sr = menuservices.Select(selectedserviceindexes); |
394 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 220 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
395 | else if (sr.Result == Menu.SelectionResult.None) { return o; } | 221 | else if (sr.Result == Menu.SelectionResult.None) { return o; } |
396 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } | 222 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } |
@@ -398,25 +224,25 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -398,25 +224,25 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
398 | else { } | 224 | else { } |
399 | foreach (var p in sr.SelectedParameterList) | 225 | foreach (var p in sr.SelectedParameterList) |
400 | { | 226 | { |
401 | - WindowsService ws = p as WindowsService; | 227 | + WindowsService ws = p.Parameters as WindowsService; |
402 | try | 228 | try |
403 | { | 229 | { |
404 | var success = WindowsServiceManagerCore.Stop(ws.Name, ws.Xml_StopTimeout); | 230 | var success = WindowsServiceManagerCore.Stop(ws.Name, ws.Xml_StopTimeout); |
405 | ColorConsole.WriteLine($"Service stopped. Name:{ws.Name}", ConsoleColor.Green); | 231 | ColorConsole.WriteLine($"Service stopped. Name:{ws.Name}", ConsoleColor.Green); |
406 | } | 232 | } |
407 | - catch (Exception ex) | ||
408 | - { | ||
409 | - ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); | ||
410 | - } | 233 | + catch (Exception ex) { ColorConsole.WriteLine(ex.Message, ConsoleColor.Red); } |
411 | } | 234 | } |
412 | return o; | 235 | return o; |
413 | } | 236 | } |
414 | - private static object SetUserAccount(object parameter,object o) | ||
415 | - { | ||
416 | - var config = parameter as WindowsServiceManagerXmlProcessor; | ||
417 | - var menuservices = DisplayServices(config, $"Select the windows service(es) to manage with function '{nameof(SetUserAccount)}'!", silent: true); | 237 | + private static object SetUserAccount(object parameter, object o) |
238 | + { | ||
239 | + var config = (parameter as Menu.ExecutorParameter).GetConfig<WindowsServiceManagerXmlProcessor>(); | ||
240 | + var args = (parameter as Menu.ExecutorParameter).Args; | ||
241 | + var selectedserviceindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.WindowsServiceManager.Function.CMD_SERVICES); | ||
242 | + | ||
243 | + var menuservices = DisplayWindowsServiceMenu(config, $"Select the windows service(es) to manage with function '{nameof(SetUserAccount)}'!", silent: true); | ||
418 | 244 | ||
419 | - Menu.Selection sr = menuservices.Select(); | 245 | + Menu.Selection sr = menuservices.Select(selectedserviceindexes); |
420 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } | 246 | if (sr.Result == Menu.SelectionResult.Exit) { return o; } |
421 | else if (sr.Result == Menu.SelectionResult.None) { return o; } | 247 | else if (sr.Result == Menu.SelectionResult.None) { return o; } |
422 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } | 248 | else if (sr.Result == Menu.SelectionResult.Error) { return o; } |
@@ -426,37 +252,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -426,37 +252,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
426 | string username = null, password = null; | 252 | string username = null, password = null; |
427 | foreach (var p in sr.SelectedParameterList) | 253 | foreach (var p in sr.SelectedParameterList) |
428 | { | 254 | { |
429 | - WindowsService ws = p as WindowsService; | 255 | + WindowsService ws = p.Parameters as WindowsService; |
430 | try | 256 | try |
431 | { | 257 | { |
432 | using (var wmiService = WindowsServiceManagerCore.GetServiceObject(ws.Name)) | 258 | using (var wmiService = WindowsServiceManagerCore.GetServiceObject(ws.Name)) |
433 | { | 259 | { |
434 | - if (username==null) | ||
435 | - { | ||
436 | - string olduserinfo = WindowsServiceManagerCore.GetUserInfo(wmiService); | ||
437 | - ColorConsole.WriteLine($"Current user info: {olduserinfo}"); | ||
438 | - ColorConsole.WriteLine("Enter username then password. [Enter]=save.EX=exit"); | ||
439 | - ColorConsole.WriteLine("Username is in the form of 'domainname\\username'"); | ||
440 | - ColorConsole.WriteLine("Special usernames are: (Empty=API) "); | ||
441 | - | ||
442 | - ColorConsole.WriteLine($"LSE", ConsoleColor.Yellow, bracket: "()", prefix: " ", suffix: $" {nameof(ServiceAccount.LocalService)}"); | ||
443 | - ColorConsole.WriteLine($"LSY", ConsoleColor.Yellow, bracket: "()", prefix: " ", suffix: $" {nameof(ServiceAccount.LocalSystem)}"); | ||
444 | - ColorConsole.WriteLine($"NSE", ConsoleColor.Yellow, bracket: "()", prefix: " ", suffix: $" {nameof(ServiceAccount.NetworkService)}"); | ||
445 | - | ||
446 | - ColorConsole.WriteLine(); | ||
447 | - ColorConsole.WriteLine($"EX", ConsoleColor.Red, bracket: "()", prefix: " ", suffix: " Exit"); | ||
448 | - | ||
449 | - username = ColorConsole.ReadLine("username -->", ConsoleColor.Yellow, bracket: "[]"); | ||
450 | - if (username == "EX") { return null; } | ||
451 | - else if (string.IsNullOrEmpty(username)) { username = nameof(ServiceAccount.LocalSystem); } | ||
452 | - else if (username.ToUpper() == "LSE" || username == nameof(ServiceAccount.LocalService)) { username = nameof(ServiceAccount.LocalService); } | ||
453 | - else if (username.ToUpper() == "LSY" || username == nameof(ServiceAccount.LocalSystem)) { username = nameof(ServiceAccount.LocalSystem); } | ||
454 | - else if (username.ToUpper() == "NSE" || username == nameof(ServiceAccount.NetworkService)) { username = nameof(ServiceAccount.NetworkService); } | ||
455 | - else | ||
456 | - { | ||
457 | - password = ColorConsole.ReadLine("password -->", ConsoleColor.Yellow, bracket: "[]"); | ||
458 | - if (password == "EX") { return null; } | ||
459 | - } | 260 | + if (username == null) |
261 | + { | ||
262 | + GetUsernameAndPassword(wmiService,ws,out username, out password); | ||
263 | + if (username == "EX" || password == "EX") { return null; } | ||
460 | } | 264 | } |
461 | if (WindowsServiceManagerCore.SetUserAccount(wmiService, username, password)) { ColorConsole.WriteLine($"Service user account changed. Name:{ws.Name}", ConsoleColor.Green); } | 265 | if (WindowsServiceManagerCore.SetUserAccount(wmiService, username, password)) { ColorConsole.WriteLine($"Service user account changed. Name:{ws.Name}", ConsoleColor.Green); } |
462 | else { ColorConsole.WriteLine($"Service user account change FAILED! Name:{ws.Name}", ConsoleColor.Red); } | 266 | else { ColorConsole.WriteLine($"Service user account change FAILED! Name:{ws.Name}", ConsoleColor.Red); } |
@@ -467,6 +271,147 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -467,6 +271,147 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
467 | return o; | 271 | return o; |
468 | } | 272 | } |
469 | #endregion First level Executors with UI | 273 | #endregion First level Executors with UI |
274 | + | ||
275 | + #region DisplayServices | ||
276 | + private static void ServiceListDisplayer() { DisplayWindowsServiceMenu(); } | ||
277 | + public static Menu DisplayWindowsServiceMenu(WindowsServiceManagerXmlProcessor config=null,string prompt = null,bool silent=false) | ||
278 | + { | ||
279 | + if (config==null) { config = new WindowsServiceManagerXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); } | ||
280 | + var menuservices = new Menu("Windows services",prompt) | ||
281 | + .SetMenuItemDisplayer(DisplayServiceInfo) | ||
282 | + .SetSelectionMode(Menu.SelectionMode.Multi); | ||
283 | + menuservices.ClearMenuItemList(); | ||
284 | + | ||
285 | + List<WindowsServiceGroup> wsgdefList = config.GetWindowsServiceGroupDefinitionList(); | ||
286 | + foreach (var wsgdef in wsgdefList) | ||
287 | + { | ||
288 | + string menuitemtext = wsgdef.Xml_Description + "(" + string.Join(",", wsgdef.Xml_WindowsServiceKeyList) + ")"; | ||
289 | + menuservices.AddMenuItem(new Menu.ItemGroup(wsgdef.Xml_Key, menuitemtext, wsgdef.Xml_WindowsServiceKeyList)); | ||
290 | + } | ||
291 | + | ||
292 | + menuservices.AddMenuItem(new Menu.ItemSeparator());// separator | ||
293 | + | ||
294 | + List<WindowsService> wsdefList = config.GetWindowsServiceDefinitionList(); | ||
295 | + foreach (var wsdef in wsdefList) | ||
296 | + { | ||
297 | + menuservices.AddMenuItem(new Menu.Item(wsdef.Xml_Key, null, null, new Menu.ExecutorParameter(pars: wsdef.CollectWindowsServiceInfo()))); | ||
298 | + } | ||
299 | + | ||
300 | + if (!silent) { menuservices.DisplayItems(1); } | ||
301 | + return menuservices; | ||
302 | + } | ||
303 | + #endregion DisplayServices | ||
304 | + | ||
305 | + #region private method: DisplayServiceInfo | ||
306 | + private static object DisplayServiceInfo(object obj, int lineix) | ||
307 | + { | ||
308 | + if (obj == null) { return null; } | ||
309 | + WindowsService ws = (obj as Menu.ExecutorParameter).Parameters as WindowsService; | ||
310 | + if (ws == null) { return null; } | ||
311 | + if (lineix == 0) | ||
312 | + { | ||
313 | + ColorConsole.Write($"{ws.Description}", ConsoleColor.Black, ConsoleColor.White); | ||
314 | + ColorConsole.WriteLine($"{ws.DisplayName}", bracket: "()"); | ||
315 | + return ws.DisplayName+ws.Description; | ||
316 | + } | ||
317 | + else if (lineix == 1) | ||
318 | + { | ||
319 | + ColorConsole.Write($"Win service:"); | ||
320 | + ColorConsole.Write($"{ws.Name}", ConsoleColor.Cyan); | ||
321 | + var fc2 = | ||
322 | + ws.Status.Contains(nameof(WindowsService.WmiServiceStatus.OK)) ? ConsoleColor.Green | ||
323 | + : ws.Status.Contains(nameof(WindowsService.WmiServiceStatus.Unknown)) ? ConsoleColor.Red | ||
324 | + : ws.Status.Contains(nameof(WindowsService.WmiServiceStatus.Error)) ? ConsoleColor.Red | ||
325 | + : ConsoleColor.Yellow; | ||
326 | + ColorConsole.Write($"("); | ||
327 | + ColorConsole.Write($"{ws.Status}", fc2); | ||
328 | + var fc0 = | ||
329 | + ws.State.Contains(nameof(WindowsService.WmiServiceState.Running)) ? ConsoleColor.Green | ||
330 | + : ws.State.Contains(nameof(WindowsService.WmiServiceState.Unknown)) ? ConsoleColor.Red | ||
331 | + : ws.State.Contains(nameof(WindowsService.WmiServiceState.Unregistered)) ? ConsoleColor.Red | ||
332 | + : ConsoleColor.Yellow; | ||
333 | + ColorConsole.Write($" / "); | ||
334 | + ColorConsole.Write($"{ws.State}", fc0); | ||
335 | + ColorConsole.Write($")"); | ||
336 | + ColorConsole.Write($", StartMode:"); | ||
337 | + ColorConsole.Write($"{ws.StartMode}", ConsoleColor.Cyan); | ||
338 | + if(ws.Status==nameof(WindowsService.WmiServiceStatus.OK) && ws.State != nameof(WindowsService.WmiServiceState.Stopped) && ws.State != nameof(WindowsService.WmiServiceState.Unknown)) | ||
339 | + { | ||
340 | + ColorConsole.Write($", Priority:"); | ||
341 | + ColorConsole.Write($"{ws.PriorityClass}", ConsoleColor.White); | ||
342 | + ColorConsole.Write($", ProcessId:"); | ||
343 | + ColorConsole.Write($"{ws.ProcessId}", ConsoleColor.White); | ||
344 | + } | ||
345 | + ColorConsole.WriteLine(); | ||
346 | + return ws.Name; | ||
347 | + } | ||
348 | + else if (lineix == 2) | ||
349 | + { | ||
350 | + if (string.IsNullOrEmpty(ws.PathName)) { return ""; } | ||
351 | + var cmdarray = CommandLineParser.SplitArgs(ws.PathName).ToArray(); | ||
352 | + ColorConsole.Write($"Start command:"); | ||
353 | + ColorConsole.WriteLine($"{cmdarray[0]}", ConsoleColor.White); | ||
354 | + return ws.PathName; | ||
355 | + } | ||
356 | + else if (lineix == 3) | ||
357 | + { | ||
358 | + if (string.IsNullOrEmpty(ws.PathName)) { return ""; } | ||
359 | + var cmdparams = CommandLineParser.SplitArgs(ws.PathName).Skip(1).ToArray(); | ||
360 | + if (cmdparams.Length==0) { return ""; } | ||
361 | + var cmdparamsstr = string.Join("][", cmdparams); | ||
362 | + ColorConsole.Write($"Start arguments:"); | ||
363 | + ColorConsole.WriteLine($"[{cmdparamsstr}]", ConsoleColor.White); | ||
364 | + return cmdparamsstr; | ||
365 | + } | ||
366 | + else if (lineix == 4) | ||
367 | + { | ||
368 | + ColorConsole.Write($"User:"); | ||
369 | + ColorConsole.WriteLine($"{ws.StartName}", ConsoleColor.White); | ||
370 | + return ws.StartName; | ||
371 | + } | ||
372 | + else if (lineix == 5) | ||
373 | + { | ||
374 | + ColorConsole.WriteLine(); | ||
375 | + return " "; | ||
376 | + } | ||
377 | + return null; | ||
378 | + } | ||
379 | + #endregion private method: DisplayServiceInfo | ||
380 | + | ||
381 | + #region private GetUsernameAndPassword | ||
382 | + private static void GetUsernameAndPassword(ManagementObject wmiService, WindowsService ws, out string username, out string password) | ||
383 | + { | ||
384 | + username = null; | ||
385 | + password = null; | ||
386 | + if (Menu.IsCommandMode()) { username = ws.Xml_Username; password = ws.Xml_Password; return; } | ||
387 | + | ||
388 | + string olduserinfo = WindowsServiceManagerCore.GetUserInfo(wmiService); | ||
389 | + ColorConsole.WriteLine($"Current user info: {olduserinfo}"); | ||
390 | + ColorConsole.WriteLine("Enter username then password. [Enter]=save.EX=exit"); | ||
391 | + ColorConsole.WriteLine("Username is in the form of 'domainname\\username'"); | ||
392 | + ColorConsole.WriteLine($"Empty={ws.Xml_Username} (default defined in XML)"); | ||
393 | + ColorConsole.WriteLine("Special usernames are:"); | ||
394 | + | ||
395 | + ColorConsole.WriteLine($"LSE", ConsoleColor.Yellow, bracket: "()", prefix: " ", suffix: $" {nameof(ServiceAccount.LocalService)}"); | ||
396 | + ColorConsole.WriteLine($"LSY", ConsoleColor.Yellow, bracket: "()", prefix: " ", suffix: $" {nameof(ServiceAccount.LocalSystem)}"); | ||
397 | + ColorConsole.WriteLine($"NSE", ConsoleColor.Yellow, bracket: "()", prefix: " ", suffix: $" {nameof(ServiceAccount.NetworkService)}"); | ||
398 | + | ||
399 | + ColorConsole.WriteLine(); | ||
400 | + ColorConsole.WriteLine($"EX", ConsoleColor.Red, bracket: "()", prefix: " ", suffix: " Exit"); | ||
401 | + | ||
402 | + username = ColorConsole.ReadLine("username -->", ConsoleColor.Yellow, bracket: "[]"); | ||
403 | + if (username == "EX") { return; } | ||
404 | + else if (string.IsNullOrEmpty(username)) { username = ws.Xml_Username; password = ws.Xml_Password; } | ||
405 | + else if (username.ToUpper() == "LSE" || username == nameof(ServiceAccount.LocalService)) { username = nameof(ServiceAccount.LocalService); } | ||
406 | + else if (username.ToUpper() == "LSY" || username == nameof(ServiceAccount.LocalSystem)) { username = nameof(ServiceAccount.LocalSystem); } | ||
407 | + else if (username.ToUpper() == "NSE" || username == nameof(ServiceAccount.NetworkService)) { username = nameof(ServiceAccount.NetworkService); } | ||
408 | + else | ||
409 | + { | ||
410 | + password = ColorConsole.ReadLine("password -->", ConsoleColor.Yellow, bracket: "[]"); | ||
411 | + if (password == "EX") { return; } | ||
412 | + } | ||
413 | + } | ||
414 | + #endregion private GetUsernameAndPassword | ||
470 | } | 415 | } |
471 | #endregion WindowsServiceManager class | 416 | #endregion WindowsServiceManager class |
472 | 417 | ||
@@ -533,7 +478,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -533,7 +478,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
533 | try { Process proc = Process.GetProcessById(pid); proc.Kill(); } | 478 | try { Process proc = Process.GetProcessById(pid); proc.Kill(); } |
534 | catch (ArgumentException) { } // Process already exited. | 479 | catch (ArgumentException) { } // Process already exited. |
535 | } | 480 | } |
536 | - public static bool Register(WindowsService ws) | 481 | + |
482 | + #region Register | ||
483 | + /// <summary> | ||
484 | + /// Szerviz regisztrálása | ||
485 | + /// </summary> | ||
486 | + /// <param name="ws">a szerviz adatait tartalmazó objektum</param> | ||
487 | + /// <param name="dependencygroupservicenamelist">azon szervizek listája, amelyekkel egy függőségi csoportba tartozik</param> | ||
488 | + /// <returns></returns> | ||
489 | + public static bool Register(WindowsService ws,List<string> dependencygroupservicenamelist) | ||
537 | { | 490 | { |
538 | // sc.exe create "ServiceName" binpath= "c:\windows\system32\NewServ.exe" displayname= "Service display name" obj= "username" password="password" start= auto depend= "sname1/sname2/snmae3" | 491 | // sc.exe create "ServiceName" binpath= "c:\windows\system32\NewServ.exe" displayname= "Service display name" obj= "username" password="password" start= auto depend= "sname1/sname2/snmae3" |
539 | // sc.exe \\myserver create NewService binpath= c:\windows\system32\NewServ.exe | 492 | // sc.exe \\myserver create NewService binpath= c:\windows\system32\NewServ.exe |
@@ -568,8 +521,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -568,8 +521,15 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
568 | { | 521 | { |
569 | argumentlist.Add($"obj="); argumentlist.Add(ws.Xml_IdentityType.ToString().Quote()); | 522 | argumentlist.Add($"obj="); argumentlist.Add(ws.Xml_IdentityType.ToString().Quote()); |
570 | } | 523 | } |
571 | - var dependonparametert = String.Join("/", ws.Xml_Dependon); | ||
572 | - argumentlist.Add($"depend="); argumentlist.Add(dependonparametert.Quote()); | 524 | + |
525 | + // dependency csoport feldolgozása | ||
526 | + var effectivedependonlist = new List<string>(); | ||
527 | + foreach (var sn in ws.Xml_Dependon) { if (dependencygroupservicenamelist.Contains(sn)) { effectivedependonlist.Add(sn); } } | ||
528 | + foreach (var sn in ws.Xml_Dependon) { if (dependencygroupservicenamelist==null || !dependencygroupservicenamelist.Any() || dependencygroupservicenamelist.Contains("*") || dependencygroupservicenamelist.Contains(sn)) { effectivedependonlist.Add(sn); } } | ||
529 | + //--------------------------------------- | ||
530 | + | ||
531 | + var dependonparameter = String.Join("/", effectivedependonlist); | ||
532 | + argumentlist.Add($"depend="); argumentlist.Add(dependonparameter.Quote()); | ||
573 | 533 | ||
574 | var startparameter = | 534 | var startparameter = |
575 | ws.Xml_StartMode == ServiceStartMode.Automatic ? "auto" | 535 | ws.Xml_StartMode == ServiceStartMode.Automatic ? "auto" |
@@ -616,6 +576,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -616,6 +576,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
616 | } | 576 | } |
617 | return true; | 577 | return true; |
618 | } | 578 | } |
579 | + #endregion Register | ||
619 | 580 | ||
620 | public static bool Unregister(WindowsService ws) | 581 | public static bool Unregister(WindowsService ws) |
621 | { | 582 | { |
@@ -734,6 +695,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -734,6 +695,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
734 | List<WindowsService> _winservicelist; | 695 | List<WindowsService> _winservicelist; |
735 | List<WindowsService> _winservicelistinstartorder; | 696 | List<WindowsService> _winservicelistinstartorder; |
736 | List<WindowsService> _winservicelistinstoporder; | 697 | List<WindowsService> _winservicelistinstoporder; |
698 | + List<WindowsServiceGroup> _winservicegrouplist; | ||
737 | #region constructor | 699 | #region constructor |
738 | public WindowsServiceManagerXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) | 700 | public WindowsServiceManagerXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) |
739 | { | 701 | { |
@@ -743,15 +705,28 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -743,15 +705,28 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
743 | { | 705 | { |
744 | foreach (var wsxml in wsxmllist) { var ws = new WindowsService(wsxml); if (ws.Valid) { _winservicelist.Add(ws); } } | 706 | foreach (var wsxml in wsxmllist) { var ws = new WindowsService(wsxml); if (ws.Valid) { _winservicelist.Add(ws); } } |
745 | } | 707 | } |
746 | - _winservicelistinstartorder = ProduceDefinitionListInStartOrder(); | ||
747 | - _winservicelistinstoporder = ProduceDefinitionListInStartOrder(); _winservicelistinstoporder.Reverse(); | 708 | + _winservicelistinstartorder = ProduceWindowsServiceDefinitionListInStartOrder(); |
709 | + _winservicelistinstoporder = ProduceWindowsServiceDefinitionListInStartOrder(); _winservicelistinstoporder.Reverse(); | ||
710 | + | ||
711 | + _winservicegrouplist = new List<WindowsServiceGroup>(); | ||
712 | + var wsgxmllist = GetAllXElements(nameof(WindowsService.XmlStructure.WindowsServiceGroup)); | ||
713 | + if (wsgxmllist != null && wsgxmllist.Any()) | ||
714 | + { | ||
715 | + foreach (var wsgxml in wsgxmllist) { var wsg = new WindowsServiceGroup(wsgxml); if (wsg.Valid) { _winservicegrouplist.Add(wsg); } } | ||
716 | + } | ||
748 | } | 717 | } |
749 | #endregion constructor | 718 | #endregion constructor |
750 | - #region GetDefinitionList | ||
751 | - public List<WindowsService> GetDefinitionList() { return _winservicelist; } | ||
752 | - public List<WindowsService> GetDefinitionListInStartOrder() { return _winservicelistinstartorder; } | ||
753 | - public List<WindowsService> GetDefinitionListInStopOrder() { return _winservicelistinstoporder; } | ||
754 | - private List<WindowsService> ProduceDefinitionListInStartOrder() | 719 | + #region GetWindowsServiceGroupDefinitionList |
720 | + public WindowsServiceGroup GetWindowsServiceGroup(string key) { return _winservicegrouplist.FirstOrDefault(x => x.Xml_Key == key); } | ||
721 | + public List<WindowsServiceGroup> GetWindowsServiceGroupDefinitionList() { return _winservicegrouplist; } | ||
722 | + #endregion GetWindowsServiceGroupDefinitionList | ||
723 | + | ||
724 | + #region GetWindowsServiceDefinitionList | ||
725 | + public WindowsService GetWindowsService(string key) { return _winservicelist.FirstOrDefault(x => x.Xml_Key == key); } | ||
726 | + public List<WindowsService> GetWindowsServiceDefinitionList() { return _winservicelist; } | ||
727 | + public List<WindowsService> GetWindowsServiceDefinitionListInStartOrder() { return _winservicelistinstartorder; } | ||
728 | + public List<WindowsService> GetWindowsServiceDefinitionListInStopOrder() { return _winservicelistinstoporder; } | ||
729 | + private List<WindowsService> ProduceWindowsServiceDefinitionListInStartOrder() | ||
755 | { | 730 | { |
756 | List<WindowsService> listinstartorder = new List<WindowsService>(); | 731 | List<WindowsService> listinstartorder = new List<WindowsService>(); |
757 | bool ready = false;//akkor lesz false, ha már minden | 732 | bool ready = false;//akkor lesz false, ha már minden |
@@ -764,7 +739,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -764,7 +739,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
764 | if (namelistinstartorder.Contains(s.Name)) { continue; }//ez a szerviz már bekerült a startorder listába | 739 | if (namelistinstartorder.Contains(s.Name)) { continue; }//ez a szerviz már bekerült a startorder listába |
765 | ready = false; | 740 | ready = false; |
766 | var dl = s.Xml_Dependon; | 741 | var dl = s.Xml_Dependon; |
767 | - if (dl.Length == 0) { listinstartorder.Add(s); continue; }//ha nem függ senkitől, betesszük a startorder listába | 742 | + if (!dl.Any()) { listinstartorder.Add(s); continue; }//ha nem függ senkitől, betesszük a startorder listába |
768 | foreach (var dli in dl) | 743 | foreach (var dli in dl) |
769 | { | 744 | { |
770 | if (string.IsNullOrWhiteSpace(dli)) { continue; } | 745 | if (string.IsNullOrWhiteSpace(dli)) { continue; } |
@@ -775,7 +750,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -775,7 +750,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
775 | } | 750 | } |
776 | return listinstartorder; | 751 | return listinstartorder; |
777 | } | 752 | } |
778 | - #endregion GetDefinitionList | 753 | + #endregion GetWindowsServiceDefinitionList |
779 | } | 754 | } |
780 | #endregion WindowsServiceManagerXmlProcessor class | 755 | #endregion WindowsServiceManagerXmlProcessor class |
781 | #region WindowsService class | 756 | #region WindowsService class |
@@ -787,8 +762,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -787,8 +762,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
787 | public string DisplayName; | 762 | public string DisplayName; |
788 | public string Description; | 763 | public string Description; |
789 | public string PathName; | 764 | public string PathName; |
790 | - public string[] ThisDependsOn; | ||
791 | - public string[] ServicesDependOnThis; | 765 | + public List<string> ThisDependsOn; |
766 | + public List<string> ServicesDependOnThis; | ||
792 | public int ProcessId; | 767 | public int ProcessId; |
793 | public ServiceStartMode StartMode; | 768 | public ServiceStartMode StartMode; |
794 | public string State; | 769 | public string State; |
@@ -796,6 +771,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -796,6 +771,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
796 | public string StartName; | 771 | public string StartName; |
797 | public string PriorityClass; | 772 | public string PriorityClass; |
798 | 773 | ||
774 | + public string Xml_Key; | ||
799 | public string Xml_DisplayName; | 775 | public string Xml_DisplayName; |
800 | public string Xml_Description; | 776 | public string Xml_Description; |
801 | public string Xml_Exe; | 777 | public string Xml_Exe; |
@@ -803,7 +779,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -803,7 +779,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
803 | public ServiceStartMode Xml_StartMode; | 779 | public ServiceStartMode Xml_StartMode; |
804 | public string Xml_Priority; | 780 | public string Xml_Priority; |
805 | public string Xml_Arguments; | 781 | public string Xml_Arguments; |
806 | - public string[] Xml_Dependon; | 782 | + public List<string> Xml_Dependon; |
807 | public string Xml_RegistrationMode; | 783 | public string Xml_RegistrationMode; |
808 | public ServiceAccount Xml_IdentityType; | 784 | public ServiceAccount Xml_IdentityType; |
809 | public string Xml_Username; | 785 | public string Xml_Username; |
@@ -819,6 +795,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -819,6 +795,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
819 | public WindowsService(XElement winservicexml) | 795 | public WindowsService(XElement winservicexml) |
820 | { | 796 | { |
821 | string ATTRIBUTEMANDATORY = nameof(XmlStructure.WindowsService) + " attribute is mandatory! Name: {0}"; | 797 | string ATTRIBUTEMANDATORY = nameof(XmlStructure.WindowsService) + " attribute is mandatory! Name: {0}"; |
798 | + Xml_Key = GetValue(nameof(XmlStructure.WindowsService.Attributes.Key), winservicexml, ""); | ||
799 | + if (string.IsNullOrEmpty(Xml_Key)) { throw new ApplicationException(string.Format(ATTRIBUTEMANDATORY, nameof(XmlStructure.WindowsService.Attributes.Key))); } | ||
822 | Name = winservicexml.Attribute(XName.Get(nameof(XmlStructure.WindowsService.Attributes.Name)))?.Value; | 800 | Name = winservicexml.Attribute(XName.Get(nameof(XmlStructure.WindowsService.Attributes.Name)))?.Value; |
823 | if (!ValidServiceName(Name)) | 801 | if (!ValidServiceName(Name)) |
824 | { | 802 | { |
@@ -840,13 +818,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -840,13 +818,12 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
840 | Xml_Priority = GetValue(nameof(XmlStructure.WindowsService.Attributes.Priority), winservicexml, XmlStructure.WindowsService.Attributes.Priority.Values.DEFAULT); | 818 | Xml_Priority = GetValue(nameof(XmlStructure.WindowsService.Attributes.Priority), winservicexml, XmlStructure.WindowsService.Attributes.Priority.Values.DEFAULT); |
841 | Xml_Arguments = GetValue(nameof(XmlStructure.WindowsService.Attributes.Arguments), winservicexml, ""); | 819 | Xml_Arguments = GetValue(nameof(XmlStructure.WindowsService.Attributes.Arguments), winservicexml, ""); |
842 | 820 | ||
843 | - var XmlDependon = new List<string>(); | 821 | + Xml_Dependon = new List<string>(); |
844 | string[] dependonarray = GetValue(nameof(XmlStructure.WindowsService.Attributes.DependOn), winservicexml, "").Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); | 822 | string[] dependonarray = GetValue(nameof(XmlStructure.WindowsService.Attributes.DependOn), winservicexml, "").Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); |
845 | foreach (var ds in dependonarray) | 823 | foreach (var ds in dependonarray) |
846 | { | 824 | { |
847 | - if (ValidServiceName(ds)) { XmlDependon.Add(ds); } | 825 | + if (ValidServiceName(ds)) { Xml_Dependon.Add(ds); } |
848 | } | 826 | } |
849 | - Xml_Dependon = XmlDependon.ToArray(); | ||
850 | 827 | ||
851 | Xml_RegistrationMode = GetValue(nameof(XmlStructure.WindowsService.Attributes.RegistrationMode), winservicexml, XmlStructure.WindowsService.Attributes.RegistrationMode.Values.DEFAULT); | 828 | Xml_RegistrationMode = GetValue(nameof(XmlStructure.WindowsService.Attributes.RegistrationMode), winservicexml, XmlStructure.WindowsService.Attributes.RegistrationMode.Values.DEFAULT); |
852 | Xml_RegistrationMode = Xml_RegistrationMode.Replace('-', '_'); | 829 | Xml_RegistrationMode = Xml_RegistrationMode.Replace('-', '_'); |
@@ -866,12 +843,71 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -866,12 +843,71 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
866 | Xml_StopTimeout = GetValue(nameof(XmlStructure.WindowsService.Attributes.StopTimeout), winservicexml, XmlStructure.WindowsService.Attributes.StopTimeout.Values.DEFAULT); | 843 | Xml_StopTimeout = GetValue(nameof(XmlStructure.WindowsService.Attributes.StopTimeout), winservicexml, XmlStructure.WindowsService.Attributes.StopTimeout.Values.DEFAULT); |
867 | } | 844 | } |
868 | private bool ValidServiceName(string sn) { return !string.IsNullOrWhiteSpace(Name) && sn[0] != '@'; } | 845 | private bool ValidServiceName(string sn) { return !string.IsNullOrWhiteSpace(Name) && sn[0] != '@'; } |
846 | + #region public CollectWindowsServiceInfo | ||
847 | + public WindowsService CollectWindowsServiceInfo() | ||
848 | + { | ||
849 | + using (var wmiService = WindowsServiceManagerCore.GetServiceObject(this.Name)) | ||
850 | + { | ||
851 | + using (var service = WindowsServiceManagerCore.GetServiceController(this.Name)) | ||
852 | + { | ||
853 | + var wmiserviceproblem = false; | ||
854 | + try { wmiService.Get(); } catch { wmiserviceproblem = true; } | ||
855 | + if (wmiService == null || service == null || wmiserviceproblem) | ||
856 | + { | ||
857 | + this.DisplayName = this.Xml_DisplayName; | ||
858 | + this.Description = this.Xml_Description; | ||
859 | + this.ThisDependsOn = this.Xml_Dependon; | ||
860 | + this.ServicesDependOnThis = new List<string>() { "???" }; | ||
861 | + this.PathName = $"\"{this.Xml_Exe}\" {this.Xml_Arguments}"; | ||
862 | + this.StartMode = this.Xml_StartMode; | ||
863 | + this.State = nameof(WmiServiceState.Unregistered); | ||
864 | + this.Status = nameof(WindowsService.WmiServiceStatus.Unregistered); | ||
865 | + if (this.Xml_IdentityType == ServiceAccount.User) { this.StartName = this.Xml_Username + $"({this.Xml_Password})"; } | ||
866 | + else { this.StartName = this.Xml_IdentityType.ToString(); } | ||
867 | + this.ProcessId = 0; | ||
868 | + this.PriorityClass = this.Xml_Priority; | ||
869 | + } | ||
870 | + else | ||
871 | + { | ||
872 | + this.DisplayName = (string)wmiService[nameof(WindowsService.DisplayName)]; | ||
873 | + this.Description = (string)wmiService[nameof(WindowsService.Description)]; | ||
874 | + if (string.IsNullOrEmpty(this.Description)) { this.Description = this.DisplayName; } | ||
875 | + if (string.IsNullOrEmpty(this.DisplayName)) { this.DisplayName = this.Description; } | ||
876 | + this.ServicesDependOnThis = service.DependentServices.Select(s => s.ServiceName).ToList(); | ||
877 | + try { this.ThisDependsOn = service.ServicesDependedOn.Select(s => s.ServiceName).ToList(); } catch { this.ThisDependsOn = new List<string>() { "???" }; } | ||
878 | + this.PathName = (string)wmiService[nameof(WindowsService.PathName)]; if (this.PathName == null) { this.PathName = ""; } | ||
879 | + var sm = (string)wmiService[nameof(WindowsService.StartMode)]; | ||
880 | + this.StartMode = | ||
881 | + sm == "Auto" ? ServiceStartMode.Automatic | ||
882 | + : sm == "Auto" ? ServiceStartMode.Manual | ||
883 | + : sm == "Auto" ? ServiceStartMode.Disabled | ||
884 | + : sm == "Auto" ? ServiceStartMode.Boot | ||
885 | + : sm == "Auto" ? ServiceStartMode.System | ||
886 | + : ServiceStartMode.Manual; | ||
887 | + this.State = (string)wmiService[nameof(WindowsService.State)]; | ||
888 | + this.Status = (string)wmiService[nameof(WindowsService.Status)]; | ||
889 | + this.StartName = (string)wmiService[nameof(WindowsService.StartName)]; | ||
890 | + this.ProcessId = 0; | ||
891 | + this.PriorityClass = "-"; | ||
892 | + if (this.State != nameof(WmiServiceState.Stopped)) | ||
893 | + { | ||
894 | + this.ProcessId = Convert.ToInt32(wmiService[nameof(WindowsService.ProcessId)]); | ||
895 | + this.PriorityClass = Process.GetProcessById(this.ProcessId).PriorityClass.ToString(); | ||
896 | + } | ||
897 | + } | ||
898 | + } | ||
899 | + } | ||
900 | + return this; | ||
901 | + } | ||
902 | + #endregion public CollectWindowsServiceInfo | ||
903 | + | ||
869 | #endregion xml constructor | 904 | #endregion xml constructor |
870 | #region cloner constructor | 905 | #region cloner constructor |
871 | public WindowsService(WindowsService ws) | 906 | public WindowsService(WindowsService ws) |
872 | { | 907 | { |
873 | Name = ws.Name; | 908 | Name = ws.Name; |
874 | Valid = ws.Valid; | 909 | Valid = ws.Valid; |
910 | + Xml_Key= ws.Xml_Key; | ||
875 | Xml_DisplayName = ws.Xml_DisplayName; | 911 | Xml_DisplayName = ws.Xml_DisplayName; |
876 | Xml_Description = ws.Xml_Description; | 912 | Xml_Description = ws.Xml_Description; |
877 | Xml_Exe = ws.Xml_Exe; | 913 | Xml_Exe = ws.Xml_Exe; |
@@ -891,10 +927,20 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -891,10 +927,20 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
891 | #region XmlStructure | 927 | #region XmlStructure |
892 | public static class XmlStructure | 928 | public static class XmlStructure |
893 | { | 929 | { |
930 | + public static class WindowsServiceGroup | ||
931 | + { | ||
932 | + public static class Attributes | ||
933 | + { | ||
934 | + public static class Key { public static class Values { public static string DEFAULT = ""; } } | ||
935 | + public static class Description { public static class Values { public static string DEFAULT = ""; } } | ||
936 | + public static class WindowsServiceKeyList { public static class Values { public static string DEFAULT = ""; } } | ||
937 | + } | ||
938 | + } | ||
894 | public static class WindowsService | 939 | public static class WindowsService |
895 | { | 940 | { |
896 | public static class Attributes | 941 | public static class Attributes |
897 | { | 942 | { |
943 | + public static class Key { public static class Values { public static string DEFAULT = ""; } } | ||
898 | public static class Name { } | 944 | public static class Name { } |
899 | public static class DisplayName { } | 945 | public static class DisplayName { } |
900 | public static class Description { } | 946 | public static class Description { } |
@@ -946,7 +992,65 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -946,7 +992,65 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
946 | } | 992 | } |
947 | } | 993 | } |
948 | #endregion XmlStructure | 994 | #endregion XmlStructure |
995 | + #region public classes,types | ||
996 | + public enum WmiServiceStatus | ||
997 | + { | ||
998 | + OK, | ||
999 | + Error, | ||
1000 | + Degraded, | ||
1001 | + Unknown, | ||
1002 | + Pred_Fail, | ||
1003 | + Starting, | ||
1004 | + Stopping, | ||
1005 | + Service, | ||
1006 | + Stressed, | ||
1007 | + NonRecover, | ||
1008 | + No_Contact, | ||
1009 | + Lost_Comm, | ||
1010 | + Unregistered, | ||
1011 | + } | ||
1012 | + public enum WmiServiceState | ||
1013 | + { | ||
1014 | + StartPending, | ||
1015 | + Running, | ||
1016 | + Paused, | ||
1017 | + PausedPending, | ||
1018 | + Stopped, | ||
1019 | + StopPending, | ||
1020 | + Unknown, | ||
1021 | + Unregistered, | ||
1022 | + } | ||
1023 | + #endregion public classes,types | ||
949 | } | 1024 | } |
950 | #endregion WindowsService class | 1025 | #endregion WindowsService class |
951 | - | 1026 | + #region WindowsServiceGroup class |
1027 | + public class WindowsServiceGroup : XmlLinqBase | ||
1028 | + { | ||
1029 | + public bool Valid; | ||
1030 | + public List<string> Xml_WindowsServiceKeyList; | ||
1031 | + public string Xml_Key; | ||
1032 | + public string Xml_Description; | ||
1033 | + public WindowsServiceGroup() { } | ||
1034 | + public WindowsServiceGroup(WindowsServiceGroup wsg) | ||
1035 | + { | ||
1036 | + Xml_Key = wsg.Xml_Key; | ||
1037 | + Xml_WindowsServiceKeyList = wsg.Xml_WindowsServiceKeyList.Select(x => x).ToList(); | ||
1038 | + Xml_Description = wsg.Xml_Description; | ||
1039 | + Valid = wsg.Valid; | ||
1040 | + } | ||
1041 | + public WindowsServiceGroup(XElement wsgxml) | ||
1042 | + { | ||
1043 | + Xml_Key = GetValue(nameof(WindowsService.XmlStructure.WindowsServiceGroup.Attributes.Key), wsgxml, WindowsService.XmlStructure.WindowsServiceGroup.Attributes.Key.Values.DEFAULT); | ||
1044 | + Xml_Description = GetValue(nameof(WindowsService.XmlStructure.WindowsServiceGroup.Attributes.Description), wsgxml, WindowsService.XmlStructure.WindowsServiceGroup.Attributes.Description.Values.DEFAULT); | ||
1045 | + var keycommaliststring = GetValue(nameof(WindowsService.XmlStructure.WindowsServiceGroup.Attributes.WindowsServiceKeyList), wsgxml, WindowsService.XmlStructure.WindowsServiceGroup.Attributes.WindowsServiceKeyList.Values.DEFAULT); | ||
1046 | + Valid = false; | ||
1047 | + if (!string.IsNullOrWhiteSpace(keycommaliststring)) | ||
1048 | + { | ||
1049 | + Xml_WindowsServiceKeyList = new List<string>(keycommaliststring.Split(new char[] { ',' },StringSplitOptions.RemoveEmptyEntries)); | ||
1050 | + if (Xml_WindowsServiceKeyList.Contains("*")) { Xml_WindowsServiceKeyList = new List<string>() { "*" }; } | ||
1051 | + Valid = Xml_WindowsServiceKeyList.Any(); | ||
1052 | + } | ||
1053 | + } | ||
1054 | + } | ||
1055 | + #endregion WindowsServiceGroup class | ||
952 | } | 1056 | } |
Vrh.Log4Pro.MaintenanceConsole/Program.cs
@@ -3,11 +3,27 @@ using System.Collections.Generic; | @@ -3,11 +3,27 @@ using System.Collections.Generic; | ||
3 | using System.Linq; | 3 | using System.Linq; |
4 | using System.Text; | 4 | using System.Text; |
5 | using System.Threading.Tasks; | 5 | using System.Threading.Tasks; |
6 | +using System.Threading; | ||
6 | 7 | ||
7 | using Microsoft.Web.Administration; | 8 | using Microsoft.Web.Administration; |
8 | using System.Management; | 9 | using System.Management; |
9 | using System.Diagnostics; | 10 | using System.Diagnostics; |
10 | 11 | ||
12 | +using Vrh.Log4Pro.MaintenanceConsole.ColorConsoleNS; | ||
13 | +using Vrh.Log4Pro.MaintenanceConsole.MenuNS; | ||
14 | +using Vrh.Log4Pro.MaintenanceConsole.ToolsNS; | ||
15 | + | ||
16 | +using Vrh.Log4Pro.MaintenanceConsole.WebApplicationManagerNS; | ||
17 | +using Vrh.Log4Pro.MaintenanceConsole.WindowsServiceManagerNS; | ||
18 | +using Vrh.Log4Pro.MaintenanceConsole.BackupPackageManagerNS; | ||
19 | +using Vrh.Log4Pro.MaintenanceConsole.SQLDataBaseManagerNS; | ||
20 | +using Vrh.Log4Pro.MaintenanceConsole.ScheduledTaskManagerNS; | ||
21 | +using Vrh.Log4Pro.MaintenanceConsole.FileCleanerManagerNS; | ||
22 | +using Vrh.Log4Pro.MaintenanceConsole.MaintenanceToolManagerNS; | ||
23 | +using Vrh.Log4Pro.MaintenanceConsole.UserManagerNS; | ||
24 | + | ||
25 | +using Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS; | ||
26 | + | ||
11 | using Vrh.XmlProcessing; | 27 | using Vrh.XmlProcessing; |
12 | using VRH.Common; | 28 | using VRH.Common; |
13 | using System.Xml.Linq; | 29 | using System.Xml.Linq; |
@@ -18,12 +34,18 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -18,12 +34,18 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
18 | { | 34 | { |
19 | static void Main(string[] args) | 35 | static void Main(string[] args) |
20 | { | 36 | { |
21 | - ColorConsole.ReadLine("Press a key to start..."); | ||
22 | - var appconfigpath = CommandLine.GetCommandLineArgument(args, "-APPCONFIG"); | 37 | + |
38 | + var forcedmodulekey = CommandLine.GetCommandLineArgument(args, CLP.CMD_MODULE); | ||
39 | + var commandmode = !string.IsNullOrEmpty(forcedmodulekey); | ||
40 | + var silentmode = commandmode && !string.IsNullOrEmpty(CommandLine.GetCommandLineArgument(args, CLP.CMD_SILENT, switchtype: true)); | ||
41 | + ColorConsole.SetSilentMode(silentmode); | ||
42 | + Menu.SetCommandMode(commandmode); | ||
43 | + | ||
44 | + var appconfigpath = CommandLine.GetCommandLineArgument(args, CLP.CMD_APPCONFIG); | ||
23 | CommandLine.SetAppConfigFile(appconfigpath); | 45 | CommandLine.SetAppConfigFile(appconfigpath); |
24 | 46 | ||
25 | try { ColorConsole.SetWindowSize(120, 64); } | 47 | try { ColorConsole.SetWindowSize(120, 64); } |
26 | - catch (Exception ex) | 48 | + catch |
27 | { | 49 | { |
28 | ColorConsole.WriteLine("Change the size of the console fonts smaller!"); | 50 | ColorConsole.WriteLine("Change the size of the console fonts smaller!"); |
29 | ColorConsole.ReadKey(); | 51 | ColorConsole.ReadKey(); |
@@ -37,27 +59,98 @@ namespace Vrh.Log4Pro.MaintenanceConsole | @@ -37,27 +59,98 @@ namespace Vrh.Log4Pro.MaintenanceConsole | ||
37 | } | 59 | } |
38 | 60 | ||
39 | var mm = new Menu("Log4ProIS Maintenance Console") | 61 | var mm = new Menu("Log4ProIS Maintenance Console") |
40 | - .AddMenuItem(new Menu.Item("WAM", "Web Application Manager", WebApplicationManager.Execute)) | ||
41 | - .AddMenuItem(new Menu.Item("WSM", "Windows Service Manager", WindowsServiceManager.Execute)) | ||
42 | - .AddMenuItem(new Menu.Item("FCL", "File Cleaner Manager", FileCleanerManager.Execute)) | ||
43 | - .AddMenuItem(new Menu.Item("SCH", "Scheduled Task Manager", ScheduledTaskmanagerManager.Execute)) | 62 | + .AddMenuItem(new Menu.Item(CLP.Module.WebApplicationManager.KEY, "Web Application Manager", WebApplicationManager.Execute, new Menu.ExecutorParameter(args: args))) |
63 | + .AddMenuItem(new Menu.Item(CLP.Module.WindowsServiceManager.KEY, "Windows Service Manager", WindowsServiceManager.Execute, new Menu.ExecutorParameter(args: args))) | ||
64 | + .AddMenuItem(new Menu.Item(CLP.Module.FileCleanerManager.KEY, "File Cleaner Manager", FileCleanerManager.Execute, new Menu.ExecutorParameter(args: args))) | ||
65 | + .AddMenuItem(new Menu.Item(CLP.Module.ScheduledTaskManager.KEY, "Scheduled Task Manager", ScheduledTaskManager.Execute, new Menu.ExecutorParameter(args: args))) | ||
66 | + .AddMenuItem(new Menu.Item(CLP.Module.BackupPackageManager.KEY, "Backup Package Manager", BackupPackageManager.Execute, new Menu.ExecutorParameter(args: args))) | ||
67 | + .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.KEY, "SQL Database Manager", SQLDataBaseManager.Execute, new Menu.ExecutorParameter(args: args))) | ||
68 | + .AddMenuItem(new Menu.Item(CLP.Module.Log4ProUserManager.KEY, "Log4Pro User Manager", UserManager.Execute, new Menu.ExecutorParameter(args: args))) | ||
44 | .AddMenuItem(new Menu.ItemSeparator('-')) | 69 | .AddMenuItem(new Menu.ItemSeparator('-')) |
45 | - .AddMenuItem(new Menu.Item("TOL", "Maintenance tools", MaintenanceToolManager.Execute)) | 70 | + .AddMenuItem(new Menu.Item(CLP.Module.MaintenanceToolManager.KEY, "Maintenance tools", MaintenanceToolManager.Execute, new Menu.ExecutorParameter(args: args))) |
71 | + .SetMenuHeaderDisplayer(DisplayComputerInfo) | ||
46 | .SetSelectionMode(Menu.SelectionMode.Single); | 72 | .SetSelectionMode(Menu.SelectionMode.Single); |
47 | 73 | ||
48 | - var commandmode = !string.IsNullOrEmpty(CommandLine.GetCommandLineArgument(args, "-MODULE")); | ||
49 | - if (commandmode) | 74 | + mm.ExecuteMenu(forcedmodulekey); |
75 | + | ||
76 | + ColorConsole.PressAnykeyToContinue(); | ||
77 | + } | ||
78 | + static void DisplayComputerInfo() | ||
79 | + { | ||
80 | + const string XMLCONNECTIONSTRING = "config=MAINTENANCECONSOLE;"; | ||
81 | + const string XMLCONNECTIONSTRING_DEFAULT = "file=Config.Xml;"; | ||
82 | + var config = new MaintenanceConsoleXmlProcessor(XMLCONNECTIONSTRING, "", "hu-HU"); | ||
83 | + | ||
84 | + ColorConsole.WriteLine(config.Xml_Header,ConsoleColor.Yellow,bracket:"[]"); | ||
85 | + | ||
86 | + //computername | ||
87 | + ColorConsole.WriteLine(""); | ||
88 | + ColorConsole.Write("Computer name: "); | ||
89 | + ColorConsole.Write(System.Environment.MachineName, ConsoleColor.Yellow, bracket: "[]",prefix: "", suffix: ","); | ||
90 | + var hostname = System.Net.Dns.GetHostName(); | ||
91 | + ColorConsole.Write(hostname, ConsoleColor.Yellow, bracket: "[]", prefix: "DNS hostname:"); | ||
92 | + ColorConsole.WriteLine(""); | ||
93 | + | ||
94 | + //username | ||
95 | + ColorConsole.Write("Username:"); | ||
96 | + ColorConsole.Write(Environment.UserName, ConsoleColor.Yellow, bracket: "[]", prefix: "RunAs:", suffix: ","); | ||
97 | + ColorConsole.Write(System.Security.Principal.WindowsIdentity.GetCurrent().Name, ConsoleColor.Yellow, bracket: "[]", prefix: "LoggedIn:"); | ||
98 | + ColorConsole.WriteLine(""); | ||
99 | + | ||
100 | + //ip address | ||
101 | + ColorConsole.Write("IP addresses: "); | ||
102 | + var host = System.Net.Dns.GetHostEntry(hostname); | ||
103 | + foreach (var ip in host.AddressList) | ||
50 | { | 104 | { |
51 | - var silentmode = !string.IsNullOrEmpty(CommandLine.GetCommandLineArgument(args, "-SILENT", switchtype: true)); | ||
52 | - ColorConsole.SetSilentMode(silentmode); | ||
53 | - Menu.SetCommandModeAllMenus(); | ||
54 | - mm.ExecuteCmd(args); | 105 | + if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) |
106 | + { | ||
107 | + ColorConsole.Write(ip.ToString(), ConsoleColor.Yellow, bracket: "[]", prefix: $"{ip.AddressFamily}:",suffix: ","); | ||
108 | + } | ||
55 | } | 109 | } |
56 | - else | 110 | + ColorConsole.WriteLine(""); |
111 | + | ||
112 | + // processor architecture | ||
113 | + ColorConsole.Write("Processors: "); | ||
114 | + ColorConsole.Write(System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"), ConsoleColor.Yellow, bracket: "[]", prefix: "Architecture: ",suffix:", "); | ||
115 | + foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get()) | ||
116 | + { | ||
117 | + ColorConsole.Write(item["NumberOfProcessors"].ToString(), ConsoleColor.Yellow, bracket: "[]", prefix: "Physical:",suffix:", "); | ||
118 | + ColorConsole.Write(item["NumberOfLogicalProcessors"].ToString(), ConsoleColor.Yellow, bracket: "[]", prefix: "Logical:", suffix: ", "); | ||
119 | + } | ||
120 | + | ||
121 | + int coreCount = 0; | ||
122 | + foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get()) | ||
57 | { | 123 | { |
58 | - mm.ExecuteMenu(); | ||
59 | - ColorConsole.PressAnykeyToContinue(); | 124 | + coreCount += int.Parse(item["NumberOfCores"].ToString()); |
60 | } | 125 | } |
126 | + ColorConsole.Write(coreCount.ToString(), ConsoleColor.Yellow, bracket: "[]", prefix: "Cores:"); | ||
127 | + ColorConsole.WriteLine(""); | ||
128 | + | ||
129 | + // os version | ||
130 | + ColorConsole.Write("Operating system: "); | ||
131 | + ColorConsole.Write(System.Environment.OSVersion.Platform.ToString(), ConsoleColor.Yellow, bracket: "[]", prefix: "Platform:",suffix: ","); | ||
132 | + ColorConsole.Write(System.Environment.OSVersion.ServicePack, ConsoleColor.Yellow, bracket: "[]", prefix: "Service pack:", suffix: ","); | ||
133 | + ColorConsole.Write(System.Environment.OSVersion.VersionString, ConsoleColor.Yellow, bracket: "[]", prefix: "Version string:"); | ||
134 | + ColorConsole.WriteLine(""); | ||
135 | + ColorConsole.WriteLine(""); | ||
136 | + } | ||
137 | + } | ||
138 | + #region MaintenanceConsoleXmlProcessor class | ||
139 | + public class MaintenanceConsoleXmlProcessor : XmlParser | ||
140 | + { | ||
141 | + public string Xml_Header; | ||
142 | + #region constructor | ||
143 | + public MaintenanceConsoleXmlProcessor(string xmlcs, string basefolder, string lcid) : base(xmlcs, basefolder, lcid, null) | ||
144 | + { | ||
145 | + Xml_Header = GetValue(GetXElement(nameof(XmlStructure.Header)),""); | ||
146 | + } | ||
147 | + #endregion constructor | ||
148 | + #region XmlStructure | ||
149 | + public static class XmlStructure | ||
150 | + { | ||
151 | + public static class Header { } | ||
61 | } | 152 | } |
153 | + #endregion XmlStructure | ||
62 | } | 154 | } |
155 | + #endregion MaintenanceConsoleXmlProcessor class | ||
63 | } | 156 | } |
Vrh.Log4Pro.MaintenanceConsole/Vrh.Log4Pro.MaintenanceConsole.csproj
@@ -9,12 +9,13 @@ | @@ -9,12 +9,13 @@ | ||
9 | <OutputType>Exe</OutputType> | 9 | <OutputType>Exe</OutputType> |
10 | <RootNamespace>Vrh.Log4Pro.MaintenanceConsole</RootNamespace> | 10 | <RootNamespace>Vrh.Log4Pro.MaintenanceConsole</RootNamespace> |
11 | <AssemblyName>Vrh.Log4Pro.MaintenanceConsole</AssemblyName> | 11 | <AssemblyName>Vrh.Log4Pro.MaintenanceConsole</AssemblyName> |
12 | - <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion> | 12 | + <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> |
13 | <FileAlignment>512</FileAlignment> | 13 | <FileAlignment>512</FileAlignment> |
14 | <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> | 14 | <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> |
15 | <Deterministic>true</Deterministic> | 15 | <Deterministic>true</Deterministic> |
16 | <NuGetPackageImportStamp> | 16 | <NuGetPackageImportStamp> |
17 | </NuGetPackageImportStamp> | 17 | </NuGetPackageImportStamp> |
18 | + <TargetFrameworkProfile /> | ||
18 | </PropertyGroup> | 19 | </PropertyGroup> |
19 | <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> | 20 | <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> |
20 | <PlatformTarget>AnyCPU</PlatformTarget> | 21 | <PlatformTarget>AnyCPU</PlatformTarget> |
@@ -35,6 +36,9 @@ | @@ -35,6 +36,9 @@ | ||
35 | <ErrorReport>prompt</ErrorReport> | 36 | <ErrorReport>prompt</ErrorReport> |
36 | <WarningLevel>4</WarningLevel> | 37 | <WarningLevel>4</WarningLevel> |
37 | </PropertyGroup> | 38 | </PropertyGroup> |
39 | + <PropertyGroup> | ||
40 | + <ApplicationIcon>servicelogo.ico</ApplicationIcon> | ||
41 | + </PropertyGroup> | ||
38 | <ItemGroup> | 42 | <ItemGroup> |
39 | <Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> | 43 | <Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> |
40 | <HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll</HintPath> | 44 | <HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll</HintPath> |
@@ -42,6 +46,117 @@ | @@ -42,6 +46,117 @@ | ||
42 | <Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> | 46 | <Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> |
43 | <HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll</HintPath> | 47 | <HintPath>..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll</HintPath> |
44 | </Reference> | 48 | </Reference> |
49 | + <Reference Include="Microsoft.Data.SqlClient, Version=2.0.20168.4, Culture=neutral, PublicKeyToken=23ec7fc2d6eaa4a5, processorArchitecture=MSIL"> | ||
50 | + <HintPath>..\packages\Microsoft.Data.SqlClient.2.0.0\lib\net46\Microsoft.Data.SqlClient.dll</HintPath> | ||
51 | + </Reference> | ||
52 | + <Reference Include="Microsoft.Data.Tools.Sql.BatchParser, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
53 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.Data.Tools.Sql.BatchParser.dll</HintPath> | ||
54 | + </Reference> | ||
55 | + <Reference Include="Microsoft.Identity.Client, Version=4.14.0.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae, processorArchitecture=MSIL"> | ||
56 | + <HintPath>..\packages\Microsoft.Identity.Client.4.14.0\lib\net45\Microsoft.Identity.Client.dll</HintPath> | ||
57 | + </Reference> | ||
58 | + <Reference Include="Microsoft.IdentityModel.JsonWebTokens, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> | ||
59 | + <HintPath>..\packages\Microsoft.IdentityModel.JsonWebTokens.5.6.0\lib\net461\Microsoft.IdentityModel.JsonWebTokens.dll</HintPath> | ||
60 | + </Reference> | ||
61 | + <Reference Include="Microsoft.IdentityModel.Logging, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> | ||
62 | + <HintPath>..\packages\Microsoft.IdentityModel.Logging.5.6.0\lib\net461\Microsoft.IdentityModel.Logging.dll</HintPath> | ||
63 | + </Reference> | ||
64 | + <Reference Include="Microsoft.IdentityModel.Protocols, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> | ||
65 | + <HintPath>..\packages\Microsoft.IdentityModel.Protocols.5.6.0\lib\net461\Microsoft.IdentityModel.Protocols.dll</HintPath> | ||
66 | + </Reference> | ||
67 | + <Reference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> | ||
68 | + <HintPath>..\packages\Microsoft.IdentityModel.Protocols.OpenIdConnect.5.6.0\lib\net461\Microsoft.IdentityModel.Protocols.OpenIdConnect.dll</HintPath> | ||
69 | + </Reference> | ||
70 | + <Reference Include="Microsoft.IdentityModel.Tokens, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> | ||
71 | + <HintPath>..\packages\Microsoft.IdentityModel.Tokens.5.6.0\lib\net461\Microsoft.IdentityModel.Tokens.dll</HintPath> | ||
72 | + </Reference> | ||
73 | + <Reference Include="Microsoft.SqlServer.Assessment, Version=1.100.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
74 | + <HintPath>..\packages\Microsoft.SqlServer.Assessment.1.0.280\lib\net462\Microsoft.SqlServer.Assessment.dll</HintPath> | ||
75 | + </Reference> | ||
76 | + <Reference Include="Microsoft.SqlServer.Assessment.Types, Version=1.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
77 | + <HintPath>..\packages\Microsoft.SqlServer.Assessment.Authoring.1.0.280\lib\net462\Microsoft.SqlServer.Assessment.Types.dll</HintPath> | ||
78 | + </Reference> | ||
79 | + <Reference Include="Microsoft.SqlServer.ConnectionInfo, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
80 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.ConnectionInfo.dll</HintPath> | ||
81 | + </Reference> | ||
82 | + <Reference Include="Microsoft.SqlServer.Dmf, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
83 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Dmf.dll</HintPath> | ||
84 | + </Reference> | ||
85 | + <Reference Include="Microsoft.SqlServer.Dmf.Common, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
86 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Dmf.Common.dll</HintPath> | ||
87 | + </Reference> | ||
88 | + <Reference Include="Microsoft.SqlServer.Management.Assessment, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
89 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.Assessment.dll</HintPath> | ||
90 | + </Reference> | ||
91 | + <Reference Include="Microsoft.SqlServer.Management.Collector, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
92 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.Collector.dll</HintPath> | ||
93 | + </Reference> | ||
94 | + <Reference Include="Microsoft.SqlServer.Management.CollectorEnum, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
95 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.CollectorEnum.dll</HintPath> | ||
96 | + </Reference> | ||
97 | + <Reference Include="Microsoft.SqlServer.Management.HadrData, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
98 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.HadrData.dll</HintPath> | ||
99 | + </Reference> | ||
100 | + <Reference Include="Microsoft.SqlServer.Management.HadrModel, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
101 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.HadrModel.dll</HintPath> | ||
102 | + </Reference> | ||
103 | + <Reference Include="Microsoft.SqlServer.Management.RegisteredServers, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
104 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.RegisteredServers.dll</HintPath> | ||
105 | + </Reference> | ||
106 | + <Reference Include="Microsoft.SqlServer.Management.Sdk.Sfc, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
107 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.Sdk.Sfc.dll</HintPath> | ||
108 | + </Reference> | ||
109 | + <Reference Include="Microsoft.SqlServer.Management.SmoMetadataProvider, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
110 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.SmoMetadataProvider.dll</HintPath> | ||
111 | + </Reference> | ||
112 | + <Reference Include="Microsoft.SqlServer.Management.SqlParser, Version=16.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
113 | + <HintPath>..\packages\Microsoft.SqlServer.Management.SqlParser.160.20216.14\lib\net462\Microsoft.SqlServer.Management.SqlParser.dll</HintPath> | ||
114 | + </Reference> | ||
115 | + <Reference Include="Microsoft.SqlServer.Management.SqlScriptPublish, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
116 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.SqlScriptPublish.dll</HintPath> | ||
117 | + </Reference> | ||
118 | + <Reference Include="Microsoft.SqlServer.Management.XEvent, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
119 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.XEvent.dll</HintPath> | ||
120 | + </Reference> | ||
121 | + <Reference Include="Microsoft.SqlServer.Management.XEventDbScoped, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
122 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.XEventDbScoped.dll</HintPath> | ||
123 | + </Reference> | ||
124 | + <Reference Include="Microsoft.SqlServer.Management.XEventDbScopedEnum, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
125 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.XEventDbScopedEnum.dll</HintPath> | ||
126 | + </Reference> | ||
127 | + <Reference Include="Microsoft.SqlServer.Management.XEventEnum, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
128 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Management.XEventEnum.dll</HintPath> | ||
129 | + </Reference> | ||
130 | + <Reference Include="Microsoft.SqlServer.PolicyEnum, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
131 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.PolicyEnum.dll</HintPath> | ||
132 | + </Reference> | ||
133 | + <Reference Include="Microsoft.SqlServer.RegSvrEnum, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
134 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.RegSvrEnum.dll</HintPath> | ||
135 | + </Reference> | ||
136 | + <Reference Include="Microsoft.SqlServer.ServiceBrokerEnum, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
137 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.ServiceBrokerEnum.dll</HintPath> | ||
138 | + </Reference> | ||
139 | + <Reference Include="Microsoft.SqlServer.Smo, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
140 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Smo.dll</HintPath> | ||
141 | + </Reference> | ||
142 | + <Reference Include="Microsoft.SqlServer.Smo.Notebook, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
143 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.Smo.Notebook.dll</HintPath> | ||
144 | + </Reference> | ||
145 | + <Reference Include="Microsoft.SqlServer.SmoExtended, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
146 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.SmoExtended.dll</HintPath> | ||
147 | + </Reference> | ||
148 | + <Reference Include="Microsoft.SqlServer.SqlClrProvider, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
149 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.SqlClrProvider.dll</HintPath> | ||
150 | + </Reference> | ||
151 | + <Reference Include="Microsoft.SqlServer.SqlEnum, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
152 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.SqlEnum.dll</HintPath> | ||
153 | + </Reference> | ||
154 | + <Reference Include="Microsoft.SqlServer.SqlWmiManagement, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
155 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.SqlWmiManagement.dll</HintPath> | ||
156 | + </Reference> | ||
157 | + <Reference Include="Microsoft.SqlServer.WmiEnum, Version=16.200.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL"> | ||
158 | + <HintPath>..\packages\Microsoft.SqlServer.SqlManagementObjects.161.46041.41\lib\net462\Microsoft.SqlServer.WmiEnum.dll</HintPath> | ||
159 | + </Reference> | ||
45 | <Reference Include="Microsoft.Web.Administration, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> | 160 | <Reference Include="Microsoft.Web.Administration, Version=10.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> |
46 | <HintPath>..\packages\Microsoft.Web.Administration.11.1.0\lib\netstandard1.5\Microsoft.Web.Administration.dll</HintPath> | 161 | <HintPath>..\packages\Microsoft.Web.Administration.11.1.0\lib\netstandard1.5\Microsoft.Web.Administration.dll</HintPath> |
47 | </Reference> | 162 | </Reference> |
@@ -51,17 +166,22 @@ | @@ -51,17 +166,22 @@ | ||
51 | <Reference Include="Microsoft.Win32.Registry, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> | 166 | <Reference Include="Microsoft.Win32.Registry, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> |
52 | <HintPath>..\packages\Microsoft.Win32.Registry.4.0.0\lib\net46\Microsoft.Win32.Registry.dll</HintPath> | 167 | <HintPath>..\packages\Microsoft.Win32.Registry.4.0.0\lib\net46\Microsoft.Win32.Registry.dll</HintPath> |
53 | </Reference> | 168 | </Reference> |
169 | + <Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> | ||
170 | + <HintPath>..\packages\Newtonsoft.Json.11.0.1\lib\net45\Newtonsoft.Json.dll</HintPath> | ||
171 | + </Reference> | ||
54 | <Reference Include="System" /> | 172 | <Reference Include="System" /> |
55 | <Reference Include="System.AppContext, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> | 173 | <Reference Include="System.AppContext, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> |
56 | <HintPath>..\packages\System.AppContext.4.1.0\lib\net46\System.AppContext.dll</HintPath> | 174 | <HintPath>..\packages\System.AppContext.4.1.0\lib\net46\System.AppContext.dll</HintPath> |
57 | </Reference> | 175 | </Reference> |
58 | <Reference Include="System.ComponentModel.Composition" /> | 176 | <Reference Include="System.ComponentModel.Composition" /> |
59 | <Reference Include="System.ComponentModel.DataAnnotations" /> | 177 | <Reference Include="System.ComponentModel.DataAnnotations" /> |
178 | + <Reference Include="System.Configuration" /> | ||
60 | <Reference Include="System.Configuration.Install" /> | 179 | <Reference Include="System.Configuration.Install" /> |
61 | <Reference Include="System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> | 180 | <Reference Include="System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> |
62 | <HintPath>..\packages\System.Console.4.0.0\lib\net46\System.Console.dll</HintPath> | 181 | <HintPath>..\packages\System.Console.4.0.0\lib\net46\System.Console.dll</HintPath> |
63 | </Reference> | 182 | </Reference> |
64 | <Reference Include="System.Core" /> | 183 | <Reference Include="System.Core" /> |
184 | + <Reference Include="System.Data.Linq" /> | ||
65 | <Reference Include="System.Diagnostics.DiagnosticSource, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL"> | 185 | <Reference Include="System.Diagnostics.DiagnosticSource, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL"> |
66 | <HintPath>..\packages\System.Diagnostics.DiagnosticSource.4.0.0\lib\net46\System.Diagnostics.DiagnosticSource.dll</HintPath> | 186 | <HintPath>..\packages\System.Diagnostics.DiagnosticSource.4.0.0\lib\net46\System.Diagnostics.DiagnosticSource.dll</HintPath> |
67 | </Reference> | 187 | </Reference> |
@@ -71,9 +191,14 @@ | @@ -71,9 +191,14 @@ | ||
71 | <Reference Include="System.Diagnostics.Tracing, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> | 191 | <Reference Include="System.Diagnostics.Tracing, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> |
72 | <HintPath>..\packages\System.Diagnostics.Tracing.4.1.0\lib\net462\System.Diagnostics.Tracing.dll</HintPath> | 192 | <HintPath>..\packages\System.Diagnostics.Tracing.4.1.0\lib\net462\System.Diagnostics.Tracing.dll</HintPath> |
73 | </Reference> | 193 | </Reference> |
194 | + <Reference Include="System.Drawing" /> | ||
74 | <Reference Include="System.Globalization.Calendars, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> | 195 | <Reference Include="System.Globalization.Calendars, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> |
75 | <HintPath>..\packages\System.Globalization.Calendars.4.0.1\lib\net46\System.Globalization.Calendars.dll</HintPath> | 196 | <HintPath>..\packages\System.Globalization.Calendars.4.0.1\lib\net46\System.Globalization.Calendars.dll</HintPath> |
76 | </Reference> | 197 | </Reference> |
198 | + <Reference Include="System.IdentityModel" /> | ||
199 | + <Reference Include="System.IdentityModel.Tokens.Jwt, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> | ||
200 | + <HintPath>..\packages\System.IdentityModel.Tokens.Jwt.5.6.0\lib\net461\System.IdentityModel.Tokens.Jwt.dll</HintPath> | ||
201 | + </Reference> | ||
77 | <Reference Include="System.IO, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> | 202 | <Reference Include="System.IO, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"> |
78 | <HintPath>..\packages\System.IO.4.1.0\lib\net462\System.IO.dll</HintPath> | 203 | <HintPath>..\packages\System.IO.4.1.0\lib\net462\System.IO.dll</HintPath> |
79 | </Reference> | 204 | </Reference> |
@@ -140,23 +265,34 @@ | @@ -140,23 +265,34 @@ | ||
140 | </Reference> | 265 | </Reference> |
141 | <Reference Include="System.Web" /> | 266 | <Reference Include="System.Web" /> |
142 | <Reference Include="System.Web.ApplicationServices" /> | 267 | <Reference Include="System.Web.ApplicationServices" /> |
268 | + <Reference Include="System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> | ||
269 | + <HintPath>..\packages\Microsoft.AspNet.Providers.Core.2.0.0\lib\net40\System.Web.Providers.dll</HintPath> | ||
270 | + </Reference> | ||
271 | + <Reference Include="System.Windows.Forms" /> | ||
143 | <Reference Include="System.Xml.Linq" /> | 272 | <Reference Include="System.Xml.Linq" /> |
144 | <Reference Include="System.Data.DataSetExtensions" /> | 273 | <Reference Include="System.Data.DataSetExtensions" /> |
145 | <Reference Include="Microsoft.CSharp" /> | 274 | <Reference Include="Microsoft.CSharp" /> |
146 | <Reference Include="System.Data" /> | 275 | <Reference Include="System.Data" /> |
147 | <Reference Include="System.Xml" /> | 276 | <Reference Include="System.Xml" /> |
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> | 277 | + <Reference Include="VRH.Common, Version=2.20.1.0, Culture=neutral, processorArchitecture=MSIL"> |
278 | + <HintPath>..\packages\VRH.Common.2.20.1\lib\net45\VRH.Common.dll</HintPath> | ||
279 | + </Reference> | ||
280 | + <Reference Include="Vrh.Web.Providers, Version=2.0.2.0, Culture=neutral, processorArchitecture=MSIL"> | ||
281 | + <HintPath>..\packages\VRH.Web.Providers.2.0.2\lib\net452\Vrh.Web.Providers.dll</HintPath> | ||
150 | </Reference> | 282 | </Reference> |
151 | - <Reference Include="Vrh.XmlProcessing, Version=1.23.0.0, Culture=neutral, processorArchitecture=MSIL"> | ||
152 | - <HintPath>..\packages\Vrh.XmlProcessing.1.23.0\lib\net45\Vrh.XmlProcessing.dll</HintPath> | 283 | + <Reference Include="Vrh.XmlProcessing, Version=1.24.0.0, Culture=neutral, processorArchitecture=MSIL"> |
284 | + <HintPath>..\packages\Vrh.XmlProcessing.1.24.0\lib\net45\Vrh.XmlProcessing.dll</HintPath> | ||
153 | </Reference> | 285 | </Reference> |
154 | </ItemGroup> | 286 | </ItemGroup> |
155 | <ItemGroup> | 287 | <ItemGroup> |
156 | <Compile Include="ConsoleFunction - CommandLineParser.cs" /> | 288 | <Compile Include="ConsoleFunction - CommandLineParser.cs" /> |
157 | <Compile Include="ConsoleFunction - ColorConsole.cs" /> | 289 | <Compile Include="ConsoleFunction - ColorConsole.cs" /> |
158 | <Compile Include="ConsoleFunction - Menu.cs" /> | 290 | <Compile Include="ConsoleFunction - Menu.cs" /> |
291 | + <Compile Include="ConsoleFunction - Tools - Membership.cs" /> | ||
159 | <Compile Include="ConsoleFunction - Tools.cs" /> | 292 | <Compile Include="ConsoleFunction - Tools.cs" /> |
293 | + <Compile Include="Manager - BackupPackageManager.cs" /> | ||
294 | + <Compile Include="Manager - UserManager.cs" /> | ||
295 | + <Compile Include="Manager - SQLDataBaseManager.cs" /> | ||
160 | <Compile Include="Manager - ScheduledTaskManager.cs" /> | 296 | <Compile Include="Manager - ScheduledTaskManager.cs" /> |
161 | <Compile Include="Manager - WindowsServiceManager.cs" /> | 297 | <Compile Include="Manager - WindowsServiceManager.cs" /> |
162 | <Compile Include="Manager - FileCleanerManager.cs" /> | 298 | <Compile Include="Manager - FileCleanerManager.cs" /> |
@@ -170,6 +306,8 @@ | @@ -170,6 +306,8 @@ | ||
170 | <CopyToOutputDirectory>Always</CopyToOutputDirectory> | 306 | <CopyToOutputDirectory>Always</CopyToOutputDirectory> |
171 | </None> | 307 | </None> |
172 | <None Include="packages.config" /> | 308 | <None Include="packages.config" /> |
309 | + <None Include="system.web.membership.config" /> | ||
310 | + <None Include="system.web.rolemanager.config" /> | ||
173 | <None Include="Vrh.NugetModuls.Documentations\VRH.Common\ReadMe.md" /> | 311 | <None Include="Vrh.NugetModuls.Documentations\VRH.Common\ReadMe.md" /> |
174 | <None Include="Vrh.NugetModuls.Documentations\Vrh.XmlProcessing\ReadMe.md" /> | 312 | <None Include="Vrh.NugetModuls.Documentations\Vrh.XmlProcessing\ReadMe.md" /> |
175 | </ItemGroup> | 313 | </ItemGroup> |
@@ -177,11 +315,14 @@ | @@ -177,11 +315,14 @@ | ||
177 | <Content Include="Config.xml"> | 315 | <Content Include="Config.xml"> |
178 | <CopyToOutputDirectory>Always</CopyToOutputDirectory> | 316 | <CopyToOutputDirectory>Always</CopyToOutputDirectory> |
179 | </Content> | 317 | </Content> |
318 | + <Content Include="servicelogo.ico" /> | ||
180 | <Content Include="XmlParser.xml"> | 319 | <Content Include="XmlParser.xml"> |
181 | <CopyToOutputDirectory>Always</CopyToOutputDirectory> | 320 | <CopyToOutputDirectory>Always</CopyToOutputDirectory> |
182 | </Content> | 321 | </Content> |
183 | </ItemGroup> | 322 | </ItemGroup> |
184 | - <ItemGroup /> | 323 | + <ItemGroup> |
324 | + <WCFMetadata Include="Connected Services\" /> | ||
325 | + </ItemGroup> | ||
185 | <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> | 326 | <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> |
186 | <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> | 327 | <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> |
187 | <PropertyGroup> | 328 | <PropertyGroup> |
@@ -189,6 +330,8 @@ | @@ -189,6 +330,8 @@ | ||
189 | </PropertyGroup> | 330 | </PropertyGroup> |
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'))" /> | 331 | <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'))" /> | 332 | <Error Condition="!Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\EntityFramework.6.4.4\build\EntityFramework.targets'))" /> |
333 | + <Error Condition="!Exists('..\packages\Microsoft.Data.SqlClient.SNI.2.0.0\build\net46\Microsoft.Data.SqlClient.SNI.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Data.SqlClient.SNI.2.0.0\build\net46\Microsoft.Data.SqlClient.SNI.targets'))" /> | ||
192 | </Target> | 334 | </Target> |
193 | <Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.targets" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" /> | 335 | <Import Project="..\packages\EntityFramework.6.4.4\build\EntityFramework.targets" Condition="Exists('..\packages\EntityFramework.6.4.4\build\EntityFramework.targets')" /> |
336 | + <Import Project="..\packages\Microsoft.Data.SqlClient.SNI.2.0.0\build\net46\Microsoft.Data.SqlClient.SNI.targets" Condition="Exists('..\packages\Microsoft.Data.SqlClient.SNI.2.0.0\build\net46\Microsoft.Data.SqlClient.SNI.targets')" /> | ||
194 | </Project> | 337 | </Project> |
195 | \ No newline at end of file | 338 | \ No newline at end of file |
Vrh.Log4Pro.MaintenanceConsole/XmlParser.xml
1 | <?xml version="1.0" encoding="utf-8" ?> | 1 | <?xml version="1.0" encoding="utf-8" ?> |
2 | -<XmlParserConfiguration LCID="en-US" NameSeparator="{}@@##||"> | 2 | +<XmlParserConfiguration LCID="en-US" NameSeparator="@@||"> |
3 | <XmlParser> | 3 | <XmlParser> |
4 | - <XmlVar Name="SINGLESERVERIP">127.0.0.1</XmlVar> | ||
5 | - <XmlVar Name="WEBALMHOST">@SINGLESERVERIP@</XmlVar> | ||
6 | - <XmlVar Name="WEBALM">WebALM</XmlVar> | ||
7 | - | ||
8 | - <XmlVar Name="WEBCPHOST">@SINGLESERVERIP@</XmlVar> | ||
9 | - <XmlVar Name="WEBCP">WebPack</XmlVar> | ||
10 | - | ||
11 | - <XmlVar Name="WEBANDONHOST">@SINGLESERVERIP@</XmlVar> | ||
12 | - <XmlVar Name="WEBANDON">WebAndon</XmlVar> | ||
13 | - | ||
14 | - <!-- A komment be és ki módszert válaszd légyszi, ne írd át! --> | ||
15 | - <!--<XmlVar Name="APPROOTPATH">d:\!Dev\VRH\LearALMNew</XmlVar>--> | ||
16 | - <XmlVar Name="APPROOTPATH">c:\Log4ProIS</XmlVar> | ||
17 | - <XmlVar Name="CENTRALCONFIGPATH">c:\Log4ProIS\CONFIG</XmlVar> | ||
18 | - <XmlVar Name="ACROOTPATH">@APPROOTPATH@\VRH.Log4Pro.ACALM</XmlVar> | ||
19 | - | ||
20 | - <XmlVar Name="WEBAPPROOT">@APPROOTPATH@\wwwroot_Log4ProIS</XmlVar> | ||
21 | - <XmlVar Name="APPDATA">@WEBAPPROOT@\App_Data</XmlVar> | ||
22 | - <XmlVar Name="APPDATAALM">@WEBAPPROOT@\App_Data\ALM</XmlVar> | ||
23 | - <XmlVar Name="APPDATACP">@WEBAPPROOT@\App_Data\CP</XmlVar> | ||
24 | - <XmlVar Name="APPDATAANDON">@WEBAPPROOT@\App_Data\ANDON</XmlVar> | ||
25 | - <XmlVar Name="APPDATAISTRM">@WEBAPPROOT@\App_Data\IS-TRM</XmlVar> | ||
26 | - | ||
27 | - <XmlVar Name="WEBAPPROOT_WEBPACK">@APPROOTPATH@\wwwroot_WebPack</XmlVar> | ||
28 | - <XmlVar Name="APPDATA_WEBPACK">@WEBAPPROOT_WEBPACK@\App_Data</XmlVar> | ||
29 | - | ||
30 | - <XmlVar Name="WEBAPPROOT_ANDON">@APPROOTPATH@\wwwroot_WebAndon</XmlVar> | ||
31 | - <XmlVar Name="APPDATA_ANDON">@WEBAPPROOT_ANDON@\App_Data</XmlVar> | ||
32 | - | ||
33 | - <XmlVar Name="WEBAPPROOT_ALM">@APPROOTPATH@\wwwroot_WebALM</XmlVar> | ||
34 | - <XmlVar Name="APPDATA_ALM">@WEBAPPROOT_ALM@\App_Data</XmlVar> | ||
35 | - | ||
36 | - <XmlVar Name="DCWF_ALMROOT">@APPROOTPATH@\VRH.Log4Pro.ASEDC-DCWF_ALM\</XmlVar> | ||
37 | - <XmlVar Name="DCWF_CPROOT">@APPROOTPATH@\VRH.Log4Pro.ASEDC-DCWF_CP\</XmlVar> | ||
38 | - <XmlVar Name="ASEMON_ROOT">@APPROOTPATH@\VRH.Log4Pro.ASEDC-ASEMON\</XmlVar> | ||
39 | - | ||
40 | - <XmlVar Name="ALMSERVERIP">localhost</XmlVar> | ||
41 | - <XmlVar Name="ALMBACKUPS">c:\Log4ProISBackups</XmlVar> | ||
42 | - | ||
43 | - <XmlVar Name="ALMDOCUMENTS">@ALMBACKUPS@\Documents</XmlVar> | ||
44 | - | ||
45 | - | ||
46 | - <XmlVar Name="XMLPARSERBUTTONDEFXML">@APPDATA@\WebMonitor\XmlParserButtonDefinitions.xml</XmlVar> | ||
47 | - | ||
48 | - <XmlVar Name="ENABLEDISTRIBUTEWCFCONFIGFILES">false</XmlVar> | ||
49 | - <XmlVar Name="COMMONSITENAME">SITE_SLNOTEBOOKDELL</XmlVar> | 4 | + <XmlVar Name="APPROOTPATH">c:\Log4ProIS</XmlVar> |
5 | + <XmlVar Name="DIR_MAINTENANCECONSOLE">@APPROOTPATH@\MAINTENANCECONSOLE</XmlVar> | ||
50 | </XmlParser> | 6 | </XmlParser> |
51 | - | ||
52 | - <XmlParser Description="Common menu parameters"> | ||
53 | - <XmlVar Name="MENUCREATEROLES">true</XmlVar> | ||
54 | - <XmlVar Name="MENUROLEPREFIX"></XmlVar> | ||
55 | - <XmlVar Name="MENUCREATEWORDCODES">true</XmlVar> | ||
56 | - <XmlVar Name="MENUWORDCODEPREFIX">Menu.Xml</XmlVar> | ||
57 | - <XmlVar Name="MENUGROUPBEHAVIOR">Accordion</XmlVar> | ||
58 | - <XmlVar Name="STYLE_DIALOG_W40">max-width:40vmax;</XmlVar> | ||
59 | - <XmlVar Name="STYLE_DIALOG_W80">max-width:80vmax;</XmlVar> | ||
60 | - <XmlVar Name="STYLE_DIALOG_W120">max-width:120vmax;</XmlVar> | ||
61 | - <XmlVar Name="STYLE_DIALOG_MENU">max-width:90vmax;margin 100; padding 10;</XmlVar> | ||
62 | - <XmlVar Name="STYLE_DIALOG_RETURNINFO">max-width:50vmax;font-size:larger;color:white;</XmlVar> | ||
63 | - <XmlVar Name="STYLE_DIALOG_ENTRYM">max-width:70vmax;font-size:larger;color:white;</XmlVar> | ||
64 | - <XmlVar Name="STYLE_DIALOG_ENTRYXL">max-width:100vmax;font-size:larger;color:white;</XmlVar> | ||
65 | - </XmlParser> | ||
66 | - | ||
67 | <Configurations> | 7 | <Configurations> |
68 | - <Configuration Name="Vrh.Log4Pro.MaintenanceConsole" File="C:\___VCSOLUTIONS\Vrh.Log4Pro.MaintenanceConsole\Vrh.Log4Pro.MaintenanceConsole\Xml.Parser" /> | ||
69 | - | ||
70 | - | ||
71 | - <Configuration Name="VRH.ConnectionStringStore" File="@CENTRALCONFIGPATH@\ConnectionStringStore.xml" /> | ||
72 | - | ||
73 | - | ||
74 | - <Configuration Name="Menu" File="@APPDATA@\Menu\Menu.xml" Element="MainMenu"/> | ||
75 | - <Configuration Name="RedisScripter" File="@APPDATA@\RedisManager\RedisManagerScripts.xml" /> | ||
76 | - <Configuration Name="UserAuthentication" File="@APPDATA@\UserAdministration\UserAdministration.xml" /> | ||
77 | - <Configuration Name="WebForm" File="@APPDATA@\WebForm\WebForms.xml"/> | ||
78 | - | ||
79 | - <!--Ezt jelenleg az IdTranslator Web felület használja, mint alapértelmezett XmlConnectionString használja, mint alapértelmezett--> | ||
80 | - <Configuration Name="IdTranslator" File="@APPDATA@\IdTranslator\IdTranslator.xml"/> | ||
81 | - | ||
82 | - <Configuration Name="IVConnector" File="@ACROOTPATH@\IVConnector2.0.0\IVConnector.Config.xml"/> | ||
83 | - | ||
84 | - <Configuration Name="DCWF_ALM" File="{DCWF_ALMROOT}DCWF_ALM-parameters.xml" Element="DCWF_ALMParameters"/> | ||
85 | - <Configuration Name="DCWP_ALM" File="{DCWF_ALMROOT}DCWF_ALM-WP-parameters.xml" Element="DCWP"/> | ||
86 | - <Configuration Name="DCWPWCF_ALM" File="{DCWF_ALMROOT}DCWF_ALM-WP-parameters.xml" Element="DCWPWCF"/> | ||
87 | - <Configuration Name="DCWF_ALMMenuPage" File="@APPDATAALM@\DCWF_ALMMenuPage.xml" Element="MenuPageDCWF_ALM"/> | ||
88 | - <Configuration Name="DCWF_ALMWebMonitorMenuPage" File="@APPDATAALM@\DCWF_ALMMenuPage.xml" Element="MenuPageWebMonitor"/> | ||
89 | - <!--<Configuration Name="DCWF_ALMOneReportMenuPage" File="@APPDATAALM@\DCWF_ALMMenuPage.xml" Element="MenuPageOneReport"/>--> | ||
90 | - | ||
91 | - <Configuration Name="DCWF_ALMOneReportWebForms" File="@APPDATAALM@\OneReport\OneReports.xml" Element="WebFormXML"/> | ||
92 | - <Configuration Name="DCWF_ALMOneReportMenuPage" File="@APPDATAALM@\OneReport\OneReports.xml" Element="MenuPageOneReport"/> | ||
93 | - <Configuration Name="ALM_OneReport" File="@APPDATAALM@\OneReport\OneReports.xml" Element="ReportDefinitions"/> | ||
94 | - | ||
95 | - <Configuration Name="DCWF_ALMFileManagerMenuPage" File="@APPDATAALM@\DCWF_ALMMenuPage.xml" Element="MenuPageFileManager"/> | ||
96 | - <Configuration Name="DCWF_ALMOneScripter" File="@APPDATAALM@\OneScripter\OneScripterMenuPage.xml" /> | ||
97 | - <Configuration Name="DCWF_ALMRedisManager" File="@APPDATAALM@\RedisManager\RedisManagerConfig.xml" /> | ||
98 | - <Configuration Name="DCWF_ALMServiceControl" File="@APPDATAALM@\ServiceControl\ServiceControlConfig.xml" /> | ||
99 | - <Configuration Name="DCWF_ALMASEMWManager" File="@APPDATAALM@\AseMwManager\AseMwManager.xml" /> | ||
100 | - <Configuration Name="DCWF_ALMConfigEditorMenuPage" File="@APPDATAALM@\ConfigEditor\ConfigEditorALMMenuPage.xml" /> | ||
101 | - <Configuration Name="InterventionDCWFWCF_ALMInterventionService" File="@APPDATAALM@\Interventions\DCWF_ALMInterventions.xml"/> | ||
102 | - <Configuration Name="InterventionDTMInterventionService" File="@APPDATAALM@\Interventions\ALMInterventions.xml"/> | ||
103 | - <Configuration Name="DCWF_ALMConfigEditor" File="@APPDATAALM@\ConfigEditor\ConfigEditorALM.xml" /> | ||
104 | - <Configuration Name="DCWF_ALMiSchedulerReportMenuPage" File="@APPDATAALM@\DCWF_ALMMenuPage.xml" Element="MenuPageiSchedulerReport" /> | ||
105 | - <Configuration Name="DCWF_ALMiScheduler" File="@APPDATAALM@\iScheduler\iScheduler.xml"/> | ||
106 | - <Configuration Name="DCWF_ALMiSchedulerReport" File="@APPDATAALM@\iScheduler\iSchedulerReport.xml"/> | ||
107 | - <Configuration Name="DCWF_ALMiSchedulerWebForms" File="@APPDATAALM@\iScheduler\iSchedulerWebforms.xml"/> | ||
108 | - <Configuration Name="SelectListsALM" File="@APPDATAALM@\Intervention\DCWF_ALMSelectLists.xml"/> | ||
109 | - <Configuration Name="ALM_WebMonitor" File="@APPDATAALM@\WebMonitor\WebMonitor.xml"/> | ||
110 | - <Configuration Name="ALM_Matrix1D" File="@APPDATAALM@\WebMonitor\Matrix1D.xml"/> | ||
111 | - <Configuration Name="ALM_Matrix2D" File="@APPDATAALM@\WebMonitor\Matrix2D.xml"/> | ||
112 | - <Configuration Name="ALM_TrendDiagram" File="@APPDATAALM@\WebMonitor\TrendDiagram.xml"/> | ||
113 | - | ||
114 | - <Configuration Name="ISTRM_MenuPage" File="@APPDATAISTRM@\ISTRMMenuPage.xml" Element="MenuPageISTRM"/> | ||
115 | - <Configuration Name="ISTRM_WebMonitor" File="@APPDATAISTRM@\WebMonitor\WebMonitor.xml"/> | ||
116 | - <Configuration Name="ISTRM_Matrix2D" File="@APPDATAISTRM@\WebMonitor\Matrix2D.xml"/> | ||
117 | - | ||
118 | - | ||
119 | - <Configuration Name="ANDONMenuPage" File="@APPDATAANDON@\ANDONMenuPage.xml" Element="MenuPageAndon"/> | ||
120 | - <Configuration Name="ANDONConfig" File="@APPDATAANDON@\Andon.Config.XML"/> | ||
121 | - <Configuration Name="ANDONRedisManager" File="@APPDATAANDON@\Andon.Config.XML" Element="RedisManager" /> | ||
122 | - | ||
123 | - <Configuration Name="DCWF_CP" File="{DCWF_CPROOT}DCWF_CP-parameters.xml"/> | ||
124 | - <Configuration Name="DCWP_CP" File="{DCWF_CPROOT}DCWF_CP-WP-parameters.xml" Element="DCWP"/> | ||
125 | - <Configuration Name="DCWPWCF_CP" File="{DCWF_CPROOT}DCWF_CP-WP-parameters.xml" Element="DCWPWCF"/> | ||
126 | - <Configuration Name="DCWF_CP_ivConnectorOut" File="{DCWF_CPROOT}DCWF_CP-IVCONNECTOR.xml"/> | ||
127 | - <Configuration Name="DCWF_CPMenuPage" File="@APPDATACP@\DCWF_CPMenuPage.xml" Element="MenuPageDCWF_CP"/> | ||
128 | - <Configuration Name="DCWF_CPASEMWManager" File="@APPDATACP@\AseMwManager\AseMwManager.xml" /> | ||
129 | - <Configuration Name="DCWF_CPServiceControl" File="@APPDATACP@\ServiceControl\ServiceControlConfig.xml" /> | ||
130 | - <Configuration Name="DCWF_CPRedisManager" File="@APPDATACP@\RedisManager\RedisManagerConfig.xml" /> | ||
131 | - <Configuration Name="CPConfig" File="@APPDATACP@\CPConfiguration.xml" /> | ||
132 | - <Configuration Name="InterventionDCWFWCF_CPInterventionService" File="@APPDATACP@\Interventions\DCWF_CPInterventions.xml"/> | ||
133 | - <Configuration Name="SelectListsCP" File="@APPDATACP@\Interventions\DCWF_CPSelectLists.xml"/> | ||
134 | - <Configuration Name="ConfigEditorCP" File="@APPDATACP@\ConfigEditor\ConfigEditorCP.xml" /> | ||
135 | - <Configuration Name="WebMonitorCP" File="@APPDATACP@\WebMonitor\WebMonitorCP.xml"/> | ||
136 | - <Configuration Name="Matrix1DCP" File="@APPDATACP@\WebMonitor\Matrix1DCP.xml"/> | ||
137 | - <Configuration Name="Matrix2DCP" File="@APPDATACP@\WebMonitor\Matrix2DCP.xml"/> | ||
138 | - | 8 | + <Configuration></Configuration> |
9 | + <Configurations Description="MAINTENANCECONSOLE"> | ||
10 | + <Configuration Name="MAINTENANCECONSOLE_BACKUPMANAGER" File="@DIR_MAINTENANCECONSOLE@\Config.xml" Element = "BackupPackages"/> | ||
11 | + <Configuration Name="MAINTENANCECONSOLE_FILECLEANERMANAGER" File="@DIR_MAINTENANCECONSOLE@\Config.xml" Element = "FileCleaner"/> | ||
12 | + <Configuration Name="MAINTENANCECONSOLE_MAINTENANCETOOLMANAGER" File="@DIR_MAINTENANCECONSOLE@\Config.xml" Element = "MaintenanceTools"/> | ||
13 | + <Configuration Name="MAINTENANCECONSOLE_SCHEDULEDTASKMANAGER" File="@DIR_MAINTENANCECONSOLE@\Config.xml" Element = "ScheduledTasks"/> | ||
14 | + <Configuration Name="MAINTENANCECONSOLE_WEBAPPLICATIONMANAGER" File="@DIR_MAINTENANCECONSOLE@\Config.xml" Element = "WebApplications"/> | ||
15 | + <Configuration Name="MAINTENANCECONSOLE_WINDOWSSERVICEMANAGER" File="@DIR_MAINTENANCECONSOLE@\Config.xml" Element = "WindowsServices"/> | ||
16 | + <Configuration Name="MAINTENANCECONSOLE_SQLDATABASEMANAGER" File="@DIR_MAINTENANCECONSOLE@\Config.xml" Element = "SQLDataBases"/> | ||
17 | + <Configuration Name="MAINTENANCECONSOLE_LOG4PROUSERMANAGER" File="@DIR_MAINTENANCECONSOLE@\Config.xml" Element = "Log4ProUserManager"/> | ||
18 | + </Configurations> | ||
139 | </Configurations> | 19 | </Configurations> |
140 | -</XmlParserConfiguration> | ||
141 | \ No newline at end of file | 20 | \ No newline at end of file |
21 | +</XmlParserConfiguration> |
Vrh.Log4Pro.MaintenanceConsole/packages.config
1 | <?xml version="1.0" encoding="utf-8"?> | 1 | <?xml version="1.0" encoding="utf-8"?> |
2 | <packages> | 2 | <packages> |
3 | <package id="EntityFramework" version="6.4.4" targetFramework="net462" /> | 3 | <package id="EntityFramework" version="6.4.4" targetFramework="net462" /> |
4 | + <package id="Microsoft.AspNet.Providers" version="2.0.0" targetFramework="net472" /> | ||
5 | + <package id="Microsoft.AspNet.Providers.Core" version="2.0.0" targetFramework="net472" /> | ||
6 | + <package id="Microsoft.Data.SqlClient" version="2.0.0" targetFramework="net462" /> | ||
7 | + <package id="Microsoft.Data.SqlClient.SNI" version="2.0.0" targetFramework="net462" /> | ||
8 | + <package id="Microsoft.Identity.Client" version="4.14.0" targetFramework="net462" /> | ||
9 | + <package id="Microsoft.IdentityModel.JsonWebTokens" version="5.6.0" targetFramework="net462" /> | ||
10 | + <package id="Microsoft.IdentityModel.Logging" version="5.6.0" targetFramework="net462" /> | ||
11 | + <package id="Microsoft.IdentityModel.Protocols" version="5.6.0" targetFramework="net462" /> | ||
12 | + <package id="Microsoft.IdentityModel.Protocols.OpenIdConnect" version="5.6.0" targetFramework="net462" /> | ||
13 | + <package id="Microsoft.IdentityModel.Tokens" version="5.6.0" targetFramework="net462" /> | ||
4 | <package id="Microsoft.NETCore.Platforms" version="1.0.1" targetFramework="net462" /> | 14 | <package id="Microsoft.NETCore.Platforms" version="1.0.1" targetFramework="net462" /> |
15 | + <package id="Microsoft.SqlServer.Assessment" version="1.0.280" targetFramework="net462" /> | ||
16 | + <package id="Microsoft.SqlServer.Assessment.Authoring" version="1.0.280" targetFramework="net462" /> | ||
17 | + <package id="Microsoft.SqlServer.Management.SqlParser" version="160.20216.14" targetFramework="net462" /> | ||
18 | + <package id="Microsoft.SqlServer.SqlManagementObjects" version="161.46041.41" targetFramework="net462" /> | ||
5 | <package id="Microsoft.Web.Administration" version="11.1.0" targetFramework="net462" /> | 19 | <package id="Microsoft.Web.Administration" version="11.1.0" targetFramework="net462" /> |
6 | <package id="Microsoft.Win32.Primitives" version="4.0.1" targetFramework="net462" /> | 20 | <package id="Microsoft.Win32.Primitives" version="4.0.1" targetFramework="net462" /> |
7 | <package id="Microsoft.Win32.Registry" version="4.0.0" targetFramework="net462" /> | 21 | <package id="Microsoft.Win32.Registry" version="4.0.0" targetFramework="net462" /> |
8 | <package id="NETStandard.Library" version="1.6.0" targetFramework="net462" /> | 22 | <package id="NETStandard.Library" version="1.6.0" targetFramework="net462" /> |
9 | - <package id="System.AppContext" version="4.1.0" targetFramework="net462" /> | 23 | + <package id="Newtonsoft.Json" version="11.0.1" targetFramework="net462" /> |
24 | + <package id="System.AppContext" version="4.1.0" targetFramework="net462" requireReinstallation="true" /> | ||
10 | <package id="System.Collections" version="4.0.11" targetFramework="net462" /> | 25 | <package id="System.Collections" version="4.0.11" targetFramework="net462" /> |
11 | <package id="System.Collections.Concurrent" version="4.0.12" targetFramework="net462" /> | 26 | <package id="System.Collections.Concurrent" version="4.0.12" targetFramework="net462" /> |
12 | <package id="System.Console" version="4.0.0" targetFramework="net462" /> | 27 | <package id="System.Console" version="4.0.0" targetFramework="net462" /> |
@@ -17,13 +32,14 @@ | @@ -17,13 +32,14 @@ | ||
17 | <package id="System.Diagnostics.Tracing" version="4.1.0" targetFramework="net462" /> | 32 | <package id="System.Diagnostics.Tracing" version="4.1.0" targetFramework="net462" /> |
18 | <package id="System.Globalization" version="4.0.11" targetFramework="net462" /> | 33 | <package id="System.Globalization" version="4.0.11" targetFramework="net462" /> |
19 | <package id="System.Globalization.Calendars" version="4.0.1" targetFramework="net462" /> | 34 | <package id="System.Globalization.Calendars" version="4.0.1" targetFramework="net462" /> |
35 | + <package id="System.IdentityModel.Tokens.Jwt" version="5.6.0" targetFramework="net462" /> | ||
20 | <package id="System.IO" version="4.1.0" targetFramework="net462" /> | 36 | <package id="System.IO" version="4.1.0" targetFramework="net462" /> |
21 | <package id="System.IO.Compression" version="4.1.0" targetFramework="net462" /> | 37 | <package id="System.IO.Compression" version="4.1.0" targetFramework="net462" /> |
22 | <package id="System.IO.Compression.ZipFile" version="4.0.1" targetFramework="net462" /> | 38 | <package id="System.IO.Compression.ZipFile" version="4.0.1" targetFramework="net462" /> |
23 | <package id="System.IO.FileSystem" version="4.0.1" targetFramework="net462" /> | 39 | <package id="System.IO.FileSystem" version="4.0.1" targetFramework="net462" /> |
24 | <package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net462" /> | 40 | <package id="System.IO.FileSystem.Primitives" version="4.0.1" targetFramework="net462" /> |
25 | - <package id="System.Linq" version="4.1.0" targetFramework="net462" /> | ||
26 | - <package id="System.Linq.Expressions" version="4.1.0" targetFramework="net462" /> | 41 | + <package id="System.Linq" version="4.1.0" targetFramework="net462" requireReinstallation="true" /> |
42 | + <package id="System.Linq.Expressions" version="4.1.0" targetFramework="net462" requireReinstallation="true" /> | ||
27 | <package id="System.Management" version="5.0.0" targetFramework="net462" /> | 43 | <package id="System.Management" version="5.0.0" targetFramework="net462" /> |
28 | <package id="System.Net.Http" version="4.1.0" targetFramework="net462" /> | 44 | <package id="System.Net.Http" version="4.1.0" targetFramework="net462" /> |
29 | <package id="System.Net.Primitives" version="4.0.11" targetFramework="net462" /> | 45 | <package id="System.Net.Primitives" version="4.0.11" targetFramework="net462" /> |
@@ -41,7 +57,7 @@ | @@ -41,7 +57,7 @@ | ||
41 | <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.0.0" targetFramework="net462" /> | 57 | <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.0.0" targetFramework="net462" /> |
42 | <package id="System.Runtime.Numerics" version="4.0.1" targetFramework="net462" /> | 58 | <package id="System.Runtime.Numerics" version="4.0.1" targetFramework="net462" /> |
43 | <package id="System.Security.Claims" version="4.0.1" targetFramework="net462" /> | 59 | <package id="System.Security.Claims" version="4.0.1" targetFramework="net462" /> |
44 | - <package id="System.Security.Cryptography.Algorithms" version="4.2.0" targetFramework="net462" /> | 60 | + <package id="System.Security.Cryptography.Algorithms" version="4.2.0" targetFramework="net462" requireReinstallation="true" /> |
45 | <package id="System.Security.Cryptography.Encoding" version="4.0.0" targetFramework="net462" /> | 61 | <package id="System.Security.Cryptography.Encoding" version="4.0.0" targetFramework="net462" /> |
46 | <package id="System.Security.Cryptography.Primitives" version="4.0.0" targetFramework="net462" /> | 62 | <package id="System.Security.Cryptography.Primitives" version="4.0.0" targetFramework="net462" /> |
47 | <package id="System.Security.Cryptography.X509Certificates" version="4.1.0" targetFramework="net462" /> | 63 | <package id="System.Security.Cryptography.X509Certificates" version="4.1.0" targetFramework="net462" /> |
@@ -49,12 +65,13 @@ | @@ -49,12 +65,13 @@ | ||
49 | <package id="System.ServiceProcess.ServiceController" version="4.1.0" targetFramework="net462" /> | 65 | <package id="System.ServiceProcess.ServiceController" version="4.1.0" targetFramework="net462" /> |
50 | <package id="System.Text.Encoding" version="4.0.11" targetFramework="net462" /> | 66 | <package id="System.Text.Encoding" version="4.0.11" targetFramework="net462" /> |
51 | <package id="System.Text.Encoding.Extensions" version="4.0.11" targetFramework="net462" /> | 67 | <package id="System.Text.Encoding.Extensions" version="4.0.11" targetFramework="net462" /> |
52 | - <package id="System.Text.RegularExpressions" version="4.1.0" targetFramework="net462" /> | 68 | + <package id="System.Text.RegularExpressions" version="4.1.0" targetFramework="net462" requireReinstallation="true" /> |
53 | <package id="System.Threading" version="4.0.11" targetFramework="net462" /> | 69 | <package id="System.Threading" version="4.0.11" targetFramework="net462" /> |
54 | <package id="System.Threading.Tasks" version="4.0.11" targetFramework="net462" /> | 70 | <package id="System.Threading.Tasks" version="4.0.11" targetFramework="net462" /> |
55 | <package id="System.Threading.Timer" version="4.0.1" targetFramework="net462" /> | 71 | <package id="System.Threading.Timer" version="4.0.1" targetFramework="net462" /> |
56 | <package id="System.Xml.ReaderWriter" version="4.0.11" targetFramework="net462" /> | 72 | <package id="System.Xml.ReaderWriter" version="4.0.11" targetFramework="net462" /> |
57 | <package id="System.Xml.XDocument" version="4.0.11" targetFramework="net462" /> | 73 | <package id="System.Xml.XDocument" version="4.0.11" targetFramework="net462" /> |
58 | - <package id="VRH.Common" version="2.19.1" targetFramework="net462" /> | ||
59 | - <package id="Vrh.XmlProcessing" version="1.23.0" targetFramework="net462" /> | 74 | + <package id="VRH.Common" version="2.20.1" targetFramework="net472" /> |
75 | + <package id="VRH.Web.Providers" version="2.0.2" targetFramework="net472" /> | ||
76 | + <package id="Vrh.XmlProcessing" version="1.24.0" targetFramework="net462" /> | ||
60 | </packages> | 77 | </packages> |
61 | \ No newline at end of file | 78 | \ No newline at end of file |
No preview for this file type
Vrh.Log4Pro.MaintenanceConsole/system.web.membership.config
0 → 100644
@@ -0,0 +1,12 @@ | @@ -0,0 +1,12 @@ | ||
1 | +<membership defaultProvider="VrhMembershipProvider"> | ||
2 | + <providers> | ||
3 | + <add name="VrhMembershipProvider" type="Vrh.Web.Providers.VrhMembershipProvider, Vrh.Web.Providers" connectionStringName="Vrh.Web.Providers:connectionstring" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" passwordCompatMode="Framework20" /> | ||
4 | + </providers> | ||
5 | +</membership> | ||
6 | +<!-- | ||
7 | +<membership defaultProvider="DefaultMembershipProvider"> | ||
8 | + <providers> | ||
9 | + <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="VrhWebMembership" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordCompatMode="Framework20" applicationName="/" /> | ||
10 | + </providers> | ||
11 | +</membership> | ||
12 | +--> | ||
0 | \ No newline at end of file | 13 | \ No newline at end of file |
Vrh.Log4Pro.MaintenanceConsole/system.web.rolemanager.config
0 → 100644
@@ -0,0 +1,12 @@ | @@ -0,0 +1,12 @@ | ||
1 | +<roleManager enabled="true" defaultProvider="VrhRoleProvider"> | ||
2 | + <providers> | ||
3 | + <add name="VrhRoleProvider" type="Vrh.Web.Providers.VrhRoleProvider, Vrh.Web.Providers" connectionStringName="Vrh.Web.Providers:connectionstring" applicationName="/" /> | ||
4 | + </providers> | ||
5 | +</roleManager> | ||
6 | +<!-- | ||
7 | +<roleManager enabled="true" defaultProvider="DefaultRoleProvider"> | ||
8 | + <providers> | ||
9 | + <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="Vrh.Web.Providers:connectionstring" applicationName="/" /> | ||
10 | + </providers> | ||
11 | +</roleManager> | ||
12 | +--> | ||
0 | \ No newline at end of file | 13 | \ No newline at end of file |