This commit is contained in:
2024-06-04 16:15:09 +01:00
parent e40876aeb2
commit 2f6395485a
123 changed files with 11943 additions and 314 deletions
@@ -9,11 +9,11 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="MSTest.TestAdapter" Version="3.2.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.2.1" />
<PackageReference Include="coverlet.collector" Version="6.0.1">
<PackageReference Include="MSTest.TestAdapter" Version="3.4.3" />
<PackageReference Include="MSTest.TestFramework" Version="3.4.3" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
@@ -9,11 +9,11 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="MSTest.TestAdapter" Version="3.2.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.2.1" />
<PackageReference Include="coverlet.collector" Version="6.0.1">
<PackageReference Include="MSTest.TestAdapter" Version="3.4.3" />
<PackageReference Include="MSTest.TestFramework" Version="3.4.3" />
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
+1
View File
@@ -100,6 +100,7 @@ namespace Saxonite.Net.Core.Web.Base.App
{
public Dictionary<Sax.Database, DatabaseConfig> Databases { get; } = new Dictionary<Sax.Database, DatabaseConfig>();
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();
+57 -4
View File
@@ -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<Sax.Database, ISacsDatabase> Databases { get; } = new Dictionary<Sax.Database, ISacsDatabase>();
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);
}
+5 -1
View File
@@ -63,7 +63,8 @@ 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<SaxAuthenticationHandler>("forbidScheme", "Handle Forbidden");
@@ -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
@@ -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; }
//-------------------------------------------------------------------
/// <summary>
/// Periodic processing to execute application processes as required.
/// </summary>
protected abstract void DoWork(object state);
//-------------------------------------------------------------------
/// <summary>
/// Triggered when the application host is ready to start the service.
/// </summary>
/// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
/// <returns></returns>
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;
}
/// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// </summary>
/// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
/// <returns></returns>
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;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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<TypeCodeDesc> DataItemTypeCodes { get { return Internals.DataItemTypeCodes; } }
@@ -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;
// 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,6 +95,8 @@ namespace Saxonite.Net.Core.Web.Base.Middleware
}
// Log property details.
if (result.Model != null && SaxSystem.DebugMode &&
// 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.
@@ -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<TypeCodeDesc> DataItemTypeCodes { get { return Internals.DataItemTypeCodes; } }
@@ -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();
/// <summary>
/// Determine which USGA data population process to run.
/// <para>- Method is invoked periodically (every 20 mins) by the Admin Hosted Service Console.</para>
/// <para>- 1. Populate countries if not already done or not done for a while (eg. 24 hours).</para>
/// <para>- 2. Populate provinces for a Country that has none or occasionally to refresh one that has.</para>
/// <para>- 3. Populate Courses for a Province that has none or occasionally to refresh one that has.</para>
/// <para>- 4. Populate Courses for a Province that has none or occasionally to refresh one that has.</para>
/// </summary>
public static void ExecuteScheduledUsgaDataLookup(SaxSessionContext sessionContext, DbUpdateInfo dbUpdateInfo, SacsTaskData taskData)
{
SaLogger.Debug($"{SysUtil.Fn}");
using (DisposableCollection<SacsDisposable> disposableItems = new DisposableCollection<SacsDisposable>())
{
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<SaxGolfUsgaCountry> 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<SaxGolfUsgaDataLookup.CountryData> 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<SaxGolfUsgaCountry> usgaCountriesWithProvinces = new List<SaxGolfUsgaCountry>();
List<SaxGolfUsgaCountry> usgaCountriesWithNoProvinces = new List<SaxGolfUsgaCountry>();
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<SaxGolfUsgaDataLookup.ProvinceData> 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<SaxGolfUsgaProvince> usgaProvinces = internals.ReferenceGolfMgr.GetUsgaProvinceList(prmUsgaProvince).OrderBy(_ => SacsRandomHelper.GetInt32(Int32.MaxValue)).ToList();
if (usgaProvinces.Any())
{
// Refresh Country Provinces.
List<SaxGolfUsgaDataLookup.ProvinceData> 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<SaxGolfUsgaProvince> usgaProvincesWithFacilities = new List<SaxGolfUsgaProvince>();
List<SaxGolfUsgaProvince> usgaProvincesWithNoFacilities = new List<SaxGolfUsgaProvince>();
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<SaxGolfUsgaDataLookup.CourseData> 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<SaxGolfUsgaDataLookup.CourseData> 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<SaxGolfUsgaCourse> usgaCourses = internals.ReferenceGolfMgr.GetUsgaCourseList(prmCourse).OrderBy(_ => SacsRandomHelper.GetInt32(Int32.MaxValue)).ToList();
List<SaxGolfUsgaCourse> usgaCoursesWithMarkers = new List<SaxGolfUsgaCourse>();
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<SaxGolfUsgaDataLookup.MarkerData> 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<SaxGolfUsgaDataLookup.MarkerData> 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<SaxGolfUsgaDataLookup.CourseData> 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<SaxGolfUsgaDataLookup.ProvinceData> provincesData = usgaDataLookup.LookupUsgaProvincesForCountry(usgaCountry.CountryCode);
SaLogger.Info($"{SysUtil.Fn} USGA Provinces populated for {usgaCountry.CountryCode} {usgaCountry.CountryName}: {provincesData.Count}. [Fallback]", true);
return;
}
}
}
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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<String> Ratings { get; } = new List<string>();
}
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.
//------------------------------------------------------------------
/// <summary>
/// Data elements that may be required in subsequent requests etc.
/// </summary>
private class UsgaRequestData
{
public DateTime PopulatedAt { get; } = DateTime.Now;
public Dictionary<String, SacsHttpCookieData> Cookies { get; } = new Dictionary<String, SacsHttpCookieData>();
public String RequestVerificationToken { get; set; }
}
private UsgaRequestData usgaRequestData = null;
/// <summary>
/// Populate the request data from the Home Page response.
/// </summary>
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));
}
}
/// <summary>
/// Get the USGA request data to extract useful elements, eg. verification token and cookies.
/// <para>- Request data is refreshed periodically in case of expiry.</para>
/// </summary>
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;
}
//------------------------------------------------------------------
/// <summary>
/// USGA Countries.
/// <para>- Countries are listed on the home page of the USGA site in a dropdown.</para>
/// </summary>
public List<CountryData> LookupUsgaCountries()
{
List<CountryData> usgaCountries = new List<CountryData>();
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<SaxReferenceGolfMgr.UsgaCountryData> countriesData = new List<SaxReferenceGolfMgr.UsgaCountryData>();
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;
}
//------------------------------------------------------------------
/// <summary>
/// USGA Provinces for country.
/// </summary>
public List<ProvinceData> LookupUsgaProvincesForCountry(String countryCode)
{
List<ProvinceData> usgaProvinces = new List<ProvinceData>();
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<string, string>("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<SaxReferenceGolfMgr.UsgaProvinceData> provincesData = new List<SaxReferenceGolfMgr.UsgaProvinceData>();
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;
}
//------------------------------------------------------------------
/// <summary>
/// USGA Courses for country.
/// </summary>
public List<CourseData> LookupUsgaCoursesForCountryAndProvince(String countryCode, String provinceCode)
{
List<CourseData> usgaCourses = new List<CourseData>();
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<string, string>("clubName", ""));
request.FormData.Add(new KeyValuePair<string, string>("clubCity", ""));
request.FormData.Add(new KeyValuePair<string, string>("clubState", provinceCode));
request.FormData.Add(new KeyValuePair<string, string>("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<String> UnrecognisedCourseProperties = new HashSet<string>(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<String, SaxReferenceGolfMgr.UsgaCountryData> countriesData = new Dictionary<String, SaxReferenceGolfMgr.UsgaCountryData>();
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<String, SaxReferenceGolfMgr.UsgaProvinceData> provincesData = new Dictionary<String, SaxReferenceGolfMgr.UsgaProvinceData>();
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<SysId, SaxReferenceGolfMgr.UsgaFacilityData> facilitiesData = new Dictionary<SysId, SaxReferenceGolfMgr.UsgaFacilityData>();
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<SysId, SaxReferenceGolfMgr.UsgaCourseData> coursesData = new Dictionary<SysId, SaxReferenceGolfMgr.UsgaCourseData>();
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;
}
/// <summary>
/// Combine facility and course names as required to generate course caption.
/// <para>- NB Course name is sufficient if same as facility name.</para>
/// </summary>
/// <param name="course"></param>
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;
}
/// <summary>
/// Cleanse Facility name by removing generic phrases, eg. golf club, hotel etc.
/// </summary>
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);
}
/// <summary>
/// Cleanse Course name by removing generic phrases, including those defined for facility name.
/// </summary>
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;
}
//------------------------------------------------------------------
/// <summary>
/// Identify the column for each marker property.
/// </summary>
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;
}
/// <summary>
/// USGA Markers for course.
/// </summary>
public List<MarkerData> LookupUsgaMarkersForCourse(SysId usgaCourseId)
{
List<MarkerData> usgaMarkers = new List<MarkerData>();
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<SaxReferenceGolfMgr.UsgaMarkerData> markersData = new List<SaxReferenceGolfMgr.UsgaMarkerData>();
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;
}
//------------------------------------------------------------------
}
//======================================================================
}
@@ -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;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
+2 -1
View File
@@ -23,7 +23,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.16" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.61" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.30" />
</ItemGroup>
<ItemGroup>
@@ -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<String, SaxAppConfig> appConfigs = new Dictionary<string, SaxAppConfig>();
private Dictionary<String, SaxEmailConfig> emailConfigs = new Dictionary<string, SaxEmailConfig>();
@@ -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
/// <summary>Initialise environment - from internal (above) or unit tests.</summary>
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))
@@ -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);
@@ -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<SaxHostedServiceConsole_Admin>();
}
//-------------------------------------------------------------------
@@ -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 }
/// <summary>
/// Process tracking data to control when process is run.
/// </summary>
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<ProcessType, ProcessControlData> processes { get; } = new Dictionary<ProcessType, ProcessControlData>();
//-------------------------------------------------------------------
// Construction.
public SaxHostedServiceConsole_Admin()
{
InitialiseProcesses();
}
//-------------------------------------------------------------------
// Clean-up.
protected override void Dispose(bool disposing)
{
}
//-------------------------------------------------------------------
/// <summary>
/// Periodic processing to execute application processes as required.
/// <para>- See parent class for timer logic.</para>
/// </summary>
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);
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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);
@@ -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);
@@ -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);
}
/// <summary>Set the 'Keep Logged In' response cookie to expired with no data.</summary>
@@ -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<SacsDisposable> disposableItems = new DisposableCollection<SacsDisposable>())
{
// 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<String, int> tableRowCounts = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
@@ -83,7 +83,7 @@ namespace Saxonite.Net.Core.Web.Admin.Controllers
}
}
// Core database tables.
// Database tables.
List<DbDfnTable> 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);
@@ -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<LogFolderData> Folders { get; } = new List<LogFolderData>();
}
//-------------------------------------------------------------------
/// <summary>
/// Retrieve the list of folders under the root folder.
/// <para>- These should correspond to applications (admin, api, online etc).</para>
/// </summary>
[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<LogFolderData> Years { get; } = new List<LogFolderData>();
}
//-------------------------------------------------------------------
/// <summary>
/// Retrieve the list of year folders under the selected folder.
/// </summary>
[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<LogFolderData> Months { get; } = new List<LogFolderData>();
}
//-------------------------------------------------------------------
/// <summary>
/// Retrieve the list of year folders under the selected folder.
/// </summary>
[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<LogFileData> Tables { get; } = new List<LogFileData>();
public List<LogFileData> Files { get; } = new List<LogFileData>();
}
//-------------------------------------------------------------------
[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<String> classNames = new List<string>();
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 += $"<div class='{String.Join(" ", classNames)}'>" + line + "</div>";
}
}
catch (Exception exc)
{
SaLogger.Warn($"{SysUtil.Fn} {ExceptionUtil.GetLogMessage(exc, "reading log file", 0)}");
}
// Complete response.
responseData.Success = true;
@@ -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);
}
@@ -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<SelectListItem> GetDatabases()
{
List<CodeDesc> items = new List<CodeDesc>();
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();
@@ -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);
@@ -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);
}
@@ -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;
}
@@ -273,6 +273,9 @@
<data name="label.contact" xml:space="preserve">
<value>Contact</value>
</data>
<data name="label.core" xml:space="preserve">
<value>Core</value>
</data>
<data name="label.country" xml:space="preserve">
<value>Country</value>
</data>
@@ -327,6 +330,9 @@
<data name="label.first.name" xml:space="preserve">
<value>First name</value>
</data>
<data name="label.folder" xml:space="preserve">
<value>Folder</value>
</data>
<data name="label.forgotten.password" xml:space="preserve">
<value>Forgotten password?</value>
</data>
@@ -348,6 +354,9 @@
<data name="label.indices" xml:space="preserve">
<value>Indices</value>
</data>
<data name="label.instance" xml:space="preserve">
<value>Instance</value>
</data>
<data name="label.iso2.code" xml:space="preserve">
<value>ISO2 code</value>
</data>
@@ -387,6 +396,9 @@
<data name="label.method" xml:space="preserve">
<value>Method</value>
</data>
<data name="label.month" xml:space="preserve">
<value>Month</value>
</data>
<data name="label.name" xml:space="preserve">
<value>Name</value>
</data>
@@ -474,6 +486,9 @@
<data name="label.roles" xml:space="preserve">
<value>Roles</value>
</data>
<data name="label.root.folder" xml:space="preserve">
<value>Root folder</value>
</data>
<data name="label.rows" xml:space="preserve">
<value>Rows</value>
</data>
@@ -552,6 +567,9 @@
<data name="label.value" xml:space="preserve">
<value>Value</value>
</data>
<data name="label.year" xml:space="preserve">
<value>Year</value>
</data>
<data name="label.yes" xml:space="preserve">
<value>Yes</value>
</data>
@@ -756,18 +774,24 @@
<data name="sport.caption.sports" xml:space="preserve">
<value>Sports</value>
</data>
<data name="system.caption.core.database.schema" xml:space="preserve">
<value>Core Database Schema</value>
</data>
<data name="system.caption.database" xml:space="preserve">
<value>System - Database</value>
</data>
<data name="system.caption.database.core" xml:space="preserve">
<value>Core Database</value>
</data>
<data name="system.caption.database.reference" xml:space="preserve">
<value>Reference Database</value>
</data>
<data name="system.caption.database.schemas" xml:space="preserve">
<value>Database schemas</value>
</data>
<data name="system.caption.database.support" xml:space="preserve">
<value>Support Database</value>
</data>
<data name="system.caption.logs" xml:space="preserve">
<value>System - Logs</value>
</data>
<data name="system.caption.support.database.schema" xml:space="preserve">
<value>Support Database Schema</value>
</data>
<data name="system.msg.database.schema.valid" xml:space="preserve">
<value>Database schema is valid.</value>
</data>
@@ -10,7 +10,7 @@
<ItemGroup>
<PackageReference Include="jQuery.UI.Combined" Version="1.13.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.16" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.30" />
<PackageReference Include="System.Collections.Specialized" Version="4.3.0" />
</ItemGroup>
+42 -30
View File
@@ -55,44 +55,56 @@
@* Database Schema form. *@
@using (@Html.BeginForm(FormMethod.Post, new { @id = "frmDatabaseSchema" }))
{
<input type="hidden" name="DatabaseInstance" class="DatabaseInstance" />
<input type="hidden" name="DatabaseFilter.Instance" class="DatabaseInstance" />
}
@* Database Schema - Core *@
<div class="sax-panel-info sax-panel-results DbSchema Core">
@* Database Schema Verification *@
<div class="sax-panel-info sax-panel-results">
<div class="sax-header">
<div class="sax-caption">@Localiser["system.caption.core.database.schema"]</div>
</div>
<div class="sax-content">
<div class="sax-panel-messages"></div>
<div class="sax-panel-item-list"></div>
<div class="sax-panel-item-template">
@* Db Schema templates *@
<div class="sax-panel-item DbSchemaItem">
<div class="sax-header">
<div class="sax-caption SchemaTable">@(Localiser["label.table"]): <span class="TableName"></span></div>
</div>
<div class="sax-content">
<div class="SchemaIndex">@(Localiser["label.index"]): <span class="IndexName"></span></div>
<div class="SchemaColumn">@(Localiser["label.column"]): <span class="ColumnName"></span></div>
<div class=""><span class="Comment"></span></div>
</div>
</div>
</div>
</div>
</div>
@* Database Schema - Support *@
<div class="sax-panel-info sax-panel-results DbSchema Support">
<div class="sax-header">
<div class="sax-caption">@Localiser["system.caption.support.database.schema"]</div>
<div class="sax-caption">@Localiser["system.caption.database.schemas"]</div>
</div>
<div class="sax-content">
@* Database Schema - Core *@
<div class="sax-panel-info DbSchema Core">
<div class="sax-header">
<div class="sax-caption">@Localiser["system.caption.database.core"]</div>
</div>
<div class="sax-content">
<div class="sax-panel-messages"></div>
<div class="sax-panel-item-list"></div>
</div>
</div>
@* Database Schema - Reference *@
<div class="sax-panel-info DbSchema Reference">
<div class="sax-header">
<div class="sax-caption">@Localiser["system.caption.database.reference"]</div>
</div>
<div class="sax-content">
<div class="sax-panel-messages"></div>
<div class="sax-panel-item-list"></div>
</div>
</div>
@* Database Schema - Reference *@
<div class="sax-panel-info DbSchema Support">
<div class="sax-header">
<div class="sax-caption">@Localiser["system.caption.database.support"]</div>
</div>
<div class="sax-content">
<div class="sax-panel-messages"></div>
<div class="sax-panel-item-list"></div>
</div>
</div>
<div class="sax-panel-item-template">
@* Db Schema templates *@
<div class="sax-panel-item DbSchemaItem">
@@ -17,8 +17,10 @@
@using (@Html.BeginForm(FormMethod.Post, new { @id = "frmDbTableFilter", @class = "sax-form", @onSubmit = "return false;" }))
{
<div class="row">
<div class="col-sm-5 sax-label text-left text-sm-right">@Localiser["label.search"]</div>
<div class="col-sm-7">@Html.TextBoxFor(model => model.DatabaseFilter.Search, new { @id = "ifFilterDatabaseTable", @class = "FilterDatabaseTable", @maxlength = "32" })</div>
<div class="col-sm-5 col-md-3 sax-label text-left text-sm-right">@Localiser["label.instance"]</div>
<div class="col-sm-7 col-md-3 mb-sm-1 mb-md-0">@Html.DropDownListFor(model => model.DatabaseFilter.Instance, Model.GetDatabases(), new { @id = "cbDatabaseFilterInstance", @class = "DatabaseFilterInstance" })</div>
<div class="col-sm-5 col-md-3 sax-label text-left text-sm-right">@Localiser["label.search"]</div>
<div class="col-sm-7 col-md-3">@Html.TextBoxFor(model => model.DatabaseFilter.Search, new { @id = "ifDatabaseFilterSearch", @class = "DatabaseFilterSearch", @maxlength = "32" })</div>
</div>
}
</div>
@@ -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 @@
<div class="">
@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" })
}
<table>
+69 -12
View File
@@ -4,7 +4,43 @@
ViewData["Title"] = "System - Logs";
}
<div class="container-fluid">
<style>
#dlgLogFile .FileData
{
font-family: Courier New, Courier, monospace;
font-size: 10px;
color: slategray;
overflow-x: auto;
overflow-y: auto;
}
#dlgLogFile .FileData .tab
{
padding-left: 16px;
}
#dlgLogFile .FileData .tab2
{
padding-left: 32px;
}
#dlgLogFile .FileData .err
{
color: darkred;
}
#dlgLogFile .FileData .wrn
{
color: darkorange;
}
#dlgLogFile .FileData .inf
{
color: darkGreen;
}
</style>
<div class="container-fluid LogFiles">
<div class="sax-panel-filter">
<div class="sax-header row">
@@ -16,29 +52,50 @@
<div class="sax-content">
@using (@Html.BeginForm(FormMethod.Post, new { @id = "frmLogsFilter", @class = "sax-form", @onSubmit = "return false;" }))
{
<input type="hidden" name="LogsFilter.Filename" class="FilterLogFilename" />
<div class="row mb-2">
<div class="col-sm-5 sax-label text-left text-sm-right">@Localiser["label.root.folder"]</div>
<div class="col-sm-7 sax-value">@(Model.LoggingRootFolder)</div>
</div>
<div class="row mb-2">
<div class="col-sm-5 sax-label text-left text-sm-right">@Localiser["label.folder"]</div>
<div class="col-sm-7"><div style="max-width:200px;"><select id="cbFilterLogFolder" name="LogsFilter.Folder" class="FilterLogFolder"></select></div></div>
</div>
<div class="row mb-2">
<div class="col-sm-5 sax-label text-left text-sm-right">@Localiser["label.year"]</div>
<div class="col-sm-7"><div style="max-width:200px;"><select id="cbFilterLogYear" name="LogsFilter.Year" class="FilterLogYear"></select></div></div>
</div>
<div class="row">
<div class="col-sm-5 sax-label text-left text-sm-right">@Localiser["label.filename"]</div>
<div class="col-sm-7">@Html.TextBoxFor(model => model.LogsFilter.Filename, new { @id = "ifFilterLogFilename", @class = "FilterLogFilename", @maxlength = "32" })</div>
<div class="col-sm-5 sax-label text-left text-sm-right">@Localiser["label.month"]</div>
<div class="col-sm-7"><div style="max-width:200px;"><select id="cbFilterLogMonth" name="LogsFilter.Month" class="FilterLogMonth"></select></div></div>
</div>
}
</div>
</div>
<div class="sax-panel-results">
</div>
<div class="sax-panel-messages"></div>
<div class="sax-panel-item-list"></div>
<div class="sax-panel-item-template">
<div class="sax-panel-item LogFile">
<div class="sax-header row">
<div class="col">
<div class="sax-caption"><div class="sax-action Filename"></div></div>
</div>
<div class="fixed sax-actions">
<div class="sax-content">
<div class="row">
<div class="col"><div class="sax-action Filename"></div></div>
<div class=" text-right"><span class="Length"></span></div>
</div>
</div>
<div class="sax-content"></div>
</div>
</div>
</div>
<div id="dlgLogFile" class="sax-dialog">
<div class="sax-data FileData"></div>
</div>
</div>
<script>
sax.data.logFolder = '@(Localiser.EscapeJavascriptText(Model.LogsFilter.Folder))';
sax.data.logYear = '@(Localiser.EscapeJavascriptText(Model.LogsFilter.Year))';
sax.data.logMonth = '@(Localiser.EscapeJavascriptText(Model.LogsFilter.Month))';
</script>
@@ -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"
}
}
]
+27 -1
View File
@@ -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;
+11 -5
View File
@@ -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($('<div class="sax-message">' + sax.msg.dataQuerying + '</div>')).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($('<div class="sax-message">' + sax.msg.dbSchemaValid + '</div>')).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);
+7 -7
View File
@@ -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;
}
@@ -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');
+199 -1
View File
@@ -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($('<div class="sax-message">' + sax.msg.dataQuerying + '</div>')).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($('<div class="sax-message">' + sax.msg.dataNoneFound + '</div>')).fadeIn(500);
for (let itemIdx = 0; itemIdx < items.length; itemIdx++)
$ctrl.cbFolders.append($('<option value="' + items[itemIdx].name + '">' + items[itemIdx].name + '</option>'));
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($('<div class="sax-message">' + sax.msg.dataQuerying + '</div>')).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($('<div class="sax-message">' + sax.msg.dataNoneFound + '</div>')).fadeIn(500);
for (let itemIdx = 0; itemIdx < items.length; itemIdx++)
$ctrl.cbYears.append($('<option value="' + items[itemIdx].name + '">' + items[itemIdx].name + '</option>'));
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($('<div class="sax-message">' + sax.msg.dataQuerying + '</div>')).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($('<div class="sax-message">' + sax.msg.dataNoneFound + '</div>')).fadeIn(500);
for (let itemIdx = 0; itemIdx < items.length; itemIdx++)
$ctrl.cbMonths.append($('<option value="' + items[itemIdx].name + '">' + items[itemIdx].name + '</option>'));
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($('<div class="sax-message">' + sax.msg.dataQuerying + '</div>')).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($('<div class="sax-message">' + sax.msg.dataNoneFound + '</div>')).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($('<div class="sax-message">' + sax.msg.dataQuerying + '</div>')).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));
@@ -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
/// <summary>Initialise environment - from internal (above) or unit tests.</summary>
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;
@@ -10,7 +10,7 @@
<ItemGroup>
<PackageReference Include="jQuery.UI.Combined" Version="1.13.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="3.1.16" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.30" />
<PackageReference Include="System.Collections.Specialized" Version="4.3.0" />
</ItemGroup>
@@ -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"
}
}
]
@@ -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
{
+4 -3
View File
@@ -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.
+9 -2
View File
@@ -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,
}
//-------------------------------------------------------------------
+53 -29
View File
@@ -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),
@@ -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: '(<Table>.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<String> reservedWords = new List<String>()
{
"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",
};
//-------------------------------------------------------------------
}
}
@@ -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),
@@ -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
@@ -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);
//-------------------------------------------------------------------
@@ -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,
}
//-------------------------------------------------------------------
/// <summary>Properties other than common.</summary>
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<SaStatus> validStatuses = new List<SaStatus>()
{
SaStatus.Active,
SaStatus.Inactive,
SaStatus.Deleted,
};
public static SaStatus DefaultStatus { get { return SaStatus.Active; } }
public static List<SaStatus> ValidStatuses { get { return new List<SaStatus>(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,
}
/// <summary>
/// Item list parameters.
/// </summary>
public new class Params : SacsHierarchyItem.Params
{
// List filtering.
public List<SysId> IdsIncluded { get; } = new List<SysId>();
public List<SysId> IdsExcluded { get; } = new List<SysId>();
/// <summary>Generic filter - partial country code or name.</summary>
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<SaxGolfUsgaCountry> values, SysId countryId)
{
if (!SysId.IsValid(countryId)) return null;
foreach (SaxGolfUsgaCountry country in values)
if (country.Id.Equals(countryId)) return country;
return null;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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,
}
//-------------------------------------------------------------------
/// <summary>Properties other than common.</summary>
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<SaStatus> validStatuses = new List<SaStatus>()
{
SaStatus.Active,
SaStatus.Inactive,
SaStatus.Deleted,
};
public static SaStatus DefaultStatus { get { return SaStatus.Active; } }
public static List<SaStatus> ValidStatuses { get { return new List<SaStatus>(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,
}
/// <summary>
/// Item list parameters.
/// </summary>
public new class Params : SacsHierarchyItem.Params
{
// List filtering.
public List<SysId> IdsIncluded { get; } = new List<SysId>();
public List<SysId> IdsExcluded { get; } = new List<SysId>();
public List<SysId> ProvinceIdsIncluded { get; } = new List<SysId>();
public List<SysId> FacilityIdsIncluded { get; } = new List<SysId>();
/// <summary>USGA Course Ids.</summary>
public List<SysId> CourseIdsIncluded { get; } = new List<SysId>();
/// <summary>Generic filter - partial name, address etc.</summary>
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<SaxGolfUsgaCourse> values, SysId courseId)
{
if (!SysId.IsValid(courseId)) return null;
foreach (SaxGolfUsgaCourse province in values)
if (province.Id.Equals(courseId)) return province;
return null;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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,
}
//-------------------------------------------------------------------
/// <summary>Properties other than common.</summary>
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<SaStatus> validStatuses = new List<SaStatus>()
{
SaStatus.Active,
SaStatus.Inactive,
SaStatus.Deleted,
};
public static SaStatus DefaultStatus { get { return SaStatus.Active; } }
public static List<SaStatus> ValidStatuses { get { return new List<SaStatus>(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,
}
/// <summary>
/// Item list parameters.
/// </summary>
public new class Params : SacsHierarchyItem.Params
{
// List filtering.
public List<SysId> IdsIncluded { get; } = new List<SysId>();
public List<SysId> IdsExcluded { get; } = new List<SysId>();
public List<SysId> ProvinceIdsIncluded { get; } = new List<SysId>();
/// <summary>USGA Facility Ids.</summary>
public List<SysId> FacilityIdsIncluded { get; } = new List<SysId>();
/// <summary>Generic filter - partial province code or name.</summary>
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<SaxGolfUsgaFacility> values, SysId facilityId)
{
if (!SysId.IsValid(facilityId)) return null;
foreach (SaxGolfUsgaFacility province in values)
if (province.Id.Equals(facilityId)) return province;
return null;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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,
}
//-------------------------------------------------------------------
/// <summary>Properties other than common.</summary>
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<SaStatus> validStatuses = new List<SaStatus>()
{
SaStatus.Active,
SaStatus.Inactive,
SaStatus.Deleted,
};
public static SaStatus DefaultStatus { get { return SaStatus.Active; } }
public static List<SaStatus> ValidStatuses { get { return new List<SaStatus>(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,
}
/// <summary>
/// Item list parameters.
/// </summary>
public new class Params : SacsHierarchyItem.Params
{
// List filtering.
public List<SysId> IdsIncluded { get; } = new List<SysId>();
public List<SysId> IdsExcluded { get; } = new List<SysId>();
public List<SysId> CourseIdsIncluded { get; } = new List<SysId>();
/// <summary>USGA Marker Ids.</summary>
public List<SysId> MarkerIdsIncluded { get; } = new List<SysId>();
/// <summary>Generic filter - partial caption, holes, tee, gender etc.</summary>
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<SaxGolfUsgaMarker> values, SysId markerId)
{
if (!SysId.IsValid(markerId)) return null;
foreach (SaxGolfUsgaMarker province in values)
if (province.Id.Equals(markerId)) return province;
return null;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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,
}
//-------------------------------------------------------------------
/// <summary>Properties other than common.</summary>
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<SaStatus> validStatuses = new List<SaStatus>()
{
SaStatus.Active,
SaStatus.Inactive,
SaStatus.Deleted,
};
public static SaStatus DefaultStatus { get { return SaStatus.Active; } }
public static List<SaStatus> ValidStatuses { get { return new List<SaStatus>(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,
}
/// <summary>
/// Item list parameters.
/// </summary>
public new class Params : SacsHierarchyItem.Params
{
// List filtering.
public List<SysId> IdsIncluded { get; } = new List<SysId>();
public List<SysId> IdsExcluded { get; } = new List<SysId>();
public List<SysId> CountryIdsIncluded { get; } = new List<SysId>();
/// <summary>Generic filter - partial province code or name.</summary>
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<SaxGolfUsgaProvince> values, SysId provinceId)
{
if (!SysId.IsValid(provinceId)) return null;
foreach (SaxGolfUsgaProvince province in values)
if (province.Id.Equals(provinceId)) return province;
return null;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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;
}
@@ -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.
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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;
}
/// <summary>
/// Bulk update USGA Countries.
/// <para>- Country code must be supplied to act as identifier.</para>
/// <para>- Other properties are validated as per country rules - check error state.</para>
/// <para>- Other properties are left as is if null.</para>
/// </summary>
public abstract bool BulkUpdateUsgaCountries(List<UsgaCountryData> countries, DbUpdateInfo dbUpdateInfo);
//-------------------------------------------------------------------
// Item list.
public abstract ColumnDfn GetUsgaCountryColumnDfn(SaxGolfUsgaCountry.Column columnId, String caption = "", int width = 0);
public abstract List<String> GetUsgaCountryQueryFilter(SaxGolfUsgaCountry.Params prmUsgaCountry);
public abstract long GetUsgaCountryCount(SaxGolfUsgaCountry.Params prmUsgaCountry);
public long GetActiveUsgaCountryCount() { return GetUsgaCountryCount(new SaxGolfUsgaCountry.Params()); }
public abstract List<SaxGolfUsgaCountry> GetUsgaCountryList(SaxGolfUsgaCountry.Params prmUsgaCountry);
public abstract DbResultSet ExecuteUsgaCountryQuery(List<ColumnDfn> columns, SaxGolfUsgaCountry.Params prmUsgaCountry);
//-------------------------------------------------------------------
/// <summary>
/// Extract and format result set data value where specific handling is required.
/// <para>Where response is an invalid data value, format value using column.FormatValue(values).</para>
/// </summary>
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;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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; }
}
/// <summary>
/// Bulk update USGA Courses.
/// <para>- Facility code must be supplied to identify parent.</para>
/// <para>- Course Id must be supplied to act as identifier.</para>
/// <para>- Other properties are validated as per province rules - check error state.</para>
/// <para>- Other properties are left as is if null.</para>
/// </summary>
public abstract bool BulkUpdateUsgaCourses(List<UsgaCourseData> courses, DbUpdateInfo dbUpdateInfo);
//-------------------------------------------------------------------
// Item list.
public abstract ColumnDfn GetUsgaCourseColumnDfn(SaxGolfUsgaCourse.Column columnId, String caption = "", int width = 0);
public abstract List<String> GetUsgaCourseQueryFilter(SaxGolfUsgaCourse.Params prmUsgaCourse);
public abstract long GetUsgaCourseCount(SaxGolfUsgaCourse.Params prmUsgaCourse);
public abstract List<SaxGolfUsgaCourse> GetUsgaCourseList(SaxGolfUsgaCourse.Params prmUsgaCourse);
public abstract DbResultSet ExecuteUsgaCourseQuery(List<ColumnDfn> columns, SaxGolfUsgaCourse.Params prmUsgaCourse);
//-------------------------------------------------------------------
/// <summary>
/// Extract and format result set data value where specific handling is required.
/// <para>Where response is an invalid data value, format value using column.FormatValue(values).</para>
/// </summary>
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;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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;
}
/// <summary>
/// Bulk update USGA Facilities.
/// <para>- Province code must be supplied to identify parent.</para>
/// <para>- Facility Id must be supplied to act as identifier.</para>
/// <para>- Other properties are validated as per province rules - check error state.</para>
/// <para>- Other properties are left as is if null.</para>
/// </summary>
public abstract bool BulkUpdateUsgaFacilities(List<UsgaFacilityData> facilities, DbUpdateInfo dbUpdateInfo);
//-------------------------------------------------------------------
// Item list.
public abstract ColumnDfn GetUsgaFacilityColumnDfn(SaxGolfUsgaFacility.Column columnId, String caption = "", int width = 0);
public abstract List<String> GetUsgaFacilityQueryFilter(SaxGolfUsgaFacility.Params prmUsgaFacility);
public abstract long GetUsgaFacilityCount(SaxGolfUsgaFacility.Params prmUsgaFacility);
public abstract List<SaxGolfUsgaFacility> GetUsgaFacilityList(SaxGolfUsgaFacility.Params prmUsgaFacility);
public abstract DbResultSet ExecuteUsgaFacilityQuery(List<ColumnDfn> columns, SaxGolfUsgaFacility.Params prmUsgaFacility);
//-------------------------------------------------------------------
/// <summary>
/// Extract and format result set data value where specific handling is required.
/// <para>Where response is an invalid data value, format value using column.FormatValue(values).</para>
/// </summary>
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;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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; }
}
/// <summary>
/// Bulk update USGA Markers.
/// <para>- Course Id must be supplied to identify parent.</para>
/// <para>- Marker Id must be supplied to act as identifier.</para>
/// <para>- Other properties are validated as per merker rules - check error state.</para>
/// <para>- Other properties are left as is if null.</para>
/// </summary>
public abstract bool BulkUpdateUsgaMarkers(List<UsgaMarkerData> markers, DbUpdateInfo dbUpdateInfo);
//-------------------------------------------------------------------
// Item list.
public abstract ColumnDfn GetUsgaMarkerColumnDfn(SaxGolfUsgaMarker.Column columnId, String caption = "", int width = 0);
public abstract List<String> GetUsgaMarkerQueryFilter(SaxGolfUsgaMarker.Params prmUsgaMarker);
public abstract long GetUsgaMarkerCount(SaxGolfUsgaMarker.Params prmUsgaMarker);
public abstract List<SaxGolfUsgaMarker> GetUsgaMarkerList(SaxGolfUsgaMarker.Params prmUsgaMarker);
public abstract DbResultSet ExecuteUsgaMarkerQuery(List<ColumnDfn> columns, SaxGolfUsgaMarker.Params prmUsgaMarker);
//-------------------------------------------------------------------
/// <summary>
/// Extract and format result set data value where specific handling is required.
/// <para>Where response is an invalid data value, format value using column.FormatValue(values).</para>
/// </summary>
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;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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;
}
/// <summary>
/// Bulk update USGA Provinces.
/// <para>- Country code must be supplied to identify parent.</para>
/// <para>- Province code must be supplied to act as identifier.</para>
/// <para>- Other properties are validated as per province rules - check error state.</para>
/// <para>- Other properties are left as is if null.</para>
/// </summary>
public abstract bool BulkUpdateUsgaProvinces(List<UsgaProvinceData> provinces, DbUpdateInfo dbUpdateInfo);
//-------------------------------------------------------------------
// Item list.
public abstract ColumnDfn GetUsgaProvinceColumnDfn(SaxGolfUsgaProvince.Column columnId, String caption = "", int width = 0);
public abstract List<String> GetUsgaProvinceQueryFilter(SaxGolfUsgaProvince.Params prmUsgaProvince);
public abstract long GetUsgaProvinceCount(SaxGolfUsgaProvince.Params prmUsgaProvince);
public abstract List<SaxGolfUsgaProvince> GetUsgaProvinceList(SaxGolfUsgaProvince.Params prmUsgaProvince);
public abstract DbResultSet ExecuteUsgaProvinceQuery(List<ColumnDfn> columns, SaxGolfUsgaProvince.Params prmUsgaProvince);
//-------------------------------------------------------------------
/// <summary>
/// Extract and format result set data value where specific handling is required.
/// <para>Where response is an invalid data value, format value using column.FormatValue(values).</para>
/// </summary>
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;
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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)
{
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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; } }
//-------------------------------------------------------------------
@@ -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": {
@@ -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",
@@ -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");
@@ -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);
@@ -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.
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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.
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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.
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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.
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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.
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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
{
@@ -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<String> fields { get; } = new List<String>()
{
"Id",
"CountryCode",
"CountryName",
"EntCountryCode",
"Notes",
"Flags",
"Status",
"CreateOn",
"CreateBy",
"CreateHost",
"UpdateOn",
"UpdateBy",
"UpdateHost",
};
protected static List<String> fieldsId { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsPrimary { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsIgnoreOnUpdate { get; } = new List<String>()
{
"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<String> Fields { get { return new List<String>(fields); } }
public static List<String> FieldsId { get { return new List<String>(fieldsId); } }
public static List<String> 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<String> ExistingColumnNames { get { return GetExistingColumnNames(Fields); } }
public List<String> 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<String> 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<String> 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);
}
//-------------------------------------------------------------------
}
}
@@ -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<String> fields { get; } = new List<String>()
{
"Id",
"FacilityId",
"CourseId",
"LegacyCrpCourseId",
"Caption",
"CourseName",
"FullName",
"Address1",
"Address2",
"City",
"Email",
"Telephone",
"Notes",
"Flags",
"Status",
"CreateOn",
"CreateBy",
"CreateHost",
"UpdateOn",
"UpdateBy",
"UpdateHost",
};
protected static List<String> fieldsId { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsPrimary { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsIgnoreOnUpdate { get; } = new List<String>()
{
"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<String> Fields { get { return new List<String>(fields); } }
public static List<String> FieldsId { get { return new List<String>(fieldsId); } }
public static List<String> 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<String> ExistingColumnNames { get { return GetExistingColumnNames(Fields); } }
public List<String> 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<String> 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<String> 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);
}
//-------------------------------------------------------------------
}
}
@@ -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<String> fields { get; } = new List<String>()
{
"Id",
"ProvinceId",
"FacilityId",
"FacilityName",
"Notes",
"Flags",
"Status",
"CreateOn",
"CreateBy",
"CreateHost",
"UpdateOn",
"UpdateBy",
"UpdateHost",
};
protected static List<String> fieldsId { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsPrimary { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsIgnoreOnUpdate { get; } = new List<String>()
{
"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<String> Fields { get { return new List<String>(fields); } }
public static List<String> FieldsId { get { return new List<String>(fieldsId); } }
public static List<String> 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<String> ExistingColumnNames { get { return GetExistingColumnNames(Fields); } }
public List<String> 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<String> 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<String> 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);
}
//-------------------------------------------------------------------
}
}
@@ -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<String> fields { get; } = new List<String>()
{
"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<String> fieldsId { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsPrimary { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsIgnoreOnUpdate { get; } = new List<String>()
{
"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<String> Fields { get { return new List<String>(fields); } }
public static List<String> FieldsId { get { return new List<String>(fieldsId); } }
public static List<String> 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<String> ExistingColumnNames { get { return GetExistingColumnNames(Fields); } }
public List<String> 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<String> 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<String> 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);
}
//-------------------------------------------------------------------
}
}
@@ -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<String> fields { get; } = new List<String>()
{
"Id",
"CountryId",
"ProvinceCode",
"EntProvinceCode",
"ProvinceName",
"Notes",
"Flags",
"Status",
"CreateOn",
"CreateBy",
"CreateHost",
"UpdateOn",
"UpdateBy",
"UpdateHost",
};
protected static List<String> fieldsId { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsPrimary { get; } = new List<String>()
{
"Id",
};
protected static List<String> fieldsIgnoreOnUpdate { get; } = new List<String>()
{
"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<String> Fields { get { return new List<String>(fields); } }
public static List<String> FieldsId { get { return new List<String>(fieldsId); } }
public static List<String> 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<String> ExistingColumnNames { get { return GetExistingColumnNames(Fields); } }
public List<String> 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<String> 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<String> 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);
}
//-------------------------------------------------------------------
}
}
@@ -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
{

Some files were not shown because too many files have changed in this diff Show More