public async Task RemoveLog(string keepTime) { DateTime operateTime = DateTime.Now; if (keepTime == "7") //保留近一周 { operateTime = DateTime.Now.AddDays(-7); } else if (keepTime == "1") //保留近一个月 { operateTime = DateTime.Now.AddMonths(-1); } else if (keepTime == "3") //保留近三个月 { operateTime = DateTime.Now.AddMonths(-3); } if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { var expression = ExtLinq.True <LogEntity>(); expression = expression.And(t => t.F_Date <= operateTime); await repository.Delete(expression); } else { var list = HandleLogHelper.HGetAll <LogEntity>(currentuser.CompanyId).Values.ToList(); var strList = list.Where(t => t.F_Date <= operateTime).Select(a => a.F_Id).ToList(); await HandleLogHelper.HDelAsync(currentuser.CompanyId, strList.ToArray()); } }
public async Task WriteDbLog(LogEntity logEntity) { logEntity.F_Id = Utils.GuId(); logEntity.F_Date = DateTime.Now; try { if (currentuser == null || string.IsNullOrEmpty(currentuser.UserId)) { logEntity.F_IPAddress = WebHelper.Ip; if (GlobalContext.SystemConfig.LocalLAN != false) { logEntity.F_IPAddressName = "本地局域网"; } else { logEntity.F_IPAddressName = WebHelper.GetIpLocation(logEntity.F_IPAddress); } logEntity.F_CompanyId = GlobalContext.SystemConfig.SysemMasterProject; } else { logEntity.F_IPAddress = currentuser.LoginIPAddress; logEntity.F_IPAddressName = currentuser.LoginIPAddressName; logEntity.F_CompanyId = currentuser.CompanyId; } logEntity.Create(); if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { uniwork.Rollback(); await repository.Insert(logEntity); } else { await HandleLogHelper.HSetAsync(logEntity.F_CompanyId, logEntity.F_Id, logEntity); } } catch (Exception) { logEntity.F_IPAddress = WebHelper.Ip; if (GlobalContext.SystemConfig.LocalLAN != false) { logEntity.F_IPAddressName = "本地局域网"; } else { logEntity.F_IPAddressName = WebHelper.GetIpLocation(logEntity.F_IPAddress); } logEntity.F_CompanyId = GlobalContext.SystemConfig.SysemMasterProject; logEntity.Create(); if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { await repository.Insert(logEntity); } else { await HandleLogHelper.HSetAsync(logEntity.F_CompanyId, logEntity.F_Id, logEntity); } } }
// 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; }
public async Task <List <LogEntity> > GetList() { if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { return(repository.IQueryable().ToList()); } else { return(HandleLogHelper.HGetAll <LogEntity>(currentuser.CompanyId).Values.ToList());; } }
public async Task <List <LogEntity> > GetList(Pagination pagination, int timetype, string keyword = "") { //获取数据权限 var result = new List <LogEntity>(); DateTime startTime = DateTime.Now.ToString("yyyy-MM-dd").ToDate(); DateTime endTime = DateTime.Now.ToString("yyyy-MM-dd").ToDate().AddDays(1); switch (timetype) { case 1: break; case 2: startTime = startTime.AddDays(-7); break; case 3: startTime = startTime.AddMonths(-1); break; case 4: startTime = startTime.AddMonths(-3); break; default: break; } if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { var list = repository.IQueryable(); if (!string.IsNullOrEmpty(keyword)) { list = list.Where(u => u.F_Account.Contains(keyword) || u.F_Description.Contains(keyword) || u.F_ModuleName.Contains(keyword)); } list = list.Where(t => t.F_Date >= startTime && t.F_Date <= endTime); result = await repository.OrderList(list, pagination); } else { result = HandleLogHelper.HGetAll <LogEntity>(currentuser.CompanyId).Values.ToList(); if (!string.IsNullOrEmpty(keyword)) { result = result.Where(u => u.F_Account.Contains(keyword) || u.F_Description.Contains(keyword) || u.F_ModuleName.Contains(keyword)).Where(t => t.F_Date >= startTime && t.F_Date <= endTime).ToList(); } else { result = result.Where(t => t.F_Date >= startTime && t.F_Date <= endTime).ToList(); } pagination.records = result.Count(); result = result.OrderByDescending(a => a.F_CreatorTime).Skip((pagination.page - 1) * pagination.rows).Take(pagination.rows).ToList(); } return(GetFieldsFilterData(result)); }
public async Task <List <OpenJobLogEntity> > GetLogList(string keyValue) { if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { return(uniwork.IQueryable <OpenJobLogEntity>().Where(a => a.F_JobId == keyValue).OrderByDesc(a => a.F_CreatorTime).ToList()); } else { return(HandleLogHelper.HGetAll <OpenJobLogEntity>(keyValue).Values.OrderByDescending(a => a.F_CreatorTime).ToList());; } }
public async Task DeleteLogForm(string keyValue) { if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { await uniwork.Delete <OpenJobLogEntity>(a => a.F_JobId == keyValue); } else { string[] list = HandleLogHelper.HGetAll <OpenJobLogEntity>(keyValue).Keys.ToArray(); await HandleLogHelper.HDelAsync(keyValue, list); } }
public async Task WriteDbLog(bool result, string resultLog) { LogEntity logEntity = new LogEntity(); logEntity.F_Id = Utils.GuId(); logEntity.F_Date = DateTime.Now; logEntity.F_Account = currentuser.UserCode; logEntity.F_NickName = currentuser.UserName; logEntity.F_IPAddress = currentuser.LoginIPAddress; logEntity.F_IPAddressName = currentuser.LoginIPAddressName; logEntity.F_CompanyId = currentuser.CompanyId; logEntity.F_Result = result; logEntity.F_Description = resultLog; logEntity.Create(); if (HandleLogProvider != Define.CACHEPROVIDER_REDIS) { await repository.Insert(logEntity); } else { await HandleLogHelper.HSetAsync(currentuser.CompanyId, logEntity.F_Id, logEntity); } }
// 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); } })); }