public static List <string> GetMoguProxyListFromCache() { var fullName = MemoryCacheHelper.GetCacheItem <List <string> >("moguproxyList", delegate() { var res = HttpClientHolder.GetRequest("http://piping.mogumiao.com/proxy/api/get_ip_bs?appKey=e7178154a26948f38f155af1e4f7a440&count=5&expiryDate=0&format=1&newLine=2"); while (res.IndexOf("提取频繁请按照规定频率提取") >= 0) { System.Threading.Thread.Sleep(10000); res = HttpClientHolder.GetRequest("http://piping.mogumiao.com/proxy/api/get_ip_bs?appKey=e7178154a26948f38f155af1e4f7a440&count=5&expiryDate=0&format=1&newLine=2"); } List <string> listProxy = new List <string>(); var jarray = JObject.Parse(res)["msg"] as JArray; foreach (var jitem in jarray) { listProxy.Add($"{jitem["ip"].NullToString()}:{jitem["port"].NullToString()}"); } return(listProxy); }, new TimeSpan(0, 0, 30));//30分钟过期 return(fullName); }
public T Get <T>(string key) { switch (_CacheOptions.CacheMediaType) { case CacheMediaType.Local: return(MemoryCacheHelper.Get <string, T>(key)); case CacheMediaType.Redis: try { var redisResult = GetRedisCacheProvider().Get(key); if (!string.IsNullOrEmpty(redisResult)) { return(JsonConvert.DeserializeObject <T>(redisResult)); } } catch (ArgumentException argEx) { throw argEx; } return(default(T)); default: return(default(T)); } }
public void AddEmployeeActivityTest() { //arrange DBSettings dBSettings = new DBSettings(); IMemoryCache memoryCache = MemoryCacheHelper.GetMemoryCache(); CacheSettings cacheSettings = new CacheSettings(); EmployeeActivityDBContext employeeActivityDBContext = new EmployeeActivityDBContext(dBSettings); EmployeeActivityRepository employeeActivityRepository = new EmployeeActivityRepository(employeeActivityDBContext, memoryCache, cacheSettings); EmployeeActivityController employeeActivityController = new EmployeeActivityController(employeeActivityRepository); var tics = DateTime.Now.Ticks; EmployeeActivityViewModel employeeActivity = new EmployeeActivityViewModel() { FirstName = string.Concat("FName_", tics), LastName = string.Concat("LName_", tics), EmailAddress = string.Concat(tics, "@email.com"), ActivityName = string.Concat("Activity_Name_", tics), Comments = string.Concat("Comments_", tics) }; //act var result = employeeActivityController.AddEmployeeActivity(employeeActivity); //assert var viewResult = Assert.IsType <RedirectToActionResult>(result); }
public ActionResult Products() { var sitemapItems = new List <SitemapItem>(); String key = String.Format("ProductSitemapItemCache-{0}", StoreId); ProductSitemapItemCache.TryGet(key, out sitemapItems); if (sitemapItems == null) { sitemapItems = new List <SitemapItem>(); var products = ProductRepository.GetProductByTypeAndCategoryIdFromCache(StoreId, StoreConstants.ProductType, -1); var categories = ProductCategoryService.GetProductCategoriesByStoreIdFromCache(StoreId, StoreConstants.ProductType); foreach (var product in products) { var cat = categories.FirstOrDefault(r => r.Id == product.ProductCategoryId); if (cat != null) { var productDetailLink = LinkHelper.GetProductIdRouteValue(product, cat.Name); var siteMap = new SitemapItem(Url.AbsoluteAction("Product", "Products", new { id = productDetailLink }), changeFrequency: SitemapChangeFrequency.Monthly, priority: 1.0); sitemapItems.Add(siteMap); } } ProductSitemapItemCache.Set(key, sitemapItems, MemoryCacheHelper.CacheAbsoluteExpirationPolicy(ProjectAppSettings.CacheLongSeconds)); } return(new SitemapResult(sitemapItems)); }
/// <summary> /// 获取每次操作微信API的Token访问令牌 /// </summary> /// <returns></returns> public static MD_AccessTokenResult GetAccessToken() { string url = ConfigurationManager.AppSettings["hxurl"] + "/token"; //正常情况下access_token有效期为7200秒,这里使用缓存设置短于这个时间即可 MD_AccessTokenResult access_token = MemoryCacheHelper.GetCacheItem <MD_AccessTokenResult>("hxaccess_token", delegate() { MD_AccessTokenResult result = new MD_AccessTokenResult(); string data = "{\"grant_type\": \"client_credentials\",\"client_id\":\"YXA6TSjk4EBLEeekxD1y9NWlTg\",\"client_secret\":\"YXA6RPwUCNQ97-WoQG1-8_ChwTQ1bhs\"}"; string jsonStr = WebHelper.GetHXRequestData(url, "post", "", false, data); if (jsonStr.Contains("error")) { ErrorMsg errorResult = new ErrorMsg(); errorResult = JsonConvert.DeserializeObject <ErrorMsg>(jsonStr); result.ErrorResult = errorResult; result.Result = false; } else { AccessTokenModel model = new AccessTokenModel(); model = JsonConvert.DeserializeObject <AccessTokenModel>(jsonStr); result.SuccessResult = model; result.Result = true; } return(result); }, new TimeSpan(0, 0, 5100000)//过期 ); return(access_token); }
/// <summary> /// 获取实体信息 /// </summary> /// <returns></returns> public static EntityInfo GetEntityInfo <T>() where T : BaseEntity { var t = typeof(T); if (!MemoryCacheHelper.Exists(t.FullName)) { var entityInfo = new EntityInfo(); var tableName = t.Name; var obs = t.GetTypeInfo().GetCustomAttribute <TableAttribute>(); if (obs != null) { tableName = obs.Name; } var fields = new List <string>(); var properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); var dbProps = new List <PropertyInfo>(); foreach (var p in properties) { if (p.CanWrite && p.CanRead && p.GetCustomAttribute <NotMappedAttribute>() == null) { fields.Add(p.Name); dbProps.Add(p); } } entityInfo.TableName = tableName; entityInfo.Properties = dbProps.ToArray(); entityInfo.Columns = fields; MemoryCacheHelper.SetCache(t.FullName, entityInfo, TimeSpan.FromDays(1)); } return(MemoryCacheHelper.GetCache <EntityInfo>(t.FullName)); }
public PetsRepository(MemoryCacheHelper memoryCache) { _cache = memoryCache; if (_cache.CacheTryGetValue(PetMemoryKey) == null) { var items = new List <Pet>() { new Pet { Id = 1, Name = "Tom", Dob = new DateTime(2015, 1, 1), Sex = "Male", Breed = "German Shepard" }, new Pet { Id = 2, Name = "Jerry", Dob = new DateTime(2015, 1, 1), Sex = "Male", Breed = "Bulldog" }, new Pet { Id = 3, Name = "Max", Dob = new DateTime(2015, 1, 1), Sex = "Male", Breed = "Labrador Etriever" }, new Pet { Id = 4, Name = "Amber", Dob = new DateTime(2015, 1, 1), Sex = "Female", Breed = "Poodle" }, new Pet { Id = 5, Name = "Abbey", Dob = new DateTime(2015, 1, 1), Sex = "Female", Breed = "Boxer" }, }; _cache.CacheTrySetValue(PetMemoryKey, items); } }
public Store GetStore(String domainName) { String key = String.Format("GetStoreDomain-{0}", domainName); Store site = null; StoreCache.TryGet(key, out site); if (site == null) { site = this.GetStoreByDomain(domainName); if (site != null) { string layout = String.Format("~/Views/Shared/Layouts/{0}.cshtml", !String.IsNullOrEmpty((String)site.Layout) ? (String)site.Layout : "_Layout1"); var isFileExist = File.Exists(System.Web.HttpContext.Current.Server.MapPath(layout)); _defaultlayout = String.Format(_defaultlayout, ProjectAppSettings.GetWebConfigString("DefaultLayout", "_Layout1")); if (!isFileExist) { Logger.Info(String.Format("Layout is not found.Default Layout {0} is used.Site Domain is {1} ", _defaultlayout, site.Domain)); } String selectedLayout = isFileExist ? layout : _defaultlayout; site.Layout = selectedLayout; StoreCache.Set(key, site, MemoryCacheHelper.CacheAbsoluteExpirationPolicy(ProjectAppSettings.GetWebConfigInt("TooMuchTime_CacheAbsoluteExpiration_Minute", 100000))); } } return(site); }
public ActionResult GetSubnetDeviceStatus(int sId) { var result = new JsonResult(); try { string key = string.Format("subnet_device_status_{0}", sId); var nodeStatus = MemoryCacheHelper.GetCacheItem<List<TopoNodeStatus>>(key, () => { IEnumerable<Device> devices = null; using (var ctx = new GlsunViewEntities()) { devices = ctx.Device.Where(d => d.SID == sId).ToList(); } List<TopoNodeStatus> status = new List<TopoNodeStatus>(); foreach (var d in devices) { status.Add(DeviceStatusGetter.GetDeviceStatus(d)); } return status; }, null, DateTime.Now.AddSeconds(5)); result.Data = new { Code = "", Data = nodeStatus }; } catch (Exception ex) { result.Data = new { Code = "Exception", Data = ex.Message }; } return result; }
public async Task <ResultData> CheckToken([FromUri] string token) { ResultData oResultData = new ResultData(); try { //Kiểm tra key có tồn tại và đã hết thời gian kích hoạt chưa if (!string.IsNullOrWhiteSpace(token) && MemoryCacheHelper.HasExitsKey(token)) { string userName = Convert.ToString(MemoryCacheHelper.GetValue(token)); ApplicationUser user = UserManager.FindByName <ApplicationUser, string>(userName); if (user != null) { oResultData.Success = true; } else { oResultData.Success = false; } } else { oResultData.Success = false; oResultData.ErrorMessage = MT.Resources.GlobalResource.ErrorExpriedActiveLink; } } catch (Exception ex) { oResultData.SetError(ex); } return(oResultData); }
public CarsRepository(MemoryCacheHelper memoryCache) { _cache = memoryCache; if (_cache.CacheTryGetValue(CarMemoryKey) == null) { var items = new List <Car>() { new Car { Id = 1, Make = "Audi", Model = "Q3", Year = "2018", CurrentMileage = 8522 }, new Car { Id = 2, Make = "Mercedes", Model = "C500", Year = "2018", CurrentMileage = 8324 }, new Car { Id = 3, Make = "Honda", Model = "CRV", Year = "2018", CurrentMileage = 9000 }, new Car { Id = 4, Make = "Honda", Model = "Accord", Year = "2018", CurrentMileage = 20000 }, new Car { Id = 5, Make = "Audi", Model = "Q3", Year = "2018", CurrentMileage = 5000 } }; _cache.CacheTrySetValue(CarMemoryKey, items); } }
public JsonResult AjaxLogin(string name, string password) { var result = new Result(false); if (string.IsNullOrWhiteSpace(name)) { result.Message = "消息:用户名不能为空!"; } if (string.IsNullOrWhiteSpace(password)) { result.Message = "消息:密码不能为空!"; } MemoryCacheHelper.RemoveCacheAll(); if (!RbacPrincipal.Login(name, password)) { result.Message = "消息:用户或密码错误,请重新输入!!"; } else { result = new Result(true); var identity = LEnvironment.Principal as MyFormsPrincipal <MyUserDataPrincipal>; if (identity != null) { //if (identity.DepUserType == 2) //{ // result.Message = "../../" + LCL.MvcExtensions.PageFlowService.PageNodes.FindPageNode("LayoutHome1").Value; //} //else //{ result.Message = "../../" + LCL.MvcExtensions.PageFlowService.PageNodes.FindPageNode("LayoutHome").Value; // } } } return(Json(result, JsonRequestBehavior.AllowGet)); }
public ActionResult RefreshCache() { var result = DC.Set <VOS_Rule>().ToList(); MemoryCacheHelper.Set(MemoryCacheHelper.GetRuleCaches, result, new TimeSpan(7, 0, 0, 0)); return(Json(true)); }
public void AddEmployeeTest() { //arrange IDBSettings dBSettings = new DBSettings(); IMemoryCache memoryCache = MemoryCacheHelper.GetMemoryCache(); CacheSettings cacheSettings = new CacheSettings(); EmployeeActivityByDapperRepository employeeActivityProvider = new EmployeeActivityByDapperRepository(dBSettings, memoryCache, cacheSettings); var tics = DateTime.Now.Ticks; EmployeeActivity employeeActivity = new EmployeeActivity() { FirstName = string.Concat("dapper_", tics), LastName = string.Concat("LName_", tics), EmailAddress = string.Concat(tics, "@email.com"), ActivityName = string.Concat("Activity_Name_", tics), Comments = string.Concat("Comments_", tics) }; //act var result = employeeActivityProvider.AddEmployee(employeeActivity); //assert Assert.NotEmpty(dBSettings.ConnectionString); Assert.NotNull(employeeActivity); Assert.NotEqual <int>(0, result); }
public void Wipe() { string testFolder = Path.Join(AppDomain.CurrentDomain.BaseDirectory, this.GetType().Name); if (Directory.Exists(testFolder)) { Directory.Delete(testFolder, true); } Directory.CreateDirectory(testFolder); Core.ITetriSettings settings = new Core.TetriSettings(new TestLogger <Core.TetriSettings>()) { TempPath = Path.Join(testFolder, "Temp") }; Directory.CreateDirectory(settings.TempPath); string testFilePath = Path.Join(settings.TempPath, "test"); File.WriteAllText(testFilePath, string.Empty); Core.ITagsService tagService = new Core.TagsService( settings, new TestLogger <Core.ITagsService>(), new Core.PackageListCache(MemoryCacheHelper.GetInstance())); Core.IIndexReader reader = new Core.IndexReader(settings, new Core.ThreadDefault(), tagService, new TestLogger <Core.IIndexReader>(), new FileSystem(), HashServiceHelper.Instance()); reader.Initialize(); Assert.False(File.Exists(testFilePath)); }
/// <summary> /// 获取子网状态 /// </summary> /// <returns></returns> public ActionResult GetSubnetStatus() { var result = new JsonResult(); try { var nodeStatus = MemoryCacheHelper.GetCacheItem<List<TopoNodeStatus>>("subnet_status", () => { IEnumerable<Subnet> nets = null; using (var ctx = new GlsunViewEntities()) { nets = ctx.Subnet.ToList(); } List<TopoNodeStatus> status = new List<TopoNodeStatus>(); foreach (var n in nets) { status.Add(DeviceStatusGetter.GetSubnetStatus(n)); } return status; }, null, DateTime.Now.AddSeconds(10)); result.Data = new { Code = "", Data = nodeStatus }; } catch (Exception ex) { result.Data = new { Code = "Exception", Data = ex.Message }; } return result; }
public string AddUser(UserInputDto userInputDto) { userInputDto.RegDate = DateTime.Now; userInputDto.CreateTime = DateTime.Now; userInputDto.LoginNum = 0; string ip = HttpContext.Connection.RemoteIpAddress.ToString(); string validateCode = MemoryCacheHelper.GetCache(ip).ToString(); //if (!string.IsNullOrEmpty(validateCode) && validateCode.ToLower() == userInputDto.validateCode) //{ Users user; user = _accountService.GetUserByQQ(userInputDto.QQ); if (user != null) { HttpContext.Response.StatusCode = 214; return("hasQQ"); } int row = _accountService.CreateAndUpdateUsers(userInputDto); if (row >= 1) { return("success"); } else { HttpContext.Response.StatusCode = 214; return("UnknowErr"); } //} //else //{ // HttpContext.Response.StatusCode = 214; // return "ValidateErr"; //} }
public ActionResult Login(Account account) { //if (Session["ValidateCode"].ToString() != account.VerifyCode) //{ // ModelState.AddModelError("VerifyCode", "validate code is error"); // return View(); //} if (!ModelState.IsValid) { return(View()); } if (string.IsNullOrWhiteSpace(account.Name)) { ModelState.AddModelError("Name", "消息:用户名不能为空!"); return(View()); } if (string.IsNullOrWhiteSpace(account.Password)) { ModelState.AddModelError("Name", "消息:密码不能为空!"); return(View()); } MemoryCacheHelper.RemoveCacheAll(); if (!LCLPrincipal.Login(account.Name, account.Password)) { ModelState.AddModelError("Name", "消息:用户或密码错误,请重新输入!"); return(View()); } else { return(RedirectIndex()); } }
public ResultData GetCaptcha() { ResultData oResultData = new ResultData(); try { string capcha = ""; Bitmap bm = MT.Library.CommonFunction.CreateCapcha(ref capcha); MemoryCacheHelper.Add(Commonkey.Capcha, capcha, DateTimeOffset.Now.AddMinutes(5)); using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { bm.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); byte[] imageBytes = stream.ToArray(); string base64String = Convert.ToBase64String(imageBytes); oResultData.Data = base64String; } } catch (Exception ex) { oResultData.SetError(ex); } return(oResultData); }
/// <summary> /// Action执行中触发委托 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { string code = filterContext.HttpContext.Request.Query["code"].ToString(); var wxPubInfo = MemoryCacheHelper.GetCache <Wx_PublicInfo>("WxPubInfo"); if (null != code && code.Length > 0) { ModelWxUserInfo mWxUserInfo = WXOAuthApiHelper.GetUserInfo(wxPubInfo.AppId, wxPubInfo.AppSecret, code); if (mWxUserInfo != null) { filterContext.HttpContext.Response.Cookies.Append(ComConst.Wx_ModelWxUserInfo, JsonHelper.ToJson(mWxUserInfo), ComHelper.GetCookieOpetion()); filterContext.HttpContext.Session.SetString(ComConst.Wx_ModelWxUserInfo, JsonHelper.ToJson(mWxUserInfo)); } } else { if (filterContext.HttpContext.Request.Cookies.TryGetValue(ComConst.Wx_ModelWxUserInfo, out string value)) { filterContext.HttpContext.Response.Cookies.Append(ComConst.Wx_ModelWxUserInfo, value, ComHelper.GetCookieOpetion()); filterContext.HttpContext.Session.SetString(ComConst.Wx_ModelWxUserInfo, value); } else { var rst = new ContentResult(); rst.Content = "登录过期,请退出重新进入"; filterContext.Result = rst; } } }
public ActionResult AdminSearch(String adminsearchkey, int page = 1) { if (String.IsNullOrEmpty(adminsearchkey)) { return(View(new PagedList <BaseEntity>(new List <BaseEntity>(), page - 1, 20, 0))); } ViewBag.SearchKey = adminsearchkey; adminsearchkey = adminsearchkey.Trim().ToLower(); int storeId = this.LoginStore.Id; String key = String.Format("SearchEntireStore-{0}-{1}", storeId, adminsearchkey); List <BaseEntity> resultList = null; StoreSearchCache.TryGet(key, out resultList); if (resultList == null) { resultList = SearchEntireStoreAsync(adminsearchkey, storeId).Result; StoreSearchCache.Set(key, resultList, MemoryCacheHelper.CacheAbsoluteExpirationPolicy(ProjectAppSettings.GetWebConfigInt("SearchEntireStore_Minute", 10))); } var returnSearchModel = new PagedList <BaseEntity>(resultList, page - 1, 20, resultList.Count); return(View(returnSearchModel)); }
public List <ProductCategory> GetProductCategoriesByStoreIdFromCache(int storeId, string type) { String key = String.Format("GetProductCategoriesByStoreIdFromCache-{0}-{1}", storeId, type); List <ProductCategory> items = null; ProductCategoryCache.TryGet(key, out items); if (items == null) { var cats = this.FindBy(r => r.StoreId == storeId && r.CategoryType.Equals(type, StringComparison.InvariantCultureIgnoreCase)) .OrderBy(r => r.Ordering) .Include(r => r.Products.Select(r1 => r1.ProductFiles.Select(m => m.FileManager))); items = cats.ToList(); foreach (var category in items) { foreach (var ccc in category.Products) { ccc.Description = ""; // GeneralHelper.GetDescription(ccc.Description, 200); } } ProductCategoryCache.Set(key, items, MemoryCacheHelper.CacheAbsoluteExpirationPolicy(ProjectAppSettings.GetWebConfigInt("ProductCategories_CacheAbsoluteExpiration_Minute", 10))); } return(items); }
public async Task <ActionResult> Brands() { var sitemapItems = new List <SitemapItem>(); String key = String.Format("BrandsSiteMap-{0}", StoreId); ProductSitemapItemCache.TryGet(key, out sitemapItems); if (sitemapItems == null) { sitemapItems = new List <SitemapItem>(); var brandsTask = BrandService.GetBrandsAsync(StoreId, null, true); await Task.WhenAll(brandsTask); var brands = brandsTask.Result; foreach (var brand in brands) { var brandDetailLink = LinkHelper.GetBrandIdRouteValue(brand); var siteMap = new SitemapItem(Url.AbsoluteAction("detail", "brands", new { id = brandDetailLink }), changeFrequency: SitemapChangeFrequency.Monthly, priority: 1.0); sitemapItems.Add(siteMap); } ProductSitemapItemCache.Set(key, sitemapItems, MemoryCacheHelper.CacheAbsoluteExpirationPolicy(ProjectAppSettings.CacheLongSeconds)); } return(new SitemapResult(sitemapItems)); }
public string CheckUpdate(string currentVersion) { try { string[] verStrs = MemoryCacheHelper.GetCacheItem <string[]>("upcache", () => { string updatePath = ConfigHelper.GetConfigString("ClientUpdateDir", "", true); if (string.IsNullOrWhiteSpace(updatePath)) { return(null); } string[] ups = Directory.GetDirectories(updatePath, "*", SearchOption.TopDirectoryOnly); string newdir = ups.Max(); //DateTime UpTime = DateTime.ParseExact(Path.GetFileNameWithoutExtension(newdir), "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture); string[] lines = File.ReadAllLines(newdir + "\\Version.txt"); string newVersion = lines[0]; //string upStr = null; string nvText = StringPlus.GetArrayStr(lines, Environment.NewLine); //string[] apps = Directory.GetFiles(newdir, "*.exe", SearchOption.TopDirectoryOnly); //string newApp = apps.Max(); //string[] otas = Directory.GetFiles(newdir + "\\ota", "*", SearchOption.AllDirectories); //string otastr = StringPlus.GetArrayStr(otas, ";"); //List<string> list = new List<string>(); //list.Add("Update"); //list.Add(DateTimeHelper.TimeToStamp(UpTime).ToString()); //list.Add(newVersion); //list.Add(nvText); //list.Add(newApp); //list.Add(otastr); //upStr = StringPlus.GetArrayStr(list); return(new[] { newVersion, nvText }); }, DateTime.Now.AddMinutes(15)); if (verStrs != null) { string newVersion = verStrs[0]; if (String.CompareOrdinal(currentVersion, newVersion) >= 0) { return(null); } else { return(verStrs[1]); } } else { return(null); } } catch (Exception e) { LogHelper.Log.Error("获取客户端更新信息失败", e); return(null); } }
/// <summary> /// 获取树形展示数据 /// </summary> /// <returns></returns> public ActionResult GetJsTreeJson(bool update = false) { #region 使用MemoryCache缓存提高速度 System.Reflection.MethodBase method = System.Reflection.MethodBase.GetCurrentMethod(); string key = string.Format("{0}-{1}-{2}", method.DeclaringType.FullName, method.Name, ""); if (update) { MemoryCacheHelper.RemoveItem(key); } var result = MemoryCacheHelper.GetCacheItem <ActionResult>(key, delegate() { List <JsTreeData> treeList = new List <JsTreeData>(); List <DictTypeInfo> typeList = BLLFactory <DictType> .Instance.Find("PID='-1' "); foreach (DictTypeInfo info in typeList) { JsTreeData node = new JsTreeData(info.ID, info.Name, "fa fa-file icon-state-warning icon-lg"); GetJsTreeJson(info.ID, node); treeList.Add(node); } return(ToJsonContent(treeList)); }, new TimeSpan(0, 30, 0));//30分钟过期 return(result); #endregion }
public async void AddEmployeeActivityByFormTest() { //arrange DBSettings dBSettings = new DBSettings(); IMemoryCache memoryCache = MemoryCacheHelper.GetMemoryCache(); CacheSettings cacheSettings = new CacheSettings(); EmployeeActivityByDapperRepository employeeActivityRepository = new EmployeeActivityByDapperRepository(dBSettings, memoryCache, cacheSettings); EmployeeActivityApiByDapperController employeeActivityController = new EmployeeActivityApiByDapperController(employeeActivityRepository); var tics = DateTime.Now.Ticks; EmployeeActivity employeeActivity = new EmployeeActivity() { FirstName = string.Concat("FName_", tics), LastName = string.Concat("LName_", tics), EmailAddress = string.Concat(tics, "@email.com"), ActivityName = string.Concat("Activity_Name_", tics), Comments = string.Concat("Comments_", tics) }; //act var result = await employeeActivityController.AddEmployeeActivityByBody(employeeActivity); //assert Assert.NotEqual <int>(0, result); }
public bool IsExist <TValue>(string key, out TValue value) { switch (_CacheOptions.CacheMediaType) { case CacheMediaType.Local: return(MemoryCacheHelper.Exist(key, out value)); case CacheMediaType.Redis: try { var redisResult = GetRedisCacheProvider().Get(key); if (!string.IsNullOrEmpty(redisResult)) { value = JsonConvert.DeserializeObject <TValue>(redisResult); return(true); } } catch (ArgumentException argEx) { throw argEx; } value = default(TValue); return(false); default: value = default(TValue); return(false); } }
/// <inheritdoc /> /// <summary> /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.Request.Method == HttpMethod.Get) { //5min降级时间 var b = ThrottlingHelper.ThrottlingDegrade(ConfigHelper.GetIntValue("Throttling"), 300); //当开启动态降级 if (b) { var controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName; var actionName = actionContext.ActionDescriptor.ActionName; var item = GetKey(controllerName, actionName, actionContext.ActionArguments); var bRes = MemoryCacheHelper.Get(item); if (bRes != null) { var bResult = (ResponseResult)bRes; if (DateTimeOffset.Now.DateTime <= bResult.Expires.DateTime) { var res = actionContext.Request.CreateResponse(); res.Headers.CacheControl = new CacheControlHeaderValue { MaxAge = TimeSpan.FromSeconds(180), Public = true, NoCache = false }; res.Content = new StringContent(bResult.ResponseContent, Encoding.UTF8, "application/json"); actionContext.Response = res; } } } } base.OnActionExecuting(actionContext); }
public StorePagedList <Content> GetContentsCategoryId(int storeId, int?categoryId, string typeName, bool?isActive, int page, int pageSize) { String key = String.Format("Store-{0}-GetContentsCategoryId-{1}-{2}-{3}-{4}-{5}", storeId, typeName, categoryId, isActive.HasValue ? isActive.Value.ToStr() : "", page, pageSize); StorePagedList <Content> items = null; _contentCacheStorePagedList.IsCacheEnable = this.IsCacheEnable; _contentCacheStorePagedList.TryGet(key, out items); if (items == null) { var returnList = this.GetAllIncluding(r => r.ContentFiles.Select(r1 => r1.FileManager)) .Where(r2 => r2.StoreId == storeId && r2.Type.Equals(typeName, StringComparison.InvariantCultureIgnoreCase)); if (categoryId.HasValue) { returnList = returnList.Where(r => r.CategoryId == categoryId.Value); } if (isActive.HasValue) { returnList = returnList.Where(r => r.State == isActive); } var cat = returnList.OrderByDescending(r => r.Id).ToList(); items = new StorePagedList <Content>(cat.Skip((page - 1) * pageSize).Take(pageSize).ToList(), page, pageSize, cat.Count()); // items = new PagedList<Content>(cat, page, cat.Count()); // items = (PagedList<Content>) cat.ToPagedList(page, pageSize); _contentCacheStorePagedList.Set(key, items, MemoryCacheHelper.CacheAbsoluteExpirationPolicy(this.CacheMinute)); } return(items); }
protected override void OnLoad(EventArgs e) { #region GridControl中特殊字段绑定 DataTable dicDpt = Tmo_FakeEntityClient.Instance.GetData("tmo_department", new[] { "dpt_id", "dpt_name", "dpt_parent" }, "dpt_id in (" + TmoComm.login_docInfo.children_department + "," + TmoComm.login_docInfo.doc_department + ")"); DataRow dr1 = dicDpt.NewRow(); dr1["dpt_id"] = -1; dr1["dpt_name"] = "无部门"; dicDpt.Rows.Add(dr1); TSCommon.BindRepositoryImageComboBox(rp_doc_department, dicDpt, "dpt_name", "dpt_id"); DataTable dicGroup = MemoryCacheHelper.GetCacheItem <DataTable>("tmo_docgroup", () => Tmo_FakeEntityClient.Instance.GetData("tmo_docgroup", new[] { "group_id", "group_name" }, "group_level>=" + TmoComm.login_docInfo.doc_group_level), DateTime.Now.AddMinutes(5)); DataTable dicGroupCp = dicGroup.Copy(); DataRow dr2 = dicGroupCp.NewRow(); dr2["group_id"] = -1; dr2["group_name"] = "无群组"; dicGroupCp.Rows.Add(dr2); TSCommon.BindRepositoryImageComboBox(rp_doc_group, dicGroupCp, "group_name", "group_id"); #endregion #region 查询条件绑定 UCTreeListSelector selCheck = new UCTreeListSelector(false); DataRow[] drs = dicDpt.Select("dpt_id=" + TmoComm.login_docInfo.doc_department); for (int i = 0; i < drs.Length; i++) { dicDpt.Rows.Remove(drs[i]); } selCheck.InitData(doc_department, dicDpt, "dpt_id", "dpt_parent", "dpt_name", true); TSCommon.BindImageComboBox(doc_group, dicGroup, "", "group_name", "group_id", true); #endregion base.OnLoad(e); }