kreta/KretaWeb/Global.asax.cs
2024-03-13 00:33:46 +01:00

354 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Reflection;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Xml;
using Kreta.BusinessLogic.Classes;
using Kreta.BusinessLogic.Helpers;
using Kreta.BusinessLogic.Security;
using Kreta.Client.CoreApi.Configuration;
using Kreta.Client.Eugyintezes.Configuration;
using Kreta.Client.FileService.Configuration;
using Kreta.Client.KGR.Configuration;
using Kreta.Client.Kir;
using Kreta.Client.Leltar.Configuration;
using Kreta.Client.SzirApi.Configuration;
using Kreta.Client.GlobalApi.Configuration;
using Kreta.Core;
using Kreta.Core.Configuratiaton;
using Kreta.Core.JsonConverter;
using Kreta.Framework;
using Kreta.Web.App_Start;
using Kreta.Web.Areas;
using Kreta.Web.Configuration;
using Kreta.Web.Logger;
using Kreta.Web.ModelBinder.Mvc;
using Newtonsoft.Json;
using CoreConstants = Kreta.Core.Constants;
namespace Kreta.Web
{
public class Global : HttpApplication
{
protected static KretaServer.KretaServer kretaServer;
void Application_Start(object sender, EventArgs e)
{
string mdszUrl = ApplicationData.MdszUrl;
string kirLoginUrl = ApplicationData.KirLoginUrl;
string kirServiceUrl = KirHelper.GetServiceUrl();
string kir2ServiceUrl = KirClient.GetServiceUrl();
string reCAPTCHA = ApplicationData.ReCaptchaValidateUrl;
string eventHubBaseUrl = CoreConstants.Configuration.EventHubBaseUrl;
var nexiusConfig = (NexiusCourseServiceConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.NexiusCourseService);
string nexiusServiceUrl = nexiusConfig.RequestBaseUri.ToString();
var ugyfelszolgalatConfig = (UgyfelszolgalatConfig)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.UgyfelszolgalatConfig);
var kozpontiKretaConfig = (KozpontiKretaConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.KozpontiKretaConfig);
var eugyintezesClientConfiguration = (EugyintezesClientConfiguration)ConfigurationManager.GetSection("EugyintezesClientConfiguration");
var kirConfiguration = (KirConfiguration)ConfigurationManager.GetSection("KirConfiguration");
var sapConfiguration = (SapConfiguration)ConfigurationManager.GetSection("SapConfiguration");
var fileServiceClientConfiguration = (FileServiceClientConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.FileServiceClientConfiguration);
var coreApiClientConfiguration = (CoreApiClientConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.CoreApiClientConfiguration);
var kgrClientConfiguration = (KGRClientConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.KGRClientConfiguration);
var leltarClientConfiguration = (LeltarClientConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.LeltarClientConfiguration);
var szirApiClientConfiguration = (SzirApiClientConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.SzirApiClientConfiguration);
var idpConfiguration = (IdpConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.IdpConfiguration);
var eesztConfiguration = (EESZTConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.EESZTConfig);
var globalApiConfiguration = (GlobalApiConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.GlobalApiConfiguration);
var urls = new string[] { mdszUrl, kirLoginUrl, kirServiceUrl, kir2ServiceUrl, eventHubBaseUrl, nexiusServiceUrl, ugyfelszolgalatConfig.Url,
kozpontiKretaConfig.KgrUrl, kozpontiKretaConfig.KtrUrl, eugyintezesClientConfiguration.BaseUrl, reCAPTCHA, kirConfiguration.Url,
sapConfiguration.BaseUrl, fileServiceClientConfiguration.IDPUrl, fileServiceClientConfiguration.FileUploadUrl,
coreApiClientConfiguration.IDPUrl, coreApiClientConfiguration.DKTUrl, coreApiClientConfiguration.CoreApiIDPUrl, coreApiClientConfiguration.CoreApiUrl, kgrClientConfiguration.IDPUrl, kgrClientConfiguration.KGRUrl,
leltarClientConfiguration.BaseUrl,
idpConfiguration.Authority,
eesztConfiguration.InterfaceUrl,
szirApiClientConfiguration.ApiUrl,
globalApiConfiguration.GlobalApiUrl, globalApiConfiguration.TokenUrl
};
var poszeidonConfig = (IktatoServiceConfiguration)ConfigurationManager.GetSection(CoreConstants.ConfigurationSectionNames.KretaPoszeidonConfig);
ServicePointManager.ServerCertificateValidationCallback += (requestSender, certificate, chain, sslPolicyErrors) =>
{
var cfg = poszeidonConfig.EndpointAddress.Substring(poszeidonConfig.EndpointAddress.IndexOf("}") + 1);
if (((HttpWebRequest)requestSender).Address.ToString().EndsWith(cfg))
{
return true;
}
if (sslPolicyErrors == SslPolicyErrors.None)
{
if (requestSender is HttpWebRequest request)
{
var requestUrl = request.Address.ToString();
foreach (string url in urls)
{
if (requestUrl.Contains(url))
{
return true;
}
}
}
else if (requestSender is SmtpClient)
{
return true;
}
}
return false;
};
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
MvcHandler.DisableMvcResponseHeader = true;
ServerStarter();
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
FilterConfig.RegisterGlobalApiFilters(GlobalConfiguration.Configuration.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = KretaClaimTypes.AntiForgeryToken;
RegisterCustomValidators();
RegisterCustomModelBinders();
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Culture = new CultureInfo(CoreConstants.General.HungarianCulture)
{
NumberFormat = { NumberDecimalSeparator = "," }
},
Converters = new List<JsonConverter> { new StringTrimConverter() }
};
}
void RegisterCustomValidators()
{
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(KretaRequiredAttribute), typeof(RequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(KretaStringLengthAttribute), typeof(StringLengthAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(KretaRangeAttribute), typeof(RangeAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(KretaMinLengthAttribute), typeof(MinLengthAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(KretaMaxLengthAttribute), typeof(MaxLengthAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(KretaRequiredIfAttribute), typeof(RequiredAttributeAdapter));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(KretaRegularExpressionAttribute), typeof(RegularExpressionAttributeAdapter));
}
void RegisterCustomModelBinders()
{
ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
ModelBinders.Binders.Add(typeof(double?), new DoubleModelBinder());
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(int), new IntegerModelBinder());
ModelBinders.Binders.Add(typeof(int?), new IntegerModelBinder());
ModelBinders.Binders.Add(typeof(string), new StringTrimModelBinder());
}
private void ServerStarter()
{
//Inditaskor loggolas
WriteStack();
//Ha valami hiba volt
if (Application["WebStartRequirement"] != null)
{
return;
}
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
//ha nincs inicializalva
//vagy ha nem fut a server
//akkor elinditom
if (kretaServer == null || kretaServer.IsRunning == false)
{
XmlNode fullnode = (XmlNode)ConfigurationManager.GetSection("ServerConfig");
XmlDocument doc = new XmlDocument();
doc.LoadXml(fullnode.SelectSingleNode("/ServerConfig/config").OuterXml);
//Server inditasa
if (kretaServer == null)
{
kretaServer = new KretaServer.KretaServer(doc.DocumentElement);
}
if (ApplicationData.KretaDebug)
{
kretaServer.Start();
}
else
{
try
{
kretaServer.Start();
}
catch
{
Application["WebStartRequirement"] = "Jelenleg a szolgáltatás szünetel!";
return;
}
}
ApplicationData.SystemType = kretaServer.Configuration.SystemType;
}
// fastreport beallitas
FastReport.Utils.Config.WebMode = true;
Debug.WriteLine("LEFUTOTT AZ APPLICATIONSTART!!!!!!!");
}
void Application_End(object sender, EventArgs e)
{
WriteStack();
//ha nem null
if (kretaServer != null)
{
//ha fut akkor leallitom
if (kretaServer.IsRunning)
{
kretaServer.Stop();
}
//ha nem fut akkor meg nullozom
else
{
kretaServer = null;
}
}
HangfireLogger.ShutdownSerilog();
}
private void WriteStack()
{
try
{
HttpRuntime runtime = (HttpRuntime)typeof(HttpRuntime).InvokeMember("_theRuntime",
BindingFlags.NonPublic
| BindingFlags.Static
| BindingFlags.GetField,
null,
null,
null);
if (runtime == null)
return;
string shutDownMessage = (string)runtime.GetType().InvokeMember(
"_shutDownMessage",
BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.GetField,
null,
runtime,
null);
string shutDownStack = (string)runtime.GetType().InvokeMember(
"_shutDownStack",
BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.GetField,
null,
runtime,
null);
//EventLog-ba iras
//try
//{
// if (!EventLog.SourceExists(".NETRuntime"))
// {
// EventLog.CreateEventSource(".NETRuntime", "Application");
// }
// EventLog log = new EventLog();
// log.Source = ".NET Runtime";
// log.WriteEntry(string.Format(
// "\r\n\r\n_shutDownMessage={0}\r\n\r\n_shutDownStack={1}",
// shutDownMessage,
// shutDownStack),
// EventLogEntryType.Error);
//}
//catch { }
//Fajlba iras
StackTrace oSt = new StackTrace();
string message = DateTime.Now + "<br>" + oSt + "<br>" + GetHashCode();
if (System.IO.Directory.Exists(@"c:\temp"))
{
using (System.IO.StreamWriter oWr = new System.IO.StreamWriter(@"c:\temp\SdaLogs", true))
{
oWr.WriteLine(message);
oWr.WriteLine(
$"\r\n\r\n_shutDownMessage={shutDownMessage}\r\n\r\n_shutDownStack={shutDownStack}");
}
}
}
catch
{
}
}
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
Debug.WriteLine(args.Name);
return null;
}
void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
if (exception != null && !ApplicationData.KretaDebug && Request.Url.AbsoluteUri.IndexOf("HibaOldal", StringComparison.OrdinalIgnoreCase) < 0)
{
SDAServer.Instance.Logger.ExceptionThrown(exception);
Response.Redirect("~/HibaOldal");
}
}
void Application_BeginRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
if (app != null && app.Context != null)
{
app.Context.Response.Headers.Remove("Server");
}
}
void Application_EndRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Items.Contains(nameof(UserContext)))
{
var context = HttpContext.Current.Items[nameof(UserContext)] as UserContext;
if (context != null && context.Activated)
{
context.DeActivate();
}
}
}
}
}