/// <summary> /// 用户当前操作 /// </summary> /// <param name="objectId">操作对象Id</param> /// <param name="tenantTypeId">租户类型Id</param> /// <param name="userId">用户的UserId</param> /// <returns>用户当前所做的操作:True-顶,false-踩,null-未做任何操作</returns> public bool?IsSupport(long objectId, string tenantTypeId, long userId) { var sql = Sql.Builder; sql .Select("IsSupport") .From("tn_AttitudeRecords") .Where("ObjectId = @0 and TenantTypeId = @1 and UserId = @2", objectId, tenantTypeId, userId); string cacheKey = GetCacheKey_IsSupport(objectId, tenantTypeId, userId); bool?isSupport = cacheService.Get(cacheKey) as bool?; if (isSupport == null) { //获取是否支持 isSupport = CreateDAO().FirstOrDefault <bool?>(sql); if (isSupport != null) { cacheService.Add(cacheKey, isSupport, CachingExpirationType.SingleObject); } } return(isSupport); }
public async Task <IActionResult> GetList() { if (_cacheService.Any("users")) { var users = _cacheService.Get <List <GetUsersResorce> >("users"); return(Ok(users)); } else { BaseResponse <IEnumerable <User> > userListResponse = await userServices.GetWhere(x => x.Id > 0); if (userListResponse.Success) { var result = userServices.GetWhereUserResource(userListResponse.Extra); _cacheService.Add("users", result); return(Ok(result)); } else { return(BadRequest(userListResponse.ErrorMessage)); } } }
public IActionResult Index() { string cacheKey = "key"; string result; if (!_cacheService.Exists(cacheKey)) { result = $"LineZero{DateTime.Now}"; _cacheService.Add(cacheKey, result, TimeSpan.FromMinutes(1), true); } result = _cacheService.Get(cacheKey).ToString(); ViewBag.Cache = result; if (!_cacheService.Exists("ss")) { _cacheService.Add("ss", "Hello World!", TimeSpan.FromMinutes(1), true); } if (!_cacheService.Exists("xx")) { _cacheService.Add("xx", "Hello Universe!", TimeSpan.FromMinutes(1), true); } var values = _cacheService.GetAll(new string[] { "ss", "xx" }); ViewBag.keys = values; return(View()); }
/// <summary> /// 获取OwnerData /// </summary> /// <param name="ownerId">用户Id</param> /// <param name="tenantTypeId">租户类型Id</param> /// <param name="dataKey">数据标识</param> public OwnerData Get(long ownerId, string tenantTypeId, string dataKey) { string cacheKey = GetCacheKey_GetOwnerData(ownerId, dataKey, tenantTypeId); OwnerData ownerData = cacheService.Get(cacheKey) as OwnerData; if (ownerData == null || ownerData.Id == 0) { var sql = PetaPoco.Sql.Builder; sql.Select("*") .From("tn_OwnerData") .Where("OwnerId = @0", ownerId) .Where("Datakey = @0", dataKey) .Where("TenantTypeId = @0", tenantTypeId); ownerData = CreateDAO().FirstOrDefault <OwnerData>(sql); if (ownerData == null) { ownerData = OwnerData.New(); ownerData.OwnerId = ownerId; ownerData.TenantTypeId = tenantTypeId; ownerData.Datakey = dataKey; } cacheService.Add(cacheKey, ownerData, CachingExpirationType.SingleObject); } return(ownerData); }
/// <summary> /// 创建Token值 /// </summary> /// <param name="entity">实体</param> /// <returns>返回token 数据</returns> public dynamic CreateToken(UserEntity entity) { DateTime expirteTime = DateTime.UtcNow.AddMinutes(Convert.ToDouble(ConfigHelper.GetSectionValue("expiresAt"))); Dictionary <string, object> payload = new Dictionary <string, object>(); payload.Add("ID", entity.ID); payload.Add("UserName", entity.UserName); payload.Add("Email", entity.Email); payload.Add("RolesID", entity.RoleID); var tokenacces = new { UserId = entity.ID, //RolesID=entity.RoleID, entity.UserName, AccessToken = Encrypts.CreateToken(payload, Convert.ToInt32(ConfigHelper.GetSectionValue("expiresAt"))), Expires = new DateTimeOffset(expirteTime).ToUnixTimeSeconds(), Success = true }; if (tokenacces.Success) { _cacheService.Add(entity.ID, tokenacces.AccessToken); } return(tokenacces); }
public IActionResult GetNavigation() { string cacheData = _cacheService.Get("WebSiteNavigationCache"); if (string.IsNullOrEmpty(cacheData)) { var repository = _unitOfWork.GetRepository <Entity.m_WebSiteNavigation>(); var resultData = repository.Query() .OrderBy(nav => nav.SortCount) .Where(q => q.IsShow == true) .Select(nav => new Models.WebSiteNavigationDataModel() { AppendTime = nav.AppendTime.Value, IsShow = nav.IsShow.Value, IsTarget = nav.IsTarget.Value, LinkUrl = nav.LinkUrl, NavigationId = nav.NavigationId.Value, NavigationName = nav.NavigationName, SortCount = nav.SortCount.Value }).ToList(); cacheData = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(resultData))); //写入缓存 _cacheService.Add("WebSiteNavigationCache", cacheData); return(APIReturnMethod.ReturnSuccess(resultData)); } else { cacheData = Encoding.UTF8.GetString(Convert.FromBase64String(cacheData.Replace("\"", ""))); //从缓存中获取 return(APIReturnMethod.ReturnSuccess(JsonConvert.DeserializeObject <List <Models.WebSiteNavigationDataModel> >(cacheData))); } }
public IEnumerable <string> Get() { string value = "ccc"; TestClass model = new TestClass() { Name = value, Order = 1, Left = new TestClass() { Name = value + "Left", Order = 1 }, Right = new TestClass() { Name = value + "Right", Right = new TestClass() { Name = value + "Right2", Order = 0 }, Order = 2 } }; _CacheService.Add("abc", "abcdef"); _CacheService.Add("test", model); return(new string[] { "value1", "value2" }); }
public ActionResult <List <PublicCategoryModel> > PublicList() { try { List <PublicCategoryModel> model; const string cacheKey = "AnkaCMS.WebApi.Controllers.CategoryController.PublicList"; if (_cacheService.Exists(cacheKey)) { model = _cacheService.Get <List <PublicCategoryModel> >(cacheKey); } else { model = _serviceCategory.PublicList(); _cacheService.Add(cacheKey, model); _cacheService.AddToKeyList(cacheKey); } return(Ok(model)); } catch (NotFoundException) { ModelState.AddModelError("ErrorMessage", Messages.DangerRecordNotFound); return(BadRequest(ModelState)); } catch (Exception exception) { ModelState.AddModelError("ErrorMessage", Messages.DangerRecordNotFound + " " + exception); return(BadRequest(ModelState)); } }
/// <summary> /// Is this a dos attack? /// </summary> public (bool ShouldBlockClient, ThrottleInfo?ThrottleInfo) IsDosAttack(AntiDosFirewallRequestInfo requestInfo) { var key = GetCacheKey(requestInfo); var expiresAt = GetCacheExpiresAt(); if (!_cacheService.TryGetValue <ThrottleInfo>(key, out var clientThrottleInfo)) { clientThrottleInfo = new ThrottleInfo { RequestsCount = 1, ExpiresAt = expiresAt }; _cacheService.Add(key, clientThrottleInfo, expiresAt, size: 1); return(false, clientThrottleInfo); } if (clientThrottleInfo.RequestsCount > _antiDosConfig.Value.AllowedRequests) { clientThrottleInfo.BanReason = "IsDosAttack"; _cacheService.Add(key, clientThrottleInfo, expiresAt, size: 1); return(true, clientThrottleInfo); } clientThrottleInfo.RequestsCount++; _cacheService.Add(key, clientThrottleInfo, expiresAt, size: 1); return(false, clientThrottleInfo); }
public IActionResult Get(string id) { if (!string.IsNullOrEmpty(id)) { _cacheService.Remove(id); } string code = CaptchaHelper.GetSingleObj().CreateCode(); string captoken = "V_" + Guid.NewGuid().ToString(); TimeSpan timeSpan = new TimeSpan(0, 0, 30); _cacheService.Add(captoken, code, timeSpan); var bitmap = CaptchaHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40); MemoryStream ms = new MemoryStream(); bitmap.Save(ms, ImageFormat.Gif); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); String strbaser64 = Convert.ToBase64String(arr); var send = new CacheM { Token = captoken, Img = strbaser64 }; return(Json(send)); }
/// <summary> /// Checks to see if the user is in the cache. If so then /// validates the date. User will be filtered out if the changed /// by /// </summary> /// <param name="userToFilter">Reference to the user to check.</param> /// <param name="jobConfig">The current job configuration.</param> /// <returns></returns> public ActiveDirectoryUser Execute(ActiveDirectoryUser userToFilter, JobElement jobConfig) { if (_cacheService == null) { _cacheService = CacheServiceFactory.CreateCacheService(Logger, jobConfig.Name); } var cacheKey = userToFilter.Attributes["distinguishedName"].ToString(); var currentUserHash = BuildUserCacheHashValue(userToFilter); if (!_cacheService.ContainsKey(cacheKey)) { // add the value to the cache _cacheService.Add(cacheKey, currentUserHash); // user is not in the cache...allow through return(userToFilter); } // create a json version of the user and compare to the cached value // if they are not the same then the user has been updated var cachedUserHash = _cacheService.GetValue(cacheKey); if (!currentUserHash.Equals(cachedUserHash, StringComparison.InvariantCulture)) { // update the cache entry _cacheService.Add(cacheKey, currentUserHash); return(userToFilter); } return(null); }
public async Task <JsonResult> Login(string mobile, string password) { //验证 var member = new MemberDto { Id = 1, Name = "测试" }; //生成Token var tokenVersion = DateTime.Now.Ticks.ToString(); var claims = new List <Claim>() { new Claim(ClaimTypes.Version, tokenVersion) , new Claim(ClaimTypes.NameIdentifier, member.Id.ToString()) , new Claim(ClaimTypes.Name, member.Name) , new Claim(ClaimTypes.Role, ((int)MemberRole.Default).ToString()) }; var token = _jwtProvider.CreateToken(claims); var loginMember = new LoginMember { Id = member.Id, Name = member.Name }; //如果当前已登陆,则退出当前登录 DoLogout(); _cacheService.Add(string.Format(CacheKeyDefinition.ApiMemberToken, member.Id, tokenVersion), loginMember, TimeSpan.FromMinutes(_jwtConfig.ExpiredMinutes)); return(Json(token)); }
/// <summary> /// 获取某人的某项(或所有)认证实体 /// </summary> public List <Identification> GetUserIdentifications(long userId, long identificationTypeId) { //构建cacheKey StringBuilder cacheKey = new StringBuilder(); string userIdCacheKey = RealTimeCacheHelper.GetListCacheKeyPrefix(CacheVersionType.AreaVersion, "UserId", userId); cacheKey.AppendFormat("Identifications::identificationTypeId-{0}:userIdCacheKey-{1}", identificationTypeId, userIdCacheKey); //先从缓存里取归档项目列表,如果缓存里没有就去数据库取 List <Identification> identifications = cacheService.Get <List <Identification> >(cacheKey.ToString()); if (identifications == null) { identifications = new List <Identification>(); var sql = Sql.Builder.Select("*").From("spb_Identifications"); sql.Where("UserId=@0", userId); if (identificationTypeId > 0) { sql.Where("IdentificationTypeId=@0", identificationTypeId); } identifications = CreateDAO().Fetch <Identification>(sql); //加入缓存 cacheService.Add(cacheKey.ToString(), identifications, CachingExpirationType.ObjectCollection); } return(identifications); }
public virtual T GetByCache(Expression <Func <T, bool> > expression, object entityId) { T local = default(T); if (Repository <T> .RealTimeCacheHelper.EnableCache) { local = cacheService.Get <T>(Repository <T> .RealTimeCacheHelper.GetCacheKeyOfEntity(entityId)); } if (local == null) { using (var db = DbService.GetInstance()) { local = DbService.GetInstance().Queryable <T>().FirstOrDefault(expression); } if (Repository <T> .RealTimeCacheHelper.EnableCache && local != null) { cacheService.Add(Repository <T> .RealTimeCacheHelper.GetCacheKeyOfEntity(local.EntityId), local, Repository <T> .RealTimeCacheHelper.CachingExpirationType); } } if ((local != null)) { return(local); } return(default(T)); }
public async Task SaveEntity <T>(T item) where T : class, IEntity { //item.WithType<IVersionedEntity>(x => x.Date = DateTime.Now); await modCacheService.Add <T>(item); await modStorage.Save <T>(item); }
public async Task <IActionResult> Edit(long?id) { //生成编辑ID,sku变动时根据此ID来操作缓存数据 var EditID = ID.NewID(); ViewData["EditID"] = EditID; if (id.HasValue) { //编辑 var model = await _service.GetByIdAsync(id.Value); if (model == null) { throw new VinoDataNotFoundException("无法取得数据!"); } //取得所有sku并保存到缓存 ProductSkuSearch where = new ProductSkuSearch(); where.ProductId = model.Id; var skus = await _skuService.GetListAsync(where, null); if (skus == null) { skus = new List <ProductSkuDto>(); } foreach (var sku in skus) { sku.ModifyStatus = Domain.Enum.EmEntityModifyStatus.UnChange; } var cacheKey = string.Format(CacheKeyDefinition.ProductSkuTemp, EditID); _cacheService.Add(cacheKey, skus, new TimeSpan(10, 0, 0)); //取得商品类目数据 var dict = new Dictionary <int, long>(); if (model.CategoryId.HasValue) { (await _productCategoryService.GetWithParentsAsync(model.CategoryId.Value)).ForEach(x => dict.Add(x.Level, x.Id)); } ViewBag.Category = JsonConvert.SerializeObject(dict); ViewData["Mode"] = "Edit"; return(View(model)); } else { //新增 ProductDto dto = new ProductDto(); ViewBag.Category = ""; ViewData["Mode"] = "Add"; return(View(dto)); } }
public object Get(string id) { _cacheService.Add("a", "1"); _cacheService.Add("b", "2"); //Console.Write(_cacheService.Get("a")); //Console.Write(_cacheService.Get("b")); return(_cacheService.GetValue("a")); }
public IEnumerable <BrigadeModel> GetAllData() { IEnumerable <BrigadeModel> brigadeList = _cache.Get <IEnumerable <BrigadeModel> >("brigadeList"); if (brigadeList == null) { brigadeList = _repos.GetAllData(); _cache.Add <IEnumerable <BrigadeModel> >("brigadeList", brigadeList, 20); } return(brigadeList); }
/// <summary> /// 获取标签的所有内容项集合 /// </summary> /// <param name="tagName">标签名称</param> /// <param name="tenantTypeId">租户类型Id</param> /// <param name="ownerId">拥有者Id</param> /// <returns>返回指定的内容项Id集合</returns> public IEnumerable <long> GetItemIds(string tagName, string tenantTypeId, long?ownerId) { PetaPocoDatabase dao = CreateDAO(); //获取缓存 StringBuilder cacheKey = new StringBuilder(RealTimeCacheHelper.GetListCacheKeyPrefix(CacheVersionType.AreaVersion, "TagName", tagName)); cacheKey.AppendFormat(":ItemIds-TenantTypeId:{0}-OwnerId:{0}", tenantTypeId, ownerId.HasValue ? ownerId.ToString() : string.Empty); //组装sql语句 var sql = PetaPoco.Sql.Builder; if (ownerId.HasValue && ownerId > 0) { sql.Select("ItemId") .From("tn_ItemsInTags IT") .InnerJoin("tn_TagsInOwners TIO") .On("IT.TagInOwnerId = TIO.Id") .Where("TIO.OwnerId = @0", ownerId); if (!string.IsNullOrEmpty(tenantTypeId)) { sql.Where("TIO.TenantTypeId = @0", tenantTypeId); } if (!string.IsNullOrEmpty(tagName)) { sql.Where("TIO.TagName = @0", tagName); } } else { sql.Select("ItemId") .From("tn_ItemsInTags"); if (!string.IsNullOrEmpty(tenantTypeId)) { sql.Where("TenantTypeId = @0", tenantTypeId); } if (!string.IsNullOrEmpty(tagName)) { sql.Where("TagName = @0", tagName); } } IEnumerable <long> itemIds = null; itemIds = cacheService.Get <IEnumerable <long> >(cacheKey.ToString()); if (itemIds == null) { itemIds = dao.FetchFirstColumn(sql).Cast <long>(); cacheService.Add(cacheKey.ToString(), itemIds, CachingExpirationType.ObjectCollection); } return(itemIds); }
/// <summary> /// 获取预置的配色方案 /// </summary> /// <param name="presentAreaKey"></param> public IEnumerable <CustomStyle> GetColorSchemes(string presentAreaKey) { string cacheKey = "ColorSchemes-" + presentAreaKey; List <CustomStyle> customStyles = cacheService.Get <List <CustomStyle> >(cacheKey); if (customStyles == null) { customStyles = new List <CustomStyle>(); XElement colorSchemesElement = XElement.Load(WebUtility.GetPhysicalFilePath(string.Format("~/Themes/{0}/Custom/ColorScheme.config", presentAreaKey))); if (colorSchemesElement != null) { IEnumerable <XElement> colorSchemeElements = colorSchemesElement.Elements("colorScheme"); foreach (XElement colorSchemeElement in colorSchemeElements) { Dictionary <string, string> definedColours = new Dictionary <string, string>(); CustomStyle customStyle = new CustomStyle(); var isDarkAttr = colorSchemeElement.Attribute("isDark"); bool isDark = false; if (isDarkAttr != null) { bool.TryParse(isDarkAttr.Value, out isDark); } customStyle.IsDark = isDark; var imageUrlAttr = colorSchemeElement.Attribute("imageUrl"); if (imageUrlAttr != null) { customStyle.ImageUrl = imageUrlAttr.Value; } IEnumerable <XElement> colorElements = colorSchemeElement.Elements("color"); foreach (XElement colorElement in colorElements) { var labelAttr = colorElement.Attribute("label"); if (labelAttr == null) { continue; } string colorLabel = labelAttr.Value; var valueAttr = colorElement.Attribute("value"); if (valueAttr == null) { continue; } definedColours[colorLabel] = valueAttr.Value; } customStyle.DefinedColours = definedColours; customStyles.Add(customStyle); } } cacheService.Add(cacheKey, customStyles, CachingExpirationType.RelativelyStable); } return(customStyles); }
public IEnumerable <Role> GetRoleList() { //return cacheService.GetOrAdd(Constants.General.RoleList, repositoryInstance.GetRoleList()) as IEnumerable<Role>; var roleList = cacheService.Get(Constants.General.RoleList) as IEnumerable <Role>; if (roleList == null) { roleList = repositoryInstance.GetRoleList(); cacheService.Add(Constants.General.RoleList, roleList); } return(roleList); }
public IEnumerable <IDictionary <string, object> > GetEntity(string entityName) { string c_key = $"reports_{entityName}"; var entityListCache = _cacheService.Get <IEnumerable <IDictionary <string, object> > >(c_key); if (entityListCache == null) { var entityList = _dbContext.QueryAll(entityName, true); entityListCache = TranslateDynamic(entityList); _cacheService.Add(c_key, entityListCache); } return(entityListCache); }
public Video GetVideo(string videoID) { var cacheKey = "videoRepository:GetVideo:" + videoID; var result = (Video)_cacheService.Get(cacheKey); if (result == null) { result = _underlyingRepository.GetVideo(videoID); _cacheService.Add(cacheKey, result, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } return(result); }
public virtual int Create(TEntity newEntity) { var dbEntity = GetEntity(newEntity); dbEntity.State = EntityState.Added; Db.SaveChanges(); var id = newEntity.Id; Cache?.Add($"{SingleCacheKeyPrefix}:{id}", JsonConvert.SerializeObject(newEntity)); return(id); }
public async void ControlServiceGetShouldGetObjectFromMemoryCache() { //Arrange var testObjectKey = _fixture.Create <string>(); var testObject = _fixture.Create <Guid>(); //Act await _cacheService.Add <Guid>(testObjectKey, testObject); var result = await _controlService.Get <Guid>(testObjectKey); //Assert result.Should().Be(testObject); }
public async void CacheSecviceAddShouldToAddObjectIntoMemoryCache() { //Arrange var testObjectKey = _fixture.Create <string>(); var testObject = _fixture.Create <Guid>(); //Act await _cacheService.Add <Guid>(testObjectKey, testObject); var result = (Guid)_memoryCache.Get(testObjectKey); //Assert result.Should().Be(testObject); }
/// <summary> /// 获取一级评论在评论列表中的页码数 /// </summary> /// <param name="commentId">评论id</param> /// <param name="tenantType">租户类型id</param> /// <param name="commentedObjectId">被评论对象id</param> /// <param name="sortBy">排序方式</param> /// <returns></returns> public int GetPageIndexForCommentInCommens(long commentId, string tenantType, long commentedObjectId, SortBy_Comment sortBy) { int pageIndex = 1; string cacheKey = GetCachekey_GetRootComments(tenantType, commentedObjectId, sortBy); PagingEntityIdCollection peic = cacheService.Get <PagingEntityIdCollection>(cacheKey); if (peic == null) { peic = CreateDAO().FetchPagingPrimaryKeys <Comment>(PrimaryMaxRecords, PageSize * CacheablePageCount, 1, GetSql_CommentPageIndex(tenantType, commentedObjectId, sortBy)); peic.IsContainsMultiplePages = true; cacheService.Add(cacheKey, peic, CachingExpirationType.ObjectCollection); } if (peic != null) { IList <long> commentIds = peic.GetTopEntityIds(peic.Count).Cast <long>().ToList(); int commentIndex = commentIds.IndexOf(commentId); if (commentIndex > 0) { pageIndex = commentIndex / PageSize + 1; } else { PetaPoco.Sql sql = PetaPoco.Sql.Builder .Select("count(Id)") .From("tn_Comments") .Where("TenantTypeId=@0", tenantType) .Where("CommentedObjectId=@0", commentedObjectId); switch (sortBy) { case SortBy_Comment.DateCreated: sql.Where("Id<@0", commentId); break; case SortBy_Comment.DateCreatedDesc: sql.Where("Id>@0", commentId); break; default: sql.Where("Id>@0", commentId); break; } commentIndex = CreateDAO().FirstOrDefault <int>(sql); if (commentIndex > 0) { pageIndex = commentIndex / PageSize + 1; } } } return(pageIndex); }
public PagedList <AlbumSummary> ListAlbums(int page, int pageSize) { var cacheKey = "pictureRepository:ListAlbums:" + page + ":" + pageSize; var result = (PagedList <AlbumSummary>)_cacheService.Get(cacheKey); if (result == null) { result = _underlyingRepository.ListAlbums(page, pageSize); _cacheService.Add(cacheKey, result, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } return(result); }
/// <summary> /// 将文字存入缓存 (用于保存验证码上的字符) /// </summary> /// <param name="context"></param> /// <param name="text"></param> /// <param name="publicKey"></param> /// <param name="validationKeepAlive"></param> /// <param name="validationTimeoutSeconds"></param> public static void CacheText(HttpContextBase context, string text, string publicKey, bool validationKeepAlive, int validationTimeoutSeconds) { string textKey = GetCacheKeyForText(publicKey); if (PersistenceMode == VerificationCodePersistenceMode.Cache) { cacheService.Add(textKey, text, new TimeSpan(0, 0, validationTimeoutSeconds)); } else { context.Session[textKey] = text; } }
public async Task <IEnumerable <FacilityParameterModel> > GetFacilities(string language) { var items = _cacheService.Get("cache_facilities") as IEnumerable <FacilityParameterModel>; if (items != null) { return(items); } language.ConvertLocaleStringToServerLanguage(); items = await _commonService.GetFacilities(language); _cacheService.Add("cache_facilities", items); return(items); }