Ejemplo n.º 1
0
 protected Test(Xunit.Abstractions.ITestOutputHelper testOutput)
 {
     _testOutput         = testOutput;
     Log.Logger          = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Console().CreateLogger();
     RuntimeConfigHolder = new RuntimeConfigHolder(Log.Logger);
     RuntimeConfigLoader = new DebugRuntimeConfigLoader();
     RuntimeConfigHolder.SetLoader(RuntimeConfigLoader);
     RuntimeConfigHolder.Reload().Wait();
 }
Ejemplo n.º 2
0
        // ---

        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.ProcessExit += onStop;
            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
                if (e.SpecialKey == ConsoleSpecialKey.ControlC)
                {
                    e.Cancel = true;
                    new Thread(delegate() {
                        Environment.Exit(2);
                    }).Start();
                }
            };

            // globlization
            System.Globalization.CultureInfo.DefaultThreadCurrentCulture   = System.Globalization.CultureInfo.InvariantCulture;
            System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;

            _environment = new Microsoft.AspNetCore.Hosting.Internal.HostingEnvironment();
            _environment.EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            var curDir = Directory.GetCurrentDirectory();

            Console.OutputEncoding = Encoding.UTF8;

            _shutdownToken          = new CancellationTokenSource();
            _shutdownCompletedEvent = new ManualResetEventSlim();

            // config
            try {
                var cfgDir = Environment.GetEnvironmentVariable("ASPNETCORE_CONFIGPATH");

                _configuration = new ConfigurationBuilder()
                                 .SetBasePath(cfgDir)
                                 .AddJsonFile("appsettings.json", optional: false)
                                 .AddJsonFile($"appsettings.{_environment.EnvironmentName}.json", optional: false)
                                 .AddJsonFile($"appsettings.{_environment.EnvironmentName}.PK.json", optional: _environment.IsDevelopment())
                                 .Build()
                ;

                _appConfig = new AppConfig();
                _configuration.Bind(_appConfig);
            }
            catch (Exception e) {
                throw new Exception("Failed to get app settings", e);
            }

            // serilog config
            var logConf = new LoggerConfiguration();
            {
                if (_environment.IsDevelopment())
                {
                    logConf.MinimumLevel.Verbose();
                }
                logConf.WriteTo.Console(outputTemplate: "{Timestamp:dd-MMM-yyyy-HH:mm} [{Level:u3}] {Message}   at {SourceContext}{NewLine}{Exception}");
            }
            var logger = Log.Logger = logConf.CreateLogger();

            logger.Information("Starting");

            // runtime config
            _runtimeConfigHolder = new RuntimeConfigHolder(logger);

            // setup services
            var servicesCollection = new ServiceCollection();

            SetupCommonServices(servicesCollection);
            var services = servicesCollection.BuildServiceProvider();

            // config loader
            _runtimeConfigHolder.SetLoader(services.GetRequiredService <IRuntimeConfigLoader>());

            // setup ms logger
            // services.GetRequiredService<Microsoft.Extensions.Logging.ILoggerFactory>().AddNLog();

            // start required services
            StartServices();

            // run workers and wait for completion
            RunWorkers(services);

            // cleanup
            StopServices();
            Log.CloseAndFlush();

            if (_environment.IsDevelopment() && Environment.UserInteractive)
            {
                Console.WriteLine("Press space");
                do
                {
                    while (!Console.KeyAvailable)
                    {
                        Thread.Sleep(100);
                    }
                } while (Console.ReadKey(true).Key != ConsoleKey.Spacebar);
            }

            logger.Information("Stopped");
            _shutdownCompletedEvent.Set();
        }
Ejemplo n.º 3
0
        public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime, IRuntimeConfigLoader runtimeConfigLoader)
        {
            applicationLifetime.ApplicationStopping.Register(OnServerStopRequested);
            applicationLifetime.ApplicationStopped.Register(OnServerStopped);

            // globlization
            app.UseRequestLocalization(new RequestLocalizationOptions {
                DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(System.Globalization.CultureInfo.InvariantCulture),
                SupportedCultures     = new List <System.Globalization.CultureInfo> {
                    System.Globalization.CultureInfo.InvariantCulture
                },
                SupportedUICultures = new List <System.Globalization.CultureInfo> {
                    System.Globalization.CultureInfo.InvariantCulture
                },
            });

            // config loader
            _runtimeConfigHolder.SetLoader(runtimeConfigLoader);

            // setup ms logger
            // app.ApplicationServices.GetRequiredService<Microsoft.Extensions.Logging.ILoggerFactory>().AddNLog();

            // nginx proxy
            {
                var forwardingOptions = new ForwardedHeadersOptions()
                {
                    ForwardedHeaders      = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
                    RequireHeaderSymmetry = false,
                    ForwardLimit          = null,
                };
                forwardingOptions.KnownNetworks.Clear();
                forwardingOptions.KnownProxies.Clear();
                app.UseForwardedHeaders(forwardingOptions);
            }

            // 503: response on exception
            app.UseExceptionHandler(builder => {
                builder.Run(async context => {
                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    context.RequestServices?.GetService <ILogger>()?.ForContext(this.GetType())?.Error(error?.Error ?? new Exception("No extra data"), "Service failure");
                    var resp = APIResponse.GeneralInternalFailure(error?.Error, !_environment.IsProduction());
                    await resp.WriteResponse(context).ConfigureAwait(false);
                });
            });

            // 403: always write body if unathorized
            app.Use(async(context, next) => {
                await next();
                if (context.Response.StatusCode == 403)
                {
                    var resp = APIResponse.BadRequest(APIErrorCode.Unauthorized);
                    await resp.WriteResponse(context).ConfigureAwait(false);
                }
            });

            // check content type
            app.Use(async(context, next) => {
                var flatPath = context.Request.Path.ToString();

                if (context.Request.Method == "POST" && flatPath.StartsWith("/api/") && !flatPath.Contains("/callback/"))
                {
                    if (!(context.Request.ContentType?.StartsWith("application/json") ?? false))
                    {
                        var resp = APIResponse.BadRequest(APIErrorCode.InvalidContentType, "Json format is only allowed");
                        await resp.WriteResponse(context).ConfigureAwait(false);
                        return;
                    }
                }
                await next();
            });

            // swagger
            if (!_environment.IsProduction())
            {
                app.UseSwagger(opts => {
                });
                app.UseSwaggerUI(opts => {
                    opts.SwaggerEndpoint("/" + ((_appConfig.Apps.RelativeApiPath).Trim('/') + "/swagger/api/swagger.json").Trim('/'), "API");
                });
            }

            // 404: redirect to index: not found, not a file, not api request
            app.Use(async(context, next) => {
                await next();
                if (context.Response.StatusCode == 404)
                {
                    var resp = APIResponse.BadRequest(APIErrorCode.MethodNotFound);
                    await resp.WriteResponse(context).ConfigureAwait(false);
                }
            });

            app.UseAuthentication();

            app.UseCors(opts => {
                opts.WithMethods("GET", "POST", "OPTIONS");
                opts.AllowAnyHeader();
                opts.AllowAnyOrigin();
            }
                        );

            app.UseMvc();

            RunServices();
        }