private IWebHostBuilder GetExceptionPropagatingHostBuilder()
        {
#if NETCOREAPP2_0
            string projectId = LoggingTestApplicationPropagateExceptions.ProjectId;
            // Sample: RegisterGoogleLoggerPropagateExceptions2
            return(new WebHostBuilder()
                   .ConfigureServices(services =>
            {
                // Explicitly create logger options that will propagate any exceptions thrown
                // during logging.
                RetryOptions retryOptions = RetryOptions.NoRetry(ExceptionHandling.Propagate);
                // Also set the no buffer option so that writing the logs is attempted inmediately.
                BufferOptions bufferOptions = BufferOptions.NoBuffer();
                LoggerOptions loggerOptions = LoggerOptions.Create(bufferOptions: bufferOptions, retryOptions: retryOptions);

                // Replace projectId with your Google Cloud Project ID.
                services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(sp, projectId, options: loggerOptions));
            })
                   .UseStartup <Startup>());

            // End sample
#else
            return(new WebHostBuilder().UseStartup <LoggingTestApplicationPropagateExceptions>());
#endif
        }
Пример #2
0
        public async Task Logging_NoServiceProvider()
        {
            string testId = IdGenerator.FromDateTime();

            var builder = GetHostBuilder <VanillaApplication>(webHostBuilder =>
                                                              webHostBuilder.ConfigureLogging(loggingBuilder =>
            {
                var projectId = TestEnvironment.GetTestProjectId();
                var provider  = GoogleLoggerProvider.Create(serviceProvider: null, projectId, LoggerOptions.Create(LogLevel.Warning));
                loggingBuilder.AddProvider(provider);
            }));

            using (TestServer server = GetTestServer(builder))
                using (var client = server.CreateClient())
                {
                    await client.GetAsync($"/Main/Warning/{testId}");

                    await client.GetAsync($"/Main/Error/{testId}");

                    await client.GetAsync($"/Main/Critical/{testId}");
                }
            _fixture.AddValidator(testId, results =>
            {
                Assert.Equal(3, results.Count());
                Assert.NotNull(results.FirstOrDefault(l => l.Severity == LogSeverity.Warning));
                Assert.NotNull(results.FirstOrDefault(l => l.Severity == LogSeverity.Error));
                Assert.NotNull(results.FirstOrDefault(l => l.Severity == LogSeverity.Critical));
            });
        }
 public static ILoggerFactory AddGoogle(this ILoggerFactory factory, LogTarget logTarget, IServiceProvider serviceProvider,
                                        LoggerOptions options = null, LoggingServiceV2Client client = null)
 {
     GaxPreconditions.CheckNotNull(factory, nameof(factory));
     GaxPreconditions.CheckNotNull(logTarget, nameof(logTarget));
     factory.AddProvider(GoogleLoggerProvider.Create(logTarget, serviceProvider, options, client));
     return(factory);
 }
Пример #4
0
        public override object InsertEvent(AuditEvent auditEvent)
        {
            GoogleLoggerProvider googleLoggerProvider = GoogleLoggerProvider.Create(_serviceProvider, "gcplogging");
            ILogger logger = googleLoggerProvider.CreateLogger("Audit.NET");

            logger.LogInformation(JsonSerializer.Serialize(auditEvent));
            return(null);
        }
Пример #5
0
        public static IWebHost BuildWebHost(string[] args)
        {
            ReadAppSettings();

            return(WebHost.CreateDefaultBuilder(args)
                   .ConfigureLogging((ctx, logging) => logging.AddProvider(GoogleLoggerProvider.Create(AppSettings.GoogleCloudSettings.ProjectId)))
                   .UseStartup <Startup>()
                   .Build());
        }
Пример #6
0
        private static IWebHostBuilder GetSimpleHostBuilder2()
        {
            string projectId = TestEnvironment.GetTestProjectId();

            // Sample: RegisterGoogleLogger3
            return(new WebHostBuilder()
                   .ConfigureLogging(builder => builder.AddProvider(GoogleLoggerProvider.Create(serviceProvider: null, projectId)))
                   .UseStartup <Startup>());
            // End sample
        }
Пример #7
0
 public void Configure()
 {
     // Sample: RegisterGoogleLogger2
     string projectId = "[Google Cloud Platform project ID]";
     var    webHost   = new WebHostBuilder()
                        .ConfigureLogging((hostingContext, logging) =>
                                          logging.AddProvider(GoogleLoggerProvider.Create(projectId)))
                        .UseStartup <Startup>()
                        .Build();
     // End sample
 }
 public void Configure()
 {
     // Sample: RegisterGoogleLogger2
     string projectId = "[Google Cloud Platform project ID]";
     var    webHost   = new WebHostBuilder()
                        .ConfigureServices(services =>
     {
         services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(sp, projectId));
     })
                        .UseStartup <Startup>()
                        .Build();
     // End sample
 }
Пример #9
0
        private static IWebHostBuilder GetSimpleHostBuilder()
        {
            string projectId = TestEnvironment.GetTestProjectId();

            // Sample: RegisterGoogleLogger2
            return(new WebHostBuilder()
                   .ConfigureServices(services =>
            {
                // Replace projectId with your Google Cloud Project ID.
                services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(sp, projectId));
            })
                   .UseStartup <Startup>());
            // End sample
        }
Пример #10
0
        /// <summary>
        /// Adds a <see cref="GoogleLoggerProvider"/> for <see cref="GoogleLogger"/>s.
        /// </summary>
        /// <param name="builder">The logger builder. Cannot be null.</param>
        /// <param name="serviceProvider">The service provider to resolve additional services from.</param>
        /// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine.
        ///     The Google Cloud Platform project ID. If unspecified and running on GAE or GCE the project ID will be
        ///     detected from the platform.</param>
        /// <param name="options">Optional, options for the logger.</param>
        /// <param name="client">Optional, logging client.</param>
        public static void AddGoogle(this ILoggingBuilder builder,
                                     IServiceProvider serviceProvider,
                                     string projectId              = null,
                                     LoggerOptions options         = null,
                                     LoggingServiceV2Client client = null)
        {
            GaxPreconditions.CheckNotNull(builder, nameof(builder));

            options   = options ?? LoggerOptions.Create();
            projectId = Project.GetAndCheckProjectId(projectId, options.MonitoredResource);
            LogTarget logTarget = LogTarget.ForProject(projectId);

            var provider = GoogleLoggerProvider.Create(serviceProvider, projectId, options, client);

            builder.Services.AddSingleton <ILoggerProvider>(provider);
        }
Пример #11
0
        private IWebHostBuilder GetUrlWriterHostBuilder()
        {
            string projectId = TestEnvironment.GetTestProjectId();

            // Sample: RegisterGoogleLoggerWriteUrl2
            return(new WebHostBuilder()
                   .ConfigureServices(services =>
            {
                // Once created, the GoogleLogger will write the URL where logs can be found
                // to a given System.IO.TextWriter, for instance System.Console.Out.
                LoggerOptions loggerOptions = LoggerOptions.Create(loggerDiagnosticsOutput: Console.Out);

                // Replace projectId with your Google Cloud Project ID.
                services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(sp, projectId, loggerOptions));
            })
                   .UseStartup <Startup>());
            // End sample
        }
        private IWebHostBuilder GetSimpleHostBuilder()
        {
#if NETCOREAPP2_0
            string projectId = TestEnvironment.GetTestProjectId();
            // Sample: RegisterGoogleLogger2
            return(new WebHostBuilder()
                   .ConfigureServices(services =>
            {
                // Replace projectId with your Google Cloud Project ID.
                services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(sp, projectId));
            })
                   .UseStartup <Startup>());

            // End sample
#else
            return(new WebHostBuilder().UseStartup <LoggingTestApplication>());
#endif
        }
        public LoggingSnippetsTests()
        {
            _testId = Utils.GetTestId();
            IWebHostBuilder builder;

#if NETCOREAPP2_0
            // Sample: RegisterGoogleLogger2
            builder = new WebHostBuilder()
                      .ConfigureServices(services =>
            {
                // Replace ProjectId with your Google Cloud Project ID.
                services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(sp, ProjectId));
            })
                      .UseStartup <Startup>();
            // End sample
#else
            builder = new WebHostBuilder().UseStartup <LoggingTestApplication>();
#endif
            _server = new TestServer(builder);
            _client = _server.CreateClient();

            _startTime = DateTime.UtcNow;
        }
Пример #14
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .ConfigureAppConfiguration((context, configBuilder) =>
            {
                HostingEnvironment = context.HostingEnvironment;

                configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

                Configuration = configBuilder.Build();
                GcpProjectId  = GetProjectId(Configuration);
            })
                       .ConfigureServices(services =>
            {
                // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
                services.AddMvc();

                if (HasGcpProjectId)
                {
                    // Enables Stackdriver Trace.
                    services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                    // Sends Exceptions to Stackdriver Error Reporting.
                    services.AddGoogleExceptionLogging(
                        options =>
                    {
                        options.ProjectId   = GcpProjectId;
                        options.ServiceName = GetServiceName(Configuration);
                        options.Version     = GetVersion(Configuration);
                    });
                    services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
                }
            })
                       .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                if (HostingEnvironment.IsDevelopment())
                {
                    // Only use Console and Debug logging during development.
                    loggingBuilder.AddConsole(options =>
                                              options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                    loggingBuilder.AddDebug();
                }
            })
                       .Configure((app) =>
            {
                var logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");

                if (HasGcpProjectId)
                {
                    logger.LogInformation("Stackdriver Logging enabled: https://console.cloud.google.com/logs/");

                    // Sends logs to Stackdriver Error Reporting.
                    app.UseGoogleExceptionLogging();
                    logger.LogInformation(
                        "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                    // Sends logs to Stackdriver Trace.
                    app.UseGoogleTrace();
                    logger.LogInformation("Stackdriver Trace enabled: https://console.cloud.google.com/traces/");
                }
                else
                {
                    logger.LogWarning(
                        "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                }

                app.UseMvc();
            })
                       .Build();

            host.Run();
        }
Пример #15
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .ConfigureAppConfiguration((context, configBuilder) =>
            {
                HostingEnvironment = context.HostingEnvironment;

                configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

                Configuration = configBuilder.Build();
                GcpProjectId  = GetProjectId(Configuration);
            })
                       .ConfigureServices(services =>
            {
                // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
                //services.AddMvc();

                if (HasGcpProjectId)
                {
                    // Enables Stackdriver Trace.
                    services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                    // Sends Exceptions to Stackdriver Error Reporting.
                    services.AddGoogleExceptionLogging(
                        options =>
                    {
                        options.ProjectId   = GcpProjectId;
                        options.ServiceName = GetServiceName(Configuration);
                        options.Version     = GetVersion(Configuration);
                    });
                    services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
                }

                //Banco de Dados
                services.AddEntityFrameworkNpgsql().AddDbContext <BancoContexto>(options =>
                {
                    options.UseNpgsql(Configuration.GetConnectionString("BancoSorteadorString"));
                });


                //AutoMapper
                var mappingConfig = new MapperConfiguration(mc =>
                {
                    mc.AddProfile(new DomainToViewProfile());
                    mc.AddProfile(new ViewToDomainProfile());
                });
                IMapper mapper = mappingConfig.CreateMapper();
                services.AddSingleton(mapper);

                //Injeção de Dependência
                services.AddTransient <ISorteioService, SorteioService>();
                services.AddTransient <ISorteioDetalheService, SorteioDetalheService>();
                services.AddTransient <ISalaService, SalaService>();
                services.AddTransient <IParticipanteService, ParticipanteService>();
                services.AddTransient <IUsuarioService, UsuarioService>();
                services.AddTransient <ILoginService, LoginService>();

                services.AddTransient <ISorteioRepository, SorteioRepository>();
                services.AddTransient <ISorteioDetalheRepository, SorteioDetalheRepository>();
                services.AddTransient <ISalaRepository, SalaRepository>();
                services.AddTransient <IParticipanteRepository, ParticipanteRepository>();
                services.AddTransient <IUsuarioRepository, UsuarioRepository>();

                services.AddTransient <ISorteioAppService, SorteioAppService>();
                services.AddTransient <ISorteioDetalheAppService, SorteioDetalheAppService>();
                services.AddTransient <ISalaAppService, SalaAppService>();
                services.AddTransient <IParticipanteAppService, ParticipanteAppService>();
                services.AddTransient <ILoginAppService, LoginAppService>();
                services.AddMvc();
                services.AddSignalR();


                services.AddAuthentication("TestScheme")
                .AddCookie("TestScheme", options =>
                {
                    //options.CookieHttpOnly = true;
                    options.LoginPath = "/Login";
                });

                //services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, ConfigureCookies>();
            })
                       .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                if (HostingEnvironment.IsDevelopment())
                {
                    // Only use Console and Debug logging during development.
                    loggingBuilder.AddConsole(options =>
                                              options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                    loggingBuilder.AddDebug();
                }
            })
                       .Configure((app) =>
            {
                var logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");
                if (HasGcpProjectId)
                {
                    // Sends logs to Stackdriver Error Reporting.
                    app.UseGoogleExceptionLogging();
                    // Sends logs to Stackdriver Trace.
                    app.UseGoogleTrace();

                    logger.LogInformation(
                        "Stackdriver Logging enabled: https://console.cloud.google.com/logs/");
                    logger.LogInformation(
                        "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                    logger.LogInformation(
                        "Stackdriver Trace enabled: https://console.cloud.google.com/traces/");
                }
                else
                {
                    logger.LogWarning(
                        "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                }

                if (HostingEnvironment.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                        RequestPath  = new PathString("/lib")
                    });
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }

                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                                       ForwardedHeaders.XForwardedProto
                });

                app.UseStaticFiles();
                app.UseAuthentication();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Sorteios}/{action=Index}/{id?}");
                });

                app.UseSignalR(routes =>
                {
                    routes.MapHub <SorteioHub>("/sorteio");
                });
            })
                       .Build();

            host.Run();
        }
Пример #16
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .ConfigureAppConfiguration((context, configBuilder) =>
            {
                HostingEnvironment = context.HostingEnvironment;

                configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

                Configuration = configBuilder.Build();
                GcpProjectId  = GetProjectId(Configuration);
            })
                       .ConfigureServices(services =>
            {
                // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
                services.AddMvc();
                services.AddSession();
                services.AddSession(options => {
                    options.IdleTimeout = TimeSpan.FromMinutes(10.0);    //You can set Time
                });
                services.Configure <CookiePolicyOptions>(options =>
                {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    options.CheckConsentNeeded    = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
                });
                services.AddAuthentication(options =>
                {
                    options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
                }).AddCookie(options =>
                {
                    options.LoginPath      = new PathString("/Index");
                    options.ExpireTimeSpan = TimeSpan.FromMinutes(5.0);
                });
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
                services.AddDbContext <NewContext>(options =>
                                                   options.UseSqlServer(Configuration.GetConnectionString("DevConnection"))
                                                   );

                //Fix json failed when use include
                services.AddMvc().AddJsonOptions(options => {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });

                if (HasGcpProjectId)
                {
                    // Enables Stackdriver Trace.
                    services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                    // Sends Exceptions to Stackdriver Error Reporting.
                    services.AddGoogleExceptionLogging(
                        options =>
                    {
                        options.ProjectId   = GcpProjectId;
                        options.ServiceName = GetServiceName(Configuration);
                        options.Version     = GetVersion(Configuration);
                    });
                    services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
                }
            })
                       .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                if (HostingEnvironment.IsDevelopment())
                {
                    // Only use Console and Debug logging during development.
                    loggingBuilder.AddConsole(options =>
                                              options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                    loggingBuilder.AddDebug();
                }
            })
                       .Configure((app) =>
            {
                var logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");
                if (HasGcpProjectId)
                {
                    // Sends logs to Stackdriver Error Reporting.
                    app.UseGoogleExceptionLogging();
                    // Sends logs to Stackdriver Trace.
                    app.UseGoogleTrace();

                    logger.LogInformation(
                        "Stackdriver Logging enabled: https://console.cloud.google.com/logs/");
                    logger.LogInformation(
                        "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                    logger.LogInformation(
                        "Stackdriver Trace enabled: https://console.cloud.google.com/traces/");
                }
                else
                {
                    logger.LogWarning(
                        "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                }

                if (HostingEnvironment.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                        RequestPath  = new PathString("/lib")
                    });
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }

                app.UseSession();
                app.UseCookiePolicy();
                app.UseAuthentication();
                app.UseStaticFiles();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            })
                       .Build();

            host.Run();
        }
Пример #17
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .ConfigureAppConfiguration((context, configBuilder) =>
            {
                HostingEnvironment = context.HostingEnvironment;

                configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

                Configuration = configBuilder.Build();
                GcpProjectId  = GetProjectId(Configuration);
            })
                       .ConfigureServices(services =>
            {
                // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
                services.AddMvc();
                services.Configure <Settings>(options =>
                {
                    options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
                    options.Database         = Configuration.GetSection("MongoConnection:Database").Value;
                });
                if (HasGcpProjectId)
                {
                    // Enables Stackdriver Trace.
                    services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                    // Sends Exceptions to Stackdriver Error Reporting.
                    services.AddGoogleExceptionLogging(
                        options =>
                    {
                        options.ProjectId   = GcpProjectId;
                        options.ServiceName = GetServiceName(Configuration);
                        options.Version     = GetVersion(Configuration);
                    });
                    services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
                }
                services.AddTransient <IArabicQManager, ArabicManager>();
                services.AddTransient <IChineseQManager, ChineseManager>();
                services.AddTransient <IEnglishQManager, EnglishManager>();
                services.AddTransient <IFrenchQManager, FrenchManager>();
                services.AddTransient <IHindiQManager, HindiManager>();
                services.AddTransient <ISpanishQManager, SpanishManager>();
                services.AddTransient <IUrduQManager, UrduManager>();
            })
                       .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                if (HostingEnvironment.IsDevelopment())
                {
                    // Only use Console and Debug logging during development.
                    loggingBuilder.AddConsole(options =>
                                              options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                    loggingBuilder.AddDebug();
                }
            })
                       .Configure((app) =>
            {
                var logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");
                if (HasGcpProjectId)
                {
                    // Sends logs to Stackdriver Error Reporting.
                    app.UseGoogleExceptionLogging();
                    // Sends logs to Stackdriver Trace.
                    app.UseGoogleTrace();

                    logger.LogInformation(
                        "Stackdriver Logging enabled: https://console.cloud.google.com/logs/");
                    logger.LogInformation(
                        "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                    logger.LogInformation(
                        "Stackdriver Trace enabled: https://console.cloud.google.com/traces/");
                }
                else
                {
                    logger.LogWarning(
                        "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                }

                if (HostingEnvironment.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                        RequestPath  = new PathString("/lib")
                    });
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }

                app.UseStaticFiles();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            })
                       .Build();

            host.Run();
        }
Пример #18
0
        private static IWebHostBuilder CreateWebHostBuilder()
        {
            return(new WebHostBuilder()
                   .UseKestrel()
                   .UseContentRoot(Directory.GetCurrentDirectory())
                   .UseIISIntegration()
                   .ConfigureAppConfiguration((context, configBuilder) =>
            {
                HostingEnvironment = context.HostingEnvironment;

                configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

                Configuration = configBuilder.Build();
                GcpProjectId = GetProjectId(Configuration);
            })
                   .ConfigureServices(services =>
            {
                services.ConfigureMySqlContext(Configuration);
                services.ConfigureRepositoryWrapper();
                services.ConfigureServices();

                // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
                services.AddMvc();
                services.AddMemoryCache();

                // Add functionality to inject IOptions<T>
                services.AddOptions();

                // Add our Config object so it can be injected
                services.Configure <MyConfig>(Configuration.GetSection("MyConfig"));

                // Register the Swagger generator, defining 1 or more Swagger documents
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new OpenApiInfo {
                        Title = "Sistema Solar Web API", Version = "v1"
                    });
                    // Set the comments path for the Swagger JSON and UI.
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                    c.IncludeXmlComments(xmlPath);
                });

                if (HasGcpProjectId)
                {
                    // Enables Stackdriver Trace.
                    services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                    // Sends Exceptions to Stackdriver Error Reporting.
                    services.AddGoogleExceptionLogging(
                        options =>
                    {
                        options.ProjectId = GcpProjectId;
                        options.ServiceName = GetServiceName(Configuration);
                        options.Version = GetVersion(Configuration);
                    });
                    services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
                }
            })
                   .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                if (HostingEnvironment.IsDevelopment())
                {
                    // Only use Console and Debug logging during development.
                    loggingBuilder.AddConsole(options =>
                                              options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                    loggingBuilder.AddDebug();
                }
            })
                   .Configure((app) =>
            {
                var logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");

                if (HasGcpProjectId)
                {
                    logger.LogInformation("Stackdriver Logging enabled: https://console.cloud.google.com/logs/");

                    // Sends logs to Stackdriver Error Reporting.
                    app.UseGoogleExceptionLogging();
                    logger.LogInformation(
                        "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                    // Sends logs to Stackdriver Trace.
                    app.UseGoogleTrace();
                    logger.LogInformation("Stackdriver Trace enabled: https://console.cloud.google.com/traces/");
                }
                else
                {
                    logger.LogWarning(
                        "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                }

                // Enable middleware to serve generated Swagger as a JSON endpoint.
                app.UseSwagger();

                // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
                // specifying the Swagger JSON endpoint.
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("./swagger/v1/swagger.json", "SistemaSolar Web API V1");
                    c.RoutePrefix = string.Empty;
                });

                app.UseStaticFiles();
                app.UseMvc();
            }));
        }
Пример #19
0
            public static void Main(string[] args)
            {
                CreateWebHostBuilder(args).Build().Run();

                var host = new WebHostBuilder()
                           .UseKestrel()
                           .UseContentRoot(Directory.GetCurrentDirectory())
                           .UseIISIntegration()
                           .ConfigureAppConfiguration((context, configBuilder) =>
                {
                    HostingEnvironment = context.HostingEnvironment;

                    configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();

                    Configuration = configBuilder.Build();
                    GcpProjectId  = GetProjectId(Configuration);
                })
                           .ConfigureServices(services =>
                {
                    // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
                    services.AddMvc();

                    if (HasGcpProjectId)
                    {
                        // Enables Stackdriver Trace.
                        services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                        // Sends Exceptions to Stackdriver Error Reporting.
                        services.AddGoogleExceptionLogging(
                            options =>
                        {
                            options.ProjectId   = GcpProjectId;
                            options.ServiceName = GetServiceName(Configuration);
                            options.Version     = GetVersion(Configuration);
                        });
                        services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
                    }
                })
                           .ConfigureLogging(loggingBuilder =>
                {
                    loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                    if (HostingEnvironment.IsDevelopment())
                    {
                        // Only use Console and Debug logging during development.
                        loggingBuilder.AddConsole(options =>
                                                  options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                        loggingBuilder.AddDebug();
                    }
                })
                           .Configure((app) =>
                {
                    var logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");
                    if (HasGcpProjectId)
                    {
                        // Sends logs to Stackdriver Error Reporting.
                        app.UseGoogleExceptionLogging();
                        // Sends logs to Stackdriver Trace.
                        app.UseGoogleTrace();

                        logger.LogInformation(
                            "Stackdriver Logging enabled: https://console.cloud.google.com/logs/");
                        logger.LogInformation(
                            "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                        logger.LogInformation(
                            "Stackdriver Trace enabled: https://console.cloud.google.com/traces/");
                    }
                    else
                    {
                        logger.LogWarning(
                            "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                        logger.LogWarning(
                            "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                        logger.LogWarning(
                            "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                    }

                    if (HostingEnvironment.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                        app.UseStaticFiles(new StaticFileOptions
                        {
                            FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                            RequestPath  = new PathString("/lib")
                        });
                    }
                    else
                    {
                        app.UseExceptionHandler("/Home/Error");
                    }

                    app.UseStaticFiles();

                    app.UseMvc(routes =>
                    {
                        routes.MapRoute(
                            name: "default",
                            template: "{controller=Home}/{action=Index}/{id?}");
                    });
                })
                           .Build();

                host.Run();

                Parser.Default.ParseArguments <CloudOptions, ApiOptions, HttpOptions, HandOptions>(args)
                .MapResult(
                    (HandOptions opts) => ChooseAuthMethodAndInvoke(opts, new HandCodedLibrary()),
                    (ApiOptions opts) => ChooseAuthMethodAndInvoke(opts, new ApiLibrary()),
                    (HttpOptions opts) => ChooseAuthMethodAndInvoke(opts, new HttpLibrary()),
                    (CloudOptions opts) => ChooseAuthMethodAndInvoke(opts, new CloudLibrary()),
                    errs => 1);
            }
Пример #20
0
        private static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .ConfigureAppConfiguration((context, configBuilder) => {
            HostingEnvironment = context.HostingEnvironment;

            configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

            Configuration = configBuilder.Build();
            GcpProjectId  = GetProjectId(Configuration);
        })
        .ConfigureServices(services => {
            // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
            services.AddMvc();
#if (GcpProjectIdInConfig)
            // Enables Stackdriver Trace.
            services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
            // Sends Exceptions to Stackdriver Error Reporting.
            services.AddGoogleExceptionLogging(
                options => {
                options.ProjectId   = GcpProjectId;
                options.ServiceName = GetServiceName(Configuration);
                options.Version     = GetVersion(Configuration);
            });
            services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
#else
            if (HasGcpProjectId)
            {
                // Enables Stackdriver Trace.
                services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                // Sends Exceptions to Stackdriver Error Reporting.
                services.AddGoogleExceptionLogging(
                    options => {
                    options.ProjectId   = GcpProjectId;
                    options.ServiceName = GetServiceName(Configuration);
                    options.Version     = GetVersion(Configuration);
                });
                services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
            }
#endif
        })
        .ConfigureLogging(loggingBuilder => {
            loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
            if (HostingEnvironment.IsDevelopment())
            {
                // Only use Console and Debug logging during development.
                loggingBuilder.AddConsole(options =>
                                          options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                loggingBuilder.AddDebug();
            }
        })
        .Configure(app => {
            ILogger logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");
#if (GcpProjectIdInConfig)
            // Sends logs to Stackdriver Error Reporting.
            app.UseGoogleExceptionLogging();
            // Sends logs to Stackdriver Trace.
            app.UseGoogleTrace();

            logger.LogInformation("Stackdriver Logging enabled: " +
                                  $"https://console.cloud.google.com/logs?project-id={GcpProjectId}");
            logger.LogInformation("Stackdriver Error Reporting enabled: " +
                                  $"https://console.cloud.google.com/errors?project-id={GcpProjectId}");
            logger.LogInformation("Stackdriver Trace enabled: " +
                                  $"https://console.cloud.google.com/traces?project-id={GcpProjectId}");
#else
            if (HasGcpProjectId)
            {
                // Sends logs to Stackdriver Error Reporting.
                app.UseGoogleExceptionLogging();
                // Sends logs to Stackdriver Trace.
                app.UseGoogleTrace();

                logger.LogInformation("Stackdriver Logging enabled: " +
                                      $"https://console.cloud.google.com/logs?project-id={GcpProjectId}");
                logger.LogInformation("Stackdriver Error Reporting enabled: " +
                                      $"https://console.cloud.google.com/errors?project-id={GcpProjectId}");
                logger.LogInformation("Stackdriver Trace enabled: " +
                                      $"https://console.cloud.google.com/traces?project-id={GcpProjectId}");
            }
            else
            {
                logger.LogWarning("Stackdriver Logging, Error Reporting, and Trace are not enabled. " +
                                  "Missing Google:ProjectId in configuration.");
            }
#endif

            if (HostingEnvironment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // So middleware knows requests arrived via https.
            app.UseForwardedHeaders(
                new ForwardedHeadersOptions {
                ForwardedHeaders = ForwardedHeaders.XForwardedProto
            });

            app.UseStaticFiles(
                new StaticFileOptions {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                RequestPath = new PathString("/lib")
            });

            app.UseStaticFiles();

            app.UseMvc(routes => routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"));
        })
        .Build();
Пример #21
0
        private static IHostBuilder GetSimpleHostBuilder2()
        {
            string projectId = TestEnvironment.GetTestProjectId();

            // Sample: RegisterGoogleLogger3_Core3
            var hostBuilder = Host.CreateDefaultBuilder()
                              .ConfigureWebHostDefaults(webBuilder => webBuilder
                                                        // Replace projectId with your Google Cloud Project ID.
                                                        .ConfigureLogging(builder => builder.AddProvider(GoogleLoggerProvider.Create(serviceProvider: null, projectId)))
                                                        .UseStartup <Startup>());

            // End sample
            return(hostBuilder.ConfigureWebHost(webBuilder => webBuilder.UseTestServer()));
        }
Пример #22
0
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                       .UseKestrel()
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseIISIntegration()
                       .ConfigureAppConfiguration((context, configBuilder) =>
            {
                HostingEnvironment = context.HostingEnvironment;

                configBuilder.SetBasePath(HostingEnvironment.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{HostingEnvironment.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

                Configuration = configBuilder.Build();
                GcpProjectId  = GetProjectId(Configuration);
            })
                       .ConfigureServices(services =>
            {
                // Add framework services.Microsoft.VisualStudio.ExtensionManager.ExtensionManagerService
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

                if (HasGcpProjectId)
                {
                    // Enables Stackdriver Trace.
                    services.AddGoogleTrace(options => options.ProjectId = GcpProjectId);
                    // Sends Exceptions to Stackdriver Error Reporting.
                    services.AddGoogleExceptionLogging(
                        options =>
                    {
                        options.ProjectId   = GcpProjectId;
                        options.ServiceName = GetServiceName(Configuration);
                        options.Version     = GetVersion(Configuration);
                    });

                    services.AddSingleton <ILoggerProvider>(sp => GoogleLoggerProvider.Create(GcpProjectId));
                    services.AddServicesDependencies(GcpProjectId);
                }
            })
                       .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.AddConfiguration(Configuration.GetSection("Logging"));
                if (HostingEnvironment.IsDevelopment())
                {
                    // Only use Console and Debug logging during development.
                    loggingBuilder.AddConsole(options =>
                                              options.IncludeScopes = Configuration.GetValue <bool>("Logging:IncludeScopes"));
                    loggingBuilder.AddDebug();
                }
            })
                       .Configure((app) =>
            {
                app.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedProto
                });

                var options = new RewriteOptions();

                options.Rules.Add(new NonWwwRule());
                options.AddRedirectToHttps();

                app.UseRewriter(options);

                var logger = app.ApplicationServices.GetService <ILoggerFactory>().CreateLogger("Startup");
                if (HasGcpProjectId)
                {
                    // Sends logs to Stackdriver Error Reporting.
                    app.UseGoogleExceptionLogging();
                    // Sends logs to Stackdriver Trace.
                    app.UseGoogleTrace();

                    logger.LogInformation(
                        "Stackdriver Logging enabled: https://console.cloud.google.com/logs/");
                    logger.LogInformation(
                        "Stackdriver Error Reporting enabled: https://console.cloud.google.com/errors/");
                    logger.LogInformation(
                        "Stackdriver Trace enabled: https://console.cloud.google.com/traces/");
                }
                else
                {
                    logger.LogWarning(
                        "Stackdriver Logging not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Error Reporting not enabled. Missing Google:ProjectId in configuration.");
                    logger.LogWarning(
                        "Stackdriver Trace not enabled. Missing Google:ProjectId in configuration.");
                }

                if (HostingEnvironment.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                        RequestPath  = new PathString("/lib")
                    });
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseStatusCodePages();
                app.UseAuthentication();
                app.UseStaticFiles();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });

                UserSeeder.Initialize(app.ApplicationServices);
            }).Build();

            host.Run();
        }