/// <summary> /// 获取菜单模块树型列表 /// </summary> /// <param name="systemCode">子系统</param> /// <param name="isMenu">是否菜单(0/1)</param> public DataTable GetModuleTree(string systemCode, string isMenu = null) { if (string.IsNullOrEmpty(systemCode)) { systemCode = "Base"; } //读取选定子系统的菜单模块 var manager = new BaseModuleManager(UserInfo, systemCode + "Module"); // 获取所有数据 var parameters = new List <KeyValuePair <string, object> >(); if (ValidateUtil.IsInt(isMenu)) { parameters.Add(new KeyValuePair <string, object>(BaseModuleEntity.FieldIsMenu, isMenu)); } parameters.Add(new KeyValuePair <string, object>(BaseModuleEntity.FieldEnabled, 1)); parameters.Add(new KeyValuePair <string, object>(BaseModuleEntity.FieldDeleted, 0)); //2017.12.20增加默认的HttpRuntime.Cache缓存 var cacheKey = "DataTable." + systemCode + ".ModuleTree." + isMenu; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); return(CacheUtil.Cache <DataTable>(cacheKey, () => manager.GetModuleTree(manager.GetDataTable(parameters, BaseModuleEntity.FieldSortCode)), true, false, cacheTime)); //直接读取数据库 //return manager.GetModuleTree(manager.GetModuleTree(manager.GetDataTable(parameters, BaseModuleEntity.FieldSortCode))); }
/// <summary> /// 缓存预热,强制重新缓存 /// </summary> /// <returns>影响行数</returns> public static int CachePreheatingMacAddress() { var result = 0; var parameters = new List <KeyValuePair <string, object> >(); parameters.Add(new KeyValuePair <string, object>(BaseParameterEntity.FieldCategoryCode, "MacAddress")); parameters.Add(new KeyValuePair <string, object>(BaseParameterEntity.FieldEnabled, 1)); parameters.Add(new KeyValuePair <string, object>(BaseParameterEntity.FieldDeleted, 0)); // 把所有的数据都缓存起来的代码 var manager = new BaseParameterManager(); var dataReader = manager.ExecuteReader(parameters); if (dataReader != null && !dataReader.IsClosed) { while (dataReader.Read()) { var key = "MAC:" + dataReader[BaseParameterEntity.FieldParameterId]; var macAddress = dataReader[BaseParameterEntity.FieldParameterContent].ToString().ToLower(); CacheUtil.Set(key, macAddress); result++; if (result % 500 == 0) { Console.WriteLine(result + " : " + macAddress); } } dataReader.Close(); } return(result); }
public static int Delete(long id, IEntity obj, EntityInfo entityInfo) { List <IInterceptor> ilist = MappingClass.Instance.InterceptorList; for (int i = 0; i < ilist.Count; i++) { ilist[i].BeforDelete(obj); } int rowAffected = 0; rowAffected += deleteSingle(id, entityInfo); if (entityInfo.ChildEntityList.Count > 0) { foreach (EntityInfo info in entityInfo.ChildEntityList) { rowAffected += deleteSingle(id, Entity.GetInfo(info.Type.FullName)); } } if (entityInfo.Parent != null) { IEntity objP = Entity.New(entityInfo.Parent.Type.FullName); rowAffected += deleteSingle(id, Entity.GetInfo(objP)); } for (int i = 0; i < ilist.Count; i++) { ilist[i].AfterDelete(obj); } CacheUtil.CheckCountCache("delete", obj, entityInfo); return(rowAffected); }
/// <summary> /// 设置缓存 /// 20151007 吉日嘎拉,需要在一个连接上进行大量的操作 /// 20160128 吉日嘎拉,一些空调间的判断。 /// </summary> /// <param name="entity">用户实体</param> public static void SetCache(BaseUserEntity entity) { var key = string.Empty; if (entity != null && entity.Id > 0) { key = "User:"******"User:ByNickName:" + entity.NickName.ToLower(); CacheUtil.Set <string>(key, entity.Id.ToString()); } if (!string.IsNullOrEmpty(entity.Code)) { key = "User:ByCode:" + entity.Code; CacheUtil.Set <string>(key, entity.Id.ToString()); key = "User:ByCompanyId:ByCode" + entity.CompanyId + ":" + entity.Code; CacheUtil.Set <string>(key, entity.Id.ToString()); } var companyCode = BaseOrganizationManager.GetCodeByCache(entity.CompanyId.ToString()); if (!string.IsNullOrEmpty(companyCode)) { key = "User:ByCompanyCode:ByCode" + companyCode + ":" + entity.Code; CacheUtil.Set <string>(key, entity.Id.ToString()); } Console.WriteLine(entity.Id + " : " + entity.RealName); } }
/// <summary> /// 从缓存中获取角色编号 /// </summary> /// <param name="systemCode">系统编码</param> /// <param name="userId"></param> /// <param name="companyId"></param> /// <returns></returns> public static string[] GetRoleIdsByCache(string systemCode, string userId, string companyId = null) { // 返回值 string[] result = null; if (!string.IsNullOrEmpty(userId)) { //2017.12.20增加默认的HttpRuntime.Cache缓存 var cacheKey = "Array" + systemCode + userId + companyId + "RoleIds"; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); result = CacheUtil.Cache <string[]>(cacheKey, () => { //进行数据库查询 var userManager = new BaseUserManager(); return(userManager.GetRoleIds(systemCode, userId, companyId)); }, true, false, cacheTime); //// 进行数据库查询 //BaseUserManager userManager = new BaseUserManager(); //result = userManager.GetRoleIds(systemCode, userId, companyId); } return(result); }
/// <summary> /// 获取实体 /// </summary> /// <param name="name"></param> /// <param name="openId"></param> /// <param name="unionId"></param> /// <returns></returns> public BaseUserOAuthEntity GetEntity(string name, string openId, string unionId) { BaseUserOAuthEntity result = null; if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(openId)) { name = dbHelper.SqlSafe(name); //需要显示未被删除的记录 var sql = "SELECT TOP 1 * FROM " + CurrentTableName + " WHERE " + BaseUserOAuthEntity.FieldName + " = N'" + name + "'"; if (!string.IsNullOrEmpty(openId)) { sql += " AND " + BaseUserOAuthEntity.FieldOpenId + " = N'" + openId + "'"; } if (!string.IsNullOrEmpty(unionId)) { sql += " AND " + BaseUserOAuthEntity.FieldUnionId + " = N'" + unionId + "'"; } //未删除 sql += " AND " + BaseUserOAuthEntity.FieldDeleted + " = 0 AND " + BaseUserOAuthEntity.FieldEnabled + " = 1 "; //排序 sql += " ORDER BY " + BaseUserOAuthEntity.FieldId + " DESC"; var dt = DbHelper.Fill(sql); if (dt != null && dt.Rows.Count != 0) { //result = BaseEntity.Create<AppContentEntity>(dt); var cacheKey = CurrentTableName + ".Entity." + openId; var cacheTime = TimeSpan.FromMilliseconds(86400000); result = CacheUtil.Cache <BaseUserOAuthEntity>(cacheKey, () => BaseEntity.Create <BaseUserOAuthEntity>(dt), true, false, cacheTime); } } return(result); }
/// <summary> /// 设置List缓存 /// </summary> /// <param name="key"></param> /// <param name="list"></param> private static void SetListCache(string key, List <BaseModuleEntity> list) { if (!string.IsNullOrWhiteSpace(key) && list != null) { CacheUtil.Set <List <BaseModuleEntity> >(key, list); } }
/// <summary> /// 载入配置/或文件 /// </summary> public static void Load(this TextBox textBox, string path = null) { ConsoleUtil.Print("TextBox({0}).Load()", textBox.Name); string text; if (string.IsNullOrEmpty(path)) { text = CacheUtil.GetFromFile <string>(textBox.Name); } else { text = FileUtil.GetText(path); } if (!string.IsNullOrEmpty(text)) { /* * 此处赋值textBox.Text = text * 如果textBox.Text == text 不会触发TextChanged * 如果textBox.Text != text 会触发TextChanged * 但是textBox进行前端输入(包括粘贴,输入相同字符) 无论==、!=都会触发TextChanged */ textBox.Text = text; } }
public Dictionary <string, CustomerExtAttributesModel> GetCustomerAttributeList(string extattributeid, bool clear) { if (string.IsNullOrEmpty(extattributeid)) { return(null); } Dictionary <string, CustomerExtAttributesModel> dict = null; string cacheKey = CacheKey.CUSTOMER_ATTRIBUTE_DICT.GetKeyDefine(extattributeid); dict = CacheUtil.Get <Dictionary <string, CustomerExtAttributesModel> >(cacheKey); if (dict == null || clear) { dict = GetProductCustomerAttributeListFromDatabase(extattributeid); if (dict != null) { CacheUtil.Set(cacheKey, dict); } else { CacheUtil.Remove(cacheKey); } } return(dict); }
/// <summary> /// 从缓存获取获取实体 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="name">名称</param> /// <returns>权限实体</returns> public static BaseRoleEntity GetEntityByCacheByName(string systemCode, string name) { BaseRoleEntity result = null; if (string.IsNullOrWhiteSpace(systemCode)) { systemCode = "Base"; } // 动态读取表中的数据 var tableName = systemCode + "Role"; //2017.12.20增加默认的HttpRuntime.Cache缓存 var cacheKey = "List." + systemCode + ".Role"; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); var listRole = CacheUtil.Cache <List <BaseRoleEntity> >(cacheKey, () => { var parametersWhere = new List <KeyValuePair <string, object> > { new KeyValuePair <string, object>(BaseRoleEntity.FieldDeleted, 0), new KeyValuePair <string, object>(BaseRoleEntity.FieldEnabled, 1) }; return(new BaseRoleManager(tableName).GetList <BaseRoleEntity>(parametersWhere, BaseRoleEntity.FieldId)); }, true, false, cacheTime); result = listRole.Find(t => t.Name == name); //直接读取数据库 //BaseRoleManager manager = new BaseRoleManager(tableName); //result = manager.GetEntityByName(name); return(result); }
/// <summary> /// 获取模块菜单表,从缓存读取 /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="refreshCache">是否刷新缓存</param> /// <returns>角色列表</returns> public static List <BaseRoleEntity> GetEntitiesByCache(string systemCode = "Base", bool refreshCache = false) { var result = new List <BaseRoleEntity>(); var tableName = systemCode + "Role"; //2017.12.20增加默认的HttpRuntime.Cache缓存 var cacheKey = "List." + systemCode + ".Role"; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); result = CacheUtil.Cache <List <BaseRoleEntity> >(cacheKey, () => { var roleManager = new BaseRoleManager(tableName); // 读取目标表中的数据 var parametersWhere = new List <KeyValuePair <string, object> > { // 有效的菜单 new KeyValuePair <string, object>(BaseRoleEntity.FieldEnabled, 1), // 没被删除的菜单 new KeyValuePair <string, object>(BaseRoleEntity.FieldDeleted, 0) }; // parameters.Add(new KeyValuePair<string, object>(BaseRoleEntity.FieldIsVisible, 1)); return(roleManager.GetList <BaseRoleEntity>(parametersWhere, BaseRoleEntity.FieldSortCode)); }, true, refreshCache, cacheTime); return(result); }
public async Task <ActionResult> Register(SummonerModel model) { ViewModel = await CreateViewModelAsync(); if (!ModelState.IsValid) { return(Error(ModelState)); } // Rule: Summoner must not be registered to a User. if (await Summoners.IsSummonerRegistered(model.Region, model.SummonerName)) { return(Error("Summoner is already registered.")); } // Rule: Summoner must exist. var cacheKey = string.Concat(model.Region, ":", model.SummonerName).ToLowerInvariant(); var summoner = await CacheUtil.GetItemAsync(cacheKey, () => Riot.FindSummonerAsync(model.Region, model.SummonerName)); if (summoner == null) { return(Error("Summoner not found.")); } return(Success()); }
public Dictionary <string, ProductCategorySalesStatusModel> GetProductCategorySalesStatusList(string productCategoryId, bool clear) { if (string.IsNullOrEmpty(productCategoryId)) { return(null); } Dictionary <string, ProductCategorySalesStatusModel> dict = null; string cacheKey = CacheKey.PRODUCT_CATEGORY_SALESTATUS_DICT.GetKeyDefine(productCategoryId); dict = CacheUtil.Get <Dictionary <string, ProductCategorySalesStatusModel> >(cacheKey); if (dict == null || clear) { dict = GetProductCategorySalesStatusListFromDatabase(productCategoryId); if (dict != null) { CacheUtil.Set(cacheKey, dict); } else { CacheUtil.Remove(cacheKey); } } return(dict); }
/// <summary> /// 清除缓存 /// </summary> public static void ClearCache() { lock (BaseSystemInfo.UserLock) { CacheUtil.Remove(BaseStaffEntity.CurrentTableName); } }
public void ProcessRequest(HttpContext context) { string url = context.Request.Path; context.Response.ContentType = "text/javascript"; StringBuilder content = new StringBuilder(5000); string filepath = context.Server.MapPath(url); object filecontent = CacheUtil.GetCache(url); if (filecontent == null || context.Request.Params["rc"] == "1" || Global.isCache == false) { filecontent = FileUtil.readFile(filepath); if (filecontent != null) { CacheUtil.SetCache(url, filecontent); } else { filecontent = $"console.log('{url} load error')"; } } filecontent = filecontent.ToString().Replace("[localhostIp]", ip); context.Response.Write(filecontent.ToString()); context.Response.Flush(); }
/// <summary> /// 多个角色,都有啥权限?单个角色都有啥权限的循环获取? /// </summary> /// <param name="systemCode">系统编号</param> /// <param name="roleIds">角色主键数组</param> /// <returns>权限数组</returns> public static string[] GetPermissionIdsByCache(string systemCode, string[] roleIds) { string[] result = null; var key = string.Empty; var roleId = string.Empty; string[] permissionIds = null; key = "Permission:" + systemCode + ":Role:" + roleId; var hs = new HashSet <string>(); result = CacheUtil.Cache(key, () => { for (var i = 0; i < roleIds.Length; i++) { permissionIds = new BasePermissionManager().GetPermissionIds(systemCode, roleIds[i], "Role"); foreach (var permissionId in permissionIds) { hs.Add(permissionId); } } return(hs.ToArray()); }, true); return(result); }
/// <summary> /// 根据字典编码、主键获取实体 /// </summary> /// <param name="dictionaryCode">字典编码</param> /// <param name="itemKey">字典项主键</param> /// <param name="itemValue">字典项值</param> /// <returns></returns> public BaseDictionaryItemEntity GetEntity(string dictionaryCode, string itemKey, string itemValue = null) { BaseDictionaryItemEntity entity = null; if (!string.IsNullOrEmpty(dictionaryCode) && !string.IsNullOrEmpty(itemKey)) { var entityBaseDictionary = new BaseDictionaryManager(UserInfo).GetEntityByCode(dictionaryCode); if (entityBaseDictionary != null) { var parameters = new List <KeyValuePair <string, object> > { new KeyValuePair <string, object>(BaseDictionaryItemEntity.FieldDictionaryId, entityBaseDictionary.Id), new KeyValuePair <string, object>(BaseDictionaryItemEntity.FieldItemKey, itemKey), new KeyValuePair <string, object>(BaseDictionaryItemEntity.FieldDeleted, 0), new KeyValuePair <string, object>(BaseDictionaryItemEntity.FieldEnabled, 1) }; if (!string.IsNullOrEmpty(itemValue)) { parameters.Add(new KeyValuePair <string, object>(BaseDictionaryItemEntity.FieldItemValue, itemValue)); } var cacheKey = CurrentTableName + ".Entity." + dictionaryCode + "." + itemKey; var cacheTime = TimeSpan.FromMilliseconds(86400000); entity = CacheUtil.Cache <BaseDictionaryItemEntity>(cacheKey, () => BaseEntity.Create <BaseDictionaryItemEntity>(GetDataTable(parameters)), true, false, cacheTime); } } return(entity); }
public static TTarget Map <TSource, TTarget>(TSource source) where TTarget : new() { if (source is null) { throw new ArgumentNullException(nameof(source)); } var sourceType = typeof(TSource); var destinationType = typeof(TTarget); var properties = CacheUtil.GetTypeProperties(destinationType); var sourceProps = CacheUtil.GetTypeProperties(sourceType) .Where(x => properties.Any(_ => _.Name.EqualsIgnoreCase(x.Name))) .ToArray(); var result = new TTarget(); if (properties.Length > 0) { foreach (var property in properties) { var sourceProperty = sourceProps.FirstOrDefault(p => p.Name.EqualsIgnoreCase(property.Name)); if (sourceProperty == null) { continue; } var propGetter = sourceProperty.GetValueGetter(); if (propGetter != null) { property.GetValueSetter()?.Invoke(result, propGetter.Invoke(source)); } } } return(result); }
/// <summary> /// 获取产品信息领域模型。 /// </summary> /// <param name="productId"></param> /// <param name="clear"></param> /// <returns></returns> public ProductInfoDomainModel GetProductDomainInfoByProductId(string productId, bool clear) { if (string.IsNullOrEmpty(productId)) { return(null); } string cacheKey = CacheKey.PRODUCT_DOMAIN_MODEL.GetKeyDefine(productId); ProductInfoDomainModel info = CacheUtil.Get <ProductInfoDomainModel>(cacheKey); if (info == null || clear) { info = GetProductDomainInfoByProductIdFromDatabase(productId); if (info != null) { CacheUtil.Set(cacheKey, info); } else { CacheUtil.Remove(cacheKey); } } return(info); }
/// <summary> /// A DataRow extension method that converts the @this to the entities. /// </summary> /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="dr">The @this to act on.</param> /// <returns>@this as a T.</returns> public static T ToEntity <T>([NotNull] this DataRow dr) { var type = typeof(T); var properties = CacheUtil.GetTypeProperties(type).Where(p => p.CanWrite).ToArray(); var entity = NewFuncHelper <T> .Instance(); if (type.IsValueType) { var obj = (object)entity; foreach (var property in properties) { if (dr.Table.Columns.Contains(property.Name)) { property.GetValueSetter()?.Invoke(obj, dr[property.Name].GetValueFromDbValue()); } } entity = (T)obj; } else { foreach (var property in properties) { if (dr.Table.Columns.Contains(property.Name)) { property.GetValueSetter()?.Invoke(entity, dr[property.Name].GetValueFromDbValue()); } } } return(entity); }
/// <summary> /// 通过 openId 获取用户信息 /// </summary> /// <param name="openId">唯一键</param> /// <returns>用户实体</returns> public static BaseUserEntity GetEntityByOpenIdByCache(string openId) { BaseUserEntity result = null; var userId = string.Empty; var key = "OpenId"; if (!string.IsNullOrWhiteSpace(openId)) { key += openId; result = CacheUtil.Cache(key, () => { // 到数据库里查一次 userId = new BaseUserLogonManager().GetIdByOpenId(openId); if (!string.IsNullOrWhiteSpace(userId)) { return(new BaseUserManager().GetEntity(userId)); } else { return(null); } }, true); } return(result); }
internal Dictionary <string, string> GetCredentials(string environmentId, string itemName) { Dictionary <string, string> credentialsDic; if (CacheUtil.IsCachingEnabled()) { credentialsDic = CredentialsCacheHelper.GetCredentialsCache(environmentId); if (credentialsDic != null) { return(credentialsDic); } } var result = _httpClient.GetAsync($"{LcsUrl}/DeploymentPortal/GetCredentials/{LcsProjectId}?environmentId={environmentId}&deploymentItemName={itemName}&_={DateTimeOffset.Now.ToUnixTimeSeconds()}").Result; result.EnsureSuccessStatusCode(); var responseBody = result.Content.ReadAsStringAsync().Result; var response = JsonConvert.DeserializeObject <Response>(responseBody); if (response.Success && response.Data != null) { credentialsDic = JsonConvert.DeserializeObject <Dictionary <string, string> >(response.Data.ToString()); if (CacheUtil.IsCachingEnabled()) { CredentialsCacheHelper.AddCredentialsCache(environmentId, credentialsDic); } return(credentialsDic); } return(null); }
/// <summary> /// 获取公众号的AccessToken /// </summary> /// <returns></returns> public WxOffAccessTokenResp GetOffcialAccessToken() { var tokenResp = CacheUtil.Get <WxOffAccessTokenResp>(m_OffcialAccessTokenKey, ModuleNames.SnsCenter); if (tokenResp == null || tokenResp.expires_date < DateTime.Now) { OsHttpRequest req = new OsHttpRequest(); req.AddressUrl = $"{m_ApiUrl}/cgi-bin/token?grant_type=client_credential&appid={ApiConfig.AppId}&secret={ApiConfig.AppSecret}"; req.HttpMothed = HttpMothed.GET; tokenResp = RestCommon <WxOffAccessTokenResp>(req); if (!tokenResp.IsSuccess) { return(tokenResp); } tokenResp.expires_date = DateTime.Now.AddSeconds(tokenResp.expires_in - 600); CacheUtil.AddOrUpdate(m_OffcialAccessTokenKey, tokenResp, TimeSpan.FromSeconds(tokenResp.expires_in), null, ModuleNames.SnsCenter); } return(tokenResp); }
/// <summary> /// 验证OpenId /// </summary> /// <param name="openId"></param> /// <returns></returns> public static bool ValidateOpenId(string openId) { var result = false; if (!string.IsNullOrWhiteSpace(openId)) { var userId = CacheUtil.Get <string>("openId" + openId); if (!string.IsNullOrWhiteSpace(userId)) { result = true; } } if (!result) { var url = BaseSystemInfo.UserCenterHost + "UserCenterV42/LogonService.ashx"; var webClient = new WebClient(); var postValues = new NameValueCollection(); postValues.Add("function", "ValidateOpenId"); postValues.Add("systemCode", BaseSystemInfo.SystemCode); postValues.Add("ipAddress", Utils.GetIp()); postValues.Add("securityKey", BaseSystemInfo.SecurityKey); postValues.Add("openId", openId); // 向服务器发送POST数据 var responseArray = webClient.UploadValues(url, postValues); var response = Encoding.UTF8.GetString(responseArray); if (!string.IsNullOrEmpty(response)) { result = response.Equals(true.ToString(), StringComparison.InvariantCultureIgnoreCase); } } return(result); }
/// <summary> /// 获取所有用户的角色列表 /// </summary> /// <param name="systemCode">系统编号</param> /// <returns>角色数据表</returns> public DataTable GetUserRole(string systemCode) { var result = new DataTable(BaseRoleEntity.CurrentTableName); var userRoleTableName = BaseUserRoleEntity.CurrentTableName; if (!string.IsNullOrWhiteSpace(systemCode)) { userRoleTableName = systemCode + "UserRole"; } var roleTableName = BaseRoleEntity.CurrentTableName; if (!string.IsNullOrWhiteSpace(systemCode)) { roleTableName = systemCode + "Role"; } var sb = Pool.StringBuilder.Get(); sb.AppendLine("SELECT BaseRole.Code, BaseRole.Name, BaseRole.Description, UserRole.Id, UserRole.UserId, UserRole.RoleId, UserRole.Enabled, UserRole.Deleted, UserRole.CreateTime, UserRole.CreateBy, UserRole.UpdateTime, UserRole.UpdateBy"); sb.AppendLine(" FROM BaseRole INNER JOIN (SELECT Id, UserId, RoleId, Enabled, Deleted, CreateTime, CreateBy, UpdateTime, UpdateBy FROM BaseUserRole WHERE Enabled = 1 AND " + BaseUserRoleEntity.FieldDeleted + " = 0) UserRole ON BaseRole.Id = UserRole.RoleId"); sb.AppendLine(" WHERE BaseRole.Enabled = 1 AND BaseRole." + BaseRoleEntity.FieldDeleted + " = 0 ORDER BY UserRole.CreateTime DESC"); //替换表名 sb = sb.Replace("BaseUserRole", userRoleTableName); sb = sb.Replace("BaseRole", roleTableName); var cacheKey = "DataTable." + systemCode + ".UserRole"; //var cacheTime = default(TimeSpan); var cacheTime = TimeSpan.FromMilliseconds(86400000); result = CacheUtil.Cache <DataTable>(cacheKey, () => Fill(sb.Put()), true, false, cacheTime); return(result); }
/// <summary> /// 获取公众号的AccessToken /// </summary> /// <returns></returns> public async Task <WxOffAccessTokenResp> GetAccessTokenAsync() { var tokenResp = CacheUtil.Get <WxOffAccessTokenResp>(m_OffcialAccessTokenKey, ModuleNames.SocialCenter); if (tokenResp != null && tokenResp.expires_date >= DateTime.Now) { return(tokenResp); } var req = new OsHttpRequest { AddressUrl = $"{m_ApiUrl}/cgi-bin/token?grant_type=client_credential&appid={ApiConfig.AppId}&secret={ApiConfig.AppSecret}", HttpMothed = HttpMothed.GET }; tokenResp = await RestCommonJson <WxOffAccessTokenResp>(req); if (!tokenResp.IsSuccess()) { return(tokenResp); } tokenResp.expires_date = DateTime.Now.AddSeconds(tokenResp.expires_in - 600); CacheUtil.AddOrUpdate(m_OffcialAccessTokenKey, tokenResp, TimeSpan.FromSeconds(tokenResp.expires_in), null, ModuleNames.SocialCenter); return(tokenResp); }
public CPUInfo GetCPUInfo() { CPUInfo CpuInfo; if (!CacheUtil.TryGetValue <CPUInfo>(cacheKey, out CpuInfo)) { CpuInfo = new CPUInfo(); GetSystemInfo(ref CpuInfo); ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"); foreach (ManagementObject mo in mos.Get()) { CpuInfo.cpuType = mo["name"].ToString(); break; } CacheUtil.Set <CPUInfo>(cacheKey, CpuInfo, CacheTime.NotRemovable); } PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName); CpuInfo.cpuLoad = pc.NextValue(); return(CpuInfo); }
private void PatchForm_Load(object sender, EventArgs e) { if (!File.Exists(Cache)) { this.Text += " (无缓存)"; return; } string[] lines = CacheUtil.GetAllLines(Cache); if (lines.Length == 0) { this.Text += " (空缓存)"; return; } string lastLine = lines[lines.Length - 1]; if (lastLine.StartsWith("INSERT", true, System.Globalization.CultureInfo.CurrentCulture)) { this.Text += " (需关机)"; } else if (lastLine.StartsWith("UPDATE", true, System.Globalization.CultureInfo.CurrentCulture)) { this.Text += " (需开机)"; } else { MessageBox.Show("请手动检查缓存文件格式", "读取格式异常!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public ActionResult ImagePreview() { RequestUtil req = new RequestUtil(); string callback = req.String("callback"); int width = req.Int("width", defaultValue: 640); int height = req.Int("height", defaultValue: 1024); HttpPostedFileBase pic = Request.Files.Count == 0 ? null : Request.Files[0]; if (pic != null && pic.ContentLength != 0) { byte[] imageBuffer = ImageUtil.Compress(pic.InputStream, 40, width, height); string guid = System.Guid.NewGuid().ToString("N"); CacheUtil.CreateCache("preview-" + guid, 0.1, imageBuffer); return(Content(HtmlUtil.Result(callback, new { success = true, guid = guid, name = Request.Files.Keys[0] }))); } else { return(Content(HtmlUtil.Result(callback, new { success = false, msg = "您还未选择图片" }))); } }
public ResponseDataEntity Set() { //日志等级由系统维护,通过配置参数获取 //系统临时设置日志级别,log4可直接设置为ALL级别,如果需要测试接口等其他级别可通过这个配置调整 CacheUtil.Add("LogLevel", "ERROR", new TimeSpan(0, 5, 0)); return(ResponseUtil.Success()); }