Exemplo n.º 1
0
        public void Ctor_CanCreateSqlServerStorage_WithExistingConnection()
        {
            var connection = ConnectionUtils.CreateConnection();
            var storage    = new PostgreSqlStorage(connection, _options);

            Assert.NotNull(storage);
        }
		public void Ctor_CanCreateSqlServerStorage_WithExistingConnection()
		{
			var connection = ConnectionUtils.CreateConnection();
			var storage = new PostgreSqlStorage(connection, _options);

			Assert.NotNull(storage);
		}
 public TestPage()
 {
     var connectionString = ConnectionUtils.GetConnectionString();
     var storage = new PostgreSqlStorage(connectionString, new PostgreSqlStorageOptions { PrepareSchemaIfNecessary = false });
     // HACK: Workaround for injection test storage
     GetType().GetProperty(nameof(Storage)).SetValue(this, storage);
 }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseNpgsql(Configuration.GetConnectionString("psqlConnection")))
            .AddDbContext <LogDbContext>(options =>
                                         options.UseNpgsql(Configuration.GetConnectionString("psqlConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            var sb = new NpgsqlConnectionStringBuilder(Configuration.GetConnectionString("psqlConnection"))
            {
                Pooling = false
            };
            var storage = new PostgreSqlStorage(sb.ConnectionString);

            services.AddHangfire(x => x.UseStorage(storage));
            services.AddMvc();

            // Add application services.
            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddTransient <ISmsSender, AuthMessageSender>();
            services.AddTransient <IServerLogService, ServerLogService>();
            services.AddTransient <ISettingsService, SettingsService>();
            services.AddScoped <IServerLogRepository, ServerLogRepository>();
            services.AddScoped <IIPLocationRepository, IPLocationRepository>();
            services.AddScoped <ISettingsRepository, SettingsRepository>();
        }
Exemplo n.º 5
0
        public MAMQPostgreSqlConnection(PostgreSqlStorage storage, IEnumerable <string>?queues, PostgreSqlStorageOptions options, string nameOrConnectionString)
        {
            const string postgresSqlConnectionTypeName = "Hangfire.PostgreSql.PostgreSqlConnection";
            Type?        type = typeof(PostgreSqlStorage)
                                .Assembly
                                .GetType(postgresSqlConnectionTypeName);

            Type?pgStorageType = typeof(PostgreSqlStorage);

            if (type == null)
            {
                throw new InvalidOperationException($"{postgresSqlConnectionTypeName} has not been loaded into the process.");
            }

            //BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
            //FieldInfo field = pgStorageType.GetField("_existingConnection", bindFlags);
            //var func = pgStorageType.GetMethod("CreateAndOpenConnection", BindingFlags.Instance | BindingFlags.NonPublic);
            //var npgsqlConnection = func.Invoke(storage, new object[] { });

            //var npgsqlConnection = field.GetValue(storage);

            // NpgsqlConnection connection,
            // PersistentJobQueueProviderCollection queueProviders,
            //PostgreSqlStorageOptions options)

            var npgsqlConnection = new NpgsqlConnection(nameOrConnectionString);

            npgsqlConnection.Open();
            var connection = type.Assembly.CreateInstance(type.FullName, false, BindingFlags.Instance | BindingFlags.Public, null, new object[] { npgsqlConnection, storage.QueueProviders, options }, null, null) as JobStorageConnection;

            _postgreSqlConnection = connection ?? throw new InvalidOperationException($"Could not create an instance for {postgresSqlConnectionTypeName}");

            _queues = queues;
        }
        public void AddToQueue_AddsAJobToTheQueue_UsingStorageConnection_WithTransactionScopeEnlistment()
        {
            string jobId;
            var    storage = new PostgreSqlStorage(ConnectionUtils.GetConnectionString(), new PostgreSqlStorageOptions {
                EnableTransactionScopeEnlistment = true
            });

            using (var storageConnection = storage.GetConnection())
            {
                using (var writeTransaction = storageConnection.CreateWriteTransaction())
                {
                    // Explicitly call multiple write commands here, as AddToQueue previously opened an own connection.
                    // This triggered a prepared transaction which should be avoided.
                    jobId = storageConnection.CreateExpiredJob(Job.FromExpression(() => Console.Write("Hi")), new Dictionary <string, string>(), DateTime.UtcNow, TimeSpan.FromMinutes(1));

                    writeTransaction.SetJobState(jobId, new ScheduledState(DateTime.UtcNow));
                    writeTransaction.AddToQueue("default", jobId);
                    writeTransaction.PersistJob(jobId);
                    writeTransaction.Commit();
                }
            }

            UseConnection(connection =>
            {
                var record = connection.Query(@"select * from """ + GetSchemaName() + @""".""jobqueue""").Single();
                Assert.Equal(jobId, record.jobid.ToString());
                Assert.Equal("default", record.queue);
                Assert.Null(record.FetchedAt);
            });
        }
Exemplo n.º 7
0
 private static PostgreSqlJobQueue CreateJobQueue(PostgreSqlStorage storage, bool useNativeDatabaseTransactions)
 {
     return(new PostgreSqlJobQueue(storage, new PostgreSqlStorageOptions()
     {
         SchemaName = GetSchemaName(),
         UseNativeDatabaseTransactions = useNativeDatabaseTransactions
     }));
 }
Exemplo n.º 8
0
 public RabbitMqSqlServerStorageExtensionsFacts()
 {
     _storage = new PostgreSqlStorage(
         @"Server=.\sqlexpress;Database=TheDatabase;Trusted_Connection=True;",
         new PostgreSqlStorageOptions()
     {
         PrepareSchemaIfNecessary = false
     });
 }
        /// <summary>
		/// Tells the bootstrapper to use PostgreSQL as a job storage,
		/// that can be accessed using the given connection string or 
		/// its name.
		/// </summary>
		/// <param name="configuration">Configuration</param>
		/// <param name="nameOrConnectionString">Connection string or its name</param>
		public static PostgreSqlStorage UsePostgreSqlStorage(
            this IGlobalConfiguration configuration,
            string nameOrConnectionString)
        {
            var storage = new PostgreSqlStorage(nameOrConnectionString);
            configuration.UseStorage(storage);

            return storage;
        }
        /// <summary>
        /// Tells the bootstrapper to use PostgreSQL as a job storage
        /// with the given options, that can be accessed using the specified
        /// connection string or its name.
        /// </summary>
        /// <param name="configuration">Configuration</param>
        /// <param name="nameOrConnectionString">Connection string or its name</param>
        /// <param name="options">Advanced options</param>
        public static PostgreSqlStorage UsePostgreSqlStorage(
            this IBootstrapperConfiguration configuration,
            string nameOrConnectionString,
            PostgreSqlStorageOptions options)
        {
            var storage = new PostgreSqlStorage(nameOrConnectionString, options);
            configuration.UseStorage(storage);

            return storage;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Tells the bootstrapper to use PostgreSQL as a job storage,
        /// that can be accessed using the given connection string or
        /// its name.
        /// </summary>
        /// <param name="configuration">Configuration</param>
        /// <param name="nameOrConnectionString">Connection string or its name</param>
        public static PostgreSqlStorage UsePostgreSqlStorage(
            this IBootstrapperConfiguration configuration,
            string nameOrConnectionString)
        {
            var storage = new PostgreSqlStorage(nameOrConnectionString);

            configuration.UseStorage(storage);

            return(storage);
        }
Exemplo n.º 12
0
        public void GetConnection_ReturnsExistingConnection_WhenStorageUsesIt()
        {
            var connection = ConnectionUtils.CreateConnection();
            var storage    = new PostgreSqlStorage(connection, _options);

            using (var storageConnection = (PostgreSqlConnection)storage.GetConnection())
            {
                Assert.Same(connection, storageConnection.Connection);
                Assert.False(storageConnection.OwnsConnection);
            }
        }
		public void GetConnection_ReturnsExistingConnection_WhenStorageUsesIt()
		{
			var connection = ConnectionUtils.CreateConnection();
			var storage = new PostgreSqlStorage(connection, _options);

			using (var storageConnection = (PostgreSqlConnection) storage.GetConnection())
			{
				Assert.Same(connection, storageConnection.Connection);
				Assert.False(storageConnection.OwnsConnection);
			}
		}
Exemplo n.º 14
0
        /// <summary>
        /// Tells the bootstrapper to use PostgreSQL as a job storage
        /// with the given options, that can be accessed using the specified
        /// connection string or its name.
        /// </summary>
        /// <param name="configuration">Configuration</param>
        /// <param name="nameOrConnectionString">Connection string or its name</param>
        /// <param name="options">Advanced options</param>
        public static PostgreSqlStorage UsePostgreSqlStorage(
            this IGlobalConfiguration configuration,
            string nameOrConnectionString,
            PostgreSqlStorageOptions options)
        {
            var storage = new PostgreSqlStorage(nameOrConnectionString, options);

            configuration.UseStorage(storage);

            return(storage);
        }
Exemplo n.º 15
0
        private static void UseConnection(Action <IDbConnection, PostgreSqlStorage> action)
        {
            var storage = new PostgreSqlStorage(ConnectionUtils.GetConnectionString());

            storage.UseConnection(connection =>
            {
                action(connection, storage);

                return(true);
            });
        }
        private static long CreateJobQueueRecord(PostgreSqlStorage storage, string jobId, string queue)
        {
            string arrangeSql = @"
insert into """ + GetSchemaName() + @""".""jobqueue"" (""jobid"", ""queue"", ""fetchedat"")
values (@id, @queue, now() at time zone 'utc') returning ""id""";

            return
                ((long)
                 storage.UseConnection(connection => connection.Query(arrangeSql, new { id = Convert.ToInt32(jobId, CultureInfo.InvariantCulture), queue = queue })
                                       .Single()
                                       .id));
        }
Exemplo n.º 17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(options => { options.LoginPath = "/"; });
            services.AddMvc().AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Home/Dashboard");
                options.Conventions.AllowAnonymousToPage("/");
            });

            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;
            });
            CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
            services.AddSwaggerGen(c =>
            {
                //The generated Swagger JSON file will have these properties.
                c.SwaggerDoc("v1", new Info
                {
                    Title   = "Swagger XML Api Demo",
                    Version = "v1",
                });

                //Locate the XML file being generated by ASP.NET...
                //var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
                //var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                ////... and tell Swagger to use those XML comments.
                //c.IncludeXmlComments(xmlPath);
            });


            services.AddDistributedMemoryCache();

            var storage = new PostgreSqlStorage(Configuration["ConnectionString:dbConnectionString"].ToString());

            //var storage = new PostgreSqlStorage("User ID=postgres;Password=sql321user;Host=localhost;Port=5432;Database=CloudBackup;Pooling=true;");

            Hangfire.GlobalConfiguration.Configuration.UseStorage(storage);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddHangfire(c => c.UseStorage(storage));
        }
        public static void ConfigurationHangfire(this IServiceCollection services, IConfiguration configuration,
                                                 IGlobalConfiguration globalConfiguration)
        {
            var serverProvider = services.BuildServiceProvider();

            var langStr    = configuration.GetSection(HangfireLangKey).Get <string>();
            var envLangStr = GetEnvConfig <string>("Lang");

            if (!string.IsNullOrEmpty(envLangStr))
            {
                langStr = envLangStr;
            }
            if (!string.IsNullOrEmpty(langStr))
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(langStr);
            }

            var hangfireSettings = serverProvider.GetService <IOptions <HangfireSettings> >().Value;

            ConfigFromEnv(hangfireSettings);

            var httpJobOptions = serverProvider.GetService <IOptions <HangfireHttpJobOptions> >().Value;

            ConfigFromEnv(httpJobOptions);

            httpJobOptions.GlobalSettingJsonFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory !, "hangfire",
                                                                    "hangfire_global.json");

            var sqlConnectStr    = configuration.GetSection(HangfireConnectStringKey).Get <string>();
            var envSqlConnectStr = GetEnvConfig <string>("HangfirePostgreConnectionString");

            if (!string.IsNullOrEmpty(envSqlConnectStr))
            {
                sqlConnectStr = envSqlConnectStr;
            }

            PostgreSqlStorage storage = new PostgreSqlStorage(sqlConnectStr);

            globalConfiguration
            .UseStorage(storage)
            .UseConsole(new ConsoleOptions
            {
                BackgroundColor = "#000079"
            })
            .UseTagsWithPostgreSql(new TagsOptions()
            {
                TagsListStyle = TagsListStyle.Dropdown
            })
            .UseHangfireHttpJob(httpJobOptions)
            .UseHeartbeatPage();
        }
Exemplo n.º 19
0
        public static PostgreSqlStorage UseRabbitMq(this PostgreSqlStorage storage, Action <RabbitMqConnectionConfiguration> configureAction, params string[] queues)
        {
            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }
            if (queues == null)
            {
                throw new ArgumentNullException(nameof(queues));
            }
            if (queues.Length == 0)
            {
                throw new ArgumentException("No queue(s) specified for RabbitMQ provider.", nameof(queues));
            }
            if (configureAction == null)
            {
                throw new ArgumentNullException(nameof(configureAction));
            }

            var conf = new RabbitMqConnectionConfiguration();

            configureAction(conf);

            var cf = new ConnectionFactory();

            // Use configuration from URI, otherwise use properties
            if (conf.Uri != null)
            {
                cf.Uri = conf.Uri;
            }
            else
            {
                cf.HostName    = conf.HostName;
                cf.Port        = conf.Port;
                cf.UserName    = conf.Username;
                cf.Password    = conf.Password;
                cf.VirtualHost = conf.VirtualHost;
            }

            var provider = new RabbitMqJobQueueProvider(queues, cf, channel =>
                                                        channel.BasicQos(0, conf.PrefetchCount,
                                                                         false // applied separately to each new consumer on the channel
                                                                         ));

            storage.QueueProviders.Add(provider, queues);

            return(storage);
        }
Exemplo n.º 20
0
        public PostgreSqlMonitoringApiFacts()
        {
            var defaultProvider = new Mock <IPersistentJobQueueProvider>();

            defaultProvider.Setup(x => x.GetJobQueue())
            .Returns(new Mock <IPersistentJobQueue>().Object);

            _queueProviders = new PersistentJobQueueProviderCollection(defaultProvider.Object);
            _options        = new PostgreSqlStorageOptions()
            {
                PrepareSchemaIfNecessary = false,
                SchemaName = ConnectionUtils.GetSchemaName()
            };

            _storage = new PostgreSqlStorage(ConnectionUtils.GetConnectionString(), _options);
        }
Exemplo n.º 21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddDistributedMemoryCache();
            services.AddSession();

            services.AddMvc(config => config.Filters.Add(typeof(TwittSquareAuthorizationFilter)));

            services.AddDbContext <TwitterContext>(x => x.UseNpgsql(Constant.DatabaseConnectionString, b => b.MigrationsAssembly("TwittSquare.ASP.Model")));

            var storage = new PostgreSqlStorage(Configuration.GetConnectionString("DefaultConnection"));

            services.AddHangfire(c => c.UseStorage(storage));
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            var connectionString = "Server=localhost;Port=5432;User Id=fila;Password=123456;Database=hangfire;Pooling=true;";

            var options = new BackgroundJobServerOptions()
            {
                WorkerCount = 10,
            };

            var storage = new PostgreSqlStorage(connectionString, new PostgreSqlStorageOptions()
            {
                InvisibilityTimeout      = TimeSpan.FromMinutes(1),
                PrepareSchemaIfNecessary = true
            });

            using (var server = new BackgroundJobServer(options, storage))
            {
                Console.Title = "Server";
                Console.WriteLine("Pressione qualquer tecla para encerrar.");
                Console.ReadKey();
            }
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            //var memoryStorage = new MemoryStorage();

            var postgreSqlStorage = new PostgreSqlStorage("server=127.0.0.1;database=hangfire_sample;uid=postgres;password=password")
                                    .UseRabbitMq(conf =>
            {
                conf.HostName = "localhost";
            }, "default");

            var container = new Container();

            container.Register(typeof(IX <>), new [] { typeof(IX <>).Assembly });

            var server = new BackgroundJobServer(new BackgroundJobServerOptions()
            {
                Activator = new SimpleInjectorJobActivator(container)
            }, postgreSqlStorage);

            Console.WriteLine("server started");
            Console.ReadKey();

            server.Dispose();
        }
Exemplo n.º 24
0
        private ExpirationManager CreateManager(NpgsqlConnection connection)
        {
            var storage = new PostgreSqlStorage(connection, _options);

            return(new ExpirationManager(storage, _options, TimeSpan.Zero));
        }
Exemplo n.º 25
0
 public ExpirationManagerFacts()
 {
     _storage = new PostgreSqlStorage(ConnectionUtils.GetConnectionString());
     _token   = new CancellationToken(true);
 }
 public PostgreSqlFetchedJobFacts()
 {
     _options = new PostgreSqlStorageOptions();
     _storage = new PostgreSqlStorage(ConnectionUtils.GetConnectionString());
 }
Exemplo n.º 27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            string connectionString = GetConnectionString();

            services.AddAuthorization();
            services.RegisterPermissionHandler();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IDbAppContextFactory, DbAppContextFactory>(CreateDbAppContextFactory);
            services.AddSingleton <IConfiguration>(Configuration);

            // Add database context
            services.AddDbContext <DbAppContext>(options => options.UseNpgsql(connectionString));

            // allow for large files to be uploaded
            services.Configure <FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = 1073741824; // 1 GB
            });

            services.AddResponseCompression();

            // Add framework services.
            services.AddMvc(options => options.AddDefaultAuthorizationPolicyFilter())
            .AddJsonOptions(
                opts => {
                opts.SerializerSettings.ContractResolver     = new CamelCasePropertyNamesContractResolver();
                opts.SerializerSettings.Formatting           = Newtonsoft.Json.Formatting.Indented;
                opts.SerializerSettings.DateFormatHandling   = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
                opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
                // ReferenceLoopHandling is set to Ignore to prevent JSON parser issues with the user / roles model.
                opts.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            // enable Hangfire
            PostgreSqlStorageOptions postgreSqlStorageOptions = new PostgreSqlStorageOptions {
                SchemaName = "public"
            };
            PostgreSqlStorage storage = new PostgreSqlStorage(connectionString, postgreSqlStorageOptions);

            services.AddHangfire(config =>
            {
                config.UseStorage(storage);
                config.UseConsole();
            });

            // Configure Swagger
            services.AddSwaggerGen();
            services.ConfigureSwaggerGen(options =>
            {
                options.SingleApiVersion(new Info
                {
                    Version     = "v1",
                    Title       = "HETS REST API",
                    Description = "Hired Equipment Tracking System"
                });

                options.DescribeAllEnumsAsStrings();

                var comments = new XPathDocument($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml");
                options.OperationFilter <XmlCommentsOperationFilter>(comments);
                options.ModelFilter <XmlCommentsModelFilter>(comments);
            });

            // Add application services.
            services.RegisterApplicationServices();
        }
		private ExpirationManager CreateManager(NpgsqlConnection connection)
		{
			var storage = new PostgreSqlStorage(connection, _options);
			return new ExpirationManager(storage, _options, TimeSpan.Zero);
		}
Exemplo n.º 29
0
        public void ConfigureServices(IServiceCollection services)
        {
            string connectionString = GetConnectionString();

            services.AddAuthorization();
            services.RegisterPermissionHandler();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IDbAppContextFactory, DbAppContextFactory>(CreateDbAppContextFactory);
            services.AddSingleton <IConfiguration>(Configuration);

            // Add database context
            // - Pattern should be using Configuration.GetConnectionString("Schoolbus") directly; see GetConnectionString for more details.
            services.AddDbContext <DbAppContext>(options => options.UseNpgsql(connectionString));

            // allow for large files to be uploaded
            services.Configure <FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = 1073741824; // 1 GB
            });

            services.AddResponseCompression();

            // Add framework services.
            services.AddMvc(options => options.AddDefaultAuthorizationPolicyFilter())
            .AddJsonOptions(
                opts => {
                opts.SerializerSettings.ContractResolver     = new CamelCasePropertyNamesContractResolver();
                opts.SerializerSettings.Formatting           = Newtonsoft.Json.Formatting.Indented;
                opts.SerializerSettings.DateFormatHandling   = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
                opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
                // ReferenceLoopHandling is set to Ignore to prevent JSON parser issues with the user / roles model.
                opts.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            // enable Hangfire
            PostgreSqlStorage storage = new PostgreSqlStorage(connectionString);

            services.AddHangfire(x => x.UseStorage(storage));

            // Configure Swagger
            services.AddSwaggerGen();
            services.ConfigureSwaggerGen(options =>
            {
                options.SingleApiVersion(new Info
                {
                    Version     = "v1",
                    Title       = "SBI REST API",
                    Description = "School Bus Inspection System"
                });

                options.DescribeAllEnumsAsStrings();

                // The swagger API documentation pages look far better with code documentation
                // as input, but we need to protect the application from crashing on startup
                // if the code documetation does not get generated for some reason.
                string codeDocPath = $"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml";
                if (File.Exists(codeDocPath))
                {
                    var comments = new XPathDocument(codeDocPath);
                    options.OperationFilter <XmlCommentsOperationFilter>(comments);
                    options.ModelFilter <XmlCommentsModelFilter>(comments);
                }
            });

            // Add application services.
            services.RegisterApplicationServices();
        }
Exemplo n.º 30
0
        /// <summary>
        /// Add services to the container
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            string connectionString = GetConnectionString();

            // add database context
            services.AddDbContext <DbAppContext>(options => options.UseNpgsql(connectionString));

            // setup siteminder authentication (core 2.0)
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = SiteMinderAuthOptions.AuthenticationSchemeName;
                options.DefaultChallengeScheme    = SiteMinderAuthOptions.AuthenticationSchemeName;
            }).AddSiteminderAuth(options =>
            {
            });

            // setup authorization
            services.AddAuthorization();
            services.RegisterPermissionHandler();

            // allow for large files to be uploaded
            services.Configure <FormOptions>(options =>
            {
                options.MultipartBodyLengthLimit = 1073741824; // 1 GB
            });

            services.AddMvc(options => options.AddDefaultAuthorizationPolicyFilter())
            .AddJsonOptions(
                opts => {
                opts.SerializerSettings.ContractResolver     = new CamelCasePropertyNamesContractResolver();
                opts.SerializerSettings.Formatting           = Newtonsoft.Json.Formatting.Indented;
                opts.SerializerSettings.DateFormatHandling   = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
                opts.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;

                // ReferenceLoopHandling is set to Ignore to prevent JSON parser issues with the user / roles model.
                opts.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

            // enable Hangfire
            PostgreSqlStorageOptions postgreSqlStorageOptions = new PostgreSqlStorageOptions {
                SchemaName = "public"
            };

            PostgreSqlStorage storage = new PostgreSqlStorage(connectionString, postgreSqlStorageOptions);

            services.AddHangfire(config =>
            {
                config.UseStorage(storage);
                config.UseConsole();
            });

            // Configure Swagger - only required in the Development Environment
            if (_hostingEnv.IsDevelopment())
            {
                services.AddSwaggerGen();
                services.ConfigureSwaggerGen(options =>
                {
                    options.SingleApiVersion(new Info
                    {
                        Version     = "v1",
                        Title       = "HETS REST API",
                        Description = "Hired Equipment Tracking System"
                    });

                    options.DescribeAllEnumsAsStrings();
                });
            }

            // Add application services.
            services.RegisterApplicationServices();

            services.AddDistributedMemoryCache(); // Adds a default in-memory cache
            services.AddSession();
        }