Portal application - initial.

This commit is contained in:
2021-07-08 20:50:46 +01:00
parent 13c79a8da4
commit 01ae03ddfc
1208 changed files with 186342 additions and 1690 deletions
@@ -0,0 +1,148 @@
using Microsoft.Extensions.Configuration;
using Sarand.BusinessMgr.Net.Core.Web.Consoles;
using Sarand.BusinessMgr.Net.Standard.Base.App;
using Sarand.BusinessMgr.Net.Standard.Base.Consoles;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.CodeTypes;
using Sarand.Net.Standard.Base.Core;
using Sarand.Net.Standard.Base.Dbas;
using Sarand.Net.Standard.Base.Diary;
using Sarand.Net.Standard.Base.Interfaces;
using Sarand.Net.Standard.Base.IO;
using Sarand.Net.Standard.Base.ItemData;
using Sarand.Net.Standard.Base.ItemDocs;
using Sarand.Net.Standard.Base.ItemOptions;
using Sarand.Net.Standard.Base.ReferenceData;
using Sarand.Net.Standard.Base.Security;
using Sarand.Net.Standard.Base.UpdateLog;
using Sarand.Net.Standard.Base.Utils;
using Sarand.Net.Standard.Dbas.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sarand.BusinessMgr.Net.Core.Web.App
{
//=======================================================================
public abstract class SbmApplication_Web : SbmApplication
{
//-------------------------------------------------------------------
// Data members.
protected Sbm.InstanceType instanceType;
protected String environmentName = "";
//-------------------------------------------------------------------
// Protected construction.
protected SbmApplication_Web() : base(new PropertySet())
{
WebApp = this;
}
//-------------------------------------------------------------------
// Properties.
public override SbmSystem System { get { return System_Web; } }
public SbmSystem_Web System_Web { get; protected set; }
public static SbmApplication_Web WebApp { get; private set; }
// Application instance.
public override Sbm.InstanceType InstanceType { get { return instanceType; } }
public override String EnvironmentName { get { return environmentName; } }
public bool Development { get; protected set; }
public String LoggingRootFolder { get; protected set; } = "";
// Application components.
public abstract String SessionCookieName { get; }
public virtual SbmSessionContext SessionContext { get; protected set; }
public abstract SbmSessionConfig SessionConfig { get; }
public override IDatabaseInfo CreateBusMgrDbInfo(SbmSessionContext sessionContext) { return new DbDataItem.DatabaseInfo(GetBusMgrDatabase(sessionContext)); }
// Configuration.
public IConfiguration Configuration { get; protected set; }
public IConfiguration SbmConfiguration { get; protected set; }
//-------------------------------------------------------------------
// Logging.
protected void LogApplicationStart(String fn)
{
// Log application start.
List<StringPair> applicationParams = new List<StringPair>();
applicationParams.Add("Host", SbmSystem.ComputerName);
applicationParams.Add("Version", Sbm.Version.GetFullVersion());
applicationParams.Add("Instance", InstanceType.ToString() + (!StringUtil.IsEmpty(SessionConfig.Instance) ? " [" + SessionConfig.Instance + "]" : ""));
applicationParams.Add("Configuration", SbmSystem.DebugMode ? "Debug" : "Release");
applicationParams.Add("Environment", EnvironmentName);
applicationParams.Add("Database", SessionConfig.BusMgrDatabase.Location);
applicationParams.Add("Application root", SbmSystem.ApplicationFolder);
if (!StringUtil.IsEmpty(SessionConfig.Documents.RootFolder))
applicationParams.Add("Documents root", SessionConfig.Documents.RootFolder);
applicationParams.Add("Email context", SessionConfig.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);
}
//-------------------------------------------------------------------
protected void InitialiseTemporaryLoggingFolder()
{
// Default logging folder - in case of startup failure.
try
{
foreach (String folder in new String[] { @"D:\Sarand\Projects\User\AHoward\VS2017\Sbmonite\Logs" })
{
if (DirectoryUtil.DirectoryExists(folder))
{
SaLogger.LogFolder = folder;
break;
}
}
}
catch (Exception) { }
}
//-------------------------------------------------------------------
// Create consoles.
public override SbmConfigConsole CreateConfigConsole(SbmSessionContext sessionContext)
{
return null;
}
public override SaDiaryConsole CreateDiaryConsole(SbmUserContext userContext)
{
return null;
}
public override SaSecurityConsole CreateSecurityConsole(SbmUserContext userContext)
{
return null;
}
public override SaCodeTypeConsole CreateCodeTypeConsole(SbmUserContext userContext)
{
return null;
}
public override SaReferenceDataConsole CreateReferenceDataConsole(SbmUserContext userContext)
{
return null;
}
public override SaItemDataConsole CreateItemDataConsole(SbmUserContext userContext)
{
return null;
}
public override SaItemDocConsole CreateItemDocConsole(SbmUserContext userContext)
{
return null;
}
public override SaItemOptionConsole CreateItemOptionConsole(SbmUserContext userContext)
{
return null;
}
public override SaInterfaceConsole CreateInterfaceConsole(SbmUserContext userContext)
{
return null;
}
public override SaUpdateLogConsole CreateUpdateLogConsole(SbmUserContext userContext)
{
return null;
}
public override SbmEmailConsole CreateEmailConsole(SbmUserContext userContext)
{
return new SbmEmailConsole_Web(EmailConfig);
}
//-------------------------------------------------------------------
}
//=======================================================================
}
+161
View File
@@ -0,0 +1,161 @@
using Microsoft.AspNetCore.Html;
using Microsoft.Extensions.Localization;
using Sarand.BusinessMgr.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Core;
using Sarand.Net.Standard.Base.Utils;
using System;
using System.Collections.Generic;
using System.Text;
namespace Sarand.BusinessMgr.Net.Core.Web.App
{
//=======================================================================
public abstract class SbmLocaliser
{
//-------------------------------------------------------------------
// Data members.
//-------------------------------------------------------------------
/// <summary>
/// Localisers are supplied by derived object.
/// </summary>
protected SbmLocaliser()
{
}
//-------------------------------------------------------------------
// Properties.
public abstract IStringLocalizer MainProperties { get; }
public virtual List<IStringLocalizer> AlternativeProperties { get; } = new List<IStringLocalizer>();
//-------------------------------------------------------------------
// Generic phrase translation.
//-------------------------------------------------------------------
/// <summary>Retrieve localised text.</summary>
public LocalizedString GetText(string key)
{
return GetText(key, new object[] { });
}
public LocalizedString GetText(string key, object param)
{
return GetText(key, new object[] { param });
}
public LocalizedString GetText(string key, object param1, object param2)
{
return GetText(key, new object[] { param1, param2 });
}
public LocalizedString GetText(string key, object[] parameters)
{
LocalizedString text = MainProperties.GetString(key, parameters);
if (text.ResourceNotFound)
{
SaLogger.Debug(GetType().Name + ".GetText Key not found: " + key);
// Look up key in alternative property files.
foreach (IStringLocalizer properties in AlternativeProperties ?? new List<IStringLocalizer>())
{
text = properties.GetString(key, parameters);
if (!text.ResourceNotFound)
break;
}
}
return text;
}
// Square bracket indexing.
public LocalizedString this[String key]
{
get { return GetText(key); }
}
public LocalizedString this[String key, object param]
{
get { return GetText(key, param); }
}
public LocalizedString this[String key, object param1, object param2]
{
get { return GetText(key, param1, param2); }
}
//-------------------------------------------------------------------
/// <summary>
/// Localised HTML text.
/// <para>Line delimiters changed to '<br/>'.</para>
/// </summary>
public HtmlString GetHtmlText(string key, String param1 = "", String param2 = "")
{
return GetHtmlText(key, new Object[] { param1, param2 });
}
/// <summary>
/// Localised HTML text.
/// <para>Line delimiters changed to '<br/>'.</para>
/// </summary>
public HtmlString GetHtmlText(string key, object[] parameters)
{
LocalizedString localisedText = GetText(key, parameters);
String value = localisedText.Value;
// Replace all line delimiters.
value = value.Replace("\r\n", "\n").Replace("\n", "<br/>").Replace("\r", "<br/>");
return new HtmlString(value);
}
//-------------------------------------------------------------------
/// <summary>
/// Localised javascript string.
/// <para>All quotes are escaped.</para>
/// </summary>
public LocalizedString GetJavascriptText(string key, String param1 = "", String param2 = "")
{
LocalizedString localisedText = GetText(key, param1, param2);
return new LocalizedString(localisedText, EscapeJavascriptText(localisedText.Value), localisedText.ResourceNotFound);
}
public String EscapeJavascriptText(string value)
{
// Escape all quotes.
value = value.Replace("'", "\\'").Replace("\"", "\\\"");
return value;
}
//-------------------------------------------------------------------
// Numeric and datetime formatting
//-------------------------------------------------------------------
public static String DateFormat_Default { get; } = "d-MMM-yyyy";
public static String DateWithWeekdayFormat_Default { get; } = "ddd d-MMM-yyyy";
public String FormatDate(DateTime value, Boolean includeWeekday = true)
{
String dateFormat = includeWeekday ? DateWithWeekdayFormat_Default : DateFormat_Default;
return DateUtil.Format(value, dateFormat);
}
//-------------------------------------------------------------------
// Specific phrase translation.
//-------------------------------------------------------------------
private class CodeCache
{
public List<TypeCodeDesc> affiliateTypeCodes;
// To be completed.
}
private CodeCache codes = new CodeCache();
// Status.
public String GetStatusCaption(SaStatus status)
{
// ToDo Status description localisation.
return SacsSystem.GetStatusDesc(status);
}
// Affiliate Type.
public String GetAffiliateTypeTypeCaption(Sbm.AffiliateType participation)
{
if ((int)participation < 1) return "";
if (codes.affiliateTypeCodes == null)
codes.affiliateTypeCodes = SbmSystem.GetCodesOfType(null, Sbm.SystemCode.AffiliateType);
// ToDo Affiliate Type localisation.
return codes.affiliateTypeCodes.GetDescForType(participation);
}
// To be completed.
//-------------------------------------------------------------------
}
//=======================================================================
}
+199
View File
@@ -0,0 +1,199 @@
using Microsoft.Extensions.Configuration;
using Sarand.BusinessMgr.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Utils;
using System;
using System.Collections.Generic;
using System.Text;
namespace Sarand.BusinessMgr.Net.Core.Web.App
{
//=======================================================================
public class SbmSessionConfig
{
//---------------------------------------------------------------
// Data members.
private readonly List<String> environments = new List<string>();
//---------------------------------------------------------------
// Construction.
public SbmSessionConfig(String context, ConfigurationSection configSection, SbmSessionConfig defaultConfig)
{
Context = context;
populateDefaults(defaultConfig);
PopulateConfig(configSection);
}
//---------------------------------------------------------------
private void populateDefaults(SbmSessionConfig defaultConfig)
{
if (defaultConfig == null) return;
Security.Password.MinLength = defaultConfig.Security.Password.MinLength;
Security.SignIn.KeepLoggedIn.Allowed = defaultConfig.Security.SignIn.KeepLoggedIn.Allowed;
Security.SignIn.KeepLoggedIn.CookieExpiresDays = defaultConfig.Security.SignIn.KeepLoggedIn.CookieExpiresDays;
}
private void PopulateConfig(ConfigurationSection configSection)
{
if (configSection != null)
{
// Environments.
foreach (ConfigurationSection environment in configSection.GetSection("Environments").GetChildren())
environments.Add(StringUtil.TrimAll(environment.Value));
Instance = StringUtil.OnEmpty(configSection["Instance"], Instance);
// Security.
IConfigurationSection security = configSection.GetSection("Security");
if (security.Exists())
{
// Security - Password.
IConfigurationSection securityPassword = security.GetSection("Password");
if (securityPassword.Exists())
{
Security.Password.MinLength = StringUtil.ToInt(securityPassword["MinLength"], Security.Password.MinLength);
}
// Security - Sign-Up.
IConfigurationSection securitySignUp = security.GetSection("SignUp");
if (securitySignUp.Exists())
{
}
// Security - Sign-In.
IConfigurationSection securitySignIn = security.GetSection("SignIn");
if (securitySignIn.Exists())
{
IConfigurationSection keepLoggedIn = securitySignIn.GetSection("SignIn");
if (keepLoggedIn.Exists())
{
Security.SignIn.KeepLoggedIn.Allowed = StringUtil.ToBool(StringUtil.OnEmpty(keepLoggedIn["Allowed"], Security.SignIn.KeepLoggedIn.Allowed.ToString()));
Security.SignIn.KeepLoggedIn.CookieExpiresDays = StringUtil.ToInt(keepLoggedIn["CookieExpiresDays"], Security.SignIn.KeepLoggedIn.CookieExpiresDays);
}
}
}
// Email.
IConfigurationSection email = configSection.GetSection("Email");
if (email.Exists())
{
Email.Context = email["Context"];
PopulateEmailConfig(Email.ContactUs, email.GetSection("ContactUs"));
PopulateEmailConfig(Email.Signup_Activate, email.GetSection("Signup").GetSection("Activate"));
PopulateEmailConfig(Email.Signup_Welcome, email.GetSection("Signup").GetSection("Welcome"));
}
// Documents.
IConfigurationSection documents = configSection.GetSection("Documents");
if (documents.Exists())
{
Documents.RootFolder = StringUtil.OnEmpty(documents["RootFolder"], Documents.RootFolder);
}
// Logging.
IConfigurationSection logging = configSection.GetSection("Logging");
if (logging.Exists())
{
Logging.RootFolder = StringUtil.OnEmpty(logging["RootFolder"], Logging.RootFolder);
}
// Database.
extractDatabaseConfig(BusMgrDatabase, configSection.GetSection("CoreDatabase"));
// Variants.
foreach (ConfigurationSection variantSection in configSection.GetSection("Variants").GetChildren())
{
// Variants override selected values but must match the application root folder to identify a specific instance.
String applicationRootPath = variantSection["ApplicationRootFolder"];
if (StringUtil.IsEmpty(applicationRootPath)) continue;
if (!SbmSystem.ApplicationFolder.EqualsCI(applicationRootPath)) continue;
PopulateConfig(variantSection);
}
}
}
private void PopulateEmailConfig(EmailConfig.SpecificEmailConfig config, IConfigurationSection emailSection)
{
if (!emailSection.Exists()) return;
foreach (var addressTo in emailSection.GetSection("AddressesTo").GetChildren())
config.AddressesTo.Add(StringUtil.TrimAll(addressTo.Value));
foreach (var addressCc in emailSection.GetSection("AddressesCc").GetChildren())
config.AddressesCc.Add(StringUtil.TrimAll(addressCc.Value));
foreach (var addressBcc in emailSection.GetSection("AddressesBcc").GetChildren())
config.AddressesBcc.Add(StringUtil.TrimAll(addressBcc.Value));
}
private void extractDatabaseConfig(DatabaseConfig database, IConfigurationSection databaseSection)
{
if (!databaseSection.Exists()) return;
database.Location = StringUtil.OnEmpty(databaseSection["Location"], database.Location);
database.User = StringUtil.OnEmpty(databaseSection["User"], database.User);
database.Password = StringUtil.OnEmpty(databaseSection["Password"], database.Password);
}
//---------------------------------------------------------------
// Properties.
public String Context { get; }
public List<String> Environments { get { return new List<String>(environments); } }
public String Instance { get; set; } = "";
// Security.
public class SecurityConfig
{
public class PasswordConfig
{
public int MinLength { get; set; }
}
public PasswordConfig Password { get; } = new PasswordConfig();
public class SignUpConfig
{
public class ActivationConfig
{
public int EmailLinkExpiresMins = Sbm.Config.Security.Activation.EmailLinkExpiresMins_Default;
}
public ActivationConfig Activation { get; } = new ActivationConfig();
}
public SignUpConfig SignUp { get; } = new SignUpConfig();
public class SignInConfig
{
public class PasswordRequestConfig
{
public int EmailLinkExpiresMins = Sbm.Config.Security.Activation.EmailLinkExpiresMins_Default;
}
public PasswordRequestConfig PasswordRequest { get; } = new PasswordRequestConfig();
public class KeepLoggedInConfig
{
public bool Allowed { get; set; } = Sbm.Config.Security.SignIn.KeepLoggedIn.Allowed_Default;
public int CookieExpiresDays { get; set; } = Sbm.Config.Security.SignIn.KeepLoggedIn.CookieExpiresDays_Default;
}
public KeepLoggedInConfig KeepLoggedIn { get; } = new KeepLoggedInConfig();
}
public SignInConfig SignIn { get; } = new SignInConfig();
}
public SecurityConfig Security { get; } = new SecurityConfig();
// Email.
public class EmailConfig
{
public class SpecificEmailConfig
{
public List<String> AddressesTo { get; } = new List<string>();
public List<String> AddressesCc { get; } = new List<string>();
public List<String> AddressesBcc { get; } = new List<string>();
}
public SpecificEmailConfig ContactUs { get; } = new SpecificEmailConfig();
public SpecificEmailConfig Signup_Activate { get; } = new SpecificEmailConfig();
public SpecificEmailConfig Signup_Welcome { get; } = new SpecificEmailConfig();
public String Context { get; internal set; }
}
public EmailConfig Email { get; } = new EmailConfig();
// Databases.
public class DatabaseConfig
{
public String Location { get; internal set; }
public String User { get; internal set; }
public String Password { get; internal set; }
}
public DatabaseConfig BusMgrDatabase { get; } = new DatabaseConfig();
// Documents.
public class DocumentsConfig
{
public String RootFolder { get; internal set; }
}
public DocumentsConfig Documents { get; } = new DocumentsConfig();
// Logging.
public class LoggingConfig
{
public String RootFolder { get; internal set; }
}
public LoggingConfig Logging { get; } = new LoggingConfig();
//---------------------------------------------------------------
}
//=======================================================================
}
@@ -0,0 +1,22 @@
using Sarand.BusinessMgr.Net.Standard.Base.App;
using System;
using System.Collections.Generic;
using System.Text;
namespace Sarand.BusinessMgr.Net.Core.Web.App
{
//=======================================================================
public class SbmSessionContext_Web : SbmSessionContext
{
//-------------------------------------------------------------------
/// <summary>Blank construction - used for deserilisation of session data.</summary>
protected SbmSessionContext_Web(Sbm.Application application) : base(0, application) { }
public SbmSessionContext_Web(ushort sesionContextIndex, Sbm.Application application) :
base(sesionContextIndex, application)
{
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -0,0 +1,39 @@
using Sarand.BusinessMgr.Net.Standard.Base.App;
using Sarand.BusinessMgr.Net.Standard.Base.Bus;
using Sarand.Net.Standard.Base.Security;
using System;
using System.Collections.Generic;
using System.Text;
namespace Sarand.BusinessMgr.Net.Core.Web.App
{
//=======================================================================
public abstract class SbmSessionData_Web : SbmSessionData
{
//-------------------------------------------------------------------
// Private construction - for JSON deserialisation.
protected SbmSessionData_Web(long sessionIdx, int itemIdx, SbmSessionContext sessionContext) :
base(sessionIdx, itemIdx, sessionContext)
{
}
// Protected construction.
protected SbmSessionData_Web(SbmSessionContext sessionContext, SaSecurityItem securityItemUser, SbmAffiliate affiliateUser) :
base(sessionContext, securityItemUser, affiliateUser)
{
}
//-------------------------------------------------------------------
// User Context.
public SbmUserContext UserContext
{
get
{
SbmUserContext userContext = new SbmUserContext_Web(SessionContext);
return userContext;
}
}
//-------------------------------------------------------------------
}
//=======================================================================
}
+207
View File
@@ -0,0 +1,207 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Net.Http.Headers;
using Sarand.BusinessMgr.Net.Core.Web.Middleware;
using Sarand.BusinessMgr.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.App;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Text;
namespace Sarand.BusinessMgr.Net.Core.Web.App
{
//=======================================================================
public class SbmStartup_Web
{
//-------------------------------------------------------------------
// Data members.
// Localisation.
private static RequestCulture defaultRequestCulture = new RequestCulture("en-GB", "en-GB");
private static List<CultureInfo> supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-GB"),
new CultureInfo("en-US"),
new CultureInfo("en"),
new CultureInfo("fr-FR"),
new CultureInfo("fr"),
};
//-------------------------------------------------------------------
// Protected construction.
protected SbmStartup_Web(IConfiguration configuration)
{
Configuration = configuration;
}
//-------------------------------------------------------------------
// Properties.
public IConfiguration Configuration { get; }
public static RequestCulture DefaultRequestCulture { get { return defaultRequestCulture; } }
public static List<CultureInfo> SupportedCultures { get { return new List<CultureInfo>(supportedCultures); } }
//-------------------------------------------------------------------
// This method gets called by the runtime. Use this method to add services to the container.
protected class ConfigureServicesConfig
{
public IServiceCollection services;
public String sessionCookieName;
public bool sessionCookieHttpOnly;
public TimeSpan sessionIdleTimeout;
}
protected void ConfigureServices(ConfigureServicesConfig config)
{
// Authentication service.
// Required to handle 'Forbidden' responses etc.
config.services
.AddAuthentication(options => {
options.DefaultAuthenticateScheme = "forbidScheme";
options.DefaultForbidScheme = "forbidScheme";
options.AddScheme<SbmAuthenticationHandler>("forbidScheme", "Handle Forbidden");
});
// Added to support memory caching of sessions.
config.services.AddMemoryCache();
//config.services.AddDistributedMemoryCache(); - for multiple web servers.
// Online web application cookie definition.
config.services.AddSession
(options =>
{
options.Cookie.Name = config.sessionCookieName;
options.Cookie.HttpOnly = config.sessionCookieHttpOnly;
options.IdleTimeout = config.sessionIdleTimeout;
// Override cookie policy for session cookie. Ref. config.app.UseCookiePolicy()
options.Cookie.IsEssential = true;
}
);
// Localisation properties folder.
String resourcesPath = "Localisation";
config.services.AddLocalization(opts => { opts.ResourcesPath = resourcesPath; });
// Modify pages during debug.
#if DEBUG
if (SbmSystem.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();
#endif
config.services.AddMvc
(options =>
{
// Model binding - intercepting form values being bound to models.
options.ModelBinderProviders.Insert(0, new SbmModelBinderProvider());
// Blank form values to be populated to model as empty strings rather than null values.
options.ModelMetadataDetailsProviders.Add(new SbmMetadataProvider());
}
)
// View and data annotation localisations.
.AddViewLocalization(
LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = resourcesPath; })
.AddDataAnnotationsLocalization();
// Configure localisation middleware.
config.services.Configure<RequestLocalizationOptions>
(opts =>
{
// Default culture to use for requests.
opts.DefaultRequestCulture = DefaultRequestCulture;
// Cultures supported by the application. Formatting numbers, dates, etc.
opts.SupportedCultures = SupportedCultures;
// UI cultures supported by the application. UI strings that have been localized.
opts.SupportedUICultures = SupportedCultures;
}
);
// Allows access to the HttpContext inside a service.
config.services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
//-------------------------------------------------------------------
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
protected class ConfigureConfig
{
public IApplicationBuilder app;
public IHostApplicationLifetime hostApplicationLifetime;
public IWebHostEnvironment env;
}
protected void Configure(ConfigureConfig config)
{
if (config.env.IsDevelopment())
{
config.app.UseDeveloperExceptionPage();
}
else
{
config.app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
config.app.UseHsts();
}
config.app.UseHttpsRedirection();
config.app.UseStaticFiles();
config.app.UseCookiePolicy();
config.app.UseSession();
config.app.UseRouting();
//config.app.UseAuthorization();
config.app.UseAntiforgeryTokens();
config.app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
// Application events.
// NB The shutdown events only fire if he application stops 'gracefully'.
config.hostApplicationLifetime.ApplicationStarted.Register(OnApplicationStarted);
config.hostApplicationLifetime.ApplicationStopping.Register(OnApplicationStopping);
config.hostApplicationLifetime.ApplicationStopped.Register(OnApplicationStopped);
config.app.Use(async (context, next) =>
{
if (context.Request.Method.Equals(HttpMethod.Get.Method))
{
context.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromSeconds(10)
};
//context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
}
await next();
});
}
//-------------------------------------------------------------------
// Application events.
private readonly static String ApplicationEventLogPrefix = "### ";
private void OnApplicationStarted()
{
SaLogger.Info(ApplicationEventLogPrefix + "Application started");
}
private void OnApplicationStopping()
{
SaLogger.Info(ApplicationEventLogPrefix + "Application stopping");
}
private void OnApplicationStopped()
{
SaLogger.Info(ApplicationEventLogPrefix + "Application stopped");
}
//-------------------------------------------------------------------
}
//=======================================================================
}
+133
View File
@@ -0,0 +1,133 @@
using Sarand.BusinessMgr.Net.Standard.Dbas.App;
using Sarand.Net.Standard.Base.App;
using Sarand.Net.Standard.Base.Core;
using Sarand.Net.Standard.Base.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace Sarand.BusinessMgr.Net.Core.Web.App
{
//=======================================================================
public class SbmSystem_Web : SbmSystem_Dbas
{
//-------------------------------------------------------------------
// Data members.
//-------------------------------------------------------------------
/// <summary>Static initialisation.</summary>
static SbmSystem_Web()
{
InitComputerName();
InitUserName();
InitApplicationPath();
InitApplicationFolder();
InitAssemblyBuildAt();
}
//-------------------------------------------------------------------
// Construction.
public SbmSystem_Web(PropertySet properties) : base(properties)
{
}
//-------------------------------------------------------------------
/// <summary>
/// Computer name
/// <para>Windows: System.Environment.MachineName</para>
/// <para>Web: HttpContext.Current.Server.MachineName</para>
/// <para>FQDN: System.Net.Dns.GetHostName()</para>
/// </summary>
private static void InitComputerName()
{
try
{
ComputerName = System.Environment.MachineName;
}
catch (Exception exc)
{
SaLogger.Warn("SbmSystem.InitComputerName Failed to initialise computer name from environment. " + ExceptionUtil.GetErrorStateMessage(exc));
}
try
{
if (StringUtil.IsEmpty(ComputerName))
ComputerName = Environment.GetEnvironmentVariable("CUMPUTERNAME") ?? Environment.GetEnvironmentVariable("HOSTNAME");
}
catch (Exception exc)
{
SaLogger.Warn("SbmSystem.InitComputerName Failed to initialise computer name from environment variable. " + ExceptionUtil.GetErrorStateMessage(exc));
}
}
//-------------------------------------------------------------------
/// <summary>To be populated by application<para>Windows: Environment.UserName</para></summary>
private static void InitUserName()
{
try
{
UserName = Environment.UserName;
}
catch (Exception exc)
{
SaLogger.Warn("SbmSystem.InitUserName Failed to initialise user name. " + ExceptionUtil.GetErrorStateMessage(exc));
}
}
//-------------------------------------------------------------------
/// <summary>
/// Application Path.
/// <para>Windows: System.Reflection.Assembly.GetEntryAssembly().Location;</para>
/// </summary>
private static void InitApplicationPath()
{
try
{
ApplicationPath = Assembly.GetEntryAssembly().Location;
}
catch (Exception exc)
{
SaLogger.Warn("SbmSystem.InitApplicationPath Failed to initialise application path. " + ExceptionUtil.GetErrorStateMessage(exc));
}
}
//-------------------------------------------------------------------
/// <summary>
/// Application folder.
/// <para>Windows: System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);</para>
/// </summary>
private static void InitApplicationFolder()
{
try
{
ApplicationFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
}
catch (Exception exc)
{
SaLogger.Warn("SbmSystem.InitApplicationFolder Failed to initialise application folder. " + ExceptionUtil.GetErrorStateMessage(exc));
}
}
//-------------------------------------------------------------------
/// <summary>
/// DateTime when the executing assembly was built.
/// </summary>
private static void InitAssemblyBuildAt()
{
try
{
// Assembly build date.
Assembly assembly = Assembly.GetExecutingAssembly();
AssemblyBuildAt = File.GetLastWriteTime(assembly.Location);
}
catch (Exception exc)
{
SaLogger.Warn("SbmSystem.InitAssemblyBuildAt Failed to initialise assembly build date. " + ExceptionUtil.GetErrorStateMessage(exc));
}
}
//-------------------------------------------------------------------
}
//=======================================================================
}
@@ -0,0 +1,26 @@
using Sarand.BusinessMgr.Net.Standard.Base.App;
using System;
using System.Collections.Generic;
using System.Text;
namespace Sarand.BusinessMgr.Net.Core.Web.App
{
//=======================================================================
public class SbmUserContext_Web : SbmUserContext
{
//-------------------------------------------------------------------
// Data memebrs.
//-------------------------------------------------------------------
// Construction.
public SbmUserContext_Web(SbmSessionContext sessionContext) : base(sessionContext)
{
}
//-------------------------------------------------------------------
// Properties.
//-------------------------------------------------------------------
}
//=======================================================================
}