From 7cdc4aa4219de9dae9bd3e978e3c673f8d77b425 Mon Sep 17 00:00:00 2001 From: Schwirg László Date: Mon, 12 Aug 2024 20:03:57 +0200 Subject: [PATCH] v1.25.0.0 - Adding/Removing trigger to store lastupdate timestamp --- Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - CommandLineParser.cs | 2 ++ Vrh.Log4Pro.MaintenanceConsole/Manager - SQLDataBaseManager.cs | 145 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- Vrh.Log4Pro.MaintenanceConsole/Properties/AssemblyInfo.cs | 4 ++-- 3 files changed, 147 insertions(+), 4 deletions(-) diff --git a/Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - CommandLineParser.cs b/Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - CommandLineParser.cs index 1160b8f..d54479d 100644 --- a/Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - CommandLineParser.cs +++ b/Vrh.Log4Pro.MaintenanceConsole/ConsoleFunction - CommandLineParser.cs @@ -308,6 +308,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole.CommandLineParserNS public static class ExecuteScript{ public const string KEY = "EXE"; } public static class CreateLoginAndUser{ public const string KEY = "CRU"; } public static class AddUserForLogin{ public const string KEY = "CRA"; } + public static class CreateLastUpdatedTrigger{ public const string KEY = "TRA"; } + public static class RemoveLastUpdatedTrigger{ public const string KEY = "TRD"; } } } diff --git a/Vrh.Log4Pro.MaintenanceConsole/Manager - SQLDataBaseManager.cs b/Vrh.Log4Pro.MaintenanceConsole/Manager - SQLDataBaseManager.cs index af0eb56..69ac017 100644 --- a/Vrh.Log4Pro.MaintenanceConsole/Manager - SQLDataBaseManager.cs +++ b/Vrh.Log4Pro.MaintenanceConsole/Manager - SQLDataBaseManager.cs @@ -53,6 +53,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole.SQLDataBaseManagerNS .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.ExecuteScript.KEY, "Execute script", ExecuteScript, ep)) .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.CreateLoginAndUser.KEY, "Create Server login and database user", CreteLoginAndAddToDB, ep)) .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.AddUserForLogin.KEY, "Add database user to an existing Login", AddExistingLoginToDB, ep)) + .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.CreateLastUpdatedTrigger.KEY, "Add LastUpdated trigger to a datatable column", CreateLastUpdatedTrigger, ep)) + .AddMenuItem(new Menu.Item(CLP.Module.SQLDataBaseManager.Function.RemoveLastUpdatedTrigger.KEY, "Add LastUpdated trigger to a datatable column", RemoveLastUpdatedTrigger, ep)) .SetSelectionMode(Menu.SelectionMode.Single) .SetMenuHeaderDisplayer(DataBaseListDisplayer); menufunctions.ExecuteMenu(functionkey); @@ -225,6 +227,144 @@ namespace Vrh.Log4Pro.MaintenanceConsole.SQLDataBaseManagerNS } private static object CreteLoginAndAddToDB(object parameter, object o) { return _CreteLoginAndUser(parameter, o, true); } private static object AddExistingLoginToDB(object parameter, object o) { return _CreteLoginAndUser(parameter, o, false); } + + private static object CreateLastUpdatedTrigger(object parameter, object o) { return _RemoveAndCreateLastUpdatedTrigger(parameter, o, false); } + private static object RemoveLastUpdatedTrigger(object parameter, object o) { return _RemoveAndCreateLastUpdatedTrigger(parameter, o, true); } + #region script texts for _RemoveAndCreateLastUpdatedTrigger + const string Header_Script = + @"USE [{DBNAME}] + +SET ANSI_NULLS ON +GO + +SET QUOTED_IDENTIFIER ON +GO +"; + const string CreateLastUpdatedColumn_Script = Header_Script + + @"ALTER TABLE [{SCHEMA}].[{TABLE}] + ADD [{COLUMN}] DATETIME +GO +"; + const string CreateLastUpdatedTrigger_Script = Header_Script + + @"CREATE TRIGGER [{SCHEMA}].[{TRIGGER}] + ON [{SCHEMA}].[{TABLE}] + AFTER INSERT, UPDATE +AS +BEGIN + SET NOCOUNT ON; + + UPDATE [{SCHEMA}].[{TABLE}] SET [{COLUMN}] = GETDATE() + FROM [{SCHEMA}].[{TABLE}] pper + INNER JOIN inserted i + ON pper.ID = i.ID; +END +GO +"; + const string EnableLastUpdatedTrigger_Script = Header_Script + + @"ALTER TABLE [{SCHEMA}].[{TABLE}] ENABLE TRIGGER [{TRIGGER}] +GO +"; + + const string RemoveLastUpdatedColumn_Script = Header_Script + + @"ALTER TABLE [{SCHEMA}].[{TABLE}] DROP COLUMN [{COLUMN}] +GO +"; + + const string RemoveLastUpdatedTrigger_Script = + @"USE [{DBNAME}] +DROP TRIGGER [{SCHEMA}].[{TRIGGER}]; +GO +"; + #endregion script texts for _RemoveAndCreateLastUpdatedTrigger + private static object _RemoveAndCreateLastUpdatedTrigger(object parameter, object o,bool removeonly) + { + try + { + var config = (parameter as Menu.ExecutorParameter).GetConfig(); + var args = (parameter as Menu.ExecutorParameter).Args; + var selectedtaskindexes = CommandLine.GetCommandLineArgument(args, CLP.Module.ScheduledTaskManager.Function.CMD_TASKS); + var menufolders = DisplaySQLDataBaseMenu(config, $"Select the SQL database(s) to manage with function '{nameof(CreateLastUpdatedTrigger)}'!", silent: true); + Menu.Selection sr = menufolders.Select(selectedtaskindexes); + if (sr.Result == Menu.SelectionResult.Exit) { return o; } + else if (sr.Result == Menu.SelectionResult.None) { return o; } + else if (sr.Result == Menu.SelectionResult.Error) { return o; } + else if (sr.Result == Menu.SelectionResult.Ok) { } + else { } + var p = sr.SelectedParameterList.FirstOrDefault(); + if (p == null) { return o; } + SQLDataBase sqld = p.Parameters as SQLDataBase; + + getparameters:; + string action = removeonly ? "REMOVING" : "CREATING"; + ColorConsole.WriteLine(prefix: $"Enter the parameters for {action} LastUpdated trigger.", bracket: "", text: "", f: ConsoleColor.Yellow); + ColorConsole.WriteLine(prefix: $" Format#1:", bracket: "()", text: "DBNAME,TABLEWITHSCHEMA,COLUMN", f: ConsoleColor.Yellow); + ColorConsole.WriteLine(prefix: $" Format#2:", bracket: "()", text: "TABLEWITHSCHEMA,COLUMN", f: ConsoleColor.Yellow); + ColorConsole.WriteLine(prefix: $" Format#3:", bracket: "()", text: "TABLEWITHSCHEMA", f: ConsoleColor.Yellow); + ColorConsole.WriteLine(prefix: " ", text: "DBNAME", bracket: "", suffix: $": name of the database of the trigger; default is {sqld.DBName} (example:LearALM2)"); + ColorConsole.WriteLine(prefix: " ", text: "[SCHEMA.]TABLE", bracket: "", suffix: $": name of the table (with schema) of the trigger; default dbo (example:ALM.ProductionPeriods)"); + ColorConsole.WriteLine(prefix: " ", text: "COLUMN", bracket: "", suffix: $": name of the column (will be created) of the trigger; default is LastUpdated (example:LastUpdated)"); + + var createtriggerparameters = ColorConsole.ReadLine($"EX=exit.", ConsoleColor.Yellow, suffix: " --> "); + if (createtriggerparameters.ToUpper() == "EX") { return o; } + if (string.IsNullOrWhiteSpace(createtriggerparameters)) { goto getparameters; } + var optionList = createtriggerparameters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + + string db = ""; + string tablewithschema = ""; + string column = ""; + if (optionList.Length == 1) { tablewithschema = optionList[0]; } + else if (optionList.Length == 2) { tablewithschema = optionList[0]; column = optionList[1]; } + else if (optionList.Length == 3) { db = optionList[0]; tablewithschema = optionList[1]; column = optionList[2]; } + else /*if (optionList.Length > 3)*/ { ColorConsole.WriteLine("ERROR! No more parameters required beside DBNAME,TABLEWITHSCHEMA and COLUMN!", ConsoleColor.Red); goto getparameters; } + + if (string.IsNullOrWhiteSpace(db)) db = sqld.DBName; + if (string.IsNullOrWhiteSpace(column)) column = "LastUpdated"; + + if (string.IsNullOrWhiteSpace(db)) { ColorConsole.WriteLine("ERROR! DATABASE can not be empty!", ConsoleColor.Red); goto getparameters; } + if (string.IsNullOrWhiteSpace(tablewithschema)) { ColorConsole.WriteLine("ERROR! TABLEWITHSCHEMA can not be empty!", ConsoleColor.Red); goto getparameters; } + var tablewithschemasplitted = tablewithschema.Split('.'); + if (tablewithschemasplitted.Length != 1 && tablewithschemasplitted.Length != 2) { ColorConsole.WriteLine("ERROR! TABLEWITHSCHEMA incorrect!", ConsoleColor.Red); goto getparameters; } + if (string.IsNullOrWhiteSpace(column)) { ColorConsole.WriteLine("ERROR! COLUMN can not be empty!", ConsoleColor.Red); goto getparameters; } + + string schema = ""; + string table = tablewithschema; + if (tablewithschemasplitted.Length == 2) { schema = tablewithschemasplitted[0]; table = tablewithschemasplitted[1]; } + string triggername = $"TRG_LASTUPDATETS_{db}_{schema}_{table}_{column}"; + string parameters = $"DBNAME={db};SCHEMA={schema};TABLE={table};COLUMN={column};TRIGGER={triggername};"; + string ssScriptText = null; + + if (!Tools.ResolveArguments(parameters, RemoveLastUpdatedTrigger_Script, out ssScriptText)) { throw new ApplicationException(); } + try {SQLDataBaseManagerCore.ExecuteSQLScript(sqld.SQLCS, ssScriptText, 5000, null); } + catch (Exception e) {ColorConsole.WriteLine(e.Message, ConsoleColor.Yellow);} + if (!Tools.ResolveArguments(parameters, RemoveLastUpdatedColumn_Script, out ssScriptText)) { throw new ApplicationException(); } + try {SQLDataBaseManagerCore.ExecuteSQLScript(sqld.SQLCS, ssScriptText, 5000, null);} + catch (Exception e) { ColorConsole.WriteLine(e.Message, ConsoleColor.Yellow); } + + if (!removeonly) + { + if (!Tools.ResolveArguments(parameters, CreateLastUpdatedColumn_Script, out ssScriptText)) { throw new ApplicationException(); } + SQLDataBaseManagerCore.ExecuteSQLScript(sqld.SQLCS, ssScriptText, 5000, null); + + if (!Tools.ResolveArguments(parameters, CreateLastUpdatedTrigger_Script, out ssScriptText)) { throw new ApplicationException(); } + SQLDataBaseManagerCore.ExecuteSQLScript(sqld.SQLCS, ssScriptText, 5000, null); + + if (!Tools.ResolveArguments(parameters, EnableLastUpdatedTrigger_Script, out ssScriptText)) { throw new ApplicationException(); } + SQLDataBaseManagerCore.ExecuteSQLScript(sqld.SQLCS, ssScriptText, 5000, null); + } + ColorConsole.WriteLine($"SUCCESS! {action} trigger to store LastUpdate TimeStamp: Database={db},Table={schema}.{table},Column={column}", ConsoleColor.Green); + return o; + } + catch (ApplicationException e) + { + ColorConsole.WriteLine("FATAL ERROR! in script parameter substitution!", ConsoleColor.Red); + return o; + } + catch (Exception e) + { + ColorConsole.WriteLine("FATAL ERROR! "+e.Message, ConsoleColor.Red); + return o; + } + } private static object _CreteLoginAndUser(object parameter, object o,bool createlogin) { const string COMMA = ","; @@ -971,7 +1111,7 @@ namespace Vrh.Log4Pro.MaintenanceConsole.SQLDataBaseManagerNS } sqlc.Close(); - if (DataSet != null && DataSet.Tables != null) + try { var firstreturnedtable = DataSet.Tables[0]; var firstreturnedrow = firstreturnedtable.Rows[0]; @@ -981,7 +1121,8 @@ namespace Vrh.Log4Pro.MaintenanceConsole.SQLDataBaseManagerNS var rm = Convert.ToString(secondreturnedvalue); return new ReturnInfoJSON() { ReturnValue = rv, ReturnMessage = rm, }; } - else { return new ReturnInfoJSON() { ReturnValue = 0, ReturnMessage = null, }; } + catch { } + return new ReturnInfoJSON() { ReturnValue = 0, ReturnMessage = null, }; } /// diff --git a/Vrh.Log4Pro.MaintenanceConsole/Properties/AssemblyInfo.cs b/Vrh.Log4Pro.MaintenanceConsole/Properties/AssemblyInfo.cs index 57fbe46..b78e5f7 100644 --- a/Vrh.Log4Pro.MaintenanceConsole/Properties/AssemblyInfo.cs +++ b/Vrh.Log4Pro.MaintenanceConsole/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.24.0.0")] -[assembly: AssemblyFileVersion("1.24.0.0")] +[assembly: AssemblyVersion("1.25.0.0")] +[assembly: AssemblyFileVersion("1.25.0.0")] -- libgit2 0.21.2