public static int Main(string[] args) { ITraceManager traceManager = new Log4netTraceManager(new Log4netWrapper()); var rc = HostFactory.New(x => { x.Service <ApiService>(sc => { sc.ConstructUsing(s => new ApiService()); sc.WhenStarted((s, hostControl) => s.Start(hostControl)); sc.WhenStopped((s, hostControl) => s.Stop(hostControl)); }); x.RunAsLocalSystem(); x.SetDescription(ApiService.Description); x.SetDisplayName(ApiService.DisplayName); x.SetServiceName(ApiService.ServiceName); x.EnableServiceRecovery(recoveryOption => recoveryOption.RestartService(0)); x.StartAutomaticallyDelayed(); }); TopshelfExitCode exitCode = TopshelfExitCode.AbnormalExit; try { exitCode = rc.Run(); } catch (Exception e) { traceManager.TraceError(e, "ERROR on service starting."); } return((int)exitCode); }
/// <summary> /// Grant credentials according to standard authentication method /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // Creation of service ITraceManager traceManager = new Log4netTraceManager(new Log4netWrapper()); ISecurityContext securityContext = new IdentitySecurityContext(traceManager, new AuthenticationService()); ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType); var(User, Result) = await securityContext.TryLogonUser(context.UserName, context.Password, string.Empty); if (Result) { AuthenticationProperties props = new AuthenticationProperties(new Dictionary <string, string> { ["username"] = context.UserName }); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); AuthenticationTicket ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); traceManager.TraceInfo($"Authentication failed for username={context.UserName}"); return; } }
public static ITraceManager GetTraceManager() { log4net.Config.XmlConfigurator.Configure(); ITraceManager traceManager = new Log4netTraceManager(new Log4netWrapper()); return(traceManager); }
protected void Application_Start() { // Setup Log4Net configuration (in App.config) log4net.Config.XmlConfigurator.Configure(); ITraceManager traceManager = new Log4netTraceManager(new Log4netWrapper()); //Register Syncfusion license Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("MTA3NjkwQDMxMzcyZTMxMmUzMGRpNUF0QThQTklxRFlMeDhXR3NRZFlHcnU4VjN5Z2tGS3FaT2sxM1hER1E9;MTA3NjkxQDMxMzcyZTMxMmUzMFVqQ0tFMGcxclFlNUVKVUJtdWpGcWlmQ1gvbE9PMGxZYWxHTFZYSmxHZDQ9;MTA3NjkyQDMxMzcyZTMxMmUzMEZMTENrQjNCYjUvNmtKTHFNRHBGRkxXVlFXNGZReDVrbWl2WXZsczFORlk9;MTA3NjkzQDMxMzcyZTMxMmUzME5MY3VCaXEydmZyS085RmhzdWtMK2pjNE4wQmY1RUZxMHorMHhHZGlpOFU9;MTA3Njk0QDMxMzcyZTMxMmUzMERPVCtOWHBlT0NZVkM5aExMOUhtL3JMdDFyMWcySEl1cGdlZjBubm1wQW89;MTA3Njk1QDMxMzcyZTMxMmUzMFM5YmYyTDhoL1N4Z2RIeEZ4S1p6KzF5eGxkdkp2VDNIMFpkZHBwYWVndFE9;MTA3Njk2QDMxMzcyZTMxMmUzMEtFZTNrcnBaelBHUXg4TC9kdGE0TjVQTHNIVVloTDZ3N1I4VHQ0NysvTEE9;MTA3Njk3QDMxMzcyZTMxMmUzMExlamxrNmhmL0RyR3Y2QzBoYitxOXhyazRnR0JZUUJBZThJZmhENG1oVGs9;MTA3Njk4QDMxMzcyZTMxMmUzMGRrTFo4clJIR29kZEZrdlRSUlFsQ3VvckJGRjNiZCtscFNYbE0zRThQSGc9;MTA3Njk5QDMxMzcyZTMxMmUzMERPVCtOWHBlT0NZVkM5aExMOUhtL3JMdDFyMWcySEl1cGdlZjBubm1wQW89"); AreaRegistration.RegisterAllAreas(); UnityMvcActivator.Start(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Refresh the file caches with all the files present in the folder ~/Files //APIHttpClient.RefreshDownloadedFiles(Server.MapPath("~/Files")); ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType <JsonValueProviderFactory>().FirstOrDefault()); ValueProviderFactories.Factories.Add(new MyJsonValueProviderFactory()); ModelBinders.Binders[typeof(DocumentationDraft)] = new GenericModelBinder <DocumentationDraft>(); ModelBinders.Binders[typeof(UpdateDispositionDocumentationDraftModel)] = new GenericModelBinder <UpdateDispositionDocumentationDraftModel>(); ModelBinders.Binders[typeof(SaveDocumentationDraftActionsModel)] = new GenericModelBinder <SaveDocumentationDraftActionsModel>(); ModelBinders.Binders[typeof(UpdateActionDispositionDocumentationDraftModel)] = new GenericModelBinder <UpdateActionDispositionDocumentationDraftModel>(); ModelBinders.Binders[typeof(UpdateVideoDocumentationDraftModel)] = new GenericModelBinder <UpdateVideoDocumentationDraftModel>(); ModelBinders.Binders[typeof(UpdateReleaseNotesDocumentationDraftModel)] = new GenericModelBinder <UpdateReleaseNotesDocumentationDraftModel>(); ModelBinders.Binders[typeof(GetActionModel)] = new GenericModelBinder <GetActionModel>(); try { traceManager.TraceInfo($"Webadmin is starting with folder ~/Files={Server.MapPath("~/Files")}"); } catch (Exception) { } }
/// <summary> /// Grant credentials according to standard authentication method /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { // Creation of service ITraceManager traceManager = new Log4netTraceManager(new Log4netWrapper()); ISecurityContext securityContext = new IdentitySecurityContext(traceManager, new AuthenticationService()); ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType); try { (User User, bool Result) = await securityContext.TryLogonUser(context.UserName, context.Password, ""); if (Result) { AuthenticationProperties props = new AuthenticationProperties(new Dictionary <string, string> { ["username"] = context.UserName }); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); AuthenticationTicket ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } else if (User != null && context.Password == User.Password.ToHashString()) { securityContext.ReconnectUser(User); AuthenticationProperties props = new AuthenticationProperties(new Dictionary <string, string> { ["username"] = context.UserName }); identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); AuthenticationTicket ticket = new AuthenticationTicket(identity, props); context.Validated(ticket); } else { throw new Exception("Provided username and password is incorrect"); } } catch (Exception ex) { context.SetError("invalid_grant", ex.Message); traceManager.TraceError($"Authentication failed for username={context.UserName} with msg={ex.Message}{(ex.InnerException == null ? string.Empty : $" and inner={ex.InnerException?.Message}")}", ex); }
static void Main(string[] args) { HostFactory.Run(x => { var traceManager = new Log4netTraceManager(new Log4netWrapper()); // If in docker container, edit the config file if (IsInContainer()) { traceManager.TraceDebug("Edit dynamically config file from docker container"); var dataSource = Environment.GetEnvironmentVariable("DATASOURCE"); var database = Environment.GetEnvironmentVariable("DATABASE"); var fileServerScheme = Environment.GetEnvironmentVariable("FILESERVERSCHEME"); var fileServer = Environment.GetEnvironmentVariable("FILESERVER"); var fileServerPort = Environment.GetEnvironmentVariable("FILESERVERPORT"); var sendNotificationInterval = Environment.GetEnvironmentVariable("SENDNOTIFICATIONINTERVAL"); traceManager.TraceDebug($"DATASOURCE : {dataSource}"); traceManager.TraceDebug($"DATABASE : {database}"); traceManager.TraceDebug($"FILESERVERSCHEME : {fileServerScheme}"); traceManager.TraceDebug($"FILESERVER : {fileServer}"); traceManager.TraceDebug($"FILESERVERPORT : {fileServerPort}"); traceManager.TraceDebug($"SENDNOTIFICATIONINTERVAL : {sendNotificationInterval}"); using (var process = new Process()) { process.StartInfo.FileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "kl2suitenotificationconfig.exe"); process.StartInfo.Arguments = $"-ConfigFile KProcess.KL2.Notification.exe.config -DataSource {dataSource} -Database {database} -FileServerScheme {fileServerScheme} -FileServer {fileServer} -FileServerPort {fileServerPort} -SendNotificationInterval {sendNotificationInterval}"; try { process.Start(); process.WaitForExit(); traceManager.TraceError("Config file correctly updated."); } catch { traceManager.TraceError("An issue has occured during config edition."); } } } Console.WriteLine("Registering dependencies ..."); traceManager.TraceDebug("Registering dependencies ..."); var container = UnityResolver.RegisterServices(IoC.Container); int emailInterval = Convert.ToInt16(ConfigurationManager.AppSettings["SendNotificationInterval"]); x.UseUnityContainer(container); x.UsingQuartzJobFactory(() => new UnityJobFactory(container)); x.Service <NotificationJobService>(s => { s.ConstructUsingUnityContainer(); s.WhenStarted(service => service.OnStart()); s.WhenStopped(service => service.OnStop()); s.ScheduleQuartzJob(q => q.WithJob(() => JobBuilder.Create <SendEmailsJob>().Build()) .AddTrigger(() => TriggerBuilder.Create() .WithSimpleSchedule(b => b.WithIntervalInMinutes(emailInterval).RepeatForever()).Build()) ); s.ScheduleQuartzJob(q => q.WithJob(() => JobBuilder.Create <CollectReportsJob>().Build()) .AddTrigger(() => TriggerBuilder.Create() .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(07, 00).InTimeZone(TimeZoneInfo.Local)).Build()) //.WithSimpleSchedule(b => b.WithIntervalInMinutes(30).RepeatForever()).Build()) ); //s.ScheduleQuartzJob(q => // q.WithJob(() => // JobBuilder.Create<CreateEmailJob>().Build()) // .AddTrigger(() => // TriggerBuilder.Create() // //.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(15, 37).InTimeZone(TimeZoneInfo.Local)).Build()) // .WithSimpleSchedule(b => b.WithIntervalInMinutes(3).RepeatForever()).Build()) //); }); x.RunAsLocalSystem() .DependsOnEventLog() .StartAutomatically() .EnableServiceRecovery(rc => rc.RestartService(0)); x.SetServiceName(NotificationJobService.ServiceName); x.SetDisplayName(NotificationJobService.DisplayName); x.SetDescription(NotificationJobService.Description); // TEST daily inspections reporting /*var job = container.Resolve<CollectReportsJob>(); * job.Execute(null);*/ }); }