// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(config => { config.SwaggerDoc("v1", new OpenApiInfo { Title = "HaotianCloud Api", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); config.IncludeXmlComments(xmlPath, true); //添加控制器层注释(true表示显示控制器注释) }); //缓存选择 if (Configuration.GetSection("SystemConfig:CacheProvider").Value != Define.CACHEPROVIDER_REDIS) { services.AddMemoryCache(); } else { //redis 注入服务 string redisConnectiong = Configuration.GetSection("SystemConfig:RedisConnectionString").Value; // 多客户端 1、基础 2、操作日志 var redisDB1 = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 0); BaseHelper.Initialization(redisDB1); var redisDB2 = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 1); HandleLogHelper.Initialization(redisDB2); services.AddSingleton(redisDB1); services.AddSingleton(redisDB2); } //注入数据库连接 services.AddScoped <Chloe.IDbContext>((serviceProvider) => { return(DBContexHelper.Contex()); }); //代替HttpContext.Current services.AddHttpContextAccessor(); services.AddHttpClient(); services.AddOptions(); //跨域 services.AddCors(); services.AddControllers(options => { options.Filters.Add <ModelActionFilter>(); options.ModelMetadataDetailsProviders.Add(new ModelBindingMetadataProvider()); }).AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }).ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; }); services.AddControllers().AddControllersAsServices(); services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(GlobalContext.HostingEnvironment.ContentRootPath + Path.DirectorySeparatorChar + "DataProtection")); GlobalContext.SystemConfig = Configuration.GetSection("SystemConfig").Get <SystemConfig>(); GlobalContext.Services = services; GlobalContext.Configuration = Configuration; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddSession(); //代替HttpContext.Current services.AddHttpContextAccessor(); //缓存缓存选择 if (Configuration.GetSection("SystemConfig:CacheProvider").Value != Define.CACHEPROVIDER_REDIS) { services.AddMemoryCache(); } else { //redis 注入服务 string redisConnectiong = Configuration.GetSection("SystemConfig:RedisConnectionString").Value; // 多客户端 1、基础 2、操作日志 var redisDB1 = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 0); BaseHelper.Initialization(redisDB1); var redisDB2 = new CSRedisClient(redisConnectiong + ",defaultDatabase=" + 1); HandleLogHelper.Initialization(redisDB2); services.AddSingleton(redisDB1); services.AddSingleton(redisDB2); } #region 依赖注入 //注入数据库连接 services.AddScoped <Chloe.IDbContext>((serviceProvider) => { return(DBContexHelper.Contex()); }); #region 注入 Quartz调度类 services.AddSingleton <JobCenter>(); services.AddSingleton <JobExecute>(); //注册ISchedulerFactory的实例。 services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>(); services.AddSingleton <IJobFactory, IOCJobFactory>(); #endregion //注入SignalR实时通讯,默认用json传输 services.AddSignalR(options => { //客户端发保持连接请求到服务端最长间隔,默认30秒,改成4分钟,网页需跟着设置connection.keepAliveIntervalInMilliseconds = 12e4;即2分钟 options.ClientTimeoutInterval = TimeSpan.FromMinutes(4); //服务端发保持连接请求到客户端间隔,默认15秒,改成2分钟,网页需跟着设置connection.serverTimeoutInMilliseconds = 24e4;即4分钟 options.KeepAliveInterval = TimeSpan.FromMinutes(2); }); ////注册html解析 //services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All)); ////注册特性 //services.AddScoped<HandlerLoginAttribute>(); //services.AddScoped<HandlerAuthorizeAttribute>(); ////ajax不能使用注入 ////services.AddScoped<HandlerAjaxOnlyAttribute>(); //services.AddScoped<HandlerAdminAttribute>(); //////定时任务(已废除) ////services.AddBackgroundServices(); #endregion services.AddHttpClient(); services.AddControllersWithViews(options => { options.Filters.Add <GlobalExceptionFilter>(); options.Filters.Add <ModelActionFilter>(); options.ModelMetadataDetailsProviders.Add(new ModelBindingMetadataProvider()); options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }).AddNewtonsoftJson(options => { // 返回数据首字母不小写,CamelCasePropertyNamesContractResolver是小写 options.SerializerSettings.ContractResolver = new DefaultContractResolver(); }); services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN"); services.AddControllersWithViews().AddControllersAsServices(); //调试前端可更新 services.AddControllersWithViews().AddRazorRuntimeCompilation(); services.AddOptions(); services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(GlobalContext.HostingEnvironment.ContentRootPath + Path.DirectorySeparatorChar + "DataProtection")); GlobalContext.SystemConfig = Configuration.GetSection("SystemConfig").Get <SystemConfig>(); GlobalContext.Services = services; GlobalContext.Configuration = Configuration; //更新数据库管理员和主系统 try { var context = DBContexHelper.Contex(); var _setService = new Service.SystemOrganize.SystemSetService(context); Domain.SystemOrganize.SystemSetEntity temp = new Domain.SystemOrganize.SystemSetEntity(); temp.F_AdminAccount = GlobalContext.SystemConfig.SysemUserCode; temp.F_AdminPassword = GlobalContext.SystemConfig.SysemUserPwd; temp.F_DBProvider = GlobalContext.SystemConfig.DBProvider; temp.F_DbString = GlobalContext.SystemConfig.DBConnectionString; _setService.SubmitForm(temp, GlobalContext.SystemConfig.SysemMasterProject); } catch (Exception ex) { LogHelper.Write(ex); } }
public Task Execute(IJobExecutionContext context) { return(Task.Run(async() => { string jobId = ""; JobDataMap jobData = null; OpenJobEntity dbJobEntity = null; DateTime now = DateTime.Now; try { jobData = context.JobDetail.JobDataMap; jobId = jobData["F_Id"].ToString(); using (IDbContext _context = DBContexHelper.Contex()) { OpenJobsService autoJobService = new OpenJobsService(_context, _schedulerFactory, _iocJobfactory); // 获取数据库中的任务 dbJobEntity = await autoJobService.GetForm(jobId); if (dbJobEntity != null) { if (dbJobEntity.F_EnabledMark == true) { CronTriggerImpl trigger = context.Trigger as CronTriggerImpl; if (trigger != null) { if (trigger.CronExpressionString != dbJobEntity.F_CronExpress) { // 更新任务周期 trigger.CronExpressionString = dbJobEntity.F_CronExpress; await _scheduler.RescheduleJob(trigger.Key, trigger); return; } #region 执行任务 _context.Session.BeginTransaction(); //反射执行就行 var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory; //反射取指定前后缀的dll var referencedAssemblies = Directory.GetFiles(path, "HaotianCloud.*.dll").Select(Assembly.LoadFrom).ToArray(); var types = referencedAssemblies .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces() .Contains(typeof(IJobTask)))).ToArray(); string filename = dbJobEntity.F_FileName; var implementType = types.Where(x => x.IsClass && x.FullName == filename).FirstOrDefault(); var obj = System.Activator.CreateInstance(implementType, _context); // 创建实例(带参数) MethodInfo method = implementType.GetMethod("Start", new Type[] { }); // 获取方法信息 object[] parameters = null; var temp = (Task <AlwaysResult>)method.Invoke(obj, parameters); // 调用方法,参数为空 #endregion //需要同步,不然数据库连接会断开 _context.Update <OpenJobEntity>(t => t.F_Id == jobId, a => new OpenJobEntity { F_LastRunTime = now }); OpenJobLogEntity log = new OpenJobLogEntity(); log.F_Id = Utils.GuId(); log.F_JobId = jobId; log.F_JobName = dbJobEntity.F_JobName; log.F_CreatorTime = now; if (temp.Result.state.ToString() == ResultType.success.ToString()) { log.F_EnabledMark = true; log.F_Description = "执行成功," + temp.Result.message.ToString(); } else { log.F_EnabledMark = false; log.F_Description = "执行失败," + temp.Result.message.ToString(); } string HandleLogProvider = GlobalContext.SystemConfig.HandleLogProvider; if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { _context.Insert(log); } else { await HandleLogHelper.HSetAsync(log.F_JobId, log.F_Id, log); } _context.Session.CommitTransaction(); } } } } } catch (Exception ex) { LogHelper.WriteWithTime(ex); } })); }
public async Task SubmitForm(SystemSetEntity entity, string keyValue) { IRepositoryBase ibs = new RepositoryBase(_context); if (string.IsNullOrEmpty(keyValue)) { entity.F_DeleteMark = false; //此处需修改 entity.Create(); await repository.Insert(entity); await CacheHelper.Remove(cacheKey + "list"); } else { //此处需修改 entity.Modify(keyValue); if (currentuser.UserId != GlobalContext.SystemConfig.SysemUserId || currentuser.UserId == null) { var setentity = await repository.FindEntity(entity.F_Id); uniwork.BeginTrans(); var user = uniwork.IQueryable <UserEntity>(a => a.F_OrganizeId == entity.F_Id && a.F_IsAdmin == true).FirstOrDefault(); var userinfo = uniwork.IQueryable <UserLogOnEntity>(a => a.F_UserId == user.F_Id).FirstOrDefault(); userinfo.F_UserSecretkey = Md5.md5(Utils.CreateNo(), 16).ToLower(); userinfo.F_UserPassword = Md5.md5(DESEncrypt.Encrypt(Md5.md5(entity.F_AdminPassword, 32).ToLower(), userinfo.F_UserSecretkey).ToLower(), 32).ToLower(); await uniwork.Update <UserEntity>(a => a.F_Id == user.F_Id, a => new UserEntity { F_Account = entity.F_AdminAccount }); await CacheHelper.Remove(cacheKeyUser + user.F_Id); await uniwork.Update <UserLogOnEntity>(a => a.F_Id == userinfo.F_Id, a => new UserLogOnEntity { F_UserPassword = userinfo.F_UserPassword, F_UserSecretkey = userinfo.F_UserSecretkey }); await uniwork.Update(entity); uniwork.Commit(); } else { entity.F_AdminAccount = null; entity.F_AdminPassword = null; } await ibs.Update(entity); await CacheHelper.Remove(cacheKey + keyValue); await CacheHelper.Remove(cacheKey + "list"); } var set = await ibs.FindEntity <SystemSetEntity>(entity.F_Id); var tempkey = new RepositoryBase(DBContexHelper.Contex(set.F_DbString, set.F_DBProvider)).IQueryable <UserEntity>().Where(a => a.F_IsAdmin == true && a.F_OrganizeId == keyValue).FirstOrDefault().F_Id; await CacheHelper.Remove(cacheKeyOperator + "info_" + tempkey); if (currentuser.UserId == null) { _context.Dispose(); } }