예제 #1
0
        public static void Register(IAppBuilder app)
        {
            GlobalConfiguration.Configuration
            .UseDashboardMetric(DashboardMetrics.ServerCount)
            .UseDashboardMetric(DashboardMetrics.RecurringJobCount)
            .UseDashboardMetric(DashboardMetrics.RetriesCount)
            .UseDashboardMetric(DashboardMetrics.EnqueuedCountOrNull)
            .UseDashboardMetric(DashboardMetrics.FailedCountOrNull)
            .UseDashboardMetric(DashboardMetrics.EnqueuedAndQueueCount)
            .UseDashboardMetric(DashboardMetrics.ScheduledCount)
            .UseDashboardMetric(DashboardMetrics.ProcessingCount)
            .UseDashboardMetric(DashboardMetrics.SucceededCount)
            .UseDashboardMetric(DashboardMetrics.FailedCount)
            .UseDashboardMetric(DashboardMetrics.DeletedCount)
            .UseDashboardMetric(DashboardMetrics.AwaitingCount)
            .UseManagementPages(cc => cc.AddJobs(() => { return(GetModuleTypes()); }))
            .UseSQLiteStorage(DbConnectionName)
            .UseConsole()
            ;
            var options = new BackgroundJobServerOptions
            {
                ServerName  = $"{Environment.MachineName}.{Guid.NewGuid().ToString()}",
                WorkerCount = 20,
                Queues      = new[] { "critical", "normal", "low" }
            };
            var dashboardOptions = new DashboardOptions
            {
                Authorization = new IDashboardAuthorizationFilter[] { new DashboardAuthorizationFilter() }
            };

            app.UseHangfireDashboard(Url, dashboardOptions);

            //app.UseHangfireServer(options);
            app.UseHangfireServer();
        }
예제 #2
0
파일: Startup.cs 프로젝트: adouv/CGT.API
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseStaticFiles();

            var options = new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            };

            app.UseHangfireServer();
            app.UseHangfireDashboard("/hangfire", options);

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

            var TaskFactory = svp.GetService <TaskQuest>();

            TaskFactory.Reset();
            TaskFactory.InitTaskPage();
            TaskFactory.InitTaskList();
        }
예제 #3
0
        public static BuildFunc UseHangfireDashboard(
            [NotNull] this BuildFunc builder,
            [NotNull] DashboardOptions options,
            [NotNull] JobStorage storage,
            [NotNull] RouteCollection routes)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (storage == null)
            {
                throw new ArgumentNullException("storage");
            }
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

            builder(_ => UseHangfireDashboard(options, storage, routes));

            return(builder);
        }
예제 #4
0
        /// <summary>
        /// Extension method used to add the dashboard UI of Hangfire.
        /// </summary>
        /// <param name="builder">The application builder.</param>
        public static void UseCustomHangfireDashboard(this IApplicationBuilder builder)
        {
            Ensure.ArgumentNotNull(builder, nameof(builder));

            string pathMatch = "/hangfire";
            string appPath   = "/account/login";

            builder.UseStatusCodePages(context =>
            {
                var request  = context.HttpContext.Request;
                var response = context.HttpContext.Response;

                if (request.Path.HasValue && request.Path.Value.StartsWith(pathMatch) &&
                    response.StatusCode == (int)HttpStatusCode.Unauthorized)
                {
                    response.Redirect(appPath);
                }

                return(Task.CompletedTask);
            });

            var options = new DashboardOptions
            {
                Authorization = new[] { new CustomHangfireAuthorizationFilter() },
                AppPath       = appPath
            };

            builder.UseHangfireDashboard(pathMatch, options);
        }
예제 #5
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var configuration = app.ApplicationServices.GetRequiredService <IConfiguration>();

            if (configuration.GetSection("ApiProfilerEnabled").Get <bool>())
            {
                var miniOpts = app.ApplicationServices.GetRequiredService <IOptions <MiniProfilerOptions> >();
                var auth     = app.ApplicationServices.GetRequiredService <IOptions <ApiProfilerAuthOptions> >();

                if (!string.IsNullOrWhiteSpace(miniOpts?.Value?.RouteBasePath) &&
                    !string.IsNullOrWhiteSpace(auth?.Value?.Username) &&
                    !string.IsNullOrWhiteSpace(auth?.Value?.Password))
                {
                    var filterOptions = new BasicAuthAuthorizationFilterOptions
                    {
                        RequireSsl         = false,
                        SslRedirect        = false,
                        LoginCaseSensitive = true,
                        Users = new[] { new BasicAuthAuthorizationUser {
                                            Login = auth?.Value?.Username, PasswordClear = auth?.Value?.Password
                                        } }
                    };
                    var options = new DashboardOptions
                    {
                        Authorization = new[] { new BasicAuthAuthorizationFilter(filterOptions) }
                    };

                    // 必须在需要控制的中间件之前执行
                    app.UseWhen(context => context.Request.Path.StartsWithSegments(new PathString(miniOpts.Value.RouteBasePath)),
                                x => x.UseMiddleware <AspNetCoreDashboardMiddleware>(options));
                }

                app.UseCsaApiProfiler();
            }
        }
예제 #6
0
        public void ConfigureOwin(IAppBuilder app, IUnityContainer container)
        {
            JobStorage.Current = CreateJobStorage(Stage.ConfigureOwin);

            // Configure Hangfire dashboard

            var securityService          = container.Resolve <ISecurityService>();
            var moduleInitializerOptions = container.Resolve <IModuleInitializerOptions>();

            var appPath = "/" + moduleInitializerOptions.RoutePrefix;

            var authorizationFilters = new[]
            {
                new PermissionBasedAuthorizationFilter(securityService)
                {
                    Permission = PredefinedPermissions.BackgroundJobsManage
                }
            };

            var dashboardOptions = new DashboardOptions
            {
                AppPath       = appPath,
                Authorization = authorizationFilters
            };

            app.UseHangfireDashboard(appPath + "hangfire", dashboardOptions);

            // Configure Hangfire server
            if (_options.StartServer)
            {
                app.UseHangfireServer(new BackgroundJobServerOptions {
                    Activator = new UnityJobActivator(container)
                });
            }
        }
예제 #7
0
        public void Configuration(IAppBuilder app)
        {
            var authorizationFilter = new BasicAuthAuthorizationFilter(
                new BasicAuthAuthorizationFilterOptions
            {
                // Require secure connection for dashboard
                RequireSsl = true,
                // Case sensitive login checking
                LoginCaseSensitive = true,
                // Users
                Users = new[]
                {
                    new BasicAuthAuthorizationUser
                    {
                        Login         = "******",
                        PasswordClear = "passW0rd!"
                    }
                }
            });

            var options = new DashboardOptions
            {
                AuthorizationFilters = new IAuthorizationFilter[]
                {
                    authorizationFilter
                }
            };

            GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection");

            app.UseHangfireDashboard("/hangfire", options);
            app.UseHangfireServer();

            ConfigureAuth(app);
        }
예제 #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            var hangFireAuth = new DashboardOptions()
            {
                Authorization = new[]
                {
                    new HangFireAuthorization(app.ApplicationServices.GetService <IAuthorizationService>(),
                                              app.ApplicationServices.GetService <IHttpContextAccessor>()),
                }
            };

            app.UseHangfireServer();

            RecurringJob.AddOrUpdate <IGenerateDailySalesReport>(s => s.ForAllCustomers(), Cron.Daily);

            var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("a Fire-and-forget job!"));

            BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("a Continuation!"));

            app.UseHangfireDashboard("/hangfire", hangFireAuth);
        }
예제 #9
0
        public static MidFunc UsePugTraceDashboard(
            DashboardOptions options,
            TraceStorage storage,
            RouteCollection routes)
        {
            if (options == null) throw new ArgumentNullException("options");
            if (routes == null) throw new ArgumentNullException("routes");

            return
                next =>
                env =>
                {
                    var context = new OwinContext(env);
                    var dispatcher = routes.FindDispatcher(context.Request.Path.Value);

                    if (dispatcher == null)
                    {
                        return next(env);
                    }

                    if (options.AuthorizationFilters.Any(filter => !filter.Authorize(context.Environment)))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        return Task.FromResult(false);
                    }

                    var dispatcherContext = new RequestDispatcherContext(
                        options.AppPath,
                        storage,
                        context.Environment,
                        dispatcher.Item2);

                    return dispatcher.Item1.Dispatch(dispatcherContext);
                };
        }
예제 #10
0
        public static void UseAuthenticatedHangfireDashboard(this IApplicationBuilder app, IConfiguration configuration)
        {
            var filter = new BasicAuthAuthorizationFilter(
                new BasicAuthAuthorizationFilterOptions
            {
                // Require secure connection for dashboard
                RequireSsl  = false,
                SslRedirect = false,
                // Case sensitive login checking
                LoginCaseSensitive = true,
                // Users
                Users = new[]
                {
                    new BasicAuthAuthorizationUser
                    {
                        Login = configuration["Hangfire:Dashboard:Username"],
                        // Password as plain text, SHA1 will be used
                        PasswordClear = configuration["Hangfire:Dashboard:Password"]
                    }
                }
            });

            var options = new DashboardOptions
            {
                DashboardTitle = "De Urgenta Hangfire Dashboard",
                Authorization  = new IDashboardAuthorizationFilter[]
                {
                    filter
                }
            };

            app.UseHangfireDashboard(options: options);
        }
예제 #11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // enable buffering so our authentication stuff in ApiController can re-read the body after MVC
            app.Use((context, next) =>
            {
                context.Request.EnableBuffering();
                return(next());
            });

            // add CSP header
            app.Use(async(context, next) =>
            {
                context.Response.Headers.Add(
                    "Content-Security-Policy",
                    "default-src 'self'; script-src 'self'; style-src 'unsafe-inline' 'self'; img-src 'self' data:;");
                await next();
            });

            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });

            var options = new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            };

            app.UseHangfireDashboard("/hangfire", options);
            app.UseHangfireServer();
            RecurringJob.AddOrUpdate <IWalletProvider>(
                provider => provider.UpdateBlockchainWallets(), "0 */5 * ? * *");                        // every 5 minutes
            RecurringJob.AddOrUpdate <IBroker>(
                broker => broker.ProcessOrders(), "0 */5 * ? * *");                                      // every 5 minutes
            RecurringJob.AddOrUpdate <IDepositsWithdrawals>(
                depositsWithdrawals => depositsWithdrawals.ProcessChainDeposits(), "0 */10 * ? * *");    // every 10 minutes
            RecurringJob.AddOrUpdate <IDepositsWithdrawals>(
                depositsWithdrawals => depositsWithdrawals.ProcessChainWithdrawals(), "0 */10 * ? * *"); // every 10 minutes
            RecurringJob.AddOrUpdate <IDepositsWithdrawals>(
                depositsWithdrawals => depositsWithdrawals.ProcessFiatWithdrawals(), "0 */10 * ? * *");  // every 10 minutes

            var defaultLogLevel = Configuration.GetSection("Logging").GetSection("LogLevel").GetValue <LogLevel>("Default");

            loggerFactory.AddFile("logs/viafront-{Date}.txt", defaultLogLevel);
        }
        protected override void EndProcessing()
        {
            Log.Info($"{Name} - {MyInvocation.ScriptName} - {AutoReload}");

            if (string.IsNullOrEmpty(MyInvocation.ScriptName) && AutoReload)
            {
                WriteWarning("AutoReload does not work on the command line. You must save your file as a script.");
            }

            var server = new Server(Name, MyInvocation.ScriptName, AutoReload, Host, Port);

            var options = new DashboardOptions();

            options.StaticEndpoints             = Endpoint;
            options.Port                        = Port;
            options.Wait                        = Wait;
            options.Certificate                 = Certificate;
            options.CertificateFile             = CertificateFile;
            options.Password                    = CertificateFilePassword;
            options.EndpointInitialSessionState = EndpointInitialization;
            options.PublishedFolders            = PublishedFolder;

            try
            {
                server.Start(options);
            }
            catch (AggregateException ex)
            {
                Log.Error("Failed to start dashboard.", ex);
                throw ex.GetBaseException();
            }

            WriteObject(server);
        }
예제 #13
0
        public static IApplicationBuilder UseRostamBotLibraries(this IApplicationBuilder app, IConfiguration configuration, string _apiVersion)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"/swagger/v{_apiVersion}/swagger.json", $"RostamBot API v{_apiVersion}");
                c.DocumentTitle = "RostamBot API";
                c.DocExpansion(DocExpansion.List);
            });


            var hangfireDashboardOptions = new DashboardOptions
            {
                Authorization  = new[] { new HangfireDashboardAuthorizationFilter(configuration) },
                IsReadOnlyFunc = (DashboardContext context) => true,
                DisplayStorageConnectionString = false,
                StatsPollingInterval           = 30000
            };

            app.UseHangfireDashboard(configuration["RostamBotSettings:JobDashboardUrl"], hangfireDashboardOptions);

            //ToDo: remove magic numbers
            GlobalJobFilters.Filters.Add(new AutomaticRetryAttribute {
                Attempts = 2, DelaysInSeconds = new int[] { 1200, 1200 }
            });
            app.UseHangfireServer();

            RecurringJob.AddOrUpdate <ISyncReportsJob>(job => job.GetMentionsAsync(), Cron.MinuteInterval(20));
            RecurringJob.AddOrUpdate <ISyncReportsJob>(job => job.GetDirectsAsync(), Cron.MinuteInterval(20));


            return(app);
        }
예제 #14
0
        public static void ConfigureHangfire(this IAppBuilder app, IKernel kernel = null)
        {
            var configuration = GlobalConfiguration.Configuration;

            configuration.UseMemoryStorage();
            configuration
            .UseConsole()
            .UseNinjectActivator(kernel);

            var jobServerOptions = new BackgroundJobServerOptions
            {
                ServerName = "HangfireDemo",
                Queues     = JobQueues.All
            };

            app.UseHangfireServer(jobServerOptions);

            var dashboardOptions = new DashboardOptions
            {
                Authorization = new[] { new AllowAllAuthorizationFilter() }
            };

            app.UseHangfireDashboard("/integration", dashboardOptions);

            // Recurring Jobs
            RecurringJob.AddOrUpdate <IIntervalJob>(job => job.CheckPing(null), Cron.Minutely, queue: JobQueues.Recurring);
        }
예제 #15
0
        public static void Register(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "HangfireLogin"
            });

            GlobalConfiguration.Configuration
            .UseConsole()
            .UseSqlServerStorage("Hangfire")
            .UseNLogLogProvider()
            //.UseMemoryStorage()
            ;
            IDashboardAuthorizationFilter dashboardAuthorization = null;

#if DEV
            dashboardAuthorization = new DashboardAuthorizationFilter();
#else
            dashboardAuthorization = new DashboardBasicAuthorizationFilter();
#endif
            var dashboardOptions = new DashboardOptions
            {
                Authorization = new[]
                {
                    dashboardAuthorization
                }
            };

            app.UseHangfireDashboard("/hangfire", dashboardOptions);
            app.UseHangfireServer();
        }
예제 #16
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            GlobalConfiguration.Configuration
            .UseSqlServerStorage(Settings.HangfireConnectionString);

            var options = new DashboardOptions()
            {
                Authorization = new[]
                {
                    new HangfireDashBoardAuthenticationFilter()
                }
            };

            app.UseHangfireDashboard("/hangfire", options);
            app.UseHangfireServer(new BackgroundJobServerOptions()
            {
                WorkerCount = Environment.ProcessorCount,
            });

            ConfigureJobs();


            if (Path.IsPathRooted(Settings.ImagesServerUploadPath))
            {
                Settings.imagesHDD_Path = Path.Combine(Settings.ImagesServerUploadPath);
            }
            else
            {
                Settings.imagesHDD_Path = Path.Combine(HttpRuntime.AppDomainAppPath, Settings.ImagesServerUploadPath);
            }
        }
예제 #17
0
        public async Task InvokeAsync(HttpContext context)
        {
            var tenant = (AppTenant)context.Items["_tenant"];

            var connectionString = tenant.GetConnectionString("HangfireConnection") ?? (_configuration.GetSection("ConnectionStrings").GetChildren().Any(x => x.Key == "HangfireConnection") ? _configuration.GetConnectionString("HangfireConnection") : null);

            if (connectionString != null)
            {
                JobStorage storage;
                if (string.IsNullOrWhiteSpace(connectionString))
                {
                    storage = new MemoryStorage();
                }
                if (ConnectionStringHelper.IsSQLite(connectionString))
                {
                    storage = new SQLiteStorage(connectionString);
                }
                else
                {
                    storage = new SqlServerStorage(connectionString);
                }

                var options = new DashboardOptions
                {
                    Authorization = new[] { new HangfireAuthorizationfilter() },
                    AppPath       = _route.Replace("/hangfire", "")
                };

                var middleware = new AspNetCoreDashboardMiddleware(_next, storage, options, _routes);
                await middleware.Invoke(context);
            }

            context.Response.StatusCode = (int)HttpStatusCode.NotFound;
        }
예제 #18
0
        public void Configuration(IAppBuilder app)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <ReadWriteDataContext, Configuration>());
            using (var c = new ReadWriteDataContext())
                c.Database.Initialize(true);

            GlobalConfiguration.Configuration.UseSqlServerStorage(ReadWriteDataContext.READ_WRITE_CONNECTION_STRING_NAME, new SqlServerStorageOptions
            {
                JobExpirationCheckInterval = TimeSpan.FromMinutes(5)
            });


            if (Utils.GlobalConfiguration.EnableHangfire)
            {
                Pollers.StartPolling();

                app.UseHangfireServer();

                var options = new DashboardOptions
                {
                    AppPath = VirtualPathUtility.ToAbsolute("~"),
                    AuthorizationFilters = new[] { new RemoveAuthorizationFilter() }
                };
                app.UseHangfireDashboard("/hangfire", options);
                GlobalJobFilters.Filters.Add(new ImmediatelyExpireSuccessfulJobs());
            }
        }
예제 #19
0
        public static BuildFunc UseHangfireDashboard(
            [NotNull] this BuildFunc builder,
            [NotNull] DashboardOptions options,
            [NotNull] JobStorage storage,
            [NotNull] RouteCollection routes,
            [CanBeNull] IOwinDashboardAntiforgery antiforgery)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }
            if (routes == null)
            {
                throw new ArgumentNullException(nameof(routes));
            }

            builder(_ => UseHangfireDashboard(options, storage, routes, antiforgery));

            return(builder);
        }
        public AspNetCoreDashboardContext(
            [NotNull] JobStorage storage,
            [NotNull] DashboardOptions options,
            [NotNull] HttpContext httpContext)
            : base(storage, options)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            HttpContext = httpContext;
            Request     = new AspNetCoreDashboardRequest(httpContext);
            Response    = new AspNetCoreDashboardResponse(httpContext);

            var antiforgery = HttpContext.RequestServices.GetService <IAntiforgery>();

            if (antiforgery != null)
            {
                var tokenSet = antiforgery.GetAndStoreTokens(HttpContext);

                AntiforgeryHeader = tokenSet.HeaderName;
                AntiforgeryToken  = tokenSet.RequestToken;
            }
        }
예제 #21
0
        public static IApplicationBuilder UseHangfireDashboard(
            [NotNull] this IApplicationBuilder builder,
            [NotNull] string pathMatch,
            [NotNull] DashboardOptions options,
            [NotNull] JobStorage storage)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (pathMatch == null)
            {
                throw new ArgumentNullException(nameof(pathMatch));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }

            return(builder.Map(pathMatch, subApp =>
            {
                subApp.UseOwin(next =>
                {
                    next(MiddlewareExtensions.UseHangfireDashboard(options, storage, DashboardRoutes.Routes));
                });
            }));
        }
예제 #22
0
        /// <summary>
        /// 应用AspNetCore的服务业务
        /// </summary>
        /// <param name="app">Asp应用程序构建器</param>
        public override void UsePack(IApplicationBuilder app)
        {
            IServiceProvider serviceProvider = app.ApplicationServices;
            IConfiguration   configuration   = serviceProvider.GetService <IConfiguration>();
            bool             enabled         = configuration["OSharp:Hangfire:Enabled"].CastTo(false);

            if (!enabled)
            {
                return;
            }

            IGlobalConfiguration globalConfiguration = serviceProvider.GetService <IGlobalConfiguration>();

            globalConfiguration.UseLogProvider(new AspNetCoreLogProvider(serviceProvider.GetService <ILoggerFactory>()));

            BackgroundJobServerOptions serverOptions = GetBackgroundJobServerOptions(configuration);

            app.UseHangfireServer(serverOptions);

            string           url = configuration["OSharp:Hangfire:DashboardUrl"].CastTo("/hangfire");
            DashboardOptions dashboardOptions = GetDashboardOptions(configuration);

            app.UseHangfireDashboard(url, dashboardOptions);

            IHangfireJobRunner jobRunner = serviceProvider.GetService <IHangfireJobRunner>();

            jobRunner?.Start();

            IsEnabled = true;
        }
예제 #23
0
        public AspNetCoreDashboardMiddleware(
            [NotNull] RequestDelegate next,
            [NotNull] JobStorage storage,
            [NotNull] DashboardOptions options,
            [NotNull] RouteCollection routes)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }
            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (routes == null)
            {
                throw new ArgumentNullException(nameof(routes));
            }

            _next    = next;
            _storage = storage;
            _options = options;
            _routes  = routes;
        }
예제 #24
0
 public HangfireDashboardMiddleware(RequestDelegate next, JobStorage storage, DashboardOptions options, RouteCollection routes)
 {
     _next    = next;
     _storage = storage;
     _options = options;
     _routes  = routes;
 }
예제 #25
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IBackgroundJobClient backgroundJobs)
        {
            loggerFactory.AddFile(Configuration.GetSection("Logging"));
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
            app.UseDeveloperExceptionPage();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseSession();
            app.UseAuthentication();

            //app.UseHttpsRedirection();
            app.UseCookiePolicy();


            var options = new DashboardOptions
            {
                Authorization = new[] { new HFAuthorizationFilter() }
            };

            app.UseHangfireDashboard(options: options);
            app.UseHangfireServer();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "main",
                    template: "{controller=Home}/{action=Index}");
                routes.MapRoute(
                    name: "request",
                    template: "{controller=Request}/{action}/{requestId?}");
            });
        }
예제 #26
0
        private void ConfigureDashboard(IApplicationBuilder app)
        {
            _logger.LogInformation("Enabling Hangfire dashboard");
            var dashboardOptions = new DashboardOptions();

            if (_options.Dasbhoard.EnableAuthorization)
            {
                var loggerFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>();

                DashboardAuthorizationFilter dashboardAuthorizationFilter;
                if (_options.Dasbhoard.AuthorizationCallback != null)
                {
                    _logger.LogInformation("Configuring Hangfire dashboard authorization with custom callback");
                    dashboardAuthorizationFilter = new DashboardAuthorizationFilter(_options.Dasbhoard.AuthorizationCallback, loggerFactory);
                }
                else if (_options.Dasbhoard.AllowedIps?.Length > 0)
                {
                    _logger.LogInformation("Configuring Hangfire IP-based dashboard authorization");
                    dashboardAuthorizationFilter = new DashboardAuthorizationFilter(app.ApplicationServices.GetRequiredService <IHostingEnvironment>(), _options.Dasbhoard.AllowedIps, loggerFactory);
                }
                else
                {
                    throw new InvalidOperationException("No custom authorization callback or allowed IP-addresses configured for Hangfire dashboard authorization.");
                }

                dashboardOptions.Authorization = new[] { dashboardAuthorizationFilter };
            }

            app.UseHangfireDashboard(options: dashboardOptions);
        }
예제 #27
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else if (env.IsProduction())
            {
                app.UseHttpsRedirection();
            }

            app.UseCors("Cors");

            app.UseRouting();

            var dashboardOption = new DashboardOptions
            {
                Authorization = new[] {
                    new HangfireCustomBasicAuthenticationFilter {
                        User = EnvironmentVariables.HangfireUser, Pass = EnvironmentVariables.HangfirePassword
                    }
                }
            };

            app.UseHangfireDashboard("/hangfire", dashboardOption);

            app.UseAuthorization();
            app.UseEndpoints(endpoints => endpoints.MapControllers());
        }
예제 #28
0
        public async Task Execute(IJobExecutionContext context)
        {
            _storage = _storage ?? ServiceContainer.provider.GetService(typeof(IHttpReportsStorage)) as IHttpReportsStorage;
            _options = _options ?? (ServiceContainer.provider.GetService(typeof(IOptions <DashboardOptions>)) as IOptions <DashboardOptions>).Value;

            await _storage.ClearData(DateTime.Now.AddDays(-_options.ExpireDay).ToString("yyyy-MM-dd"));
        }
예제 #29
0
 public DashboardEMailHelper(
     IOptionsMonitor <DashboardOptions> optionsMonitor,
     IFulfillmentClient fulfillmentClient)
 {
     this.fulfillmentClient = fulfillmentClient;
     this.options           = optionsMonitor.CurrentValue;
 }
예제 #30
0
        public static IAppBuilder UsePdfview(
            [NotNull] this IAppBuilder builder,
            [NotNull] string pathMatch,
            [NotNull] DashboardOptions options
            )
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (pathMatch == null)
            {
                throw new ArgumentNullException(nameof(pathMatch));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            SignatureConversions.AddConversions(builder);

            Resource.Setting.ModuleName = pathMatch.Trim('/').Replace("/", ".");
            builder.Map(pathMatch, subApp => subApp.UseOwin().UseModuleActivator(options, Resource.Setting.Routes));

            return(builder);
        }
예제 #31
0
 public static IApplicationBuilder UseHangfireDashboard(
     [NotNull] this IApplicationBuilder builder,
     [NotNull] string pathMatch,
     [NotNull] DashboardOptions options)
 {
     return(builder.UseHangfireDashboard(pathMatch, options, JobStorage.Current));
 }
예제 #32
0
        public static BuildFunc UsePugTraceDashboard(
            this BuildFunc builder,
            DashboardOptions options,
            TraceStorage storage,
            RouteCollection routes)
        {
            if (builder == null) throw new ArgumentNullException("builder");
            if (options == null) throw new ArgumentNullException("options");
            if (routes == null) throw new ArgumentNullException("routes");

            builder(_ => UsePugTraceDashboard(options, storage, routes));

            return builder;
        }
        public AspNetCoreDashboardMiddleware(
            [NotNull] RequestDelegate next,
            [NotNull] JobStorage storage,
            [NotNull] DashboardOptions options,
            [NotNull] RouteCollection routes)
        {
            if (next == null) throw new ArgumentNullException(nameof(next));
            if (storage == null) throw new ArgumentNullException(nameof(storage));
            if (options == null) throw new ArgumentNullException(nameof(options));
            if (routes == null) throw new ArgumentNullException(nameof(routes));

            _next = next;
            _storage = storage;
            _options = options;
            _routes = routes;
        }