Ejemplo n.º 1
0
        private static void OptionsConfiguration(NpgsqlDbContextOptionsBuilder builder)
        {
            string assemblyName = typeof(GameDbContext).Namespace;

            builder.MigrationsHistoryTable("__ef_migrations_history", StorageConstants.Schema);
            builder.MigrationsAssembly(assemblyName);
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Bind the Appsettings.json to shiftDashboardConfig
            DashboardConfig shiftDashboardConfig = new DashboardConfig();

            Configuration.GetSection(shiftDashboardConfig.Position).Bind(shiftDashboardConfig);
            services.AddSingleton <DashboardConfig>(shiftDashboardConfig);


            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader());
            });

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });


            // Initialize DB Context
            services.AddDbContext <DashboardContext>(options =>
            {
                var builder = new NpgsqlDbContextOptionsBuilder(options);
                builder.SetPostgresVersion(new Version(9, 6));
                options.UseNpgsql(shiftDashboardConfig.ConnectionString);
            }
                                                     );

            // Shift Api Service (Need a DB Context
            services.AddTransient <IApiService, ApiService>();

            // Schedule Tasks.
            services.AddQuartz(q =>
            {
                // Create a "key" for the job
                var updateDelegateJobKey = new JobKey("UpdateDelegateJob");

                // Register the job with the DI container
                q.AddJob <UpdateDelegateJob>(opts => opts.WithIdentity(updateDelegateJobKey));

                // Create a trigger for the job
                //
                q.AddTrigger(opts => opts
                             .ForJob(updateDelegateJobKey)
                             .WithIdentity("UpdateDelegateJob-trigger") // give the trigger a unique name
                             .WithCronSchedule("0 */45 * * * ?"));;     // run every 45 minutes

                // Use a Scoped container to create jobs. I'll touch on this later
                q.UseMicrosoftDependencyInjectionScopedJobFactory();
            });

            // Add the Quartz.NET hosted service
            services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
            services.AddControllersWithViews();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
        }
        /// <summary>
        /// Use NetTopologySuite to access SQL Server spatial data.
        /// </summary>
        /// <returns>
        /// The options builder so that further configuration can be chained.
        /// </returns>
        public static NpgsqlDbContextOptionsBuilder UseNetTopologySuite(
            [NotNull] this NpgsqlDbContextOptionsBuilder optionsBuilder,
            ICoordinateSequenceFactory coordinateSequenceFactory = null,
            IPrecisionModel precisionModel = null,
            Ordinates handleOrdinates      = Ordinates.None,
            bool geographyAsDefault        = false)
        {
            Check.NotNull(optionsBuilder, nameof(optionsBuilder));

            // TODO: Global-only setup at the ADO.NET level for now, optionally allow per-connection?
            NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite(coordinateSequenceFactory, precisionModel, handleOrdinates, geographyAsDefault);

            var coreOptionsBuilder = ((IRelationalDbContextOptionsBuilderInfrastructure)optionsBuilder).OptionsBuilder;

            var extension = coreOptionsBuilder.Options.FindExtension <NpgsqlNetTopologySuiteOptionsExtension>()
                            ?? new NpgsqlNetTopologySuiteOptionsExtension();

            if (geographyAsDefault)
            {
                extension = extension.WithGeographyDefault();
            }

            ((IDbContextOptionsBuilderInfrastructure)coreOptionsBuilder).AddOrUpdateExtension(extension);

            return(optionsBuilder);
        }
        public static NpgsqlDbContextOptionsBuilder AddCustomSchemaExtension(this NpgsqlDbContextOptionsBuilder npgsqlDbContextOptionsBuilder, IServiceCollection services)
        {
            var infrastructure = npgsqlDbContextOptionsBuilder as IRelationalDbContextOptionsBuilderInfrastructure;

            infrastructure.AddCustomSchemaExtension(services);
            return(npgsqlDbContextOptionsBuilder);
        }
Ejemplo n.º 5
0
        public static NpgsqlDbContextOptionsBuilder UseZcoin(this NpgsqlDbContextOptionsBuilder builder)
        {
            RegisterEntityFrameworkInterceptors(builder);
            RegisterEntityFrameworkExtensions(builder);

            return(builder);
        }
    public static NpgsqlDbContextOptionsBuilder ApplyConfiguration(this NpgsqlDbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery);

        optionsBuilder.CommandTimeout(NpgsqlTestStore.CommandTimeout);

        return(optionsBuilder);
    }
        public static NpgsqlDbContextOptionsBuilder AddCustomSchemaModelSupport(this NpgsqlDbContextOptionsBuilder npgsqlDbContextOptionsBuilder, DbContextOptionsBuilder dbContextOptionsBuilder, IServiceCollection services)
        {
            services.AddTransient <CustomSchemaOptionsExtension>();
            dbContextOptionsBuilder.ReplaceService <IModelCacheKeyFactory, CustomSchemaModelCacheKeyFactory>();
            npgsqlDbContextOptionsBuilder.AddCustomSchemaExtension(services);

            return(npgsqlDbContextOptionsBuilder);
        }
        // TODO: Remove this if https://github.com/npgsql/efcore.pg/issues/473 ever gets resolved.
        public static NpgsqlDbContextOptionsBuilder UseDateTimeOffsetTranslations(
            this NpgsqlDbContextOptionsBuilder optionsBuilder)
        {
            ((optionsBuilder as IRelationalDbContextOptionsBuilderInfrastructure)
             .OptionsBuilder as IDbContextOptionsBuilderInfrastructure)
            .AddOrUpdateExtension(new DateTimeOffsetTranslationsOptions());

            return(optionsBuilder);
        }
Ejemplo n.º 9
0
            public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
            {
                var optionsBuilder       = base.AddOptions(builder);
                var npgsqlOptionsBuilder = new NpgsqlDbContextOptionsBuilder(optionsBuilder);

                npgsqlOptionsBuilder.MapRange("floatrange", typeof(float));
                npgsqlOptionsBuilder.MapRange <double>("Schema_Range", "test");
                return(optionsBuilder);
            }
Ejemplo n.º 10
0
        //<summary>
        // This method gets called by the runtime. Use this method to add services to the container.
        //</summary>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                //options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API de carga", Version = "v1", Description = "API de carga"
                });
                c.IncludeXmlComments(string.Format(@"{0}comments.xml", System.AppDomain.CurrentDomain.BaseDirectory));
                c.ExampleFilters();
            });
            services.AddSwaggerExamplesFromAssemblyOf <ConfigRepositoriesResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <ConfigRepositoryResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <AddRepositoryErrorResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <ModifyRepositoryErrorResponse>();

            services.AddSwaggerExamplesFromAssemblyOf <ShapeConfigResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <ShapesConfigsResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <AddShapeConfigErrorResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <ModifyShapeConfigErrorResponse>();

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Add(IPAddress.Parse("127.0.0.1"));
            });


            services.AddEntityFrameworkNpgsql().AddDbContext <EntityContext>(opt =>
            {
                var builder = new NpgsqlDbContextOptionsBuilder(opt);
                builder.SetPostgresVersion(new Version(9, 6));
                IDictionary environmentVariables = Environment.GetEnvironmentVariables();
                if (environmentVariables.Contains("PostgreConnectionmigration"))
                {
                    opt.UseNpgsql(environmentVariables["PostgreConnectionmigration"] as string);
                }
                else
                {
                    opt.UseNpgsql(Configuration.GetConnectionString("PostgreConnectionmigration"));
                }
            });
            services.AddSingleton(typeof(ConfigUrlService));
            services.AddSingleton(typeof(ConfigSparql));
            services.AddScoped(typeof(OaiPublishRDFService));
            //services.AddSingleton<IRepositoriesConfigService, RepositoriesConfigMockService>();
            services.AddScoped <IRepositoriesConfigService, RepositoriesConfigBDService>();
            //services.AddSingleton<IShapesConfigService, ShapesConfigMockService>();
            services.AddScoped <IShapesConfigService, ShapesConfigBDService>();
            services.AddScoped <ICallNeedPublishData, CallApiNeedInfoPublisData>();
            //services.AddSingleton<ISyncConfigService, SyncConfigMockService>();
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            IDictionary environmentVariables     = Environment.GetEnvironmentVariables();
            string      connectionHangfireString = "";

            if (environmentVariables.Contains("HangfireConnection"))
            {
                connectionHangfireString = environmentVariables["HangfireConnection"] as string;
            }
            else
            {
                connectionHangfireString = Configuration.GetConnectionString("HangfireConnection");
            }
            //Add Hangfire services.
            services.AddHangfire((isp, configuration) => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_110)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UsePostgreSqlStorage(connectionHangfireString, new PostgreSqlStorageOptions()
            {
                InvisibilityTimeout = TimeSpan.FromDays(1)
            }));


            services.AddHangfireServer();

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Configure cron", Version = "v1"
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
                //options.SchemaFilter<EnumSchemaFilter>();
            });
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Add(IPAddress.Parse("127.0.0.1"));
            });

            services.AddEntityFrameworkNpgsql().AddDbContext <HangfireEntityContext>(opt =>
            {
                var builder = new NpgsqlDbContextOptionsBuilder(opt);
                builder.SetPostgresVersion(new Version(9, 6));
                builder.MigrationsHistoryTable("__EFMigrationsHistory", "hangfire");
                opt.UseNpgsql(connectionHangfireString);
            });

            services.AddScoped <ICronApiService, CronApiService>();
            services.AddScoped <IProgramingMethodService, ProgramingMethodsService>();
            services.AddScoped(typeof(CallApiService));
            services.AddSingleton(typeof(ConfigUrlService));
        }
Ejemplo n.º 12
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <BotAppData.BotAppContext>(options =>
     {
         var builder = new NpgsqlDbContextOptionsBuilder(options);
         builder.SetPostgresVersion(new Version(9, 5));
         options.UseNpgsql(
             Configuration.GetConnectionString("DefaultConnection"));
     });
     services.AddControllersWithViews();
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Enable fuzzystrmatch module methods.
        /// </summary>
        /// <param name="optionsBuilder">The build being used to configure Postgres.</param>
        /// <returns>The options builder so that further configuration can be chained.</returns>
        public static NpgsqlDbContextOptionsBuilder UseFuzzyStringMatch(
            this NpgsqlDbContextOptionsBuilder optionsBuilder)
        {
            var coreOptionsBuilder = ((IRelationalDbContextOptionsBuilderInfrastructure)optionsBuilder).OptionsBuilder;
            var extension          = coreOptionsBuilder.Options.FindExtension <NpgsqlFuzzyStringMatchOptionsExtension>()
                                     ?? new NpgsqlFuzzyStringMatchOptionsExtension();

            ((IDbContextOptionsBuilderInfrastructure)coreOptionsBuilder).AddOrUpdateExtension(extension);

            return(optionsBuilder);
        }
        /// <summary>
        /// Adds PostgreSQL sequence providers and therefore enables operations on sequences.
        /// </summary>
        /// <param name="npgsqlOptionsBuilder"></param>
        /// <returns></returns>
        public static NpgsqlDbContextOptionsBuilder UseSequences(this NpgsqlDbContextOptionsBuilder npgsqlOptionsBuilder)
        {
            var infra   = (IRelationalDbContextOptionsBuilderInfrastructure)npgsqlOptionsBuilder;
            var builder = (IDbContextOptionsBuilderInfrastructure)infra.OptionsBuilder;

            var extension = infra.OptionsBuilder.Options.FindExtension <NpgsqlDbContextOptionsExtension>() ??
                            new NpgsqlDbContextOptionsExtension();

            builder.AddOrUpdateExtension(extension);

            return(npgsqlOptionsBuilder);
        }
        public static NpgsqlDbContextOptionsBuilder UseNodaTime(
            [NotNull] this NpgsqlDbContextOptionsBuilder optionsBuilder)
        {
            Check.NotNull(optionsBuilder, nameof(optionsBuilder));

            // TODO: Global-only setup at the ADO.NET level for now, optionally allow per-connection?
            NpgsqlConnection.GlobalTypeMapper.UseNodaTime();

            optionsBuilder.UsePlugin(new NodaTimePlugin());

            return(optionsBuilder);
        }
        public static NpgsqlDbContextOptionsBuilder MigrationsHistoryTableWithSchema(this NpgsqlDbContextOptionsBuilder npgsqlDbContextOptionsBuilder, DbContextOptionsBuilder optionsBuilder)
        {
            if (npgsqlDbContextOptionsBuilder != null)
            {
                IDbContextCustomSchema dbContextCustomSchema = optionsBuilder.GetDbContextCustomSchema();

                if (dbContextCustomSchema != null && dbContextCustomSchema.UseCustomSchema)
                {
                    npgsqlDbContextOptionsBuilder.MigrationsHistoryTable(dbContextCustomSchema.MigrationsHistoryTableName, dbContextCustomSchema.Schema);
                }
            }
            return(npgsqlDbContextOptionsBuilder);
        }
Ejemplo n.º 17
0
        public static NpgsqlDbContextOptionsBuilder UseJsonb(this NpgsqlDbContextOptionsBuilder builder)
        {
            // Преобразование нужно, так как в RelationalDbContextOptionsBuilder<TBuilder, TExtension>
            // свойство интерфейса IRelationalDbContextOptionsBuilderInfrastructure.OptionsBuilder
            // реализовано явно и не является public
            var optionsBuilder = ((IRelationalDbContextOptionsBuilderInfrastructure)builder).OptionsBuilder;

            // Подключаем свое расширение.
            // Преобразование нужно, так как в DbContextOptionsBuilder метод
            // IDbContextOptionsBuilderInfrastructure.AddOrUpdateExtension(...) реализован явно и не является public
            ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(new JsonbOptionsExtension());

            return(builder);
        }
        /// <summary>
        /// Use NetTopologySuite to access SQL Server spatial data.
        /// </summary>
        /// <returns> The options builder so that further configuration can be chained. </returns>
        public static NpgsqlDbContextOptionsBuilder UseJSON(this NpgsqlDbContextOptionsBuilder optionsBuilder)
        {
            // TODO: Global-only setup at the ADO.NET level for now, optionally allow per-connection?
            //     NpgsqlConnection.GlobalTypeMapper.AddMapping();//.UseNodaTime();

            var coreOptionsBuilder = ((IRelationalDbContextOptionsBuilderInfrastructure)optionsBuilder).OptionsBuilder;

            var extension = coreOptionsBuilder.Options.FindExtension <NpgsqlJsonOptionsExtension>()
                            ?? new NpgsqlJsonOptionsExtension();

            ((IDbContextOptionsBuilderInfrastructure)coreOptionsBuilder).AddOrUpdateExtension(extension);

            return(optionsBuilder);
        }
Ejemplo n.º 19
0
        static NpgsqlNodaTimeTypeMappingTest()
        {
            var optionsBuilder = new DbContextOptionsBuilder();
            var npgsqlBuilder  = new NpgsqlDbContextOptionsBuilder(optionsBuilder).UseNodaTime();
            var options        = new NpgsqlOptions();

            options.Initialize(optionsBuilder.Options);

            Mapper = new NpgsqlTypeMappingSource(
                new TypeMappingSourceDependencies(
                    new ValueConverterSelector(new ValueConverterSelectorDependencies())
                    ),
                new RelationalTypeMappingSourceDependencies(),
                options
                );
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Use NetTopologySuite to access SQL Server spatial data.
        /// </summary>
        /// <returns> The options builder so that further configuration can be chained. </returns>
        public static NpgsqlDbContextOptionsBuilder UseNodaTime(
            [NotNull] this NpgsqlDbContextOptionsBuilder optionsBuilder)
        {
            Check.NotNull(optionsBuilder, nameof(optionsBuilder));

            // TODO: Global-only setup at the ADO.NET level for now, optionally allow per-connection?
            NpgsqlConnection.GlobalTypeMapper.UseNodaTime();

            var coreOptionsBuilder = ((IRelationalDbContextOptionsBuilderInfrastructure)optionsBuilder).OptionsBuilder;

            var extension = coreOptionsBuilder.Options.FindExtension <NpgsqlNodaTimeOptionsExtension>()
                            ?? new NpgsqlNodaTimeOptionsExtension();

            ((IDbContextOptionsBuilderInfrastructure)coreOptionsBuilder).AddOrUpdateExtension(extension);

            return(optionsBuilder);
        }
Ejemplo n.º 21
0
        public static NpgsqlDbContextOptionsBuilder UseNetTopologySuite(
            [NotNull] this NpgsqlDbContextOptionsBuilder optionsBuilder,
            ICoordinateSequenceFactory coordinateSequenceFactory = null,
            IPrecisionModel precisionModel = null,
            Ordinates handleOrdinates      = Ordinates.None)
        {
            Check.NotNull(optionsBuilder, nameof(optionsBuilder));

            NetTopologySuiteBootstrapper.Bootstrap();

            // TODO: Global-only setup at the ADO.NET level for now, optionally allow per-connection?
            NpgsqlConnection.GlobalTypeMapper.UseNetTopologySuite();

            optionsBuilder.UsePlugin(new NetTopologySuitePlugin());

            return(optionsBuilder);
        }
Ejemplo n.º 22
0
        public static NpgsqlDbContextOptionsBuilder AddStringCompareSupport(
            this NpgsqlDbContextOptionsBuilder sqlServerOptionsBuilder)
        {
            var infrastructure = (IRelationalDbContextOptionsBuilderInfrastructure)
                                 sqlServerOptionsBuilder;
            var builder = (IDbContextOptionsBuilderInfrastructure)
                          infrastructure.OptionsBuilder;

            // if the extension is registered already then we keep it
            // otherwise we create a new one
            var extension = infrastructure.OptionsBuilder.Options
                            .FindExtension <NpgsqlDbContextOptionsExtension>()
                            ?? new NpgsqlDbContextOptionsExtension();

            builder.AddOrUpdateExtension(extension);

            return(sqlServerOptionsBuilder);
        }
 private static void OptionsConfiguration(NpgsqlDbContextOptionsBuilder builder)
 {
     builder.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
 }
Ejemplo n.º 24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IDictionary environmentVariables = Environment.GetEnvironmentVariables();
            string      casBaseUrl           = "";

            if (environmentVariables.Contains("CasBaseUrl"))
            {
                casBaseUrl = environmentVariables["CasBaseUrl"] as string;
            }
            else
            {
                casBaseUrl = Configuration["CasBaseUrl"];
            }

            string serviceHost = "";

            if (environmentVariables.Contains("ServiceHost"))
            {
                serviceHost = environmentVariables["ServiceHost"] as string;
            }
            else
            {
                serviceHost = Configuration["ServiceHost"];
            }
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath        = new PathString("/login");
                options.AccessDeniedPath = new PathString("/access-denied");
            })
            .AddCAS(options =>
            {
                options.CasServerUrlBase = casBaseUrl;
                options.SignInScheme     = CookieAuthenticationDefaults.AuthenticationScheme;
                options.ServiceHost      = serviceHost;
            });
            bool cargado = false;

            services.AddEntityFrameworkNpgsql().AddDbContext <EntityContext>(opt =>
            {
                var builder = new NpgsqlDbContextOptionsBuilder(opt);
                builder.SetPostgresVersion(new Version(9, 6));
                IDictionary environmentVariables = Environment.GetEnvironmentVariables();
                if (environmentVariables.Contains("PostgreConnectionmigration"))
                {
                    opt.UseNpgsql(environmentVariables["PostgreConnectionmigration"] as string);
                }
                else
                {
                    opt.UseNpgsql(Configuration.GetConnectionString("PostgreConnectionmigration"));
                }
            });

            services.AddScoped <DiscoverItemBDService, DiscoverItemBDService>();
            services.AddScoped <ProcessDiscoverStateJobBDService, ProcessDiscoverStateJobBDService>();


            services.AddControllersWithViews();
            services.AddSingleton(typeof(ConfigPathLog));
            services.AddSingleton(typeof(ConfigUrlService));
            services.AddSingleton(typeof(ConfigUrlCronService));
            services.AddSingleton(typeof(ConfigUnidataPrefix));
            services.AddScoped <ICallRepositoryConfigService, CallRepositoryConfigApiService>();
            services.AddScoped <ICallUrisFactoryApiService, CallUrisFactoryApiService>();
            services.AddScoped <ICallService, CallApiService>();
            services.AddScoped <ICallEtlService, CallEtlService>();
            services.AddScoped <ICallShapeConfigService, CallShapeConfigApiService>();
            services.AddScoped(typeof(CallCronApiService));
            services.AddScoped(typeof(CheckSystemService));
            services.AddScoped(typeof(CallCronService));
            services.AddScoped(typeof(ConfigTokenService));
            services.AddScoped(typeof(CallTokenService));
            services.AddScoped(typeof(CallApiVirtualPath));
            services.AddScoped(typeof(CallRepositoryJobService));
            services.AddScoped(typeof(ReplaceUsesService));
            var sp = services.BuildServiceProvider();

            // Resolve the services from the service provider
            var virtualProvider = sp.GetService <CallApiVirtualPath>();

            while (!cargado)
            {
                // services.AddMvcRazorRuntimeCompilation();
                try
                {
                    services.AddRazorPages().AddRazorRuntimeCompilation();
                    services.AddControllersWithViews().AddRazorRuntimeCompilation();
                    services.Configure <MvcRazorRuntimeCompilationOptions>(opts =>
                    {
                        opts.FileProviders.Add(
                            new ApiFileProvider(virtualProvider));
                    });
                    cargado = true;
                }
                catch (Exception ex)
                {
                    cargado = false;
                }
            }
        }
            public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
            {
                var npgsqlBuilder = new NpgsqlDbContextOptionsBuilder(builder).UseNodaTime();

                return(builder);
            }
Ejemplo n.º 26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IdentityModelEventSource.ShowPII = true; //Add this line
            IDictionary environmentVariables = Environment.GetEnvironmentVariables();

            services.AddControllers();
            string authority = "";

            if (environmentVariables.Contains("Authority"))
            {
                authority = environmentVariables["Authority"] as string;
            }
            else
            {
                authority = Configuration["Authority"];
            }
            string scope = "";

            if (environmentVariables.Contains("Scope"))
            {
                scope = environmentVariables["Scope"] as string;
            }
            else
            {
                scope = Configuration["Scope"];
            }

            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = authority;
                //options.Authority = "http://herc-as-front-desa.atica.um.es/identityserver";
                options.RequireHttpsMetadata = false;
                options.ApiName = scope;
            });
            services.AddAuthorization();
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Gestor documentacion", Version = "v1"
                });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                options.IncludeXmlComments(xmlPath);
                // options.ExampleFilters();
                options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "bearer",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Description  = "JWT Authorization header using the Bearer scheme."
                });
                options.OperationFilter <SecurityRequirementsOperationFilter>();
            });

            services.AddEntityFrameworkNpgsql().AddDbContext <EntityContext>(opt =>
            {
                var builder = new NpgsqlDbContextOptionsBuilder(opt);
                builder.SetPostgresVersion(new Version(9, 6));
                IDictionary environmentVariables = Environment.GetEnvironmentVariables();
                if (environmentVariables.Contains("PostgreConnectionmigration"))
                {
                    opt.UseNpgsql(environmentVariables["PostgreConnectionmigration"] as string);
                }
                else
                {
                    opt.UseNpgsql(Configuration.GetConnectionString("PostgreConnectionmigration"));
                }
            });
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Add(IPAddress.Parse("127.0.0.1"));
            });

            services.AddScoped <IPagesOperationsServices, PagesOperationService>();
            services.AddScoped <ITemplatesOperationsServices, TemplatesOperationsService>();
            services.AddScoped <IDocumentsOperationsService, DocumentsOperationsService>();
            services.AddScoped <IFileOperationService, FileOperationsService>();
        }
 public static NpgsqlDbContextOptionsBuilder UseAwsIamAuthentication(this NpgsqlDbContextOptionsBuilder optionsBuilder)
 {
     optionsBuilder.ProvidePasswordCallback(GenerateAwsIamAuthToken);
     return(optionsBuilder);
 }
Ejemplo n.º 28
0
 public static NpgsqlDbContextOptionsBuilder ConfigureForSpeakersDataContext(this NpgsqlDbContextOptionsBuilder builder) =>
 builder.UseNodaTime();
Ejemplo n.º 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();

            // Bind the Appsettings.json to shiftDashboardConfig
            DashboardConfig shiftDashboardConfig = new DashboardConfig();

            Configuration.GetSection(shiftDashboardConfig.Position).Bind(shiftDashboardConfig);
            services.AddSingleton <DashboardConfig>(shiftDashboardConfig);

            // Initialize DB Context
            services.AddDbContext <DashboardContext>(options =>
            {
                var builder = new NpgsqlDbContextOptionsBuilder(options);
                builder.SetPostgresVersion(new Version(9, 6));
                options.UseNpgsql(shiftDashboardConfig.ConnectionString);
            }
                                                     );

            // Shift Api Service (Need a DB Context
            services.AddTransient <IApiService, ApiService>();

            // Schedule Tasks.
            services.AddQuartz(q =>
            {
                // Create a "key" for the job
                var updateDelegateJobKey = new JobKey("UpdateDelegateJob");

                // Register the job with the DI container
                q.AddJob <UpdateDelegateJob>(opts => opts.WithIdentity(updateDelegateJobKey));

                // Create a trigger for the job
                //
                q.AddTrigger(opts => opts
                             .ForJob(updateDelegateJobKey)
                             .WithIdentity("UpdateDelegateJob-trigger") // give the trigger a unique name
                             .WithCronSchedule("0 */45 * * * ?"));;     // run every 45 minutes

                // Use a Scoped container to create jobs. I'll touch on this later
                q.UseMicrosoftDependencyInjectionScopedJobFactory();
            });

            // Add the Quartz.NET hosted service

            services.AddQuartzHostedService(
                q => q.WaitForJobsToComplete = true);

            if (services.All(x => x.ServiceType != typeof(HttpClient)))
            {
                services.AddScoped(
                    s =>
                {
                    var navigationManager = s.GetRequiredService <NavigationManager>();
                    return(new HttpClient
                    {
                        BaseAddress = new Uri(navigationManager.BaseUri)
                    });
                });
            }

            services.AddBlazorise(options => { options.ChangeTextOnKeyPress = true; });
            services.AddBootstrapProviders();
            services.AddFontAwesomeIcons();
        }
Ejemplo n.º 30
0
        //<summary>
        // This method gets called by the runtime. Use this method to add services to the container.
        //</summary>
        public void ConfigureServices(IServiceCollection services)
        {
            IDictionary environmentVariables = Environment.GetEnvironmentVariables();
            string      authority            = "";

            if (environmentVariables.Contains("Authority"))
            {
                authority = environmentVariables["Authority"] as string;
            }
            else
            {
                authority = _configuration["Authority"];
            }
            services.AddControllers().AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                options.JsonSerializerOptions.IgnoreNullValues = true;
            });

            if (_env.IsDevelopment())
            {
                services.AddSingleton <IAuthorizationHandler, AllowAnonymous>();
            }
            else
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority            = authority;
                    options.RequireHttpsMetadata = false;
                    options.ApiName = "apiCarga";
                });
                services.AddAuthorization();
            }

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API de carga", Version = "v1", Description = "API de carga"
                });
                c.IncludeXmlComments(string.Format(@"{0}comments.xml", System.AppDomain.CurrentDomain.BaseDirectory));
                c.ExampleFilters();
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "bearer",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Description  = "JWT Authorization header using the Bearer scheme."
                });
                c.OperationFilter <SecurityRequirementsOperationFilter>();
            });
            services.AddSwaggerExamplesFromAssemblyOf <ConfigRepositoriesResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <ConfigRepositoryResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <AddRepositoryErrorResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <ModifyRepositoryErrorResponse>();

            services.AddSwaggerExamplesFromAssemblyOf <ShapeConfigResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <ShapesConfigsResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <AddShapeConfigErrorResponse>();
            services.AddSwaggerExamplesFromAssemblyOf <ModifyShapeConfigErrorResponse>();

            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Add(IPAddress.Parse("127.0.0.1"));
            });


            services.AddEntityFrameworkNpgsql().AddDbContext <EntityContext>(opt =>
            {
                var builder = new NpgsqlDbContextOptionsBuilder(opt);
                builder.SetPostgresVersion(new Version(9, 6));
                IDictionary environmentVariables = Environment.GetEnvironmentVariables();
                if (environmentVariables.Contains("PostgreConnectionmigration"))
                {
                    opt.UseNpgsql(environmentVariables["PostgreConnectionmigration"] as string);
                }
                else
                {
                    opt.UseNpgsql(_configuration.GetConnectionString("PostgreConnectionmigration"));
                }
            });
            if (environmentVariables.Contains("uriRabbitMq"))
            {
                string uriRabbitMq         = environmentVariables["uriRabbitMq"] as string;
                string usernameRabbitMq    = environmentVariables["usernameRabbitMq"] as string;
                string passwordRabbitMq    = environmentVariables["passwordRabbitMq"] as string;
                string virtualhostRabbitMq = environmentVariables["virtualhostRabbitMq"] as string;
                string hostnameRabbitMq    = environmentVariables["hostnameRabbitMq"] as string;
                services.Configure <RabbitMQInfo>(options =>
                {
                    options.HostNameRabbitMq    = hostnameRabbitMq;
                    options.PasswordRabbitMq    = passwordRabbitMq;
                    options.UriRabbitMq         = uriRabbitMq;
                    options.UsernameRabbitMq    = usernameRabbitMq;
                    options.VirtualHostRabbitMq = virtualhostRabbitMq;
                }
                                                  );
            }
            else
            {
                services.Configure <RabbitMQInfo>(_configuration.GetSection("RabbitMQ"));
            }

            //services.AddSingleton<RabbitMQService>();
            services.AddSingleton(typeof(ConfigUrlService));
            services.AddSingleton(typeof(ConfigSparql));
            services.AddScoped(typeof(OaiPublishRDFService));
            //services.AddSingleton<IRepositoriesConfigService, RepositoriesConfigMockService>();
            services.AddScoped <IRepositoriesConfigService, RepositoriesConfigBDService>();
            services.AddScoped <IDiscoverItemService, DiscoverItemBDService>();
            services.AddSingleton <IRabbitMQService, RabbitMQService>();
            //services.AddSingleton<IShapesConfigService, ShapesConfigMockService>();
            services.AddScoped <IShapesConfigService, ShapesConfigBDService>();
            services.AddScoped <ICallNeedPublishData, CallApiNeedInfoPublisData>();
            services.AddScoped <ICallService, CallApiService>();
            services.AddScoped(typeof(CallTokenService));
            services.AddScoped(typeof(CallApiService));
            services.AddScoped(typeof(CallOAIPMH));
            services.AddScoped(typeof(CallConversor));
            //services.AddSingleton<ISyncConfigService, SyncConfigMockService>();
        }