diff --git a/SaxoniteCoreUnitTests/SaxoniteCoreUnitTests.csproj b/SaxoniteCoreUnitTests/SaxoniteCoreUnitTests.csproj index b77ebe3..7b35dbf 100644 --- a/SaxoniteCoreUnitTests/SaxoniteCoreUnitTests.csproj +++ b/SaxoniteCoreUnitTests/SaxoniteCoreUnitTests.csproj @@ -9,11 +9,11 @@ - + - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/SaxoniteCoreUnitTestsOnline/SaxoniteCoreUnitTestsOnline.csproj b/SaxoniteCoreUnitTestsOnline/SaxoniteCoreUnitTestsOnline.csproj index 8f9798f..8ced539 100644 --- a/SaxoniteCoreUnitTestsOnline/SaxoniteCoreUnitTestsOnline.csproj +++ b/SaxoniteCoreUnitTestsOnline/SaxoniteCoreUnitTestsOnline.csproj @@ -9,11 +9,11 @@ - + - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/SaxoniteCoreWeb/Base/App/SaxAppConfig.cs b/SaxoniteCoreWeb/Base/App/SaxAppConfig.cs index a0d3d2b..b006219 100644 --- a/SaxoniteCoreWeb/Base/App/SaxAppConfig.cs +++ b/SaxoniteCoreWeb/Base/App/SaxAppConfig.cs @@ -100,6 +100,7 @@ namespace Saxonite.Net.Core.Web.Base.App { public Dictionary Databases { get; } = new Dictionary(); public DatabaseConfig Core { get { return Databases.GetValue(Sax.Database.Core, new DatabaseConfig()); } } + public DatabaseConfig Reference { get { return Databases.GetValue(Sax.Database.Reference, new DatabaseConfig()); } } public DatabaseConfig Support { get { return Databases.GetValue(Sax.Database.Support, new DatabaseConfig()); } } } public DatabasesConfig Databases { get; } = new DatabasesConfig(); diff --git a/SaxoniteCoreWeb/Base/App/SaxApplication_Web.cs b/SaxoniteCoreWeb/Base/App/SaxApplication_Web.cs index 8c4d160..4bfd892 100644 --- a/SaxoniteCoreWeb/Base/App/SaxApplication_Web.cs +++ b/SaxoniteCoreWeb/Base/App/SaxApplication_Web.cs @@ -1,4 +1,6 @@ -using Microsoft.Extensions.Configuration; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Sarand.Net.Standard.Base.App; using Sarand.Net.Standard.Base.Core; using Sarand.Net.Standard.Base.Dbas; @@ -10,8 +12,10 @@ using Sarand.Net.Standard.Dbas.Data; using Saxonite.Net.Core.Web.Base.Consoles; using Saxonite.Net.Standard.Base.App; using Saxonite.Net.Standard.Base.Consoles; +using Saxonite.Net.Standard.Base.Helpers; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; @@ -34,15 +38,17 @@ namespace Saxonite.Net.Core.Web.Base.App public SaxSessionContext_Web SessionContext { get; } public Dictionary Databases { get; } = new Dictionary(); public ISacsDatabase CoreDatabase { get { return Databases.GetValue(Sax.Database.Core, null); } } + public ISacsDatabase ReferenceDatabase { get { return Databases.GetValue(Sax.Database.Reference, null); } } public ISacsDatabase SupportDatabase { get { return Databases.GetValue(Sax.Database.Support, null); } } } //------------------------------------------------------------------- // Protected construction. - protected SaxApplication_Web() + protected SaxApplication_Web(Sax.Application applicationType) { WebApp = this; System_Web = new SaxSystem_Web(); + ApplicationType = applicationType; } protected override void Dispose(bool disposing) { @@ -57,6 +63,7 @@ namespace Saxonite.Net.Core.Web.Base.App //------------------------------------------------------------------- // Globals. public static SaxApplication_Web WebApp { get; private set; } + public Sax.Application ApplicationType { get; } public override SaxSystem System { get { return System_Web; } } public SaxSystem_Web System_Web { get; private set; } // Application instance. @@ -72,7 +79,51 @@ namespace Saxonite.Net.Core.Web.Base.App public override IDatabaseInfo CreateDbInfo(SaxSessionContext sessionContext, Sax.Database databaseType) { return new DbDataItem.DatabaseInfo(GetDatabase(sessionContext, databaseType)); } // Configuration. public IConfiguration Configuration { get; protected set; } - public IConfiguration SaxConfiguration { get; protected set; } + public IConfiguration SaxConfiguration { get; private set; } + + //------------------------------------------------------------------- + protected void InitEnvironment(IWebHostEnvironment env, String logFilenamePrefix) + { + Development = env.IsDevelopment(); + environmentName = env.EnvironmentName; + SaxConfiguration = LoadApplicationConfiguration(); + + // Configure logging. + SaLogger.LogFilenamePrefix = logFilenamePrefix; + SaLogger.IncludeHostInFileMessage = false; + SaLogger.IncludeUserInFileMessage = false; + + //Messages.Add($"Host: {SaxSystem.ComputerName}"); + //Messages.Add($"Config file: appsettings.machine.{SaxSystem.ComputerName}.json"); + } + + //------------------------------------------------------------------- + // Application configuration. + private IConfiguration LoadApplicationConfiguration() + { + // Load configuration resource files. + // Later files override values from previous. + var builder = + new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddEnvironmentVariables(); + + // Saxonite Web configuration - shared by all applications. + Stream configStream = SaxResourceHelper.GetResourceStream("appsettings.json", "Config"); + if (configStream != null) builder.AddJsonStream(configStream); + configStream = SaxResourceHelper.GetResourceStream($"appsettings.{environmentName}.json", "Config"); + if (configStream != null) builder.AddJsonStream(configStream); + configStream = SaxResourceHelper.GetResourceStream($"appsettings.machine.{SaxSystem.ComputerName}.json", "Config"); + if (configStream != null) builder.AddJsonStream(configStream); + + // Application specific configuration. + builder + .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) + .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: false) + .AddJsonFile($"appsettings.machine.{SaxSystem.ComputerName}.json", optional: true, reloadOnChange: false); + + return builder.Build(); + } //------------------------------------------------------------------- // Database configuration. @@ -103,13 +154,15 @@ namespace Saxonite.Net.Core.Web.Base.App applicationParams.Add("Environment", EnvironmentName); if (!StringUtil.IsBlank(AppConfig.Databases.Core.Location)) applicationParams.Add("Database - Core", AppConfig.Databases.Core.Location); + if (!StringUtil.IsBlank(AppConfig.Databases.Reference.Location)) + applicationParams.Add("Database - Reference", AppConfig.Databases.Reference.Location); if (!StringUtil.IsBlank(AppConfig.Databases.Support.Location)) applicationParams.Add("Database - Support", AppConfig.Databases.Support.Location); applicationParams.Add("Application root", SaxSystem.ApplicationFolder); if (!StringUtil.IsEmpty(AppConfig.Documents.RootFolder)) applicationParams.Add("Documents root", AppConfig.Documents.RootFolder); applicationParams.Add("Email context", AppConfig.Email.Context + (!StringUtil.IsEmpty(EmailConfig.SMTP.Server) ? " [" + EmailConfig.SMTP.Server + "]" : "")); - SaLogger.Info(fn + " Application start." + applicationParams.Select(item => StringUtil.PadRight(item.Item1 + ":", 20, ' ') + item.Item2).Concat("", "\n\t"), true); + SaLogger.Info(fn + " Application start." + applicationParams.Select(item => StringUtil.PadRight(item.Item1 + ":", 23, ' ') + " " + item.Item2).Concat("", "\n\t"), true); if (StringUtil.IsEmpty(EmailConfig.SMTP.Server) || StringUtil.IsEmpty(EmailConfig.Message.AddressFrom)) SaLogger.Warn(fn + " Incomplete email configuration.", true); } diff --git a/SaxoniteCoreWeb/Base/App/SaxStartup.cs b/SaxoniteCoreWeb/Base/App/SaxStartup.cs index 0f2475e..11ef740 100644 --- a/SaxoniteCoreWeb/Base/App/SaxStartup.cs +++ b/SaxoniteCoreWeb/Base/App/SaxStartup.cs @@ -63,12 +63,13 @@ namespace Saxonite.Net.Core.Web.Base.App // Authentication service. // Required to handle 'Forbidden' responses etc. config.services - .AddAuthentication(options => { + .AddAuthentication(options => + { options.DefaultAuthenticateScheme = "forbidScheme"; options.DefaultForbidScheme = "forbidScheme"; options.AddScheme("forbidScheme", "Handle Forbidden"); - }); - + }); + // Added to support memory caching of sessions. config.services.AddMemoryCache(); //config.services.AddDistributedMemoryCache(); - for multiple web servers. @@ -91,11 +92,14 @@ namespace Saxonite.Net.Core.Web.Base.App // Modify pages during debug. #if DEBUG if (SaxSystem.DebugMode) + { // If the following line throws an error such as: // 'imvcbuilder' does not contain a definition for 'addrazorruntimecompilation' // Revert the NuGet Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package // to a previous version and then reinstal the latest version. config.services.AddRazorPages().AddRazorRuntimeCompilation(); + //config.services.AddControllersWithViews().AddRazorRuntimeCompilation(); + } #endif config.services.AddMvc diff --git a/SaxoniteCoreWeb/Base/Consoles/SaxHostedServiceConsole_Web.cs b/SaxoniteCoreWeb/Base/Consoles/SaxHostedServiceConsole_Web.cs new file mode 100644 index 0000000..3bfdd2c --- /dev/null +++ b/SaxoniteCoreWeb/Base/Consoles/SaxHostedServiceConsole_Web.cs @@ -0,0 +1,98 @@ +using Microsoft.Extensions.Hosting; +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Tasks; +using Sarand.Net.Standard.Base.Utils; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Saxonite.Net.Core.Web.Base.Consoles +{ + //======================================================================= + public abstract class SaxHostedServiceConsole_Web : SacsDisposable, IHostedService + { + //------------------------------------------------------------------- + // Definitions. + + //------------------------------------------------------------------- + // Data members. + private Timer processTimer; + + //------------------------------------------------------------------- + // Construction. + protected SaxHostedServiceConsole_Web () + { + } + + //------------------------------------------------------------------- + // Clean-up. + protected override void Dispose(bool disposing) + { + DisposeTimer(); + if (ProcessTaskData != null) ProcessTaskData.Dispose(); + ProcessTaskData = null; + } + + private void DisposeTimer() + { + if (processTimer != null) processTimer.Dispose(); + processTimer = null; + } + + //------------------------------------------------------------------- + // Properties. + + // Task data - allows cancellation to be triggered for executing processes, eg. when application is stopping. + protected SacsTaskData ProcessTaskData { get; private set; } + + //------------------------------------------------------------------- + + /// + /// Periodic processing to execute application processes as required. + /// + protected abstract void DoWork(object state); + + //------------------------------------------------------------------- + + /// + /// Triggered when the application host is ready to start the service. + /// + /// Indicates that the start process has been aborted. + /// + public virtual Task StartAsync(CancellationToken cancellationToken) + { + SaLogger.Info($"{SysUtil.Fn} Timed Background Service started."); + + // Initialise the background task cancellation token. + ProcessTaskData = new SacsTaskData(); + + // Initialise the scheduled task timer. + processTimer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(1)); + return Task.CompletedTask; + } + + /// + /// Triggered when the application host is performing a graceful shutdown. + /// + /// Indicates that the shutdown process should no longer be graceful. + /// + public virtual Task StopAsync(CancellationToken cancellationToken) + { + SaLogger.Info($"{SysUtil.Fn} Timed Background Service stopped."); + + // Signal cancellation to the background tasks. + ProcessTaskData.TriggerCancellation(); + + // Stop the timer. + processTimer?.Change(Timeout.Infinite, 0); + return Task.CompletedTask; + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteCoreWeb/Base/Controllers/SaxController_Base.cs b/SaxoniteCoreWeb/Base/Controllers/SaxController_Base.cs index b6bfa5f..059357b 100644 --- a/SaxoniteCoreWeb/Base/Controllers/SaxController_Base.cs +++ b/SaxoniteCoreWeb/Base/Controllers/SaxController_Base.cs @@ -21,6 +21,7 @@ using Saxonite.Net.Standard.Base.App; using Saxonite.Net.Standard.Base.Bus; using Saxonite.Net.Standard.Base.Consoles; using Saxonite.Net.Standard.Base.Mgr; +using Saxonite.Net.Standard.Base.Mgr.Reference; using Saxonite.Net.Standard.Base.Mgr.Support; using System; using System.Collections.Generic; @@ -83,6 +84,7 @@ namespace Saxonite.Net.Core.Web.Base.Controllers public SaxAccountMgr AccountMgr { get { return Internals.AccountMgr; } } public SaxActivityMgr ActivityMgr { get { return Internals.ActivityMgr; } } public SaxItemDataMgr ItemDataMgr { get { return Internals.ItemDataMgr; } } + public SaxReferenceGolfMgr ReferenceGolfMgr { get { return Internals.ReferenceGolfMgr; } } public SaxSupportMgr SupportMgr { get { return Internals.SupportMgr; } } // System codes. public List DataItemTypeCodes { get { return Internals.DataItemTypeCodes; } } diff --git a/SaxoniteCoreWeb/Base/Middleware/SaxModelBinder.cs b/SaxoniteCoreWeb/Base/Middleware/SaxModelBinder.cs index b77af81..5361961 100644 --- a/SaxoniteCoreWeb/Base/Middleware/SaxModelBinder.cs +++ b/SaxoniteCoreWeb/Base/Middleware/SaxModelBinder.cs @@ -10,6 +10,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; +using static Saxonite.Net.Standard.Base.App.Sax.Config.Security; namespace Saxonite.Net.Core.Web.Base.Middleware { @@ -57,10 +58,12 @@ namespace Saxonite.Net.Core.Web.Base.Middleware { //if (SaxSystem.DebugMode) Logger.Debug(fn + " Form property " + modelName + ": '" + result.Model.ToString() + "."); object originalValue = result.Model; - // Exclude properties that retain leading/trailing whitespace. - if (result.Model is string) + // Anything that looks like a password will be left as is. + bool password = modelName.ContainsCI("Password"); + // Exclude properties that retain leading/trailing whitespace. + if (result.Model is string) { - if (!modelName.ContainsCI("Password")) + if (!password) { string value = result.Model as string; @@ -92,10 +95,12 @@ namespace Saxonite.Net.Core.Web.Base.Middleware } // Log property details. if (result.Model != null && SaxSystem.DebugMode && - // Ignore items that correspond with objects in the model rather than values. - !result.Model.ToString().Equals(result.Model.GetType().FullName) && - // Ignore form files. - !result.Model.ToString().ContainsCI("Microsoft.AspNetCore.Http.IFormFile")) + // Ignore passwords. + !password && + // Ignore items that correspond with objects in the model rather than values. + !result.Model.ToString().Equals(result.Model.GetType().FullName) && + // Ignore form files. + !result.Model.ToString().ContainsCI("Microsoft.AspNetCore.Http.IFormFile")) SaLogger.Debug(SysUtil.Fn + " Form property " + modelName + ": '" + result.Model.ToString() + "'." + (originalValue != null && !originalValue.Equals(result.Model) ? " Original value: '" + originalValue.ToString() + "'" : "")); base.SetProperty(bindingContext, modelName, propertyMetadata, result); } diff --git a/SaxoniteCoreWeb/Base/Models/SaxModel_Base.cs b/SaxoniteCoreWeb/Base/Models/SaxModel_Base.cs index 69f5635..a6af467 100644 --- a/SaxoniteCoreWeb/Base/Models/SaxModel_Base.cs +++ b/SaxoniteCoreWeb/Base/Models/SaxModel_Base.cs @@ -14,6 +14,7 @@ using Saxonite.Net.Standard.Base.App; using Saxonite.Net.Standard.Base.Bus; using Saxonite.Net.Standard.Base.Consoles; using Saxonite.Net.Standard.Base.Mgr; +using Saxonite.Net.Standard.Base.Mgr.Reference; using Saxonite.Net.Standard.Base.Mgr.Support; using System; using System.Collections.Generic; @@ -67,6 +68,7 @@ namespace Saxonite.Net.Core.Web.Base.Models public SaxAccountMgr AccountMgr { get { return Internals.AccountMgr; } } public SaxActivityMgr ActivityMgr { get { return Internals.ActivityMgr; } } public SaxItemDataMgr ItemDataMgr { get { return Internals.ItemDataMgr; } } + public SaxReferenceGolfMgr ReferenceGolfMgr { get { return Internals.ReferenceGolfMgr; } } public SaxSupportMgr SupportMgr { get { return Internals.SupportMgr; } } // System codes. public List DataItemTypeCodes { get { return Internals.DataItemTypeCodes; } } diff --git a/SaxoniteCoreWeb/Base/Procs/SaxGolfUsgaDataLookup-ScheduledUsgaDataLookup.cs b/SaxoniteCoreWeb/Base/Procs/SaxGolfUsgaDataLookup-ScheduledUsgaDataLookup.cs new file mode 100644 index 0000000..5771ea3 --- /dev/null +++ b/SaxoniteCoreWeb/Base/Procs/SaxGolfUsgaDataLookup-ScheduledUsgaDataLookup.cs @@ -0,0 +1,225 @@ +using DocumentFormat.OpenXml.Drawing.Diagrams; +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Helpers; +using Sarand.Net.Standard.Base.Tasks; +using Sarand.Net.Standard.Base.Utils; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Saxonite.Net.Core.Web.Base.Procs +{ + //======================================================================= + partial class SaxGolfUsgaDataLookup + { + //------------------------------------------------------------------- + private class ScheduledUsgaDataLookupControlData + { + public DateTime CountriesLastLookedUp { get; set; } = DateTime.Now; + } + private static ScheduledUsgaDataLookupControlData usgaDataLookupControl { get; } = new ScheduledUsgaDataLookupControlData(); + + /// + /// Determine which USGA data population process to run. + /// - Method is invoked periodically (every 20 mins) by the Admin Hosted Service Console. + /// - 1. Populate countries if not already done or not done for a while (eg. 24 hours). + /// - 2. Populate provinces for a Country that has none or occasionally to refresh one that has. + /// - 3. Populate Courses for a Province that has none or occasionally to refresh one that has. + /// - 4. Populate Courses for a Province that has none or occasionally to refresh one that has. + /// + public static void ExecuteScheduledUsgaDataLookup(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo, SacsTaskData taskData) + { + SaLogger.Debug($"{SysUtil.Fn}"); + + using (DisposableCollection disposableItems = new DisposableCollection()) + { + SaxInternals internals = new SaxInternals(sessionContext); + disposableItems.Add(internals); + + // Configure process. + SaxGolfUsgaDataLookup.Config courseLookupConfig = new SaxGolfUsgaDataLookup.Config(sessionContext, dbUpdateInfo); + SaxGolfUsgaDataLookup usgaDataLookup = new SaxGolfUsgaDataLookup(courseLookupConfig); + + if (taskData.IsCancellationRequested) return; + + // Determine which process to run. + // Check USGA country population. + List usgaCountries = internals.ReferenceGolfMgr.GetUsgaCountryList(new SaxGolfUsgaCountry.Params()); + if (!usgaCountries.Any() || (DateTime.Now - usgaDataLookupControl.CountriesLastLookedUp).TotalHours > MathUtil.Constrain(Sax.Config.Admin.Processes.Scheduled.UsgaGolfDataLookup.HoursBetweenCountryLookup, 1, 24 * 7)) + { + // No countries currently found or long enough since last lookup. + // Lookup USGA countries. + List countriesData = usgaDataLookup.LookupUsgaCountries(); + SaLogger.Info($"{SysUtil.Fn} USGA Countries populated: {countriesData.Count}.", true); + usgaDataLookupControl.CountriesLastLookedUp = DateTime.Now; + return; + } + if (taskData.IsCancellationRequested) return; + + // Population of Countries without Provinces is only allowed occasionally to avoid delaying population of lower data. + bool populateCountryWithNoProvinces = SacsRandomHelper.GetInt32(1, 7) == 1; + + // Check USGA Country Province population. + List usgaCountriesWithProvinces = new List(); + List usgaCountriesWithNoProvinces = new List(); + foreach (SaxGolfUsgaCountry usgaCountry in usgaCountries.OrderBy(_ => SacsRandomHelper.GetInt32(Int32.MaxValue))) + { + SaxGolfUsgaProvince.Params prmUsgaProvince = new SaxGolfUsgaProvince.Params(); + prmUsgaProvince.CountryIdsIncluded.Add(usgaCountry.Id); + if (internals.ReferenceGolfMgr.GetUsgaProvinceCount(prmUsgaProvince) < 1) + { + usgaCountriesWithNoProvinces.Add(usgaCountry); + if (populateCountryWithNoProvinces) + { + // Country has no Provinces - look them up. + List provincesData = usgaDataLookup.LookupUsgaProvincesForCountry(usgaCountry.CountryCode); + SaLogger.Info($"{SysUtil.Fn} USGA Provinces populated for {usgaCountry.CountryCode} {usgaCountry.CountryName}: {provincesData.Count}.", true); + return; + } + } + else + { + // Country has Provinces. + usgaCountriesWithProvinces.Add(usgaCountry); + } + if (taskData.IsCancellationRequested) return; + } + + if (usgaCountriesWithProvinces.Any()) + { + // Pick the first (randomly sorted) Country. + SaxGolfUsgaCountry usgaCountry = usgaCountriesWithProvinces[0]; + + // One of the Countries with Provinces can have its list of provinces refreshed occasionally. + bool refreshCountryWithProvinces = SacsRandomHelper.GetInt32(1, 17) == 1; + if (refreshCountryWithProvinces) + { + SaxGolfUsgaProvince.Params prmUsgaProvince = new SaxGolfUsgaProvince.Params(); + prmUsgaProvince.CountryIdsIncluded.Add(usgaCountry.Id); + List usgaProvinces = internals.ReferenceGolfMgr.GetUsgaProvinceList(prmUsgaProvince).OrderBy(_ => SacsRandomHelper.GetInt32(Int32.MaxValue)).ToList(); + if (usgaProvinces.Any()) + { + // Refresh Country Provinces. + List provincesData = usgaDataLookup.LookupUsgaProvincesForCountry(usgaCountry.CountryCode); + SaLogger.Info($"{SysUtil.Fn} USGA Provinces refreshed for {usgaCountry.CountryCode} {usgaCountry.CountryName}: {provincesData.Count}.", true); + return; + } + } + } + + if (usgaCountriesWithProvinces.Any()) + { + // Pick the first (randomly sorted) Country. + SaxGolfUsgaCountry usgaCountry = usgaCountriesWithProvinces[0]; + + // Population of Courses for Province without Facilities is allowed occasionally. + bool populateProvinceWithNoFacilities = SacsRandomHelper.GetInt32(1, 7) == 1; + + // Check USGA Province Course population. + List usgaProvincesWithFacilities = new List(); + List usgaProvincesWithNoFacilities = new List(); + SaxGolfUsgaProvince.Params prmUsgaProvince = new SaxGolfUsgaProvince.Params(); + prmUsgaProvince.CountryIdsIncluded.Add(usgaCountry.Id); + foreach (SaxGolfUsgaProvince usgaProvince in internals.ReferenceGolfMgr.GetUsgaProvinceList(prmUsgaProvince).OrderBy(_ => SacsRandomHelper.GetInt32(Int32.MaxValue))) + { + SaxGolfUsgaFacility.Params prmUsgaFacility = new SaxGolfUsgaFacility.Params(); + prmUsgaFacility.ProvinceIdsIncluded.Add(usgaProvince.Id); + if (internals.ReferenceGolfMgr.GetUsgaFacilityCount(prmUsgaFacility) < 1) + { + usgaProvincesWithNoFacilities.Add(usgaProvince); + if (populateProvinceWithNoFacilities) + { + // Province has no Facilities - look up the courses. + List coursesData = usgaDataLookup.LookupUsgaCoursesForCountryAndProvince(usgaCountry.CountryCode, usgaProvince.ProvinceCode); + SaLogger.Info($"{SysUtil.Fn} USGA Courses populated for {usgaCountry.CountryCode} {usgaCountry.CountryName} - {usgaProvince.ProvinceCode} {usgaProvince.ProvinceName}: {coursesData.Count}.", true); + return; + } + } + else + { + // Country has provinces. + usgaProvincesWithFacilities.Add(usgaProvince); + } + if (taskData.IsCancellationRequested) return; + } + + if (usgaProvincesWithFacilities.Any()) + { + // Pick the first (randomly sorted) province. + SaxGolfUsgaProvince usgaProvince = usgaProvincesWithFacilities[0]; + + // Population of Courses for Province with Facilities is allowed occasionally. + bool populateProvinceWithFacilities = SacsRandomHelper.GetInt32(1, 17) == 1; + if (populateProvinceWithFacilities) + { + // Refresh Courses for Province with Facilities. + List coursesData = usgaDataLookup.LookupUsgaCoursesForCountryAndProvince(usgaCountry.CountryCode, usgaProvince.ProvinceCode); + SaLogger.Info($"{SysUtil.Fn} USGA Courses refreshed for {usgaCountry.CountryCode} {usgaCountry.CountryName} - {usgaProvince.ProvinceCode} {usgaProvince.ProvinceName}: {coursesData.Count}.", true); + return; + } + + // Compile list of Courses for this province. + SaxGolfUsgaCourse.Params prmCourse = new SaxGolfUsgaCourse.Params(); + prmCourse.ProvinceIdsIncluded.Add(usgaProvince.Id); + List usgaCourses = internals.ReferenceGolfMgr.GetUsgaCourseList(prmCourse).OrderBy(_ => SacsRandomHelper.GetInt32(Int32.MaxValue)).ToList(); + List usgaCoursesWithMarkers = new List(); + foreach (SaxGolfUsgaCourse usgaCourse in usgaCourses) + { + SaxGolfUsgaMarker.Params prmMarker = new SaxGolfUsgaMarker.Params(); + prmMarker.CourseIdsIncluded.Add(usgaCourse.Id); + if (internals.ReferenceGolfMgr.GetUsgaMarkerCount(prmMarker) == 0) + { + // Populate Markers for first course without markers. + List markersData = usgaDataLookup.LookupUsgaMarkersForCourse(usgaCourse.CourseId); + SaLogger.Info($"{SysUtil.Fn} USGA Markers populated for {usgaCountry.CountryCode} {usgaCountry.CountryName} - {usgaProvince.ProvinceCode} {usgaProvince.ProvinceName} - {usgaCourse.Caption} [Id: {usgaCourse.CourseId}]: {markersData.Count}.", true); + return; + } + else usgaCoursesWithMarkers.Add(usgaCourse); + } + if (usgaCoursesWithMarkers.Any()) + { + // Populate Markers for first course with markers. + SaxGolfUsgaCourse usgaCourse = usgaCoursesWithMarkers[0]; + List markersData = usgaDataLookup.LookupUsgaMarkersForCourse(usgaCourse.CourseId); + SaLogger.Info($"{SysUtil.Fn} USGA Markers refreshed for {usgaCountry.CountryCode} {usgaCountry.CountryName} - {usgaProvince.ProvinceCode} {usgaProvince.ProvinceName} - {usgaCourse.Caption} [Id: {usgaCourse.CourseId}]: {markersData.Count}.", true); + return; + } + } + + // Fallback - populate Courses for Province. + bool allowFallbackCoursePopulation = true; + if (allowFallbackCoursePopulation) + { + SaxGolfUsgaProvince usgaProvince = usgaProvincesWithNoFacilities.Any() ? usgaProvincesWithNoFacilities[0] : usgaProvincesWithFacilities.Any() ? usgaProvincesWithFacilities[0] : null; + if (usgaCountry != null && usgaProvince != null && usgaCountry.Id.Equals(usgaProvince.CountryId)) + { + List coursesData = usgaDataLookup.LookupUsgaCoursesForCountryAndProvince(usgaCountry.CountryCode, usgaProvince.ProvinceCode); + SaLogger.Info($"{SysUtil.Fn} USGA Courses populated for {usgaCountry.CountryCode} {usgaCountry.CountryName} - {usgaProvince.ProvinceCode} {usgaProvince.ProvinceName}: {coursesData.Count}. [Fallback]", true); + return; + } + } + } + + // Fallback - populate provinces for country. + bool allowFallbackProvincePopulation = true; + if (allowFallbackProvincePopulation) + { + SaxGolfUsgaCountry usgaCountry = usgaCountriesWithNoProvinces.Any() ? usgaCountriesWithNoProvinces[0] : usgaCountriesWithProvinces.Any() ? usgaCountriesWithProvinces[0] : null; + if (usgaCountry != null) + { + List provincesData = usgaDataLookup.LookupUsgaProvincesForCountry(usgaCountry.CountryCode); + SaLogger.Info($"{SysUtil.Fn} USGA Provinces populated for {usgaCountry.CountryCode} {usgaCountry.CountryName}: {provincesData.Count}. [Fallback]", true); + return; + } + } + } + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteCoreWeb/Base/Procs/SaxGolfUsgaDataLookup.cs b/SaxoniteCoreWeb/Base/Procs/SaxGolfUsgaDataLookup.cs new file mode 100644 index 0000000..0d61543 --- /dev/null +++ b/SaxoniteCoreWeb/Base/Procs/SaxGolfUsgaDataLookup.cs @@ -0,0 +1,847 @@ +using DocumentFormat.OpenXml.InkML; +using HtmlAgilityPack; +using MailKit; +using Microsoft.Net.Http.Headers; +using Newtonsoft.Json.Linq; +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Helpers; +using Sarand.Net.Standard.Base.Net; +using Sarand.Net.Standard.Base.Utils; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Mgr.Reference; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using static Saxonite.Net.Core.Web.Base.Procs.SaxGolfUsgaDataLookup; + +namespace Saxonite.Net.Core.Web.Base.Procs +{ + //====================================================================== + // USGA course rating & slope database: https://ncrdb.usga.org/ + // https://ncrdb.usga.org/courseTeeInfo.aspx?CourseID=14758 + // Ref. https://zylalabs.com/blog/enhance-your-game-with-a-free-golf-api + public partial class SaxGolfUsgaDataLookup : SaxProcess_Web + { + //------------------------------------------------------------------- + // Definitions. + public new class Config : SaxProcess_Web.Config + { + public Config(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo) : base(sessionContext, dbUpdateInfo) + { } + } + + public class CountryProvinceCodes + { + public CountryProvinceCodes(String countryCode, String provinceCode) + { + this.CountryCode = StringUtil.OnBlank(countryCode); + this.ProvinceCode = StringUtil.OnBlank(provinceCode); + } + public string CountryCode { get; } + public string ProvinceCode { get; } + public override bool Equals(object obj) + { + return Equals(obj as CountryProvinceCodes); + } + public bool Equals(CountryProvinceCodes other) + { + return other != null && CountryCode == other.CountryCode && ProvinceCode == other.ProvinceCode; + } + public override int GetHashCode() + { + return HashCode.Combine(CountryCode, ProvinceCode); + } + public override string ToString() + { + return $"CountryProvinceCodes({CountryCode}, {ProvinceCode})"; + } + } + + public class CountryData + { + public string Code { get; set; } + public string Name { get; set; } + } + + public class ProvinceData + { + public string Code { get; set; } + public string Name { get; set; } + } + + public class CourseData + { + public string CourseId { get; set; } + public string LegacyCrpCourseId { get; set; } + public string Caption { get; set; } + public string CourseName { get; set; } + public string FullName { get; set; } + public string FacilityId { get; set; } + public string FacilityName { get; set; } + public string Address1 { get; set; } + public string Address2 { get; set; } + public string City { get; set; } + public string ProvinceCode { get; set; } + public string EntProvinceCode { get; set; } + public string Province { get; set; } + public string CountryCode { get; set; } + public string EntCountryCode { get; set; } + public string Country { get; set; } + public string Email { get; set; } + public string Telephone { get; set; } + public List Ratings { get; } = new List(); + } + + public class MarkerData + { + public MarkerData(SysId courseId, short holes, string holesCaption) + { + this.CourseId = courseId; + this.Holes = holes; + this.HolesCaption = holesCaption; + } + public SysId CourseId { get; } + public SysId MarkerId { get; set; } + public string Caption { get { return StringUtil.TrimWhitespace(StringUtil.OnBlank(Tee) + " " + StringUtil.OnBlank(HolesCaption) + " " + StringUtil.OnBlank(Gender)); } } + public short Holes { get; } + public string HolesCaption { get; } + public string Tee { get; set; } + public string Gender { get; set; } + public short SlopeRating { get; set; } + public short Par { get; set; } + public decimal CourseRating { get; set; } + public decimal BogeyRating { get; set; } + public short Length { get; set; } + public bool IsValid() + { + if (!SysId.IsValid(CourseId)) return false; + if (!SysId.IsValid(MarkerId)) return false; + if (Holes < 1) return false; + if (StringUtil.IsBlank(Tee)) return false; + if (StringUtil.IsBlank(Gender)) return false; + if (SlopeRating == 0) return false; + if (Par == 0) return false; + if (CourseRating == 0) return false; + return true; + } + } + + //------------------------------------------------------------------- + // Data members. + private Config config; + + //------------------------------------------------------------------- + // Construction. + public SaxGolfUsgaDataLookup(Config config) : base(config) + { + this.config = config; + } + + //------------------------------------------------------------------- + // Properties. + + public override string ProcessDescription => "Golf Course Lookup"; + + //------------------------------------------------------------------- + // Run the process. + protected override bool Run() + { + return OK; + } + + //------------------------------------------------------------------ + // USGA data lookup. + //------------------------------------------------------------------ + + /// + /// Data elements that may be required in subsequent requests etc. + /// + private class UsgaRequestData + { + public DateTime PopulatedAt { get; } = DateTime.Now; + public Dictionary Cookies { get; } = new Dictionary(); + public String RequestVerificationToken { get; set; } + } + private UsgaRequestData usgaRequestData = null; + /// + /// Populate the request data from the Home Page response. + /// + private void PopulateUsgaRequestData(SacsHttpResponseData response) + { + try + { + if (!StringUtil.IsBlank(response.Data)) + { + usgaRequestData = new UsgaRequestData(); + + // Cookies. + usgaRequestData.Cookies.AddRange(response.Cookies); + + // Parse HTML. + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.LoadHtml(response.Data); + + // Locate verification token. + HtmlNode verificationTokenNode = htmlDoc.DocumentNode.SelectSingleNode("//input[@name='__RequestVerificationToken']"); + if (verificationTokenNode != null) + { + usgaRequestData.RequestVerificationToken = verificationTokenNode.GetAttributeValue("value", ""); + } + } + + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, "populating USGA request data", 0)); + } + } + /// + /// Get the USGA request data to extract useful elements, eg. verification token and cookies. + /// - Request data is refreshed periodically in case of expiry. + /// + private UsgaRequestData GetUsgaRequestData() + { + if (usgaRequestData == null || (DateTime.Now - usgaRequestData.PopulatedAt).TotalMinutes > 15) + { + try + { + + // Query countries on USGA website. + CancellationToken cancelToken = new CancellationToken(); + SacsHttpRequestData request = new SacsHttpRequestData(cancelToken) { Url = "https://ncrdb.usga.org/" }; + SacsHttpResponseData response = SacsHttpClient.DoRequest(request).Result; + String data = response.Data; + + PopulateUsgaRequestData(response); + + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, "querying USGA request data", 0)); + } + } + return usgaRequestData; + } + + //------------------------------------------------------------------ + /// + /// USGA Countries. + /// - Countries are listed on the home page of the USGA site in a dropdown. + /// + public List LookupUsgaCountries() + { + List usgaCountries = new List(); + + try + { + + // Query countries on USGA website. + CancellationToken cancelToken = new CancellationToken(); + SacsHttpRequestData request = new SacsHttpRequestData(cancelToken) { Url = "https://ncrdb.usga.org/" }; + SacsHttpResponseData response = SacsHttpClient.DoRequest(request).Result; + String data = response.Data; + PopulateUsgaRequestData(response); + + if (!StringUtil.IsBlank(response.Data)) + { + // Parse HTML. + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.LoadHtml(response.Data); + + // Locate countries list. + HtmlNode countriesNode = htmlDoc.GetElementbyId("ddlCountries"); + if (countriesNode != null) + { + foreach (HtmlNode countryOptionNode in countriesNode.SelectNodes("./option")) + { + String countryCode = StringUtil.TrimWhitespace(countryOptionNode.GetAttributeValue("value", "")); + String countryName = StringUtil.TrimWhitespace(WebUtil.HtmlDecode(countryOptionNode.InnerText)); + // Ignore blank code or name. + if (StringUtil.IsBlank(countryCode) || countryCode.EqualsCI("(Select)") || StringUtil.IsBlank(countryName)) continue; + // Ignore 'Select' item. + if (countryCode.EqualsCI("(Select)")) continue; + // Ignore US States and territories. + if (countryCode.StartsWithCI("US-") || countryCode.StartsWithCI("UM-")) continue; + // Ignore codes that aren't 3 chars. + if (countryCode.Length != 3) continue; + // Add country to list. + usgaCountries.Add(new CountryData() { Code = countryCode, Name = countryName }); + } + } + else SaLogger.Warn(SysUtil.Fn + " Countries node not found."); + } + + // Store countries. + List countriesData = new List(); + foreach (CountryData usgaCountry in usgaCountries) + { + SaxReferenceGolfMgr.UsgaCountryData countryData = new SaxReferenceGolfMgr.UsgaCountryData(); + countryData.CountryCode = usgaCountry.Code; + countryData.CountryName = usgaCountry.Name; + countriesData.Add(countryData); + } + ReferenceGolfMgr.BulkUpdateUsgaCountries(countriesData, config.DbUpdateInfo); + if (ReferenceGolfMgr.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error bulk updating USGA countries: {ReferenceGolfMgr.ErrorStateMessage}."); + + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, "querying USGA countries", 0)); + } + return usgaCountries; + } + + //------------------------------------------------------------------ + /// + /// USGA Provinces for country. + /// + public List LookupUsgaProvincesForCountry(String countryCode) + { + List usgaProvinces = new List(); + if (StringUtil.IsBlank(countryCode)) return usgaProvinces; + + UsgaRequestData usgaRequestData = GetUsgaRequestData(); + + try + { + // Query countries on USGA website. + CancellationToken cancelToken = new CancellationToken(); + SacsHttpRequestData request = new SacsHttpRequestData(cancelToken) { Url = "https://ncrdb.usga.org/NCRListing?handler=LoadStates" }; + // Headers. + request.RequestHeaders.Add(HeaderNames.Accept, "*/*"); + request.RequestHeaders.Add(HeaderNames.AcceptEncoding, "gzip, deflate, br, zstd"); + request.RequestHeaders.Add(HeaderNames.AcceptLanguage, "en-GB,en;q=0.9"); + request.RequestHeaders.Add(HeaderNames.DNT, "1"); + request.RequestHeaders.Add(HeaderNames.Origin, "https://ncrdb.usga.org/"); + request.RequestHeaders.Add("Priority", "u=1, i"); + request.RequestHeaders.Add(HeaderNames.Referer, "https://ncrdb.usga.org/"); + if (!StringUtil.IsBlank(usgaRequestData.RequestVerificationToken)) + request.RequestHeaders.Add("Requestverificationtoken", usgaRequestData.RequestVerificationToken); + // Content. + request.FormData.Add(new KeyValuePair("countryCode", countryCode)); + request.ContentHeaders.Add(HeaderNames.ContentType, "application/x-www-form-urlencoded; charset=UTF-8"); + // Request. + SacsHttpResponseData response = SacsHttpClient.DoRequest(request).Result; + String data = response.Data; + + if (!StringUtil.IsBlank(response.Data)) + { + dynamic provincesJson = SacsJsonHelper.DeserializeJsonObject(response.Data); + if (provincesJson is JArray) + { + JArray provincesArray = provincesJson as JArray; + foreach (var provinceToken in provincesArray) + { + // Province properties. + ProvinceData provinceData = new ProvinceData(); + foreach (var propertyToken in provinceToken) + { + if (propertyToken is JProperty) + { + JProperty provinceProperty = propertyToken as JProperty; + String propertyName = provinceProperty.Name; + String propertyStringValue = StringUtil.TrimWhitespace(provinceProperty.Value.ToString()); + if (propertyName.EqualsCI("text")) + provinceData.Name = propertyStringValue; + else if (propertyName.EqualsCI("value")) + provinceData.Code = propertyStringValue; + else if (propertyName.EqualsCI("group")) { } + else if (propertyName.EqualsCI("selected")) { } + else if (propertyName.EqualsCI("disabled")) { } + } + } + if (!StringUtil.IsBlank(provinceData.Code) && !provinceData.Code.EqualsCI("(Select)") && !StringUtil.IsBlank(provinceData.Name)) + usgaProvinces.Add(provinceData); + } + } + } + + // Store provinces. + List provincesData = new List(); + foreach (ProvinceData usgaProvince in usgaProvinces) + { + SaxReferenceGolfMgr.UsgaProvinceData provinceData = new SaxReferenceGolfMgr.UsgaProvinceData(); + provinceData.CountryCode = countryCode; + provinceData.ProvinceCode = usgaProvince.Code; + provinceData.ProvinceName = usgaProvince.Name; + provincesData.Add(provinceData); + } + ReferenceGolfMgr.BulkUpdateUsgaProvinces(provincesData, config.DbUpdateInfo); + if (ReferenceGolfMgr.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error bulk updating USGA provinces: {ReferenceGolfMgr.ErrorStateMessage}."); + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, $"querying USGA provinces for {countryCode}", 0)); + } + return usgaProvinces; + } + + //------------------------------------------------------------------ + /// + /// USGA Courses for country. + /// + public List LookupUsgaCoursesForCountryAndProvince(String countryCode, String provinceCode) + { + List usgaCourses = new List(); + if (StringUtil.IsBlank(countryCode) || StringUtil.IsBlank(provinceCode)) return usgaCourses; + + UsgaRequestData usgaRequestData = GetUsgaRequestData(); + + try + { + // Query countries on USGA website. + CancellationToken cancelToken = new CancellationToken(); + SacsHttpRequestData request = new SacsHttpRequestData(cancelToken) { Url = "https://ncrdb.usga.org/NCRListing?handler=LoadCourses" }; + // Headers. + request.RequestHeaders.Add(HeaderNames.Accept, "*/*"); + request.RequestHeaders.Add(HeaderNames.AcceptEncoding, "gzip, deflate, br, zstd"); + request.RequestHeaders.Add(HeaderNames.AcceptLanguage, "en-GB,en;q=0.9"); + request.RequestHeaders.Add(HeaderNames.DNT, "1"); + request.RequestHeaders.Add(HeaderNames.Origin, "https://ncrdb.usga.org/"); + request.RequestHeaders.Add("Priority", "u=1, i"); + request.RequestHeaders.Add(HeaderNames.Referer, "https://ncrdb.usga.org/"); + if (!StringUtil.IsBlank(usgaRequestData.RequestVerificationToken)) + request.RequestHeaders.Add("Requestverificationtoken", usgaRequestData.RequestVerificationToken); + // Content. + request.FormData.Add(new KeyValuePair("clubName", "")); + request.FormData.Add(new KeyValuePair("clubCity", "")); + request.FormData.Add(new KeyValuePair("clubState", provinceCode)); + request.FormData.Add(new KeyValuePair("clubCountry", countryCode)); + request.ContentHeaders.Add(HeaderNames.ContentType, "application/x-www-form-urlencoded; charset=UTF-8"); + // Request. + SacsHttpResponseData response = SacsHttpClient.DoRequest(request).Result; + String data = response.Data; + + if (!StringUtil.IsBlank(response.Data)) + { + HashSet UnrecognisedCourseProperties = new HashSet(StringComparer.InvariantCultureIgnoreCase); + dynamic coursesJson = SacsJsonHelper.DeserializeJsonObject(response.Data); + if (coursesJson is JArray) + { + JArray coursesArray = coursesJson as JArray; + foreach (var courseToken in coursesArray) + { + // Course properties. + CourseData courseData = new CourseData(); + foreach (var propertyToken in courseToken) + { + if (propertyToken is JProperty) + { + JProperty courseProperty = propertyToken as JProperty; + String propertyName = courseProperty.Name; + String propertyStringValue = StringUtil.TrimWhitespace(courseProperty.Value.ToString()); + if (propertyName.EqualsCI("courseId")) + courseData.CourseId = propertyStringValue; + else if (propertyName.EqualsCI("legacyCRPCourseId")) + courseData.LegacyCrpCourseId = propertyStringValue; + else if (propertyName.EqualsCI("courseName")) + courseData.CourseName = propertyStringValue; + else if (propertyName.EqualsCI("facilityId")) + courseData.FacilityId = propertyStringValue; + else if (propertyName.EqualsCI("facilityName")) + courseData.FacilityName = propertyStringValue; + else if (propertyName.EqualsCI("fullName")) + courseData.FullName = propertyStringValue; + else if (propertyName.EqualsCI("address1")) + courseData.Address1 = propertyStringValue; + else if (propertyName.EqualsCI("address2")) + courseData.Address2 = propertyStringValue; + else if (propertyName.EqualsCI("city")) + courseData.City = propertyStringValue; + else if (propertyName.EqualsCI("entStateCode")) + courseData.EntProvinceCode = propertyStringValue; + else if (propertyName.EqualsCI("state")) + courseData.ProvinceCode = propertyStringValue; + else if (propertyName.EqualsCI("stateDisplay")) + courseData.Province = propertyStringValue; + else if (propertyName.EqualsCI("country")) + courseData.CountryCode = propertyStringValue; + else if (propertyName.EqualsCI("entCountryCode")) + courseData.EntCountryCode = propertyStringValue; + else if (propertyName.EqualsCI("email")) + courseData.Email = propertyStringValue; + else if (propertyName.EqualsCI("telephone")) + courseData.Telephone = propertyStringValue; + else if (propertyName.EqualsCI("ratings")) + { + if (courseProperty.Value.Count() > 0) + courseData.Ratings.Add(""); + } + else UnrecognisedCourseProperties.Add(propertyName); + } + } + if (!StringUtil.IsBlank(courseData.CourseId) && !StringUtil.IsBlank(courseData.CourseName)) + { + // Populate caption and add to list. + SetCourseCaption(courseData); + usgaCourses.Add(courseData); + } + } + } + if (UnrecognisedCourseProperties.Any()) + SaLogger.Warn(SysUtil.Fn + " Unrecognised USGA course properties: " + String.Join(", ", UnrecognisedCourseProperties)); + } + + // Store countries. + Dictionary countriesData = new Dictionary(); + foreach (CourseData usgaCourse in usgaCourses) + { + SaxReferenceGolfMgr.UsgaCountryData countryData = new SaxReferenceGolfMgr.UsgaCountryData(); + countryData.CountryCode = usgaCourse.CountryCode; + countryData.EntCountryCode = usgaCourse.EntCountryCode; + countriesData[countryData.CountryCode] = countryData; + } + ReferenceGolfMgr.BulkUpdateUsgaCountries(countriesData.Values.ToList(), config.DbUpdateInfo); + if (ReferenceGolfMgr.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error bulk updating USGA countries: {ReferenceGolfMgr.ErrorStateMessage}."); + + // Store provinces. + Dictionary provincesData = new Dictionary(); + foreach (CourseData usgaCourse in usgaCourses) + { + SaxReferenceGolfMgr.UsgaProvinceData provinceData = new SaxReferenceGolfMgr.UsgaProvinceData(); + provinceData.CountryCode = usgaCourse.CountryCode; + provinceData.ProvinceCode = usgaCourse.ProvinceCode; + provinceData.EntProvinceCode = usgaCourse.EntProvinceCode; + provincesData[provinceData.ProvinceCode] = provinceData; + } + ReferenceGolfMgr.BulkUpdateUsgaProvinces(provincesData.Values.ToList(), config.DbUpdateInfo); + if (ReferenceGolfMgr.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error bulk updating USGA provinces: {ReferenceGolfMgr.ErrorStateMessage}."); + + // Store facilities. + Dictionary facilitiesData = new Dictionary(); + foreach (CourseData usgaCourse in usgaCourses) + { + if (StringUtil.IsBlank(usgaCourse.FacilityId)) continue; + SaxReferenceGolfMgr.UsgaFacilityData facilityData = new SaxReferenceGolfMgr.UsgaFacilityData(); + facilityData.ProvinceCode = provinceCode; + facilityData.FacilityId = StringUtil.ToSysId(usgaCourse.FacilityId); + facilityData.FacilityName = usgaCourse.FacilityName; + if (!SysId.IsValid(facilityData.FacilityId)) + { + SaLogger.Warn($"{SysUtil.Fn} Invalid Facility Id for {usgaCourse.CourseName}: {usgaCourse.FacilityId}."); + continue; + } + facilitiesData[facilityData.FacilityId] = facilityData; + } + ReferenceGolfMgr.BulkUpdateUsgaFacilities(facilitiesData.Values.ToList(), config.DbUpdateInfo); + if (ReferenceGolfMgr.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error bulk updating USGA facilities: {ReferenceGolfMgr.ErrorStateMessage}."); + + // Store courses. + Dictionary coursesData = new Dictionary(); + foreach (CourseData usgaCourse in usgaCourses) + { + if (StringUtil.IsBlank(usgaCourse.CourseId)) continue; + SaxReferenceGolfMgr.UsgaCourseData courseData = new SaxReferenceGolfMgr.UsgaCourseData(); + courseData.FacilityId = StringUtil.ToSysId(usgaCourse.FacilityId); + courseData.CourseId = StringUtil.ToSysId(usgaCourse.CourseId); + courseData.LegacyCrpCourseId = StringUtil.ToSysId(usgaCourse.LegacyCrpCourseId); + courseData.Caption = usgaCourse.Caption; + courseData.CourseName = usgaCourse.CourseName; + courseData.FullName = usgaCourse.FullName; + courseData.Address1 = usgaCourse.Address1; + courseData.Address2 = usgaCourse.Address2; + courseData.City = usgaCourse.City; + courseData.Email = usgaCourse.Email; + courseData.Telephone = usgaCourse.Telephone; + if (!SysId.IsValid(courseData.CourseId)) + { + SaLogger.Warn($"{SysUtil.Fn} Invalid Course Id for {usgaCourse.CourseName}: {usgaCourse.CourseId}."); + continue; + } + coursesData[courseData.CourseId] = courseData; + } + ReferenceGolfMgr.BulkUpdateUsgaCourses(coursesData.Values.ToList(), config.DbUpdateInfo); + if (ReferenceGolfMgr.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error bulk updating USGA courses: {ReferenceGolfMgr.ErrorStateMessage}."); + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, $"querying USGA courses for {countryCode}", 0)); + } + return usgaCourses; + } + + /// + /// Combine facility and course names as required to generate course caption. + /// - NB Course name is sufficient if same as facility name. + /// + /// + private void SetCourseCaption(CourseData course) + { + // Facility (club) name. + // - Strip id in brackets + anything following and remove generic phrases (golf club, hotel etc). + String facilityName = CleanseFacilityName(Regex.Replace(course.FacilityName, "\\s*\\(\\s*\\d+\\s*\\).*$", "")); + // Course name. + // - Remove id in brackets (occasionally found). + // - Remove generic phrases (including for facility name). + String courseName = CleanseCourseName(Regex.Replace(course.CourseName, "\\(\\s*\\d+\\s*\\)", "")); + course.Caption = courseName; + if (!CourseNameMatchesFacility(facilityName, courseName)) + course.Caption = facilityName + " - " + courseName; + } + + /// + /// Cleanse Facility name by removing generic phrases, eg. golf club, hotel etc. + /// + private String CleanseFacilityName(String facilityName) + { + facilityName = Regex.Replace(facilityName, "Hotel\\s*(and|&)\\s*(Golf|Country)\\s*Club", "", RegexOptions.IgnoreCase); + facilityName = Regex.Replace(facilityName, "Hotel,*\\s*Golf\\s*(and|&)\\s*Spa", "", RegexOptions.IgnoreCase); + facilityName = Regex.Replace(facilityName, "Golf\\s*(and|&)\\s*(Country|Sailing)\\s*Club", "", RegexOptions.IgnoreCase); + facilityName = Regex.Replace(facilityName, "Golf\\s*Club\\s*(and|&)\\s*Hotel", "", RegexOptions.IgnoreCase); + facilityName = Regex.Replace(facilityName, "Golf\\s*Club\\s*Ltd", "", RegexOptions.IgnoreCase); + facilityName = Regex.Replace(facilityName, "Golf\\s*(Club|Course|Links|Centre|Academy|Resort|Klub)", "", RegexOptions.IgnoreCase); + facilityName = Regex.Replace(facilityName, "Club\\s*de\\s*Golf", "", RegexOptions.IgnoreCase); + return StringUtil.TrimWhitespace(facilityName); + } + + /// + /// Cleanse Course name by removing generic phrases, including those defined for facility name. + /// + private String CleanseCourseName(String facilityName) + { + // Course name occasionally suffixed with 'Course' but this is meaningful in many cases (old course, new course). + //facilityName = Regex.Replace(facilityName, "\\bCourse\\b", "", RegexOptions.IgnoreCase); + return CleanseFacilityName(facilityName); + } + + private bool CourseNameMatchesFacility(String facilityName, String courseName) + { + if (courseName.EqualsCI(facilityName)) return true; + // Strip selected char/symbols (especially apostrophes which are inconsistent). + if (Regex.Replace(courseName, "[\\s-',\\.]", "").EqualsCI(Regex.Replace(facilityName, "[\\s-',\\.]", ""))) return true; + // Course name can end on Golf or Course and still match facility. + if (Regex.Replace(courseName, "\\s*(Golf|Course)$", "").EqualsCI(facilityName)) return true; + return false; + } + + //------------------------------------------------------------------ + /// + /// Identify the column for each marker property. + /// + private class MarkerColumnData + { + public int ColIdx_Tee { get; set; } = -1; + public int ColIdx_Gender { get; set; } = -1; + public int ColIdx_Par { get; set; } = -1; + public int ColIdx_CourseRating { get; set; } = -1; + public int ColIdx_BogeyRating { get; set; } = -1; + public int ColIdx_SlopeRating { get; set; } = -1; + public int ColIdx_Front9 { get; set; } = -1; + public int ColIdx_Back9 { get; set; } = -1; + public int ColIdx_Front9CourseRating { get; set; } = -1; + public int ColIdx_Back9CourseRating { get; set; } = -1; + public int ColIdx_Front9BogeyRating { get; set; } = -1; + public int ColIdx_Back9BogeyRating { get; set; } = -1; + public int ColIdx_Front9SlopeRating { get; set; } = -1; + public int ColIdx_Back9SlopeRating { get; set; } = -1; + public int ColIdx_MarkerId { get; set; } = -1; + public int ColIdx_Length { get; set; } = -1; + } + /// + /// USGA Markers for course. + /// + public List LookupUsgaMarkersForCourse(SysId usgaCourseId) + { + List usgaMarkers = new List(); + if (!SysId.IsValid(usgaCourseId)) return usgaMarkers; + MarkerColumnData markerColumns = new MarkerColumnData(); + + try + { + // Query countries on USGA website. + CancellationToken cancelToken = new CancellationToken(); + SacsHttpRequestData request = new SacsHttpRequestData(cancelToken) { Url = $"https://ncrdb.usga.org/courseTeeInfo?CourseID={usgaCourseId}" }; + SacsHttpResponseData response = SacsHttpClient.DoRequest(request).Result; + String data = response.Data; + + if (!StringUtil.IsBlank(response.Data)) + { + // Parse HTML. + HtmlDocument htmlDoc = new HtmlDocument(); + htmlDoc.LoadHtml(response.Data); + + // Locate countries list. + HtmlNode teeTableNode = htmlDoc.GetElementbyId("gvTee"); + if (teeTableNode != null) + { + // Identify marker columns. + int teeColumnIdx = -1; + foreach (HtmlNode teeHeaderNode in teeTableNode.SelectNodes("./tr[1]/th")) + { + teeColumnIdx++; + String headerText = StringUtil.TrimWhitespace(WebUtil.HtmlDecode(teeHeaderNode.InnerText)); + if (StringUtil.IsBlank(headerText) || headerText.EqualsCI("CH")) + { + // Columns ignored. + } + else if (headerText.EqualsCI("Tee Name")) markerColumns.ColIdx_Tee = teeColumnIdx; + else if (headerText.EqualsCI("Gender")) markerColumns.ColIdx_Gender = teeColumnIdx; + else if (headerText.EqualsCI("Par")) markerColumns.ColIdx_Par = teeColumnIdx; + else if (headerText.EqualsCI("TeeId")) markerColumns.ColIdx_MarkerId = teeColumnIdx; + else if (headerText.EqualsCI("Length")) markerColumns.ColIdx_Length = teeColumnIdx; + // Specific part-course (9 holes) values. + else if (headerText.EqualsCI("RatingF9")) markerColumns.ColIdx_Front9CourseRating = teeColumnIdx; + else if (headerText.EqualsCI("RatingB9")) markerColumns.ColIdx_Back9CourseRating = teeColumnIdx; + else if (headerText.EqualsCI("Front (9)")) markerColumns.ColIdx_Front9 = teeColumnIdx; + else if (headerText.EqualsCI("Back (9)")) markerColumns.ColIdx_Back9 = teeColumnIdx; + else if (headerText.EqualsCI("Bogey Rating (F9)")) markerColumns.ColIdx_Front9BogeyRating = teeColumnIdx; + else if (headerText.EqualsCI("Bogey Rating (B9)")) markerColumns.ColIdx_Back9BogeyRating = teeColumnIdx; + else if (headerText.EqualsCI("Slope (F9)")) markerColumns.ColIdx_Front9SlopeRating = teeColumnIdx; + else if (headerText.EqualsCI("Slope (B9)")) markerColumns.ColIdx_Back9SlopeRating = teeColumnIdx; + // Less specific full-course (commonly 18 holes) values. + else if (headerText.IsMatchCI("Course Rating")) markerColumns.ColIdx_CourseRating = teeColumnIdx; + else if (headerText.IsMatchCI("Bogey Rating")) markerColumns.ColIdx_BogeyRating = teeColumnIdx; + else if (headerText.IsMatchCI("Slope Rating")) markerColumns.ColIdx_SlopeRating = teeColumnIdx; + else SaLogger.Info($"{SysUtil.Fn} Unexpected Marker column header: {headerText}"); + } + foreach (HtmlNode teeRowNode in teeTableNode.SelectNodes("./tr[position()>1]")) + { + MarkerData markerData18 = new MarkerData(usgaCourseId, 18, "18"); + MarkerData markerDataF9 = new MarkerData(usgaCourseId, 9, "F9"); + MarkerData markerDataB9 = new MarkerData(usgaCourseId, 9, "B9"); + teeColumnIdx = -1; + foreach (HtmlNode teePropertyNode in teeRowNode.SelectNodes("./td")) + { + teeColumnIdx++; + String propertyText = StringUtil.TrimWhitespace(WebUtil.HtmlDecode(teePropertyNode.InnerText)); + if (markerColumns.ColIdx_Tee == teeColumnIdx) + { + markerData18.Tee = propertyText; + markerDataF9.Tee = propertyText; + markerDataB9.Tee = propertyText; + } + else if (markerColumns.ColIdx_Gender == teeColumnIdx) + { + markerData18.Gender = propertyText; + markerDataF9.Gender = propertyText; + markerDataB9.Gender = propertyText; + } + else if (markerColumns.ColIdx_Par == teeColumnIdx) + { + markerData18.Par = StringUtil.ToShort(propertyText); + } + else if (markerColumns.ColIdx_CourseRating == teeColumnIdx) + { + markerData18.CourseRating = StringUtil.ToDecimal(propertyText); + } + else if (markerColumns.ColIdx_BogeyRating == teeColumnIdx) + { + markerData18.BogeyRating = StringUtil.ToDecimal(propertyText); + } + else if (markerColumns.ColIdx_SlopeRating == teeColumnIdx) + { + markerData18.SlopeRating = StringUtil.ToShort(propertyText); + } + else if (markerColumns.ColIdx_Front9CourseRating == teeColumnIdx) + { + if (markerDataF9.CourseRating == 0) + markerDataF9.CourseRating = StringUtil.ToDecimal(propertyText); + } + else if (markerColumns.ColIdx_Back9CourseRating == teeColumnIdx) + { + if (markerDataB9.CourseRating == 0) + markerDataB9.CourseRating = StringUtil.ToDecimal(propertyText); + } + else if (markerColumns.ColIdx_Front9 == teeColumnIdx) + { + // Format: CourseRating / SlopeRating. + markerDataF9.CourseRating = StringUtil.ToDecimal(Regex.Replace(propertyText, "\\s*/.*$", "")); + markerDataF9.SlopeRating = StringUtil.ToShort(Regex.Replace(propertyText, "^.*/\\s*", "")); + } + else if (markerColumns.ColIdx_Back9 == teeColumnIdx) + { + // Format: CourseRating / SlopeRating. + markerDataB9.CourseRating = StringUtil.ToDecimal(Regex.Replace(propertyText, "\\s*/.*$", "")); + markerDataB9.SlopeRating = StringUtil.ToShort(Regex.Replace(propertyText, "^.*/\\s*", "")); + } + else if (markerColumns.ColIdx_Front9BogeyRating == teeColumnIdx) + { + markerDataF9.BogeyRating = StringUtil.ToDecimal(propertyText); + } + else if (markerColumns.ColIdx_Back9BogeyRating == teeColumnIdx) + { + markerDataB9.BogeyRating = StringUtil.ToDecimal(propertyText); + } + else if (markerColumns.ColIdx_Front9SlopeRating == teeColumnIdx) + { + if (markerDataF9.SlopeRating == 0) + markerDataF9.SlopeRating = StringUtil.ToShort(propertyText); + } + else if (markerColumns.ColIdx_Back9SlopeRating == teeColumnIdx) + { + // Back 9 Slope Rating populated with value for Front 9. + //markerDataB9.SlopeRating = StringUtil.ToInt(propertyText); + } + else if (markerColumns.ColIdx_MarkerId == teeColumnIdx) + { + markerData18.MarkerId = StringUtil.ToSysId(propertyText); + // Unclear if Tee Id is relevant to 9 holes. + //markerDataF9.MarkerId = StringUtil.ToSysId(propertyText); + //markerDataB9.MarkerId = StringUtil.ToSysId(propertyText); + } + else if (markerColumns.ColIdx_Length == teeColumnIdx) + { + markerData18.Length = StringUtil.ToShort(propertyText); + } + } + + // Add valid markers to list. + if (markerData18.IsValid()) + usgaMarkers.Add(markerData18); + if (markerDataF9.IsValid()) + usgaMarkers.Add(markerDataF9); + if (markerDataB9.IsValid()) + usgaMarkers.Add(markerDataB9); + } + } + else SaLogger.Warn(SysUtil.Fn + " Tee table not found."); + } + + // Store markers. + List markersData = new List(); + foreach (MarkerData usgaMarker in usgaMarkers) + { + if (!SysId.IsValid(usgaMarker.CourseId)) continue; + //if (!SysId.IsValid(usgaMarker.MarkerId)) continue; + if (StringUtil.IsBlank(usgaMarker.Caption)) continue; + SaxReferenceGolfMgr.UsgaMarkerData markerData = new SaxReferenceGolfMgr.UsgaMarkerData(); + markerData.CourseId = usgaMarker.CourseId; + markerData.MarkerId = usgaMarker.MarkerId; + markerData.Caption = usgaMarker.Caption; + markerData.Holes = usgaMarker.Holes; + markerData.HolesCaption = usgaMarker.HolesCaption; + markerData.Tee = usgaMarker.Tee; + markerData.Gender = usgaMarker.Gender; + markerData.SlopeRating = usgaMarker.SlopeRating; + markerData.Par = usgaMarker.Par; + markerData.CourseRating = usgaMarker.CourseRating; + markerData.BogeyRating = usgaMarker.BogeyRating; + markerData.Length = usgaMarker.Length; + markersData.Add(markerData); + } + ReferenceGolfMgr.BulkUpdateUsgaMarkers(markersData, config.DbUpdateInfo); + if (ReferenceGolfMgr.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error bulk updating USGA markers: {ReferenceGolfMgr.ErrorStateMessage}."); + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, $"querying USGA markers for course Id: {usgaCourseId}", 0)); + } + return usgaMarkers; + } + + //------------------------------------------------------------------ + } + //====================================================================== +} diff --git a/SaxoniteCoreWeb/Base/Procs/SaxProcess_Web.cs b/SaxoniteCoreWeb/Base/Procs/SaxProcess_Web.cs new file mode 100644 index 0000000..f55b649 --- /dev/null +++ b/SaxoniteCoreWeb/Base/Procs/SaxProcess_Web.cs @@ -0,0 +1,53 @@ +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Proc.Excel; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Procs; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Saxonite.Net.Core.Web.Base.Procs +{ + //======================================================================= + public abstract class SaxProcess_Web : SaxProcess_Base + { + //------------------------------------------------------------------- + // Definitions. + public new class Config : SaxProcess_Base.Config + { + protected Config(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo) : base(sessionContext, dbUpdateInfo) + { } + } + + //------------------------------------------------------------------- + // Data members. + private Config config; + + //------------------------------------------------------------------- + // Construction. + protected SaxProcess_Web(Config config) : base(config) + { + this.config = config; + } + + //------------------------------------------------------------------- + // Excel Spreadsheet utilities. + //------------------------------------------------------------------- + protected override SaMsExcelColumnHeading_Config GetExcelColumnHeadingConfig() + { + SaMsExcelColumnHeading_Config configHeading = base.GetExcelColumnHeadingConfig(); + return configHeading; + } + + protected override SaMsExcelStyleAttr GetExcelDefaultWorkbookStyle() + { + SaMsExcelStyleAttr styleAttr = base.GetExcelDefaultWorkbookStyle(); + return styleAttr; + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteCoreWeb/SaxoniteCoreWeb.csproj b/SaxoniteCoreWeb/SaxoniteCoreWeb.csproj index 692d92f..f7a0691 100644 --- a/SaxoniteCoreWeb/SaxoniteCoreWeb.csproj +++ b/SaxoniteCoreWeb/SaxoniteCoreWeb.csproj @@ -23,7 +23,8 @@ - + + diff --git a/SaxoniteCoreWebAdmin/Admin/App/SaxApplication_Admin.cs b/SaxoniteCoreWebAdmin/Admin/App/SaxApplication_Admin.cs index efad334..b4c057d 100644 --- a/SaxoniteCoreWebAdmin/Admin/App/SaxApplication_Admin.cs +++ b/SaxoniteCoreWebAdmin/Admin/App/SaxApplication_Admin.cs @@ -31,7 +31,7 @@ namespace Saxonite.Net.Core.Web.Admin.App { //------------------------------------------------------------------- // Data members. - private bool generateDatabaseDefinitions = false; + private bool generateDatabaseDefinitions = true; private bool populateRegions = false; private Dictionary appConfigs = new Dictionary(); private Dictionary emailConfigs = new Dictionary(); @@ -44,7 +44,7 @@ namespace Saxonite.Net.Core.Web.Admin.App //------------------------------------------------------------------- // Construction. - public SaxApplication_Admin(IConfiguration configuration) + public SaxApplication_Admin(IConfiguration configuration) : base(Sax.Application.Admin) { InitialiseTemporaryLoggingFolder(); try @@ -100,31 +100,16 @@ namespace Saxonite.Net.Core.Web.Admin.App /// Initialise environment - from internal (above) or unit tests. protected void InitEnvironment(IWebHostEnvironment env) { - Development = env.IsDevelopment(); - environmentName = env.EnvironmentName; - SaLogger.LogFilenamePrefix = "Sax-Web-Adm"; - SaLogger.IncludeHostInFileMessage = false; - SaLogger.IncludeUserInFileMessage = false; + base.InitEnvironment(env, "Sax-Web-Adm"); try { - // Load server configuration. - var builder = new ConfigurationBuilder() - .SetBasePath(env.ContentRootPath) - .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) - .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false) - .AddJsonFile($"appsettings.machine.{SaxSystem.ComputerName}.json", optional: false, reloadOnChange: false) - .AddEnvironmentVariables(); - SaxConfiguration = builder.Build(); - - //Messages.Add($"Host: {SaxSystem.ComputerName}"); - //Messages.Add($"Config file: appsettings.machine.{SaxSystem.ComputerName}.json"); - // Application configuration. appConfigs = SaxAppConfigHelper.ExtractAppConfigs(SaxConfiguration.GetSection("AppConfigs")); emailConfigs = SaxEmailConfigHelper.ExtractEmailConfigs(SaxConfiguration.GetSection("EmailConfigs")); + + // Ensure root log folder ends with 'Admin' folder. LoggingRootFolder = AppConfig.Logging.RootFolder; - // Ensure root log folder ends with Admin folder. if (!StringUtil.IsBlank(LoggingRootFolder) && !Regex.IsMatch(LoggingRootFolder, "[\\\\/]Admin$", RegexOptions.IgnoreCase)) LoggingRootFolder = StringUtil.CombineFilePath(LoggingRootFolder, "Admin"); @@ -150,8 +135,9 @@ namespace Saxonite.Net.Core.Web.Admin.App //Messages.Add($"DbConnection: {coreDatabase.ConnectionString}"); // Session context - only one context available/necessary (for now). - SessionContextData_Admin sessionContextData = new SessionContextData_Admin(new SaxSessionContext_Web(100, Sax.Application.Admin)); + SessionContextData_Admin sessionContextData = new SessionContextData_Admin(new SaxSessionContext_Web(100, ApplicationType)); ConfigureDatabaseConnection(sessionContextData, Sax.Database.Core); + ConfigureDatabaseConnection(sessionContextData, Sax.Database.Reference); ConfigureDatabaseConnection(sessionContextData, Sax.Database.Support); sessionContexts.Add(sessionContextData.SessionContext.Index, sessionContextData); SessionContext = sessionContextData.SessionContext; @@ -183,6 +169,11 @@ namespace Saxonite.Net.Core.Web.Admin.App //SaUpdateLogDbDfnGenerator.Generate(database.ConnectionString); } + // Reference database. + ISacsDatabase referenceDatabase = GetDatabase(sessionContext, Sax.Database.Reference); + if (referenceDatabase != null && !StringUtil.IsEmpty(referenceDatabase.ConnectionString)) + SaxDbDfnGenerator.Generate(Sax.Database.Reference, referenceDatabase.ConnectionString); + // Support database. ISacsDatabase supportDatabase = GetDatabase(sessionContext, Sax.Database.Support); if (supportDatabase != null && !StringUtil.IsEmpty(supportDatabase.ConnectionString)) diff --git a/SaxoniteCoreWebAdmin/Admin/App/SaxSessionData_Admin.cs b/SaxoniteCoreWebAdmin/Admin/App/SaxSessionData_Admin.cs index 78252d8..47e5e19 100644 --- a/SaxoniteCoreWebAdmin/Admin/App/SaxSessionData_Admin.cs +++ b/SaxoniteCoreWebAdmin/Admin/App/SaxSessionData_Admin.cs @@ -59,6 +59,31 @@ namespace Saxonite.Net.Core.Web.Admin.App } public FilterData Filter { get; private set; } = new FilterData(); + //------------------------------------------------------------------- + // System. + public class SystemData + { + // Databases. + public class DatabaseData + { + } + public DatabaseData Database { get; private set; } = new DatabaseData(); + + // Logs. + public class LogsData + { + public class FilterData + { + public String Folder { get; set; } + public String Year { get; set; } + public String Month { get; set; } + } + public FilterData Filter { get; private set; } = new FilterData(); + } + public LogsData Logs { get; private set; } = new LogsData(); + } + public SystemData System { get; private set; } = new SystemData(); + //------------------------------------------------------------------- // Online application encryption IV value - for consistent encryption during session. public String Base64IV_AdminApp { get; private set; } = SacsEncryptionHelper.InitSymmetricEncryptionIV(SaxController_Admin.Base64Key_AdminApp); diff --git a/SaxoniteCoreWebAdmin/Admin/App/SaxStartup_Admin.cs b/SaxoniteCoreWebAdmin/Admin/App/SaxStartup_Admin.cs index 16ff632..f912538 100644 --- a/SaxoniteCoreWebAdmin/Admin/App/SaxStartup_Admin.cs +++ b/SaxoniteCoreWebAdmin/Admin/App/SaxStartup_Admin.cs @@ -50,6 +50,9 @@ namespace Saxonite.Net.Core.Web.Admin.App options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None; }); + + // Hosted (schedule) services. + services.AddHostedService(); } //------------------------------------------------------------------- diff --git a/SaxoniteCoreWebAdmin/Admin/Consoles/SaxHostedServiceConsole_Admin.cs b/SaxoniteCoreWebAdmin/Admin/Consoles/SaxHostedServiceConsole_Admin.cs new file mode 100644 index 0000000..a081a90 --- /dev/null +++ b/SaxoniteCoreWebAdmin/Admin/Consoles/SaxHostedServiceConsole_Admin.cs @@ -0,0 +1,124 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Tasks; +using Sarand.Net.Standard.Base.Utils; +using Saxonite.Net.Core.Web.Admin.App; +using Saxonite.Net.Core.Web.Base.Consoles; +using Saxonite.Net.Core.Web.Base.Procs; +using Saxonite.Net.Standard.Base.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace Saxonite.Net.Core.Web.Admin.Consoles +{ + //======================================================================= + public class SaxHostedServiceConsole_Admin : SaxHostedServiceConsole_Web + { + //------------------------------------------------------------------- + // Definitions. + private enum ProcessType { Unknown = 0, GolfUsgaReferenceLookup } + + /// + /// Process tracking data to control when process is run. + /// + private class ProcessControlData + { + // Construction. + public ProcessControlData(ProcessType processType, TimeSpan minTimeBetweenRuns) + { + this.ProcessType = processType; + this.MinTimeBetweenRuns = minTimeBetweenRuns; + ResetRunTime(); + } + // Properties. + public ProcessType ProcessType { get; } + public TimeSpan MinTimeBetweenRuns { get; } + public DateTime LastRunAt { get; private set; } + // Utilities. + public bool ReadyToRun() + { + //SaLogger.Info($"{SysUtil.Fn} Process: {ProcessType}. Secs since last run: {(DateTime.Now - LastRunAt).TotalSeconds}. Seconds between runs: {MinTimeBetweenRuns.TotalSeconds}."); + return (DateTime.Now - LastRunAt) > MinTimeBetweenRuns; + } + public void ResetRunTime() + { + LastRunAt = DateTime.Now; + } + } + + //------------------------------------------------------------------- + // Data members. + private Dictionary processes { get; } = new Dictionary(); + + //------------------------------------------------------------------- + // Construction. + public SaxHostedServiceConsole_Admin() + { + InitialiseProcesses(); + } + + //------------------------------------------------------------------- + // Clean-up. + protected override void Dispose(bool disposing) + { + } + + //------------------------------------------------------------------- + + /// + /// Periodic processing to execute application processes as required. + /// - See parent class for timer logic. + /// + protected override void DoWork(object state) + { + //SaLogger.Info($"{SysUtil.Fn} Timed Background Service is working. State: {state}"); + SaxSessionContext sessionContext = SaxApplication_Admin.AppInstance.SessionContext; + DbUpdateInfo dbUpdateInfo = new DbUpdateInfo(new SysId(), "AdminScheduled", SacsSystem.ComputerName); + + // Check for cancellation. + var token = ProcessTaskData.CancellationToken; + if (token.IsCancellationRequested) return; + + // Identify processes that are ready to run. + foreach (ProcessControlData process in processes.Where(item => item.Value.ReadyToRun()).Select(item => item.Value)) + { + //SaLogger.Info($"{SysUtil.Fn} Executing process: {process.ProcessType}."); + process.ResetRunTime(); + switch (process.ProcessType) + { + case ProcessType.GolfUsgaReferenceLookup: + // Run on separate thread. + Task task = new Task(() => + { + SaxGolfUsgaDataLookup.ExecuteScheduledUsgaDataLookup(sessionContext, dbUpdateInfo, ProcessTaskData); + }, ProcessTaskData.CancellationToken); + task.Start(); + break; + } + } + } + + //------------------------------------------------------------------- + // Initialisation. + + private void InitialiseProcesses() + { + if (Sax.Config.Admin.Processes.Scheduled.UsgaGolfDataLookup.Enabled) + InitialiseProcess(ProcessType.GolfUsgaReferenceLookup, TimeSpan.FromMinutes(MathUtil.Constrain(Sax.Config.Admin.Processes.Scheduled.UsgaGolfDataLookup.MinsBetweenExecution, 2, 120))); + } + + private void InitialiseProcess(ProcessType processType, TimeSpan minTimeBetweenRuns) + { + if (!processes.ContainsKey(processType)) + processes[processType] = new ProcessControlData(processType, minTimeBetweenRuns); + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteCoreWebAdmin/Admin/Controllers/OrganisationController-Ajax-Upload.cs b/SaxoniteCoreWebAdmin/Admin/Controllers/OrganisationController-Ajax-Upload.cs index 56ee45f..66e8312 100644 --- a/SaxoniteCoreWebAdmin/Admin/Controllers/OrganisationController-Ajax-Upload.cs +++ b/SaxoniteCoreWebAdmin/Admin/Controllers/OrganisationController-Ajax-Upload.cs @@ -118,7 +118,7 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers return Json(responseData.SetMessage(messageTitle, Localiser["msg.process.in.progress"])); // Create the upload process. - SaxOrganisationUploader.Config processConfig = new SaxOrganisationUploader.Config(SessionContext, model.OrganisationDataFile[0]); + SaxOrganisationUploader.Config processConfig = new SaxOrganisationUploader.Config(SessionContext, DbUpdateInfo, model.OrganisationDataFile[0]); processConfig.SheetNameOrNumber = model.SheetNameOrNumber; processConfig.HeaderRowPos = (uint)StringUtil.ToInt(model.HeaderRow); processConfig.FirstDataRowPos = (uint)StringUtil.ToInt(model.FirstDataRow); diff --git a/SaxoniteCoreWebAdmin/Admin/Controllers/OrganisationController-Download.cs b/SaxoniteCoreWebAdmin/Admin/Controllers/OrganisationController-Download.cs index 143b3eb..7de69dd 100644 --- a/SaxoniteCoreWebAdmin/Admin/Controllers/OrganisationController-Download.cs +++ b/SaxoniteCoreWebAdmin/Admin/Controllers/OrganisationController-Download.cs @@ -51,7 +51,7 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers return BadRequest(); // Export data. - SaxOrganisationExporter.Config exporterConfig = new SaxOrganisationExporter.Config(SessionContext, GetOrganisationListFilter(model, AccountMgr)); + SaxOrganisationExporter.Config exporterConfig = new SaxOrganisationExporter.Config(SessionContext, DbUpdateInfo, GetOrganisationListFilter(model, AccountMgr)); exporterConfig.Format = SaxOrganisationExporter.ExportFormat.Excel_Open; exporterConfig.IncludeId = StringUtil.ToBool(model.IncludeId); SaxOrganisationExporter exporter = new SaxOrganisationExporter(exporterConfig); diff --git a/SaxoniteCoreWebAdmin/Admin/Controllers/SaxController_Admin.cs b/SaxoniteCoreWebAdmin/Admin/Controllers/SaxController_Admin.cs index 58a9620..d70536a 100644 --- a/SaxoniteCoreWebAdmin/Admin/Controllers/SaxController_Admin.cs +++ b/SaxoniteCoreWebAdmin/Admin/Controllers/SaxController_Admin.cs @@ -188,7 +188,7 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers String keepLoggedInCookieValue = GenerateKeepLoggedInCookieValue(); int cookieExpiresDays = Math.Max(Sax.Config.Security.SignIn.KeepLoggedIn.CookieExpiresDays_Min, Math.Min(Sax.Config.Security.SignIn.KeepLoggedIn.CookieExpiresDays_Max, AppConfig.Security.SignIn.KeepLoggedIn.CookieExpiresDays)); SetResponseCookie(KeepLoggedIn.CookieName, keepLoggedInCookieValue, DateTime.Now.AddDays(cookieExpiresDays), true); - SaLogger.Info(this.GetType().Name + ".SetKeepLoggedInCookie 'Keep Logged In' cookie set. Value: " + keepLoggedInCookieValue); + SaLogger.Debug(this.GetType().Name + ".SetKeepLoggedInCookie 'Keep Logged In' cookie set. Value: " + keepLoggedInCookieValue); } /// Set the 'Keep Logged In' response cookie to expired with no data. diff --git a/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController-Ajax-Database.cs b/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController-Ajax-Database.cs index dbd1077..a18ea6e 100644 --- a/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController-Ajax-Database.cs +++ b/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController-Ajax-Database.cs @@ -63,9 +63,9 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers // Record disposable items as they are created so all can be disposed when needed. using (DisposableCollection disposableItems = new DisposableCollection()) { - - // Core Database connection. - ISacsDatabase db = Internals.CoreDatabase; + // Database connection. + Sax.Database databaseInstance = EnumUtil.ParseEnum(StringUtil.EmptyOnNull(model.DatabaseFilter.Instance), Sax.Database.Core); + ISacsDatabase db = App.GetDatabase(SessionContext, databaseInstance); // Database table row counts. Dictionary tableRowCounts = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -83,7 +83,7 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers } } - // Core database tables. + // Database tables. List tableDfns = db.GetTableDfns(); foreach (DbDfnTable tableDfn in tableDfns.OrderBy(item => item.Name)) { @@ -149,15 +149,15 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers { // Database instance. - Sax.Database databaseInstance = EnumUtil.ParseEnum(StringUtil.EmptyOnNull(model.DatabaseInstance), Sax.Database.Unknown); + Sax.Database databaseInstance = EnumUtil.ParseEnum(StringUtil.EmptyOnNull(model.DatabaseFilter.Instance), Sax.Database.Unknown); if (databaseInstance <= 0) return Json(responseData.SetMessage(messageTitle, "Database instance must be specified")); responseData.Instance = databaseInstance.ToString(); - // Core Database connection. + // Database connection. ISacsDatabase db = App.GetDatabase(SessionContext, databaseInstance); if (db == null) - return Json(responseData.SetMessage(messageTitle, "Unrecognised database instance specified: " + model.DatabaseInstance)); + return Json(responseData.SetMessage(messageTitle, "Unrecognised database instance specified: " + model.DatabaseFilter.Instance)); // Retrieve XML database schema definition. var assembly = typeof(SaxSystem_Dbas).GetTypeInfo().Assembly; @@ -347,8 +347,13 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers if (StringUtil.IsEmpty(model.DatabaseTable.Name)) return Json(responseData.SetMessage(messageTitle, "Table name must be supplied.")); - // Core Database connection. - ISacsDatabase db = Internals.CoreDatabase; + // Database instance. + Sax.Database databaseInstance = EnumUtil.ParseEnum(StringUtil.EmptyOnNull(model.DatabaseTable.Instance), Sax.Database.Unknown); + if (databaseInstance <= 0) + return Json(responseData.SetMessage(messageTitle, "Database instance must be specified")); + + // Database connection. + ISacsDatabase db = App.GetDatabase(SessionContext, databaseInstance); // Table definition. DbDfnTable tableDfn = db.GetTableDfn(model.DatabaseTable.Name, true); diff --git a/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController-Ajax-Logs.cs b/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController-Ajax-Logs.cs index aa49910..4c12057 100644 --- a/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController-Ajax-Logs.cs +++ b/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController-Ajax-Logs.cs @@ -1,14 +1,18 @@ -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; using Sarand.Net.Standard.Base.App; using Sarand.Net.Standard.Base.Bus; using Sarand.Net.Standard.Base.Core; using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; using Saxonite.Net.Core.Web.Admin.Models; using Saxonite.Net.Standard.Base.App; using Saxonite.Net.Standard.Base.Bus; using System; using System.Collections.Generic; +using System.IO; using System.Linq; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Saxonite.Net.Core.Web.Admin.Controllers @@ -20,24 +24,168 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers { //------------------------------------------------------------------- // Database data. - private class LogFileData + private class LogFolderData { public String Name { get; set; } } + private class LogFileData + { + public String Name { get; set; } + public long Size { get; set; } + } //------------------------------------------------------------------- - // Get Database Table List ajax request. + // Get Log Folder List ajax request. + //------------------------------------------------------------------- + private class AjaxResponse_LogFolderList : AjaxResponse_Data + { + // Construction. + public AjaxResponse_LogFolderList(SaxModel_Admin model) : base(model) { } + // Log file list. + public List Folders { get; } = new List(); + } + //------------------------------------------------------------------- + /// + /// Retrieve the list of folders under the root folder. + /// - These should correspond to applications (admin, api, online etc). + /// + [HttpPost] + [Route("System/Ajax/Logs/GetFolderList")] + [Route("System/Ajax/Logs/GetFolders")] + public IActionResult Ajax_GetLogFolderList(Model_System model) + { + String fn = GetType().Name + ".Ajax_GetLogFolderList"; + String messageTitle = Localiser["system.caption.logs"]; + AjaxResponse_LogFolderList responseData = new AjaxResponse_LogFolderList(model); + + // Validate session. + if (!ValidUserSession) + return GetAjaxResult_InvalidSession(responseData); + + // Identify folders in root log folder. + String rootLogFolder = model.LoggingRootFolder; + foreach (String folder in Directory.EnumerateDirectories(rootLogFolder)) + { + String folderName = Path.GetFileName(folder); + if (folderName.IsMatch("^(Online|Admin|Api)$", RegexOptions.IgnoreCase)) + responseData.Folders.Add(new LogFolderData() { Name = folderName }); + } + + // Complete response. + responseData.Success = true; + + return Json(responseData); + } + + //------------------------------------------------------------------- + // Get Log Year Folder List ajax request. + //------------------------------------------------------------------- + private class AjaxResponse_LogYearList : AjaxResponse_Data + { + // Construction. + public AjaxResponse_LogYearList(SaxModel_Admin model) : base(model) { } + // Log file list. + public List Years { get; } = new List(); + } + //------------------------------------------------------------------- + /// + /// Retrieve the list of year folders under the selected folder. + /// + [HttpPost] + [Route("System/Ajax/Logs/GetYearList")] + [Route("System/Ajax/Logs/GetYears")] + public IActionResult Ajax_GetLogYearList(Model_System model) + { + String fn = GetType().Name + ".Ajax_GetLogYearList"; + String messageTitle = Localiser["system.caption.logs"]; + AjaxResponse_LogYearList responseData = new AjaxResponse_LogYearList(model); + + // Validate session. + if (!ValidUserSession) + return GetAjaxResult_InvalidSession(responseData); + + // Store filter properties to session. + SessionData_Admin.System.Logs.Filter.Folder = model.LogsFilter.Folder; + SessionData_Admin.System.Logs.Filter.Year = ""; + SessionData_Admin.System.Logs.Filter.Month = ""; + + // Identify folders in selected log folder. + String logFolder = Path.Combine(model.LoggingRootFolder, model.LogsFilter.Folder); + foreach (String folder in Directory.EnumerateDirectories(logFolder)) + { + String folderName = Path.GetFileName(folder); + if (folderName.IsMatch("^\\d{4}$")) + responseData.Years.Add(new LogFolderData() { Name = folderName }); + } + + // Complete response. + responseData.Success = true; + + return Json(responseData); + } + + //------------------------------------------------------------------- + // Get Log Month Folder List ajax request. + //------------------------------------------------------------------- + private class AjaxResponse_LogMonthList : AjaxResponse_Data + { + // Construction. + public AjaxResponse_LogMonthList(SaxModel_Admin model) : base(model) { } + // Log file list. + public List Months { get; } = new List(); + } + //------------------------------------------------------------------- + /// + /// Retrieve the list of year folders under the selected folder. + /// + [HttpPost] + [Route("System/Ajax/Logs/GetMonthList")] + [Route("System/Ajax/Logs/GetMonths")] + public IActionResult Ajax_GetLogMonthList(Model_System model) + { + String fn = GetType().Name + ".Ajax_GetLogMonthList"; + String messageTitle = Localiser["system.caption.logs"]; + AjaxResponse_LogMonthList responseData = new AjaxResponse_LogMonthList(model); + + // Validate session. + if (!ValidUserSession) + return GetAjaxResult_InvalidSession(responseData); + + // Store filter properties to session. + SessionData_Admin.System.Logs.Filter.Folder = model.LogsFilter.Folder; + SessionData_Admin.System.Logs.Filter.Year = model.LogsFilter.Year; + SessionData_Admin.System.Logs.Filter.Month = ""; + //SessionData_Admin.System.Logs.Filter.Month = model.LogsFilter.Month; + + // Identify folders in selected year folder. + String logFolder = Path.Combine(model.LoggingRootFolder, model.LogsFilter.Folder, model.LogsFilter.Year); + foreach (String folder in Directory.EnumerateDirectories(logFolder)) + { + String folderName = Path.GetFileName(folder); + if (folderName.IsMatch("^\\d{6}$")) + responseData.Months.Add(new LogFolderData() { Name = folderName }); + } + + // Complete response. + responseData.Success = true; + + return Json(responseData); + } + + //------------------------------------------------------------------- + // Get Log File List ajax request. //------------------------------------------------------------------- private class AjaxResponse_LogFileList : AjaxResponse_Data { // Construction. public AjaxResponse_LogFileList(SaxModel_Admin model) : base(model) { } // Log file list. - public List Tables { get; } = new List(); + public List Files { get; } = new List(); } //------------------------------------------------------------------- [HttpPost] - [Route("System/Ajax/GetLogFileList")] + [Route("System/Ajax/Logs/GetFileList")] + [Route("System/Ajax/Logs/GetFiles")] public IActionResult Ajax_GetLogFileList(Model_System model) { String fn = GetType().Name + ".Ajax_GetLogFileList"; @@ -48,6 +196,97 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers if (!ValidUserSession) return GetAjaxResult_InvalidSession(responseData); + // Store filter properties to session. + SessionData_Admin.System.Logs.Filter.Folder = model.LogsFilter.Folder; + SessionData_Admin.System.Logs.Filter.Year = model.LogsFilter.Year; + SessionData_Admin.System.Logs.Filter.Month = model.LogsFilter.Month; + + // Identify folders in selected year folder. + String logFolder = Path.Combine(model.LoggingRootFolder, model.LogsFilter.Folder, model.LogsFilter.Year, model.LogsFilter.Month); + DirectoryInfo folder = new DirectoryInfo(logFolder); + foreach (FileInfo file in folder.EnumerateFiles()) + { + responseData.Files.Add(new LogFileData() { Name = file.Name, Size = file.Length }); + } + + // Complete response. + responseData.Success = true; + + return Json(responseData); + } + + //------------------------------------------------------------------- + // Get Log File ajax request. + //------------------------------------------------------------------- + private class AjaxResponse_LogFile : AjaxResponse_Data + { + // Construction. + public AjaxResponse_LogFile(SaxModel_Admin model) : base(model) { } + // Log file. + public class LogFileData + { + public String Path { get; set; } + public String Name { get; set; } + public String Data { get; set; } + public String Html { get; set; } = ""; + } + public LogFileData File { get; } = new LogFileData(); + } + //------------------------------------------------------------------- + [HttpPost] + [Route("System/Ajax/Logs/GetFile")] + [Route("System/Ajax/Logs/GetLogFile")] + public IActionResult Ajax_GetLogFile(Model_System model) + { + String fn = GetType().Name + ".Ajax_GetLogFile"; + String messageTitle = Localiser["system.caption.logs"]; + AjaxResponse_LogFile responseData = new AjaxResponse_LogFile(model); + + // Validate session. + if (!ValidUserSession) + return GetAjaxResult_InvalidSession(responseData); + + // Store filter properties to session. + SessionData_Admin.System.Logs.Filter.Folder = model.LogsFilter.Folder; + SessionData_Admin.System.Logs.Filter.Year = model.LogsFilter.Year; + SessionData_Admin.System.Logs.Filter.Month = model.LogsFilter.Month; + + // Identify folders in selected year folder. + responseData.File.Path = Path.Combine(model.LoggingRootFolder, model.LogsFilter.Folder, model.LogsFilter.Year, model.LogsFilter.Month, model.LogsFilter.Filename); + responseData.File.Name = Path.GetFileName(responseData.File.Path); + try + { + String[] fileLines = System.IO.File.ReadAllLines(responseData.File.Path); + responseData.File.Data = String.Join("\n", fileLines); + // Construct html data. + foreach (var fileLine in fileLines) + { + String line = fileLine; + List classNames = new List(); + if (fileLine.IsMatch("^\t{2}")) + { + line = Regex.Replace(fileLine, "^\t+", ""); + classNames.Add("tab2"); + } + if (fileLine.IsMatch("^\t")) + { + line = Regex.Replace(fileLine, "^\t", ""); + classNames.Add("tab"); + } + if (line.IsMatch("\\d{8}:\\d{6}\\s+(error|err)\\s+", RegexOptions.IgnoreCase)) + classNames.Add("err"); + else if (line.IsMatch("\\d{8}:\\d{6}\\s+(warn|wrn)\\s+", RegexOptions.IgnoreCase)) + classNames.Add("wrn"); + else if (line.IsMatch("\\d{8}:\\d{6}\\s+(info|inf)\\s+", RegexOptions.IgnoreCase)) + classNames.Add("inf"); + responseData.File.Html += $"
" + line + "
"; + } + } + catch (Exception exc) + { + SaLogger.Warn($"{SysUtil.Fn} {ExceptionUtil.GetLogMessage(exc, "reading log file", 0)}"); + } + // Complete response. responseData.Success = true; diff --git a/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController.cs b/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController.cs index 83d298a..a67715a 100644 --- a/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController.cs +++ b/SaxoniteCoreWebAdmin/Admin/Controllers/SystemController.cs @@ -68,6 +68,10 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers return RedirectToAction("", ""); model.AdditionalFiles_JS.Add("js/sax-sys-logs.js"); + model.LogsFilter.Folder = StringUtil.OnBlank(SessionData_Admin.System.Logs.Filter.Folder, "Admin"); + model.LogsFilter.Year = StringUtil.OnBlank(SessionData_Admin.System.Logs.Filter.Year, DateTime.Today.ToString("yyyy")); + model.LogsFilter.Month = StringUtil.OnBlank(SessionData_Admin.System.Logs.Filter.Month, DateTime.Today.ToString("yyyyMM")); + return View(model); } diff --git a/SaxoniteCoreWebAdmin/Admin/Models/Model_System.cs b/SaxoniteCoreWebAdmin/Admin/Models/Model_System.cs index 843358c..353fbd5 100644 --- a/SaxoniteCoreWebAdmin/Admin/Models/Model_System.cs +++ b/SaxoniteCoreWebAdmin/Admin/Models/Model_System.cs @@ -1,8 +1,12 @@ -using Saxonite.Net.Core.Web.Base.App; +using Microsoft.AspNetCore.Mvc.Rendering; +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Core; +using Saxonite.Net.Core.Web.Base.App; using Saxonite.Net.Core.Web.Base.Models; using System; using System.Collections.Generic; using System.Linq; +using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Saxonite.Net.Core.Web.Admin.Models @@ -19,25 +23,43 @@ namespace Saxonite.Net.Core.Web.Admin.Models //------------------------------------------------------------------- // Properties. - public String DatabaseInstance { get; set; } //------------------------------------------------------------------- // Database page properties. public class DatabaseFilterData { + public String Instance { get; set; } public String Search { get; set; } } public DatabaseFilterData DatabaseFilter { get; } = new DatabaseFilterData(); public class DatabaseTableData { + public String Instance { get; set; } public String Name { get; set; } } public DatabaseTableData DatabaseTable { get; } = new DatabaseTableData(); + public IEnumerable GetDatabases() + { + List items = new List(); + if (SessionData?.ValidUserSession ?? false) + { + items.Add("Core", Localiser["label.core"]); + items.Add("Reference", Localiser["label.reference"]); + items.Add("Support", Localiser["label.support"]); + } + return new SelectList(items, "Code", "Desc"); + } + //------------------------------------------------------------------- // Logs page properties. + public String LoggingRootFolder { get; } = Regex.Replace(SaLogger.LogFolder, "[\\\\/]Admin$", ""); + // Log file filter. public class LogsFilterData { + public String Folder { get; set; } + public String Year { get; set; } + public String Month { get; set; } public String Filename { get; set; } } public LogsFilterData LogsFilter { get; } = new LogsFilterData(); diff --git a/SaxoniteCoreWebAdmin/Admin/Procs/SaxOrganisationExporter.cs b/SaxoniteCoreWebAdmin/Admin/Procs/SaxOrganisationExporter.cs index 8bec81f..b4547fe 100644 --- a/SaxoniteCoreWebAdmin/Admin/Procs/SaxOrganisationExporter.cs +++ b/SaxoniteCoreWebAdmin/Admin/Procs/SaxOrganisationExporter.cs @@ -33,7 +33,7 @@ namespace Saxonite.Net.Core.Web.Admin.Procs // Process configuration. public new class Config : SaxProcess_Admin.Config { - public Config(SaxSessionContext sessionContext, SaxOrganisation.Params prmOrganisation) : base(sessionContext) + public Config(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo, SaxOrganisation.Params prmOrganisation) : base(sessionContext, dbUpdateInfo) { PrmOrganisation = prmOrganisation; } @@ -138,7 +138,7 @@ namespace Saxonite.Net.Core.Web.Admin.Procs control.Spreadsheet = new SaMsSpreadsheet_POI(); control.Spreadsheet.CreateWorkbook(); control.Spreadsheet.WorksheetName = "Organisations"; - control.Spreadsheet.ApplyDefaultStyle(GetExceldefaultWorkbookStyle()); + control.Spreadsheet.ApplyDefaultStyle(GetExcelDefaultWorkbookStyle()); // Columns. ColumnDfn colId = AccountMgr.GetOrganisationColumnDfn(SaxOrganisation.Column.Id); diff --git a/SaxoniteCoreWebAdmin/Admin/Procs/SaxOrganisationUploader.cs b/SaxoniteCoreWebAdmin/Admin/Procs/SaxOrganisationUploader.cs index 974f678..87e032b 100644 --- a/SaxoniteCoreWebAdmin/Admin/Procs/SaxOrganisationUploader.cs +++ b/SaxoniteCoreWebAdmin/Admin/Procs/SaxOrganisationUploader.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Http; using Sarand.Net.Standard.Base.App; using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; using Sarand.Net.Standard.Base.Helpers; using Sarand.Net.Standard.Base.Utils; using Sarand.Net.Standard.Proc.Excel; @@ -28,7 +29,7 @@ namespace Saxonite.Net.Core.Web.Admin.Procs // Process configuration. public new class Config : SaxProcess_Admin.Config { - public Config(SaxSessionContext sessionContext, IFormFile dataFile) : base(sessionContext) + public Config(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo, IFormFile dataFile) : base(sessionContext, dbUpdateInfo) { this.DataFile = new UploadFileData(dataFile); } diff --git a/SaxoniteCoreWebAdmin/Admin/Procs/SaxProcess_Admin.cs b/SaxoniteCoreWebAdmin/Admin/Procs/SaxProcess_Admin.cs index 2f54a89..1d6dff2 100644 --- a/SaxoniteCoreWebAdmin/Admin/Procs/SaxProcess_Admin.cs +++ b/SaxoniteCoreWebAdmin/Admin/Procs/SaxProcess_Admin.cs @@ -1,5 +1,7 @@ -using Sarand.Net.Standard.Proc.Excel; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Proc.Excel; using Sarand.Net.Standard.Proc.Procs; +using Saxonite.Net.Core.Web.Base.Procs; using Saxonite.Net.Standard.Base.App; using Saxonite.Net.Standard.Base.Procs; using System; @@ -9,13 +11,13 @@ using System.Text; namespace Saxonite.Net.Core.Web.Admin.Procs { //======================================================================= - public abstract class SaxProcess_Admin : SaxProcess_Base + public abstract class SaxProcess_Admin : SaxProcess_Web { //------------------------------------------------------------------- // Definitions. - public new class Config : SaxProcess_Base.Config + public new class Config : SaxProcess_Web.Config { - protected Config(SaxSessionContext sessionContext) : base(sessionContext) + protected Config(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo) : base(sessionContext, dbUpdateInfo) { } } @@ -33,28 +35,15 @@ namespace Saxonite.Net.Core.Web.Admin.Procs //------------------------------------------------------------------- // Excel Spreadsheet utilities. //------------------------------------------------------------------- - protected SaMsExcelColumnHeading_Config GetExcelColumnHeadingConfig() + protected override SaMsExcelColumnHeading_Config GetExcelColumnHeadingConfig() { - SaMsExcelColumnHeading_Config configHeading = new SaMsExcelColumnHeading_Config(); - configHeading.FontAttr.Name = "Arial"; - configHeading.FontAttr.HeightInPoints = 10; - configHeading.FontAttr.ColourIndex = SaXlColourIndex.DarkBlue; - configHeading.FontAttr.Bold = true; - configHeading.HeadingTextWrap = true; - configHeading.ForegroundColourIndex = SaXlColourIndex.LightYellow; - configHeading.BorderWeight = SaXlBorderWeight.Medium; + SaMsExcelColumnHeading_Config configHeading = base.GetExcelColumnHeadingConfig(); return configHeading; } - protected SaMsExcelStyleAttr GetExceldefaultWorkbookStyle() + protected override SaMsExcelStyleAttr GetExcelDefaultWorkbookStyle() { - SaMsExcelStyleAttr styleAttr = new SaMsExcelStyleAttr(); - styleAttr.FontAttr.Name = "Arial"; - styleAttr.FontAttr.HeightInPoints = 9; - styleAttr.FontAttr.ColourIndex = SaXlColourIndex.Black; - styleAttr.HorizontalAlignment = (short)XlHAlign.xlHAlignLeft; - styleAttr.VerticalAlignment = (short)XlVAlign.xlVAlignTop; - styleAttr.WrapText = true; + SaMsExcelStyleAttr styleAttr = base.GetExcelDefaultWorkbookStyle(); return styleAttr; } diff --git a/SaxoniteCoreWebAdmin/Localisation/SaxAdminProperties.resx b/SaxoniteCoreWebAdmin/Localisation/SaxAdminProperties.resx index 26172b2..612ac5d 100644 --- a/SaxoniteCoreWebAdmin/Localisation/SaxAdminProperties.resx +++ b/SaxoniteCoreWebAdmin/Localisation/SaxAdminProperties.resx @@ -273,6 +273,9 @@ Contact + + Core + Country @@ -327,6 +330,9 @@ First name + + Folder + Forgotten password? @@ -348,6 +354,9 @@ Indices + + Instance + ISO2 code @@ -387,6 +396,9 @@ Method + + Month + Name @@ -474,6 +486,9 @@ Roles + + Root folder + Rows @@ -552,6 +567,9 @@ Value + + Year + Yes @@ -756,18 +774,24 @@ Sports - - Core Database Schema - System - Database + + Core Database + + + Reference Database + + + Database schemas + + + Support Database + System - Logs - - Support Database Schema - Database schema is valid. diff --git a/SaxoniteCoreWebAdmin/SaxoniteCoreWebAdmin.csproj b/SaxoniteCoreWebAdmin/SaxoniteCoreWebAdmin.csproj index 51db26a..5bc5e50 100644 --- a/SaxoniteCoreWebAdmin/SaxoniteCoreWebAdmin.csproj +++ b/SaxoniteCoreWebAdmin/SaxoniteCoreWebAdmin.csproj @@ -10,7 +10,7 @@ - + diff --git a/SaxoniteCoreWebAdmin/Views/Home/Index.cshtml b/SaxoniteCoreWebAdmin/Views/Home/Index.cshtml index 0cb94d0..c0cc304 100644 --- a/SaxoniteCoreWebAdmin/Views/Home/Index.cshtml +++ b/SaxoniteCoreWebAdmin/Views/Home/Index.cshtml @@ -55,44 +55,56 @@ @* Database Schema form. *@ @using (@Html.BeginForm(FormMethod.Post, new { @id = "frmDatabaseSchema" })) { - + } -@* Database Schema - Core *@ -
+@* Database Schema Verification *@ +
-
@Localiser["system.caption.core.database.schema"]
+
@Localiser["system.caption.database.schemas"]
-
-
-
- @* Db Schema templates *@ -
-
-
@(Localiser["label.table"]):
-
-
-
@(Localiser["label.index"]):
-
@(Localiser["label.column"]):
-
-
-
-
-
- -
- -@* Database Schema - Support *@ -
- -
-
@Localiser["system.caption.support.database.schema"]
-
-
-
-
+ + @* Database Schema - Core *@ +
+ +
+
@Localiser["system.caption.database.core"]
+
+
+
+
+
+ +
+ + @* Database Schema - Reference *@ +
+ +
+
@Localiser["system.caption.database.reference"]
+
+
+
+
+
+ +
+ + @* Database Schema - Reference *@ +
+ +
+
@Localiser["system.caption.database.support"]
+
+
+
+
+
+ +
+
@* Db Schema templates *@
diff --git a/SaxoniteCoreWebAdmin/Views/System/Database.cshtml b/SaxoniteCoreWebAdmin/Views/System/Database.cshtml index d4f93b8..a9f4d90 100644 --- a/SaxoniteCoreWebAdmin/Views/System/Database.cshtml +++ b/SaxoniteCoreWebAdmin/Views/System/Database.cshtml @@ -17,8 +17,10 @@ @using (@Html.BeginForm(FormMethod.Post, new { @id = "frmDbTableFilter", @class = "sax-form", @onSubmit = "return false;" })) {
-
@Localiser["label.search"]
-
@Html.TextBoxFor(model => model.DatabaseFilter.Search, new { @id = "ifFilterDatabaseTable", @class = "FilterDatabaseTable", @maxlength = "32" })
+
@Localiser["label.instance"]
+
@Html.DropDownListFor(model => model.DatabaseFilter.Instance, Model.GetDatabases(), new { @id = "cbDatabaseFilterInstance", @class = "DatabaseFilterInstance" })
+
@Localiser["label.search"]
+
@Html.TextBoxFor(model => model.DatabaseFilter.Search, new { @id = "ifDatabaseFilterSearch", @class = "DatabaseFilterSearch", @maxlength = "32" })
}
@@ -54,6 +56,7 @@ @using (@Html.BeginForm(FormMethod.Post, new { @id = "frmDbTableName", @onSubmit = "return false;" })) { + @Html.HiddenFor(model => model.DatabaseTable.Instance, new { @class = "DatabaseTableInstance" }) @Html.HiddenFor(model => model.DatabaseTable.Name, new { @class = "DatabaseTableName" }) } @@ -70,6 +73,7 @@
@using (@Html.BeginForm(FormMethod.Post, new { @id = "frmDbTable", @onSubmit = "return false;" })) { + @Html.HiddenFor(model => model.DatabaseTable.Instance, new { @class = "DatabaseTableInstance" }) @Html.HiddenFor(model => model.DatabaseTable.Name, new { @class = "DatabaseTableName" }) } diff --git a/SaxoniteCoreWebAdmin/Views/System/Logs.cshtml b/SaxoniteCoreWebAdmin/Views/System/Logs.cshtml index ed981c6..e19e808 100644 --- a/SaxoniteCoreWebAdmin/Views/System/Logs.cshtml +++ b/SaxoniteCoreWebAdmin/Views/System/Logs.cshtml @@ -4,7 +4,43 @@ ViewData["Title"] = "System - Logs"; } -
+ + +
@@ -16,29 +52,50 @@
@using (@Html.BeginForm(FormMethod.Post, new { @id = "frmLogsFilter", @class = "sax-form", @onSubmit = "return false;" })) { + +
+
@Localiser["label.root.folder"]
+
@(Model.LoggingRootFolder)
+
+
+
@Localiser["label.folder"]
+
+
+
+
@Localiser["label.year"]
+
+
-
@Localiser["label.filename"]
-
@Html.TextBoxFor(model => model.LogsFilter.Filename, new { @id = "ifFilterLogFilename", @class = "FilterLogFilename", @maxlength = "32" })
+
@Localiser["label.month"]
+
}
- -
- -
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+ + \ No newline at end of file diff --git a/SaxoniteCoreWebAdmin/appsettings.Machine.Sarand602.json b/SaxoniteCoreWebAdmin/appsettings.Machine.Sarand602.json index 4a14b71..b78ed33 100644 --- a/SaxoniteCoreWebAdmin/appsettings.Machine.Sarand602.json +++ b/SaxoniteCoreWebAdmin/appsettings.Machine.Sarand602.json @@ -53,7 +53,7 @@ "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Admin\\Docs" }, "Logging": { - "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Admin\\Logs" + "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Logs" }, "Variants": [ { @@ -63,7 +63,7 @@ "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Admin\\Docs" }, "Logging": { - "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Admin\\Logs" + "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Logs" } } ] diff --git a/SaxoniteCoreWebAdmin/wwwroot/css/sax-form.css b/SaxoniteCoreWebAdmin/wwwroot/css/sax-form.css index 46b6800..a0a2def 100644 --- a/SaxoniteCoreWebAdmin/wwwroot/css/sax-form.css +++ b/SaxoniteCoreWebAdmin/wwwroot/css/sax-form.css @@ -16,6 +16,17 @@ overflow: hidden; } +.sax-panel-info .sax-panel-info +{ + margin: 6px auto; + padding: 0; + background-color: #fff; + border: solid 1px #979797; + border-color: var(--color-primary); + border-radius: 4px; + overflow: hidden; +} + .sax-panel-form.security { max-width: 520px; @@ -38,6 +49,11 @@ border-color: var(--color-primary); } +.sax-panel-info .sax-panel-info > .sax-header +{ + padding: 6px 4px; +} + .sax-panel-info > .sax-header .sax-caption, .sax-panel-form > .sax-header .sax-caption { @@ -46,6 +62,11 @@ color: var(--color-primary-dark); } +.sax-panel-info .sax-panel-info > .sax-header .sax-caption +{ + font-size: 1.25rem; +} + .sax-panel-info > .sax-header .sax-action img:hover, .sax-panel-form > .sax-header .sax-action img:hover { @@ -68,6 +89,11 @@ padding: 8px 12px; } +.sax-panel-info .sax-panel-info > .sax-content +{ + padding: 4px 8px; +} + .sax-panel-section.sax-edit .sax-panel-info, .sax-panel-section.sax-populating .sax-button-action.edit, .sax-panel-section .sax-panel-form @@ -174,7 +200,7 @@ { display: none; margin-top: 8px; - padding-left: 24px; + padding-left: 16px; font-size: 1.00rem; background-position: left top; background-repeat: no-repeat; diff --git a/SaxoniteCoreWebAdmin/wwwroot/js/sax-home.js b/SaxoniteCoreWebAdmin/wwwroot/js/sax-home.js index 25b0824..e1ab125 100644 --- a/SaxoniteCoreWebAdmin/wwwroot/js/sax-home.js +++ b/SaxoniteCoreWebAdmin/wwwroot/js/sax-home.js @@ -72,7 +72,7 @@ if (sax.awaitingLogin) return; if (!ah.awaitingSchemaResponse) { - let $pnlSchema = $('.sax-panel-results.DbSchema.' + instance); + let $pnlSchema = $('.sax-panel-results .sax-panel-info.DbSchema.' + instance); var $items = $('.sax-panel-item-list', $pnlSchema).fadeOut(200).empty(); var $msgs = $('.sax-panel-messages', $pnlSchema).hide().empty().append($('
' + sax.msg.dataQuerying + '
')).fadeIn(200); } @@ -85,20 +85,25 @@ { //sax.debug('handleDbSchemaResponse', response); delete ah.awaitingSchemaResponse; - let $pnlSchema = $('.sax-panel-results.DbSchema.' + response.instance) ; + let $pnlSchema = $('.sax-panel-results .sax-panel-info.DbSchema.' + response.instance) ; var $msgs = $('.sax-panel-messages', $pnlSchema).hide().empty(); var $items = $('.sax-panel-item-list', $pnlSchema).hide().empty(); - var $tmpl = $('.sax-panel-item-template .sax-panel-item.DbSchemaItem', $pnlSchema); if (!response.success) return; - if (response.instance == 'Core') ah.toSchema = setTimeout(function () { ah.refreshDbSchema('Support'); }, 250); + if (response.instance == 'Core') ah.toSchema = setTimeout(function () { ah.refreshDbSchema('Reference'); }, 250); + if (response.instance == 'Reference') ah.toSchema = setTimeout(function () { ah.refreshDbSchema('Support'); }, 250); // Items. var items = response.items; if (!items.length) return $msgs.append($('
' + sax.msg.dbSchemaValid + '
')).fadeIn(500); + sax.debug(ah.getDbSchemaTemplate()); for (let itemIdx = 0; itemIdx < items.length; itemIdx++) - $items.append(ah.populateDbSchemaItem($tmpl.clone(), items[itemIdx])); + $items.append(ah.populateDbSchemaItem(ah.getDbSchemaTemplate(), items[itemIdx])); $items.slideDown(750); } + ah.getDbSchemaTemplate = function () + { + return $('.sax-panel-results .sax-panel-item-template .sax-panel-item.DbSchemaItem').clone(); + } ah.populateDbSchemaItem = function ($item, item) { if (!item) return; @@ -118,6 +123,7 @@ $pnl.appStats = $('.sax-panel-results.ApplicationStats'); $frm.dbSchema = $('#frmDatabaseSchema'); $pnl.dbSchemaCore = $('.sax-panel-results.DbSchema.Core'); + $pnl.dbSchemaReference = $('.sax-panel-results.DbSchema.Reference'); $pnl.dbSchemaSupport = $('.sax-panel-results.DbSchema.Support'); ah.toStats = setTimeout(ah.refreshApplicationStats, 400); diff --git a/SaxoniteCoreWebAdmin/wwwroot/js/sax-main.js b/SaxoniteCoreWebAdmin/wwwroot/js/sax-main.js index 63ab918..77a5713 100644 --- a/SaxoniteCoreWebAdmin/wwwroot/js/sax-main.js +++ b/SaxoniteCoreWebAdmin/wwwroot/js/sax-main.js @@ -56,12 +56,12 @@ if (file.filename) return filename.split('.').pop(); return ""; } - sax.formatFileSize = function (size) + sax.formatFileSize = function (size, decimals=0) { - if (size / 10 ** 9 > 1) return Math.floor(size / 10 ** 9) + 'Gb'; - if (size / 10 ** 6 > 1) return Math.floor(size / 10 ** 6) + 'Mb'; - if (size / 10 ** 3 > 1) return Math.floor(size / 10 ** 3) + 'Kb'; - return size + 'bytes'; + if (size / 10 ** 9 > 1) return (size / 10.0 ** 9).toFixed(decimals) + ' Gb'; + if (size / 10 ** 6 > 1) return (size / 10.0 ** 6).toFixed(decimals) + ' Mb'; + if (size / 10 ** 3 > 1) return (size / 10.0 ** 3).toFixed(decimals) + ' Kb'; + return size + ' bytes'; } sax.escapeRegExp = function (val) { @@ -196,8 +196,8 @@ { $dlg.dialog( { - minWidth: null, maxWidth: null, width: Math.min(width || 400, $(win).width() * .90), - minHeight: null, maxHeight: null, height: Math.min(height || 320, $(win).innerHeight() * .90) + minWidth: null, maxWidth: null, width: Math.min(width || 400, $(win).width() * .95), + minHeight: null, maxHeight: null, height: Math.min(height || 320, $(win).innerHeight() * .95) }).dialog('open'); return $dlg; } diff --git a/SaxoniteCoreWebAdmin/wwwroot/js/sax-sys-db.js b/SaxoniteCoreWebAdmin/wwwroot/js/sax-sys-db.js index 461db63..e90c44a 100644 --- a/SaxoniteCoreWebAdmin/wwwroot/js/sax-sys-db.js +++ b/SaxoniteCoreWebAdmin/wwwroot/js/sax-sys-db.js @@ -59,6 +59,7 @@ sd.viewItem = function (item) { //sax.debug('viewItem', item.tableName, $frm.tableName, $('.DatabaseTableName', $frm.tableName)) + $('.DatabaseTableInstance', $frm.tableName).val($('.DatabaseFilterInstance', $frm.filter).val()); $('.DatabaseTableName', $frm.tableName).val(item.tableName); sax.ajax.updateItem = sax.ajax.updateItem || { url: sax.url.base + 'System/Ajax/GetDatabaseTable', formId: 'frmDbTableName', callbackFn: sd.onViewItem }; sax.doAjaxRequest(sax.ajax.updateItem, 50); @@ -148,7 +149,8 @@ $('.sax-input').on('input', function () { sax.clearControlError(this); }); $frm.filter = $('#frmDbTableFilter'); - $('.FilterDatabaseTable', $frm.filter).on('input', function () { sd.refreshResults(250); }); + $('.DatabaseFilterInstance', $frm.filter).on('change', function () { sd.refreshResults(250); }); + $('.DatabaseFilterSearch', $frm.filter).on('input', function () { sd.refreshResults(250); }); $frm.tableName = $('#frmDbTableName'); $frm.table = $('#frmDbTable'); diff --git a/SaxoniteCoreWebAdmin/wwwroot/js/sax-sys-logs.js b/SaxoniteCoreWebAdmin/wwwroot/js/sax-sys-logs.js index 6a31426..c7f0087 100644 --- a/SaxoniteCoreWebAdmin/wwwroot/js/sax-sys-logs.js +++ b/SaxoniteCoreWebAdmin/wwwroot/js/sax-sys-logs.js @@ -5,13 +5,211 @@ (function (win, doc, undef) { "use strict"; - sax.itemIdPrefix = 'Itm_'; + let sl = sax.sysLogs = { data: {}, $pnl: {}, $frm: {}, $ctrl: {}, $dlg: {} }; + let $pnl = sl.$pnl; let $frm = sl.$frm; let $ctrl = sl.$ctrl; let $dlg = sl.$dlg; //-------------------------------------------------------------- + sl.refreshFolders = function (delay) + { + if (!sl.data.awaitingRefreshFoldersResponse) + { + var $items = $('.sax-panel-item-list', $pnl.results).fadeOut(200).empty(); + $pnl.msgs.hide().empty().append($('
' + sax.msg.dataQuerying + '
')).fadeIn(200); + } + sax.ajax.refreshFolders = sax.ajax.refreshFolders || { url: sax.url.base + 'System/Ajax/Logs/GetFolders', formId: sl.$frm.filter.prop('id'), callbackFn: sl.doRefreshFolders }; + sax.doAjaxRequest(sax.ajax.refreshFolders, delay || 50); + sl.data.awaitingRefreshFoldersResponse = true; + } + sl.doRefreshFolders = function (response) + { + //sax.debug('doRefreshFolders', response); + delete sl.data.awaitingRefreshFoldersResponse; + sl.clearFilterFolders(); + sax.refreshControlValues(response.controlValues); + $pnl.msgs.hide().empty(); + if (!response.success) return; + // Folders. + var items = response.folders; + if (!items.length) + return $pnl.msgs.append($('
' + sax.msg.dataNoneFound + '
')).fadeIn(500); + for (let itemIdx = 0; itemIdx < items.length; itemIdx++) + $ctrl.cbFolders.append($('')); + if (sax.data.logFolder) $ctrl.cbFolders.val(sax.data.logFolder); + delete sax.data.logFolder; + $ctrl.cbFolders.trigger('change'); + } + + //-------------------------------------------------------------- + sl.clearFilterFolders = function () + { + sl.clearFilterYears(); + $('option', $ctrl.cbFolders).remove(); + } + sl.clearFilterYears = function () + { + sl.clearFilterMonths(); + $('option', $ctrl.cbYears).remove(); + } + sl.clearFilterMonths = function () + { + sl.clearFiles(); + $('option', $ctrl.cbMonths).remove(); + } + sl.clearFiles = function () + { + $('.sax-panel-messages', $pnl.results).hide().empty(); + $('.sax-panel-item-list', $pnl.results).hide().empty(); + } + + //-------------------------------------------------------------- + sl.refreshYears = function (delay) + { + if (!sl.data.awaitingRefreshYearsResponse) + { + var $items = $('.sax-panel-item-list', $pnl.results).fadeOut(200).empty(); + $pnl.msgs.hide().empty().append($('
' + sax.msg.dataQuerying + '
')).fadeIn(200); + } + sax.ajax.refreshYears = sax.ajax.refreshYears || { url: sax.url.base + 'System/Ajax/Logs/GetYears', formId: sl.$frm.filter.prop('id'), callbackFn: sl.doRefreshYears }; + sax.doAjaxRequest(sax.ajax.refreshYears, delay || 50); + sl.data.awaitingRefreshYearsResponse = true; + } + sl.doRefreshYears = function (response) + { + //sax.debug('doRefreshYears', response); + delete sl.data.awaitingRefreshYearsResponse; + sl.clearFilterYears(); + sax.refreshControlValues(response.controlValues); + $pnl.msgs.hide().empty(); + if (!response.success) return; + // Years. + var items = response.years; + if (!items.length) + return $pnl.msgs.append($('
' + sax.msg.dataNoneFound + '
')).fadeIn(500); + for (let itemIdx = 0; itemIdx < items.length; itemIdx++) + $ctrl.cbYears.append($('')); + if (sax.data.logYear) $ctrl.cbYears.val(sax.data.logYear); + delete sax.data.logYear; + $ctrl.cbYears.trigger('change'); + } + + //-------------------------------------------------------------- + sl.refreshMonths = function (delay) + { + if (!sl.data.awaitingRefreshMonthsResponse) + { + var $items = $('.sax-panel-item-list', $pnl.results).fadeOut(200).empty(); + $pnl.msgs.hide().empty().append($('
' + sax.msg.dataQuerying + '
')).fadeIn(200); + } + sax.ajax.refreshMonths = sax.ajax.refreshMonths || { url: sax.url.base + 'System/Ajax/Logs/GetMonths', formId: sl.$frm.filter.prop('id'), callbackFn: sl.doRefreshMonths }; + sax.doAjaxRequest(sax.ajax.refreshMonths, delay || 50); + sl.data.awaitingRefreshMonthsResponse = true; + } + sl.doRefreshMonths = function (response) + { + //sax.debug('doRefreshMonths', response); + delete sl.data.awaitingRefreshMonthsResponse; + sl.clearFilterMonths(); + sax.refreshControlValues(response.controlValues); + $pnl.msgs.hide().empty(); + if (!response.success) return; + // Months. + var items = response.months; + if (!items.length) + return $pnl.msgs.append($('
' + sax.msg.dataNoneFound + '
')).fadeIn(500); + for (let itemIdx = 0; itemIdx < items.length; itemIdx++) + $ctrl.cbMonths.append($('')); + if (sax.data.logMonth) $ctrl.cbMonths.val(sax.data.logMonth); + delete sax.data.logMonth; + $ctrl.cbMonths.trigger('change'); + } + + //-------------------------------------------------------------- + sl.refreshFiles = function (delay) + { + if (!sl.data.awaitingRefreshFilesResponse) + { + var $items = $('.sax-panel-item-list', $pnl.results).fadeOut(200).empty(); + $pnl.msgs.hide().empty().append($('
' + sax.msg.dataQuerying + '
')).fadeIn(200); + } + sax.ajax.refreshFiles = sax.ajax.refreshFiles || { url: sax.url.base + 'System/Ajax/Logs/GetFiles', formId: sl.$frm.filter.prop('id'), callbackFn: sl.doRefreshFiles }; + sax.doAjaxRequest(sax.ajax.refreshFiles, delay || 50); + sl.data.awaitingRefreshFilesResponse = true; + } + sl.doRefreshFiles = function (response) + { + sax.debug('doRefreshFiles', response); + delete sl.data.awaitingRefreshFilesResponse; + sl.clearFiles(); + sax.refreshControlValues(response.controlValues); + $pnl.msgs.hide().empty(); + var $items = $('.sax-panel-item-list', $pnl.results).hide().empty(); + if (!response.success) return; + // Files. + var items = response.files; + if (!items.length) + return $pnl.msgs.append($('
' + sax.msg.dataNoneFound + '
')).fadeIn(500); + for (let itemIdx = 0; itemIdx < items.length; itemIdx++) + $items.append(sl.populateItem(sl.getFileTemplate(), items[itemIdx])); + $items.fadeIn(50); + } + sl.populateItem = function ($item,item) + { + if (!item) return $item; + $('.Filename', $item).text(item.name).off('click').on('click', function () { sl.getFile(item.name) }); + $('.Length', $item).text(sax.formatFileSize(item.size,2)); + return $item; + } + sl.getFileTemplate = function () + { + return $('.sax-panel-item-template .sax-panel-item.LogFile', $pnl.results).clone(); + } + + //-------------------------------------------------------------- + sl.getFile = function (filename, delay) + { + $('.FilterLogFilename', $frm.filter).val(filename); + if (!sl.data.awaitingGetFileResponse) + { + $pnl.msgs.hide().empty().append($('
' + sax.msg.dataQuerying + '
')).fadeIn(200); + } + sax.ajax.getFile = sax.ajax.getFile || { url: sax.url.base + 'System/Ajax/Logs/GetFile', formId: sl.$frm.filter.prop('id'), callbackFn: sl.doGetFiles }; + sax.doAjaxRequest(sax.ajax.getFile, delay || 50); + sl.data.awaitingGetFileResponse = true; + } + sl.doGetFiles = function (response) + { + sax.debug('doGetFiles', response); + delete sl.data.awaitingGetFileResponse; + $pnl.msgs.hide().empty(); + if (!response.success) return; + + // Display table details. + $dlg.file.dialog('option', 'title', "File: " + response.file.name || response.popupTitle); + $('.FileData', $dlg.file).html(response.file.html); + sax.openDialog($dlg.file, $(win).width(), $(win).height()); + } //-------------------------------------------------------------- $(function () { + $pnl.logFiles = $('.LogFiles'); + $pnl.filter = $('.sax-panel-filter', $pnl.logFiles); + $pnl.results = $('.sax-panel-results', $pnl.logFiles); + $pnl.msgs = $('.sax-panel-messages', $pnl.results) + + $pnl.filter.on('click', '.sax-action.sax-results-refresh', function () { sl.refreshFiles(); }); + $('.sax-input').on('input', function () { sax.clearControlError(this); }); + + $frm.filter = $('#frmLogsFilter'); + $ctrl.cbFolders = $('#cbFilterLogFolder', $frm.filter).on('change', function () { sl.refreshYears(250); }); + $ctrl.cbYears = $('#cbFilterLogYear', $frm.filter).on('change', function () { sl.refreshMonths(250); }); + $ctrl.cbMonths = $('#cbFilterLogMonth', $frm.filter).on('change', function () { sl.refreshFiles(250); }); + + var opt = sax.dlgOpts(); + opt.buttons[sax.dlg.btn.close] = function () { $(this).dialog('close'); }; + $dlg.file= $('#dlgLogFile').dialog(opt); + + setTimeout(sl.refreshFolders, 250); }); }(window, window.document)); diff --git a/SaxoniteCoreWebOnline/Online/App/SaxApplication_Online.cs b/SaxoniteCoreWebOnline/Online/App/SaxApplication_Online.cs index d56d743..7651a1e 100644 --- a/SaxoniteCoreWebOnline/Online/App/SaxApplication_Online.cs +++ b/SaxoniteCoreWebOnline/Online/App/SaxApplication_Online.cs @@ -39,7 +39,7 @@ namespace Saxonite.Net.Core.Web.Online.App //------------------------------------------------------------------- // Construction. - public SaxApplication_Online(IConfiguration configuration) + public SaxApplication_Online(IConfiguration configuration) : base(Sax.Application.Online) { InitialiseTemporaryLoggingFolder(); try @@ -61,9 +61,9 @@ namespace Saxonite.Net.Core.Web.Online.App // Clear globals. AppInstance = null; // Console helper. - if (ConsoleHelper_Online!= null) + if (ConsoleHelper_Online != null) ConsoleHelper_Online.Dispose(); - ConsoleHelper_Online= null; + ConsoleHelper_Online = null; } base.Dispose(disposing); } @@ -93,28 +93,16 @@ namespace Saxonite.Net.Core.Web.Online.App /// Initialise environment - from internal (above) or unit tests. protected void InitEnvironment(IWebHostEnvironment env) { - Development = env.IsDevelopment(); - environmentName = env.EnvironmentName; - SaLogger.LogFilenamePrefix = "Sax-Web-Onl"; - SaLogger.IncludeHostInFileMessage = false; - SaLogger.IncludeUserInFileMessage = false; + base.InitEnvironment(env, "Sax-Web-Onl"); try { - // Load server configuration. - var builder = new ConfigurationBuilder() - .SetBasePath(env.ContentRootPath) - .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) - .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false) - .AddJsonFile($"appsettings.machine.{SaxSystem.ComputerName}.json", optional: false, reloadOnChange: false) - .AddEnvironmentVariables(); - SaxConfiguration = builder.Build(); - // Application configuration. appConfigs = SaxAppConfigHelper.ExtractAppConfigs(SaxConfiguration.GetSection("AppConfigs")); emailConfigs = SaxEmailConfigHelper.ExtractEmailConfigs(SaxConfiguration.GetSection("EmailConfigs")); + + // Ensure root log folder ends with 'Online' folder. LoggingRootFolder = AppConfig.Logging.RootFolder; - // Ensure root log folder ends with Admin folder. if (!StringUtil.IsBlank(LoggingRootFolder) && !Regex.IsMatch(LoggingRootFolder, "[\\\\/]Online$", RegexOptions.IgnoreCase)) LoggingRootFolder = StringUtil.CombineFilePath(LoggingRootFolder, "Online"); @@ -135,8 +123,9 @@ namespace Saxonite.Net.Core.Web.Online.App LogApplicationStart(SysUtil.Fn); // Session context - only one context available/necessary (for now). - SessionContextData_Online sessionContextData = new SessionContextData_Online(new SaxSessionContext_Web(100, Sax.Application.Online)); + SessionContextData_Online sessionContextData = new SessionContextData_Online(new SaxSessionContext_Web(100, ApplicationType)); ConfigureDatabaseConnection(sessionContextData, Sax.Database.Core); + ConfigureDatabaseConnection(sessionContextData, Sax.Database.Reference); ConfigureDatabaseConnection(sessionContextData, Sax.Database.Support); sessionContexts.Add(sessionContextData.SessionContext.Index, sessionContextData); SessionContext = sessionContextData.SessionContext; diff --git a/SaxoniteCoreWebOnline/SaxoniteCoreWebOnline.csproj b/SaxoniteCoreWebOnline/SaxoniteCoreWebOnline.csproj index 91771e1..9b42383 100644 --- a/SaxoniteCoreWebOnline/SaxoniteCoreWebOnline.csproj +++ b/SaxoniteCoreWebOnline/SaxoniteCoreWebOnline.csproj @@ -10,7 +10,7 @@ - + diff --git a/SaxoniteCoreWebOnline/appsettings.Machine.Sarand602.json b/SaxoniteCoreWebOnline/appsettings.Machine.Sarand602.json index c7e2acd..0382111 100644 --- a/SaxoniteCoreWebOnline/appsettings.Machine.Sarand602.json +++ b/SaxoniteCoreWebOnline/appsettings.Machine.Sarand602.json @@ -48,7 +48,7 @@ "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Online\\Docs" }, "Logging": { - "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Online\\Logs" + "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Logs" }, "Variants": [ { @@ -58,7 +58,7 @@ "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Online\\Docs" }, "Logging": { - "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Online\\Logs" + "RootFolder": "C:\\Sarand\\Saxonite\\Demo\\Logs" } } ] diff --git a/SaxoniteStandardBase/Base/App/Sax-Config.cs b/SaxoniteStandardBase/Base/App/Sax-Config.cs index 65c5448..207f1f3 100644 --- a/SaxoniteStandardBase/Base/App/Sax-Config.cs +++ b/SaxoniteStandardBase/Base/App/Sax-Config.cs @@ -169,6 +169,18 @@ namespace Saxonite.Net.Standard.Base.App public static long KeepLoggedInTimeoutMillis { get; } = (long)(SacsSystem.DebugMode ? TimeSpan.FromMinutes(1) : TimeSpan.FromMinutes(5)).TotalMilliseconds; } } + public static class Processes + { + public static class Scheduled + { + public static class UsgaGolfDataLookup + { + public static bool Enabled { get; set; } = SacsSystem.DebugMode ? true : true; + public static int MinsBetweenExecution { get; set; } = SacsSystem.DebugMode ? 12 : 20; + public static int HoursBetweenCountryLookup { get; set; } = SacsSystem.DebugMode ? 24 : 24 * 5; + } + } + } } public static class Links { diff --git a/SaxoniteStandardBase/Base/App/Sax-Version.cs b/SaxoniteStandardBase/Base/App/Sax-Version.cs index 8db1fea..0b8d804 100644 --- a/SaxoniteStandardBase/Base/App/Sax-Version.cs +++ b/SaxoniteStandardBase/Base/App/Sax-Version.cs @@ -18,7 +18,7 @@ namespace Saxonite.Net.Standard.Base.App //------------------------------------------------------------------- public static class Version { - private static String version { get; } = "1.2.11.3"; + private static String version { get; } = "1.2.11.4"; // Retrieve version. public static String GetFullVersion () { return version; } public static String GetAppVersion () @@ -41,8 +41,9 @@ namespace Saxonite.Net.Standard.Base.App // Version history. //------------------------------------------------------------------- // 1.2.11 6-Jul-2023 - // - Organisation associations, admin download [Feb24]. - // - Basic Api app [Apr24]. + // - Organisation associations, admin download. [Feb24] + // - Basic Api app. [Apr24] + // - Admin Database and logs pages evolved. [May24] // 1.2.10 11-Oct-2022 // - Online organisations display issue fixed. // - User Sport 'Preparing' options. diff --git a/SaxoniteStandardBase/Base/App/Sax.cs b/SaxoniteStandardBase/Base/App/Sax.cs index 1088433..0306779 100644 --- a/SaxoniteStandardBase/Base/App/Sax.cs +++ b/SaxoniteStandardBase/Base/App/Sax.cs @@ -55,7 +55,8 @@ namespace Saxonite.Net.Standard.Base.App { Unknown = 0, Core = 10, - Support = 20, + Reference = 20, + Support = 90, } //------------------------------------------------------------------- @@ -103,8 +104,14 @@ namespace Saxonite.Net.Standard.Base.App ItemAddress = 405, ItemAssociation = 410, ItemSport = 420, + // Reference. + Golf_UsgaCountry = 1000, + Golf_UsgaProvince = 1001, + Golf_UsgaFacility = 1002, + Golf_UsgaCourse = 1003, + Golf_UsgaMarker = 1004, // Support. - UserReport = 1010, + UserReport = 9010, } //------------------------------------------------------------------- diff --git a/SaxoniteStandardBase/Base/App/SaxDbDfn_Core.cs b/SaxoniteStandardBase/Base/App/SaxDbDfn_Core.cs index 7d3ffdd..33196bf 100644 --- a/SaxoniteStandardBase/Base/App/SaxDbDfn_Core.cs +++ b/SaxoniteStandardBase/Base/App/SaxDbDfn_Core.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Base.App { @@ -435,10 +435,19 @@ namespace Saxonite.Base.App { int tableIdx = (int)table - 1; if (tableIdx < 0 || tableIdx >= tableCount) return String.Empty; - String tableName = tables[(int)tableIdx]; + String tableName = tables[(int)tableIdx].Name; if (delimitReservedWords) tableName = DelimitReservedWord(tableName); return tableName; } + public static String GetTableNameQual (TableIdx table, bool delimitReservedWords = true) + { + int tableIdx = (int)table - 1; + if (tableIdx < 0 || tableIdx >= tableCount) return String.Empty; + String schemaName = tables[(int)tableIdx].Schema; + String tableName = tables[(int)tableIdx].Name; + if (delimitReservedWords) { schemaName = DelimitReservedWord(schemaName); tableName = DelimitReservedWord(tableName); } + return (StringUtil.IsBlank(schemaName) ? "" : schemaName + ".") + tableName; + } //------------------------------------------------------------------- // Identify the table that corresponds with the specified column. @@ -488,8 +497,15 @@ namespace Saxonite.Base.App } public static String DelimitReservedWord (String word) { - if (!IsReservedWord(word)) return word; - switch (reservedWordDelim) + return IsReservedWord(word) ? DelimitWord(word) : word; + } + public static String DelimitWord (String word) + { + return DelimitWord(word, reservedWordDelim); + } + public static String DelimitWord (String word, DbReservedWordDelim wordDelim) + { + switch (wordDelim) { case DbReservedWordDelim.None: break; @@ -566,30 +582,40 @@ namespace Saxonite.Base.App //------------------------------------------------------------------- // Table definitions. - private static readonly String[] tables = + private class TableDfn { - "ActivityFeedback", - "ActivityIndex", - "Article", - "ItemAddress", - "ItemAssociation", - "ItemImage", - "ItemSport", - "Organisation", - "OrganisationEvent", - "OrganisationOpportunity", - "Region", - "Sport", - "UserAccount", - "UserActivity", - "UserConfig", - "UserEligibility", - "UserOnline", - "UserOrganisation", - "UserRole", - "UserSession", - "UserSport", - "UserSportExperience", + internal String Schema { get; set; } + internal String Name { get; set; } + internal TableDfn (String schema, String name) + { + this.Schema= schema; + this.Name = name; + } + } + private static readonly TableDfn[] tables = + { + new TableDfn("dbo","ActivityFeedback"), + new TableDfn("dbo","ActivityIndex"), + new TableDfn("dbo","Article"), + new TableDfn("dbo","ItemAddress"), + new TableDfn("dbo","ItemAssociation"), + new TableDfn("dbo","ItemImage"), + new TableDfn("dbo","ItemSport"), + new TableDfn("dbo","Organisation"), + new TableDfn("dbo","OrganisationEvent"), + new TableDfn("dbo","OrganisationOpportunity"), + new TableDfn("dbo","Region"), + new TableDfn("dbo","Sport"), + new TableDfn("dbo","UserAccount"), + new TableDfn("dbo","UserActivity"), + new TableDfn("dbo","UserConfig"), + new TableDfn("dbo","UserEligibility"), + new TableDfn("dbo","UserOnline"), + new TableDfn("dbo","UserOrganisation"), + new TableDfn("dbo","UserRole"), + new TableDfn("dbo","UserSession"), + new TableDfn("dbo","UserSport"), + new TableDfn("dbo","UserSportExperience"), }; //------------------------------------------------------------------- @@ -612,8 +638,6 @@ namespace Saxonite.Base.App this.DataLen = dataLen; } } - - //------------------------------------------------------------------- private static readonly ColumnDfn[] columns = { new ColumnDfn(1,"ItemType",3,5,false,5), diff --git a/SaxoniteStandardBase/Base/App/SaxDbDfn_Reference.cs b/SaxoniteStandardBase/Base/App/SaxDbDfn_Reference.cs new file mode 100644 index 0000000..a25f43e --- /dev/null +++ b/SaxoniteStandardBase/Base/App/SaxDbDfn_Reference.cs @@ -0,0 +1,488 @@ +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using System; +using System.Collections.Generic; +using System.Linq; + +//--------------------------------------------------------------------------- +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 +//--------------------------------------------------------------------------- +namespace Saxonite.Base.App +{ + public class SaxDbDfn_Reference + { + //------------------------------------------------------------------- + // Table identifiers. + public enum TableIdx + { + Unknown = 0, + UsgaCountry, + UsgaCourse, + UsgaFacility, + UsgaMarker, + UsgaProvince, + } + + //------------------------------------------------------------------- + // Column identifiers. + public enum ColumnIdx + { + Unknown = 0, + UsgaCountry_Id, + UsgaCountry_CountryCode, + UsgaCountry_CountryName, + UsgaCountry_EntCountryCode, + UsgaCountry_Notes, + UsgaCountry_Flags, + UsgaCountry_Status, + UsgaCountry_CreateOn, + UsgaCountry_CreateBy, + UsgaCountry_CreateHost, + UsgaCountry_UpdateOn, + UsgaCountry_UpdateBy, + UsgaCountry_UpdateHost, + UsgaCourse_Id, + UsgaCourse_FacilityId, + UsgaCourse_CourseId, + UsgaCourse_LegacyCrpCourseId, + UsgaCourse_Caption, + UsgaCourse_CourseName, + UsgaCourse_FullName, + UsgaCourse_Address1, + UsgaCourse_Address2, + UsgaCourse_City, + UsgaCourse_Email, + UsgaCourse_Telephone, + UsgaCourse_Notes, + UsgaCourse_Flags, + UsgaCourse_Status, + UsgaCourse_CreateOn, + UsgaCourse_CreateBy, + UsgaCourse_CreateHost, + UsgaCourse_UpdateOn, + UsgaCourse_UpdateBy, + UsgaCourse_UpdateHost, + UsgaFacility_Id, + UsgaFacility_ProvinceId, + UsgaFacility_FacilityId, + UsgaFacility_FacilityName, + UsgaFacility_Notes, + UsgaFacility_Flags, + UsgaFacility_Status, + UsgaFacility_CreateOn, + UsgaFacility_CreateBy, + UsgaFacility_CreateHost, + UsgaFacility_UpdateOn, + UsgaFacility_UpdateBy, + UsgaFacility_UpdateHost, + UsgaMarker_Id, + UsgaMarker_CourseId, + UsgaMarker_MarkerId, + UsgaMarker_Caption, + UsgaMarker_Holes, + UsgaMarker_HolesCaption, + UsgaMarker_Tee, + UsgaMarker_Gender, + UsgaMarker_SlopeRating, + UsgaMarker_Par, + UsgaMarker_CourseRating, + UsgaMarker_BogeyRating, + UsgaMarker_Length, + UsgaMarker_Notes, + UsgaMarker_Flags, + UsgaMarker_Status, + UsgaMarker_CreateOn, + UsgaMarker_CreateBy, + UsgaMarker_CreateHost, + UsgaMarker_UpdateOn, + UsgaMarker_UpdateBy, + UsgaMarker_UpdateHost, + UsgaProvince_Id, + UsgaProvince_CountryId, + UsgaProvince_ProvinceCode, + UsgaProvince_EntProvinceCode, + UsgaProvince_ProvinceName, + UsgaProvince_Notes, + UsgaProvince_Flags, + UsgaProvince_Status, + UsgaProvince_CreateOn, + UsgaProvince_CreateBy, + UsgaProvince_CreateHost, + UsgaProvince_UpdateOn, + UsgaProvince_UpdateBy, + UsgaProvince_UpdateHost, + } + + //------------------------------------------------------------------- + // Data members. + private static readonly int tableCount = 5; + private static readonly int columnCount = 83; + private static ulong maxTextLen = 0; + + //------------------------------------------------------------------- + // Retrieve Table details (eg. name: 'Company'). + public static int GetTableCount () + { + return tableCount; + } + public static String GetTableName (TableIdx table, bool delimitReservedWords = true) + { + int tableIdx = (int)table - 1; + if (tableIdx < 0 || tableIdx >= tableCount) return String.Empty; + String tableName = tables[(int)tableIdx].Name; + if (delimitReservedWords) tableName = DelimitReservedWord(tableName); + return tableName; + } + public static String GetTableNameQual (TableIdx table, bool delimitReservedWords = true) + { + int tableIdx = (int)table - 1; + if (tableIdx < 0 || tableIdx >= tableCount) return String.Empty; + String schemaName = tables[(int)tableIdx].Schema; + String tableName = tables[(int)tableIdx].Name; + if (delimitReservedWords) { schemaName = DelimitReservedWord(schemaName); tableName = DelimitReservedWord(tableName); } + return (StringUtil.IsBlank(schemaName) ? "" : schemaName + ".") + tableName; + } + + //------------------------------------------------------------------- + // Identify the table that corresponds with the specified column. + public static TableIdx GetTableForColumn (ColumnIdx column) + { + int columnIdx = (int)column - 1; + if (columnIdx < 0 || columnIdx >= columnCount) return TableIdx.Unknown; + return columns[columnIdx].TableIdx; + } + + //------------------------------------------------------------------- + // Retrieve the specified Column's name (Qualified include table name: '(
.Column>)'). + public static String GetColumnName (ColumnIdx column, bool delimitReservedWords = true) + { + int columnIdx = (int)column - 1; + if (columnIdx < 0 || columnIdx >= columnCount) return String.Empty; + String columnName = columns[columnIdx].Name; + if (delimitReservedWords) columnName = DelimitReservedWord(columnName); + return columnName; + } + public static String GetColumnNameQual (ColumnIdx column, String tableAlias = "", bool braces = false) + { + String columnName = GetColumnName(column); + if (!String.IsNullOrEmpty(columnName)) + { + String tableName = StringUtil.EmptyOnNull(tableAlias); + if (tableName.IsEmpty()) tableName = GetTableName(GetTableForColumn(column)); + columnName = tableName + (tableName.Length > 0 ? "." : "") + columnName; + if (braces) + columnName = "(" + columnName + ")"; + } + return columnName; + } + + //------------------------------------------------------------------- + // Reserved words. + private static DbReservedWordDelim reservedWordDelim = DbReservedWordDelim.SquareBrackets; + public static void SetReservedWordDelim (DbReservedWordDelim reservedWordDelim) + { + SaxDbDfn_Reference.reservedWordDelim = reservedWordDelim; + } + public static bool IsReservedWord (String word) + { + if (String.IsNullOrEmpty(word)) return false; + if (reservedWords.Contains(word, StringComparer.OrdinalIgnoreCase)) return true; + return false; + } + public static String DelimitReservedWord (String word) + { + return IsReservedWord(word) ? DelimitWord(word) : word; + } + public static String DelimitWord (String word) + { + return DelimitWord(word, reservedWordDelim); + } + public static String DelimitWord (String word, DbReservedWordDelim wordDelim) + { + switch (wordDelim) + { + case DbReservedWordDelim.None: + break; + case DbReservedWordDelim.DoubleQuotes: + word = "\"" + word + "\""; + break; + case DbReservedWordDelim.SquareBrackets: + default: + word = "[" + word + "]"; + break; + } + return word; + } + + //------------------------------------------------------------------- + // Retrieve information about the specified Column. + public static DbColumnDataType GetColDataType (ColumnIdx column) + { + int columnIdx = (int)column - 1; + if (columnIdx < 0 || columnIdx >= columnCount) return DbColumnDataType.Unknown; + return columns[columnIdx].DataType; + } + public static short GetColNativeDataType (ColumnIdx column) + { + int columnIdx = (int)column - 1; + if (columnIdx < 0 || columnIdx >= columnCount) return 0; + return columns[columnIdx].NativeDataType; + } + public static void SetMaxTextLen (ulong maxTextLen) + { + SaxDbDfn_Reference.maxTextLen = maxTextLen; + } + public static bool IsColFmtText (ColumnIdx column) + { + int columnIdx = (int)column - 1; + if (columnIdx < 0 || columnIdx >= columnCount) return false; + return (columns[columnIdx].DataType == DbColumnDataType.VarChar); + } + public static ulong GetColTextLen (ColumnIdx column) + { + int columnIdx = (int)column - 1; + if (columnIdx < 0 || columnIdx >= columnCount) return 0; + if (columns[columnIdx].DataType == DbColumnDataType.VarChar) + { + ulong textLen = columns[columnIdx].DataLen; + if (maxTextLen > 0 && textLen > maxTextLen) textLen = maxTextLen; + return textLen; + } + return 0; + } + public static bool IsColFmtBool (ColumnIdx column) + { + int columnIdx = (int)column - 1; + if (columnIdx < 0 || columnIdx >= columnCount) return false; + return (columns[columnIdx].DataType == DbColumnDataType.Bit); + } + public static bool IsColFmtNumeric (ColumnIdx column) + { + int columnIdx = (int)column - 1; + if (columnIdx < 0 || columnIdx >= columnCount) return false; + switch (columns[columnIdx].DataType) + { + case DbColumnDataType.TinyInt: + case DbColumnDataType.SmallInt: + case DbColumnDataType.Int: + case DbColumnDataType.BigInt: + case DbColumnDataType.Single: + case DbColumnDataType.Double: + case DbColumnDataType.Decimal: + return true; + } + return false; + } + + //------------------------------------------------------------------- + // Table definitions. + private class TableDfn + { + internal String Schema { get; set; } + internal String Name { get; set; } + internal TableDfn (String schema, String name) + { + this.Schema= schema; + this.Name = name; + } + } + private static readonly TableDfn[] tables = + { + new TableDfn("golf","UsgaCountry"), + new TableDfn("golf","UsgaCourse"), + new TableDfn("golf","UsgaFacility"), + new TableDfn("golf","UsgaMarker"), + new TableDfn("golf","UsgaProvince"), + }; + + //------------------------------------------------------------------- + // Table column definitions. + private class ColumnDfn + { + internal TableIdx TableIdx { get; set; } + internal String Name { get; set; } + internal DbColumnDataType DataType { get; set; } + internal short NativeDataType { get; set; } + internal bool IsIdentity { get; set; } + internal ulong DataLen { get; set; } + internal ColumnDfn (int tableIdx, String name, int dataType, short nativeDataType, bool isIdentity, ulong dataLen) + { + this.TableIdx = (TableIdx)tableIdx; + this.Name = name; + this.DataType = (DbColumnDataType)dataType; + this.NativeDataType = nativeDataType; + this.IsIdentity = isIdentity; + this.DataLen = dataLen; + } + } + private static readonly ColumnDfn[] columns = + { + new ColumnDfn(1,"Id",5,-5,true,19), + new ColumnDfn(1,"CountryCode",0,12,false,10), + new ColumnDfn(1,"CountryName",0,-9,false,200), + new ColumnDfn(1,"EntCountryCode",0,12,false,10), + new ColumnDfn(1,"Notes",0,-9,false,2000), + new ColumnDfn(1,"Flags",3,5,false,5), + new ColumnDfn(1,"Status",0,12,false,3), + new ColumnDfn(1,"CreateOn",9,93,false,23), + new ColumnDfn(1,"CreateBy",4,4,false,10), + new ColumnDfn(1,"CreateHost",0,12,false,100), + new ColumnDfn(1,"UpdateOn",9,93,false,23), + new ColumnDfn(1,"UpdateBy",4,4,false,10), + new ColumnDfn(1,"UpdateHost",0,12,false,100), + new ColumnDfn(2,"Id",5,-5,true,19), + new ColumnDfn(2,"FacilityId",5,-5,false,19), + new ColumnDfn(2,"CourseId",5,-5,false,19), + new ColumnDfn(2,"LegacyCrpCourseId",5,-5,false,19), + new ColumnDfn(2,"Caption",0,-9,false,200), + new ColumnDfn(2,"CourseName",0,-9,false,200), + new ColumnDfn(2,"FullName",0,-9,false,200), + new ColumnDfn(2,"Address1",0,-9,false,200), + new ColumnDfn(2,"Address2",0,-9,false,200), + new ColumnDfn(2,"City",0,-9,false,200), + new ColumnDfn(2,"Email",0,-9,false,200), + new ColumnDfn(2,"Telephone",0,-9,false,200), + new ColumnDfn(2,"Notes",0,-9,false,2000), + new ColumnDfn(2,"Flags",3,5,false,5), + new ColumnDfn(2,"Status",0,12,false,3), + new ColumnDfn(2,"CreateOn",9,93,false,23), + new ColumnDfn(2,"CreateBy",4,4,false,10), + new ColumnDfn(2,"CreateHost",0,12,false,100), + new ColumnDfn(2,"UpdateOn",9,93,false,23), + new ColumnDfn(2,"UpdateBy",4,4,false,10), + new ColumnDfn(2,"UpdateHost",0,12,false,100), + new ColumnDfn(3,"Id",5,-5,true,19), + new ColumnDfn(3,"ProvinceId",5,-5,false,19), + new ColumnDfn(3,"FacilityId",5,-5,false,19), + new ColumnDfn(3,"FacilityName",0,-9,false,200), + new ColumnDfn(3,"Notes",0,-9,false,2000), + new ColumnDfn(3,"Flags",3,5,false,5), + new ColumnDfn(3,"Status",0,12,false,3), + new ColumnDfn(3,"CreateOn",9,93,false,23), + new ColumnDfn(3,"CreateBy",4,4,false,10), + new ColumnDfn(3,"CreateHost",0,12,false,100), + new ColumnDfn(3,"UpdateOn",9,93,false,23), + new ColumnDfn(3,"UpdateBy",4,4,false,10), + new ColumnDfn(3,"UpdateHost",0,12,false,100), + new ColumnDfn(4,"Id",5,-5,true,19), + new ColumnDfn(4,"CourseId",5,-5,false,19), + new ColumnDfn(4,"MarkerId",5,-5,false,19), + new ColumnDfn(4,"Caption",0,-9,false,200), + new ColumnDfn(4,"Holes",3,5,false,5), + new ColumnDfn(4,"HolesCaption",0,-9,false,32), + new ColumnDfn(4,"Tee",0,-9,false,32), + new ColumnDfn(4,"Gender",0,-9,false,32), + new ColumnDfn(4,"SlopeRating",3,5,false,5), + new ColumnDfn(4,"Par",3,5,false,5), + new ColumnDfn(4,"CourseRating",8,3,false,9), + new ColumnDfn(4,"BogeyRating",8,3,false,9), + new ColumnDfn(4,"Length",3,5,false,5), + new ColumnDfn(4,"Notes",0,-9,false,2000), + new ColumnDfn(4,"Flags",3,5,false,5), + new ColumnDfn(4,"Status",0,12,false,3), + new ColumnDfn(4,"CreateOn",9,93,false,23), + new ColumnDfn(4,"CreateBy",4,4,false,10), + new ColumnDfn(4,"CreateHost",0,12,false,100), + new ColumnDfn(4,"UpdateOn",9,93,false,23), + new ColumnDfn(4,"UpdateBy",4,4,false,10), + new ColumnDfn(4,"UpdateHost",0,12,false,100), + new ColumnDfn(5,"Id",5,-5,true,19), + new ColumnDfn(5,"CountryId",5,-5,false,19), + new ColumnDfn(5,"ProvinceCode",0,12,false,20), + new ColumnDfn(5,"EntProvinceCode",0,12,false,20), + new ColumnDfn(5,"ProvinceName",0,-9,false,200), + new ColumnDfn(5,"Notes",0,-9,false,2000), + new ColumnDfn(5,"Flags",3,5,false,5), + new ColumnDfn(5,"Status",0,12,false,3), + new ColumnDfn(5,"CreateOn",9,93,false,23), + new ColumnDfn(5,"CreateBy",4,4,false,10), + new ColumnDfn(5,"CreateHost",0,12,false,100), + new ColumnDfn(5,"UpdateOn",9,93,false,23), + new ColumnDfn(5,"UpdateBy",4,4,false,10), + new ColumnDfn(5,"UpdateHost",0,12,false,100), + }; + + //------------------------------------------------------------------- + // Reserved words. + private static readonly List reservedWords = new List() + { + "ADD", + "ALL", + "ALTER", + "AND", + "ANY", + "AS", + "ASC", + "AVG", + "BEGIN", + "BETWEEN", + "BY", + "CASE", + "CAST", + "COLUMN", + "COMMIT", + "CONSTRAINT", + "CONVERT", + "COUNT", + "CREATE", + "CURRENCY", + "DEFAULT", + "DELETE", + "DESC", + "DISTINCT", + "DROP", + "ELSE", + "END", + "EXECUTE", + "EXISTS", + "FALSE", + "FROM", + "GRANT", + "GROUP", + "HAVING", + "IN", + "INDEX", + "INNER", + "INSERT", + "INTO", + "IS", + "JOIN", + "KEY", + "LEFT", + "LIKE", + "MAX", + "MIN", + "NOT", + "NULL", + "ON", + "OR", + "ORDER", + "OUTER", + "OUTPUT", + "PRIMARY", + "PROCEDURE", + "REVOKE", + "ROLLBACK", + "ROWCOUNT", + "SELECT", + "SET", + "SQL", + "SUM", + "TABLE", + "THEN", + "TRANSACTION", + "TRUE", + "UNION", + "UNIQUE", + "UPDATE", + "USER", + "VALUES", + "VIEW", + "WHEN", + "WHERE", + }; + + //------------------------------------------------------------------- + } +} diff --git a/SaxoniteStandardBase/Base/App/SaxDbDfn_Support.cs b/SaxoniteStandardBase/Base/App/SaxDbDfn_Support.cs index 42f4f1d..93fd5ce 100644 --- a/SaxoniteStandardBase/Base/App/SaxDbDfn_Support.cs +++ b/SaxoniteStandardBase/Base/App/SaxDbDfn_Support.cs @@ -6,7 +6,7 @@ using System.Collections.Generic; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:56 //--------------------------------------------------------------------------- namespace Saxonite.Base.App { @@ -74,10 +74,19 @@ namespace Saxonite.Base.App { int tableIdx = (int)table - 1; if (tableIdx < 0 || tableIdx >= tableCount) return String.Empty; - String tableName = tables[(int)tableIdx]; + String tableName = tables[(int)tableIdx].Name; if (delimitReservedWords) tableName = DelimitReservedWord(tableName); return tableName; } + public static String GetTableNameQual (TableIdx table, bool delimitReservedWords = true) + { + int tableIdx = (int)table - 1; + if (tableIdx < 0 || tableIdx >= tableCount) return String.Empty; + String schemaName = tables[(int)tableIdx].Schema; + String tableName = tables[(int)tableIdx].Name; + if (delimitReservedWords) { schemaName = DelimitReservedWord(schemaName); tableName = DelimitReservedWord(tableName); } + return (StringUtil.IsBlank(schemaName) ? "" : schemaName + ".") + tableName; + } //------------------------------------------------------------------- // Identify the table that corresponds with the specified column. @@ -127,8 +136,15 @@ namespace Saxonite.Base.App } public static String DelimitReservedWord (String word) { - if (!IsReservedWord(word)) return word; - switch (reservedWordDelim) + return IsReservedWord(word) ? DelimitWord(word) : word; + } + public static String DelimitWord (String word) + { + return DelimitWord(word, reservedWordDelim); + } + public static String DelimitWord (String word, DbReservedWordDelim wordDelim) + { + switch (wordDelim) { case DbReservedWordDelim.None: break; @@ -205,10 +221,20 @@ namespace Saxonite.Base.App //------------------------------------------------------------------- // Table definitions. - private static readonly String[] tables = + private class TableDfn { - "UserReport", - "UserReportComment", + internal String Schema { get; set; } + internal String Name { get; set; } + internal TableDfn (String schema, String name) + { + this.Schema= schema; + this.Name = name; + } + } + private static readonly TableDfn[] tables = + { + new TableDfn("dbo","UserReport"), + new TableDfn("dbo","UserReportComment"), }; //------------------------------------------------------------------- @@ -231,8 +257,6 @@ namespace Saxonite.Base.App this.DataLen = dataLen; } } - - //------------------------------------------------------------------- private static readonly ColumnDfn[] columns = { new ColumnDfn(1,"Id",5,-5,true,19), diff --git a/SaxoniteStandardBase/Base/App/SaxInternals.cs b/SaxoniteStandardBase/Base/App/SaxInternals.cs index 2e07d5e..d32031c 100644 --- a/SaxoniteStandardBase/Base/App/SaxInternals.cs +++ b/SaxoniteStandardBase/Base/App/SaxInternals.cs @@ -11,6 +11,7 @@ using Sarand.Net.Standard.Base.Bus; using Sarand.Net.Standard.Base.App; using Sarand.Net.Standard.Base.Utils; using Saxonite.Net.Standard.Base.Mgr.Support; +using Saxonite.Net.Standard.Base.Mgr.Reference; namespace Saxonite.Net.Standard.Base.App { @@ -30,6 +31,9 @@ namespace Saxonite.Net.Standard.Base.App public SaxAccountMgr accountMgr = null; public SaxActivityMgr activityMgr = null; public SaxItemDataMgr itemDataMgr = null; + // Reference. + public SaxReferenceGolfMgr referenceGolfMgr = null; + // Support. public SaxSupportMgr supportMgr = null; } private readonly Managers mgr = new Managers(); @@ -72,6 +76,7 @@ namespace Saxonite.Net.Standard.Base.App if (mgr.accountMgr != null) mgr.accountMgr.Dispose(); mgr.accountMgr = null; if (mgr.activityMgr != null) mgr.activityMgr.Dispose(); mgr.activityMgr = null; if (mgr.itemDataMgr != null) mgr.itemDataMgr.Dispose(); mgr.itemDataMgr = null; + if (mgr.referenceGolfMgr != null) mgr.referenceGolfMgr.Dispose(); mgr.referenceGolfMgr = null; if (mgr.supportMgr != null) mgr.supportMgr.Dispose(); mgr.supportMgr = null; if (con.activityConsole != null) con.activityConsole.Dispose(); con.activityConsole = null; } @@ -166,6 +171,15 @@ namespace Saxonite.Net.Standard.Base.App return mgr.itemDataMgr; } } + public SaxReferenceGolfMgr ReferenceGolfMgr + { + get + { + if (mgr.referenceGolfMgr == null) + mgr.referenceGolfMgr = System.CreateReferenceGolfMgr(SessionContext, this); + return mgr.referenceGolfMgr; + } + } public SaxSupportMgr SupportMgr { get diff --git a/SaxoniteStandardBase/Base/App/SaxSystem.cs b/SaxoniteStandardBase/Base/App/SaxSystem.cs index 5e0a845..4a894ea 100644 --- a/SaxoniteStandardBase/Base/App/SaxSystem.cs +++ b/SaxoniteStandardBase/Base/App/SaxSystem.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Text; using Saxonite.Net.Standard.Base.Mgr.Support; +using Saxonite.Net.Standard.Base.Mgr.Reference; namespace Saxonite.Net.Standard.Base.App { @@ -28,6 +29,7 @@ namespace Saxonite.Net.Standard.Base.App public abstract SaxAccountMgr CreateAccountMgr(SaxSessionContext sessionContext, SaxInternals internals); public abstract SaxItemDataMgr CreateItemDataMgr(SaxSessionContext sessionContext, SaxInternals internals); public abstract SaxActivityMgr CreateActivityMgr(SaxSessionContext sessionContext, SaxInternals internals); + public abstract SaxReferenceGolfMgr CreateReferenceGolfMgr(SaxSessionContext sessionContext, SaxInternals internals); public abstract SaxSupportMgr CreateSupportMgr(SaxSessionContext sessionContext, SaxInternals internals); //------------------------------------------------------------------- diff --git a/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaCountry.cs b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaCountry.cs new file mode 100644 index 0000000..b9aa0c1 --- /dev/null +++ b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaCountry.cs @@ -0,0 +1,222 @@ +using DocumentFormat.OpenXml.Office2010.Excel; +using NPOI.SS.Formula.Functions; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Saxonite.Net.Standard.Base.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using static Sarand.Net.Standard.Base.Bus.SacsHierarchyItem; + +namespace Saxonite.Net.Standard.Base.Bus.Reference +{ + //======================================================================= + // Golf - USGA Country. + //======================================================================= + public abstract class SaxGolfUsgaCountry : SacsHierarchyItem + { + //------------------------------------------------------------------- + // Columns. + public enum Column + { + Pos, + Id, + CountryCode, + EntCountryCode, + CountryName, + // Associated data. + // Common. + Notes, + Flags, + Status, + Status_Desc, + Status_Ind, + CreateOn_Date, + UpdateOn_Date, + } + + //------------------------------------------------------------------- + /// Properties other than common. + public class DataProperties + { + public String CountryCode { get; set; } = String.Empty; + public String EntCountryCode { get; set; } = String.Empty; + public String CountryName { get; set; } = String.Empty; + } + + //------------------------------------------------------------------- + // Data. + public new class Data : SacsHierarchyItem.Data + { + // Data members. + private readonly DataProperties data = new DataProperties(); + // Construction. + public Data() + { + Status = DefaultStatus; + } + // Properties. + public String CountryCode + { + get { return data.CountryCode; } + set { CheckChanged(data.CountryCode, value); data.CountryCode = value; } + } + public String EntCountryCode + { + get { return data.EntCountryCode; } + set { CheckChanged(data.EntCountryCode, value); data.EntCountryCode = value; } + } + public String CountryName + { + get { return data.CountryName; } + set { CheckChanged(data.CountryName, value); data.CountryName = value; } + } + // Population. + internal void PopulateFrom(Data data) + { + CountryCode = data.CountryCode; + EntCountryCode = data.EntCountryCode; + CountryName = data.CountryName; + base.PopulateFrom(data); + } + public Data Clone() + { + Data data = new Data(); + data.PopulateFrom(this); + return data; + } + } + + //------------------------------------------------------------------- + // Error field - identify properties with validation error. + public new class ErrField : SacsHierarchyItem.ErrField + { + // Identifies the field that has invalid data. + public ValidValue CountryCode { get; set; } = ValidValue.Valid; + public ValidValue EntCountryCode { get; set; } = ValidValue.Valid; + public ValidValue CountryName { get; set; } = ValidValue.Valid; + } + + //------------------------------------------------------------------- + // Data members. + private readonly Data data = new Data(); + + //------------------------------------------------------------------- + // Construction. + protected SaxGolfUsgaCountry(SysId id) : base(id) + { + base.SetData(data); + Status = DefaultStatus; + } + + //------------------------------------------------------------------- + // Status. + private static readonly List validStatuses = new List() + { + SaStatus.Active, + SaStatus.Inactive, + SaStatus.Deleted, + }; + public static SaStatus DefaultStatus { get { return SaStatus.Active; } } + public static List ValidStatuses { get { return new List(validStatuses); } } + public static DataValue.TriStateType GetStatusTriState(SaStatus status) + { + if (status == SaStatus.Active) return DataValue.TriStateType.Green; + if (status == SaStatus.Inactive) return DataValue.TriStateType.Red; + if (status == SaStatus.Deleted) return DataValue.TriStateType.Purple; + return DataValue.TriStateType.Unknown; + } + + //------------------------------------------------------------------- + // Utilities. + public ItemId GetItemId() + { + return new ItemId((short)Sax.DataItemType.Golf_UsgaCountry, Id); + } + + //------------------------------------------------------------------- + // Properties. + public Data GetData() { return data.Clone(); } + public void SetData(Data data) + { + String fn = GetType().Name + ".SetData"; + // Properties that cannot be changed if previously specified. + if (SysId.IsValid(Id) && SysId.ToInt(Id) != SysId.ToInt(data.Id)) + throw new NotSupportedException(fn + " Id cannot be changed"); + this.data.PopulateFrom(data); + } + public String CountryCode + { + get { return data.CountryCode; } + set { data.CountryCode = value; } + } + public String EntCountryCode + { + get { return data.EntCountryCode; } + set { data.EntCountryCode = value; } + } + public String CountryName + { + get { return data.CountryName; } + set { data.CountryName = value; } + } + + //------------------------------------------------------------------- + // Flags - positions 1-16 available. + + //------------------------------------------------------------------- + // A s s o c i a t e d D a t a + //------------------------------------------------------------------- + + //------------------------------------------------------------------- + // P a r a m s + //------------------------------------------------------------------- + // List parameters. + public enum StatusCat + { + Any, + ActiveOnly, + InactiveOnly, + NotDeleted, + DeletedOnly, + } + /// + /// Item list parameters. + /// + public new class Params : SacsHierarchyItem.Params + { + // List filtering. + public List IdsIncluded { get; } = new List(); + public List IdsExcluded { get; } = new List(); + /// Generic filter - partial country code or name. + public String CountryFilter { get; set; } + public String CountryCodeFull { get; set; } + public String CountryNameFull { get; set; } + public String CountryNamePartial { get; set; } + // Common properties. + public String NotesPartial { get; set; } + public StatusCat StatusCat { get; set; } = StatusCat.ActiveOnly; + } + + //------------------------------------------------------------------- + } + //======================================================================= + // Item list extension methods. + public static class SaxGolfUsgaCountryList + { + //------------------------------------------------------------------- + public static SaxGolfUsgaCountry GetCountryById(this IEnumerable values, SysId countryId) + { + if (!SysId.IsValid(countryId)) return null; + foreach (SaxGolfUsgaCountry country in values) + if (country.Id.Equals(countryId)) return country; + return null; + } + + //------------------------------------------------------------------- + } + + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaCourse.cs b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaCourse.cs new file mode 100644 index 0000000..4c0a394 --- /dev/null +++ b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaCourse.cs @@ -0,0 +1,345 @@ +using NPOI.SS.Formula.Functions; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Saxonite.Net.Standard.Base.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Saxonite.Net.Standard.Base.Bus.Reference +{ + //======================================================================= + // Golf - USGA Course. + //======================================================================= + public abstract class SaxGolfUsgaCourse : SacsHierarchyItem + { + //------------------------------------------------------------------- + // Columns. + public enum Column + { + Pos, + Id, + CountryId, + Country_Name, + ProvinceId, + Province_Name, + FacilityId, + Facility_Name, + CourseId, + LegacyCrpCourseId, + Caption, + CourseName, + FullName, + Address1, + Address2, + City, + Email, + Telephone, + // Associated data. + // Common. + Notes, + Flags, + Status, + Status_Desc, + Status_Ind, + CreateOn_Date, + UpdateOn_Date, + } + + //------------------------------------------------------------------- + /// Properties other than common. + public class DataProperties + { + public SysId FacilityId { get; set; } + public SysId CourseId { get; set; } + public SysId LegacyCrpCourseId { get; set; } + public String Caption { get; set; } = String.Empty; + public String CourseName { get; set; } = String.Empty; + public String FullName { get; set; } = String.Empty; + public String Address1 { get; set; } = String.Empty; + public String Address2 { get; set; } = String.Empty; + public String City { get; set; } = String.Empty; + public String Email { get; set; } = String.Empty; + public String Telephone { get; set; } = String.Empty; + } + + //------------------------------------------------------------------- + // Data. + public new class Data : SacsHierarchyItem.Data + { + // Data members. + private readonly DataProperties data = new DataProperties(); + // Construction. + public Data() + { + Status = DefaultStatus; + } + // Properties. + public SysId FacilityId + { + get { return data.FacilityId; } + set { CheckChanged(data.FacilityId, value); data.FacilityId = value; } + } + public SysId CourseId + { + get { return data.CourseId; } + set { CheckChanged(data.CourseId, value); data.CourseId = value; } + } + public SysId LegacyCrpCourseId + { + get { return data.LegacyCrpCourseId; } + set { CheckChanged(data.LegacyCrpCourseId, value); data.LegacyCrpCourseId = value; } + } + public String Caption + { + get { return data.Caption; } + set { CheckChanged(data.Caption, value); data.Caption = value; } + } + public String CourseName + { + get { return data.CourseName; } + set { CheckChanged(data.CourseName, value); data.CourseName = value; } + } + public String FullName + { + get { return data.FullName; } + set { CheckChanged(data.FullName, value); data.FullName = value; } + } + public String Address1 + { + get { return data.Address1; } + set { CheckChanged(data.Address1, value); data.Address1 = value; } + } + public String Address2 + { + get { return data.Address2; } + set { CheckChanged(data.Address2, value); data.Address2 = value; } + } + public String City + { + get { return data.City; } + set { CheckChanged(data.City, value); data.City = value; } + } + public String Email + { + get { return data.Email; } + set { CheckChanged(data.Email, value); data.Email = value; } + } + public String Telephone + { + get { return data.Telephone; } + set { CheckChanged(data.Telephone, value); data.Telephone = value; } + } + // Population. + internal void PopulateFrom(Data data) + { + FacilityId = data.FacilityId; + CourseId = data.CourseId; + LegacyCrpCourseId = data.LegacyCrpCourseId; + Caption = data.Caption; + CourseName = data.CourseName; + FullName = data.FullName; + Address1 = data.Address1; + Address2 = data.Address2; + City = data.City; + Email = data.Email; + Telephone = data.Telephone; + base.PopulateFrom(data); + } + public Data Clone() + { + Data data = new Data(); + data.PopulateFrom(this); + return data; + } + } + + //------------------------------------------------------------------- + // Error field - identify properties with validation error. + public new class ErrField : SacsHierarchyItem.ErrField + { + // Identifies the field that has invalid data. + public ValidValue FacilityId { get; set; } = ValidValue.Valid; + public ValidValue CourseId { get; set; } = ValidValue.Valid; + public ValidValue LegacyCrpCourseId { get; set; } = ValidValue.Valid; + public ValidValue Caption { get; set; } = ValidValue.Valid; + public ValidValue CourseName { get; set; } = ValidValue.Valid; + public ValidValue FullName { get; set; } = ValidValue.Valid; + public ValidValue Address1 { get; set; } = ValidValue.Valid; + public ValidValue Address2 { get; set; } = ValidValue.Valid; + public ValidValue City { get; set; } = ValidValue.Valid; + public ValidValue Email { get; set; } = ValidValue.Valid; + public ValidValue Telephone { get; set; } = ValidValue.Valid; + } + + //------------------------------------------------------------------- + // Data members. + private readonly Data data = new Data(); + + //------------------------------------------------------------------- + // Construction. + protected SaxGolfUsgaCourse(SysId id, SysId facilityId) : base(id) + { + base.SetData(data); + this.FacilityId = facilityId; + Status = DefaultStatus; + } + + //------------------------------------------------------------------- + // Status. + private static readonly List validStatuses = new List() + { + SaStatus.Active, + SaStatus.Inactive, + SaStatus.Deleted, + }; + public static SaStatus DefaultStatus { get { return SaStatus.Active; } } + public static List ValidStatuses { get { return new List(validStatuses); } } + public static DataValue.TriStateType GetStatusTriState(SaStatus status) + { + if (status == SaStatus.Active) return DataValue.TriStateType.Green; + if (status == SaStatus.Inactive) return DataValue.TriStateType.Red; + if (status == SaStatus.Deleted) return DataValue.TriStateType.Purple; + return DataValue.TriStateType.Unknown; + } + + //------------------------------------------------------------------- + // Utilities. + public ItemId GetItemId() + { + return new ItemId((short)Sax.DataItemType.Golf_UsgaCourse, Id); + } + + //------------------------------------------------------------------- + // Properties. + public Data GetData() { return data.Clone(); } + public void SetData(Data data) + { + String fn = GetType().Name + ".SetData"; + // Properties that cannot be changed if previously specified. + if (SysId.IsValid(Id) && SysId.ToInt(Id) != SysId.ToInt(data.Id)) + throw new NotSupportedException(fn + " Id cannot be changed"); + this.data.PopulateFrom(data); + } + public SysId FacilityId + { + get { return data.FacilityId; } + set { data.FacilityId = value; } + } + public SysId CourseId + { + get { return data.CourseId; } + set { data.CourseId = value; } + } + public SysId LegacyCrpCourseId + { + get { return data.LegacyCrpCourseId; } + set { data.LegacyCrpCourseId = value; } + } + public String Caption + { + get { return data.Caption; } + set { data.Caption = value; } + } + public String CourseName + { + get { return data.CourseName; } + set { data.CourseName = value; } + } + public String FullName + { + get { return data.FullName; } + set { data.FullName = value; } + } + public String Address1 + { + get { return data.Address1; } + set { data.Address1 = value; } + } + public String Address2 + { + get { return data.Address2; } + set { data.Address2 = value; } + } + public String City + { + get { return data.City; } + set { data.City = value; } + } + public String Email + { + get { return data.Email; } + set { data.Email = value; } + } + public String Telephone + { + get { return data.Telephone; } + set { data.Telephone = value; } + } + + //------------------------------------------------------------------- + // Flags - positions 1-16 available. + + //------------------------------------------------------------------- + // A s s o c i a t e d D a t a + //------------------------------------------------------------------- + + //------------------------------------------------------------------- + // P a r a m s + //------------------------------------------------------------------- + // List parameters. + public enum StatusCat + { + Any, + ActiveOnly, + InactiveOnly, + NotDeleted, + DeletedOnly, + } + /// + /// Item list parameters. + /// + public new class Params : SacsHierarchyItem.Params + { + // List filtering. + public List IdsIncluded { get; } = new List(); + public List IdsExcluded { get; } = new List(); + public List ProvinceIdsIncluded { get; } = new List(); + public List FacilityIdsIncluded { get; } = new List(); + /// USGA Course Ids. + public List CourseIdsIncluded { get; } = new List(); + /// Generic filter - partial name, address etc. + public String CourseFilter { get; set; } + public String CourseNameFull { get; set; } + public String CourseNamePartial { get; set; } + // Common properties. + public String NotesPartial { get; set; } + public StatusCat StatusCat { get; set; } = StatusCat.ActiveOnly; + // Table aliases - blank if not linked. + public String Alias_Country { get; set; } + public String Alias_Province { get; set; } + public String Alias_Facility { get; set; } + } + + //------------------------------------------------------------------- + } + //======================================================================= + // Item list extension methods. + public static class SaxGolfUsgaCourseList + { + //------------------------------------------------------------------- + public static SaxGolfUsgaCourse GetCourseById(this IEnumerable values, SysId courseId) + { + if (!SysId.IsValid(courseId)) return null; + foreach (SaxGolfUsgaCourse province in values) + if (province.Id.Equals(courseId)) return province; + return null; + } + + //------------------------------------------------------------------- + } + + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaFacility.cs b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaFacility.cs new file mode 100644 index 0000000..dfc2ce3 --- /dev/null +++ b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaFacility.cs @@ -0,0 +1,229 @@ +using NPOI.SS.Formula.Functions; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Saxonite.Net.Standard.Base.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Saxonite.Net.Standard.Base.Bus.Reference +{ + //======================================================================= + // Golf - USGA Facility. + //======================================================================= + public abstract class SaxGolfUsgaFacility : SacsHierarchyItem + { + //------------------------------------------------------------------- + // Columns. + public enum Column + { + Pos, + Id, + CountryId, + Country_Name, + ProvinceId, + Province_Name, + FacilityId, + FacilityName, + // Associated data. + // Common. + Notes, + Flags, + Status, + Status_Desc, + Status_Ind, + CreateOn_Date, + UpdateOn_Date, + } + + //------------------------------------------------------------------- + /// Properties other than common. + public class DataProperties + { + public SysId ProvinceId { get; set; } + public SysId FacilityId { get; set; } + public String FacilityName { get; set; } = String.Empty; + } + + //------------------------------------------------------------------- + // Data. + public new class Data : SacsHierarchyItem.Data + { + // Data members. + private readonly DataProperties data = new DataProperties(); + // Construction. + public Data() + { + Status = DefaultStatus; + } + // Properties. + public SysId ProvinceId + { + get { return data.ProvinceId; } + set { CheckChanged(data.ProvinceId, value); data.ProvinceId = value; } + } + public SysId FacilityId + { + get { return data.FacilityId; } + set { CheckChanged(data.FacilityId, value); data.FacilityId = value; } + } + public String FacilityName + { + get { return data.FacilityName; } + set { CheckChanged(data.FacilityName, value); data.FacilityName = value; } + } + // Population. + internal void PopulateFrom(Data data) + { + ProvinceId = data.ProvinceId; + FacilityId = data.FacilityId; + FacilityName = data.FacilityName; + base.PopulateFrom(data); + } + public Data Clone() + { + Data data = new Data(); + data.PopulateFrom(this); + return data; + } + } + + //------------------------------------------------------------------- + // Error field - identify properties with validation error. + public new class ErrField : SacsHierarchyItem.ErrField + { + // Identifies the field that has invalid data. + public ValidValue ProvinceId { get; set; } = ValidValue.Valid; + public ValidValue FacilityId { get; set; } = ValidValue.Valid; + public ValidValue FacilityName { get; set; } = ValidValue.Valid; + } + + //------------------------------------------------------------------- + // Data members. + private readonly Data data = new Data(); + + //------------------------------------------------------------------- + // Construction. + protected SaxGolfUsgaFacility(SysId id, SysId provinceId) : base(id) + { + base.SetData(data); + this.ProvinceId = provinceId; + Status = DefaultStatus; + } + + //------------------------------------------------------------------- + // Status. + private static readonly List validStatuses = new List() + { + SaStatus.Active, + SaStatus.Inactive, + SaStatus.Deleted, + }; + public static SaStatus DefaultStatus { get { return SaStatus.Active; } } + public static List ValidStatuses { get { return new List(validStatuses); } } + public static DataValue.TriStateType GetStatusTriState(SaStatus status) + { + if (status == SaStatus.Active) return DataValue.TriStateType.Green; + if (status == SaStatus.Inactive) return DataValue.TriStateType.Red; + if (status == SaStatus.Deleted) return DataValue.TriStateType.Purple; + return DataValue.TriStateType.Unknown; + } + + //------------------------------------------------------------------- + // Utilities. + public ItemId GetItemId() + { + return new ItemId((short)Sax.DataItemType.Golf_UsgaFacility, Id); + } + + //------------------------------------------------------------------- + // Properties. + public Data GetData() { return data.Clone(); } + public void SetData(Data data) + { + String fn = GetType().Name + ".SetData"; + // Properties that cannot be changed if previously specified. + if (SysId.IsValid(Id) && SysId.ToInt(Id) != SysId.ToInt(data.Id)) + throw new NotSupportedException(fn + " Id cannot be changed"); + this.data.PopulateFrom(data); + } + public SysId ProvinceId + { + get { return data.ProvinceId; } + set { data.ProvinceId = value; } + } + public SysId FacilityId + { + get { return data.FacilityId; } + set { data.FacilityId = value; } + } + public String FacilityName + { + get { return data.FacilityName; } + set { data.FacilityName = value; } + } + + //------------------------------------------------------------------- + // Flags - positions 1-16 available. + + //------------------------------------------------------------------- + // A s s o c i a t e d D a t a + //------------------------------------------------------------------- + + //------------------------------------------------------------------- + // P a r a m s + //------------------------------------------------------------------- + // List parameters. + public enum StatusCat + { + Any, + ActiveOnly, + InactiveOnly, + NotDeleted, + DeletedOnly, + } + /// + /// Item list parameters. + /// + public new class Params : SacsHierarchyItem.Params + { + // List filtering. + public List IdsIncluded { get; } = new List(); + public List IdsExcluded { get; } = new List(); + public List ProvinceIdsIncluded { get; } = new List(); + /// USGA Facility Ids. + public List FacilityIdsIncluded { get; } = new List(); + /// Generic filter - partial province code or name. + public String FacilityFilter { get; set; } + public String FacilityNameFull { get; set; } + public String FacilityNamePartial { get; set; } + // Common properties. + public String NotesPartial { get; set; } + public StatusCat StatusCat { get; set; } = StatusCat.ActiveOnly; + // Table aliases - blank if not linked. + public String Alias_Country { get; set; } + public String Alias_Province { get; set; } + } + + //------------------------------------------------------------------- + } + //======================================================================= + // Item list extension methods. + public static class SaxGolfUsgaFacilityList + { + //------------------------------------------------------------------- + public static SaxGolfUsgaFacility GetFacilityById(this IEnumerable values, SysId facilityId) + { + if (!SysId.IsValid(facilityId)) return null; + foreach (SaxGolfUsgaFacility province in values) + if (province.Id.Equals(facilityId)) return province; + return null; + } + + //------------------------------------------------------------------- + } + + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaMarker.cs b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaMarker.cs new file mode 100644 index 0000000..9487c2c --- /dev/null +++ b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaMarker.cs @@ -0,0 +1,359 @@ +using NPOI.SS.Formula.Functions; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Saxonite.Net.Standard.Base.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Saxonite.Net.Standard.Base.Bus.Reference +{ + //======================================================================= + // Golf - USGA Marker. + //======================================================================= + public abstract class SaxGolfUsgaMarker : SacsHierarchyItem + { + //------------------------------------------------------------------- + // Columns. + public enum Column + { + Pos, + Id, + CountryId, + Country_Name, + ProvinceId, + Province_Name, + FacilityId, + Facility_Name, + CourseId, + Course_Name, + MarkerId, + Caption, + Holes, + HolesCaption, + Tee, + Gender, + SlopeRating, + Par, + CourseRating, + BogeyRating, + Length, + // Associated data. + // Common. + Notes, + Flags, + Status, + Status_Desc, + Status_Ind, + CreateOn_Date, + UpdateOn_Date, + } + + //------------------------------------------------------------------- + /// Properties other than common. + public class DataProperties + { + public SysId CourseId { get; set; } + public SysId MarkerId { get; set; } + public String Caption { get; set; } = ""; + public short Holes { get; set; } + public String HolesCaption { get; set; } = ""; + public String Tee { get; set; } = ""; + public String Gender { get; set; } = ""; + public short SlopeRating { get; set; } + public short Par { get; set; } + public decimal CourseRating { get; set; } + public decimal BogeyRating { get; set; } + public short Length { get; set; } + } + + //------------------------------------------------------------------- + // Data. + public new class Data : SacsHierarchyItem.Data + { + // Data members. + private readonly DataProperties data = new DataProperties(); + // Construction. + public Data() + { + Status = DefaultStatus; + } + // Properties. + public SysId CourseId + { + get { return data.CourseId; } + set { CheckChanged(data.CourseId, value); data.CourseId = value; } + } + public SysId MarkerId + { + get { return data.MarkerId; } + set { CheckChanged(data.MarkerId, value); data.MarkerId = value; } + } + public String Caption + { + get { return data.Caption; } + set { CheckChanged(data.Caption, value); data.Caption = value; } + } + public short Holes + { + get { return data.Holes; } + set { CheckChanged(data.Holes, value); data.Holes = value; } + } + public String HolesCaption + { + get { return data.HolesCaption; } + set { CheckChanged(data.HolesCaption, value); data.HolesCaption = value; } + } + public String Tee + { + get { return data.Tee; } + set { CheckChanged(data.Tee, value); data.Tee = value; } + } + public String Gender + { + get { return data.Gender; } + set { CheckChanged(data.Gender, value); data.Gender = value; } + } + public short SlopeRating + { + get { return data.SlopeRating; } + set { CheckChanged(data.SlopeRating, value); data.SlopeRating = value; } + } + public short Par + { + get { return data.Par; } + set { CheckChanged(data.Par, value); data.Par = value; } + } + public decimal CourseRating + { + get { return data.CourseRating; } + set { CheckChanged(data.CourseRating, value); data.CourseRating = value; } + } + public decimal BogeyRating + { + get { return data.BogeyRating; } + set { CheckChanged(data.BogeyRating, value); data.BogeyRating = value; } + } + public short Length + { + get { return data.Length; } + set { CheckChanged(data.Length, value); data.Length = value; } + } + // Population. + internal void PopulateFrom(Data data) + { + CourseId = data.CourseId; + MarkerId = data.MarkerId; + Caption = data.Caption; + Holes = data.Holes; + HolesCaption = data.HolesCaption; + Tee = data.Tee; + Gender = data.Gender; + SlopeRating = data.SlopeRating; + Par = data.Par; + CourseRating = data.CourseRating; + BogeyRating = data.BogeyRating; + Length = data.Length; + base.PopulateFrom(data); + } + public Data Clone() + { + Data data = new Data(); + data.PopulateFrom(this); + return data; + } + } + + //------------------------------------------------------------------- + // Error field - identify properties with validation error. + public new class ErrField : SacsHierarchyItem.ErrField + { + // Identifies the field that has invalid data. + public ValidValue CourseId { get; set; } = ValidValue.Valid; + public ValidValue MarkerId { get; set; } = ValidValue.Valid; + public ValidValue Caption { get; set; } = ValidValue.Valid; + public ValidValue Holes { get; set; } = ValidValue.Valid; + public ValidValue HolesCaption { get; set; } = ValidValue.Valid; + public ValidValue Tee { get; set; } = ValidValue.Valid; + public ValidValue Gender { get; set; } = ValidValue.Valid; + public ValidValue SlopeRating { get; set; } = ValidValue.Valid; + public ValidValue Par { get; set; } = ValidValue.Valid; + public ValidValue CourseRating { get; set; } = ValidValue.Valid; + public ValidValue BogeyRating { get; set; } = ValidValue.Valid; + public ValidValue Length { get; set; } = ValidValue.Valid; + } + + //------------------------------------------------------------------- + // Data members. + private readonly Data data = new Data(); + + //------------------------------------------------------------------- + // Construction. + protected SaxGolfUsgaMarker(SysId id, SysId facilityId) : base(id) + { + base.SetData(data); + this.CourseId = facilityId; + Status = DefaultStatus; + } + + //------------------------------------------------------------------- + // Status. + private static readonly List validStatuses = new List() + { + SaStatus.Active, + SaStatus.Inactive, + SaStatus.Deleted, + }; + public static SaStatus DefaultStatus { get { return SaStatus.Active; } } + public static List ValidStatuses { get { return new List(validStatuses); } } + public static DataValue.TriStateType GetStatusTriState(SaStatus status) + { + if (status == SaStatus.Active) return DataValue.TriStateType.Green; + if (status == SaStatus.Inactive) return DataValue.TriStateType.Red; + if (status == SaStatus.Deleted) return DataValue.TriStateType.Purple; + return DataValue.TriStateType.Unknown; + } + + //------------------------------------------------------------------- + // Utilities. + public ItemId GetItemId() + { + return new ItemId((short)Sax.DataItemType.Golf_UsgaMarker, Id); + } + + //------------------------------------------------------------------- + // Properties. + public Data GetData() { return data.Clone(); } + public void SetData(Data data) + { + String fn = GetType().Name + ".SetData"; + // Properties that cannot be changed if previously specified. + if (SysId.IsValid(Id) && SysId.ToInt(Id) != SysId.ToInt(data.Id)) + throw new NotSupportedException(fn + " Id cannot be changed"); + this.data.PopulateFrom(data); + } + public SysId CourseId + { + get { return data.CourseId; } + set { data.CourseId = value; } + } + public SysId MarkerId + { + get { return data.MarkerId; } + set { data.MarkerId = value; } + } + public String Caption + { + get { return data.Caption; } + set { data.Caption = value; } + } + public short Holes + { + get { return data.Holes; } + set { data.Holes = value; } + } + public String HolesCaption + { + get { return data.HolesCaption; } + set { data.HolesCaption = value; } + } + public String Tee + { + get { return data.Tee; } + set { data.Tee = value; } + } + public String Gender + { + get { return data.Gender; } + set { data.Gender = value; } + } + public short SlopeRating + { + get { return data.SlopeRating; } + set { data.SlopeRating = value; } + } + public short Par + { + get { return data.Par; } + set { data.Par = value; } + } + public decimal CourseRating + { + get { return data.CourseRating; } + set { data.CourseRating = value; } + } + public decimal BogeyRating + { + get { return data.BogeyRating; } + set { data.BogeyRating = value; } + } + public short Length + { + get { return data.Length; } + set { data.Length = value; } + } + + //------------------------------------------------------------------- + // Flags - positions 1-16 available. + + //------------------------------------------------------------------- + // A s s o c i a t e d D a t a + //------------------------------------------------------------------- + + //------------------------------------------------------------------- + // P a r a m s + //------------------------------------------------------------------- + // List parameters. + public enum StatusCat + { + Any, + ActiveOnly, + InactiveOnly, + NotDeleted, + DeletedOnly, + } + /// + /// Item list parameters. + /// + public new class Params : SacsHierarchyItem.Params + { + // List filtering. + public List IdsIncluded { get; } = new List(); + public List IdsExcluded { get; } = new List(); + public List CourseIdsIncluded { get; } = new List(); + /// USGA Marker Ids. + public List MarkerIdsIncluded { get; } = new List(); + /// Generic filter - partial caption, holes, tee, gender etc. + public String MarkerFilter { get; set; } + // Common properties. + public String NotesPartial { get; set; } + public StatusCat StatusCat { get; set; } = StatusCat.ActiveOnly; + // Table aliases - blank if not linked. + public String Alias_Country { get; set; } + public String Alias_Province { get; set; } + public String Alias_Facility { get; set; } + public String Alias_Course{ get; set; } + } + + //------------------------------------------------------------------- + } + //======================================================================= + // Item list extension methods. + public static class SaxGolfUsgaMarkerList + { + //------------------------------------------------------------------- + public static SaxGolfUsgaMarker GetMarkerById(this IEnumerable values, SysId markerId) + { + if (!SysId.IsValid(markerId)) return null; + foreach (SaxGolfUsgaMarker province in values) + if (province.Id.Equals(markerId)) return province; + return null; + } + + //------------------------------------------------------------------- + } + + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaProvince.cs b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaProvince.cs new file mode 100644 index 0000000..87b1f2c --- /dev/null +++ b/SaxoniteStandardBase/Base/Bus/Reference/SaxGolfUsgaProvince.cs @@ -0,0 +1,239 @@ +using NPOI.SS.Formula.Functions; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Saxonite.Net.Standard.Base.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Saxonite.Net.Standard.Base.Bus.Reference +{ + //======================================================================= + // Golf - USGA Province. + //======================================================================= + public abstract class SaxGolfUsgaProvince : SacsHierarchyItem + { + //------------------------------------------------------------------- + // Columns. + public enum Column + { + Pos, + Id, + CountryId, + Country_Name, + ProvinceCode, + EntProvinceCode, + ProvinceName, + // Associated data. + // Common. + Notes, + Flags, + Status, + Status_Desc, + Status_Ind, + CreateOn_Date, + UpdateOn_Date, + } + + //------------------------------------------------------------------- + /// Properties other than common. + public class DataProperties + { + public SysId CountryId { get; set; } + public String ProvinceCode { get; set; } = String.Empty; + public String EntProvinceCode { get; set; } = String.Empty; + public String ProvinceName { get; set; } = String.Empty; + } + + //------------------------------------------------------------------- + // Data. + public new class Data : SacsHierarchyItem.Data + { + // Data members. + private readonly DataProperties data = new DataProperties(); + // Construction. + public Data() + { + Status = DefaultStatus; + } + // Properties. + public SysId CountryId + { + get { return data.CountryId; } + set { CheckChanged(data.CountryId, value); data.CountryId = value; } + } + public String ProvinceCode + { + get { return data.ProvinceCode; } + set { CheckChanged(data.ProvinceCode, value); data.ProvinceCode = value; } + } + public String EntProvinceCode + { + get { return data.EntProvinceCode; } + set { CheckChanged(data.EntProvinceCode, value); data.EntProvinceCode = value; } + } + public String ProvinceName + { + get { return data.ProvinceName; } + set { CheckChanged(data.ProvinceName, value); data.ProvinceName = value; } + } + // Population. + internal void PopulateFrom(Data data) + { + CountryId = data.CountryId; + ProvinceCode = data.ProvinceCode; + EntProvinceCode = data.EntProvinceCode; + ProvinceName = data.ProvinceName; + base.PopulateFrom(data); + } + public Data Clone() + { + Data data = new Data(); + data.PopulateFrom(this); + return data; + } + } + + //------------------------------------------------------------------- + // Error field - identify properties with validation error. + public new class ErrField : SacsHierarchyItem.ErrField + { + // Identifies the field that has invalid data. + public ValidValue CountryId { get; set; } = ValidValue.Valid; + public ValidValue ProvinceCode { get; set; } = ValidValue.Valid; + public ValidValue EntProvinceCode { get; set; } = ValidValue.Valid; + public ValidValue ProvinceName { get; set; } = ValidValue.Valid; + } + + //------------------------------------------------------------------- + // Data members. + private readonly Data data = new Data(); + + //------------------------------------------------------------------- + // Construction. + protected SaxGolfUsgaProvince(SysId id, SysId countryId) : base(id) + { + base.SetData(data); + this.CountryId = countryId; + Status = DefaultStatus; + } + + //------------------------------------------------------------------- + // Status. + private static readonly List validStatuses = new List() + { + SaStatus.Active, + SaStatus.Inactive, + SaStatus.Deleted, + }; + public static SaStatus DefaultStatus { get { return SaStatus.Active; } } + public static List ValidStatuses { get { return new List(validStatuses); } } + public static DataValue.TriStateType GetStatusTriState(SaStatus status) + { + if (status == SaStatus.Active) return DataValue.TriStateType.Green; + if (status == SaStatus.Inactive) return DataValue.TriStateType.Red; + if (status == SaStatus.Deleted) return DataValue.TriStateType.Purple; + return DataValue.TriStateType.Unknown; + } + + //------------------------------------------------------------------- + // Utilities. + public ItemId GetItemId() + { + return new ItemId((short)Sax.DataItemType.Golf_UsgaProvince, Id); + } + + //------------------------------------------------------------------- + // Properties. + public Data GetData() { return data.Clone(); } + public void SetData(Data data) + { + String fn = GetType().Name + ".SetData"; + // Properties that cannot be changed if previously specified. + if (SysId.IsValid(Id) && SysId.ToInt(Id) != SysId.ToInt(data.Id)) + throw new NotSupportedException(fn + " Id cannot be changed"); + this.data.PopulateFrom(data); + } + public SysId CountryId + { + get { return data.CountryId; } + set { data.CountryId = value; } + } + public String ProvinceCode + { + get { return data.ProvinceCode; } + set { data.ProvinceCode = value; } + } + public String EntProvinceCode + { + get { return data.EntProvinceCode; } + set { data.EntProvinceCode = value; } + } + public String ProvinceName + { + get { return data.ProvinceName; } + set { data.ProvinceName = value; } + } + + //------------------------------------------------------------------- + // Flags - positions 1-16 available. + + //------------------------------------------------------------------- + // A s s o c i a t e d D a t a + //------------------------------------------------------------------- + + //------------------------------------------------------------------- + // P a r a m s + //------------------------------------------------------------------- + // List parameters. + public enum StatusCat + { + Any, + ActiveOnly, + InactiveOnly, + NotDeleted, + DeletedOnly, + } + /// + /// Item list parameters. + /// + public new class Params : SacsHierarchyItem.Params + { + // List filtering. + public List IdsIncluded { get; } = new List(); + public List IdsExcluded { get; } = new List(); + public List CountryIdsIncluded { get; } = new List(); + /// Generic filter - partial province code or name. + public String ProvinceFilter { get; set; } + public String ProvinceCodeFull { get; set; } + public String ProvinceNameFull { get; set; } + public String ProvinceNamePartial { get; set; } + // Common properties. + public String NotesPartial { get; set; } + public StatusCat StatusCat { get; set; } = StatusCat.ActiveOnly; + // Table aliases - blank if not linked. + public String Alias_Country { get; set; } + } + + //------------------------------------------------------------------- + } + //======================================================================= + // Item list extension methods. + public static class SaxGolfUsgaProvinceList + { + //------------------------------------------------------------------- + public static SaxGolfUsgaProvince GetProvinceById(this IEnumerable values, SysId provinceId) + { + if (!SysId.IsValid(provinceId)) return null; + foreach (SaxGolfUsgaProvince province in values) + if (province.Id.Equals(provinceId)) return province; + return null; + } + + //------------------------------------------------------------------- + } + + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Bus/SaxOrganisationEvent.cs b/SaxoniteStandardBase/Base/Bus/SaxOrganisationEvent.cs index 2fd62fb..a1fcf63 100644 --- a/SaxoniteStandardBase/Base/Bus/SaxOrganisationEvent.cs +++ b/SaxoniteStandardBase/Base/Bus/SaxOrganisationEvent.cs @@ -174,10 +174,10 @@ namespace Saxonite.Net.Standard.Base.Bus //------------------------------------------------------------------- // Construction. - protected SaxOrganisationEvent(SysId id, SysId OrganisationId) : base(id) + protected SaxOrganisationEvent(SysId id, SysId organisationId) : base(id) { base.SetData(data); - this.OrganisationId = OrganisationId; + this.OrganisationId = organisationId; Status = DefaultStatus; } diff --git a/SaxoniteStandardBase/Base/Mgr/Reference/SaxItemMgr_Reference.cs b/SaxoniteStandardBase/Base/Mgr/Reference/SaxItemMgr_Reference.cs new file mode 100644 index 0000000..9735b4a --- /dev/null +++ b/SaxoniteStandardBase/Base/Mgr/Reference/SaxItemMgr_Reference.cs @@ -0,0 +1,43 @@ +using NPOI.SS.Formula.Functions; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Net.Standard.Base.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Saxonite.Net.Standard.Base.Mgr.Reference +{ + //======================================================================= + public class SaxItemMgr_Reference : SaxItemMgr + { + //------------------------------------------------------------------- + // Data members. + + //------------------------------------------------------------------- + protected SaxItemMgr_Reference(SaxSessionContext sessionContext, SaxInternals internals) : + base(sessionContext, internals) + { + } + protected override void Dispose(bool disposing) + { + if (disposing) + { + } + base.Dispose(disposing); + } + + //------------------------------------------------------------------- + // Properties. + public ISacsDatabase ReferenceDatabase { get { return SaxGlobals.App.GetDatabase(SessionContext, Sax.Database.Reference); } } + public IDatabaseInfo ReferenceDbInfo { get { return SaxGlobals.App.CreateDbInfo(SessionContext, Sax.Database.Reference); } } + // Managers. + public SaxReferenceGolfMgr ReferenceGolfMgr { get { return Internals.ReferenceGolfMgr; } } + // Application codes. + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaCountry.cs b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaCountry.cs new file mode 100644 index 0000000..3581c56 --- /dev/null +++ b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaCountry.cs @@ -0,0 +1,187 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; +using System.Collections.Generic; + +namespace Saxonite.Net.Standard.Base.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr + { + //******************************************************************* + // Reference Mgr - Golf - USGA Country + //******************************************************************* + // Utilities. + + //------------------------------------------------------------------- + // Create item. + public abstract SaxGolfUsgaCountry CreateUsgaCountry(); + + //------------------------------------------------------------------- + // Item exists. + public bool UsgaCountryExistsById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return false; + SaxGolfUsgaCountry.Params prmUsgaCountry = new SaxGolfUsgaCountry.Params(); + prmUsgaCountry.IdsIncluded.Add(id); + prmUsgaCountry.StatusCat = SaxGolfUsgaCountry.StatusCat.Any; + return GetUsgaCountryCount(prmUsgaCountry) == 1; + } + + //------------------------------------------------------------------- + // Retrieve individual items. + public abstract SaxGolfUsgaCountry GetUsgaCountry(SaxGolfUsgaCountry.Params prmUsgaCountry); + public SaxGolfUsgaCountry GetUsgaCountryById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return null; + SaxGolfUsgaCountry.Params prmUsgaCountry = new SaxGolfUsgaCountry.Params(); + prmUsgaCountry.IdsIncluded.Add(id); + prmUsgaCountry.StatusCat = SaxGolfUsgaCountry.StatusCat.Any; + return GetUsgaCountry(prmUsgaCountry); + } + + //------------------------------------------------------------------- + // Validate item data. + public bool IsValidUsgaCountry(SaxGolfUsgaCountry usgaCountry) + { + ClearErrorState(); + if (usgaCountry == null) return SetErrorState(ErrorMessage.ItemNotSpecified); + return IsValidUsgaCountryData(usgaCountry.GetData(), new SaxGolfUsgaCountry.ErrField()); + } + public virtual bool IsValidUsgaCountryData(SaxGolfUsgaCountry.Data data, SaxGolfUsgaCountry.ErrField errField) + { + ClearErrorState(); + + //--------------------------------------------------------------- + // Country code. + if (errField.CountryCode != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.CountryCode, "code", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryCode), true)) + { + errField.CountryCode = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // ENT Country code. + if (errField.EntCountryCode != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.EntCountryCode, "ent code", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_EntCountryCode))) + { + errField.EntCountryCode = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Country name. + if (errField.CountryName != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.CountryName, "name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName), true)) + { + errField.CountryName = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + + //--------------------------------------------------------------- + // Common properties. + if (errField.Notes != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Notes, "notes", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Notes))) + { + errField.Notes = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (errField.Status != SacsHierarchyItem.ValidValue.Ignore) + { + if (!IsValidValue(data.StatusCode, "status", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Status), true, true)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (!SaxGolfUsgaCountry.ValidStatuses.Contains(data.Status)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState(ErrorMessage.InvalidStatus); + } + } + + //--------------------------------------------------------------- + return true; + } + + //------------------------------------------------------------------- + // Item database interface. + public abstract bool InsertUsgaCountry(SaxGolfUsgaCountry usgaCountry, DbUpdateInfo dbUpdateInfo); + public abstract bool UpdateUsgaCountry(SaxGolfUsgaCountry usgaCountry, DbUpdateInfo dbUpdateInfo); + public virtual bool UsgaCountryCanBeDeleted(SaxGolfUsgaCountry usgaCountry) + { + ClearErrorState(); + return true; + } + public abstract bool DeleteUsgaCountry(SaxGolfUsgaCountry usgaCountry, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Bulk updates. + public class UsgaCountryData + { + public String CountryCode { get; set; } + public String EntCountryCode { get; set; } = null; + public String CountryName { get; set; } = null; + } + /// + /// Bulk update USGA Countries. + /// - Country code must be supplied to act as identifier. + /// - Other properties are validated as per country rules - check error state. + /// - Other properties are left as is if null. + /// + public abstract bool BulkUpdateUsgaCountries(List countries, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Item list. + public abstract ColumnDfn GetUsgaCountryColumnDfn(SaxGolfUsgaCountry.Column columnId, String caption = "", int width = 0); + public abstract List GetUsgaCountryQueryFilter(SaxGolfUsgaCountry.Params prmUsgaCountry); + public abstract long GetUsgaCountryCount(SaxGolfUsgaCountry.Params prmUsgaCountry); + public long GetActiveUsgaCountryCount() { return GetUsgaCountryCount(new SaxGolfUsgaCountry.Params()); } + public abstract List GetUsgaCountryList(SaxGolfUsgaCountry.Params prmUsgaCountry); + public abstract DbResultSet ExecuteUsgaCountryQuery(List columns, SaxGolfUsgaCountry.Params prmUsgaCountry); + + //------------------------------------------------------------------- + /// + /// Extract and format result set data value where specific handling is required. + /// Where response is an invalid data value, format value using column.FormatValue(values). + /// + public virtual DataValue GetUsgaCountryDataValue(ColumnDfn column, NamedValue.Map values) + { + DataValue value = new DataValue(); + switch ((SaxGolfUsgaCountry.Column)column.Id) + { + //----------------------------------------------------------- + // Notes. + case SaxGolfUsgaCountry.Column.Notes: + { + value = new DataValue(SacsHierarchyItem.FormatForDisplay(values.GetValue(column.DataName).ToString(), 200)); + } + break; + + //----------------------------------------------------------- + // Status. + case SaxGolfUsgaCountry.Column.Status_Desc: + case SaxGolfUsgaCountry.Column.Status_Ind: + { + String statusCode = values.GetValue(column.DataName).ToString(); + SaStatus status = SacsSystem.GetStatusForCode(statusCode); + if (column.Id == (int)SaxGolfUsgaCountry.Column.Status_Desc) + value = new DataValue(SacsSystem.GetStatusDesc(status)); + else if (column.Id == (int)SaxGolfUsgaCountry.Column.Status_Ind) + value = new DataValue(SaxGolfUsgaCountry.GetStatusTriState(status)); + } + break; + + //----------------------------------------------------------- + default: + value = values.GetValue(column.DataName); + break; + + } + return value; + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaCourse.cs b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaCourse.cs new file mode 100644 index 0000000..82ce798 --- /dev/null +++ b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaCourse.cs @@ -0,0 +1,257 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; +using System.Collections.Generic; + +namespace Saxonite.Net.Standard.Base.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr + { + //******************************************************************* + // Reference Mgr - Golf - USGA Course + //******************************************************************* + // Utilities. + + //------------------------------------------------------------------- + // Create item. + public abstract SaxGolfUsgaCourse CreateUsgaCourse(SysId facilityId); + + //------------------------------------------------------------------- + // Item exists. + public bool UsgaCourseExistsById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return false; + SaxGolfUsgaCourse.Params prmUsgaCourse = new SaxGolfUsgaCourse.Params(); + prmUsgaCourse.IdsIncluded.Add(id); + prmUsgaCourse.StatusCat = SaxGolfUsgaCourse.StatusCat.Any; + return GetUsgaCourseCount(prmUsgaCourse) == 1; + } + + //------------------------------------------------------------------- + // Retrieve individual items. + public abstract SaxGolfUsgaCourse GetUsgaCourse(SaxGolfUsgaCourse.Params prmUsgaCourse); + public SaxGolfUsgaCourse GetUsgaCourseById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return null; + SaxGolfUsgaCourse.Params prmUsgaCourse = new SaxGolfUsgaCourse.Params(); + prmUsgaCourse.IdsIncluded.Add(id); + prmUsgaCourse.StatusCat = SaxGolfUsgaCourse.StatusCat.Any; + return GetUsgaCourse(prmUsgaCourse); + } + + //------------------------------------------------------------------- + // Validate item data. + public bool IsValidUsgaCourse(SaxGolfUsgaCourse usgaCourse) + { + ClearErrorState(); + if (usgaCourse == null) return SetErrorState(ErrorMessage.ItemNotSpecified); + return IsValidUsgaCourseData(usgaCourse.GetData(), new SaxGolfUsgaCourse.ErrField()); + } + public virtual bool IsValidUsgaCourseData(SaxGolfUsgaCourse.Data data, SaxGolfUsgaCourse.ErrField errField) + { + ClearErrorState(); + + //--------------------------------------------------------------- + // Facility. + if (errField.FacilityId != SacsHierarchyItem.ValidValue.Ignore && !SysId.IsValid(data.FacilityId)) + { + errField.FacilityId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Facility must be specified"); + } + // Course Id. + if (errField.CourseId != SacsHierarchyItem.ValidValue.Ignore && !SysId.IsValid(data.CourseId)) + { + errField.CourseId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Course Id must be specified"); + } + // Caption. + if (errField.Caption != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Caption, "caption", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Caption), true)) + { + errField.Caption = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Course name. + if (errField.CourseName != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.CourseName, "name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName), true)) + { + errField.CourseName = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Full name. + if (errField.FullName != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.FullName, "full name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FullName))) + { + errField.FullName = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Address line 1. + if (errField.Address1 != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Address1, "address line 1", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address1))) + { + errField.Address1 = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Address line 2. + if (errField.Address2 != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Address2, "address line 2", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address2))) + { + errField.Address2 = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // City. + if (errField.City != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.City, "city", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_City))) + { + errField.City = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Email. + if (errField.Email != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Email, "email", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Email))) + { + errField.Email = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Telephone. + if (errField.Telephone != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Telephone, "telephone", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Telephone))) + { + errField.Telephone = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + + //--------------------------------------------------------------- + // Common properties. + if (errField.Notes != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Notes, "notes", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Notes))) + { + errField.Notes = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (errField.Status != SacsHierarchyItem.ValidValue.Ignore) + { + if (!IsValidValue(data.StatusCode, "status", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Status), true, true)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (!SaxGolfUsgaCourse.ValidStatuses.Contains(data.Status)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState(ErrorMessage.InvalidStatus); + } + } + + //--------------------------------------------------------------- + // Associated data - ignore for deleted items. + if (!data.IsStatusDeleted) + { + + // Facility. + if (errField.FacilityId != SacsHierarchyItem.ValidValue.Ignore && SysId.IsValid(data.FacilityId)) + { + SaxGolfUsgaFacility.Params prmFacility = new SaxGolfUsgaFacility.Params(); + prmFacility.IdsIncluded.Add(data.FacilityId); + prmFacility.StatusCat = SaxGolfUsgaFacility.StatusCat.NotDeleted; + if (ReferenceGolfMgr.GetUsgaFacilityCount(prmFacility) < 1) + { + errField.FacilityId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Invalid course specified"); + } + } + } + + //--------------------------------------------------------------- + return true; + } + + //------------------------------------------------------------------- + // Item database interface. + public abstract bool InsertUsgaCourse(SaxGolfUsgaCourse usgaCourse, DbUpdateInfo dbUpdateInfo); + public abstract bool UpdateUsgaCourse(SaxGolfUsgaCourse usgaCourse, DbUpdateInfo dbUpdateInfo); + public virtual bool UsgaCourseCanBeDeleted(SaxGolfUsgaCourse usgaCourse) + { + ClearErrorState(); + return true; + } + public abstract bool DeleteUsgaCourse(SaxGolfUsgaCourse usgaCourse, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Bulk updates. + public class UsgaCourseData + { + public SysId FacilityId { get; set; } + public SysId CourseId { get; set; } + public SysId LegacyCrpCourseId { get; set; } + public string Caption { get; set; } + public string CourseName { get; set; } + public string FullName { get; set; } + public string Address1 { get; set; } + public string Address2 { get; set; } + public string City { get; set; } + public string Email { get; set; } + public string Telephone { get; set; } + } + /// + /// Bulk update USGA Courses. + /// - Facility code must be supplied to identify parent. + /// - Course Id must be supplied to act as identifier. + /// - Other properties are validated as per province rules - check error state. + /// - Other properties are left as is if null. + /// + public abstract bool BulkUpdateUsgaCourses(List courses, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Item list. + public abstract ColumnDfn GetUsgaCourseColumnDfn(SaxGolfUsgaCourse.Column columnId, String caption = "", int width = 0); + public abstract List GetUsgaCourseQueryFilter(SaxGolfUsgaCourse.Params prmUsgaCourse); + public abstract long GetUsgaCourseCount(SaxGolfUsgaCourse.Params prmUsgaCourse); + public abstract List GetUsgaCourseList(SaxGolfUsgaCourse.Params prmUsgaCourse); + public abstract DbResultSet ExecuteUsgaCourseQuery(List columns, SaxGolfUsgaCourse.Params prmUsgaCourse); + + //------------------------------------------------------------------- + /// + /// Extract and format result set data value where specific handling is required. + /// Where response is an invalid data value, format value using column.FormatValue(values). + /// + public virtual DataValue GetUsgaCourseDataValue(ColumnDfn column, NamedValue.Map values) + { + DataValue value = new DataValue(); + switch ((SaxGolfUsgaCourse.Column)column.Id) + { + //----------------------------------------------------------- + // Notes. + case SaxGolfUsgaCourse.Column.Notes: + { + value = new DataValue(SacsHierarchyItem.FormatForDisplay(values.GetValue(column.DataName).ToString(), 200)); + } + break; + + //----------------------------------------------------------- + // Status. + case SaxGolfUsgaCourse.Column.Status_Desc: + case SaxGolfUsgaCourse.Column.Status_Ind: + { + String statusCode = values.GetValue(column.DataName).ToString(); + SaStatus status = SacsSystem.GetStatusForCode(statusCode); + if (column.Id == (int)SaxGolfUsgaCourse.Column.Status_Desc) + value = new DataValue(SacsSystem.GetStatusDesc(status)); + else if (column.Id == (int)SaxGolfUsgaCourse.Column.Status_Ind) + value = new DataValue(SaxGolfUsgaCourse.GetStatusTriState(status)); + } + break; + + //----------------------------------------------------------- + default: + value = values.GetValue(column.DataName); + break; + + } + return value; + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaFacility.cs b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaFacility.cs new file mode 100644 index 0000000..90cfb5f --- /dev/null +++ b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaFacility.cs @@ -0,0 +1,207 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; +using System.Collections.Generic; + +namespace Saxonite.Net.Standard.Base.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr + { + //******************************************************************* + // Reference Mgr - Golf - USGA Facility + //******************************************************************* + // Utilities. + + //------------------------------------------------------------------- + // Create item. + public abstract SaxGolfUsgaFacility CreateUsgaFacility(SysId provinceId); + + //------------------------------------------------------------------- + // Item exists. + public bool UsgaFacilityExistsById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return false; + SaxGolfUsgaFacility.Params prmUsgaFacility = new SaxGolfUsgaFacility.Params(); + prmUsgaFacility.IdsIncluded.Add(id); + prmUsgaFacility.StatusCat = SaxGolfUsgaFacility.StatusCat.Any; + return GetUsgaFacilityCount(prmUsgaFacility) == 1; + } + + //------------------------------------------------------------------- + // Retrieve individual items. + public abstract SaxGolfUsgaFacility GetUsgaFacility(SaxGolfUsgaFacility.Params prmUsgaFacility); + public SaxGolfUsgaFacility GetUsgaFacilityById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return null; + SaxGolfUsgaFacility.Params prmUsgaFacility = new SaxGolfUsgaFacility.Params(); + prmUsgaFacility.IdsIncluded.Add(id); + prmUsgaFacility.StatusCat = SaxGolfUsgaFacility.StatusCat.Any; + return GetUsgaFacility(prmUsgaFacility); + } + + //------------------------------------------------------------------- + // Validate item data. + public bool IsValidUsgaFacility(SaxGolfUsgaFacility usgaFacility) + { + ClearErrorState(); + if (usgaFacility == null) return SetErrorState(ErrorMessage.ItemNotSpecified); + return IsValidUsgaFacilityData(usgaFacility.GetData(), new SaxGolfUsgaFacility.ErrField()); + } + public virtual bool IsValidUsgaFacilityData(SaxGolfUsgaFacility.Data data, SaxGolfUsgaFacility.ErrField errField) + { + ClearErrorState(); + + //--------------------------------------------------------------- + // Province. + if (errField.ProvinceId != SacsHierarchyItem.ValidValue.Ignore && !SysId.IsValid(data.ProvinceId)) + { + errField.ProvinceId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Province must be specified"); + } + // Facility code. + if (errField.FacilityId != SacsHierarchyItem.ValidValue.Ignore && !SysId.IsValid(data.FacilityId)) + { + errField.FacilityId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Facility Id must be specified"); + } + // Facility name. + if (errField.FacilityName != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.FacilityName, "name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName), true)) + { + errField.FacilityName = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + + //--------------------------------------------------------------- + // Common properties. + if (errField.Notes != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Notes, "notes", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Notes))) + { + errField.Notes = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (errField.Status != SacsHierarchyItem.ValidValue.Ignore) + { + if (!IsValidValue(data.StatusCode, "status", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Status), true, true)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (!SaxGolfUsgaFacility.ValidStatuses.Contains(data.Status)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState(ErrorMessage.InvalidStatus); + } + } + + //--------------------------------------------------------------- + // Associated data - ignore for deleted items. + if (!data.IsStatusDeleted) + { + + // Province. + if (errField.ProvinceId != SacsHierarchyItem.ValidValue.Ignore && SysId.IsValid(data.ProvinceId)) + { + SaxGolfUsgaProvince.Params prmProvince = new SaxGolfUsgaProvince.Params(); + prmProvince.IdsIncluded.Add(data.ProvinceId); + prmProvince.StatusCat = SaxGolfUsgaProvince.StatusCat.NotDeleted; + if (ReferenceGolfMgr.GetUsgaProvinceCount(prmProvince) < 1) + { + errField.ProvinceId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Invalid province specified"); + } + } + } + + //--------------------------------------------------------------- + return true; + } + + //------------------------------------------------------------------- + // Item database interface. + public abstract bool InsertUsgaFacility(SaxGolfUsgaFacility usgaFacility, DbUpdateInfo dbUpdateInfo); + public abstract bool UpdateUsgaFacility(SaxGolfUsgaFacility usgaFacility, DbUpdateInfo dbUpdateInfo); + public virtual bool UsgaFacilityCanBeDeleted(SaxGolfUsgaFacility usgaFacility) + { + ClearErrorState(); + return true; + } + public abstract bool DeleteUsgaFacility(SaxGolfUsgaFacility usgaFacility, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Bulk updates. + public class UsgaFacilityData + { + public String ProvinceCode { get; set; } + public SysId FacilityId { get; set; } + public String FacilityName { get; set; } = null; + } + /// + /// Bulk update USGA Facilities. + /// - Province code must be supplied to identify parent. + /// - Facility Id must be supplied to act as identifier. + /// - Other properties are validated as per province rules - check error state. + /// - Other properties are left as is if null. + /// + public abstract bool BulkUpdateUsgaFacilities(List facilities, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Item list. + public abstract ColumnDfn GetUsgaFacilityColumnDfn(SaxGolfUsgaFacility.Column columnId, String caption = "", int width = 0); + public abstract List GetUsgaFacilityQueryFilter(SaxGolfUsgaFacility.Params prmUsgaFacility); + public abstract long GetUsgaFacilityCount(SaxGolfUsgaFacility.Params prmUsgaFacility); + public abstract List GetUsgaFacilityList(SaxGolfUsgaFacility.Params prmUsgaFacility); + public abstract DbResultSet ExecuteUsgaFacilityQuery(List columns, SaxGolfUsgaFacility.Params prmUsgaFacility); + + //------------------------------------------------------------------- + /// + /// Extract and format result set data value where specific handling is required. + /// Where response is an invalid data value, format value using column.FormatValue(values). + /// + public virtual DataValue GetUsgaFacilityDataValue(ColumnDfn column, NamedValue.Map values) + { + DataValue value = new DataValue(); + switch ((SaxGolfUsgaFacility.Column)column.Id) + { + //----------------------------------------------------------- + // Notes. + case SaxGolfUsgaFacility.Column.Notes: + { + value = new DataValue(SacsHierarchyItem.FormatForDisplay(values.GetValue(column.DataName).ToString(), 200)); + } + break; + + //----------------------------------------------------------- + // Status. + case SaxGolfUsgaFacility.Column.Status_Desc: + case SaxGolfUsgaFacility.Column.Status_Ind: + { + String statusCode = values.GetValue(column.DataName).ToString(); + SaStatus status = SacsSystem.GetStatusForCode(statusCode); + if (column.Id == (int)SaxGolfUsgaFacility.Column.Status_Desc) + value = new DataValue(SacsSystem.GetStatusDesc(status)); + else if (column.Id == (int)SaxGolfUsgaFacility.Column.Status_Ind) + value = new DataValue(SaxGolfUsgaFacility.GetStatusTriState(status)); + } + break; + + //----------------------------------------------------------- + default: + value = values.GetValue(column.DataName); + break; + + } + return value; + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaMarker.cs b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaMarker.cs new file mode 100644 index 0000000..5d1e501 --- /dev/null +++ b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaMarker.cs @@ -0,0 +1,258 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; +using System.Collections.Generic; + +namespace Saxonite.Net.Standard.Base.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr + { + //******************************************************************* + // Reference Mgr - Golf - USGA Marker + //******************************************************************* + // Utilities. + + //------------------------------------------------------------------- + // Create item. + public abstract SaxGolfUsgaMarker CreateUsgaMarker(SysId courseId); + + //------------------------------------------------------------------- + // Item exists. + public bool UsgaMarkerExistsById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return false; + SaxGolfUsgaMarker.Params prmUsgaMarker = new SaxGolfUsgaMarker.Params(); + prmUsgaMarker.IdsIncluded.Add(id); + prmUsgaMarker.StatusCat = SaxGolfUsgaMarker.StatusCat.Any; + return GetUsgaMarkerCount(prmUsgaMarker) == 1; + } + + //------------------------------------------------------------------- + // Retrieve individual items. + public abstract SaxGolfUsgaMarker GetUsgaMarker(SaxGolfUsgaMarker.Params prmUsgaMarker); + public SaxGolfUsgaMarker GetUsgaMarkerById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return null; + SaxGolfUsgaMarker.Params prmUsgaMarker = new SaxGolfUsgaMarker.Params(); + prmUsgaMarker.IdsIncluded.Add(id); + prmUsgaMarker.StatusCat = SaxGolfUsgaMarker.StatusCat.Any; + return GetUsgaMarker(prmUsgaMarker); + } + + //------------------------------------------------------------------- + // Validate item data. + public bool IsValidUsgaMarker(SaxGolfUsgaMarker usgaMarker) + { + ClearErrorState(); + if (usgaMarker == null) return SetErrorState(ErrorMessage.ItemNotSpecified); + return IsValidUsgaMarkerData(usgaMarker.GetData(), new SaxGolfUsgaMarker.ErrField()); + } + public virtual bool IsValidUsgaMarkerData(SaxGolfUsgaMarker.Data data, SaxGolfUsgaMarker.ErrField errField) + { + ClearErrorState(); + + //--------------------------------------------------------------- + // Course. + if (errField.CourseId != SacsHierarchyItem.ValidValue.Ignore && !SysId.IsValid(data.CourseId)) + { + errField.CourseId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Course must be specified"); + } + // Marker Id. + if (errField.MarkerId != SacsHierarchyItem.ValidValue.Ignore && !SysId.IsValid(data.MarkerId)) + { + errField.MarkerId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Marker Id must be specified"); + } + // Caption. + if (errField.Caption != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Caption, "caption", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Caption), true)) + { + errField.Caption = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Holes. + if (errField.Holes != SacsHierarchyItem.ValidValue.Ignore && data.Holes < 1) + { + errField.HolesCaption = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Holes must be specified"); + } + // Holes caption. + if (errField.HolesCaption != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.HolesCaption, "holes caption", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_HolesCaption))) + { + errField.HolesCaption = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Tee. + if (errField.Tee != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Tee, "tee", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Tee), true)) + { + errField.Tee = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Gender. + if (errField.Gender != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Gender, "gender", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Gender))) + { + errField.Gender = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Slope Rating. + if (errField.SlopeRating != SacsHierarchyItem.ValidValue.Ignore && data.SlopeRating < 1) + { + errField.SlopeRating = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Slope rating must be specified"); + } + // Par. + if (errField.Par != SacsHierarchyItem.ValidValue.Ignore && data.Par < 1) + { + errField.Par = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Par must be specified"); + } + // Course Rating. + if (errField.CourseRating != SacsHierarchyItem.ValidValue.Ignore && data.CourseRating < 1) + { + errField.CourseRating = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Course rating must be specified"); + } + + //--------------------------------------------------------------- + // Common properties. + if (errField.Notes != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Notes, "notes", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Notes))) + { + errField.Notes = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (errField.Status != SacsHierarchyItem.ValidValue.Ignore) + { + if (!IsValidValue(data.StatusCode, "status", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Status), true, true)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (!SaxGolfUsgaMarker.ValidStatuses.Contains(data.Status)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState(ErrorMessage.InvalidStatus); + } + } + + //--------------------------------------------------------------- + // Associated data - ignore for deleted items. + if (!data.IsStatusDeleted) + { + + // Course. + if (errField.CourseId != SacsHierarchyItem.ValidValue.Ignore && SysId.IsValid(data.CourseId)) + { + SaxGolfUsgaCourse.Params prmCourse = new SaxGolfUsgaCourse.Params(); + prmCourse.IdsIncluded.Add(data.CourseId); + prmCourse.StatusCat = SaxGolfUsgaCourse.StatusCat.NotDeleted; + if (ReferenceGolfMgr.GetUsgaCourseCount(prmCourse) < 1) + { + errField.CourseId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Invalid marker specified"); + } + } + } + + //--------------------------------------------------------------- + return true; + } + + //------------------------------------------------------------------- + // Item database interface. + public abstract bool InsertUsgaMarker(SaxGolfUsgaMarker usgaMarker, DbUpdateInfo dbUpdateInfo); + public abstract bool UpdateUsgaMarker(SaxGolfUsgaMarker usgaMarker, DbUpdateInfo dbUpdateInfo); + public virtual bool UsgaMarkerCanBeDeleted(SaxGolfUsgaMarker usgaMarker) + { + ClearErrorState(); + return true; + } + public abstract bool DeleteUsgaMarker(SaxGolfUsgaMarker usgaMarker, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Bulk updates. + public class UsgaMarkerData + { + public SysId CourseId { get; set; } + public SysId MarkerId { get; set; } + public string Caption { get; set; } + public short Holes { get; set; } + public string HolesCaption { get; set; } + public string Tee { get; set; } + public string Gender { get; set; } + public short SlopeRating { get; set; } + public short Par { get; set; } + public decimal CourseRating { get; set; } + public decimal BogeyRating { get; set; } + public short Length { get; set; } + } + /// + /// Bulk update USGA Markers. + /// - Course Id must be supplied to identify parent. + /// - Marker Id must be supplied to act as identifier. + /// - Other properties are validated as per merker rules - check error state. + /// - Other properties are left as is if null. + /// + public abstract bool BulkUpdateUsgaMarkers(List markers, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Item list. + public abstract ColumnDfn GetUsgaMarkerColumnDfn(SaxGolfUsgaMarker.Column columnId, String caption = "", int width = 0); + public abstract List GetUsgaMarkerQueryFilter(SaxGolfUsgaMarker.Params prmUsgaMarker); + public abstract long GetUsgaMarkerCount(SaxGolfUsgaMarker.Params prmUsgaMarker); + public abstract List GetUsgaMarkerList(SaxGolfUsgaMarker.Params prmUsgaMarker); + public abstract DbResultSet ExecuteUsgaMarkerQuery(List columns, SaxGolfUsgaMarker.Params prmUsgaMarker); + + //------------------------------------------------------------------- + /// + /// Extract and format result set data value where specific handling is required. + /// Where response is an invalid data value, format value using column.FormatValue(values). + /// + public virtual DataValue GetUsgaMarkerDataValue(ColumnDfn column, NamedValue.Map values) + { + DataValue value = new DataValue(); + switch ((SaxGolfUsgaMarker.Column)column.Id) + { + //----------------------------------------------------------- + // Notes. + case SaxGolfUsgaMarker.Column.Notes: + { + value = new DataValue(SacsHierarchyItem.FormatForDisplay(values.GetValue(column.DataName).ToString(), 200)); + } + break; + + //----------------------------------------------------------- + // Status. + case SaxGolfUsgaMarker.Column.Status_Desc: + case SaxGolfUsgaMarker.Column.Status_Ind: + { + String statusCode = values.GetValue(column.DataName).ToString(); + SaStatus status = SacsSystem.GetStatusForCode(statusCode); + if (column.Id == (int)SaxGolfUsgaMarker.Column.Status_Desc) + value = new DataValue(SacsSystem.GetStatusDesc(status)); + else if (column.Id == (int)SaxGolfUsgaMarker.Column.Status_Ind) + value = new DataValue(SaxGolfUsgaMarker.GetStatusTriState(status)); + } + break; + + //----------------------------------------------------------- + default: + value = values.GetValue(column.DataName); + break; + + } + return value; + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaProvince.cs b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaProvince.cs new file mode 100644 index 0000000..1ae79a0 --- /dev/null +++ b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr-UsgaProvince.cs @@ -0,0 +1,214 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; +using System.Collections.Generic; + +namespace Saxonite.Net.Standard.Base.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr + { + //******************************************************************* + // Reference Mgr - Golf - USGA Province + //******************************************************************* + // Utilities. + + //------------------------------------------------------------------- + // Create item. + public abstract SaxGolfUsgaProvince CreateUsgaProvince(SysId countryId); + + //------------------------------------------------------------------- + // Item exists. + public bool UsgaProvinceExistsById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return false; + SaxGolfUsgaProvince.Params prmUsgaProvince = new SaxGolfUsgaProvince.Params(); + prmUsgaProvince.IdsIncluded.Add(id); + prmUsgaProvince.StatusCat = SaxGolfUsgaProvince.StatusCat.Any; + return GetUsgaProvinceCount(prmUsgaProvince) == 1; + } + + //------------------------------------------------------------------- + // Retrieve individual items. + public abstract SaxGolfUsgaProvince GetUsgaProvince(SaxGolfUsgaProvince.Params prmUsgaProvince); + public SaxGolfUsgaProvince GetUsgaProvinceById(SysId id) + { + ClearErrorState(); + if (!SysId.IsValid(id)) return null; + SaxGolfUsgaProvince.Params prmUsgaProvince = new SaxGolfUsgaProvince.Params(); + prmUsgaProvince.IdsIncluded.Add(id); + prmUsgaProvince.StatusCat = SaxGolfUsgaProvince.StatusCat.Any; + return GetUsgaProvince(prmUsgaProvince); + } + + //------------------------------------------------------------------- + // Validate item data. + public bool IsValidUsgaProvince(SaxGolfUsgaProvince usgaProvince) + { + ClearErrorState(); + if (usgaProvince == null) return SetErrorState(ErrorMessage.ItemNotSpecified); + return IsValidUsgaProvinceData(usgaProvince.GetData(), new SaxGolfUsgaProvince.ErrField()); + } + public virtual bool IsValidUsgaProvinceData(SaxGolfUsgaProvince.Data data, SaxGolfUsgaProvince.ErrField errField) + { + ClearErrorState(); + + //--------------------------------------------------------------- + // Country. + if (errField.CountryId != SacsHierarchyItem.ValidValue.Ignore && !SysId.IsValid(data.CountryId)) + { + errField.CountryId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Country must be specified"); + } + // Province code. + if (errField.ProvinceCode != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.ProvinceCode, "code", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceCode), true)) + { + errField.ProvinceCode = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // ENT Province code. + if (errField.EntProvinceCode != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.EntProvinceCode, "ENT code", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_EntProvinceCode), true)) + { + errField.EntProvinceCode = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + // Province name. + if (errField.ProvinceName != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.ProvinceName, "name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName), true)) + { + errField.ProvinceName = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + + //--------------------------------------------------------------- + // Common properties. + if (errField.Notes != SacsHierarchyItem.ValidValue.Ignore && !IsValidValue(data.Notes, "notes", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Notes))) + { + errField.Notes = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (errField.Status != SacsHierarchyItem.ValidValue.Ignore) + { + if (!IsValidValue(data.StatusCode, "status", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Status), true, true)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return false; + } + if (!SaxGolfUsgaProvince.ValidStatuses.Contains(data.Status)) + { + errField.Status = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState(ErrorMessage.InvalidStatus); + } + } + + //--------------------------------------------------------------- + // Associated data - ignore for deleted items. + if (!data.IsStatusDeleted) + { + + // Country. + if (errField.CountryId != SacsHierarchyItem.ValidValue.Ignore && SysId.IsValid(data.CountryId)) + { + SaxGolfUsgaCountry.Params prmCountry = new SaxGolfUsgaCountry.Params(); + prmCountry.IdsIncluded.Add(data.CountryId); + prmCountry.StatusCat = SaxGolfUsgaCountry.StatusCat.NotDeleted; + if (ReferenceGolfMgr.GetUsgaCountryCount(prmCountry) < 1) + { + errField.CountryId = SacsHierarchyItem.ValidValue.Invalid; + return SetErrorState("Invalid country specified"); + } + } + } + + //--------------------------------------------------------------- + return true; + } + + //------------------------------------------------------------------- + // Item database interface. + public abstract bool InsertUsgaProvince(SaxGolfUsgaProvince usgaProvince, DbUpdateInfo dbUpdateInfo); + public abstract bool UpdateUsgaProvince(SaxGolfUsgaProvince usgaProvince, DbUpdateInfo dbUpdateInfo); + public virtual bool UsgaProvinceCanBeDeleted(SaxGolfUsgaProvince usgaProvince) + { + ClearErrorState(); + return true; + } + public abstract bool DeleteUsgaProvince(SaxGolfUsgaProvince usgaProvince, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Bulk updates. + public class UsgaProvinceData + { + public String CountryCode { get; set; } + public String ProvinceCode { get; set; } + public String EntProvinceCode { get; set; } = null; + public String ProvinceName { get; set; } = null; + } + /// + /// Bulk update USGA Provinces. + /// - Country code must be supplied to identify parent. + /// - Province code must be supplied to act as identifier. + /// - Other properties are validated as per province rules - check error state. + /// - Other properties are left as is if null. + /// + public abstract bool BulkUpdateUsgaProvinces(List provinces, DbUpdateInfo dbUpdateInfo); + + //------------------------------------------------------------------- + // Item list. + public abstract ColumnDfn GetUsgaProvinceColumnDfn(SaxGolfUsgaProvince.Column columnId, String caption = "", int width = 0); + public abstract List GetUsgaProvinceQueryFilter(SaxGolfUsgaProvince.Params prmUsgaProvince); + public abstract long GetUsgaProvinceCount(SaxGolfUsgaProvince.Params prmUsgaProvince); + public abstract List GetUsgaProvinceList(SaxGolfUsgaProvince.Params prmUsgaProvince); + public abstract DbResultSet ExecuteUsgaProvinceQuery(List columns, SaxGolfUsgaProvince.Params prmUsgaProvince); + + //------------------------------------------------------------------- + /// + /// Extract and format result set data value where specific handling is required. + /// Where response is an invalid data value, format value using column.FormatValue(values). + /// + public virtual DataValue GetUsgaProvinceDataValue(ColumnDfn column, NamedValue.Map values) + { + DataValue value = new DataValue(); + switch ((SaxGolfUsgaProvince.Column)column.Id) + { + //----------------------------------------------------------- + // Notes. + case SaxGolfUsgaProvince.Column.Notes: + { + value = new DataValue(SacsHierarchyItem.FormatForDisplay(values.GetValue(column.DataName).ToString(), 200)); + } + break; + + //----------------------------------------------------------- + // Status. + case SaxGolfUsgaProvince.Column.Status_Desc: + case SaxGolfUsgaProvince.Column.Status_Ind: + { + String statusCode = values.GetValue(column.DataName).ToString(); + SaStatus status = SacsSystem.GetStatusForCode(statusCode); + if (column.Id == (int)SaxGolfUsgaProvince.Column.Status_Desc) + value = new DataValue(SacsSystem.GetStatusDesc(status)); + else if (column.Id == (int)SaxGolfUsgaProvince.Column.Status_Ind) + value = new DataValue(SaxGolfUsgaProvince.GetStatusTriState(status)); + } + break; + + //----------------------------------------------------------- + default: + value = values.GetValue(column.DataName); + break; + + } + return value; + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr.cs b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr.cs new file mode 100644 index 0000000..1b6ad3f --- /dev/null +++ b/SaxoniteStandardBase/Base/Mgr/Reference/SaxReferenceGolfMgr.cs @@ -0,0 +1,22 @@ +using Saxonite.Net.Standard.Base.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Saxonite.Net.Standard.Base.Mgr.Reference +{ + //======================================================================= + public abstract partial class SaxReferenceGolfMgr : SaxItemMgr_Reference + { + //------------------------------------------------------------------- + protected SaxReferenceGolfMgr(SaxSessionContext sessionContext, SaxInternals internals) : + base(sessionContext, internals) + { + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardBase/Base/Procs/SaxProcess_Base.cs b/SaxoniteStandardBase/Base/Procs/SaxProcess_Base.cs index 987f6b8..303c24b 100644 --- a/SaxoniteStandardBase/Base/Procs/SaxProcess_Base.cs +++ b/SaxoniteStandardBase/Base/Procs/SaxProcess_Base.cs @@ -6,6 +6,8 @@ using System.Collections.Generic; using System.Text; using Saxonite.Net.Standard.Base.App; using Sarand.Net.Standard.Proc.Excel; +using Saxonite.Net.Standard.Base.Mgr.Reference; +using Sarand.Net.Standard.Base.Dbas; namespace Saxonite.Net.Standard.Base.Procs { @@ -16,9 +18,9 @@ namespace Saxonite.Net.Standard.Base.Procs // Definitions. public new class Config : SaProcess.Config { - protected Config(SaxSessionContext sessionContext) : base() + protected Config(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo) : base(dbUpdateInfo) { - SessionContext = sessionContext; + this.SessionContext = sessionContext; } public SaxSessionContext SessionContext { get; } } @@ -52,6 +54,7 @@ namespace Saxonite.Net.Standard.Base.Procs public SaxAccountMgr AccountMgr { get { return Internals.AccountMgr; } } public SaxActivityMgr ActivityMgr { get { return Internals.ActivityMgr; } } public SaxItemDataMgr ItemDataMgr { get { return Internals.ItemDataMgr; } } + public SaxReferenceGolfMgr ReferenceGolfMgr { get { return Internals.ReferenceGolfMgr; } } public SaxSupportMgr SupportMgr { get { return Internals.SupportMgr; } } //------------------------------------------------------------------- diff --git a/SaxoniteStandardBase/Resources/Config/appsettings.Machine.Sarand110.json b/SaxoniteStandardBase/Resources/Config/appsettings.Machine.Sarand110.json index 397a235..519710c 100644 --- a/SaxoniteStandardBase/Resources/Config/appsettings.Machine.Sarand110.json +++ b/SaxoniteStandardBase/Resources/Config/appsettings.Machine.Sarand110.json @@ -18,6 +18,11 @@ "Location": "MsSql:Sarand110\\SQL2016.Saxonite_Support_Dev", "User": "saxonite", "Password": "sax-dev-2021" + }, + "Reference": { + "Location": "MsSql:Sarand110\\SQL2016.Saxonite_Reference_Dev", + "User": "saxonite", + "Password": "sax-dev-2021" } }, "Email": { diff --git a/SaxoniteStandardBase/Resources/Config/appsettings.Machine.Sarand602.json b/SaxoniteStandardBase/Resources/Config/appsettings.Machine.Sarand602.json index f49bbdd..9b17d6c 100644 --- a/SaxoniteStandardBase/Resources/Config/appsettings.Machine.Sarand602.json +++ b/SaxoniteStandardBase/Resources/Config/appsettings.Machine.Sarand602.json @@ -14,6 +14,11 @@ "User": "sax-demo-user", "Password": "sax-demo-202105" }, + "Reference": { + "Location": "MsSql:.\\SQL2016Exp.Saxonite_Reference_Demo", + "User": "sax-demo-user", + "Password": "sax-demo-202105" + }, "Support": { "Location": "MsSql:.\\SQL2016Exp.Saxonite_Support_Demo", "User": "sax-demo-user", diff --git a/SaxoniteStandardDbas/Dbas/App/SaxDbDfnGenerator.cs b/SaxoniteStandardDbas/Dbas/App/SaxDbDfnGenerator.cs index e33ff5a..07a9255 100644 --- a/SaxoniteStandardDbas/Dbas/App/SaxDbDfnGenerator.cs +++ b/SaxoniteStandardDbas/Dbas/App/SaxDbDfnGenerator.cs @@ -60,7 +60,7 @@ namespace Saxonite.Net.Standard.Dbas.App OutputDirectory = directory }; // Schema - Tables. - config.Schema.Tables_Excluded.AddRange(new String[] { }); + config.Schema.Tables_Excluded.UnionWith(new String[] { }); // Schema - Columns. config.Schema.InsertOnlyColumns.Add(".*", "CreateOn,CreateBy,CreateHost"); config.Schema.InsertOnlyColumns.Add("SomeOldTable", "Code"); diff --git a/SaxoniteStandardDbas/Dbas/App/SaxSystem_Dbas.cs b/SaxoniteStandardDbas/Dbas/App/SaxSystem_Dbas.cs index 2bfc751..82802ca 100644 --- a/SaxoniteStandardDbas/Dbas/App/SaxSystem_Dbas.cs +++ b/SaxoniteStandardDbas/Dbas/App/SaxSystem_Dbas.cs @@ -1,7 +1,9 @@ using Saxonite.Net.Standard.Base.App; using Saxonite.Net.Standard.Base.Mgr; +using Saxonite.Net.Standard.Base.Mgr.Reference; using Saxonite.Net.Standard.Base.Mgr.Support; using Saxonite.Net.Standard.Dbas.Mgr; +using Saxonite.Net.Standard.Dbas.Mgr.Reference; using Saxonite.Net.Standard.Dbas.Mgr.Support; using System; using System.Collections.Generic; @@ -37,6 +39,10 @@ namespace Saxonite.Net.Standard.Dbas.App { return new SaxItemDataMgr_Dbas(sessionContext, internals); } + public override SaxReferenceGolfMgr CreateReferenceGolfMgr(SaxSessionContext sessionContext, SaxInternals internals) + { + return new SaxReferenceGolfMgr_Dbas(sessionContext, internals); + } public override SaxSupportMgr CreateSupportMgr(SaxSessionContext sessionContext, SaxInternals internals) { return new SaxSupportMgr_Dbas(sessionContext, internals); diff --git a/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaCountry_Dbas.cs b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaCountry_Dbas.cs new file mode 100644 index 0000000..6a6054e --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaCountry_Dbas.cs @@ -0,0 +1,30 @@ +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; + +namespace Saxonite.Net.Standard.Dbas.Bus.Reference +{ + //======================================================================= + public class SaxGolfUsgaCountry_Dbas : SaxGolfUsgaCountry + { + //------------------------------------------------------------------- + // Data members. + private ISacsDatabase database; + + //------------------------------------------------------------------- + // Construction. + public SaxGolfUsgaCountry_Dbas(ISacsDatabase database, SysId id, UInt16 flags) : + base(id) + { + this.database = database; + Flags = flags; + } + + //------------------------------------------------------------------- + // Associated data. + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaCourse_Dbas.cs b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaCourse_Dbas.cs new file mode 100644 index 0000000..ec5dd13 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaCourse_Dbas.cs @@ -0,0 +1,30 @@ +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; + +namespace Saxonite.Net.Standard.Dbas.Bus.Reference +{ + //======================================================================= + public class SaxGolfUsgaCourse_Dbas : SaxGolfUsgaCourse + { + //------------------------------------------------------------------- + // Data members. + private ISacsDatabase database; + + //------------------------------------------------------------------- + // Construction. + public SaxGolfUsgaCourse_Dbas(ISacsDatabase database, SysId id, SysId facilityId, UInt16 flags) : + base(id, facilityId) + { + this.database = database; + Flags = flags; + } + + //------------------------------------------------------------------- + // Associated data. + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaFacility_Dbas.cs b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaFacility_Dbas.cs new file mode 100644 index 0000000..4a4a335 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaFacility_Dbas.cs @@ -0,0 +1,30 @@ +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; + +namespace Saxonite.Net.Standard.Dbas.Bus.Reference +{ + //======================================================================= + public class SaxGolfUsgaFacility_Dbas : SaxGolfUsgaFacility + { + //------------------------------------------------------------------- + // Data members. + private ISacsDatabase database; + + //------------------------------------------------------------------- + // Construction. + public SaxGolfUsgaFacility_Dbas(ISacsDatabase database, SysId id, SysId provinceId, UInt16 flags) : + base(id, provinceId) + { + this.database = database; + Flags = flags; + } + + //------------------------------------------------------------------- + // Associated data. + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaMarker_Dbas.cs b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaMarker_Dbas.cs new file mode 100644 index 0000000..bd32323 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaMarker_Dbas.cs @@ -0,0 +1,30 @@ +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; + +namespace Saxonite.Net.Standard.Dbas.Bus.Reference +{ + //======================================================================= + public class SaxGolfUsgaMarker_Dbas : SaxGolfUsgaMarker + { + //------------------------------------------------------------------- + // Data members. + private ISacsDatabase database; + + //------------------------------------------------------------------- + // Construction. + public SaxGolfUsgaMarker_Dbas(ISacsDatabase database, SysId id, SysId courseId, UInt16 flags) : + base(id, courseId) + { + this.database = database; + Flags = flags; + } + + //------------------------------------------------------------------- + // Associated data. + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaProvince_Dbas.cs b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaProvince_Dbas.cs new file mode 100644 index 0000000..12aab79 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Bus/Reference/SaxGolfUsgaProvince_Dbas.cs @@ -0,0 +1,30 @@ +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Dbas; +using Saxonite.Net.Standard.Base.Bus.Reference; +using System; + +namespace Saxonite.Net.Standard.Dbas.Bus.Reference +{ + //======================================================================= + public class SaxGolfUsgaProvince_Dbas : SaxGolfUsgaProvince + { + //------------------------------------------------------------------- + // Data members. + private ISacsDatabase database; + + //------------------------------------------------------------------- + // Construction. + public SaxGolfUsgaProvince_Dbas(ISacsDatabase database, SysId id, SysId countryId, UInt16 flags) : + base(id, countryId) + { + this.database = database; + Flags = flags; + } + + //------------------------------------------------------------------- + // Associated data. + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/ActivityFeedback_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/ActivityFeedback_Db.cs index 398f08b..5ce4c17 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/ActivityFeedback_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/ActivityFeedback_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/ActivityIndex_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/ActivityIndex_Db.cs index d25ccd8..0493c41 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/ActivityIndex_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/ActivityIndex_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/Article_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/Article_Db.cs index f763749..5e7ab2c 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/Article_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/Article_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/ItemAddress_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/ItemAddress_Db.cs index 6ecac11..0931ae8 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/ItemAddress_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/ItemAddress_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/ItemAssociation_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/ItemAssociation_Db.cs index e6964e6..3db21d6 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/ItemAssociation_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/ItemAssociation_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/ItemImage_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/ItemImage_Db.cs index 011b2e3..70e604d 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/ItemImage_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/ItemImage_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/ItemSport_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/ItemSport_Db.cs index 89cbc29..760f7f6 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/ItemSport_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/ItemSport_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/OrganisationEvent_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/OrganisationEvent_Db.cs index 7d9288f..419a1ba 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/OrganisationEvent_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/OrganisationEvent_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/OrganisationOpportunity_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/OrganisationOpportunity_Db.cs index 91f9dc9..a9e81bc 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/OrganisationOpportunity_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/OrganisationOpportunity_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/Organisation_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/Organisation_Db.cs index 6422f0c..dbeaa2d 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/Organisation_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/Organisation_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/Region_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/Region_Db.cs index 14ad62f..5b4909e 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/Region_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/Region_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/Sport_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/Sport_Db.cs index 942ba22..7b996c8 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/Sport_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/Sport_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserAccount_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserAccount_Db.cs index 0bc1a37..bf011ab 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserAccount_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserAccount_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserActivity_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserActivity_Db.cs index c75b2d9..ae4d495 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserActivity_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserActivity_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserConfig_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserConfig_Db.cs index 2d953d3..d39f08c 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserConfig_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserConfig_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserEligibility_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserEligibility_Db.cs index a441f9b..824b160 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserEligibility_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserEligibility_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserOnline_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserOnline_Db.cs index 94adf2f..8ded0fa 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserOnline_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserOnline_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserOrganisation_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserOrganisation_Db.cs index 200f4a4..8feb0a8 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserOrganisation_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserOrganisation_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserRole_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserRole_Db.cs index efd6ccd..0b33fc9 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserRole_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserRole_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserSession_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserSession_Db.cs index 1ba37e2..2ea5cdd 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserSession_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserSession_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserSportExperience_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserSportExperience_Db.cs index 4baeca4..906ad73 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserSportExperience_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserSportExperience_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Core/UserSport_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Core/UserSport_Db.cs index f51b166..ac823dd 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Core/UserSport_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Core/UserSport_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Core { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaCountry_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaCountry_Db.cs new file mode 100644 index 0000000..75fd680 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaCountry_Db.cs @@ -0,0 +1,218 @@ +using Microsoft.Data.SqlClient; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Saxonite.Net.Standard.Dbas.Data; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +//--------------------------------------------------------------------------- +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 +//--------------------------------------------------------------------------- +namespace Saxonite.Net.Standard.Dbas.Internal.Reference +{ + internal class Golf_UsgaCountry_Db : SaxDbDataItem + { + //------------------------------------------------------------------- + // Column definitions. + public class ColumnsData + { + public ColumnDataInt64 _Id { get; } = new ColumnDataInt64("Id", true); + public ColumnDataString _CountryCode { get; } = new ColumnDataString("CountryCode"); + public ColumnDataString _CountryName { get; } = new ColumnDataString("CountryName"); + public ColumnDataString _EntCountryCode { get; } = new ColumnDataString("EntCountryCode"); + public ColumnDataString _Notes { get; } = new ColumnDataString("Notes"); + public ColumnDataInt16 _Flags { get; } = new ColumnDataInt16("Flags"); + public ColumnDataString _Status { get; } = new ColumnDataString("Status"); + public ColumnDataDateTime _CreateOn { get; } = new ColumnDataDateTime("CreateOn"); + public ColumnDataInt32 _CreateBy { get; } = new ColumnDataInt32("CreateBy"); + public ColumnDataString _CreateHost { get; } = new ColumnDataString("CreateHost"); + public ColumnDataDateTime _UpdateOn { get; } = new ColumnDataDateTime("UpdateOn"); + public ColumnDataInt32 _UpdateBy { get; } = new ColumnDataInt32("UpdateBy"); + public ColumnDataString _UpdateHost { get; } = new ColumnDataString("UpdateHost"); + } + + //------------------------------------------------------------------- + // Data members. + protected static List fields { get; } = new List() + { + "Id", + "CountryCode", + "CountryName", + "EntCountryCode", + "Notes", + "Flags", + "Status", + "CreateOn", + "CreateBy", + "CreateHost", + "UpdateOn", + "UpdateBy", + "UpdateHost", + }; + protected static List fieldsId { get; } = new List() + { + "Id", + }; + protected static List fieldsPrimary { get; } = new List() + { + "Id", + }; + protected static List fieldsIgnoreOnUpdate { get; } = new List() + { + "CreateOn", + "CreateBy", + "CreateHost", + }; + + //------------------------------------------------------------------- + // Construction. + internal Golf_UsgaCountry_Db (IDatabaseInfo dbInfo) : base(dbInfo) + { + } + + //------------------------------------------------------------------- + // Properties. + public override String SchemaName { get; } = "golf"; + public override String TableName { get; } = "UsgaCountry"; + public String TableNameFmt { get { return (!String.IsNullOrEmpty(SchemaName) ? "[" + SchemaName + "]." : "") + "[" + TableName + "]"; } } + public static List Fields { get { return new List(fields); } } + public static List FieldsId { get { return new List(fieldsId); } } + public static List FieldsNonId { get { return fields.FindAll(item => !fieldsId.ContainsCI(item)); } } + // Columns. + public ColumnsData Cols { get; } = new ColumnsData(); + public Int64 _Id { get { return Cols._Id.Value; } set { Cols._Id.Value = value; } } + public String _CountryCode { get { return Cols._CountryCode.Value; } set { Cols._CountryCode.Value = value; } } + public String _CountryName { get { return Cols._CountryName.Value; } set { Cols._CountryName.Value = value; } } + public String _EntCountryCode { get { return Cols._EntCountryCode.Value; } set { Cols._EntCountryCode.Value = value; } } + public String _Notes { get { return Cols._Notes.Value; } set { Cols._Notes.Value = value; } } + public Int16 _Flags { get { return Cols._Flags.Value; } set { Cols._Flags.Value = value; } } + public String _Status { get { return Cols._Status.Value; } set { Cols._Status.Value = value; } } + public DateTime _CreateOn { get { return Cols._CreateOn.Value; } set { Cols._CreateOn.Value = value; } } + public Int32 _CreateBy { get { return Cols._CreateBy.Value; } set { Cols._CreateBy.Value = value; } } + public String _CreateHost { get { return Cols._CreateHost.Value; } set { Cols._CreateHost.Value = value; } } + public DateTime _UpdateOn { get { return Cols._UpdateOn.Value; } set { Cols._UpdateOn.Value = value; } } + public Int32 _UpdateBy { get { return Cols._UpdateBy.Value; } set { Cols._UpdateBy.Value = value; } } + public String _UpdateHost { get { return Cols._UpdateHost.Value; } set { Cols._UpdateHost.Value = value; } } + // Existing columns - confirmed on database if table exists. + public List ExistingColumnNames { get { return GetExistingColumnNames(Fields); } } + public List ExistingColumnNamesNonId { get { return GetExistingColumnNames(FieldsNonId); } } + + //------------------------------------------------------------------- + // Population. + public override void PopulateFrom (DbCommand dbCommand, String tableAlias, String filter) + { + dbCommand.CommandText = + "SELECT " + ExistingColumnNames.Concat(", ", (!String.IsNullOrEmpty(tableAlias) ? tableAlias + "." : "") + "[", "]") + " " + + "FROM " + TableNameFmt + (!String.IsNullOrEmpty(tableAlias) ? " " + tableAlias : "") + " " + + (!String.IsNullOrEmpty(filter) ? "WHERE " + filter : ""); + Log(GetType().Name + ".PopulateFrom", dbCommand.CommandText); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + dbDataReader.Read(); + PopulateFrom(dbDataReader); + } + } + public override void PopulateFrom (DbDataReader dbDataReader) + { + _Id = GetFieldInt64(dbDataReader, "Id", _Id); + _CountryCode = GetFieldString(dbDataReader, "CountryCode", _CountryCode); + _CountryName = GetFieldString(dbDataReader, "CountryName", _CountryName); + _EntCountryCode = GetFieldString(dbDataReader, "EntCountryCode", _EntCountryCode); + _Notes = GetFieldString(dbDataReader, "Notes", _Notes); + _Flags = GetFieldInt16(dbDataReader, "Flags", _Flags); + _Status = GetFieldString(dbDataReader, "Status", _Status); + _CreateOn = GetFieldDateTime(dbDataReader, "CreateOn", _CreateOn); + _CreateBy = GetFieldInt32(dbDataReader, "CreateBy", _CreateBy); + _CreateHost = GetFieldString(dbDataReader, "CreateHost", _CreateHost); + _UpdateOn = GetFieldDateTime(dbDataReader, "UpdateOn", _UpdateOn); + _UpdateBy = GetFieldInt32(dbDataReader, "UpdateBy", _UpdateBy); + _UpdateHost = GetFieldString(dbDataReader, "UpdateHost", _UpdateHost); + } + + //------------------------------------------------------------------- + // Insert command. + public override bool ExecuteInsertCommand (DbCommand dbCommand) + { + List columnNames = ExistingColumnNamesNonId; + // Avoid insert if Identity field is already valid. + if (_Id != 0) throw new Exception("Invalid for Insert - item already has a valid Id"); + // Construct query. + String query = + "INSERT INTO " + TableNameFmt + " " + + "("+columnNames.Concat(",","[","]")+") "; + query += "Output Inserted.Id "; + if (dbCommand is SqlCommand) + query += "VALUES (" + columnNames.Concat(",", "@", "") + ") "; + else query += "VALUES (" + StringListUtil.CreateList("?", columnNames.Count).Concat(",") + ") "; + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteInsertCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("CountryCode")) AddCommandParameter(dbCommand, "@CountryCode", _CountryCode); + if (columnNames.ContainsCI("CountryName")) AddCommandParameter(dbCommand, "@CountryName", _CountryName); + if (columnNames.ContainsCI("EntCountryCode")) AddCommandParameter(dbCommand, "@EntCountryCode", _EntCountryCode); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("CreateOn")) AddCommandParameter(dbCommand, "@CreateOn", _CreateOn); + if (columnNames.ContainsCI("CreateBy")) AddCommandParameter(dbCommand, "@CreateBy", _CreateBy); + if (columnNames.ContainsCI("CreateHost")) AddCommandParameter(dbCommand, "@CreateHost", _CreateHost); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + // Execute insert command. + bool commandSuccess = false; + int executeNonQuery = dbCommand.ExecuteNonQuery(); + if (executeNonQuery == 1) + { + dbCommand.CommandText = "SELECT Max(Id) FROM " + TableNameFmt + ";"; + _Id = Convert.ToInt64(dbCommand.ExecuteScalar()); + commandSuccess = (_Id > 0); + } + return commandSuccess; + } + + //------------------------------------------------------------------- + // Update command. + public override bool ExecuteUpdateCommand (DbCommand dbCommand) + { + // Avoid update if Identity field isn't valid. + if (_Id == 0) throw new Exception("Invalid for Update - item has an invalid Id"); + // Columns to update. + List columnNames = ExistingColumnNamesNonId.Where(item => !fieldsPrimary.ContainsCI(item) && !fieldsIgnoreOnUpdate.ContainsCI(item)).ToList(); + // Construct query. + String query = "UPDATE " + TableNameFmt + " SET "; + if (dbCommand is SqlCommand) + { + query += StringPairList.CreateFrom(columnNames.Bracket("[","]"),columnNames).Concat("=@").Concat(", ") + " "; + query += "WHERE Id=@Id;"; + } + else + { + query += columnNames.Concat(", ", "", "=?") + " "; + query += "WHERE Id=?;"; + } + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteUpdateCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("CountryCode")) AddCommandParameter(dbCommand, "@CountryCode", _CountryCode); + if (columnNames.ContainsCI("CountryName")) AddCommandParameter(dbCommand, "@CountryName", _CountryName); + if (columnNames.ContainsCI("EntCountryCode")) AddCommandParameter(dbCommand, "@EntCountryCode", _EntCountryCode); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + AddCommandParameter(dbCommand, "@Id", _Id); + int executeNonQueryResult = dbCommand.ExecuteNonQuery(); + return (executeNonQueryResult == 1); + } + + //------------------------------------------------------------------- + } +} diff --git a/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaCourse_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaCourse_Db.cs new file mode 100644 index 0000000..dc330bc --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaCourse_Db.cs @@ -0,0 +1,266 @@ +using Microsoft.Data.SqlClient; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Saxonite.Net.Standard.Dbas.Data; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +//--------------------------------------------------------------------------- +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 +//--------------------------------------------------------------------------- +namespace Saxonite.Net.Standard.Dbas.Internal.Reference +{ + internal class Golf_UsgaCourse_Db : SaxDbDataItem + { + //------------------------------------------------------------------- + // Column definitions. + public class ColumnsData + { + public ColumnDataInt64 _Id { get; } = new ColumnDataInt64("Id", true); + public ColumnDataInt64 _FacilityId { get; } = new ColumnDataInt64("FacilityId"); + public ColumnDataInt64 _CourseId { get; } = new ColumnDataInt64("CourseId"); + public ColumnDataInt64 _LegacyCrpCourseId { get; } = new ColumnDataInt64("LegacyCrpCourseId"); + public ColumnDataString _Caption { get; } = new ColumnDataString("Caption"); + public ColumnDataString _CourseName { get; } = new ColumnDataString("CourseName"); + public ColumnDataString _FullName { get; } = new ColumnDataString("FullName"); + public ColumnDataString _Address1 { get; } = new ColumnDataString("Address1"); + public ColumnDataString _Address2 { get; } = new ColumnDataString("Address2"); + public ColumnDataString _City { get; } = new ColumnDataString("City"); + public ColumnDataString _Email { get; } = new ColumnDataString("Email"); + public ColumnDataString _Telephone { get; } = new ColumnDataString("Telephone"); + public ColumnDataString _Notes { get; } = new ColumnDataString("Notes"); + public ColumnDataInt16 _Flags { get; } = new ColumnDataInt16("Flags"); + public ColumnDataString _Status { get; } = new ColumnDataString("Status"); + public ColumnDataDateTime _CreateOn { get; } = new ColumnDataDateTime("CreateOn"); + public ColumnDataInt32 _CreateBy { get; } = new ColumnDataInt32("CreateBy"); + public ColumnDataString _CreateHost { get; } = new ColumnDataString("CreateHost"); + public ColumnDataDateTime _UpdateOn { get; } = new ColumnDataDateTime("UpdateOn"); + public ColumnDataInt32 _UpdateBy { get; } = new ColumnDataInt32("UpdateBy"); + public ColumnDataString _UpdateHost { get; } = new ColumnDataString("UpdateHost"); + } + + //------------------------------------------------------------------- + // Data members. + protected static List fields { get; } = new List() + { + "Id", + "FacilityId", + "CourseId", + "LegacyCrpCourseId", + "Caption", + "CourseName", + "FullName", + "Address1", + "Address2", + "City", + "Email", + "Telephone", + "Notes", + "Flags", + "Status", + "CreateOn", + "CreateBy", + "CreateHost", + "UpdateOn", + "UpdateBy", + "UpdateHost", + }; + protected static List fieldsId { get; } = new List() + { + "Id", + }; + protected static List fieldsPrimary { get; } = new List() + { + "Id", + }; + protected static List fieldsIgnoreOnUpdate { get; } = new List() + { + "CreateOn", + "CreateBy", + "CreateHost", + }; + + //------------------------------------------------------------------- + // Construction. + internal Golf_UsgaCourse_Db (IDatabaseInfo dbInfo) : base(dbInfo) + { + } + + //------------------------------------------------------------------- + // Properties. + public override String SchemaName { get; } = "golf"; + public override String TableName { get; } = "UsgaCourse"; + public String TableNameFmt { get { return (!String.IsNullOrEmpty(SchemaName) ? "[" + SchemaName + "]." : "") + "[" + TableName + "]"; } } + public static List Fields { get { return new List(fields); } } + public static List FieldsId { get { return new List(fieldsId); } } + public static List FieldsNonId { get { return fields.FindAll(item => !fieldsId.ContainsCI(item)); } } + // Columns. + public ColumnsData Cols { get; } = new ColumnsData(); + public Int64 _Id { get { return Cols._Id.Value; } set { Cols._Id.Value = value; } } + public Int64 _FacilityId { get { return Cols._FacilityId.Value; } set { Cols._FacilityId.Value = value; } } + public Int64 _CourseId { get { return Cols._CourseId.Value; } set { Cols._CourseId.Value = value; } } + public Int64 _LegacyCrpCourseId { get { return Cols._LegacyCrpCourseId.Value; } set { Cols._LegacyCrpCourseId.Value = value; } } + public String _Caption { get { return Cols._Caption.Value; } set { Cols._Caption.Value = value; } } + public String _CourseName { get { return Cols._CourseName.Value; } set { Cols._CourseName.Value = value; } } + public String _FullName { get { return Cols._FullName.Value; } set { Cols._FullName.Value = value; } } + public String _Address1 { get { return Cols._Address1.Value; } set { Cols._Address1.Value = value; } } + public String _Address2 { get { return Cols._Address2.Value; } set { Cols._Address2.Value = value; } } + public String _City { get { return Cols._City.Value; } set { Cols._City.Value = value; } } + public String _Email { get { return Cols._Email.Value; } set { Cols._Email.Value = value; } } + public String _Telephone { get { return Cols._Telephone.Value; } set { Cols._Telephone.Value = value; } } + public String _Notes { get { return Cols._Notes.Value; } set { Cols._Notes.Value = value; } } + public Int16 _Flags { get { return Cols._Flags.Value; } set { Cols._Flags.Value = value; } } + public String _Status { get { return Cols._Status.Value; } set { Cols._Status.Value = value; } } + public DateTime _CreateOn { get { return Cols._CreateOn.Value; } set { Cols._CreateOn.Value = value; } } + public Int32 _CreateBy { get { return Cols._CreateBy.Value; } set { Cols._CreateBy.Value = value; } } + public String _CreateHost { get { return Cols._CreateHost.Value; } set { Cols._CreateHost.Value = value; } } + public DateTime _UpdateOn { get { return Cols._UpdateOn.Value; } set { Cols._UpdateOn.Value = value; } } + public Int32 _UpdateBy { get { return Cols._UpdateBy.Value; } set { Cols._UpdateBy.Value = value; } } + public String _UpdateHost { get { return Cols._UpdateHost.Value; } set { Cols._UpdateHost.Value = value; } } + // Existing columns - confirmed on database if table exists. + public List ExistingColumnNames { get { return GetExistingColumnNames(Fields); } } + public List ExistingColumnNamesNonId { get { return GetExistingColumnNames(FieldsNonId); } } + + //------------------------------------------------------------------- + // Population. + public override void PopulateFrom (DbCommand dbCommand, String tableAlias, String filter) + { + dbCommand.CommandText = + "SELECT " + ExistingColumnNames.Concat(", ", (!String.IsNullOrEmpty(tableAlias) ? tableAlias + "." : "") + "[", "]") + " " + + "FROM " + TableNameFmt + (!String.IsNullOrEmpty(tableAlias) ? " " + tableAlias : "") + " " + + (!String.IsNullOrEmpty(filter) ? "WHERE " + filter : ""); + Log(GetType().Name + ".PopulateFrom", dbCommand.CommandText); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + dbDataReader.Read(); + PopulateFrom(dbDataReader); + } + } + public override void PopulateFrom (DbDataReader dbDataReader) + { + _Id = GetFieldInt64(dbDataReader, "Id", _Id); + _FacilityId = GetFieldInt64(dbDataReader, "FacilityId", _FacilityId); + _CourseId = GetFieldInt64(dbDataReader, "CourseId", _CourseId); + _LegacyCrpCourseId = GetFieldInt64(dbDataReader, "LegacyCrpCourseId", _LegacyCrpCourseId); + _Caption = GetFieldString(dbDataReader, "Caption", _Caption); + _CourseName = GetFieldString(dbDataReader, "CourseName", _CourseName); + _FullName = GetFieldString(dbDataReader, "FullName", _FullName); + _Address1 = GetFieldString(dbDataReader, "Address1", _Address1); + _Address2 = GetFieldString(dbDataReader, "Address2", _Address2); + _City = GetFieldString(dbDataReader, "City", _City); + _Email = GetFieldString(dbDataReader, "Email", _Email); + _Telephone = GetFieldString(dbDataReader, "Telephone", _Telephone); + _Notes = GetFieldString(dbDataReader, "Notes", _Notes); + _Flags = GetFieldInt16(dbDataReader, "Flags", _Flags); + _Status = GetFieldString(dbDataReader, "Status", _Status); + _CreateOn = GetFieldDateTime(dbDataReader, "CreateOn", _CreateOn); + _CreateBy = GetFieldInt32(dbDataReader, "CreateBy", _CreateBy); + _CreateHost = GetFieldString(dbDataReader, "CreateHost", _CreateHost); + _UpdateOn = GetFieldDateTime(dbDataReader, "UpdateOn", _UpdateOn); + _UpdateBy = GetFieldInt32(dbDataReader, "UpdateBy", _UpdateBy); + _UpdateHost = GetFieldString(dbDataReader, "UpdateHost", _UpdateHost); + } + + //------------------------------------------------------------------- + // Insert command. + public override bool ExecuteInsertCommand (DbCommand dbCommand) + { + List columnNames = ExistingColumnNamesNonId; + // Avoid insert if Identity field is already valid. + if (_Id != 0) throw new Exception("Invalid for Insert - item already has a valid Id"); + // Construct query. + String query = + "INSERT INTO " + TableNameFmt + " " + + "("+columnNames.Concat(",","[","]")+") "; + query += "Output Inserted.Id "; + if (dbCommand is SqlCommand) + query += "VALUES (" + columnNames.Concat(",", "@", "") + ") "; + else query += "VALUES (" + StringListUtil.CreateList("?", columnNames.Count).Concat(",") + ") "; + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteInsertCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("FacilityId")) AddCommandParameter(dbCommand, "@FacilityId", _FacilityId); + if (columnNames.ContainsCI("CourseId")) AddCommandParameter(dbCommand, "@CourseId", _CourseId); + if (columnNames.ContainsCI("LegacyCrpCourseId")) AddCommandParameter(dbCommand, "@LegacyCrpCourseId", _LegacyCrpCourseId); + if (columnNames.ContainsCI("Caption")) AddCommandParameter(dbCommand, "@Caption", _Caption); + if (columnNames.ContainsCI("CourseName")) AddCommandParameter(dbCommand, "@CourseName", _CourseName); + if (columnNames.ContainsCI("FullName")) AddCommandParameter(dbCommand, "@FullName", _FullName); + if (columnNames.ContainsCI("Address1")) AddCommandParameter(dbCommand, "@Address1", _Address1); + if (columnNames.ContainsCI("Address2")) AddCommandParameter(dbCommand, "@Address2", _Address2); + if (columnNames.ContainsCI("City")) AddCommandParameter(dbCommand, "@City", _City); + if (columnNames.ContainsCI("Email")) AddCommandParameter(dbCommand, "@Email", _Email); + if (columnNames.ContainsCI("Telephone")) AddCommandParameter(dbCommand, "@Telephone", _Telephone); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("CreateOn")) AddCommandParameter(dbCommand, "@CreateOn", _CreateOn); + if (columnNames.ContainsCI("CreateBy")) AddCommandParameter(dbCommand, "@CreateBy", _CreateBy); + if (columnNames.ContainsCI("CreateHost")) AddCommandParameter(dbCommand, "@CreateHost", _CreateHost); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + // Execute insert command. + bool commandSuccess = false; + int executeNonQuery = dbCommand.ExecuteNonQuery(); + if (executeNonQuery == 1) + { + dbCommand.CommandText = "SELECT Max(Id) FROM " + TableNameFmt + ";"; + _Id = Convert.ToInt64(dbCommand.ExecuteScalar()); + commandSuccess = (_Id > 0); + } + return commandSuccess; + } + + //------------------------------------------------------------------- + // Update command. + public override bool ExecuteUpdateCommand (DbCommand dbCommand) + { + // Avoid update if Identity field isn't valid. + if (_Id == 0) throw new Exception("Invalid for Update - item has an invalid Id"); + // Columns to update. + List columnNames = ExistingColumnNamesNonId.Where(item => !fieldsPrimary.ContainsCI(item) && !fieldsIgnoreOnUpdate.ContainsCI(item)).ToList(); + // Construct query. + String query = "UPDATE " + TableNameFmt + " SET "; + if (dbCommand is SqlCommand) + { + query += StringPairList.CreateFrom(columnNames.Bracket("[","]"),columnNames).Concat("=@").Concat(", ") + " "; + query += "WHERE Id=@Id;"; + } + else + { + query += columnNames.Concat(", ", "", "=?") + " "; + query += "WHERE Id=?;"; + } + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteUpdateCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("FacilityId")) AddCommandParameter(dbCommand, "@FacilityId", _FacilityId); + if (columnNames.ContainsCI("CourseId")) AddCommandParameter(dbCommand, "@CourseId", _CourseId); + if (columnNames.ContainsCI("LegacyCrpCourseId")) AddCommandParameter(dbCommand, "@LegacyCrpCourseId", _LegacyCrpCourseId); + if (columnNames.ContainsCI("Caption")) AddCommandParameter(dbCommand, "@Caption", _Caption); + if (columnNames.ContainsCI("CourseName")) AddCommandParameter(dbCommand, "@CourseName", _CourseName); + if (columnNames.ContainsCI("FullName")) AddCommandParameter(dbCommand, "@FullName", _FullName); + if (columnNames.ContainsCI("Address1")) AddCommandParameter(dbCommand, "@Address1", _Address1); + if (columnNames.ContainsCI("Address2")) AddCommandParameter(dbCommand, "@Address2", _Address2); + if (columnNames.ContainsCI("City")) AddCommandParameter(dbCommand, "@City", _City); + if (columnNames.ContainsCI("Email")) AddCommandParameter(dbCommand, "@Email", _Email); + if (columnNames.ContainsCI("Telephone")) AddCommandParameter(dbCommand, "@Telephone", _Telephone); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + AddCommandParameter(dbCommand, "@Id", _Id); + int executeNonQueryResult = dbCommand.ExecuteNonQuery(); + return (executeNonQueryResult == 1); + } + + //------------------------------------------------------------------- + } +} diff --git a/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaFacility_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaFacility_Db.cs new file mode 100644 index 0000000..735d35e --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaFacility_Db.cs @@ -0,0 +1,218 @@ +using Microsoft.Data.SqlClient; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Saxonite.Net.Standard.Dbas.Data; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +//--------------------------------------------------------------------------- +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 +//--------------------------------------------------------------------------- +namespace Saxonite.Net.Standard.Dbas.Internal.Reference +{ + internal class Golf_UsgaFacility_Db : SaxDbDataItem + { + //------------------------------------------------------------------- + // Column definitions. + public class ColumnsData + { + public ColumnDataInt64 _Id { get; } = new ColumnDataInt64("Id", true); + public ColumnDataInt64 _ProvinceId { get; } = new ColumnDataInt64("ProvinceId"); + public ColumnDataInt64 _FacilityId { get; } = new ColumnDataInt64("FacilityId"); + public ColumnDataString _FacilityName { get; } = new ColumnDataString("FacilityName"); + public ColumnDataString _Notes { get; } = new ColumnDataString("Notes"); + public ColumnDataInt16 _Flags { get; } = new ColumnDataInt16("Flags"); + public ColumnDataString _Status { get; } = new ColumnDataString("Status"); + public ColumnDataDateTime _CreateOn { get; } = new ColumnDataDateTime("CreateOn"); + public ColumnDataInt32 _CreateBy { get; } = new ColumnDataInt32("CreateBy"); + public ColumnDataString _CreateHost { get; } = new ColumnDataString("CreateHost"); + public ColumnDataDateTime _UpdateOn { get; } = new ColumnDataDateTime("UpdateOn"); + public ColumnDataInt32 _UpdateBy { get; } = new ColumnDataInt32("UpdateBy"); + public ColumnDataString _UpdateHost { get; } = new ColumnDataString("UpdateHost"); + } + + //------------------------------------------------------------------- + // Data members. + protected static List fields { get; } = new List() + { + "Id", + "ProvinceId", + "FacilityId", + "FacilityName", + "Notes", + "Flags", + "Status", + "CreateOn", + "CreateBy", + "CreateHost", + "UpdateOn", + "UpdateBy", + "UpdateHost", + }; + protected static List fieldsId { get; } = new List() + { + "Id", + }; + protected static List fieldsPrimary { get; } = new List() + { + "Id", + }; + protected static List fieldsIgnoreOnUpdate { get; } = new List() + { + "CreateOn", + "CreateBy", + "CreateHost", + }; + + //------------------------------------------------------------------- + // Construction. + internal Golf_UsgaFacility_Db (IDatabaseInfo dbInfo) : base(dbInfo) + { + } + + //------------------------------------------------------------------- + // Properties. + public override String SchemaName { get; } = "golf"; + public override String TableName { get; } = "UsgaFacility"; + public String TableNameFmt { get { return (!String.IsNullOrEmpty(SchemaName) ? "[" + SchemaName + "]." : "") + "[" + TableName + "]"; } } + public static List Fields { get { return new List(fields); } } + public static List FieldsId { get { return new List(fieldsId); } } + public static List FieldsNonId { get { return fields.FindAll(item => !fieldsId.ContainsCI(item)); } } + // Columns. + public ColumnsData Cols { get; } = new ColumnsData(); + public Int64 _Id { get { return Cols._Id.Value; } set { Cols._Id.Value = value; } } + public Int64 _ProvinceId { get { return Cols._ProvinceId.Value; } set { Cols._ProvinceId.Value = value; } } + public Int64 _FacilityId { get { return Cols._FacilityId.Value; } set { Cols._FacilityId.Value = value; } } + public String _FacilityName { get { return Cols._FacilityName.Value; } set { Cols._FacilityName.Value = value; } } + public String _Notes { get { return Cols._Notes.Value; } set { Cols._Notes.Value = value; } } + public Int16 _Flags { get { return Cols._Flags.Value; } set { Cols._Flags.Value = value; } } + public String _Status { get { return Cols._Status.Value; } set { Cols._Status.Value = value; } } + public DateTime _CreateOn { get { return Cols._CreateOn.Value; } set { Cols._CreateOn.Value = value; } } + public Int32 _CreateBy { get { return Cols._CreateBy.Value; } set { Cols._CreateBy.Value = value; } } + public String _CreateHost { get { return Cols._CreateHost.Value; } set { Cols._CreateHost.Value = value; } } + public DateTime _UpdateOn { get { return Cols._UpdateOn.Value; } set { Cols._UpdateOn.Value = value; } } + public Int32 _UpdateBy { get { return Cols._UpdateBy.Value; } set { Cols._UpdateBy.Value = value; } } + public String _UpdateHost { get { return Cols._UpdateHost.Value; } set { Cols._UpdateHost.Value = value; } } + // Existing columns - confirmed on database if table exists. + public List ExistingColumnNames { get { return GetExistingColumnNames(Fields); } } + public List ExistingColumnNamesNonId { get { return GetExistingColumnNames(FieldsNonId); } } + + //------------------------------------------------------------------- + // Population. + public override void PopulateFrom (DbCommand dbCommand, String tableAlias, String filter) + { + dbCommand.CommandText = + "SELECT " + ExistingColumnNames.Concat(", ", (!String.IsNullOrEmpty(tableAlias) ? tableAlias + "." : "") + "[", "]") + " " + + "FROM " + TableNameFmt + (!String.IsNullOrEmpty(tableAlias) ? " " + tableAlias : "") + " " + + (!String.IsNullOrEmpty(filter) ? "WHERE " + filter : ""); + Log(GetType().Name + ".PopulateFrom", dbCommand.CommandText); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + dbDataReader.Read(); + PopulateFrom(dbDataReader); + } + } + public override void PopulateFrom (DbDataReader dbDataReader) + { + _Id = GetFieldInt64(dbDataReader, "Id", _Id); + _ProvinceId = GetFieldInt64(dbDataReader, "ProvinceId", _ProvinceId); + _FacilityId = GetFieldInt64(dbDataReader, "FacilityId", _FacilityId); + _FacilityName = GetFieldString(dbDataReader, "FacilityName", _FacilityName); + _Notes = GetFieldString(dbDataReader, "Notes", _Notes); + _Flags = GetFieldInt16(dbDataReader, "Flags", _Flags); + _Status = GetFieldString(dbDataReader, "Status", _Status); + _CreateOn = GetFieldDateTime(dbDataReader, "CreateOn", _CreateOn); + _CreateBy = GetFieldInt32(dbDataReader, "CreateBy", _CreateBy); + _CreateHost = GetFieldString(dbDataReader, "CreateHost", _CreateHost); + _UpdateOn = GetFieldDateTime(dbDataReader, "UpdateOn", _UpdateOn); + _UpdateBy = GetFieldInt32(dbDataReader, "UpdateBy", _UpdateBy); + _UpdateHost = GetFieldString(dbDataReader, "UpdateHost", _UpdateHost); + } + + //------------------------------------------------------------------- + // Insert command. + public override bool ExecuteInsertCommand (DbCommand dbCommand) + { + List columnNames = ExistingColumnNamesNonId; + // Avoid insert if Identity field is already valid. + if (_Id != 0) throw new Exception("Invalid for Insert - item already has a valid Id"); + // Construct query. + String query = + "INSERT INTO " + TableNameFmt + " " + + "("+columnNames.Concat(",","[","]")+") "; + query += "Output Inserted.Id "; + if (dbCommand is SqlCommand) + query += "VALUES (" + columnNames.Concat(",", "@", "") + ") "; + else query += "VALUES (" + StringListUtil.CreateList("?", columnNames.Count).Concat(",") + ") "; + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteInsertCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("ProvinceId")) AddCommandParameter(dbCommand, "@ProvinceId", _ProvinceId); + if (columnNames.ContainsCI("FacilityId")) AddCommandParameter(dbCommand, "@FacilityId", _FacilityId); + if (columnNames.ContainsCI("FacilityName")) AddCommandParameter(dbCommand, "@FacilityName", _FacilityName); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("CreateOn")) AddCommandParameter(dbCommand, "@CreateOn", _CreateOn); + if (columnNames.ContainsCI("CreateBy")) AddCommandParameter(dbCommand, "@CreateBy", _CreateBy); + if (columnNames.ContainsCI("CreateHost")) AddCommandParameter(dbCommand, "@CreateHost", _CreateHost); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + // Execute insert command. + bool commandSuccess = false; + int executeNonQuery = dbCommand.ExecuteNonQuery(); + if (executeNonQuery == 1) + { + dbCommand.CommandText = "SELECT Max(Id) FROM " + TableNameFmt + ";"; + _Id = Convert.ToInt64(dbCommand.ExecuteScalar()); + commandSuccess = (_Id > 0); + } + return commandSuccess; + } + + //------------------------------------------------------------------- + // Update command. + public override bool ExecuteUpdateCommand (DbCommand dbCommand) + { + // Avoid update if Identity field isn't valid. + if (_Id == 0) throw new Exception("Invalid for Update - item has an invalid Id"); + // Columns to update. + List columnNames = ExistingColumnNamesNonId.Where(item => !fieldsPrimary.ContainsCI(item) && !fieldsIgnoreOnUpdate.ContainsCI(item)).ToList(); + // Construct query. + String query = "UPDATE " + TableNameFmt + " SET "; + if (dbCommand is SqlCommand) + { + query += StringPairList.CreateFrom(columnNames.Bracket("[","]"),columnNames).Concat("=@").Concat(", ") + " "; + query += "WHERE Id=@Id;"; + } + else + { + query += columnNames.Concat(", ", "", "=?") + " "; + query += "WHERE Id=?;"; + } + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteUpdateCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("ProvinceId")) AddCommandParameter(dbCommand, "@ProvinceId", _ProvinceId); + if (columnNames.ContainsCI("FacilityId")) AddCommandParameter(dbCommand, "@FacilityId", _FacilityId); + if (columnNames.ContainsCI("FacilityName")) AddCommandParameter(dbCommand, "@FacilityName", _FacilityName); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + AddCommandParameter(dbCommand, "@Id", _Id); + int executeNonQueryResult = dbCommand.ExecuteNonQuery(); + return (executeNonQueryResult == 1); + } + + //------------------------------------------------------------------- + } +} diff --git a/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaMarker_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaMarker_Db.cs new file mode 100644 index 0000000..1baa3cc --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaMarker_Db.cs @@ -0,0 +1,272 @@ +using Microsoft.Data.SqlClient; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Saxonite.Net.Standard.Dbas.Data; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +//--------------------------------------------------------------------------- +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 +//--------------------------------------------------------------------------- +namespace Saxonite.Net.Standard.Dbas.Internal.Reference +{ + internal class Golf_UsgaMarker_Db : SaxDbDataItem + { + //------------------------------------------------------------------- + // Column definitions. + public class ColumnsData + { + public ColumnDataInt64 _Id { get; } = new ColumnDataInt64("Id", true); + public ColumnDataInt64 _CourseId { get; } = new ColumnDataInt64("CourseId"); + public ColumnDataInt64 _MarkerId { get; } = new ColumnDataInt64("MarkerId"); + public ColumnDataString _Caption { get; } = new ColumnDataString("Caption"); + public ColumnDataInt16 _Holes { get; } = new ColumnDataInt16("Holes"); + public ColumnDataString _HolesCaption { get; } = new ColumnDataString("HolesCaption"); + public ColumnDataString _Tee { get; } = new ColumnDataString("Tee"); + public ColumnDataString _Gender { get; } = new ColumnDataString("Gender"); + public ColumnDataInt16 _SlopeRating { get; } = new ColumnDataInt16("SlopeRating"); + public ColumnDataInt16 _Par { get; } = new ColumnDataInt16("Par"); + public ColumnDataDecimal _CourseRating { get; } = new ColumnDataDecimal("CourseRating"); + public ColumnDataDecimal _BogeyRating { get; } = new ColumnDataDecimal("BogeyRating"); + public ColumnDataInt16 _Length { get; } = new ColumnDataInt16("Length"); + public ColumnDataString _Notes { get; } = new ColumnDataString("Notes"); + public ColumnDataInt16 _Flags { get; } = new ColumnDataInt16("Flags"); + public ColumnDataString _Status { get; } = new ColumnDataString("Status"); + public ColumnDataDateTime _CreateOn { get; } = new ColumnDataDateTime("CreateOn"); + public ColumnDataInt32 _CreateBy { get; } = new ColumnDataInt32("CreateBy"); + public ColumnDataString _CreateHost { get; } = new ColumnDataString("CreateHost"); + public ColumnDataDateTime _UpdateOn { get; } = new ColumnDataDateTime("UpdateOn"); + public ColumnDataInt32 _UpdateBy { get; } = new ColumnDataInt32("UpdateBy"); + public ColumnDataString _UpdateHost { get; } = new ColumnDataString("UpdateHost"); + } + + //------------------------------------------------------------------- + // Data members. + protected static List fields { get; } = new List() + { + "Id", + "CourseId", + "MarkerId", + "Caption", + "Holes", + "HolesCaption", + "Tee", + "Gender", + "SlopeRating", + "Par", + "CourseRating", + "BogeyRating", + "Length", + "Notes", + "Flags", + "Status", + "CreateOn", + "CreateBy", + "CreateHost", + "UpdateOn", + "UpdateBy", + "UpdateHost", + }; + protected static List fieldsId { get; } = new List() + { + "Id", + }; + protected static List fieldsPrimary { get; } = new List() + { + "Id", + }; + protected static List fieldsIgnoreOnUpdate { get; } = new List() + { + "CreateOn", + "CreateBy", + "CreateHost", + }; + + //------------------------------------------------------------------- + // Construction. + internal Golf_UsgaMarker_Db (IDatabaseInfo dbInfo) : base(dbInfo) + { + } + + //------------------------------------------------------------------- + // Properties. + public override String SchemaName { get; } = "golf"; + public override String TableName { get; } = "UsgaMarker"; + public String TableNameFmt { get { return (!String.IsNullOrEmpty(SchemaName) ? "[" + SchemaName + "]." : "") + "[" + TableName + "]"; } } + public static List Fields { get { return new List(fields); } } + public static List FieldsId { get { return new List(fieldsId); } } + public static List FieldsNonId { get { return fields.FindAll(item => !fieldsId.ContainsCI(item)); } } + // Columns. + public ColumnsData Cols { get; } = new ColumnsData(); + public Int64 _Id { get { return Cols._Id.Value; } set { Cols._Id.Value = value; } } + public Int64 _CourseId { get { return Cols._CourseId.Value; } set { Cols._CourseId.Value = value; } } + public Int64 _MarkerId { get { return Cols._MarkerId.Value; } set { Cols._MarkerId.Value = value; } } + public String _Caption { get { return Cols._Caption.Value; } set { Cols._Caption.Value = value; } } + public Int16 _Holes { get { return Cols._Holes.Value; } set { Cols._Holes.Value = value; } } + public String _HolesCaption { get { return Cols._HolesCaption.Value; } set { Cols._HolesCaption.Value = value; } } + public String _Tee { get { return Cols._Tee.Value; } set { Cols._Tee.Value = value; } } + public String _Gender { get { return Cols._Gender.Value; } set { Cols._Gender.Value = value; } } + public Int16 _SlopeRating { get { return Cols._SlopeRating.Value; } set { Cols._SlopeRating.Value = value; } } + public Int16 _Par { get { return Cols._Par.Value; } set { Cols._Par.Value = value; } } + public Decimal _CourseRating { get { return Cols._CourseRating.Value; } set { Cols._CourseRating.Value = value; } } + public Decimal _BogeyRating { get { return Cols._BogeyRating.Value; } set { Cols._BogeyRating.Value = value; } } + public Int16 _Length { get { return Cols._Length.Value; } set { Cols._Length.Value = value; } } + public String _Notes { get { return Cols._Notes.Value; } set { Cols._Notes.Value = value; } } + public Int16 _Flags { get { return Cols._Flags.Value; } set { Cols._Flags.Value = value; } } + public String _Status { get { return Cols._Status.Value; } set { Cols._Status.Value = value; } } + public DateTime _CreateOn { get { return Cols._CreateOn.Value; } set { Cols._CreateOn.Value = value; } } + public Int32 _CreateBy { get { return Cols._CreateBy.Value; } set { Cols._CreateBy.Value = value; } } + public String _CreateHost { get { return Cols._CreateHost.Value; } set { Cols._CreateHost.Value = value; } } + public DateTime _UpdateOn { get { return Cols._UpdateOn.Value; } set { Cols._UpdateOn.Value = value; } } + public Int32 _UpdateBy { get { return Cols._UpdateBy.Value; } set { Cols._UpdateBy.Value = value; } } + public String _UpdateHost { get { return Cols._UpdateHost.Value; } set { Cols._UpdateHost.Value = value; } } + // Existing columns - confirmed on database if table exists. + public List ExistingColumnNames { get { return GetExistingColumnNames(Fields); } } + public List ExistingColumnNamesNonId { get { return GetExistingColumnNames(FieldsNonId); } } + + //------------------------------------------------------------------- + // Population. + public override void PopulateFrom (DbCommand dbCommand, String tableAlias, String filter) + { + dbCommand.CommandText = + "SELECT " + ExistingColumnNames.Concat(", ", (!String.IsNullOrEmpty(tableAlias) ? tableAlias + "." : "") + "[", "]") + " " + + "FROM " + TableNameFmt + (!String.IsNullOrEmpty(tableAlias) ? " " + tableAlias : "") + " " + + (!String.IsNullOrEmpty(filter) ? "WHERE " + filter : ""); + Log(GetType().Name + ".PopulateFrom", dbCommand.CommandText); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + dbDataReader.Read(); + PopulateFrom(dbDataReader); + } + } + public override void PopulateFrom (DbDataReader dbDataReader) + { + _Id = GetFieldInt64(dbDataReader, "Id", _Id); + _CourseId = GetFieldInt64(dbDataReader, "CourseId", _CourseId); + _MarkerId = GetFieldInt64(dbDataReader, "MarkerId", _MarkerId); + _Caption = GetFieldString(dbDataReader, "Caption", _Caption); + _Holes = GetFieldInt16(dbDataReader, "Holes", _Holes); + _HolesCaption = GetFieldString(dbDataReader, "HolesCaption", _HolesCaption); + _Tee = GetFieldString(dbDataReader, "Tee", _Tee); + _Gender = GetFieldString(dbDataReader, "Gender", _Gender); + _SlopeRating = GetFieldInt16(dbDataReader, "SlopeRating", _SlopeRating); + _Par = GetFieldInt16(dbDataReader, "Par", _Par); + _CourseRating = GetFieldDecimal(dbDataReader, "CourseRating", _CourseRating); + _BogeyRating = GetFieldDecimal(dbDataReader, "BogeyRating", _BogeyRating); + _Length = GetFieldInt16(dbDataReader, "Length", _Length); + _Notes = GetFieldString(dbDataReader, "Notes", _Notes); + _Flags = GetFieldInt16(dbDataReader, "Flags", _Flags); + _Status = GetFieldString(dbDataReader, "Status", _Status); + _CreateOn = GetFieldDateTime(dbDataReader, "CreateOn", _CreateOn); + _CreateBy = GetFieldInt32(dbDataReader, "CreateBy", _CreateBy); + _CreateHost = GetFieldString(dbDataReader, "CreateHost", _CreateHost); + _UpdateOn = GetFieldDateTime(dbDataReader, "UpdateOn", _UpdateOn); + _UpdateBy = GetFieldInt32(dbDataReader, "UpdateBy", _UpdateBy); + _UpdateHost = GetFieldString(dbDataReader, "UpdateHost", _UpdateHost); + } + + //------------------------------------------------------------------- + // Insert command. + public override bool ExecuteInsertCommand (DbCommand dbCommand) + { + List columnNames = ExistingColumnNamesNonId; + // Avoid insert if Identity field is already valid. + if (_Id != 0) throw new Exception("Invalid for Insert - item already has a valid Id"); + // Construct query. + String query = + "INSERT INTO " + TableNameFmt + " " + + "("+columnNames.Concat(",","[","]")+") "; + query += "Output Inserted.Id "; + if (dbCommand is SqlCommand) + query += "VALUES (" + columnNames.Concat(",", "@", "") + ") "; + else query += "VALUES (" + StringListUtil.CreateList("?", columnNames.Count).Concat(",") + ") "; + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteInsertCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("CourseId")) AddCommandParameter(dbCommand, "@CourseId", _CourseId); + if (columnNames.ContainsCI("MarkerId")) AddCommandParameter(dbCommand, "@MarkerId", _MarkerId); + if (columnNames.ContainsCI("Caption")) AddCommandParameter(dbCommand, "@Caption", _Caption); + if (columnNames.ContainsCI("Holes")) AddCommandParameter(dbCommand, "@Holes", _Holes); + if (columnNames.ContainsCI("HolesCaption")) AddCommandParameter(dbCommand, "@HolesCaption", _HolesCaption); + if (columnNames.ContainsCI("Tee")) AddCommandParameter(dbCommand, "@Tee", _Tee); + if (columnNames.ContainsCI("Gender")) AddCommandParameter(dbCommand, "@Gender", _Gender); + if (columnNames.ContainsCI("SlopeRating")) AddCommandParameter(dbCommand, "@SlopeRating", _SlopeRating); + if (columnNames.ContainsCI("Par")) AddCommandParameter(dbCommand, "@Par", _Par); + if (columnNames.ContainsCI("CourseRating")) AddCommandParameter(dbCommand, "@CourseRating", _CourseRating); + if (columnNames.ContainsCI("BogeyRating")) AddCommandParameter(dbCommand, "@BogeyRating", _BogeyRating); + if (columnNames.ContainsCI("Length")) AddCommandParameter(dbCommand, "@Length", _Length); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("CreateOn")) AddCommandParameter(dbCommand, "@CreateOn", _CreateOn); + if (columnNames.ContainsCI("CreateBy")) AddCommandParameter(dbCommand, "@CreateBy", _CreateBy); + if (columnNames.ContainsCI("CreateHost")) AddCommandParameter(dbCommand, "@CreateHost", _CreateHost); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + // Execute insert command. + bool commandSuccess = false; + int executeNonQuery = dbCommand.ExecuteNonQuery(); + if (executeNonQuery == 1) + { + dbCommand.CommandText = "SELECT Max(Id) FROM " + TableNameFmt + ";"; + _Id = Convert.ToInt64(dbCommand.ExecuteScalar()); + commandSuccess = (_Id > 0); + } + return commandSuccess; + } + + //------------------------------------------------------------------- + // Update command. + public override bool ExecuteUpdateCommand (DbCommand dbCommand) + { + // Avoid update if Identity field isn't valid. + if (_Id == 0) throw new Exception("Invalid for Update - item has an invalid Id"); + // Columns to update. + List columnNames = ExistingColumnNamesNonId.Where(item => !fieldsPrimary.ContainsCI(item) && !fieldsIgnoreOnUpdate.ContainsCI(item)).ToList(); + // Construct query. + String query = "UPDATE " + TableNameFmt + " SET "; + if (dbCommand is SqlCommand) + { + query += StringPairList.CreateFrom(columnNames.Bracket("[","]"),columnNames).Concat("=@").Concat(", ") + " "; + query += "WHERE Id=@Id;"; + } + else + { + query += columnNames.Concat(", ", "", "=?") + " "; + query += "WHERE Id=?;"; + } + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteUpdateCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("CourseId")) AddCommandParameter(dbCommand, "@CourseId", _CourseId); + if (columnNames.ContainsCI("MarkerId")) AddCommandParameter(dbCommand, "@MarkerId", _MarkerId); + if (columnNames.ContainsCI("Caption")) AddCommandParameter(dbCommand, "@Caption", _Caption); + if (columnNames.ContainsCI("Holes")) AddCommandParameter(dbCommand, "@Holes", _Holes); + if (columnNames.ContainsCI("HolesCaption")) AddCommandParameter(dbCommand, "@HolesCaption", _HolesCaption); + if (columnNames.ContainsCI("Tee")) AddCommandParameter(dbCommand, "@Tee", _Tee); + if (columnNames.ContainsCI("Gender")) AddCommandParameter(dbCommand, "@Gender", _Gender); + if (columnNames.ContainsCI("SlopeRating")) AddCommandParameter(dbCommand, "@SlopeRating", _SlopeRating); + if (columnNames.ContainsCI("Par")) AddCommandParameter(dbCommand, "@Par", _Par); + if (columnNames.ContainsCI("CourseRating")) AddCommandParameter(dbCommand, "@CourseRating", _CourseRating); + if (columnNames.ContainsCI("BogeyRating")) AddCommandParameter(dbCommand, "@BogeyRating", _BogeyRating); + if (columnNames.ContainsCI("Length")) AddCommandParameter(dbCommand, "@Length", _Length); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + AddCommandParameter(dbCommand, "@Id", _Id); + int executeNonQueryResult = dbCommand.ExecuteNonQuery(); + return (executeNonQueryResult == 1); + } + + //------------------------------------------------------------------- + } +} diff --git a/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaProvince_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaProvince_Db.cs new file mode 100644 index 0000000..8c32ff0 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Internal/Reference/Golf_UsgaProvince_Db.cs @@ -0,0 +1,224 @@ +using Microsoft.Data.SqlClient; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Saxonite.Net.Standard.Dbas.Data; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +//--------------------------------------------------------------------------- +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:55 +//--------------------------------------------------------------------------- +namespace Saxonite.Net.Standard.Dbas.Internal.Reference +{ + internal class Golf_UsgaProvince_Db : SaxDbDataItem + { + //------------------------------------------------------------------- + // Column definitions. + public class ColumnsData + { + public ColumnDataInt64 _Id { get; } = new ColumnDataInt64("Id", true); + public ColumnDataInt64 _CountryId { get; } = new ColumnDataInt64("CountryId"); + public ColumnDataString _ProvinceCode { get; } = new ColumnDataString("ProvinceCode"); + public ColumnDataString _EntProvinceCode { get; } = new ColumnDataString("EntProvinceCode"); + public ColumnDataString _ProvinceName { get; } = new ColumnDataString("ProvinceName"); + public ColumnDataString _Notes { get; } = new ColumnDataString("Notes"); + public ColumnDataInt16 _Flags { get; } = new ColumnDataInt16("Flags"); + public ColumnDataString _Status { get; } = new ColumnDataString("Status"); + public ColumnDataDateTime _CreateOn { get; } = new ColumnDataDateTime("CreateOn"); + public ColumnDataInt32 _CreateBy { get; } = new ColumnDataInt32("CreateBy"); + public ColumnDataString _CreateHost { get; } = new ColumnDataString("CreateHost"); + public ColumnDataDateTime _UpdateOn { get; } = new ColumnDataDateTime("UpdateOn"); + public ColumnDataInt32 _UpdateBy { get; } = new ColumnDataInt32("UpdateBy"); + public ColumnDataString _UpdateHost { get; } = new ColumnDataString("UpdateHost"); + } + + //------------------------------------------------------------------- + // Data members. + protected static List fields { get; } = new List() + { + "Id", + "CountryId", + "ProvinceCode", + "EntProvinceCode", + "ProvinceName", + "Notes", + "Flags", + "Status", + "CreateOn", + "CreateBy", + "CreateHost", + "UpdateOn", + "UpdateBy", + "UpdateHost", + }; + protected static List fieldsId { get; } = new List() + { + "Id", + }; + protected static List fieldsPrimary { get; } = new List() + { + "Id", + }; + protected static List fieldsIgnoreOnUpdate { get; } = new List() + { + "CreateOn", + "CreateBy", + "CreateHost", + }; + + //------------------------------------------------------------------- + // Construction. + internal Golf_UsgaProvince_Db (IDatabaseInfo dbInfo) : base(dbInfo) + { + } + + //------------------------------------------------------------------- + // Properties. + public override String SchemaName { get; } = "golf"; + public override String TableName { get; } = "UsgaProvince"; + public String TableNameFmt { get { return (!String.IsNullOrEmpty(SchemaName) ? "[" + SchemaName + "]." : "") + "[" + TableName + "]"; } } + public static List Fields { get { return new List(fields); } } + public static List FieldsId { get { return new List(fieldsId); } } + public static List FieldsNonId { get { return fields.FindAll(item => !fieldsId.ContainsCI(item)); } } + // Columns. + public ColumnsData Cols { get; } = new ColumnsData(); + public Int64 _Id { get { return Cols._Id.Value; } set { Cols._Id.Value = value; } } + public Int64 _CountryId { get { return Cols._CountryId.Value; } set { Cols._CountryId.Value = value; } } + public String _ProvinceCode { get { return Cols._ProvinceCode.Value; } set { Cols._ProvinceCode.Value = value; } } + public String _EntProvinceCode { get { return Cols._EntProvinceCode.Value; } set { Cols._EntProvinceCode.Value = value; } } + public String _ProvinceName { get { return Cols._ProvinceName.Value; } set { Cols._ProvinceName.Value = value; } } + public String _Notes { get { return Cols._Notes.Value; } set { Cols._Notes.Value = value; } } + public Int16 _Flags { get { return Cols._Flags.Value; } set { Cols._Flags.Value = value; } } + public String _Status { get { return Cols._Status.Value; } set { Cols._Status.Value = value; } } + public DateTime _CreateOn { get { return Cols._CreateOn.Value; } set { Cols._CreateOn.Value = value; } } + public Int32 _CreateBy { get { return Cols._CreateBy.Value; } set { Cols._CreateBy.Value = value; } } + public String _CreateHost { get { return Cols._CreateHost.Value; } set { Cols._CreateHost.Value = value; } } + public DateTime _UpdateOn { get { return Cols._UpdateOn.Value; } set { Cols._UpdateOn.Value = value; } } + public Int32 _UpdateBy { get { return Cols._UpdateBy.Value; } set { Cols._UpdateBy.Value = value; } } + public String _UpdateHost { get { return Cols._UpdateHost.Value; } set { Cols._UpdateHost.Value = value; } } + // Existing columns - confirmed on database if table exists. + public List ExistingColumnNames { get { return GetExistingColumnNames(Fields); } } + public List ExistingColumnNamesNonId { get { return GetExistingColumnNames(FieldsNonId); } } + + //------------------------------------------------------------------- + // Population. + public override void PopulateFrom (DbCommand dbCommand, String tableAlias, String filter) + { + dbCommand.CommandText = + "SELECT " + ExistingColumnNames.Concat(", ", (!String.IsNullOrEmpty(tableAlias) ? tableAlias + "." : "") + "[", "]") + " " + + "FROM " + TableNameFmt + (!String.IsNullOrEmpty(tableAlias) ? " " + tableAlias : "") + " " + + (!String.IsNullOrEmpty(filter) ? "WHERE " + filter : ""); + Log(GetType().Name + ".PopulateFrom", dbCommand.CommandText); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + dbDataReader.Read(); + PopulateFrom(dbDataReader); + } + } + public override void PopulateFrom (DbDataReader dbDataReader) + { + _Id = GetFieldInt64(dbDataReader, "Id", _Id); + _CountryId = GetFieldInt64(dbDataReader, "CountryId", _CountryId); + _ProvinceCode = GetFieldString(dbDataReader, "ProvinceCode", _ProvinceCode); + _EntProvinceCode = GetFieldString(dbDataReader, "EntProvinceCode", _EntProvinceCode); + _ProvinceName = GetFieldString(dbDataReader, "ProvinceName", _ProvinceName); + _Notes = GetFieldString(dbDataReader, "Notes", _Notes); + _Flags = GetFieldInt16(dbDataReader, "Flags", _Flags); + _Status = GetFieldString(dbDataReader, "Status", _Status); + _CreateOn = GetFieldDateTime(dbDataReader, "CreateOn", _CreateOn); + _CreateBy = GetFieldInt32(dbDataReader, "CreateBy", _CreateBy); + _CreateHost = GetFieldString(dbDataReader, "CreateHost", _CreateHost); + _UpdateOn = GetFieldDateTime(dbDataReader, "UpdateOn", _UpdateOn); + _UpdateBy = GetFieldInt32(dbDataReader, "UpdateBy", _UpdateBy); + _UpdateHost = GetFieldString(dbDataReader, "UpdateHost", _UpdateHost); + } + + //------------------------------------------------------------------- + // Insert command. + public override bool ExecuteInsertCommand (DbCommand dbCommand) + { + List columnNames = ExistingColumnNamesNonId; + // Avoid insert if Identity field is already valid. + if (_Id != 0) throw new Exception("Invalid for Insert - item already has a valid Id"); + // Construct query. + String query = + "INSERT INTO " + TableNameFmt + " " + + "("+columnNames.Concat(",","[","]")+") "; + query += "Output Inserted.Id "; + if (dbCommand is SqlCommand) + query += "VALUES (" + columnNames.Concat(",", "@", "") + ") "; + else query += "VALUES (" + StringListUtil.CreateList("?", columnNames.Count).Concat(",") + ") "; + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteInsertCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("CountryId")) AddCommandParameter(dbCommand, "@CountryId", _CountryId); + if (columnNames.ContainsCI("ProvinceCode")) AddCommandParameter(dbCommand, "@ProvinceCode", _ProvinceCode); + if (columnNames.ContainsCI("EntProvinceCode")) AddCommandParameter(dbCommand, "@EntProvinceCode", _EntProvinceCode); + if (columnNames.ContainsCI("ProvinceName")) AddCommandParameter(dbCommand, "@ProvinceName", _ProvinceName); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("CreateOn")) AddCommandParameter(dbCommand, "@CreateOn", _CreateOn); + if (columnNames.ContainsCI("CreateBy")) AddCommandParameter(dbCommand, "@CreateBy", _CreateBy); + if (columnNames.ContainsCI("CreateHost")) AddCommandParameter(dbCommand, "@CreateHost", _CreateHost); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + // Execute insert command. + bool commandSuccess = false; + int executeNonQuery = dbCommand.ExecuteNonQuery(); + if (executeNonQuery == 1) + { + dbCommand.CommandText = "SELECT Max(Id) FROM " + TableNameFmt + ";"; + _Id = Convert.ToInt64(dbCommand.ExecuteScalar()); + commandSuccess = (_Id > 0); + } + return commandSuccess; + } + + //------------------------------------------------------------------- + // Update command. + public override bool ExecuteUpdateCommand (DbCommand dbCommand) + { + // Avoid update if Identity field isn't valid. + if (_Id == 0) throw new Exception("Invalid for Update - item has an invalid Id"); + // Columns to update. + List columnNames = ExistingColumnNamesNonId.Where(item => !fieldsPrimary.ContainsCI(item) && !fieldsIgnoreOnUpdate.ContainsCI(item)).ToList(); + // Construct query. + String query = "UPDATE " + TableNameFmt + " SET "; + if (dbCommand is SqlCommand) + { + query += StringPairList.CreateFrom(columnNames.Bracket("[","]"),columnNames).Concat("=@").Concat(", ") + " "; + query += "WHERE Id=@Id;"; + } + else + { + query += columnNames.Concat(", ", "", "=?") + " "; + query += "WHERE Id=?;"; + } + dbCommand.CommandText = query; + Log(GetType().Name + ".ExecuteUpdateCommand", dbCommand.CommandText); + // Populate parameters. + dbCommand.Parameters.Clear(); + if (columnNames.ContainsCI("CountryId")) AddCommandParameter(dbCommand, "@CountryId", _CountryId); + if (columnNames.ContainsCI("ProvinceCode")) AddCommandParameter(dbCommand, "@ProvinceCode", _ProvinceCode); + if (columnNames.ContainsCI("EntProvinceCode")) AddCommandParameter(dbCommand, "@EntProvinceCode", _EntProvinceCode); + if (columnNames.ContainsCI("ProvinceName")) AddCommandParameter(dbCommand, "@ProvinceName", _ProvinceName); + if (columnNames.ContainsCI("Notes")) AddCommandParameter(dbCommand, "@Notes", _Notes); + if (columnNames.ContainsCI("Flags")) AddCommandParameter(dbCommand, "@Flags", _Flags); + if (columnNames.ContainsCI("Status")) AddCommandParameter(dbCommand, "@Status", _Status); + if (columnNames.ContainsCI("UpdateOn")) AddCommandParameter(dbCommand, "@UpdateOn", _UpdateOn); + if (columnNames.ContainsCI("UpdateBy")) AddCommandParameter(dbCommand, "@UpdateBy", _UpdateBy); + if (columnNames.ContainsCI("UpdateHost")) AddCommandParameter(dbCommand, "@UpdateHost", _UpdateHost); + AddCommandParameter(dbCommand, "@Id", _Id); + int executeNonQueryResult = dbCommand.ExecuteNonQuery(); + return (executeNonQueryResult == 1); + } + + //------------------------------------------------------------------- + } +} diff --git a/SaxoniteStandardDbas/Dbas/Internal/Support/UserReportComment_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Support/UserReportComment_Db.cs index d98b010..4832924 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Support/UserReportComment_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Support/UserReportComment_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:56 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Support { diff --git a/SaxoniteStandardDbas/Dbas/Internal/Support/UserReport_Db.cs b/SaxoniteStandardDbas/Dbas/Internal/Support/UserReport_Db.cs index f7d4d67..dbde2c0 100644 --- a/SaxoniteStandardDbas/Dbas/Internal/Support/UserReport_Db.cs +++ b/SaxoniteStandardDbas/Dbas/Internal/Support/UserReport_Db.cs @@ -9,7 +9,7 @@ using System.Data.Common; using System.Linq; //--------------------------------------------------------------------------- -// Code generated by Sarand Database Utilities Wed 8-Feb-2023 18:02:24 +// Code generated by Sarand Database Utilities Wed 22-May-2024 12:21:56 //--------------------------------------------------------------------------- namespace Saxonite.Net.Standard.Dbas.Internal.Support { diff --git a/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaCountry.cs b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaCountry.cs new file mode 100644 index 0000000..82228eb --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaCountry.cs @@ -0,0 +1,587 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Sarand.Net.Standard.Dbas.Data; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Internal.Reference; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +namespace Saxonite.Net.Standard.Dbas.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr_Dbas + { + //******************************************************************* + // Support Mgr - User Report + //******************************************************************* + // Utilities. + private List GetLogProperties(SaxGolfUsgaCountry usgaCountry) + { + return new List() + { + new StringPair("Id",SysId.ToString(usgaCountry.Id)), + new StringPair("CountryCode",usgaCountry.CountryCode), + new StringPair("CountryName",usgaCountry.CountryName), + new StringPair("Status",usgaCountry.StatusCode) + }; + } + + //------------------------------------------------------------------- + // Create item. + public override SaxGolfUsgaCountry CreateUsgaCountry() + { + ClearErrorState(); + return new SaxGolfUsgaCountry_Dbas(ReferenceDatabase, null, 0); + } + private SaxGolfUsgaCountry_Dbas CreateUsgaCountry(Golf_UsgaCountry_Db dbUsgaCountry) + { + ClearErrorState(); + SaxGolfUsgaCountry_Dbas usgaCountry = new SaxGolfUsgaCountry_Dbas(ReferenceDatabase, new SysId(dbUsgaCountry._Id), (ushort)dbUsgaCountry._Flags); + PopulateFrom(dbUsgaCountry, usgaCountry); + return usgaCountry; + } + + //------------------------------------------------------------------- + // Get item. + public override SaxGolfUsgaCountry GetUsgaCountry(SaxGolfUsgaCountry.Params prm) + { + ClearErrorState(); + return GetUsgaCountry(GetUsgaCountryQueryFilter(prm).Concat(" And ", "(", ")")); + } + private SaxGolfUsgaCountry GetUsgaCountry(String filter) + { + ClearErrorState(); + long count = GetUsgaCountryCount(filter); + if (count == 0) return null; + if (count != 1) + { + SetErrorState("Multiple items found"); + return null; + } + SaxGolfUsgaCountry usgaCountry = null; + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaCountry_Db dbUsgaCountry = new Golf_UsgaCountry_Db(ReferenceDbInfo); + dbUsgaCountry.PopulateFrom(dbCommand, aliasUsgaCountry, filter); + usgaCountry = CreateUsgaCountry(dbUsgaCountry); + } + catch (Exception exc) + { + SetErrorState("Database query exception"); + SaLogger.Warn(GetType().Name + ".GetUsgaCountry\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return usgaCountry; + } + + //------------------------------------------------------------------- + // Validate item. + public override bool IsValidUsgaCountryData(SaxGolfUsgaCountry.Data data, SaxGolfUsgaCountry.ErrField errField) + { + ClearErrorState(); + if (!base.IsValidUsgaCountryData(data, errField)) return false; + return true; + } + + //------------------------------------------------------------------- + // Insert item. + public override bool InsertUsgaCountry(SaxGolfUsgaCountry usgaCountry, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".InsertUsgaCountry"; + ClearErrorState(); + if (!IsValidUsgaCountry(usgaCountry)) return false; + if (SysId.IsValid(usgaCountry.Id)) return SetErrorState(ErrorMessage.ValiditemId); + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaCountry_Db dbUsgaCountry = new Golf_UsgaCountry_Db(ReferenceDbInfo); + PopulateTo(dbUsgaCountry, usgaCountry, dbUpdateInfo); + if (Golf_UsgaCountry_Db.FieldsNonId.Contains("Id")) + { + // Generate next Id. + dbUsgaCountry._Id = ReferenceDatabase.GetNextIdFromTable("UsgaCountry"); + } + dbUsgaCountry.ExecuteInsertCommand(dbCommand); + usgaCountry.Id = new SysId(dbUsgaCountry._Id); + usgaCountry.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Inserted. " + GetLogProperties(usgaCountry).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Update item. + public override bool UpdateUsgaCountry(SaxGolfUsgaCountry usgaCountry, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".UpdateUsgaCountry"; + ClearErrorState(); + if (!IsValidUsgaCountry(usgaCountry)) return false; + if (!SysId.IsValid(usgaCountry.Id)) return SetErrorState(ErrorMessage.InvalidItemId); + if (!usgaCountry.Changed) + { + if (DebugMode) SaLogger.Debug(fn + " Data not changed. " + GetLogProperties(usgaCountry).Concat(": ").Concat("", "\n\t")); + return true; + } + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaCountry_Db dbUsgaCountry = new Golf_UsgaCountry_Db(ReferenceDbInfo); + dbUsgaCountry.PopulateFrom(dbCommand, aliasUsgaCountry, "Id=" + SysId.ToString(usgaCountry.Id)); + // ToDo SaxUpdateLogItemMonitor_UsgaCountry updateLogMonitor = new SaxUpdateLogItemMonitor_UsgaCountry(SessionContext, CreateUsgaCountry(dbUsgaCountry), dbUpdateInfo); + // Update item. + PopulateTo(dbUsgaCountry, usgaCountry, dbUpdateInfo); + dbUsgaCountry.ExecuteUpdateCommand(dbCommand); + usgaCountry.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Updated. " + GetLogProperties(usgaCountry).Concat(": ").Concat("", "\n\t")); + // Record updates. + // ToDo updateLogMonitor.RecordUpdatedValues(usgaCountry); + // ToDo updateLogMonitor.LogUpdates(); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Delete item. + public override bool UsgaCountryCanBeDeleted(SaxGolfUsgaCountry usgaCountry) + { + ClearErrorState(); + if (!base.UsgaCountryCanBeDeleted(usgaCountry)) return false; + return true; + } + public override bool DeleteUsgaCountry(SaxGolfUsgaCountry usgaCountry, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".DeleteUsgaCountry"; + ClearErrorState(); + if (!UsgaCountryCanBeDeleted(usgaCountry)) return false; + + // User Roles are logically deleted by changing the status. + usgaCountry.Status = SaStatus.Deleted; + return UpdateUsgaCountry(usgaCountry, dbUpdateInfo); + + /* + * Physical deletion. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaCountry_Db dbUsgaCountry = new Golf_UsgaCountry_Db(ReferenceDbInfo); + dbUsgaCountry.PopulateFrom(dbCommand, aliasUsgaCountry, "Id=" + usgaCountry.Id.ToString()); + // Delete item. + dbCommand.CommandType = System.Data.CommandType.Text; + dbCommand.CommandText = "DELETE FROM " + SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCountry) + " WHERE Id=" + SysId.ToString(usgaCountry.Id) + ";"; + dbCommand.ExecuteNonQuery(); + usgaCountry.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Deleted. " + GetLogProperties(usgaCountry).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + */ + } + + //------------------------------------------------------------------- + // Copy data properties to and from database. + private void PopulateTo(Golf_UsgaCountry_Db dbUsgaCountry, SaxGolfUsgaCountry usgaCountry, DbUpdateInfo dbUpdateInfo) + { + dbUsgaCountry._Id = SysId.ToLong(usgaCountry.Id); + dbUsgaCountry._CountryCode = usgaCountry.CountryCode; + dbUsgaCountry._EntCountryCode = usgaCountry.EntCountryCode; + dbUsgaCountry._CountryName = usgaCountry.CountryName; + // Common. + dbUsgaCountry._Notes = usgaCountry.Notes; + dbUsgaCountry._Status = SacsSystem.GetStatusCode(usgaCountry.Status); + dbUsgaCountry._Flags = (short)usgaCountry.Flags; + if (!SysId.IsValid(usgaCountry.Id)) + { + dbUsgaCountry._CreateOn = DateTime.Now; + dbUsgaCountry._CreateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaCountry._CreateHost = dbUpdateInfo.Host; + } + dbUsgaCountry._UpdateOn = DateTime.Now; + dbUsgaCountry._UpdateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaCountry._UpdateHost = dbUpdateInfo.Host; + } + private void PopulateFrom(Golf_UsgaCountry_Db dbUsgaCountry, SaxGolfUsgaCountry usgaCountry) + { + //usgaCountry.Id = new SysId(dbUsgaCountry._Id); + usgaCountry.CountryCode = dbUsgaCountry._CountryCode; + usgaCountry.EntCountryCode = dbUsgaCountry._EntCountryCode; + usgaCountry.CountryName = dbUsgaCountry._CountryName; + // Common. + usgaCountry.Notes = dbUsgaCountry._Notes; + usgaCountry.Status = SacsSystem.GetStatusForCode(dbUsgaCountry._Status); + usgaCountry.SetCreateStamp(dbUsgaCountry._CreateOn, new SysId(dbUsgaCountry._CreateBy), dbUsgaCountry._CreateHost); + usgaCountry.SetUpdateStamp(dbUsgaCountry._UpdateOn, new SysId(dbUsgaCountry._UpdateBy), dbUsgaCountry._UpdateHost); + usgaCountry.AcceptChanges(); + } + + //------------------------------------------------------------------- + // Bulk updates. + /// + /// Bulk update USGA Countries. + /// - Country code must be supplied to act as identifier. + /// - Other properties are validated as per country rules - check error state. + /// - Other properties are left as is if null. + /// + public override bool BulkUpdateUsgaCountries(List countries, DbUpdateInfo dbUpdateInfo) + { + ClearErrorState(); + List countriesToUpdate = new List(); + + // Validate supplied data. + foreach (UsgaCountryData country in countries) + { + // Validate country properties. + // Code is mandatory, other values only validated if non-null. + if (!IsValidValue(country.CountryCode, "code", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryCode), true)) return false; + if (country.EntCountryCode != null && !IsValidValue(country.EntCountryCode, "ent code", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_EntCountryCode))) return false; + if (country.CountryName != null && !IsValidValue(country.CountryName, "name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName))) return false; + countriesToUpdate.Add(country); + } + int MaxBulkUpdateBatchSize = 64; + int batchSize = countriesToUpdate.Any() ? (int)Math.Ceiling(countriesToUpdate.Count() / Math.Ceiling((double)countriesToUpdate.Count() / MaxBulkUpdateBatchSize)) : MaxBulkUpdateBatchSize; + while (countriesToUpdate.Any()) + { + List query = new List(); + query.Add($"Declare @statusActive VarChar(3) = '{SacsSystem.GetStatusCode(SaxGolfUsgaCountry.DefaultStatus)}';"); + query.Add($"Declare @updateOn DateTime = GetUtcDate();"); + query.Add($"Declare @updateBy Int = {SysId.ToLong(dbUpdateInfo.UserId)};"); + query.Add($"Declare @updateHost VarChar(100) = '{DbQuery.FormatForCondition(dbUpdateInfo.Host)}';"); + query.Add("Merge"); + query.Add($"Into {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCountry)} uCty"); + query.Add("Using"); + query.Add("("); + query.Add("Select '' CountryCode, '' EntCountryCode, '' CountryName"); + foreach (UsgaCountryData country in countriesToUpdate.ExtractRange(0, batchSize)) + query.Add($"Union Select '{DbQuery.FormatForCondition(country.CountryCode)}', " + (country.EntCountryCode != null ? $"'{DbQuery.FormatForCondition(country.EntCountryCode)}'" : "Null") + ", " + (country.CountryName != null ? $"'{DbQuery.FormatForCondition(country.CountryName)}'" : "Null")); + query.Add(") dCty"); + query.Add("On uCty.CountryCode=dCty.CountryCode"); + query.Add("When Matched And ((dCty.EntCountryCode Is Not Null And uCty.EntCountryCode!=dCty.EntCountryCode) Or (dCty.CountryName Is Not Null And uCty.CountryName!=dCty.CountryName) Or uCty.Status!=@statusActive)"); + query.Add("Then Update Set"); + query.Add(" EntCountryCode=Coalesce(dCty.EntCountryCode,uCty.EntCountryCode),"); + query.Add(" CountryName=Coalesce(dCty.CountryName,uCty.CountryName),"); + query.Add(" Status=@statusActive,"); + query.Add(" UpdateOn=@updateOn,"); + query.Add(" UpdateBy=@updateBy,"); + query.Add(" UpdateHost=@updateHost"); + query.Add("When Not Matched And Len(IsNull(dCty.CountryName,''))>0"); + query.Add("Then Insert (CountryCode,EntCountryCode,CountryName,Notes,Flags,Status,CreateOn,CreateBy,CreateHost,UpdateOn,UpdateBy,UpdateHost)"); + query.Add($"Values (dCty.CountryCode,Coalesce(dCty.EntCountryCode,''),dCty.CountryName,'',0,@statusActive,@updateOn,@updateBy,@updateHost,@updateOn,@updateBy,@updateHost)"); + query.Add(";"); + //SaLogger.Info($"{SysUtil.Fn} Bulk USGA Country update query:\n\t{query.Concat("\n\t")}"); + + try + { + int result = ReferenceDatabase.ExecuteNonQuery(query.Concat("\n")); + if (ReferenceDatabase.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error executing bulk USGA Country update - {ReferenceDatabase.ErrorStateMessage}"); + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, " executing bulk USGA Country update")); + } + } + return HasErrorState(); + } + + //------------------------------------------------------------------- + // Item column definitions. + private static readonly String aliasUsgaCountry = "UsgPrv"; + private static readonly String aliasUsgaCountry_Dummy = "UsgPrv_Cty"; + private static readonly String prefixUsgaCountry_Dummy = aliasUsgaCountry_Dummy + "_"; + private void SetUsgaCountryColDfn + (ColumnDfn col, String caption, int width, SaxDbDfn_Reference.ColumnIdx dbCol, + ColumnAlignment align = ColumnAlignment.Default, DataValue.DataType dataType = DataValue.DataType.String, + String alias = "", String prefix = "") + { + if (String.IsNullOrEmpty(alias) && SaxDbDfn_Reference.GetTableForColumn(dbCol) == SaxDbDfn_Reference.TableIdx.UsgaCountry) + alias = aliasUsgaCountry; + col.Set(caption, width, (int)dbCol, prefix + SaxDbDfn_Reference.GetColumnName(dbCol, false), SaxDbDfn_Reference.GetColumnNameQual(dbCol, alias), dataType, align); + if (dataType == DataValue.DataType.String && dbCol != SaxDbDfn_Reference.ColumnIdx.Unknown) + col.MaxLength = (int)SaxDbDfn_Reference.GetColTextLen(dbCol); + } + public override ColumnDfn GetUsgaCountryColumnDfn(SaxGolfUsgaCountry.Column columnId, string caption = "", int width = 0) + { + ColumnDfn columnDfn = new ColumnDfn((int)columnId, caption, width); + switch (columnId) + { + //----------------------------------------------------------- + case SaxGolfUsgaCountry.Column.Pos: + SetUsgaCountryColDfn(columnDfn, "Pos", 60, SaxDbDfn_Reference.ColumnIdx.Unknown, ColumnAlignment.Right); + columnDfn.SortMode = ColumnDfn.ColumnSortMode.Off; + columnDfn.ReadOnly = true; + columnDfn.Resizable = false; + break; + case SaxGolfUsgaCountry.Column.Id: + SetUsgaCountryColDfn(columnDfn, "Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Id, ColumnAlignment.Right, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaCountry.Column.CountryCode: + SetUsgaCountryColDfn(columnDfn, "Code", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryCode, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCountry.Column.CountryName: + SetUsgaCountryColDfn(columnDfn, "Name", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + + //----------------------------------------------------------- + // Derived properties. + + //----------------------------------------------------------- + // Common properties. + case SaxGolfUsgaCountry.Column.Notes: + SetUsgaCountryColDfn(columnDfn, "Notes", 240, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Notes); + break; + case SaxGolfUsgaCountry.Column.Flags: + SetUsgaCountryColDfn(columnDfn, "Flags", 60, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Flags, ColumnAlignment.Center, DataValue.DataType.Long); + break; + case SaxGolfUsgaCountry.Column.Status: + SetUsgaCountryColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaCountry.Column.Status_Desc: + SetUsgaCountryColDfn(columnDfn, "Status", 90, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaCountry.Column.Status_Ind: + SetUsgaCountryColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Status, ColumnAlignment.Center, DataValue.DataType.TriState); + columnDfn.TriStateFormat = ColumnTriStateFormat.Lights; + break; + case SaxGolfUsgaCountry.Column.CreateOn_Date: + SetUsgaCountryColDfn(columnDfn, "Created", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CreateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCountry.Column.UpdateOn_Date: + SetUsgaCountryColDfn(columnDfn, "Updated", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_UpdateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + //----------------------------------------------------------- + } + if (!String.IsNullOrEmpty(caption)) + columnDfn.Caption = caption; + if (width > 0) + columnDfn.Width = width; + return columnDfn; + } + + //------------------------------------------------------------------- + // Item query filter. + public override List GetUsgaCountryQueryFilter(SaxGolfUsgaCountry.Params prm) + { + List filter = new List(); + + // Item Ids. + String idsIncluded = prm.IdsIncluded.Concat(","); + if (!idsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Id, aliasUsgaCountry) + " IN (" + idsIncluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Id, aliasUsgaCountry) + " NOT IN (" + idsExcluded + ")"); + + if (!StringUtil.IsBlank(prm.CountryFilter)) + { + // Split filter into words. + List filterWords = prm.CountryFilter.Split((char[])null).ToList(); + filterWords.RemoveDuplicatesCI(); + filterWords.RemoveBlanks(); + foreach (String filterWord in filterWords) + { + List articleFilter = new List(); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryCode, aliasUsgaCountry) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName, aliasUsgaCountry) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + filter.Add(articleFilter.Concat(" OR ", "(", ")")); + } + } + + // Name. + if (!StringUtil.IsEmpty(prm.CountryNameFull)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName, aliasUsgaCountry) + "='" + DbQuery.FormatForCondition(prm.CountryNameFull) + "'"); + if (!StringUtil.IsEmpty(prm.CountryNamePartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName, aliasUsgaCountry) + " LIKE '%" + DbQuery.FormatForLike(prm.CountryNamePartial) + "%'"); + + // Notes. + if (!StringUtil.IsEmpty(prm.NotesPartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Notes, aliasUsgaCountry) + " LIKE '%" + DbQuery.FormatForLike(prm.NotesPartial) + "%'"); + + // Status. + if (prm.StatusCat != SaxGolfUsgaCountry.StatusCat.Any) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Status, aliasUsgaCountry) + GetUsgaCountryStatusCatFilterCondition(prm.StatusCat)); + + if (filter.Count < 1) filter.Add("1=1"); + return filter; + } + internal static String GetUsgaCountryStatusCatFilterCondition(SaxGolfUsgaCountry.StatusCat statusCat) + { + if (statusCat == SaxGolfUsgaCountry.StatusCat.ActiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Active) + "'"; + if (statusCat == SaxGolfUsgaCountry.StatusCat.InactiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Inactive) + "'"; + if (statusCat == SaxGolfUsgaCountry.StatusCat.NotDeleted) + return "!='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + if (statusCat == SaxGolfUsgaCountry.StatusCat.DeletedOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + return ""; + } + // Item sort columns. + public List GetUsgaCountrySortColumns(SaxGolfUsgaCountry.Params prm) + { + // Sort sequence: + List sortColumnNames = new List(); + foreach (var columnDfn in prm.SortColumns) + { + // Need to ensure correct alias used for UsgaCountry columns in case of conflict. + String sortCol = String.Empty; + if (SaxDbDfn_Reference.GetTableForColumn((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn) == SaxDbDfn_Reference.TableIdx.UsgaCountry) + { + sortCol = SaxDbDfn_Reference.GetColumnNameQual((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn, aliasUsgaCountry); + } + else + { + sortCol = columnDfn.DataName; + if (!StringUtil.IsEmpty(columnDfn.SortDataName)) + sortCol = columnDfn.SortDataName; + } + if (!sortCol.IsEmpty()) + { + DbOrderByNullMode orderByNullMode = DbOrderByNullMode.Default; // eSaOrderByDemoteNulls, eSaOrderByPromoteNulls + sortColumnNames.Add(DbQuery.FormatForOrderBy(sortCol, columnDfn.SortAscending, orderByNullMode).Concat(", ")); + } + } + sortColumnNames.RemoveBlanks(); + if (sortColumnNames.IsEmpty()) + { + // Default sort columns. + sortColumnNames.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Id, aliasUsgaCountry) + " ASC"); + } + return sortColumnNames; + } + + //------------------------------------------------------------------- + // Item count. + private long GetUsgaCountryCount(String filter) + { + ClearErrorState(); + return ReferenceDatabase.GetRowCount(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCountry) + " As " + aliasUsgaCountry, filter); + } + public override long GetUsgaCountryCount(SaxGolfUsgaCountry.Params prm) + { + ClearErrorState(); + return GetUsgaCountryCount(GetUsgaCountryQueryFilter(prm).Concat(" AND ", "(", ")")); + } + + //------------------------------------------------------------------- + // Item list. + public override List GetUsgaCountryList(SaxGolfUsgaCountry.Params prm) + { + List userRoles = new List(); + DbQuery qry = new DbQuery(ReferenceDatabase.DbmsType); + qry.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCountry), aliasUsgaCountry); + Golf_UsgaCountry_Db dbUsgaCountry = new Golf_UsgaCountry_Db(ReferenceDbInfo); + qry.Columns.AddRange(dbUsgaCountry.ExistingColumnNames); + qry.Filters.AddRange(GetUsgaCountryQueryFilter(prm)); + qry.OrderBy.AddRange(GetUsgaCountrySortColumns(prm)); + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + dbCommand.CommandText = qry.BuildQuery(prm.ResultsPaging); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + while (dbDataReader.Read()) + { + dbUsgaCountry = new Golf_UsgaCountry_Db(ReferenceDbInfo); + dbUsgaCountry.PopulateFrom(dbDataReader); + userRoles.Add(CreateUsgaCountry(dbUsgaCountry)); + } + } + } + catch (Exception exc) + { + SaLogger.Warn(GetType().Name + ".GetUsgaCountryList\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return userRoles; + } + + //------------------------------------------------------------------- + // Item query execution. + public override DbResultSet ExecuteUsgaCountryQuery(List columns, SaxGolfUsgaCountry.Params prm) + { + ClearErrorState(); + + //--------------------------------------------------------------------- + // Construct query. + DbQuery query = new DbQuery(ReferenceDatabase.DbmsType); + query.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCountry), aliasUsgaCountry); + + // Add columns as defined in query list. + if (columns.HasId(SaxGolfUsgaCountry.Column.Id)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Id, aliasUsgaCountry)); + if (columns.HasId(SaxGolfUsgaCountry.Column.CountryCode)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryCode, aliasUsgaCountry)); + if (columns.HasId(SaxGolfUsgaCountry.Column.CountryName)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName, aliasUsgaCountry)); + // Common properties. + if (columns.HasId(SaxGolfUsgaCountry.Column.Notes)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Notes, aliasUsgaCountry)); + if (columns.HasId(SaxGolfUsgaCountry.Column.Flags)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Flags, aliasUsgaCountry)); + if (columns.HasId(SaxGolfUsgaCountry.Column.Status) || columns.HasId(SaxGolfUsgaCountry.Column.Status_Desc) || columns.HasId(SaxGolfUsgaCountry.Column.Status_Ind)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Status, aliasUsgaCountry)); + if (columns.HasId(SaxGolfUsgaCountry.Column.CreateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CreateOn, aliasUsgaCountry)); + if (columns.HasId(SaxGolfUsgaCountry.Column.UpdateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_UpdateOn, aliasUsgaCountry)); + + //--------------------------------------------------------------------- + // Populate filter. + query.Filters.AddRange(GetUsgaCountryQueryFilter(prm)); + + if (prm.IdsIncluded.Count != 1) + { + // Configure sort sequence. + foreach (String sortColumn in GetUsgaCountrySortColumns(prm)) + query.OrderBy.Add(sortColumn); + } + + //--------------------------------------------------------------------- + //return new DbResultSet_DataTableReader(db, query.BuildQuery(prm.ResultsPaging)); + return DbResultSet_DataReader.ExecuteQuery(ReferenceDatabase, query.BuildQuery(prm.ResultsPaging)); + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaCourse.cs b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaCourse.cs new file mode 100644 index 0000000..d037e4d --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaCourse.cs @@ -0,0 +1,721 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Sarand.Net.Standard.Dbas.Data; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Internal.Reference; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +namespace Saxonite.Net.Standard.Dbas.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr_Dbas + { + //******************************************************************* + // Support Mgr - User Report + //******************************************************************* + // Utilities. + private List GetLogProperties(SaxGolfUsgaCourse usgaCourse) + { + return new List() + { + new StringPair("Id",SysId.ToString(usgaCourse.Id)), + new StringPair("FacilityId",SysId.ToString(usgaCourse.FacilityId)), + new StringPair("CourseId",SysId.ToString(usgaCourse.CourseId)), + new StringPair("Caption ",usgaCourse.Caption), + new StringPair("Status",usgaCourse.StatusCode) + }; + } + + //------------------------------------------------------------------- + // Create item. + public override SaxGolfUsgaCourse CreateUsgaCourse(SysId facilityId) + { + ClearErrorState(); + return new SaxGolfUsgaCourse_Dbas(ReferenceDatabase, null, facilityId, 0); + } + private SaxGolfUsgaCourse_Dbas CreateUsgaCourse(Golf_UsgaCourse_Db dbUsgaCourse) + { + ClearErrorState(); + SaxGolfUsgaCourse_Dbas usgaCourse = new SaxGolfUsgaCourse_Dbas(ReferenceDatabase, new SysId(dbUsgaCourse._Id), new SysId(dbUsgaCourse._FacilityId), (ushort)dbUsgaCourse._Flags); + PopulateFrom(dbUsgaCourse, usgaCourse); + return usgaCourse; + } + + //------------------------------------------------------------------- + // Get item. + public override SaxGolfUsgaCourse GetUsgaCourse(SaxGolfUsgaCourse.Params prm) + { + ClearErrorState(); + return GetUsgaCourse(GetUsgaCourseQueryFilter(prm).Concat(" And ", "(", ")")); + } + private SaxGolfUsgaCourse GetUsgaCourse(String filter) + { + ClearErrorState(); + long count = GetUsgaCourseCount(filter); + if (count == 0) return null; + if (count != 1) + { + SetErrorState("Multiple items found"); + return null; + } + SaxGolfUsgaCourse usgaCourse = null; + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaCourse_Db dbUsgaCourse = new Golf_UsgaCourse_Db(ReferenceDbInfo); + dbUsgaCourse.PopulateFrom(dbCommand, aliasUsgaCourse, filter); + usgaCourse = CreateUsgaCourse(dbUsgaCourse); + } + catch (Exception exc) + { + SetErrorState("Database query exception"); + SaLogger.Warn(GetType().Name + ".GetUsgaCourse\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return usgaCourse; + } + + //------------------------------------------------------------------- + // Validate item. + public override bool IsValidUsgaCourseData(SaxGolfUsgaCourse.Data data, SaxGolfUsgaCourse.ErrField errField) + { + ClearErrorState(); + if (!base.IsValidUsgaCourseData(data, errField)) return false; + return true; + } + + //------------------------------------------------------------------- + // Insert item. + public override bool InsertUsgaCourse(SaxGolfUsgaCourse usgaCourse, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".InsertUsgaCourse"; + ClearErrorState(); + if (!IsValidUsgaCourse(usgaCourse)) return false; + if (SysId.IsValid(usgaCourse.Id)) return SetErrorState(ErrorMessage.ValiditemId); + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaCourse_Db dbUsgaCourse = new Golf_UsgaCourse_Db(ReferenceDbInfo); + PopulateTo(dbUsgaCourse, usgaCourse, dbUpdateInfo); + if (Golf_UsgaCourse_Db.FieldsNonId.Contains("Id")) + { + // Generate next Id. + dbUsgaCourse._Id = ReferenceDatabase.GetNextIdFromTable("UsgaCourse"); + } + dbUsgaCourse.ExecuteInsertCommand(dbCommand); + usgaCourse.Id = new SysId(dbUsgaCourse._Id); + usgaCourse.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Inserted. " + GetLogProperties(usgaCourse).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Update item. + public override bool UpdateUsgaCourse(SaxGolfUsgaCourse usgaCourse, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".UpdateUsgaCourse"; + ClearErrorState(); + if (!IsValidUsgaCourse(usgaCourse)) return false; + if (!SysId.IsValid(usgaCourse.Id)) return SetErrorState(ErrorMessage.InvalidItemId); + if (!usgaCourse.Changed) + { + if (DebugMode) SaLogger.Debug(fn + " Data not changed. " + GetLogProperties(usgaCourse).Concat(": ").Concat("", "\n\t")); + return true; + } + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaCourse_Db dbUsgaCourse = new Golf_UsgaCourse_Db(ReferenceDbInfo); + dbUsgaCourse.PopulateFrom(dbCommand, aliasUsgaCourse, "Id=" + SysId.ToString(usgaCourse.Id)); + // ToDo SaxUpdateLogItemMonitor_UsgaCourse updateLogMonitor = new SaxUpdateLogItemMonitor_UsgaCourse(SessionContext, CreateUsgaCourse(dbUsgaCourse), dbUpdateInfo); + // Update item. + PopulateTo(dbUsgaCourse, usgaCourse, dbUpdateInfo); + dbUsgaCourse.ExecuteUpdateCommand(dbCommand); + usgaCourse.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Updated. " + GetLogProperties(usgaCourse).Concat(": ").Concat("", "\n\t")); + // Record updates. + // ToDo updateLogMonitor.RecordUpdatedValues(usgaCourse); + // ToDo updateLogMonitor.LogUpdates(); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Delete item. + public override bool UsgaCourseCanBeDeleted(SaxGolfUsgaCourse usgaCourse) + { + ClearErrorState(); + if (!base.UsgaCourseCanBeDeleted(usgaCourse)) return false; + return true; + } + public override bool DeleteUsgaCourse(SaxGolfUsgaCourse usgaCourse, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".DeleteUsgaCourse"; + ClearErrorState(); + if (!UsgaCourseCanBeDeleted(usgaCourse)) return false; + + // User Roles are logically deleted by changing the status. + usgaCourse.Status = SaStatus.Deleted; + return UpdateUsgaCourse(usgaCourse, dbUpdateInfo); + + /* + * Physical deletion. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaCourse_Db dbUsgaCourse = new Golf_UsgaCourse_Db(ReferenceDbInfo); + dbUsgaCourse.PopulateFrom(dbCommand, aliasUsgaCourse, "Id=" + usgaCourse.Id.ToString()); + // Delete item. + dbCommand.CommandType = System.Data.CommandType.Text; + dbCommand.CommandText = "DELETE FROM " + SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCourse) + " WHERE Id=" + SysId.ToString(usgaCourse.Id) + ";"; + dbCommand.ExecuteNonQuery(); + usgaCourse.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Deleted. " + GetLogProperties(usgaCourse).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + */ + } + + //------------------------------------------------------------------- + // Copy data properties to and from database. + private void PopulateTo(Golf_UsgaCourse_Db dbUsgaCourse, SaxGolfUsgaCourse usgaCourse, DbUpdateInfo dbUpdateInfo) + { + dbUsgaCourse._Id = SysId.ToLong(usgaCourse.Id); + dbUsgaCourse._FacilityId = SysId.ToInt(usgaCourse.FacilityId); + dbUsgaCourse._CourseId = SysId.ToInt(usgaCourse.CourseId); + dbUsgaCourse._LegacyCrpCourseId = SysId.ToInt(usgaCourse.LegacyCrpCourseId); + dbUsgaCourse._Caption = usgaCourse.Caption; + dbUsgaCourse._CourseName = usgaCourse.CourseName; + dbUsgaCourse._FullName = usgaCourse.FullName; + dbUsgaCourse._Address1 = usgaCourse.Address1; + dbUsgaCourse._Address2 = usgaCourse.Address2; + dbUsgaCourse._City = usgaCourse.City; + dbUsgaCourse._Email = usgaCourse.Email; + dbUsgaCourse._Telephone = usgaCourse.Telephone; + // Common. + dbUsgaCourse._Notes = usgaCourse.Notes; + dbUsgaCourse._Status = SacsSystem.GetStatusCode(usgaCourse.Status); + dbUsgaCourse._Flags = (short)usgaCourse.Flags; + if (!SysId.IsValid(usgaCourse.Id)) + { + dbUsgaCourse._CreateOn = DateTime.Now; + dbUsgaCourse._CreateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaCourse._CreateHost = dbUpdateInfo.Host; + } + dbUsgaCourse._UpdateOn = DateTime.Now; + dbUsgaCourse._UpdateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaCourse._UpdateHost = dbUpdateInfo.Host; + } + private void PopulateFrom(Golf_UsgaCourse_Db dbUsgaCourse, SaxGolfUsgaCourse usgaCourse) + { + //usgaCourse.Id = new SysId(dbUsgaCourse._Id); + usgaCourse.FacilityId = new SysId(dbUsgaCourse._FacilityId); + usgaCourse.CourseId = new SysId(dbUsgaCourse._CourseId); + usgaCourse.LegacyCrpCourseId = new SysId(dbUsgaCourse._LegacyCrpCourseId); + usgaCourse.Caption = dbUsgaCourse._Caption; + usgaCourse.CourseName = dbUsgaCourse._CourseName; + usgaCourse.FullName = dbUsgaCourse._FullName; + usgaCourse.Address1 = dbUsgaCourse._Address1; + usgaCourse.Address2 = dbUsgaCourse._Address2; + usgaCourse.City = dbUsgaCourse._City; + usgaCourse.Email = dbUsgaCourse._Email; + usgaCourse.Telephone = dbUsgaCourse._Telephone; + // Common. + usgaCourse.Notes = dbUsgaCourse._Notes; + usgaCourse.Status = SacsSystem.GetStatusForCode(dbUsgaCourse._Status); + usgaCourse.SetCreateStamp(dbUsgaCourse._CreateOn, new SysId(dbUsgaCourse._CreateBy), dbUsgaCourse._CreateHost); + usgaCourse.SetUpdateStamp(dbUsgaCourse._UpdateOn, new SysId(dbUsgaCourse._UpdateBy), dbUsgaCourse._UpdateHost); + usgaCourse.AcceptChanges(); + } + + //------------------------------------------------------------------- + // Bulk updates. + /// + /// Bulk update USGA Courses. + /// - Facility Id must be supplied to identify parent. + /// - Course Id must be supplied to act as identifier. + /// - Other properties are validated as per course rules - check error state. + /// - Other properties are left as is if null. + /// + public override bool BulkUpdateUsgaCourses(List courses, DbUpdateInfo dbUpdateInfo) + { + ClearErrorState(); + List coursesToUpdate = new List(); + + // Validate supplied data. + foreach (UsgaCourseData course in courses) + { + // Validate course properties. + // Facility and Course Codes are mandatory, other values only validated if non-null. + if (!SysId.IsValid(course.FacilityId)) return SetErrorState("Facility Id must be supplied"); + if (!SysId.IsValid(course.CourseId)) return SetErrorState("Course Id must be supplied"); + if (course.Caption != null && !IsValidValue(course.Caption, "caption", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Caption), true)) return false; + if (course.CourseName != null && !IsValidValue(course.CourseName, "name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName))) return false; + if (course.FullName != null && !IsValidValue(course.FullName, "full name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FullName))) return false; + if (course.Address1 != null && !IsValidValue(course.Address1, "address 1", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address1))) return false; + if (course.Address2 != null && !IsValidValue(course.Address2, "address 2", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address2))) return false; + if (course.City != null && !IsValidValue(course.City, "city", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_City))) return false; + if (course.Email != null && !IsValidValue(course.Email, "email", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Email))) return false; + if (course.Telephone != null && !IsValidValue(course.Telephone, "telephone", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Telephone))) return false; + coursesToUpdate.Add(course); + } + int MaxBulkUpdateBatchSize = 64; + int batchSize = coursesToUpdate.Any() ? (int)Math.Ceiling(coursesToUpdate.Count() / Math.Ceiling((double)coursesToUpdate.Count() / MaxBulkUpdateBatchSize)) : MaxBulkUpdateBatchSize; + while (coursesToUpdate.Any()) + { + List query = new List(); + query.Add($"Declare @statusActive VarChar(3) = '{SacsSystem.GetStatusCode(SaxGolfUsgaCourse.DefaultStatus)}';"); + query.Add($"Declare @updateOn DateTime = GetUtcDate();"); + query.Add($"Declare @updateBy Int = {SysId.ToLong(dbUpdateInfo.UserId)};"); + query.Add($"Declare @updateHost VarChar(100) = '{DbQuery.FormatForCondition(dbUpdateInfo.Host)}';"); + query.Add("Merge"); + query.Add($"Into {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCourse)} uCrs"); + query.Add("Using"); + query.Add("("); + query.Add("Select dFty.Id FacilityId, dCrs.CourseId, dCrs.LegacyCrpCourseId, dCrs.Caption, dCrs.CourseName, dCrs.FullName, dCrs.Address1, dCrs.Address2, dCrs.City, dCrs.Email, dCrs.Telephone"); + query.Add("From"); + query.Add("("); + query.Add("Select 0 FacilityId, 0 CourseId, 0 LegacyCrpCourseId, '' Caption, '' CourseName, '' FullName, '' Address1, '' Address2, '' City, '' Email, '' Telephone"); + foreach (UsgaCourseData course in coursesToUpdate.ExtractRange(0, batchSize)) + query.Add($"Union Select {course.FacilityId}, {course.CourseId}, " + + (SysId.IsValid(course.LegacyCrpCourseId) ? $"{course.LegacyCrpCourseId}" : "Null") + "," + + (course.Caption != null ? $"'{DbQuery.FormatForCondition(course.Caption)}'" : "Null") + "," + + (course.CourseName != null ? $"'{DbQuery.FormatForCondition(course.CourseName)}'" : "Null") + "," + + (course.FullName != null ? $"'{DbQuery.FormatForCondition(course.FullName)}'" : "Null") + "," + + (course.Address1 != null ? $"'{DbQuery.FormatForCondition(course.Address1)}'" : "Null") + "," + + (course.Address2 != null ? $"'{DbQuery.FormatForCondition(course.Address2)}'" : "Null") + "," + + (course.City != null ? $"'{DbQuery.FormatForCondition(course.City)}'" : "Null") + "," + + (course.Email != null ? $"'{DbQuery.FormatForCondition(course.Email)}'" : "Null") + "," + + (course.Telephone != null ? $"'{DbQuery.FormatForCondition(course.Telephone)}'" : "Null")); + query.Add(") dCrs"); + query.Add($"Inner Join {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaFacility)} dFty On dFty.FacilityId=dCrs.FacilityId"); + query.Add(") dCrs"); + query.Add("On uCrs.FacilityId=dCrs.FacilityId And uCrs.CourseId=dCrs.CourseId"); + query.Add("When Matched And ((dCrs.LegacyCrpCourseId Is Not Null And uCrs.LegacyCrpCourseId!=dCrs.LegacyCrpCourseId) Or (dCrs.Caption Is Not Null And uCrs.Caption!=dCrs.Caption) Or (dCrs.CourseName Is Not Null And uCrs.CourseName!=dCrs.CourseName) Or (dCrs.FullName Is Not Null And uCrs.FullName!=dCrs.FullName) Or (dCrs.Address1 Is Not Null And uCrs.Address1!=dCrs.Address1) Or (dCrs.Address2 Is Not Null And uCrs.Address2!=dCrs.Address2) Or (dCrs.City Is Not Null And uCrs.City!=dCrs.City) Or (dCrs.Email Is Not Null And uCrs.Email!=dCrs.Email) Or (dCrs.Telephone Is Not Null And uCrs.Telephone!=dCrs.Telephone) Or uCrs.Status!=@statusActive)"); + query.Add("Then Update Set"); + query.Add(" LegacyCrpCourseId=Coalesce(dCrs.LegacyCrpCourseId,uCrs.LegacyCrpCourseId),"); + query.Add(" Caption=Coalesce(dCrs.Caption,uCrs.Caption),"); + query.Add(" CourseName=Coalesce(dCrs.CourseName,uCrs.CourseName),"); + query.Add(" FullName=Coalesce(dCrs.FullName,uCrs.FullName),"); + query.Add(" Address1=Coalesce(dCrs.Address1,uCrs.Address1),"); + query.Add(" Address2=Coalesce(dCrs.Address2,uCrs.Address2),"); + query.Add(" City=Coalesce(dCrs.City,uCrs.City),"); + query.Add(" Email=Coalesce(dCrs.Email,uCrs.Email),"); + query.Add(" Telephone=Coalesce(dCrs.Telephone,uCrs.Telephone),"); + query.Add(" Status=@statusActive,"); + query.Add(" UpdateOn=@updateOn,"); + query.Add(" UpdateBy=@updateBy,"); + query.Add(" UpdateHost=@updateHost"); + query.Add("When Not Matched And Len(Coalesce(dCrs.Caption,''))>0"); + query.Add("Then Insert (FacilityId,CourseId,LegacyCrpCourseId,Caption,CourseName,FullName,Address1,Address2,City,Email,Telephone,Notes,Flags,Status,CreateOn,CreateBy,CreateHost,UpdateOn,UpdateBy,UpdateHost)"); + query.Add($"Values (dCrs.FacilityId,dCrs.CourseId,Coalesce(dCrs.LegacyCrpCourseId,0),dCrs.Caption,Coalesce(dCrs.CourseName,''),Coalesce(dCrs.FullName,''),Coalesce(dCrs.Address1,''),Coalesce(dCrs.Address2,''),Coalesce(dCrs.City,''),Coalesce(dCrs.Email,''),Coalesce(dCrs.Telephone,''),'',0,@statusActive,@updateOn,@updateBy,@updateHost,@updateOn,@updateBy,@updateHost)"); + query.Add(";"); + //SaLogger.Info($"{SysUtil.Fn} Bulk USGA Course update query:\n\t{query.Concat("\n\t")}"); + + try + { + int result = ReferenceDatabase.ExecuteNonQuery(query.Concat("\n")); + if (ReferenceDatabase.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error executing bulk USGA Course update - {ReferenceDatabase.ErrorStateMessage}"); + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, " executing bulk USGA Course update")); + } + } + return HasErrorState(); + } + + //------------------------------------------------------------------- + // Item column definitions. + private static readonly String aliasUsgaCourse = "UsgCrs"; + private static readonly String aliasUsgaCourse_Facility = "UsgCrs_Cty"; + private static readonly String prefixUsgaCourse_Facility = aliasUsgaCourse_Facility + "_"; + private void SetUsgaCourseColDfn + (ColumnDfn col, String caption, int width, SaxDbDfn_Reference.ColumnIdx dbCol, + ColumnAlignment align = ColumnAlignment.Default, DataValue.DataType dataType = DataValue.DataType.String, + String alias = "", String prefix = "") + { + if (String.IsNullOrEmpty(alias) && SaxDbDfn_Reference.GetTableForColumn(dbCol) == SaxDbDfn_Reference.TableIdx.UsgaCourse) + alias = aliasUsgaCourse; + col.Set(caption, width, (int)dbCol, prefix + SaxDbDfn_Reference.GetColumnName(dbCol, false), SaxDbDfn_Reference.GetColumnNameQual(dbCol, alias), dataType, align); + if (dataType == DataValue.DataType.String && dbCol != SaxDbDfn_Reference.ColumnIdx.Unknown) + col.MaxLength = (int)SaxDbDfn_Reference.GetColTextLen(dbCol); + } + public override ColumnDfn GetUsgaCourseColumnDfn(SaxGolfUsgaCourse.Column columnId, string caption = "", int width = 0) + { + ColumnDfn columnDfn = new ColumnDfn((int)columnId, caption, width); + switch (columnId) + { + //----------------------------------------------------------- + case SaxGolfUsgaCourse.Column.Pos: + SetUsgaCourseColDfn(columnDfn, "Pos", 60, SaxDbDfn_Reference.ColumnIdx.Unknown, ColumnAlignment.Right); + columnDfn.SortMode = ColumnDfn.ColumnSortMode.Off; + columnDfn.ReadOnly = true; + columnDfn.Resizable = false; + break; + case SaxGolfUsgaCourse.Column.Id: + SetUsgaCourseColDfn(columnDfn, "Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Id, ColumnAlignment.Right, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaCourse.Column.FacilityId: + SetUsgaCourseColDfn(columnDfn, "Facility #", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FacilityId, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.Facility_Name: + SetUsgaCourseColDfn(columnDfn, "Facility", 120, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName, ColumnAlignment.Center, DataValue.DataType.String, aliasUsgaCourse_Facility, prefixUsgaCourse_Facility); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaCourse.Column.CourseId: + SetUsgaCourseColDfn(columnDfn, "Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseId, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.LegacyCrpCourseId: + SetUsgaCourseColDfn(columnDfn, "CRP Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_LegacyCrpCourseId, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.CourseName: + SetUsgaCourseColDfn(columnDfn, "Name", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.FullName: + SetUsgaCourseColDfn(columnDfn, "Full Name", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FullName, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.Address1: + SetUsgaCourseColDfn(columnDfn, "Address 1", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address1, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.Address2: + SetUsgaCourseColDfn(columnDfn, "Address 2", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address2, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.City: + SetUsgaCourseColDfn(columnDfn, "City", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_City, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.Email: + SetUsgaCourseColDfn(columnDfn, "Email", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Email, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.Telephone: + SetUsgaCourseColDfn(columnDfn, "Telephone", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Telephone, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + + //----------------------------------------------------------- + // Derived properties. + + //----------------------------------------------------------- + // Common properties. + case SaxGolfUsgaCourse.Column.Notes: + SetUsgaCourseColDfn(columnDfn, "Notes", 240, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Notes); + break; + case SaxGolfUsgaCourse.Column.Flags: + SetUsgaCourseColDfn(columnDfn, "Flags", 60, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Flags, ColumnAlignment.Center, DataValue.DataType.Long); + break; + case SaxGolfUsgaCourse.Column.Status: + SetUsgaCourseColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaCourse.Column.Status_Desc: + SetUsgaCourseColDfn(columnDfn, "Status", 90, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaCourse.Column.Status_Ind: + SetUsgaCourseColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Status, ColumnAlignment.Center, DataValue.DataType.TriState); + columnDfn.TriStateFormat = ColumnTriStateFormat.Lights; + break; + case SaxGolfUsgaCourse.Column.CreateOn_Date: + SetUsgaCourseColDfn(columnDfn, "Created", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CreateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaCourse.Column.UpdateOn_Date: + SetUsgaCourseColDfn(columnDfn, "Updated", 80, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_UpdateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + //----------------------------------------------------------- + } + if (!String.IsNullOrEmpty(caption)) + columnDfn.Caption = caption; + if (width > 0) + columnDfn.Width = width; + return columnDfn; + } + + //------------------------------------------------------------------- + // Item query filter. + public override List GetUsgaCourseQueryFilter(SaxGolfUsgaCourse.Params prm) + { + List filter = new List(); + + // Item Ids. + String idsIncluded = prm.IdsIncluded.Concat(","); + if (!idsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Id, aliasUsgaCourse) + " IN (" + idsIncluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Id, aliasUsgaCourse) + " NOT IN (" + idsExcluded + ")"); + + // Provinces. + String provinceIdsIncluded = prm.ProvinceIdsIncluded.Concat(","); + if (!provinceIdsIncluded.IsEmpty()) + { + if (StringUtil.IsBlank(prm.Alias_Province)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FacilityId, aliasUsgaCourse) + " IN (SELECT Id FROM " + SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaFacility) + " WHERE ProvinceId IN (" + provinceIdsIncluded + "))"); + else + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Id, prm.Alias_Province) + " IN (" + provinceIdsIncluded + ")"); + } + + // Facilities. + String facilityIdsIncluded = prm.FacilityIdsIncluded.Concat(","); + if (!facilityIdsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FacilityId, aliasUsgaCourse) + " IN (" + facilityIdsIncluded + ")"); + + if (!StringUtil.IsBlank(prm.CourseFilter)) + { + // Split filter into words. + List filterWords = prm.CourseFilter.Split((char[])null).ToList(); + filterWords.RemoveDuplicatesCI(); + filterWords.RemoveBlanks(); + foreach (String filterWord in filterWords) + { + List articleFilter = new List(); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName, aliasUsgaCourse) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FullName, aliasUsgaCourse) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address1, aliasUsgaCourse) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address2, aliasUsgaCourse) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_City, aliasUsgaCourse) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + filter.Add(articleFilter.Concat(" OR ", "(", ")")); + } + } + + // Name. + if (!StringUtil.IsEmpty(prm.CourseNameFull)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName, aliasUsgaCourse) + "='" + DbQuery.FormatForCondition(prm.CourseNameFull) + "'"); + if (!StringUtil.IsEmpty(prm.CourseNamePartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName, aliasUsgaCourse) + " LIKE '%" + DbQuery.FormatForLike(prm.CourseNamePartial) + "%'"); + + // Notes. + if (!StringUtil.IsEmpty(prm.NotesPartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Notes, aliasUsgaCourse) + " LIKE '%" + DbQuery.FormatForLike(prm.NotesPartial) + "%'"); + + // Status. + if (prm.StatusCat != SaxGolfUsgaCourse.StatusCat.Any) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Status, aliasUsgaCourse) + GetUsgaCourseStatusCatFilterCondition(prm.StatusCat)); + + if (filter.Count < 1) filter.Add("1=1"); + return filter; + } + internal static String GetUsgaCourseStatusCatFilterCondition(SaxGolfUsgaCourse.StatusCat statusCat) + { + if (statusCat == SaxGolfUsgaCourse.StatusCat.ActiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Active) + "'"; + if (statusCat == SaxGolfUsgaCourse.StatusCat.InactiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Inactive) + "'"; + if (statusCat == SaxGolfUsgaCourse.StatusCat.NotDeleted) + return "!='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + if (statusCat == SaxGolfUsgaCourse.StatusCat.DeletedOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + return ""; + } + // Item sort columns. + public List GetUsgaCourseSortColumns(SaxGolfUsgaCourse.Params prm) + { + // Sort sequence: + List sortColumnNames = new List(); + foreach (var columnDfn in prm.SortColumns) + { + // Need to ensure correct alias used for UsgaCourse columns in case of conflict. + String sortCol = String.Empty; + if (SaxDbDfn_Reference.GetTableForColumn((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn) == SaxDbDfn_Reference.TableIdx.UsgaCourse) + { + sortCol = SaxDbDfn_Reference.GetColumnNameQual((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn, aliasUsgaCourse); + } + else + { + sortCol = columnDfn.DataName; + if (!StringUtil.IsEmpty(columnDfn.SortDataName)) + sortCol = columnDfn.SortDataName; + } + if (!sortCol.IsEmpty()) + { + DbOrderByNullMode orderByNullMode = DbOrderByNullMode.Default; // eSaOrderByDemoteNulls, eSaOrderByPromoteNulls + sortColumnNames.Add(DbQuery.FormatForOrderBy(sortCol, columnDfn.SortAscending, orderByNullMode).Concat(", ")); + } + } + sortColumnNames.RemoveBlanks(); + if (sortColumnNames.IsEmpty()) + { + // Default sort columns. + sortColumnNames.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Id, aliasUsgaCourse) + " ASC"); + } + return sortColumnNames; + } + + //------------------------------------------------------------------- + // Item count. + private long GetUsgaCourseCount(String filter) + { + ClearErrorState(); + return ReferenceDatabase.GetRowCount(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCourse) + " As " + aliasUsgaCourse, filter); + } + public override long GetUsgaCourseCount(SaxGolfUsgaCourse.Params prm) + { + ClearErrorState(); + return GetUsgaCourseCount(GetUsgaCourseQueryFilter(prm).Concat(" AND ", "(", ")")); + } + + //------------------------------------------------------------------- + // Item list. + public override List GetUsgaCourseList(SaxGolfUsgaCourse.Params prm) + { + List userRoles = new List(); + DbQuery qry = new DbQuery(ReferenceDatabase.DbmsType); + qry.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCourse), aliasUsgaCourse); + Golf_UsgaCourse_Db dbUsgaCourse = new Golf_UsgaCourse_Db(ReferenceDbInfo); + qry.Columns.AddRange(dbUsgaCourse.ExistingColumnNames); + qry.Filters.AddRange(GetUsgaCourseQueryFilter(prm)); + qry.OrderBy.AddRange(GetUsgaCourseSortColumns(prm)); + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + dbCommand.CommandText = qry.BuildQuery(prm.ResultsPaging); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + while (dbDataReader.Read()) + { + dbUsgaCourse = new Golf_UsgaCourse_Db(ReferenceDbInfo); + dbUsgaCourse.PopulateFrom(dbDataReader); + userRoles.Add(CreateUsgaCourse(dbUsgaCourse)); + } + } + } + catch (Exception exc) + { + SaLogger.Warn(GetType().Name + ".GetUsgaCourseList\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return userRoles; + } + + //------------------------------------------------------------------- + // Item query execution. + public override DbResultSet ExecuteUsgaCourseQuery(List columns, SaxGolfUsgaCourse.Params prm) + { + ClearErrorState(); + + //--------------------------------------------------------------------- + // Construct query. + DbQuery query = new DbQuery(ReferenceDatabase.DbmsType); + query.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCourse), aliasUsgaCourse); + + // Add columns as defined in query list. + if (columns.HasId(SaxGolfUsgaCourse.Column.Id)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Id, aliasUsgaCourse)); + bool hasFacilityCols = (columns.HasId(SaxGolfUsgaCourse.Column.Facility_Name)); + if (columns.HasId(SaxGolfUsgaCourse.Column.FacilityId) || hasFacilityCols) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FacilityId, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.CourseId)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseId, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.LegacyCrpCourseId)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_LegacyCrpCourseId, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.CourseName)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.FullName)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FullName, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.Address1)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address1, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.Address2)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Address2, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.City)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_City, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.Email)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Email, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.Telephone)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Telephone, aliasUsgaCourse)); + // Common properties. + if (columns.HasId(SaxGolfUsgaCourse.Column.Notes)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Notes, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.Flags)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Flags, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.Status) || columns.HasId(SaxGolfUsgaCourse.Column.Status_Desc) || columns.HasId(SaxGolfUsgaCourse.Column.Status_Ind)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Status, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.CreateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CreateOn, aliasUsgaCourse)); + if (columns.HasId(SaxGolfUsgaCourse.Column.UpdateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_UpdateOn, aliasUsgaCourse)); + + //--------------------------------------------------------------------- + // Facility. + if (hasFacilityCols) + { + DbQueryJoin joinFacility = new DbQueryJoin(DbJoinType.LeftOuter); + joinFacility.Table = new StringPair(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaFacility), aliasUsgaCourse_Facility); + joinFacility.Filters.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Id, aliasUsgaCourse_Facility) + "=" + SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_FacilityId, aliasUsgaCourse)); + query.Joins.Add(joinFacility); + List cols = new List(); + cols.Add(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName); + foreach (var col in cols) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(col, aliasUsgaCourse_Facility), prefixUsgaCourse_Facility + SaxDbDfn_Reference.GetColumnName(col, false)); + prm.Alias_Facility = aliasUsgaCourse_Facility; + } + + //--------------------------------------------------------------------- + // Populate filter. + query.Filters.AddRange(GetUsgaCourseQueryFilter(prm)); + + if (prm.IdsIncluded.Count != 1) + { + // Configure sort sequence. + foreach (String sortColumn in GetUsgaCourseSortColumns(prm)) + query.OrderBy.Add(sortColumn); + } + + //--------------------------------------------------------------------- + //return new DbResultSet_DataTableReader(db, query.BuildQuery(prm.ResultsPaging)); + return DbResultSet_DataReader.ExecuteQuery(ReferenceDatabase, query.BuildQuery(prm.ResultsPaging)); + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaFacility.cs b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaFacility.cs new file mode 100644 index 0000000..3cad375 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaFacility.cs @@ -0,0 +1,625 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Sarand.Net.Standard.Dbas.Data; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Internal.Reference; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +namespace Saxonite.Net.Standard.Dbas.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr_Dbas + { + //******************************************************************* + // Support Mgr - User Report + //******************************************************************* + // Utilities. + private List GetLogProperties(SaxGolfUsgaFacility usgaFacility) + { + return new List() + { + new StringPair("Id",SysId.ToString(usgaFacility.Id)), + new StringPair("ProvinceId",SysId.ToString(usgaFacility.ProvinceId)), + new StringPair("FacilityId",SysId.ToString(usgaFacility.FacilityId)), + new StringPair("FacilityName",usgaFacility.FacilityName), + new StringPair("Status",usgaFacility.StatusCode) + }; + } + + //------------------------------------------------------------------- + // Create item. + public override SaxGolfUsgaFacility CreateUsgaFacility(SysId usgaProvinceId) + { + ClearErrorState(); + return new SaxGolfUsgaFacility_Dbas(ReferenceDatabase, null, usgaProvinceId, 0); + } + private SaxGolfUsgaFacility_Dbas CreateUsgaFacility(Golf_UsgaFacility_Db dbUsgaFacility) + { + ClearErrorState(); + SaxGolfUsgaFacility_Dbas usgaFacility = new SaxGolfUsgaFacility_Dbas(ReferenceDatabase, new SysId(dbUsgaFacility._Id), new SysId(dbUsgaFacility._ProvinceId), (ushort)dbUsgaFacility._Flags); + PopulateFrom(dbUsgaFacility, usgaFacility); + return usgaFacility; + } + + //------------------------------------------------------------------- + // Get item. + public override SaxGolfUsgaFacility GetUsgaFacility(SaxGolfUsgaFacility.Params prm) + { + ClearErrorState(); + return GetUsgaFacility(GetUsgaFacilityQueryFilter(prm).Concat(" And ", "(", ")")); + } + private SaxGolfUsgaFacility GetUsgaFacility(String filter) + { + ClearErrorState(); + long count = GetUsgaFacilityCount(filter); + if (count == 0) return null; + if (count != 1) + { + SetErrorState("Multiple items found"); + return null; + } + SaxGolfUsgaFacility usgaFacility = null; + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaFacility_Db dbUsgaFacility = new Golf_UsgaFacility_Db(ReferenceDbInfo); + dbUsgaFacility.PopulateFrom(dbCommand, aliasUsgaFacility, filter); + usgaFacility = CreateUsgaFacility(dbUsgaFacility); + } + catch (Exception exc) + { + SetErrorState("Database query exception"); + SaLogger.Warn(GetType().Name + ".GetUsgaFacility\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return usgaFacility; + } + + //------------------------------------------------------------------- + // Validate item. + public override bool IsValidUsgaFacilityData(SaxGolfUsgaFacility.Data data, SaxGolfUsgaFacility.ErrField errField) + { + ClearErrorState(); + if (!base.IsValidUsgaFacilityData(data, errField)) return false; + return true; + } + + //------------------------------------------------------------------- + // Insert item. + public override bool InsertUsgaFacility(SaxGolfUsgaFacility usgaFacility, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".InsertUsgaFacility"; + ClearErrorState(); + if (!IsValidUsgaFacility(usgaFacility)) return false; + if (SysId.IsValid(usgaFacility.Id)) return SetErrorState(ErrorMessage.ValiditemId); + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaFacility_Db dbUsgaFacility = new Golf_UsgaFacility_Db(ReferenceDbInfo); + PopulateTo(dbUsgaFacility, usgaFacility, dbUpdateInfo); + if (Golf_UsgaFacility_Db.FieldsNonId.Contains("Id")) + { + // Generate next Id. + dbUsgaFacility._Id = ReferenceDatabase.GetNextIdFromTable("UsgaFacility"); + } + dbUsgaFacility.ExecuteInsertCommand(dbCommand); + usgaFacility.Id = new SysId(dbUsgaFacility._Id); + usgaFacility.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Inserted. " + GetLogProperties(usgaFacility).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Update item. + public override bool UpdateUsgaFacility(SaxGolfUsgaFacility usgaFacility, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".UpdateUsgaFacility"; + ClearErrorState(); + if (!IsValidUsgaFacility(usgaFacility)) return false; + if (!SysId.IsValid(usgaFacility.Id)) return SetErrorState(ErrorMessage.InvalidItemId); + if (!usgaFacility.Changed) + { + if (DebugMode) SaLogger.Debug(fn + " Data not changed. " + GetLogProperties(usgaFacility).Concat(": ").Concat("", "\n\t")); + return true; + } + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaFacility_Db dbUsgaFacility = new Golf_UsgaFacility_Db(ReferenceDbInfo); + dbUsgaFacility.PopulateFrom(dbCommand, aliasUsgaFacility, "Id=" + SysId.ToString(usgaFacility.Id)); + // ToDo SaxUpdateLogItemMonitor_UsgaFacility updateLogMonitor = new SaxUpdateLogItemMonitor_UsgaFacility(SessionContext, CreateUsgaFacility(dbUsgaFacility), dbUpdateInfo); + // Update item. + PopulateTo(dbUsgaFacility, usgaFacility, dbUpdateInfo); + dbUsgaFacility.ExecuteUpdateCommand(dbCommand); + usgaFacility.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Updated. " + GetLogProperties(usgaFacility).Concat(": ").Concat("", "\n\t")); + // Record updates. + // ToDo updateLogMonitor.RecordUpdatedValues(usgaFacility); + // ToDo updateLogMonitor.LogUpdates(); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Delete item. + public override bool UsgaFacilityCanBeDeleted(SaxGolfUsgaFacility usgaFacility) + { + ClearErrorState(); + if (!base.UsgaFacilityCanBeDeleted(usgaFacility)) return false; + return true; + } + public override bool DeleteUsgaFacility(SaxGolfUsgaFacility usgaFacility, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".DeleteUsgaFacility"; + ClearErrorState(); + if (!UsgaFacilityCanBeDeleted(usgaFacility)) return false; + + // User Roles are logically deleted by changing the status. + usgaFacility.Status = SaStatus.Deleted; + return UpdateUsgaFacility(usgaFacility, dbUpdateInfo); + + /* + * Physical deletion. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaFacility_Db dbUsgaFacility = new Golf_UsgaFacility_Db(ReferenceDbInfo); + dbUsgaFacility.PopulateFrom(dbCommand, aliasUsgaFacility, "Id=" + usgaFacility.Id.ToString()); + // Delete item. + dbCommand.CommandType = System.Data.CommandType.Text; + dbCommand.CommandText = "DELETE FROM " + SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaFacility) + " WHERE Id=" + SysId.ToString(usgaFacility.Id) + ";"; + dbCommand.ExecuteNonQuery(); + usgaFacility.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Deleted. " + GetLogProperties(usgaFacility).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + */ + } + + //------------------------------------------------------------------- + // Copy data properties to and from database. + private void PopulateTo(Golf_UsgaFacility_Db dbUsgaFacility, SaxGolfUsgaFacility usgaFacility, DbUpdateInfo dbUpdateInfo) + { + dbUsgaFacility._Id = SysId.ToLong(usgaFacility.Id); + dbUsgaFacility._ProvinceId = SysId.ToInt(usgaFacility.ProvinceId); + dbUsgaFacility._FacilityId = SysId.ToLong(usgaFacility.FacilityId); + dbUsgaFacility._FacilityName = usgaFacility.FacilityName; + // Common. + dbUsgaFacility._Notes = usgaFacility.Notes; + dbUsgaFacility._Status = SacsSystem.GetStatusCode(usgaFacility.Status); + dbUsgaFacility._Flags = (short)usgaFacility.Flags; + if (!SysId.IsValid(usgaFacility.Id)) + { + dbUsgaFacility._CreateOn = DateTime.Now; + dbUsgaFacility._CreateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaFacility._CreateHost = dbUpdateInfo.Host; + } + dbUsgaFacility._UpdateOn = DateTime.Now; + dbUsgaFacility._UpdateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaFacility._UpdateHost = dbUpdateInfo.Host; + } + private void PopulateFrom(Golf_UsgaFacility_Db dbUsgaFacility, SaxGolfUsgaFacility usgaFacility) + { + //usgaFacility.Id = new SysId(dbUsgaFacility._Id); + usgaFacility.ProvinceId = new SysId(dbUsgaFacility._ProvinceId); + usgaFacility.FacilityId = new SysId(dbUsgaFacility._FacilityId); + usgaFacility.FacilityName = dbUsgaFacility._FacilityName; + // Common. + usgaFacility.Notes = dbUsgaFacility._Notes; + usgaFacility.Status = SacsSystem.GetStatusForCode(dbUsgaFacility._Status); + usgaFacility.SetCreateStamp(dbUsgaFacility._CreateOn, new SysId(dbUsgaFacility._CreateBy), dbUsgaFacility._CreateHost); + usgaFacility.SetUpdateStamp(dbUsgaFacility._UpdateOn, new SysId(dbUsgaFacility._UpdateBy), dbUsgaFacility._UpdateHost); + usgaFacility.AcceptChanges(); + } + + //------------------------------------------------------------------- + // Bulk updates. + /// + /// Bulk update USGA Facilities. + /// - Province code must be supplied to identify parent. + /// - Facility Id must be supplied to act as identifier. + /// - Other properties are validated as per facility rules - check error state. + /// - Other properties are left as is if null. + /// + public override bool BulkUpdateUsgaFacilities(List facilities, DbUpdateInfo dbUpdateInfo) + { + ClearErrorState(); + List facilitiesToUpdate = new List(); + + // Validate supplied data. + foreach (UsgaFacilityData facility in facilities) + { + // Validate facility properties. + // Province and Facility Codes are mandatory, other values only validated if non-null. + if (!IsValidValue(facility.ProvinceCode, "province", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceCode), true)) return false; + if (!SysId.IsValid(facility.FacilityId)) return SetErrorState("Facility Id must be supplied"); + if (facility.FacilityName != null && !IsValidValue(facility.FacilityName, "name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName))) return false; + facilitiesToUpdate.Add(facility); + } + int MaxBulkUpdateBatchSize = 64; + int batchSize = facilitiesToUpdate.Any() ? (int)Math.Ceiling(facilitiesToUpdate.Count() / Math.Ceiling((double)facilitiesToUpdate.Count() / MaxBulkUpdateBatchSize)) : MaxBulkUpdateBatchSize; + while (facilitiesToUpdate.Any()) + { + List query = new List(); + query.Add($"Declare @statusActive VarChar(3) = '{SacsSystem.GetStatusCode(SaxGolfUsgaFacility.DefaultStatus)}';"); + query.Add($"Declare @updateOn DateTime = GetUtcDate();"); + query.Add($"Declare @updateBy Int = {SysId.ToLong(dbUpdateInfo.UserId)};"); + query.Add($"Declare @updateHost VarChar(100) = '{DbQuery.FormatForCondition(dbUpdateInfo.Host)}';"); + query.Add("Merge"); + query.Add($"Into {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaFacility)} uFty"); + query.Add("Using"); + query.Add("("); + query.Add("Select dPrv.Id ProvinceId, dFty.ProvinceCode, dFty.FacilityId, dFty.FacilityName"); + query.Add("From"); + query.Add("("); + query.Add("Select '' ProvinceCode, '' FacilityId, '' FacilityName"); + foreach (UsgaFacilityData facility in facilitiesToUpdate.ExtractRange(0, batchSize)) + query.Add($"Union Select '{DbQuery.FormatForCondition(facility.ProvinceCode)}', {SysId.ToString(facility.FacilityId)}, " + (facility.FacilityName != null ? $"'{DbQuery.FormatForCondition(facility.FacilityName)}'" : "Null")); + query.Add(") dFty"); + query.Add($"Inner Join {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaProvince)} dPrv On dPrv.ProvinceCode=dFty.ProvinceCode"); + query.Add(") dFty"); + query.Add("On uFty.ProvinceId=dFty.ProvinceId And uFty.FacilityId=dFty.FacilityId"); + query.Add("When Matched And ((dFty.FacilityName Is Not Null And uFty.FacilityName!=dFty.FacilityName) Or uFty.Status!=@statusActive)"); + query.Add("Then Update Set"); + query.Add(" FacilityName=Coalesce(dFty.FacilityName,uFty.FacilityName),"); + query.Add(" Status=@statusActive,"); + query.Add(" UpdateOn=@updateOn,"); + query.Add(" UpdateBy=@updateBy,"); + query.Add(" UpdateHost=@updateHost"); + query.Add("When Not Matched And Len(IsNull(dFty.FacilityName,''))>0"); + query.Add("Then Insert (ProvinceId,FacilityId,FacilityName,Notes,Flags,Status,CreateOn,CreateBy,CreateHost,UpdateOn,UpdateBy,UpdateHost)"); + query.Add($"Values (dFty.ProvinceId,dFty.FacilityId,dFty.FacilityName,'',0,@statusActive,@updateOn,@updateBy,@updateHost,@updateOn,@updateBy,@updateHost)"); + query.Add(";"); + //SaLogger.Info($"{SysUtil.Fn} Bulk USGA Facility update query:\n\t{query.Concat("\n\t")}"); + + try + { + int result = ReferenceDatabase.ExecuteNonQuery(query.Concat("\n")); + if (ReferenceDatabase.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error executing bulk USGA Facility update - {ReferenceDatabase.ErrorStateMessage}"); + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, " executing bulk USGA Facility update")); + } + } + return HasErrorState(); + } + + //------------------------------------------------------------------- + // Item column definitions. + private static readonly String aliasUsgaFacility = "UsgFty"; + private static readonly String aliasUsgaFacility_Province = "UsgFty_Prv"; + private static readonly String prefixUsgaFacility_Province = aliasUsgaFacility_Province + "_"; + private void SetUsgaFacilityColDfn + (ColumnDfn col, String caption, int width, SaxDbDfn_Reference.ColumnIdx dbCol, + ColumnAlignment align = ColumnAlignment.Default, DataValue.DataType dataType = DataValue.DataType.String, + String alias = "", String prefix = "") + { + if (String.IsNullOrEmpty(alias) && SaxDbDfn_Reference.GetTableForColumn(dbCol) == SaxDbDfn_Reference.TableIdx.UsgaFacility) + alias = aliasUsgaFacility; + col.Set(caption, width, (int)dbCol, prefix + SaxDbDfn_Reference.GetColumnName(dbCol, false), SaxDbDfn_Reference.GetColumnNameQual(dbCol, alias), dataType, align); + if (dataType == DataValue.DataType.String && dbCol != SaxDbDfn_Reference.ColumnIdx.Unknown) + col.MaxLength = (int)SaxDbDfn_Reference.GetColTextLen(dbCol); + } + public override ColumnDfn GetUsgaFacilityColumnDfn(SaxGolfUsgaFacility.Column columnId, string caption = "", int width = 0) + { + ColumnDfn columnDfn = new ColumnDfn((int)columnId, caption, width); + switch (columnId) + { + //----------------------------------------------------------- + case SaxGolfUsgaFacility.Column.Pos: + SetUsgaFacilityColDfn(columnDfn, "Pos", 60, SaxDbDfn_Reference.ColumnIdx.Unknown, ColumnAlignment.Right); + columnDfn.SortMode = ColumnDfn.ColumnSortMode.Off; + columnDfn.ReadOnly = true; + columnDfn.Resizable = false; + break; + case SaxGolfUsgaFacility.Column.Id: + SetUsgaFacilityColDfn(columnDfn, "Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Id, ColumnAlignment.Right, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaFacility.Column.ProvinceId: + SetUsgaFacilityColDfn(columnDfn, "Province #", 80, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_ProvinceId, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaFacility.Column.Province_Name: + SetUsgaFacilityColDfn(columnDfn, "Province", 120, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName, ColumnAlignment.Center, DataValue.DataType.String, aliasUsgaFacility_Province, prefixUsgaFacility_Province); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaFacility.Column.FacilityId: + SetUsgaFacilityColDfn(columnDfn, "Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityId, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaFacility.Column.FacilityName: + SetUsgaFacilityColDfn(columnDfn, "Name", 120, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + + //----------------------------------------------------------- + // Derived properties. + + //----------------------------------------------------------- + // Common properties. + case SaxGolfUsgaFacility.Column.Notes: + SetUsgaFacilityColDfn(columnDfn, "Notes", 240, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Notes); + break; + case SaxGolfUsgaFacility.Column.Flags: + SetUsgaFacilityColDfn(columnDfn, "Flags", 60, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Flags, ColumnAlignment.Center, DataValue.DataType.Long); + break; + case SaxGolfUsgaFacility.Column.Status: + SetUsgaFacilityColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaFacility.Column.Status_Desc: + SetUsgaFacilityColDfn(columnDfn, "Status", 90, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaFacility.Column.Status_Ind: + SetUsgaFacilityColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Status, ColumnAlignment.Center, DataValue.DataType.TriState); + columnDfn.TriStateFormat = ColumnTriStateFormat.Lights; + break; + case SaxGolfUsgaFacility.Column.CreateOn_Date: + SetUsgaFacilityColDfn(columnDfn, "Created", 80, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_CreateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaFacility.Column.UpdateOn_Date: + SetUsgaFacilityColDfn(columnDfn, "Updated", 80, SaxDbDfn_Reference.ColumnIdx.UsgaFacility_UpdateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + //----------------------------------------------------------- + } + if (!String.IsNullOrEmpty(caption)) + columnDfn.Caption = caption; + if (width > 0) + columnDfn.Width = width; + return columnDfn; + } + + //------------------------------------------------------------------- + // Item query filter. + public override List GetUsgaFacilityQueryFilter(SaxGolfUsgaFacility.Params prm) + { + List filter = new List(); + + // Item Ids. + String idsIncluded = prm.IdsIncluded.Concat(","); + if (!idsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Id, aliasUsgaFacility) + " IN (" + idsIncluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Id, aliasUsgaFacility) + " NOT IN (" + idsExcluded + ")"); + + // Countries. + String provinceIdsIncluded = prm.ProvinceIdsIncluded.Concat(","); + if (!provinceIdsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_ProvinceId, aliasUsgaFacility) + " IN (" + provinceIdsIncluded + ")"); + + if (!StringUtil.IsBlank(prm.FacilityFilter)) + { + // Split filter into words. + List filterWords = prm.FacilityFilter.Split((char[])null).ToList(); + filterWords.RemoveDuplicatesCI(); + filterWords.RemoveBlanks(); + foreach (String filterWord in filterWords) + { + List articleFilter = new List(); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName, aliasUsgaFacility) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + filter.Add(articleFilter.Concat(" OR ", "(", ")")); + } + } + + // Name. + if (!StringUtil.IsEmpty(prm.FacilityNameFull)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName, aliasUsgaFacility) + "='" + DbQuery.FormatForCondition(prm.FacilityNameFull) + "'"); + if (!StringUtil.IsEmpty(prm.FacilityNamePartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName, aliasUsgaFacility) + " LIKE '%" + DbQuery.FormatForLike(prm.FacilityNamePartial) + "%'"); + + // Notes. + if (!StringUtil.IsEmpty(prm.NotesPartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Notes, aliasUsgaFacility) + " LIKE '%" + DbQuery.FormatForLike(prm.NotesPartial) + "%'"); + + // Status. + if (prm.StatusCat != SaxGolfUsgaFacility.StatusCat.Any) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Status, aliasUsgaFacility) + GetUsgaFacilityStatusCatFilterCondition(prm.StatusCat)); + + if (filter.Count < 1) filter.Add("1=1"); + return filter; + } + internal static String GetUsgaFacilityStatusCatFilterCondition(SaxGolfUsgaFacility.StatusCat statusCat) + { + if (statusCat == SaxGolfUsgaFacility.StatusCat.ActiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Active) + "'"; + if (statusCat == SaxGolfUsgaFacility.StatusCat.InactiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Inactive) + "'"; + if (statusCat == SaxGolfUsgaFacility.StatusCat.NotDeleted) + return "!='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + if (statusCat == SaxGolfUsgaFacility.StatusCat.DeletedOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + return ""; + } + // Item sort columns. + public List GetUsgaFacilitySortColumns(SaxGolfUsgaFacility.Params prm) + { + // Sort sequence: + List sortColumnNames = new List(); + foreach (var columnDfn in prm.SortColumns) + { + // Need to ensure correct alias used for UsgaFacility columns in case of conflict. + String sortCol = String.Empty; + if (SaxDbDfn_Reference.GetTableForColumn((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn) == SaxDbDfn_Reference.TableIdx.UsgaFacility) + { + sortCol = SaxDbDfn_Reference.GetColumnNameQual((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn, aliasUsgaFacility); + } + else + { + sortCol = columnDfn.DataName; + if (!StringUtil.IsEmpty(columnDfn.SortDataName)) + sortCol = columnDfn.SortDataName; + } + if (!sortCol.IsEmpty()) + { + DbOrderByNullMode orderByNullMode = DbOrderByNullMode.Default; // eSaOrderByDemoteNulls, eSaOrderByPromoteNulls + sortColumnNames.Add(DbQuery.FormatForOrderBy(sortCol, columnDfn.SortAscending, orderByNullMode).Concat(", ")); + } + } + sortColumnNames.RemoveBlanks(); + if (sortColumnNames.IsEmpty()) + { + // Default sort columns. + sortColumnNames.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Id, aliasUsgaFacility) + " ASC"); + } + return sortColumnNames; + } + + //------------------------------------------------------------------- + // Item count. + private long GetUsgaFacilityCount(String filter) + { + ClearErrorState(); + return ReferenceDatabase.GetRowCount(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaFacility) + " As " + aliasUsgaFacility, filter); + } + public override long GetUsgaFacilityCount(SaxGolfUsgaFacility.Params prm) + { + ClearErrorState(); + return GetUsgaFacilityCount(GetUsgaFacilityQueryFilter(prm).Concat(" AND ", "(", ")")); + } + + //------------------------------------------------------------------- + // Item list. + public override List GetUsgaFacilityList(SaxGolfUsgaFacility.Params prm) + { + List userRoles = new List(); + DbQuery qry = new DbQuery(ReferenceDatabase.DbmsType); + qry.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaFacility), aliasUsgaFacility); + Golf_UsgaFacility_Db dbUsgaFacility = new Golf_UsgaFacility_Db(ReferenceDbInfo); + qry.Columns.AddRange(dbUsgaFacility.ExistingColumnNames); + qry.Filters.AddRange(GetUsgaFacilityQueryFilter(prm)); + qry.OrderBy.AddRange(GetUsgaFacilitySortColumns(prm)); + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + dbCommand.CommandText = qry.BuildQuery(prm.ResultsPaging); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + while (dbDataReader.Read()) + { + dbUsgaFacility = new Golf_UsgaFacility_Db(ReferenceDbInfo); + dbUsgaFacility.PopulateFrom(dbDataReader); + userRoles.Add(CreateUsgaFacility(dbUsgaFacility)); + } + } + } + catch (Exception exc) + { + SaLogger.Warn(GetType().Name + ".GetUsgaFacilityList\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return userRoles; + } + + //------------------------------------------------------------------- + // Item query execution. + public override DbResultSet ExecuteUsgaFacilityQuery(List columns, SaxGolfUsgaFacility.Params prm) + { + ClearErrorState(); + + //--------------------------------------------------------------------- + // Construct query. + DbQuery query = new DbQuery(ReferenceDatabase.DbmsType); + query.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaFacility), aliasUsgaFacility); + + // Add columns as defined in query list. + if (columns.HasId(SaxGolfUsgaFacility.Column.Id)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Id, aliasUsgaFacility)); + bool hasProvinceCols = (columns.HasId(SaxGolfUsgaFacility.Column.Province_Name)); + if (columns.HasId(SaxGolfUsgaFacility.Column.ProvinceId) || hasProvinceCols) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_ProvinceId, aliasUsgaFacility)); + if (columns.HasId(SaxGolfUsgaFacility.Column.FacilityId)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityId, aliasUsgaFacility)); + if (columns.HasId(SaxGolfUsgaFacility.Column.FacilityName)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_FacilityName, aliasUsgaFacility)); + // Common properties. + if (columns.HasId(SaxGolfUsgaFacility.Column.Notes)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Notes, aliasUsgaFacility)); + if (columns.HasId(SaxGolfUsgaFacility.Column.Flags)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Flags, aliasUsgaFacility)); + if (columns.HasId(SaxGolfUsgaFacility.Column.Status) || columns.HasId(SaxGolfUsgaFacility.Column.Status_Desc) || columns.HasId(SaxGolfUsgaFacility.Column.Status_Ind)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_Status, aliasUsgaFacility)); + if (columns.HasId(SaxGolfUsgaFacility.Column.CreateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_CreateOn, aliasUsgaFacility)); + if (columns.HasId(SaxGolfUsgaFacility.Column.UpdateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_UpdateOn, aliasUsgaFacility)); + + //--------------------------------------------------------------------- + // Province. + if (hasProvinceCols) + { + DbQueryJoin joinProvince = new DbQueryJoin(DbJoinType.LeftOuter); + joinProvince.Table = new StringPair(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaProvince), aliasUsgaFacility_Province); + joinProvince.Filters.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Id, aliasUsgaFacility_Province) + "=" + SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaFacility_ProvinceId, aliasUsgaFacility)); + query.Joins.Add(joinProvince); + List cols = new List(); + cols.Add(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName); + foreach (var col in cols) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(col, aliasUsgaFacility_Province), prefixUsgaFacility_Province + SaxDbDfn_Reference.GetColumnName(col, false)); + prm.Alias_Province = aliasUsgaFacility_Province; + } + + //--------------------------------------------------------------------- + // Populate filter. + query.Filters.AddRange(GetUsgaFacilityQueryFilter(prm)); + + if (prm.IdsIncluded.Count != 1) + { + // Configure sort sequence. + foreach (String sortColumn in GetUsgaFacilitySortColumns(prm)) + query.OrderBy.Add(sortColumn); + } + + //--------------------------------------------------------------------- + //return new DbResultSet_DataTableReader(db, query.BuildQuery(prm.ResultsPaging)); + return DbResultSet_DataReader.ExecuteQuery(ReferenceDatabase, query.BuildQuery(prm.ResultsPaging)); + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaMarker.cs b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaMarker.cs new file mode 100644 index 0000000..b564853 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaMarker.cs @@ -0,0 +1,719 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Sarand.Net.Standard.Dbas.Data; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Internal.Reference; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +namespace Saxonite.Net.Standard.Dbas.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr_Dbas + { + //******************************************************************* + // Support Mgr - User Report + //******************************************************************* + // Utilities. + private List GetLogProperties(SaxGolfUsgaMarker usgaMarker) + { + return new List() + { + new StringPair("Id",SysId.ToString(usgaMarker.Id)), + new StringPair("CourseId",SysId.ToString(usgaMarker.CourseId)), + new StringPair("MarkerId",SysId.ToString(usgaMarker.MarkerId)), + new StringPair("Caption",usgaMarker.Caption), + new StringPair("Status",usgaMarker.StatusCode) + }; + } + + //------------------------------------------------------------------- + // Create item. + public override SaxGolfUsgaMarker CreateUsgaMarker(SysId courseId) + { + ClearErrorState(); + return new SaxGolfUsgaMarker_Dbas(ReferenceDatabase, null, courseId, 0); + } + private SaxGolfUsgaMarker_Dbas CreateUsgaMarker(Golf_UsgaMarker_Db dbUsgaMarker) + { + ClearErrorState(); + SaxGolfUsgaMarker_Dbas usgaMarker = new SaxGolfUsgaMarker_Dbas(ReferenceDatabase, new SysId(dbUsgaMarker._Id), new SysId(dbUsgaMarker._CourseId), (ushort)dbUsgaMarker._Flags); + PopulateFrom(dbUsgaMarker, usgaMarker); + return usgaMarker; + } + + //------------------------------------------------------------------- + // Get item. + public override SaxGolfUsgaMarker GetUsgaMarker(SaxGolfUsgaMarker.Params prm) + { + ClearErrorState(); + return GetUsgaMarker(GetUsgaMarkerQueryFilter(prm).Concat(" And ", "(", ")")); + } + private SaxGolfUsgaMarker GetUsgaMarker(String filter) + { + ClearErrorState(); + long count = GetUsgaMarkerCount(filter); + if (count == 0) return null; + if (count != 1) + { + SetErrorState("Multiple items found"); + return null; + } + SaxGolfUsgaMarker usgaMarker = null; + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaMarker_Db dbUsgaMarker = new Golf_UsgaMarker_Db(ReferenceDbInfo); + dbUsgaMarker.PopulateFrom(dbCommand, aliasUsgaMarker, filter); + usgaMarker = CreateUsgaMarker(dbUsgaMarker); + } + catch (Exception exc) + { + SetErrorState("Database query exception"); + SaLogger.Warn(GetType().Name + ".GetUsgaMarker\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return usgaMarker; + } + + //------------------------------------------------------------------- + // Validate item. + public override bool IsValidUsgaMarkerData(SaxGolfUsgaMarker.Data data, SaxGolfUsgaMarker.ErrField errField) + { + ClearErrorState(); + if (!base.IsValidUsgaMarkerData(data, errField)) return false; + return true; + } + + //------------------------------------------------------------------- + // Insert item. + public override bool InsertUsgaMarker(SaxGolfUsgaMarker usgaMarker, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".InsertUsgaMarker"; + ClearErrorState(); + if (!IsValidUsgaMarker(usgaMarker)) return false; + if (SysId.IsValid(usgaMarker.Id)) return SetErrorState(ErrorMessage.ValiditemId); + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaMarker_Db dbUsgaMarker = new Golf_UsgaMarker_Db(ReferenceDbInfo); + PopulateTo(dbUsgaMarker, usgaMarker, dbUpdateInfo); + if (Golf_UsgaMarker_Db.FieldsNonId.Contains("Id")) + { + // Generate next Id. + dbUsgaMarker._Id = ReferenceDatabase.GetNextIdFromTable("UsgaMarker"); + } + dbUsgaMarker.ExecuteInsertCommand(dbCommand); + usgaMarker.Id = new SysId(dbUsgaMarker._Id); + usgaMarker.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Inserted. " + GetLogProperties(usgaMarker).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Update item. + public override bool UpdateUsgaMarker(SaxGolfUsgaMarker usgaMarker, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".UpdateUsgaMarker"; + ClearErrorState(); + if (!IsValidUsgaMarker(usgaMarker)) return false; + if (!SysId.IsValid(usgaMarker.Id)) return SetErrorState(ErrorMessage.InvalidItemId); + if (!usgaMarker.Changed) + { + if (DebugMode) SaLogger.Debug(fn + " Data not changed. " + GetLogProperties(usgaMarker).Concat(": ").Concat("", "\n\t")); + return true; + } + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaMarker_Db dbUsgaMarker = new Golf_UsgaMarker_Db(ReferenceDbInfo); + dbUsgaMarker.PopulateFrom(dbCommand, aliasUsgaMarker, "Id=" + SysId.ToString(usgaMarker.Id)); + // ToDo SaxUpdateLogItemMonitor_UsgaMarker updateLogMonitor = new SaxUpdateLogItemMonitor_UsgaMarker(SessionContext, CreateUsgaMarker(dbUsgaMarker), dbUpdateInfo); + // Update item. + PopulateTo(dbUsgaMarker, usgaMarker, dbUpdateInfo); + dbUsgaMarker.ExecuteUpdateCommand(dbCommand); + usgaMarker.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Updated. " + GetLogProperties(usgaMarker).Concat(": ").Concat("", "\n\t")); + // Record updates. + // ToDo updateLogMonitor.RecordUpdatedValues(usgaMarker); + // ToDo updateLogMonitor.LogUpdates(); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Delete item. + public override bool UsgaMarkerCanBeDeleted(SaxGolfUsgaMarker usgaMarker) + { + ClearErrorState(); + if (!base.UsgaMarkerCanBeDeleted(usgaMarker)) return false; + return true; + } + public override bool DeleteUsgaMarker(SaxGolfUsgaMarker usgaMarker, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".DeleteUsgaMarker"; + ClearErrorState(); + if (!UsgaMarkerCanBeDeleted(usgaMarker)) return false; + + // User Roles are logically deleted by changing the status. + usgaMarker.Status = SaStatus.Deleted; + return UpdateUsgaMarker(usgaMarker, dbUpdateInfo); + + /* + * Physical deletion. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaMarker_Db dbUsgaMarker = new Golf_UsgaMarker_Db(ReferenceDbInfo); + dbUsgaMarker.PopulateFrom(dbCommand, aliasUsgaMarker, "Id=" + usgaMarker.Id.ToString()); + // Delete item. + dbCommand.CommandType = System.Data.CommandType.Text; + dbCommand.CommandText = "DELETE FROM " + SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaMarker) + " WHERE Id=" + SysId.ToString(usgaMarker.Id) + ";"; + dbCommand.ExecuteNonQuery(); + usgaMarker.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Deleted. " + GetLogProperties(usgaMarker).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + */ + } + + //------------------------------------------------------------------- + // Copy data properties to and from database. + private void PopulateTo(Golf_UsgaMarker_Db dbUsgaMarker, SaxGolfUsgaMarker usgaMarker, DbUpdateInfo dbUpdateInfo) + { + dbUsgaMarker._Id = SysId.ToLong(usgaMarker.Id); + dbUsgaMarker._CourseId = SysId.ToInt(usgaMarker.CourseId); + dbUsgaMarker._MarkerId = SysId.ToInt(usgaMarker.MarkerId); + dbUsgaMarker._Caption = usgaMarker.Caption; + dbUsgaMarker._Holes = usgaMarker.Holes; + dbUsgaMarker._HolesCaption = usgaMarker.HolesCaption; + dbUsgaMarker._Tee = usgaMarker.Tee; + dbUsgaMarker._Gender = usgaMarker.Gender; + dbUsgaMarker._SlopeRating = usgaMarker.SlopeRating; + dbUsgaMarker._Par = usgaMarker.Par; + dbUsgaMarker._CourseRating = usgaMarker.CourseRating; + dbUsgaMarker._BogeyRating = usgaMarker.BogeyRating; + dbUsgaMarker._Length = usgaMarker.Length; + // Common. + dbUsgaMarker._Notes = usgaMarker.Notes; + dbUsgaMarker._Status = SacsSystem.GetStatusCode(usgaMarker.Status); + dbUsgaMarker._Flags = (short)usgaMarker.Flags; + if (!SysId.IsValid(usgaMarker.Id)) + { + dbUsgaMarker._CreateOn = DateTime.Now; + dbUsgaMarker._CreateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaMarker._CreateHost = dbUpdateInfo.Host; + } + dbUsgaMarker._UpdateOn = DateTime.Now; + dbUsgaMarker._UpdateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaMarker._UpdateHost = dbUpdateInfo.Host; + } + private void PopulateFrom(Golf_UsgaMarker_Db dbUsgaMarker, SaxGolfUsgaMarker usgaMarker) + { + //usgaMarker.Id = new SysId(dbUsgaMarker._Id); + usgaMarker.CourseId = new SysId(dbUsgaMarker._CourseId); + usgaMarker.MarkerId = new SysId(dbUsgaMarker._MarkerId); + usgaMarker.Caption = dbUsgaMarker._Caption; + usgaMarker.Holes = dbUsgaMarker._Holes; + usgaMarker.HolesCaption = dbUsgaMarker._HolesCaption; + usgaMarker.Tee = dbUsgaMarker._Tee; + usgaMarker.Gender = dbUsgaMarker._Gender; + usgaMarker.SlopeRating = dbUsgaMarker._SlopeRating; + usgaMarker.Par = dbUsgaMarker._Par; + usgaMarker.CourseRating = dbUsgaMarker._CourseRating; + usgaMarker.BogeyRating = dbUsgaMarker._BogeyRating; + usgaMarker.Length = dbUsgaMarker._Length; + // Common. + usgaMarker.Notes = dbUsgaMarker._Notes; + usgaMarker.Status = SacsSystem.GetStatusForCode(dbUsgaMarker._Status); + usgaMarker.SetCreateStamp(dbUsgaMarker._CreateOn, new SysId(dbUsgaMarker._CreateBy), dbUsgaMarker._CreateHost); + usgaMarker.SetUpdateStamp(dbUsgaMarker._UpdateOn, new SysId(dbUsgaMarker._UpdateBy), dbUsgaMarker._UpdateHost); + usgaMarker.AcceptChanges(); + } + + //------------------------------------------------------------------- + // Bulk updates. + /// + /// Bulk update USGA Markers. + /// - Course Id must be supplied to identify parent. + /// - Marker Id must be supplied to act as identifier. + /// - Other properties are validated as per marker rules - check error state. + /// - Other properties are left as is if null. + /// + public override bool BulkUpdateUsgaMarkers(List markers, DbUpdateInfo dbUpdateInfo) + { + ClearErrorState(); + List markersToUpdate = new List(); + + // Validate supplied data. + foreach (UsgaMarkerData marker in markers) + { + // Validate marker properties. + // Course and Marker Codes are mandatory, other values only validated if non-null. + if (!SysId.IsValid(marker.CourseId)) return SetErrorState("Course Id must be supplied"); + if (!SysId.IsValid(marker.MarkerId)) return SetErrorState("Marker Id must be supplied"); + if (marker.Caption != null && !IsValidValue(marker.HolesCaption, "caption", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_HolesCaption))) return false; + if (marker.Holes < 1) return SetErrorState("Holes must be supplied"); + if (marker.HolesCaption != null && !IsValidValue(marker.HolesCaption, "full name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_HolesCaption))) return false; + if (marker.Tee != null && !IsValidValue(marker.Tee, "tee", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Tee))) return false; + if (marker.Gender != null && !IsValidValue(marker.Gender, "gender", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Gender))) return false; + if (marker.SlopeRating < 1) return SetErrorState("Slope rating must be supplied"); + if (marker.Par < 1) return SetErrorState("Par must be supplied"); + if (marker.CourseRating < 1) return SetErrorState("Course rating must be supplied"); + markersToUpdate.Add(marker); + } + int MaxBulkUpdateBatchSize = 64; + int batchSize = markersToUpdate.Any() ? (int)Math.Ceiling(markersToUpdate.Count() / Math.Ceiling((double)markersToUpdate.Count() / MaxBulkUpdateBatchSize)) : MaxBulkUpdateBatchSize; + while (markersToUpdate.Any()) + { + List query = new List(); + query.Add($"Declare @statusActive VarChar(3) = '{SacsSystem.GetStatusCode(SaxGolfUsgaMarker.DefaultStatus)}';"); + query.Add($"Declare @updateOn DateTime = GetUtcDate();"); + query.Add($"Declare @updateBy Int = {SysId.ToLong(dbUpdateInfo.UserId)};"); + query.Add($"Declare @updateHost VarChar(100) = '{DbQuery.FormatForCondition(dbUpdateInfo.Host)}';"); + query.Add("Merge"); + query.Add($"Into {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaMarker)} uMkr"); + query.Add("Using"); + query.Add("("); + query.Add("Select dCrs.Id CourseId, dMkr.MarkerId, dMkr.Caption, dMkr.Holes, dMkr.HolesCaption, dMkr.Tee, dMkr.Gender, dMkr.SlopeRating, dMkr.Par, dMkr.CourseRating, dMkr.BogeyRating, dMkr.Length"); + query.Add("From"); + query.Add("("); + query.Add("Select 0 CourseId, 0 MarkerId, '' Caption, 0 Holes, '' HolesCaption, '' Tee, '' Gender, 0 SlopeRating, 0 Par, 0 CourseRating, 0 BogeyRating, 0 Length"); + foreach (UsgaMarkerData marker in markersToUpdate.ExtractRange(0, batchSize)) + query.Add($"Union Select {marker.CourseId},{marker.MarkerId}," + + (marker.Caption != null ? $"'{DbQuery.FormatForCondition(marker.Caption)}'" : "Null") + "," + + $"{marker.Holes}," + + (marker.HolesCaption != null ? $"'{DbQuery.FormatForCondition(marker.HolesCaption)}'" : "Null") + "," + + (marker.Tee != null ? $"'{DbQuery.FormatForCondition(marker.Tee)}'" : "Null") + "," + + (marker.Gender != null ? $"'{DbQuery.FormatForCondition(marker.Gender)}'" : "Null") + "," + + $"{marker.SlopeRating}," + + $"{marker.Par}," + + $"{marker.CourseRating}," + + (marker.BogeyRating > 0 ? $"{marker.BogeyRating}" : "Null") + "," + + (marker.Length > 0 ? $"{marker.Length}" : "Null")); + query.Add(") dMkr"); + query.Add($"Inner Join {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCourse)} dCrs On dCrs.CourseId=dMkr.CourseId"); + query.Add(") dMkr"); + query.Add("On uMkr.CourseId=dMkr.CourseId And uMkr.MarkerId=dMkr.MarkerId"); + query.Add("When Matched And ((dMkr.Caption Is Not Null And uMkr.Caption!=dMkr.Caption) Or (uMkr.Holes!=dMkr.Holes) Or (dMkr.HolesCaption Is Not Null And uMkr.HolesCaption!=dMkr.HolesCaption) Or (dMkr.Tee Is Not Null And uMkr.Tee!=dMkr.Tee) Or (dMkr.Gender Is Not Null And uMkr.Gender!=dMkr.Gender) Or (uMkr.SlopeRating!=dMkr.SlopeRating) Or (uMkr.Par!=dMkr.Par) Or (uMkr.CourseRating!=dMkr.CourseRating) Or (dMkr.BogeyRating Is Not Null And uMkr.BogeyRating!=dMkr.BogeyRating) Or (dMkr.Length Is Not Null And uMkr.Length!=dMkr.Length) Or uMkr.Status!=@statusActive)"); + query.Add("Then Update Set"); + query.Add(" Caption=Coalesce(dMkr.Caption,uMkr.Caption),"); + query.Add(" Holes=Coalesce(dMkr.Holes,uMkr.Holes),"); + query.Add(" HolesCaption=Coalesce(dMkr.HolesCaption,uMkr.HolesCaption),"); + query.Add(" Tee=Coalesce(dMkr.Tee,uMkr.Tee),"); + query.Add(" Gender=Coalesce(dMkr.Gender,uMkr.Gender),"); + query.Add(" SlopeRating=Coalesce(dMkr.SlopeRating,uMkr.SlopeRating),"); + query.Add(" Par=Coalesce(dMkr.Par,uMkr.Par),"); + query.Add(" CourseRating=Coalesce(dMkr.CourseRating,uMkr.CourseRating),"); + query.Add(" BogeyRating=Coalesce(dMkr.BogeyRating,uMkr.BogeyRating),"); + query.Add(" Length=Coalesce(dMkr.Length,uMkr.Length),"); + query.Add(" Status=@statusActive,"); + query.Add(" UpdateOn=@updateOn,"); + query.Add(" UpdateBy=@updateBy,"); + query.Add(" UpdateHost=@updateHost"); + query.Add("When Not Matched And Len(Coalesce(dMkr.Caption,''))>0 And dMkr.Holes>0 And dMkr.SlopeRating>0 And dMkr.Par>0 And dMkr.CourseRating>0"); + query.Add("Then Insert (CourseId,MarkerId,Caption,Holes,HolesCaption,Tee,Gender,SlopeRating,Par,CourseRating,BogeyRating,Length,Notes,Flags,Status,CreateOn,CreateBy,CreateHost,UpdateOn,UpdateBy,UpdateHost)"); + query.Add($"Values (dMkr.CourseId,dMkr.MarkerId,Coalesce(dMkr.Caption,''),dMkr.Holes,Coalesce(dMkr.HolesCaption,''),Coalesce(dMkr.Tee,''),Coalesce(dMkr.Gender,''),Coalesce(dMkr.SlopeRating,''),Coalesce(dMkr.Par,''),Coalesce(dMkr.CourseRating,''),Coalesce(dMkr.BogeyRating,''),Coalesce(dMkr.Length,''),'',0,@statusActive,@updateOn,@updateBy,@updateHost,@updateOn,@updateBy,@updateHost)"); + query.Add(";"); + //SaLogger.Info($"{SysUtil.Fn} Bulk USGA Marker update query:\n\t{query.Concat("\n\t")}"); + + try + { + int result = ReferenceDatabase.ExecuteNonQuery(query.Concat("\n")); + if (ReferenceDatabase.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error executing bulk USGA Marker update - {ReferenceDatabase.ErrorStateMessage}"); + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, " executing bulk USGA Marker update")); + } + } + return HasErrorState(); + } + + //------------------------------------------------------------------- + // Item column definitions. + private static readonly String aliasUsgaMarker = "UsgMkr"; + private static readonly String aliasUsgaMarker_Course = "UsgMkr_Cty"; + private static readonly String prefixUsgaMarker_Course = aliasUsgaMarker_Course + "_"; + private void SetUsgaMarkerColDfn + (ColumnDfn col, String caption, int width, SaxDbDfn_Reference.ColumnIdx dbCol, + ColumnAlignment align = ColumnAlignment.Default, DataValue.DataType dataType = DataValue.DataType.String, + String alias = "", String prefix = "") + { + if (String.IsNullOrEmpty(alias) && SaxDbDfn_Reference.GetTableForColumn(dbCol) == SaxDbDfn_Reference.TableIdx.UsgaMarker) + alias = aliasUsgaMarker; + col.Set(caption, width, (int)dbCol, prefix + SaxDbDfn_Reference.GetColumnName(dbCol, false), SaxDbDfn_Reference.GetColumnNameQual(dbCol, alias), dataType, align); + if (dataType == DataValue.DataType.String && dbCol != SaxDbDfn_Reference.ColumnIdx.Unknown) + col.MaxLength = (int)SaxDbDfn_Reference.GetColTextLen(dbCol); + } + public override ColumnDfn GetUsgaMarkerColumnDfn(SaxGolfUsgaMarker.Column columnId, string caption = "", int width = 0) + { + ColumnDfn columnDfn = new ColumnDfn((int)columnId, caption, width); + switch (columnId) + { + //----------------------------------------------------------- + case SaxGolfUsgaMarker.Column.Pos: + SetUsgaMarkerColDfn(columnDfn, "Pos", 60, SaxDbDfn_Reference.ColumnIdx.Unknown, ColumnAlignment.Right); + columnDfn.SortMode = ColumnDfn.ColumnSortMode.Off; + columnDfn.ReadOnly = true; + columnDfn.Resizable = false; + break; + case SaxGolfUsgaMarker.Column.Id: + SetUsgaMarkerColDfn(columnDfn, "Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Id, ColumnAlignment.Right, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaMarker.Column.CourseId: + SetUsgaMarkerColDfn(columnDfn, "Course #", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_CourseId, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.Course_Name: + SetUsgaMarkerColDfn(columnDfn, "Course", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName, ColumnAlignment.Center, DataValue.DataType.String, aliasUsgaMarker_Course, prefixUsgaMarker_Course); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaMarker.Column.MarkerId: + SetUsgaMarkerColDfn(columnDfn, "Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_MarkerId, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.Caption: + SetUsgaMarkerColDfn(columnDfn, "Caption", 160, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Caption); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.Holes: + SetUsgaMarkerColDfn(columnDfn, "Holes", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Holes, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.HolesCaption: + SetUsgaMarkerColDfn(columnDfn, "Holes", 100, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_HolesCaption, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.Tee: + SetUsgaMarkerColDfn(columnDfn, "Tee", 100, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Tee, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.Gender: + SetUsgaMarkerColDfn(columnDfn, "Gender", 100, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Gender, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.SlopeRating: + SetUsgaMarkerColDfn(columnDfn, "Slope Rating", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_SlopeRating, ColumnAlignment.Center, DataValue.DataType.Decimal); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.Par: + SetUsgaMarkerColDfn(columnDfn, "Par", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Par, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.CourseRating: + SetUsgaMarkerColDfn(columnDfn, "Course Rating", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_CourseRating, ColumnAlignment.Center, DataValue.DataType.Decimal); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.BogeyRating: + SetUsgaMarkerColDfn(columnDfn, "Bogey Rating", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_BogeyRating, ColumnAlignment.Center, DataValue.DataType.Decimal); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.Length: + SetUsgaMarkerColDfn(columnDfn, "Length", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Length, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + + //----------------------------------------------------------- + // Derived properties. + + //----------------------------------------------------------- + // Common properties. + case SaxGolfUsgaMarker.Column.Notes: + SetUsgaMarkerColDfn(columnDfn, "Notes", 240, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Notes); + break; + case SaxGolfUsgaMarker.Column.Flags: + SetUsgaMarkerColDfn(columnDfn, "Flags", 60, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Flags, ColumnAlignment.Center, DataValue.DataType.Long); + break; + case SaxGolfUsgaMarker.Column.Status: + SetUsgaMarkerColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaMarker.Column.Status_Desc: + SetUsgaMarkerColDfn(columnDfn, "Status", 90, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaMarker.Column.Status_Ind: + SetUsgaMarkerColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Status, ColumnAlignment.Center, DataValue.DataType.TriState); + columnDfn.TriStateFormat = ColumnTriStateFormat.Lights; + break; + case SaxGolfUsgaMarker.Column.CreateOn_Date: + SetUsgaMarkerColDfn(columnDfn, "Created", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_CreateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaMarker.Column.UpdateOn_Date: + SetUsgaMarkerColDfn(columnDfn, "Updated", 80, SaxDbDfn_Reference.ColumnIdx.UsgaMarker_UpdateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + //----------------------------------------------------------- + } + if (!String.IsNullOrEmpty(caption)) + columnDfn.Caption = caption; + if (width > 0) + columnDfn.Width = width; + return columnDfn; + } + + //------------------------------------------------------------------- + // Item query filter. + public override List GetUsgaMarkerQueryFilter(SaxGolfUsgaMarker.Params prm) + { + List filter = new List(); + + // Item Ids. + String idsIncluded = prm.IdsIncluded.Concat(","); + if (!idsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Id, aliasUsgaMarker) + " IN (" + idsIncluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Id, aliasUsgaMarker) + " NOT IN (" + idsExcluded + ")"); + + // Countries. + String courseIdsIncluded = prm.CourseIdsIncluded.Concat(","); + if (!courseIdsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_CourseId, aliasUsgaMarker) + " IN (" + courseIdsIncluded + ")"); + + if (!StringUtil.IsBlank(prm.MarkerFilter)) + { + // Split filter into words. + List filterWords = prm.MarkerFilter.Split((char[])null).ToList(); + filterWords.RemoveDuplicatesCI(); + filterWords.RemoveBlanks(); + foreach (String filterWord in filterWords) + { + List articleFilter = new List(); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Caption, aliasUsgaMarker) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_HolesCaption, aliasUsgaMarker) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Tee, aliasUsgaMarker) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Gender, aliasUsgaMarker) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + filter.Add(articleFilter.Concat(" OR ", "(", ")")); + } + } + // Notes. + if (!StringUtil.IsEmpty(prm.NotesPartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Notes, aliasUsgaMarker) + " LIKE '%" + DbQuery.FormatForLike(prm.NotesPartial) + "%'"); + + // Status. + if (prm.StatusCat != SaxGolfUsgaMarker.StatusCat.Any) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Status, aliasUsgaMarker) + GetUsgaMarkerStatusCatFilterCondition(prm.StatusCat)); + + if (filter.Count < 1) filter.Add("1=1"); + return filter; + } + internal static String GetUsgaMarkerStatusCatFilterCondition(SaxGolfUsgaMarker.StatusCat statusCat) + { + if (statusCat == SaxGolfUsgaMarker.StatusCat.ActiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Active) + "'"; + if (statusCat == SaxGolfUsgaMarker.StatusCat.InactiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Inactive) + "'"; + if (statusCat == SaxGolfUsgaMarker.StatusCat.NotDeleted) + return "!='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + if (statusCat == SaxGolfUsgaMarker.StatusCat.DeletedOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + return ""; + } + // Item sort columns. + public List GetUsgaMarkerSortColumns(SaxGolfUsgaMarker.Params prm) + { + // Sort sequence: + List sortColumnNames = new List(); + foreach (var columnDfn in prm.SortColumns) + { + // Need to ensure correct alias used for UsgaMarker columns in case of conflict. + String sortCol = String.Empty; + if (SaxDbDfn_Reference.GetTableForColumn((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn) == SaxDbDfn_Reference.TableIdx.UsgaMarker) + { + sortCol = SaxDbDfn_Reference.GetColumnNameQual((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn, aliasUsgaMarker); + } + else + { + sortCol = columnDfn.DataName; + if (!StringUtil.IsEmpty(columnDfn.SortDataName)) + sortCol = columnDfn.SortDataName; + } + if (!sortCol.IsEmpty()) + { + DbOrderByNullMode orderByNullMode = DbOrderByNullMode.Default; // eSaOrderByDemoteNulls, eSaOrderByPromoteNulls + sortColumnNames.Add(DbQuery.FormatForOrderBy(sortCol, columnDfn.SortAscending, orderByNullMode).Concat(", ")); + } + } + sortColumnNames.RemoveBlanks(); + if (sortColumnNames.IsEmpty()) + { + // Default sort columns. + sortColumnNames.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Id, aliasUsgaMarker) + " ASC"); + } + return sortColumnNames; + } + + //------------------------------------------------------------------- + // Item count. + private long GetUsgaMarkerCount(String filter) + { + ClearErrorState(); + return ReferenceDatabase.GetRowCount(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaMarker) + " As " + aliasUsgaMarker, filter); + } + public override long GetUsgaMarkerCount(SaxGolfUsgaMarker.Params prm) + { + ClearErrorState(); + return GetUsgaMarkerCount(GetUsgaMarkerQueryFilter(prm).Concat(" AND ", "(", ")")); + } + + //------------------------------------------------------------------- + // Item list. + public override List GetUsgaMarkerList(SaxGolfUsgaMarker.Params prm) + { + List userRoles = new List(); + DbQuery qry = new DbQuery(ReferenceDatabase.DbmsType); + qry.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaMarker), aliasUsgaMarker); + Golf_UsgaMarker_Db dbUsgaMarker = new Golf_UsgaMarker_Db(ReferenceDbInfo); + qry.Columns.AddRange(dbUsgaMarker.ExistingColumnNames); + qry.Filters.AddRange(GetUsgaMarkerQueryFilter(prm)); + qry.OrderBy.AddRange(GetUsgaMarkerSortColumns(prm)); + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + dbCommand.CommandText = qry.BuildQuery(prm.ResultsPaging); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + while (dbDataReader.Read()) + { + dbUsgaMarker = new Golf_UsgaMarker_Db(ReferenceDbInfo); + dbUsgaMarker.PopulateFrom(dbDataReader); + userRoles.Add(CreateUsgaMarker(dbUsgaMarker)); + } + } + } + catch (Exception exc) + { + SaLogger.Warn(GetType().Name + ".GetUsgaMarkerList\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return userRoles; + } + + //------------------------------------------------------------------- + // Item query execution. + public override DbResultSet ExecuteUsgaMarkerQuery(List columns, SaxGolfUsgaMarker.Params prm) + { + ClearErrorState(); + + //--------------------------------------------------------------------- + // Construct query. + DbQuery query = new DbQuery(ReferenceDatabase.DbmsType); + query.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaMarker), aliasUsgaMarker); + + // Add columns as defined in query list. + if (columns.HasId(SaxGolfUsgaMarker.Column.Id)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Id, aliasUsgaMarker)); + bool hasCourseCols = (columns.HasId(SaxGolfUsgaMarker.Column.Course_Name)); + if (columns.HasId(SaxGolfUsgaMarker.Column.CourseId) || hasCourseCols) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_CourseId, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.MarkerId)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_MarkerId, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.Caption)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Caption, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.Holes)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Holes, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.HolesCaption)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_HolesCaption, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.Tee)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Tee, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.Gender)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Gender, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.SlopeRating)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_SlopeRating, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.Par)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Par, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.CourseRating)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_CourseRating, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.BogeyRating)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_BogeyRating, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.Length)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Length, aliasUsgaMarker)); + // Common properties. + if (columns.HasId(SaxGolfUsgaMarker.Column.Notes)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Notes, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.Flags)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Flags, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.Status) || columns.HasId(SaxGolfUsgaMarker.Column.Status_Desc) || columns.HasId(SaxGolfUsgaMarker.Column.Status_Ind)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_Status, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.CreateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_CreateOn, aliasUsgaMarker)); + if (columns.HasId(SaxGolfUsgaMarker.Column.UpdateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_UpdateOn, aliasUsgaMarker)); + + //--------------------------------------------------------------------- + // Course. + if (hasCourseCols) + { + DbQueryJoin joinCourse = new DbQueryJoin(DbJoinType.LeftOuter); + joinCourse.Table = new StringPair(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCourse), aliasUsgaMarker_Course); + joinCourse.Filters.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_Id, aliasUsgaMarker_Course) + "=" + SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaMarker_CourseId, aliasUsgaMarker)); + query.Joins.Add(joinCourse); + List cols = new List(); + cols.Add(SaxDbDfn_Reference.ColumnIdx.UsgaCourse_CourseName); + foreach (var col in cols) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(col, aliasUsgaMarker_Course), prefixUsgaMarker_Course + SaxDbDfn_Reference.GetColumnName(col, false)); + prm.Alias_Course = aliasUsgaMarker_Course; + } + + //--------------------------------------------------------------------- + // Populate filter. + query.Filters.AddRange(GetUsgaMarkerQueryFilter(prm)); + + if (prm.IdsIncluded.Count != 1) + { + // Configure sort sequence. + foreach (String sortColumn in GetUsgaMarkerSortColumns(prm)) + query.OrderBy.Add(sortColumn); + } + + //--------------------------------------------------------------------- + //return new DbResultSet_DataTableReader(db, query.BuildQuery(prm.ResultsPaging)); + return DbResultSet_DataReader.ExecuteQuery(ReferenceDatabase, query.BuildQuery(prm.ResultsPaging)); + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaProvince.cs b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaProvince.cs new file mode 100644 index 0000000..fa7d8f5 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas-UsgaProvince.cs @@ -0,0 +1,630 @@ +using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; +using Sarand.Net.Standard.Base.Core; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Base.Utils; +using Sarand.Net.Standard.Dbas.Data; +using Saxonite.Base.App; +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Bus; +using Saxonite.Net.Standard.Base.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Bus.Reference; +using Saxonite.Net.Standard.Dbas.Internal.Reference; +using System; +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; + +namespace Saxonite.Net.Standard.Dbas.Mgr.Reference +{ + //======================================================================= + partial class SaxReferenceGolfMgr_Dbas + { + //******************************************************************* + // Support Mgr - User Report + //******************************************************************* + // Utilities. + private List GetLogProperties(SaxGolfUsgaProvince usgaProvince) + { + return new List() + { + new StringPair("Id",SysId.ToString(usgaProvince.Id)), + new StringPair("CountryId",SysId.ToString(usgaProvince.CountryId)), + new StringPair("ProvinceCode",usgaProvince.ProvinceCode), + new StringPair("ProvinceName",usgaProvince.ProvinceName), + new StringPair("Status",usgaProvince.StatusCode) + }; + } + + //------------------------------------------------------------------- + // Create item. + public override SaxGolfUsgaProvince CreateUsgaProvince(SysId countryId) + { + ClearErrorState(); + return new SaxGolfUsgaProvince_Dbas(ReferenceDatabase, null, countryId, 0); + } + private SaxGolfUsgaProvince_Dbas CreateUsgaProvince(Golf_UsgaProvince_Db dbUsgaProvince) + { + ClearErrorState(); + SaxGolfUsgaProvince_Dbas usgaProvince = new SaxGolfUsgaProvince_Dbas(ReferenceDatabase, new SysId(dbUsgaProvince._Id), new SysId(dbUsgaProvince._CountryId), (ushort)dbUsgaProvince._Flags); + PopulateFrom(dbUsgaProvince, usgaProvince); + return usgaProvince; + } + + //------------------------------------------------------------------- + // Get item. + public override SaxGolfUsgaProvince GetUsgaProvince(SaxGolfUsgaProvince.Params prm) + { + ClearErrorState(); + return GetUsgaProvince(GetUsgaProvinceQueryFilter(prm).Concat(" And ", "(", ")")); + } + private SaxGolfUsgaProvince GetUsgaProvince(String filter) + { + ClearErrorState(); + long count = GetUsgaProvinceCount(filter); + if (count == 0) return null; + if (count != 1) + { + SetErrorState("Multiple items found"); + return null; + } + SaxGolfUsgaProvince usgaProvince = null; + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaProvince_Db dbUsgaProvince = new Golf_UsgaProvince_Db(ReferenceDbInfo); + dbUsgaProvince.PopulateFrom(dbCommand, aliasUsgaProvince, filter); + usgaProvince = CreateUsgaProvince(dbUsgaProvince); + } + catch (Exception exc) + { + SetErrorState("Database query exception"); + SaLogger.Warn(GetType().Name + ".GetUsgaProvince\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return usgaProvince; + } + + //------------------------------------------------------------------- + // Validate item. + public override bool IsValidUsgaProvinceData(SaxGolfUsgaProvince.Data data, SaxGolfUsgaProvince.ErrField errField) + { + ClearErrorState(); + if (!base.IsValidUsgaProvinceData(data, errField)) return false; + return true; + } + + //------------------------------------------------------------------- + // Insert item. + public override bool InsertUsgaProvince(SaxGolfUsgaProvince usgaProvince, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".InsertUsgaProvince"; + ClearErrorState(); + if (!IsValidUsgaProvince(usgaProvince)) return false; + if (SysId.IsValid(usgaProvince.Id)) return SetErrorState(ErrorMessage.ValiditemId); + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + Golf_UsgaProvince_Db dbUsgaProvince = new Golf_UsgaProvince_Db(ReferenceDbInfo); + PopulateTo(dbUsgaProvince, usgaProvince, dbUpdateInfo); + if (Golf_UsgaProvince_Db.FieldsNonId.Contains("Id")) + { + // Generate next Id. + dbUsgaProvince._Id = ReferenceDatabase.GetNextIdFromTable("UsgaProvince"); + } + dbUsgaProvince.ExecuteInsertCommand(dbCommand); + usgaProvince.Id = new SysId(dbUsgaProvince._Id); + usgaProvince.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Inserted. " + GetLogProperties(usgaProvince).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Update item. + public override bool UpdateUsgaProvince(SaxGolfUsgaProvince usgaProvince, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".UpdateUsgaProvince"; + ClearErrorState(); + if (!IsValidUsgaProvince(usgaProvince)) return false; + if (!SysId.IsValid(usgaProvince.Id)) return SetErrorState(ErrorMessage.InvalidItemId); + if (!usgaProvince.Changed) + { + if (DebugMode) SaLogger.Debug(fn + " Data not changed. " + GetLogProperties(usgaProvince).Concat(": ").Concat("", "\n\t")); + return true; + } + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaProvince_Db dbUsgaProvince = new Golf_UsgaProvince_Db(ReferenceDbInfo); + dbUsgaProvince.PopulateFrom(dbCommand, aliasUsgaProvince, "Id=" + SysId.ToString(usgaProvince.Id)); + // ToDo SaxUpdateLogItemMonitor_UsgaProvince updateLogMonitor = new SaxUpdateLogItemMonitor_UsgaProvince(SessionContext, CreateUsgaProvince(dbUsgaProvince), dbUpdateInfo); + // Update item. + PopulateTo(dbUsgaProvince, usgaProvince, dbUpdateInfo); + dbUsgaProvince.ExecuteUpdateCommand(dbCommand); + usgaProvince.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Updated. " + GetLogProperties(usgaProvince).Concat(": ").Concat("", "\n\t")); + // Record updates. + // ToDo updateLogMonitor.RecordUpdatedValues(usgaProvince); + // ToDo updateLogMonitor.LogUpdates(); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + } + + //------------------------------------------------------------------- + // Delete item. + public override bool UsgaProvinceCanBeDeleted(SaxGolfUsgaProvince usgaProvince) + { + ClearErrorState(); + if (!base.UsgaProvinceCanBeDeleted(usgaProvince)) return false; + return true; + } + public override bool DeleteUsgaProvince(SaxGolfUsgaProvince usgaProvince, DbUpdateInfo dbUpdateInfo) + { + String fn = GetType().Name + ".DeleteUsgaProvince"; + ClearErrorState(); + if (!UsgaProvinceCanBeDeleted(usgaProvince)) return false; + + // User Roles are logically deleted by changing the status. + usgaProvince.Status = SaStatus.Deleted; + return UpdateUsgaProvince(usgaProvince, dbUpdateInfo); + + /* + * Physical deletion. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + // Retrieve item. + dbConnection.Open(); + Golf_UsgaProvince_Db dbUsgaProvince = new Golf_UsgaProvince_Db(ReferenceDbInfo); + dbUsgaProvince.PopulateFrom(dbCommand, aliasUsgaProvince, "Id=" + usgaProvince.Id.ToString()); + // Delete item. + dbCommand.CommandType = System.Data.CommandType.Text; + dbCommand.CommandText = "DELETE FROM " + SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaProvince) + " WHERE Id=" + SysId.ToString(usgaProvince.Id) + ";"; + dbCommand.ExecuteNonQuery(); + usgaProvince.Changed = false; + if (DebugMode) SaLogger.Debug(fn + " Deleted. " + GetLogProperties(usgaProvince).Concat(": ").Concat("", "\n\t")); + } + catch (Exception exc) { SetErrorState(exc.Message); } + } + return !HasErrorState(); + */ + } + + //------------------------------------------------------------------- + // Copy data properties to and from database. + private void PopulateTo(Golf_UsgaProvince_Db dbUsgaProvince, SaxGolfUsgaProvince usgaProvince, DbUpdateInfo dbUpdateInfo) + { + dbUsgaProvince._Id = SysId.ToLong(usgaProvince.Id); + dbUsgaProvince._CountryId = SysId.ToInt(usgaProvince.CountryId); + dbUsgaProvince._ProvinceCode = usgaProvince.ProvinceCode; + dbUsgaProvince._EntProvinceCode = usgaProvince.EntProvinceCode; + dbUsgaProvince._ProvinceName = usgaProvince.ProvinceName; + // Common. + dbUsgaProvince._Notes = usgaProvince.Notes; + dbUsgaProvince._Status = SacsSystem.GetStatusCode(usgaProvince.Status); + dbUsgaProvince._Flags = (short)usgaProvince.Flags; + if (!SysId.IsValid(usgaProvince.Id)) + { + dbUsgaProvince._CreateOn = DateTime.Now; + dbUsgaProvince._CreateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaProvince._CreateHost = dbUpdateInfo.Host; + } + dbUsgaProvince._UpdateOn = DateTime.Now; + dbUsgaProvince._UpdateBy = dbUpdateInfo.UserId.ToInt(); + dbUsgaProvince._UpdateHost = dbUpdateInfo.Host; + } + private void PopulateFrom(Golf_UsgaProvince_Db dbUsgaProvince, SaxGolfUsgaProvince usgaProvince) + { + //usgaProvince.Id = new SysId(dbUsgaProvince._Id); + usgaProvince.CountryId = new SysId(dbUsgaProvince._CountryId); + usgaProvince.ProvinceCode = dbUsgaProvince._ProvinceCode; + usgaProvince.EntProvinceCode = dbUsgaProvince._EntProvinceCode; + usgaProvince.ProvinceName = dbUsgaProvince._ProvinceName; + // Common. + usgaProvince.Notes = dbUsgaProvince._Notes; + usgaProvince.Status = SacsSystem.GetStatusForCode(dbUsgaProvince._Status); + usgaProvince.SetCreateStamp(dbUsgaProvince._CreateOn, new SysId(dbUsgaProvince._CreateBy), dbUsgaProvince._CreateHost); + usgaProvince.SetUpdateStamp(dbUsgaProvince._UpdateOn, new SysId(dbUsgaProvince._UpdateBy), dbUsgaProvince._UpdateHost); + usgaProvince.AcceptChanges(); + } + + //------------------------------------------------------------------- + // Bulk updates. + /// + /// Bulk update USGA Provinces. + /// - Country code must be supplied to identify parent. + /// - Province code must be supplied to act as identifier. + /// - Other properties are validated as per province rules - check error state. + /// - Other properties are left as is if null. + /// + public override bool BulkUpdateUsgaProvinces(List provinces, DbUpdateInfo dbUpdateInfo) + { + ClearErrorState(); + List provincesToUpdate = new List(); + + // Validate supplied data. + foreach (UsgaProvinceData province in provinces) + { + // Validate province properties. + // Country and Province Codes are mandatory, other values only validated if non-null. + if (!IsValidValue(province.CountryCode, "country", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryCode), true)) return false; + if (!IsValidValue(province.ProvinceCode, "code", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceCode), true)) return false; + if (!IsValidValue(province.EntProvinceCode, "ENT code", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_EntProvinceCode))) return false; + if (province.ProvinceName != null && !IsValidValue(province.ProvinceName, "name", (long)SaxDbDfn_Reference.GetColTextLen(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName))) return false; + provincesToUpdate.Add(province); + } + int MaxBulkUpdateBatchSize = 64; + int batchSize = provincesToUpdate.Any() ? (int)Math.Ceiling(provincesToUpdate.Count() / Math.Ceiling((double)provincesToUpdate.Count() / MaxBulkUpdateBatchSize)) : MaxBulkUpdateBatchSize; + while (provincesToUpdate.Any()) + { + List query = new List(); + query.Add($"Declare @statusActive VarChar(3) = '{SacsSystem.GetStatusCode(SaxGolfUsgaProvince.DefaultStatus)}';"); + query.Add($"Declare @updateOn DateTime = GetUtcDate();"); + query.Add($"Declare @updateBy Int = {SysId.ToLong(dbUpdateInfo.UserId)};"); + query.Add($"Declare @updateHost VarChar(100) = '{DbQuery.FormatForCondition(dbUpdateInfo.Host)}';"); + query.Add("Merge"); + query.Add($"Into {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaProvince)} uPrv"); + query.Add("Using"); + query.Add("("); + query.Add("Select dCty.Id CountryId, dPrv.CountryCode, dPrv.ProvinceCode, dPrv.EntProvinceCode, dPrv.ProvinceName"); + query.Add("From"); + query.Add("("); + query.Add("Select '' CountryCode, '' ProvinceCode, '' EntProvinceCode, '' ProvinceName"); + foreach (UsgaProvinceData province in provincesToUpdate.ExtractRange(0, batchSize)) + query.Add($"Union Select '{DbQuery.FormatForCondition(province.CountryCode)}', '{DbQuery.FormatForCondition(province.ProvinceCode)}', " + (province.EntProvinceCode != null ? $"'{DbQuery.FormatForCondition(province.EntProvinceCode)}'" : "Null") + "," + (province.ProvinceName != null ? $"'{DbQuery.FormatForCondition(province.ProvinceName)}'" : "Null")); + query.Add(") dPrv"); + query.Add($"Inner Join {SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCountry)} dCty On dCty.CountryCode=dPrv.CountryCode"); + query.Add(") dPrv"); + query.Add("On uPrv.CountryId=dPrv.CountryId And uPrv.ProvinceCode=dPrv.ProvinceCode"); + query.Add("When Matched And ((dPrv.EntProvinceCode Is Not Null And uPrv.EntProvinceCode!=dPrv.EntProvinceCode) Or (dPrv.ProvinceName Is Not Null And uPrv.ProvinceName!=dPrv.ProvinceName) Or uPrv.Status!=@statusActive)"); + query.Add("Then Update Set"); + query.Add(" EntProvinceCode=Coalesce(dPrv.EntProvinceCode,uPrv.EntProvinceCode),"); + query.Add(" ProvinceName=Coalesce(dPrv.ProvinceName,uPrv.ProvinceName),"); + query.Add(" Status=@statusActive,"); + query.Add(" UpdateOn=@updateOn,"); + query.Add(" UpdateBy=@updateBy,"); + query.Add(" UpdateHost=@updateHost"); + query.Add("When Not Matched And Len(IsNull(dPrv.ProvinceName,''))>0"); + query.Add("Then Insert (CountryId,ProvinceCode,EntProvinceCode,ProvinceName,Notes,Flags,Status,CreateOn,CreateBy,CreateHost,UpdateOn,UpdateBy,UpdateHost)"); + query.Add($"Values (dPrv.CountryId,dPrv.ProvinceCode,Coalesce(dPrv.EntProvinceCode,''),dPrv.ProvinceName,'',0,@statusActive,@updateOn,@updateBy,@updateHost,@updateOn,@updateBy,@updateHost)"); + query.Add(";"); + //SaLogger.Info($"{SysUtil.Fn} Bulk USGA Province update query:\n\t{query.Concat("\n\t")}"); + + try + { + int result = ReferenceDatabase.ExecuteNonQuery(query.Concat("\n")); + if (ReferenceDatabase.HasErrorState()) + SaLogger.Warn($"{SysUtil.Fn} Error executing bulk USGA Province update - {ReferenceDatabase.ErrorStateMessage}"); + } + catch (Exception exc) + { + SaLogger.Warn(SysUtil.Fn + " " + ExceptionUtil.GetLogMessage(exc, " executing bulk USGA Province update")); + } + } + return HasErrorState(); + } + + //------------------------------------------------------------------- + // Item column definitions. + private static readonly String aliasUsgaProvince = "UsgPrv"; + private static readonly String aliasUsgaProvince_Country = "UsgPrv_Cty"; + private static readonly String prefixUsgaProvince_Country = aliasUsgaProvince_Country + "_"; + private void SetUsgaProvinceColDfn + (ColumnDfn col, String caption, int width, SaxDbDfn_Reference.ColumnIdx dbCol, + ColumnAlignment align = ColumnAlignment.Default, DataValue.DataType dataType = DataValue.DataType.String, + String alias = "", String prefix = "") + { + if (String.IsNullOrEmpty(alias) && SaxDbDfn_Reference.GetTableForColumn(dbCol) == SaxDbDfn_Reference.TableIdx.UsgaProvince) + alias = aliasUsgaProvince; + col.Set(caption, width, (int)dbCol, prefix + SaxDbDfn_Reference.GetColumnName(dbCol, false), SaxDbDfn_Reference.GetColumnNameQual(dbCol, alias), dataType, align); + if (dataType == DataValue.DataType.String && dbCol != SaxDbDfn_Reference.ColumnIdx.Unknown) + col.MaxLength = (int)SaxDbDfn_Reference.GetColTextLen(dbCol); + } + public override ColumnDfn GetUsgaProvinceColumnDfn(SaxGolfUsgaProvince.Column columnId, string caption = "", int width = 0) + { + ColumnDfn columnDfn = new ColumnDfn((int)columnId, caption, width); + switch (columnId) + { + //----------------------------------------------------------- + case SaxGolfUsgaProvince.Column.Pos: + SetUsgaProvinceColDfn(columnDfn, "Pos", 60, SaxDbDfn_Reference.ColumnIdx.Unknown, ColumnAlignment.Right); + columnDfn.SortMode = ColumnDfn.ColumnSortMode.Off; + columnDfn.ReadOnly = true; + columnDfn.Resizable = false; + break; + case SaxGolfUsgaProvince.Column.Id: + SetUsgaProvinceColDfn(columnDfn, "Id", 80, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Id, ColumnAlignment.Right, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaProvince.Column.CountryId: + SetUsgaProvinceColDfn(columnDfn, "Country #", 80, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_CountryId, ColumnAlignment.Center, DataValue.DataType.Long); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaProvince.Column.Country_Name: + SetUsgaProvinceColDfn(columnDfn, "Country", 120, SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName, ColumnAlignment.Center, DataValue.DataType.String, aliasUsgaProvince_Country, prefixUsgaProvince_Country); + columnDfn.ReadOnly = true; + break; + + //------------------------------------------------------- + case SaxGolfUsgaProvince.Column.ProvinceCode: + SetUsgaProvinceColDfn(columnDfn, "Code", 80, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceCode, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaProvince.Column.ProvinceName: + SetUsgaProvinceColDfn(columnDfn, "Name", 120, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName, ColumnAlignment.Center); + columnDfn.ReadOnly = true; + break; + + //----------------------------------------------------------- + // Derived properties. + + //----------------------------------------------------------- + // Common properties. + case SaxGolfUsgaProvince.Column.Notes: + SetUsgaProvinceColDfn(columnDfn, "Notes", 240, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Notes); + break; + case SaxGolfUsgaProvince.Column.Flags: + SetUsgaProvinceColDfn(columnDfn, "Flags", 60, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Flags, ColumnAlignment.Center, DataValue.DataType.Long); + break; + case SaxGolfUsgaProvince.Column.Status: + SetUsgaProvinceColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaProvince.Column.Status_Desc: + SetUsgaProvinceColDfn(columnDfn, "Status", 90, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Status, ColumnAlignment.Center); + break; + case SaxGolfUsgaProvince.Column.Status_Ind: + SetUsgaProvinceColDfn(columnDfn, "Status", 80, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Status, ColumnAlignment.Center, DataValue.DataType.TriState); + columnDfn.TriStateFormat = ColumnTriStateFormat.Lights; + break; + case SaxGolfUsgaProvince.Column.CreateOn_Date: + SetUsgaProvinceColDfn(columnDfn, "Created", 80, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_CreateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + case SaxGolfUsgaProvince.Column.UpdateOn_Date: + SetUsgaProvinceColDfn(columnDfn, "Updated", 80, SaxDbDfn_Reference.ColumnIdx.UsgaProvince_UpdateOn, ColumnAlignment.Center, DataValue.DataType.Date); + columnDfn.ReadOnly = true; + break; + //----------------------------------------------------------- + } + if (!String.IsNullOrEmpty(caption)) + columnDfn.Caption = caption; + if (width > 0) + columnDfn.Width = width; + return columnDfn; + } + + //------------------------------------------------------------------- + // Item query filter. + public override List GetUsgaProvinceQueryFilter(SaxGolfUsgaProvince.Params prm) + { + List filter = new List(); + + // Item Ids. + String idsIncluded = prm.IdsIncluded.Concat(","); + if (!idsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Id, aliasUsgaProvince) + " IN (" + idsIncluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Id, aliasUsgaProvince) + " NOT IN (" + idsExcluded + ")"); + + // Countries. + String countryIdsIncluded = prm.CountryIdsIncluded.Concat(","); + if (!countryIdsIncluded.IsEmpty()) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_CountryId, aliasUsgaProvince) + " IN (" + countryIdsIncluded + ")"); + + if (!StringUtil.IsBlank(prm.ProvinceFilter)) + { + // Split filter into words. + List filterWords = prm.ProvinceFilter.Split((char[])null).ToList(); + filterWords.RemoveDuplicatesCI(); + filterWords.RemoveBlanks(); + foreach (String filterWord in filterWords) + { + List articleFilter = new List(); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceCode, aliasUsgaProvince) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + articleFilter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName, aliasUsgaProvince) + " Like '%" + DbQuery.FormatForLike(filterWord, true) + "%'"); + filter.Add(articleFilter.Concat(" OR ", "(", ")")); + } + } + + // Name. + if (!StringUtil.IsEmpty(prm.ProvinceNameFull)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName, aliasUsgaProvince) + "='" + DbQuery.FormatForCondition(prm.ProvinceNameFull) + "'"); + if (!StringUtil.IsEmpty(prm.ProvinceNamePartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName, aliasUsgaProvince) + " LIKE '%" + DbQuery.FormatForLike(prm.ProvinceNamePartial) + "%'"); + + // Notes. + if (!StringUtil.IsEmpty(prm.NotesPartial)) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Notes, aliasUsgaProvince) + " LIKE '%" + DbQuery.FormatForLike(prm.NotesPartial) + "%'"); + + // Status. + if (prm.StatusCat != SaxGolfUsgaProvince.StatusCat.Any) + filter.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Status, aliasUsgaProvince) + GetUsgaProvinceStatusCatFilterCondition(prm.StatusCat)); + + if (filter.Count < 1) filter.Add("1=1"); + return filter; + } + internal static String GetUsgaProvinceStatusCatFilterCondition(SaxGolfUsgaProvince.StatusCat statusCat) + { + if (statusCat == SaxGolfUsgaProvince.StatusCat.ActiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Active) + "'"; + if (statusCat == SaxGolfUsgaProvince.StatusCat.InactiveOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Inactive) + "'"; + if (statusCat == SaxGolfUsgaProvince.StatusCat.NotDeleted) + return "!='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + if (statusCat == SaxGolfUsgaProvince.StatusCat.DeletedOnly) + return "='" + SacsSystem.GetStatusCode(SaStatus.Deleted) + "'"; + return ""; + } + // Item sort columns. + public List GetUsgaProvinceSortColumns(SaxGolfUsgaProvince.Params prm) + { + // Sort sequence: + List sortColumnNames = new List(); + foreach (var columnDfn in prm.SortColumns) + { + // Need to ensure correct alias used for UsgaProvince columns in case of conflict. + String sortCol = String.Empty; + if (SaxDbDfn_Reference.GetTableForColumn((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn) == SaxDbDfn_Reference.TableIdx.UsgaProvince) + { + sortCol = SaxDbDfn_Reference.GetColumnNameQual((SaxDbDfn_Reference.ColumnIdx)columnDfn.DbColumn, aliasUsgaProvince); + } + else + { + sortCol = columnDfn.DataName; + if (!StringUtil.IsEmpty(columnDfn.SortDataName)) + sortCol = columnDfn.SortDataName; + } + if (!sortCol.IsEmpty()) + { + DbOrderByNullMode orderByNullMode = DbOrderByNullMode.Default; // eSaOrderByDemoteNulls, eSaOrderByPromoteNulls + sortColumnNames.Add(DbQuery.FormatForOrderBy(sortCol, columnDfn.SortAscending, orderByNullMode).Concat(", ")); + } + } + sortColumnNames.RemoveBlanks(); + if (sortColumnNames.IsEmpty()) + { + // Default sort columns. + sortColumnNames.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Id, aliasUsgaProvince) + " ASC"); + } + return sortColumnNames; + } + + //------------------------------------------------------------------- + // Item count. + private long GetUsgaProvinceCount(String filter) + { + ClearErrorState(); + return ReferenceDatabase.GetRowCount(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaProvince) + " As " + aliasUsgaProvince, filter); + } + public override long GetUsgaProvinceCount(SaxGolfUsgaProvince.Params prm) + { + ClearErrorState(); + return GetUsgaProvinceCount(GetUsgaProvinceQueryFilter(prm).Concat(" AND ", "(", ")")); + } + + //------------------------------------------------------------------- + // Item list. + public override List GetUsgaProvinceList(SaxGolfUsgaProvince.Params prm) + { + List userRoles = new List(); + DbQuery qry = new DbQuery(ReferenceDatabase.DbmsType); + qry.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaProvince), aliasUsgaProvince); + Golf_UsgaProvince_Db dbUsgaProvince = new Golf_UsgaProvince_Db(ReferenceDbInfo); + qry.Columns.AddRange(dbUsgaProvince.ExistingColumnNames); + qry.Filters.AddRange(GetUsgaProvinceQueryFilter(prm)); + qry.OrderBy.AddRange(GetUsgaProvinceSortColumns(prm)); + // Query data. + using (var dbConnection = ReferenceDatabase.CreateConnection()) + using (var dbCommand = dbConnection.CreateCommand()) + { + try + { + dbConnection.Open(); + dbCommand.CommandText = qry.BuildQuery(prm.ResultsPaging); + using (DbDataReader dbDataReader = dbCommand.ExecuteReader()) + { + while (dbDataReader.Read()) + { + dbUsgaProvince = new Golf_UsgaProvince_Db(ReferenceDbInfo); + dbUsgaProvince.PopulateFrom(dbDataReader); + userRoles.Add(CreateUsgaProvince(dbUsgaProvince)); + } + } + } + catch (Exception exc) + { + SaLogger.Warn(GetType().Name + ".GetUsgaProvinceList\n\tQuery: " + dbCommand.CommandText + "\n\t" + ExceptionUtil.GetLogMessage(exc)); + } + } + return userRoles; + } + + //------------------------------------------------------------------- + // Item query execution. + public override DbResultSet ExecuteUsgaProvinceQuery(List columns, SaxGolfUsgaProvince.Params prm) + { + ClearErrorState(); + + //--------------------------------------------------------------------- + // Construct query. + DbQuery query = new DbQuery(ReferenceDatabase.DbmsType); + query.Tables.Add(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaProvince), aliasUsgaProvince); + + // Add columns as defined in query list. + if (columns.HasId(SaxGolfUsgaProvince.Column.Id)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Id, aliasUsgaProvince)); + bool hasCountryCols = (columns.HasId(SaxGolfUsgaProvince.Column.Country_Name)); + if (columns.HasId(SaxGolfUsgaProvince.Column.CountryId) || hasCountryCols) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_CountryId, aliasUsgaProvince)); + if (columns.HasId(SaxGolfUsgaProvince.Column.ProvinceCode)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceCode, aliasUsgaProvince)); + if (columns.HasId(SaxGolfUsgaProvince.Column.ProvinceName)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_ProvinceName, aliasUsgaProvince)); + // Common properties. + if (columns.HasId(SaxGolfUsgaProvince.Column.Notes)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Notes, aliasUsgaProvince)); + if (columns.HasId(SaxGolfUsgaProvince.Column.Flags)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Flags, aliasUsgaProvince)); + if (columns.HasId(SaxGolfUsgaProvince.Column.Status) || columns.HasId(SaxGolfUsgaProvince.Column.Status_Desc) || columns.HasId(SaxGolfUsgaProvince.Column.Status_Ind)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_Status, aliasUsgaProvince)); + if (columns.HasId(SaxGolfUsgaProvince.Column.CreateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_CreateOn, aliasUsgaProvince)); + if (columns.HasId(SaxGolfUsgaProvince.Column.UpdateOn_Date)) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_UpdateOn, aliasUsgaProvince)); + + //--------------------------------------------------------------------- + // Country. + if (hasCountryCols) + { + DbQueryJoin joinCountry = new DbQueryJoin(DbJoinType.LeftOuter); + joinCountry.Table = new StringPair(SaxDbDfn_Reference.GetTableNameQual(SaxDbDfn_Reference.TableIdx.UsgaCountry), aliasUsgaProvince_Country); + joinCountry.Filters.Add(SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_Id, aliasUsgaProvince_Country) + "=" + SaxDbDfn_Reference.GetColumnNameQual(SaxDbDfn_Reference.ColumnIdx.UsgaProvince_CountryId, aliasUsgaProvince)); + query.Joins.Add(joinCountry); + List cols = new List(); + cols.Add(SaxDbDfn_Reference.ColumnIdx.UsgaCountry_CountryName); + foreach (var col in cols) + query.Columns.Add(SaxDbDfn_Reference.GetColumnNameQual(col, aliasUsgaProvince_Country), prefixUsgaProvince_Country + SaxDbDfn_Reference.GetColumnName(col, false)); + prm.Alias_Country = aliasUsgaProvince_Country; + } + + //--------------------------------------------------------------------- + // Populate filter. + query.Filters.AddRange(GetUsgaProvinceQueryFilter(prm)); + + if (prm.IdsIncluded.Count != 1) + { + // Configure sort sequence. + foreach (String sortColumn in GetUsgaProvinceSortColumns(prm)) + query.OrderBy.Add(sortColumn); + } + + //--------------------------------------------------------------------- + //return new DbResultSet_DataTableReader(db, query.BuildQuery(prm.ResultsPaging)); + return DbResultSet_DataReader.ExecuteQuery(ReferenceDatabase, query.BuildQuery(prm.ResultsPaging)); + } + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas.cs b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas.cs new file mode 100644 index 0000000..dc48915 --- /dev/null +++ b/SaxoniteStandardDbas/Dbas/Mgr/Reference/SaxReferenceGolfMgr_Dbas.cs @@ -0,0 +1,25 @@ +using Saxonite.Net.Standard.Base.App; +using Saxonite.Net.Standard.Base.Mgr.Reference; + +namespace Saxonite.Net.Standard.Dbas.Mgr.Reference +{ + //======================================================================= + public partial class SaxReferenceGolfMgr_Dbas : SaxReferenceGolfMgr + { + //------------------------------------------------------------------- + // Data members. + + //------------------------------------------------------------------- + // Construction. + public SaxReferenceGolfMgr_Dbas(SaxSessionContext sessionContext, SaxInternals internals) : + base(sessionContext, internals) + { + } + + //------------------------------------------------------------------- + // Properties. + + //------------------------------------------------------------------- + } + //======================================================================= +} diff --git a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserEligibility.cs b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserEligibility.cs index 5edd8e5..eeace16 100644 --- a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserEligibility.cs +++ b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserEligibility.cs @@ -404,9 +404,9 @@ namespace Saxonite.Net.Standard.Dbas.Mgr String idsIncluded = prm.IdsIncluded.Concat(","); if (!idsIncluded.IsEmpty()) filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserEligibility_Id, aliasUserEligibility) + " IN (" + idsIncluded + ")"); - String idsxcluded = prm.IdsExcluded.Concat(","); - if (!idsxcluded.IsEmpty()) - filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserEligibility_Id, aliasUserEligibility) + " NOT IN (" + idsxcluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserEligibility_Id, aliasUserEligibility) + " NOT IN (" + idsExcluded + ")"); // User accounts. String userAccountIdsIncluded = prm.UserAccountIdsIncluded.Concat(","); diff --git a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserOrganisation.cs b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserOrganisation.cs index 2bb3fd4..9261e88 100644 --- a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserOrganisation.cs +++ b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserOrganisation.cs @@ -447,9 +447,9 @@ namespace Saxonite.Net.Standard.Dbas.Mgr String idsIncluded = prm.IdsIncluded.Concat(","); if (!idsIncluded.IsEmpty()) filter.Add(colUserOrganisation_Id + " IN (" + idsIncluded + ")"); - String idsxcluded = prm.IdsExcluded.Concat(","); - if (!idsxcluded.IsEmpty()) - filter.Add(colUserOrganisation_Id + " NOT IN (" + idsxcluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(colUserOrganisation_Id + " NOT IN (" + idsExcluded + ")"); // User accounts. String userAccountIdsIncluded = prm.UserAccountIdsIncluded.Concat(","); diff --git a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserRole.cs b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserRole.cs index ecf1a01..bf8f10e 100644 --- a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserRole.cs +++ b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserRole.cs @@ -385,9 +385,9 @@ namespace Saxonite.Net.Standard.Dbas.Mgr String idsIncluded = prm.IdsIncluded.Concat(","); if (!idsIncluded.IsEmpty()) filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserRole_Id, aliasUserRole) + " IN (" + idsIncluded + ")"); - String idsxcluded = prm.IdsExcluded.Concat(","); - if (!idsxcluded.IsEmpty()) - filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserRole_Id, aliasUserRole) + " NOT IN (" + idsxcluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserRole_Id, aliasUserRole) + " NOT IN (" + idsExcluded + ")"); // User accounts. String userAccountIdsIncluded = prm.UserAccountIdsIncluded.Concat(","); diff --git a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserSport.cs b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserSport.cs index 4f2c551..9d65ba1 100644 --- a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserSport.cs +++ b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserSport.cs @@ -408,9 +408,9 @@ namespace Saxonite.Net.Standard.Dbas.Mgr String idsIncluded = prm.IdsIncluded.Concat(","); if (!idsIncluded.IsEmpty()) filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSport_Id, aliasUserSport) + " IN (" + idsIncluded + ")"); - String idsxcluded = prm.IdsExcluded.Concat(","); - if (!idsxcluded.IsEmpty()) - filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSport_Id, aliasUserSport) + " NOT IN (" + idsxcluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSport_Id, aliasUserSport) + " NOT IN (" + idsExcluded + ")"); // User accounts. String userAccountIdsIncluded = prm.UserAccountIdsIncluded.Concat(","); diff --git a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserSportExperience.cs b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserSportExperience.cs index e27bfcf..4686d63 100644 --- a/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserSportExperience.cs +++ b/SaxoniteStandardDbas/Dbas/Mgr/SaxAccountMgr_Dbas-UserSportExperience.cs @@ -427,9 +427,9 @@ namespace Saxonite.Net.Standard.Dbas.Mgr String idsIncluded = prm.IdsIncluded.Concat(","); if (!idsIncluded.IsEmpty()) filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSportExperience_Id, aliasUserSportExperience) + " IN (" + idsIncluded + ")"); - String idsxcluded = prm.IdsExcluded.Concat(","); - if (!idsxcluded.IsEmpty()) - filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSportExperience_Id, aliasUserSportExperience) + " NOT IN (" + idsxcluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSportExperience_Id, aliasUserSportExperience) + " NOT IN (" + idsExcluded + ")"); // User sports. String userSportIdsIncluded = prm.UserSportIdsIncluded.Concat(","); diff --git a/SaxoniteStandardDbas/Dbas/Mgr/SaxActivityMgr_Dbas-UserActivity.cs b/SaxoniteStandardDbas/Dbas/Mgr/SaxActivityMgr_Dbas-UserActivity.cs index aa2e938..2abf745 100644 --- a/SaxoniteStandardDbas/Dbas/Mgr/SaxActivityMgr_Dbas-UserActivity.cs +++ b/SaxoniteStandardDbas/Dbas/Mgr/SaxActivityMgr_Dbas-UserActivity.cs @@ -442,9 +442,9 @@ namespace Saxonite.Net.Standard.Dbas.Mgr String idsIncluded = prm.IdsIncluded.Concat(","); if (!idsIncluded.IsEmpty()) filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSport_Id, aliasUserActivity) + " IN (" + idsIncluded + ")"); - String idsxcluded = prm.IdsExcluded.Concat(","); - if (!idsxcluded.IsEmpty()) - filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSport_Id, aliasUserActivity) + " NOT IN (" + idsxcluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Core.GetColumnNameQual(SaxDbDfn_Core.ColumnIdx.UserSport_Id, aliasUserActivity) + " NOT IN (" + idsExcluded + ")"); // User accounts. String userAccountIdsIncluded = prm.UserAccountIdsIncluded.Concat(","); diff --git a/SaxoniteStandardDbas/Dbas/Mgr/Support/SaxSupportMgr_Dbas-UserReport.cs b/SaxoniteStandardDbas/Dbas/Mgr/Support/SaxSupportMgr_Dbas-UserReport.cs index eca422f..9f90763 100644 --- a/SaxoniteStandardDbas/Dbas/Mgr/Support/SaxSupportMgr_Dbas-UserReport.cs +++ b/SaxoniteStandardDbas/Dbas/Mgr/Support/SaxSupportMgr_Dbas-UserReport.cs @@ -355,9 +355,9 @@ namespace Saxonite.Net.Standard.Dbas.Mgr.Support String idsIncluded = prm.IdsIncluded.Concat(","); if (!idsIncluded.IsEmpty()) filter.Add(SaxDbDfn_Support.GetColumnNameQual(SaxDbDfn_Support.ColumnIdx.UserReport_Id, aliasUserReport) + " IN (" + idsIncluded + ")"); - String idsxcluded = prm.IdsExcluded.Concat(","); - if (!idsxcluded.IsEmpty()) - filter.Add(SaxDbDfn_Support.GetColumnNameQual(SaxDbDfn_Support.ColumnIdx.UserReport_Id, aliasUserReport) + " NOT IN (" + idsxcluded + ")"); + String idsExcluded = prm.IdsExcluded.Concat(","); + if (!idsExcluded.IsEmpty()) + filter.Add(SaxDbDfn_Support.GetColumnNameQual(SaxDbDfn_Support.ColumnIdx.UserReport_Id, aliasUserReport) + " NOT IN (" + idsExcluded + ")"); // User accounts. String userAccountIdsIncluded = prm.UserAccountIdsIncluded.Concat(","); diff --git a/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Core.xml b/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Core.xml index 3b192c0..7d651d8 100644 --- a/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Core.xml +++ b/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Core.xml @@ -1,4 +1,4 @@ - + @@ -1881,7 +1881,7 @@ false false 1 - 2 + 10 false @@ -2373,8 +2373,8 @@ false false false - 4 - 40 + 6 + 52 false @@ -3122,8 +3122,8 @@ false false false - 2 - 16 + 4 + 23 false @@ -7106,7 +7106,7 @@ false false 1 - 7 + 8 false diff --git a/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Reference.xml b/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Reference.xml new file mode 100644 index 0000000..972f647 --- /dev/null +++ b/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Reference.xml @@ -0,0 +1,1701 @@ + + + + + golf + UsgaCountry + + + + golf +
UsgaCountry
+ 1 + Id + BigInt + + -5 + bigint + true + 19 + 8 + 0 + NoNulls + false + + + + golf + UsgaCountry
+ 2 + CountryCode + VarChar + + 12 + varchar + false + 10 + 10 + 0 + NoNulls + false + +
+ + golf + UsgaCountry
+ 3 + CountryName + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCountry
+ 4 + EntCountryCode + VarChar + + 12 + varchar + false + 10 + 10 + 0 + Nullable + true + +
+ + golf + UsgaCountry
+ 5 + Notes + VarChar + + -9 + nvarchar + false + 2000 + 4000 + 0 + NoNulls + false + +
+ + golf + UsgaCountry
+ 6 + Flags + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaCountry
+ 7 + Status + VarChar + + 12 + varchar + false + 3 + 3 + 0 + NoNulls + false + +
+ + golf + UsgaCountry
+ 8 + CreateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaCountry
+ 9 + CreateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaCountry
+ 10 + CreateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+ + golf + UsgaCountry
+ 11 + UpdateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaCountry
+ 12 + UpdateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaCountry
+ 13 + UpdateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+ + + + golf + UsgaCountry
+ PK_Golf_UsgaCountry + 1 + true + false + false + false + 0 + 0 + false + + + 1 + Id + true + + +
+ + golf + UsgaCountry
+ IX_Golf_UsgaCountry_CountryCode + 3 + true + false + false + false + 0 + 0 + false + + + 1 + CountryCode + true + + +
+
+ + + golf + UsgaCourse + + + + golf + UsgaCourse
+ 1 + Id + BigInt + + -5 + bigint + true + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 2 + FacilityId + BigInt + + -5 + bigint + false + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 3 + CourseId + BigInt + + -5 + bigint + false + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 4 + LegacyCrpCourseId + BigInt + + -5 + bigint + false + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 5 + Caption + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 6 + CourseName + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 7 + FullName + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 8 + Address1 + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 9 + Address2 + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 10 + City + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 11 + Email + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 12 + Telephone + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 13 + Notes + VarChar + + -9 + nvarchar + false + 2000 + 4000 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 14 + Flags + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 15 + Status + VarChar + + 12 + varchar + false + 3 + 3 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 16 + CreateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaCourse
+ 17 + CreateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 18 + CreateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 19 + UpdateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaCourse
+ 20 + UpdateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaCourse
+ 21 + UpdateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+
+ + + golf + UsgaCourse
+ PK_Golf_UsgaCourse + 1 + true + false + false + false + 0 + 0 + false + + + 1 + Id + true + + +
+ + golf + UsgaCourse
+ IX_Golf_UsgaCourse_CourseId + 3 + true + false + false + false + 0 + 0 + false + + + 1 + CourseId + true + + +
+ + golf + UsgaCourse
+ IX_Golf_UsgaCourse_Facility + 3 + false + false + false + false + 0 + 0 + false + + + 1 + FacilityId + true + + +
+
+
+ + golf + UsgaFacility + + + + golf + UsgaFacility
+ 1 + Id + BigInt + + -5 + bigint + true + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 2 + ProvinceId + BigInt + + -5 + bigint + false + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 3 + FacilityId + BigInt + + -5 + bigint + false + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 4 + FacilityName + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 5 + Notes + VarChar + + -9 + nvarchar + false + 2000 + 4000 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 6 + Flags + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 7 + Status + VarChar + + 12 + varchar + false + 3 + 3 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 8 + CreateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaFacility
+ 9 + CreateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 10 + CreateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 11 + UpdateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaFacility
+ 12 + UpdateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaFacility
+ 13 + UpdateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+
+ + + golf + UsgaFacility
+ PK_Golf_UsgaFacility + 1 + true + false + false + false + 0 + 0 + false + + + 1 + Id + true + + +
+ + golf + UsgaFacility
+ IX_Golf_UsgaFacility_FacilityId + 3 + true + false + false + false + 0 + 0 + false + + + 1 + FacilityId + true + + +
+ + golf + UsgaFacility
+ IX_Golf_UsgaFacility_Province + 3 + false + false + false + false + 0 + 0 + false + + + 1 + ProvinceId + true + + +
+
+
+ + golf + UsgaMarker + + + + golf + UsgaMarker
+ 1 + Id + BigInt + + -5 + bigint + true + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 2 + CourseId + BigInt + + -5 + bigint + false + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 3 + MarkerId + BigInt + + -5 + bigint + false + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 4 + Caption + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 5 + Holes + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 6 + HolesCaption + VarChar + + -9 + nvarchar + false + 32 + 64 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 7 + Tee + VarChar + + -9 + nvarchar + false + 32 + 64 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 8 + Gender + VarChar + + -9 + nvarchar + false + 32 + 64 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 9 + SlopeRating + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 10 + Par + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 11 + CourseRating + Decimal + + 3 + decimal + false + 9 + 11 + 1 + NoNulls + false + +
+ + golf + UsgaMarker
+ 12 + BogeyRating + Decimal + + 3 + decimal + false + 9 + 11 + 1 + NoNulls + false + +
+ + golf + UsgaMarker
+ 13 + Length + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 14 + Notes + VarChar + + -9 + nvarchar + false + 2000 + 4000 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 15 + Flags + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 16 + Status + VarChar + + 12 + varchar + false + 3 + 3 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 17 + CreateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaMarker
+ 18 + CreateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 19 + CreateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 20 + UpdateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaMarker
+ 21 + UpdateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaMarker
+ 22 + UpdateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+
+ + + golf + UsgaMarker
+ PK_Golf_UsgaMarker + 1 + true + false + false + false + 0 + 0 + false + + + 1 + Id + true + + +
+
+
+ + golf + UsgaProvince + + + + golf + UsgaProvince
+ 1 + Id + BigInt + + -5 + bigint + true + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 2 + CountryId + BigInt + + -5 + bigint + false + 19 + 8 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 3 + ProvinceCode + VarChar + + 12 + varchar + false + 20 + 20 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 4 + EntProvinceCode + VarChar + + 12 + varchar + false + 20 + 20 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 5 + ProvinceName + VarChar + + -9 + nvarchar + false + 200 + 400 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 6 + Notes + VarChar + + -9 + nvarchar + false + 2000 + 4000 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 7 + Flags + SmallInt + + 5 + smallint + false + 5 + 2 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 8 + Status + VarChar + + 12 + varchar + false + 3 + 3 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 9 + CreateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaProvince
+ 10 + CreateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 11 + CreateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 12 + UpdateOn + DateTime + + 93 + datetime + false + 23 + 16 + 3 + NoNulls + false + +
+ + golf + UsgaProvince
+ 13 + UpdateBy + Int + + 4 + int + false + 10 + 4 + 0 + NoNulls + false + +
+ + golf + UsgaProvince
+ 14 + UpdateHost + VarChar + + 12 + varchar + false + 100 + 100 + 0 + NoNulls + false + +
+
+ + + golf + UsgaProvince
+ PK_Golf_UsgaProvince + 1 + true + false + false + false + 0 + 0 + false + + + 1 + Id + true + + +
+ + golf + UsgaProvince
+ IX_Golf_UsgaProvince_ProvinceCode + 3 + true + false + false + false + 0 + 0 + false + + + 1 + ProvinceCode + true + + +
+ + golf + UsgaProvince
+ IX_Golf_UsgaProvince_Country + 3 + false + false + false + false + 0 + 0 + false + + + 1 + CountryId + true + + +
+
+
+ + \ No newline at end of file diff --git a/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Support.xml b/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Support.xml index 6a61cd0..d0895b3 100644 --- a/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Support.xml +++ b/SaxoniteStandardDbas/Resources/Database/SaxDbDfn_Support.xml @@ -1,4 +1,4 @@ - + @@ -290,7 +290,7 @@ false false 1 - 4 + 5 false diff --git a/SaxoniteStandardDbas/SaxoniteStandardDbas.csproj b/SaxoniteStandardDbas/SaxoniteStandardDbas.csproj index c58064c..548af7c 100644 --- a/SaxoniteStandardDbas/SaxoniteStandardDbas.csproj +++ b/SaxoniteStandardDbas/SaxoniteStandardDbas.csproj @@ -17,6 +17,7 @@ + diff --git a/SaxoniteWebApi/Api/App/SaxApplication_Api.cs b/SaxoniteWebApi/Api/App/SaxApplication_Api.cs index dd5e303..100787e 100644 --- a/SaxoniteWebApi/Api/App/SaxApplication_Api.cs +++ b/SaxoniteWebApi/Api/App/SaxApplication_Api.cs @@ -1,15 +1,21 @@ using Microsoft.Identity.Client; using Sarand.Net.Standard.Base.App; +using Sarand.Net.Standard.Base.Bus; using Sarand.Net.Standard.Base.Dbas; using Sarand.Net.Standard.Base.Helpers; using Sarand.Net.Standard.Base.IO; +using Sarand.Net.Standard.Base.Net; using Sarand.Net.Standard.Base.Utils; using Saxonite.Net.Core.Web.Base.App; using Saxonite.Net.Core.Web.Base.Helpers; +using Saxonite.Net.Core.Web.Base.Procs; using Saxonite.Net.Standard.Base.App; using Saxonite.Net.Standard.Base.Consoles; using Saxonite.Net.Standard.Base.Helpers; using Saxonite.Web.Api.Consoles; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using static Saxonite.Net.Core.Web.Base.App.SaxAppConfig; @@ -31,7 +37,7 @@ namespace Saxonite.Web.Api.App //------------------------------------------------------------------- // Construction. - public SaxApplication_Api() + public SaxApplication_Api(WebApplication app) : base(Sax.Application.Api) { InitialiseTemporaryLoggingFolder(); try @@ -39,12 +45,19 @@ namespace Saxonite.Web.Api.App AppInstance = this; ConsoleHelper_Api = new SaxConsoleHelper_Api(this); - // Logging configuration. - SaLogger.LogFilenamePrefix = "Sax-Web-Api"; - SaLogger.IncludeHostInFileMessage = false; - SaLogger.IncludeUserInFileMessage = false; - + // Application configuration. + InitEnvironment(app.Environment, "Sax-Web-Api"); LoadConfiguration(); + + // Test API calls. + Timer? timer = null; + timer = + new Timer((obj) => + { + new Thread(new ThreadStart(() => { TestApi(); })).Start(); + if (timer != null) timer.Dispose(); + }, + null, 1000, Timeout.Infinite); } catch (Exception exc) { @@ -82,27 +95,12 @@ namespace Saxonite.Web.Api.App if (SaxSystem.ComputerName.EqualsCI("Sarand601")) environmentName = Environments.Production; - // Load server configuration. - var builder = - new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false) - .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: false) - .AddJsonFile($"appsettings.machine.{SaxSystem.ComputerName}.json", optional: true, reloadOnChange: false) - .AddEnvironmentVariables(); - Stream configStream = SaxResourceHelper.GetResourceStream("appsettings.json", "Config"); - if (configStream != null) builder.AddJsonStream(configStream); - configStream = SaxResourceHelper.GetResourceStream($"appsettings.{environmentName}.json", "Config"); - if (configStream != null) builder.AddJsonStream(configStream); - configStream = SaxResourceHelper.GetResourceStream($"appsettings.machine.{SaxSystem.ComputerName}.json", "Config"); - if (configStream != null) builder.AddJsonStream(configStream); - SaxConfiguration = builder.Build(); - // Application configuration. appConfigs = SaxAppConfigHelper.ExtractAppConfigs(SaxConfiguration.GetSection("AppConfigs")); emailConfigs = SaxEmailConfigHelper.ExtractEmailConfigs(SaxConfiguration.GetSection("EmailConfigs")); + + // Ensure root log folder ends with 'Api' folder. LoggingRootFolder = AppConfig.Logging.RootFolder; - // Ensure root log folder ends with Api folder. if (!StringUtil.IsBlank(LoggingRootFolder) && !Regex.IsMatch(LoggingRootFolder, "[\\\\/]Api$", RegexOptions.IgnoreCase)) LoggingRootFolder = StringUtil.CombineFilePath(LoggingRootFolder, "Api"); @@ -123,8 +121,9 @@ namespace Saxonite.Web.Api.App LogApplicationStart(SysUtil.Fn); // Session context - only one context available/necessary (for now). - SessionContextData_Api sessionContextData = new SessionContextData_Api(new SaxSessionContext_Web(100, Sax.Application.Api)); + SessionContextData_Api sessionContextData = new SessionContextData_Api(new SaxSessionContext_Web(100, ApplicationType)); ConfigureDatabaseConnection(sessionContextData, Sax.Database.Core); + ConfigureDatabaseConnection(sessionContextData, Sax.Database.Reference); ConfigureDatabaseConnection(sessionContextData, Sax.Database.Support); sessionContexts.Add(sessionContextData.SessionContext.Index, sessionContextData); SessionContext = sessionContextData.SessionContext; @@ -135,6 +134,85 @@ namespace Saxonite.Web.Api.App } } + //------------------------------------------------------------------- + private void TestApi() + { + // Allows you to bypass "AuthenticationException: The remote certificate is invalid according to the validation procedure." error. Don't to do this in production code... + //ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; }; + + if (false) + { + CancellationToken cancelToken = new CancellationToken(); + SacsHttpClientHelper.RequestData request = new SacsHttpClientHelper.RequestData(cancelToken); + request.UriBuilder.ConfigureSslUriBuilder("api.sportierre.com", "System/Version"); + request.ContentHeaders.Add(SacsHttpClientHelper.HeaderName_ContentType, "application/json"); + request.PostData = "{}"; + //request.ForcePost = true; + request.Debug = true; + SacsHttpClientHelper.ResponseData response = SacsHttpClientHelper.DoRequest(request).Result; + String responseData = response.Data; + } + + if (false) + { + CancellationToken cancelToken = new CancellationToken(); + SacsHttpRequestData request = new SacsHttpRequestData(cancelToken); + request.Url = "https://api.sportierre.com/System/Version"; + request.PostData = "{}"; + request.ContentHeaders.Add(SacsHttpClient.HeaderName_ContentType, "application/json"); + //request.ForcePost = true; + request.Debug = true; + SacsHttpResponseData response = SacsHttpClient.DoRequest(request).Result; + String data = response.Data; + } + + DbUpdateInfo dbUpdateInfo = new DbUpdateInfo(new SysId(), "ApiApp", SacsSystem.ComputerName); + + if (false) + { + // USGA Countries. + SaxGolfUsgaDataLookup.Config courseLookupConfig = new SaxGolfUsgaDataLookup.Config(SessionContext, dbUpdateInfo); + SaxGolfUsgaDataLookup courseLookup = new SaxGolfUsgaDataLookup(courseLookupConfig); + List countries = courseLookup.LookupUsgaCountries(); + foreach (SaxGolfUsgaDataLookup.CountryData country in countries) + { + } + } + + if (false) + { + // USGA Provinces. + SaxGolfUsgaDataLookup.Config courseLookupConfig = new SaxGolfUsgaDataLookup.Config(SessionContext, dbUpdateInfo); + SaxGolfUsgaDataLookup courseLookup = new SaxGolfUsgaDataLookup(courseLookupConfig); + List provinces = courseLookup.LookupUsgaProvincesForCountry("ENG"); + foreach (SaxGolfUsgaDataLookup.ProvinceData province in provinces) + { + } + } + + if (false) + { + // USGA Courses. + SaxGolfUsgaDataLookup.Config courseLookupConfig = new SaxGolfUsgaDataLookup.Config(SessionContext, dbUpdateInfo); + SaxGolfUsgaDataLookup courseLookup = new SaxGolfUsgaDataLookup(courseLookupConfig); + List courses = courseLookup.LookupUsgaCoursesForCountryAndProvince("ENG", "GB-NFK"); + foreach (SaxGolfUsgaDataLookup.CourseData course in courses) + { + } + } + + if (false) + { + // USGA Courses. + SaxGolfUsgaDataLookup.Config courseLookupConfig = new SaxGolfUsgaDataLookup.Config(SessionContext, dbUpdateInfo); + SaxGolfUsgaDataLookup courseLookup = new SaxGolfUsgaDataLookup(courseLookupConfig); + List markers = courseLookup.LookupUsgaMarkersForCourse(new SysId(20249)); + foreach (SaxGolfUsgaDataLookup.MarkerData marker in markers) + { + } + } + } + //------------------------------------------------------------------- } //======================================================================= diff --git a/SaxoniteWebApi/Api/Controllers/SystemController.cs b/SaxoniteWebApi/Api/Controllers/SystemController.cs index b29730e..a20296d 100644 --- a/SaxoniteWebApi/Api/Controllers/SystemController.cs +++ b/SaxoniteWebApi/Api/Controllers/SystemController.cs @@ -24,6 +24,12 @@ namespace Saxonite.Web.Api.Controllers { public String? Version { get; set; } } + [HttpGet] + [Route("[controller]/Version")] + public ResponseData_Version GetVersion_Get() + { + return GetVersion_Post(new RequestData_Version()); + } [HttpPost] [Route("[controller]/Version")] public ResponseData_Version GetVersion_Post(RequestData_Version requestData) diff --git a/SaxoniteWebApi/Api/Procs/SaxProcess_Api.cs b/SaxoniteWebApi/Api/Procs/SaxProcess_Api.cs index fdcbe52..6325ca6 100644 --- a/SaxoniteWebApi/Api/Procs/SaxProcess_Api.cs +++ b/SaxoniteWebApi/Api/Procs/SaxProcess_Api.cs @@ -1,17 +1,19 @@ -using Sarand.Net.Standard.Proc.Excel; +using Sarand.Net.Standard.Base.Dbas; +using Sarand.Net.Standard.Proc.Excel; +using Saxonite.Net.Core.Web.Base.Procs; using Saxonite.Net.Standard.Base.App; using Saxonite.Net.Standard.Base.Procs; namespace Saxonite.Web.Api.Procs { //======================================================================= - public abstract class SaxProcess_Api : SaxProcess_Base + public abstract class SaxProcess_Api : SaxProcess_Web { //------------------------------------------------------------------- // Definitions. - public new class Config : SaxProcess_Base.Config + public new class Config : SaxProcess_Web.Config { - protected Config(SaxSessionContext sessionContext) : base(sessionContext) + protected Config(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo) : base(sessionContext, dbUpdateInfo) { } } diff --git a/SaxoniteWebApi/Program.cs b/SaxoniteWebApi/Program.cs index d7da21d..60a7db0 100644 --- a/SaxoniteWebApi/Program.cs +++ b/SaxoniteWebApi/Program.cs @@ -2,8 +2,6 @@ using Saxonite.Web.Api.App; using System.Text.Json.Serialization; { - // Saxonite API application. - var application = new SaxApplication_Api(); var builder = WebApplication.CreateBuilder(args); @@ -20,6 +18,9 @@ using System.Text.Json.Serialization; var app = builder.Build(); + // Saxonite API application. + var application = new SaxApplication_Api(app); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/SaxoniteWebApi/SaxoniteWebApi.csproj b/SaxoniteWebApi/SaxoniteWebApi.csproj index 50be495..5ffff9f 100644 --- a/SaxoniteWebApi/SaxoniteWebApi.csproj +++ b/SaxoniteWebApi/SaxoniteWebApi.csproj @@ -9,7 +9,7 @@ - +