示例#1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static void TranslateDescription(Messaggio AMessage, CacheKeys AKey)
        {
            if ((AMessage != null) && (AKey != CacheKeys.NULL))
            {
                ListaDecodificaMessaggi FList = CacheManager <ListaDecodificaMessaggi> .get(AKey, VincoloType.FILESYSTEM);

                if (FList != null)
                {
                    ListaDecodificaMessaggi.ErroreRow FRow = FList.Errore.FindBycod(AMessage.Codice);

                    if (FRow != null)
                    {
                        AMessage.Descrizione = FRow.desc;
                        if (AMessage.IsVariable)
                        {
                            foreach (KeyValuePair <string, string[]> item in AMessage.Variabili)
                            {
                                if (item.Value != null)
                                {
                                    AMessage.Descrizione = AMessage.Descrizione.Replace("\\" + item.Key + "\\", string.Join("||", item.Value));
                                }
                            }
                        }
                    }
                }
            }
        }
示例#2
0
        public async Task SetCurrentImageIDToNull(int userID)
        {
            await _sqlObjectFactory.GetConnection().UsingAsync(connection =>
                                                               connection.ExecuteAsync("UPDATE pf_Profile SET ImageID = NULL WHERE UserID = @UserID", new { UserID = userID }));

            _cacheHelper.RemoveCacheObject(CacheKeys.UserProfile(userID));
        }
示例#3
0
        public async Task UpdatePoints(int userID, int points)
        {
            await _sqlObjectFactory.GetConnection().UsingAsync(connection =>
                                                               connection.ExecuteAsync("UPDATE pf_Profile SET Points = @Points WHERE UserID = @UserID", new { UserID = userID, Points = points }));

            _cacheHelper.RemoveCacheObject(CacheKeys.UserProfile(userID));
        }
示例#4
0
        public async Task DeleteAsync(DeleteReply command)
        {
            var reply = await _dbContext.Posts
                        .Include(x => x.CreatedByUser)
                        .Include(x => x.Topic).ThenInclude(x => x.Forum).ThenInclude(x => x.Category)
                        .Include(x => x.Topic).ThenInclude(x => x.Forum).ThenInclude(x => x.LastPost)
                        .FirstOrDefaultAsync(x =>
                                             x.Id == command.Id &&
                                             x.TopicId == command.TopicId &&
                                             x.Topic.ForumId == command.ForumId &&
                                             x.Topic.Forum.Category.SiteId == command.SiteId &&
                                             x.Status != PostStatusType.Deleted);

            if (reply == null)
            {
                throw new DataException($"Reply with Id {command.Id} not found.");
            }

            reply.Delete();

            _dbContext.Events.Add(new Event(command.SiteId,
                                            command.UserId,
                                            EventType.Deleted,
                                            typeof(Post),
                                            command.Id));

            if (reply.IsAnswer)
            {
                reply.Topic.SetAsAnswered(false);
            }

            reply.Topic.DecreaseRepliesCount();
            reply.Topic.Forum.DecreaseRepliesCount();
            reply.Topic.Forum.Category.DecreaseRepliesCount();
            reply.CreatedByUser.DecreaseRepliesCount();

            if (reply.Topic.Forum.LastPost != null && (reply.Id == reply.Topic.Forum.LastPostId || reply.Id == reply.Topic.Forum.LastPost.TopicId))
            {
                var newLastPost = await _dbContext.Posts
                                  .Where(x => x.ForumId == reply.Topic.ForumId &&
                                         x.Status == PostStatusType.Published &&
                                         (x.Topic == null || x.Topic.Status == PostStatusType.Published) &&
                                         x.Id != reply.Id)
                                  .OrderByDescending(x => x.CreatedOn)
                                  .FirstOrDefaultAsync();

                if (newLastPost != null)
                {
                    reply.Topic.Forum.UpdateLastPost(newLastPost.Id);
                }
                else
                {
                    reply.Topic.Forum.UpdateLastPost(null);
                }
            }

            await _dbContext.SaveChangesAsync();

            _cacheManager.Remove(CacheKeys.Forum(reply.Topic.ForumId));
        }
示例#5
0
        /// <summary>
        /// The text.
        /// </summary>
        /// <param name="merchelloContext">
        /// The merchello context.
        /// </param>
        /// <param name="area">
        /// The area.
        /// </param>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        internal static string Text(IMerchelloContext merchelloContext, string area, string key)
        {
            Mandate.ParameterNotNull(merchelloContext, "MerchelloContext");

            if (string.IsNullOrEmpty(area) || string.IsNullOrEmpty(key))
            {
                return(string.Empty);
            }

            var lang = "en";

            try
            {
                lang = MerchelloConfiguration.Current.Section.LogLocalization;
            }
            catch (Exception)
            {
                lang = "en";
            }

            var cacheKey = CacheKeys.GetLocalizationCacheKey(lang);

            var xdoc = XDocument.Parse((string)merchelloContext.Cache.RuntimeCache.GetCacheItem(cacheKey, () => ui.getLanguageFile(lang).InnerXml), LoadOptions.None);

            var xArea = xdoc.Descendants("area").FirstOrDefault(x => x.Attribute("alias").Value == area);

            if (xArea == null)
            {
                return(string.Empty);
            }

            var xKey = xArea.Descendants("key").FirstOrDefault(x => x.Attribute("alias").Value == key);

            return(xKey == null ? string.Empty : xKey.Value);
        }
        public async Task <IEnumerable <WorkspaceViewModel> > GetUserWorkspaces(string authUserId)
        {
            string cacheKey = CacheKeys.UserWorkspace(authUserId);
            IEnumerable <WorkspaceViewModel> workspaceViewModels = _memoryCache.Get <IEnumerable <WorkspaceViewModel> >(cacheKey);

            if (workspaceViewModels == null)
            {
                var userModel = await _userRepository.GetByAuthIdAsync(_dbContext, authUserId);

                // if the user has not added any workspaces yet, they may have no user record....so just return an empty enum
                if (userModel == null)
                {
                    return(Enumerable.Empty <WorkspaceViewModel>());
                }
                if (userModel.Workspaces == null || !userModel.Workspaces.Any())
                {
                    workspaceViewModels = Enumerable.Empty <WorkspaceViewModel>();
                }
                else
                {
                    var workspaceDbModels = await _workspaceRepository.GetManyByIdAsync(_dbContext, userModel.Workspaces);

                    workspaceViewModels = _mapper.Map <IEnumerable <WorkspaceDbModel>, IEnumerable <WorkspaceViewModel> >(workspaceDbModels);
                }

                _memoryCache.Set(cacheKey, workspaceViewModels, TimeSpan.FromMinutes(15));
            }

            return(workspaceViewModels);
        }
示例#7
0
        public async Task <ActionResult <ApiMessage <MediaTitleVm> > > Get(int id)
        {
            var cacheKey = CacheKeys.MediaTitle(id);

            if (_cache.TryGetValue(cacheKey, out var cachedEntity))
            {
                _logger.LogDebug("Retrieved from cache!");
                return(ApiMessage.From(_mapper.Map <MediaTitleVm>(cachedEntity as MediaTitle)));
            }

            var entity = await _service.Get(id);

            if (entity == null)
            {
                return(NotFound(new ApiMessage {
                    Error = ApiError.NotFound
                }));
            }

            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    .SetSlidingExpiration(TimeSpan.FromSeconds(5))
                                    .SetSize(1);

            _cache.Set(cacheKey, entity, cacheEntryOptions);

            return(ApiMessage.From(_mapper.Map <MediaTitleVm>(entity)));
        }
示例#8
0
        public async Task <ActionResult <ApiMessage <MediaTitleVm> > > Put(int id, [FromBody] MediaTitleVm title)
        {
            // find first to determine type
            var entity = await _service.Get(id);

            if (entity == null)
            {
                return(NotFound(new ApiMessage {
                    Error = ApiError.NotFound
                }));
            }

            title.Id = id;
            if (entity.Type == MediaTitleType.Movie)
            {
                var movie = _mapper.Map <Movie>(title);
                await _service.Update(movie);
            }
            else if (entity.Type == MediaTitleType.Series)
            {
                var series = _mapper.Map <Series>(title);
                await _service.Update(series);
            }
            // invalidate cache
            _cache.Remove(CacheKeys.MediaTitle(id));

            return(ApiMessage.From(title));
        }
        /// <summary>
        /// The caches the customer.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        private void CacheCustomer(ICustomerBase customer)
        {
            // set/reset the cookie
            var cookie = new HttpCookie(CustomerCookieName)
            {
                Value = this.ContextData.ToJson()
            };

            // Ensure a session cookie for Anonymous customers
            if (customer.IsAnonymous)
            {
                if (_anonCookieExpireDays <= 0)
                {
                    cookie.Expires = DateTime.MinValue;
                }
                else
                {
                    var expires = DateTime.Now.AddDays(_anonCookieExpireDays);
                    cookie.Expires = expires;
                }
            }

            this._umbracoContext.HttpContext.Response.Cookies.Add(cookie);

            this._cache.RequestCache.GetCacheItem(CustomerCookieName, () => this.ContextData);
            this._cache.RuntimeCache.GetCacheItem(CacheKeys.CustomerCacheKey(customer.Key), () => customer, TimeSpan.FromMinutes(5), true);
        }
        public async Task <ActionResult <IEnumerable <StudentInterventionsDTO> > > GetCachedScoringInterventions(string sectionUniqueId)
        {
            string key    = CacheKeys.Composed(CacheKeys.InterventionScoringsBySectionUniqueId, sectionUniqueId);
            var    result = await _cacheProvider.Get <IEnumerable <StudentInterventionsDTO> >(key);

            return(Ok(result));
        }
示例#11
0
        public List <dtoDisplayRepositoryItem> GetItemsWithPermissions(List <long> idItems, Int32 idCurrentPerson, RepositoryIdentifier identifier, liteRepositorySettings settings, String unknownUser, Boolean useCache = false)
        {
            String           key    = CacheKeys.UserViewOfPartialRepository(idCurrentPerson, identifier);
            ModuleRepository module = GetPermissions(identifier, idCurrentPerson);
            List <dtoDisplayRepositoryItem> rItems = lm.Comol.Core.DomainModel.Helpers.CacheHelper.Find <List <dtoDisplayRepositoryItem> >(key);

            if (rItems == null || !rItems.Any() || !useCache)
            {
                rItems = new List <dtoDisplayRepositoryItem>();
                List <dtoRepositoryItem> fItems = GetFullRepository(identifier, unknownUser, true);
                if (fItems == null)
                {
                    return(null);
                }

                List <dtoDisplayRepositoryItem> items = GetRepositoryItemsWithPermissions(settings, UC.CurrentUserID, identifier, fItems, module, module.Administration || module.ManageItems, module.Administration || module.ManageItems, false, false);
                if (items != null)
                {
                    rItems.AddRange(items);
                }
                if (useCache && rItems.Any())
                {
                    CacheHelper.AddToCache <List <dtoDisplayRepositoryItem> >(key, rItems, CacheExpiration._5minutes);
                }
            }
            return(GetItemsWithPermissions(idItems, rItems, settings, idCurrentPerson, module));
        }
示例#12
0
        public static void SetUserInRoom(this ICache cache, ChatUser user, ChatRoom room, bool value)
        {
            string key = CacheKeys.GetUserInRoom(user, room);

            // cache very briefly.  We could set this much higher if we know that we're on a non-scaled-out server.
            //cache.Set(key, value, TimeSpan.FromSeconds(1));
        }
示例#13
0
 public void RemoveCachedItem(CacheKeys CacheKeyName)
 {
     if (MainCache.Contains(CacheKeyName.ToString()))
     {
         MainCache.Remove(CacheKeyName.ToString());
     }
 }
示例#14
0
        public async Task <Assessment> GetByIdentifier(string identifier)
        {
            string key = CacheKeys.Composed(CacheKeys.AssessmentByIdentifier, identifier);
            bool   assessmentIsCached = await _cacheProvider.TryHasKey(key);

            if (assessmentIsCached)
            {
                var cachedAssessment = await _cacheProvider.GetOrDefault <Assessment>(key);

                if (cachedAssessment != null)
                {
                    return(cachedAssessment);
                }
            }

            var odsApi = await _odsApiClientProvider.NewResourcesClient();

            var assessmentsFromApiv3 = await odsApi.Get <IList <AssessmentModelv3> >("assessments", new Dictionary <string, string>()
            {
                { "assessmentIdentifier", identifier },
            });

            var foundAssessmentv3 = assessmentsFromApiv3.FirstOrDefault(a => a.AssessmentIdentifier == identifier);
            var assessmentv2      = foundAssessmentv3.MapToAssessmentv2();

            await _cacheProvider.TrySet(key, assessmentv2);

            return(assessmentv2);
        }
示例#15
0
        public async Task <Intervention> GetByIdentificationCode(string identificationCode)
        {
            var key = CacheKeys.Composed(CacheKeys.InterventionByIdentificationCode, identificationCode);

            if (await _cacheProvider.TryHasKey(key))
            {
                return(await _cacheProvider.Get <Intervention>(key));
            }

            var ods = await _odsApiClientProvider.NewResourcesClient();

            var interventions = await ods.Get <IList <Intervention> >("interventions", new Dictionary <string, string>
            {
                ["identificationCode"] = identificationCode,
            });

            var intervention = interventions.FirstOrDefault();

            if (intervention == null)
            {
                throw new InterventionNotFoundException(identificationCode);
            }

            await _cacheProvider.TrySet(key, intervention);

            return(intervention);
        }
示例#16
0
        public void should_getallkeys()
        {
            // Arrange
            CacheMock           cache    = new CacheMock();
            ApplicationSettings settings = new ApplicationSettings()
            {
                UseObjectCache = true
            };

            List <string> tagCacheItems1 = new List <string>()
            {
                "1", "2"
            };
            List <string> tagCacheItems2 = new List <string>()
            {
                "a", "b"
            };
            ListCache listCache = new ListCache(settings, cache);

            // Act
            listCache.Add("all.tags1", tagCacheItems1);
            listCache.Add("all.tags2", tagCacheItems2);

            // Assert
            List <string> keys = listCache.GetAllKeys().ToList();

            Assert.That(keys, Contains.Item(CacheKeys.ListCacheKey("all.tags1")));
            Assert.That(keys, Contains.Item(CacheKeys.ListCacheKey("all.tags2")));
        }
示例#17
0
        public static void SetUserInRoom(this ICache cache, ChatUser user, ChatRoom room, bool value)
        {
            string key = CacheKeys.GetUserInRoom(user, room);

            // Cache this forever since people don't leave rooms often
            cache.Set(key, value, TimeSpan.FromDays(365));
        }
示例#18
0
 public static async Task SaveObjectAsync <T>(this IDistributedCache cache, CacheKeys key, T item,
                                              DistributedCacheEntryOptions options, long additionalKey = 0)
 {
     var data = DataCompressor.Compress(JsonConvert.SerializeObject(item, HelperFunctions.GetJsonSettings()));
     await cache.SetStringAsync(MakeKey(key, additionalKey),
                                data, options);
 }
示例#19
0
        public bool Update(Profile profile)
        {
            var success = false;

            _sqlObjectFactory.GetConnection().Using(connection =>
                                                    success = connection.Command(_sqlObjectFactory, "UPDATE pf_Profile SET IsSubscribed = @IsSubscribed, Signature = @Signature, ShowDetails = @ShowDetails, Location = @Location, IsPlainText = @IsPlainText, DOB = @DOB, Web = @Web, AIM = @AIM, ICQ = @ICQ, YahooMessenger = @YahooMessenger, Facebook = @Facebook, Twitter = @Twitter, IsTos = @IsTos, TimeZone = @TimeZone, IsDaylightSaving = @IsDaylightSaving, AvatarID = @AvatarID, ImageID = @ImageID, HideVanity = @HideVanity, LastPostID = @LastPostID, Points = @Points WHERE UserID = @UserID")
                                                              .AddParameter(_sqlObjectFactory, "@IsSubscribed", profile.IsSubscribed)
                                                              .AddParameter(_sqlObjectFactory, "@Signature", profile.Signature.NullToEmpty())
                                                              .AddParameter(_sqlObjectFactory, "@ShowDetails", profile.ShowDetails)
                                                              .AddParameter(_sqlObjectFactory, "@Location", profile.Location.NullToEmpty())
                                                              .AddParameter(_sqlObjectFactory, "@IsPlainText", profile.IsPlainText)
                                                              .AddParameter(_sqlObjectFactory, "@DOB", profile.Dob.GetObjectOrDbNull())
                                                              .AddParameter(_sqlObjectFactory, "@Web", profile.Web.NullToEmpty())
                                                              .AddParameter(_sqlObjectFactory, "@AIM", profile.Aim.NullToEmpty())
                                                              .AddParameter(_sqlObjectFactory, "@ICQ", profile.Icq.NullToEmpty())
                                                              .AddParameter(_sqlObjectFactory, "@YahooMessenger", profile.YahooMessenger.NullToEmpty())
                                                              .AddParameter(_sqlObjectFactory, "@Facebook", profile.Facebook.NullToEmpty())
                                                              .AddParameter(_sqlObjectFactory, "@Twitter", profile.Twitter.NullToEmpty())
                                                              .AddParameter(_sqlObjectFactory, "@IsTos", profile.IsTos)
                                                              .AddParameter(_sqlObjectFactory, "@TimeZone", profile.TimeZone)
                                                              .AddParameter(_sqlObjectFactory, "@IsDaylightSaving", profile.IsDaylightSaving)
                                                              .AddParameter(_sqlObjectFactory, "@AvatarID", profile.AvatarID.GetObjectOrDbNull())
                                                              .AddParameter(_sqlObjectFactory, "@ImageID", profile.ImageID.GetObjectOrDbNull())
                                                              .AddParameter(_sqlObjectFactory, "@HideVanity", profile.HideVanity)
                                                              .AddParameter(_sqlObjectFactory, "@LastPostID", profile.LastPostID.GetObjectOrDbNull())
                                                              .AddParameter(_sqlObjectFactory, "@Points", profile.Points)
                                                              .AddParameter(_sqlObjectFactory, "@UserID", profile.UserID)
                                                              .ExecuteNonQuery() == 1);
            _cacheHelper.RemoveCacheObject(CacheKeys.UserProfile(profile.UserID));
            return(success);
        }
示例#20
0
        public async Task <IEnumerable <FakeEntity> > GetListe2Async(ClaimsPrincipal user)
        {
            _logger.LogInformation("GetListe2Async");

            return(await _cache.CacheLoadItems(() => _entityStore.LoadItemsAsync <FakeEntity>(),
                                               CacheKeys.Create <FakeEntity>("liste2")));
        }
示例#21
0
        private async Task RemoveUserFromRole(int userID, string role)
        {
            await _sqlObjectFactory.GetConnection().UsingAsync(connection =>
                                                               connection.ExecuteAsync("DELETE FROM pf_PopForumsUserRole WHERE UserID = @UserID AND Role = @Role", new { UserID = userID, Role = role }));

            _cacheHelper.RemoveCacheObject(CacheKeys.UserRole(userID));
        }
示例#22
0
        public IValueSet Map(ValueSetDescriptionDto dto)
        {
            // Ensure not already cached with full codes list
            var found = this.cache.GetCachedValueSetWithAllCodes(dto.ValueSetUniqueID, this.codeSystemCodes.ToArray());

            if (found != null)
            {
                return(found);
            }

            // Clears cache item in case a short list item is stored (forces cache update)
            var cacheKey = CacheKeys.ValueSetKey(dto.ValueSetUniqueID, this.codeSystemCodes.ToArray());

            this.cache.ClearItem(cacheKey);

            // ValueSet must have codes
            var codes = this.fetch.Invoke(dto.ValueSetUniqueID, this.codeSystemCodes.ToArray());

            if (!codes.Any())
            {
                return(null);
            }

            return((IValueSet)this.cache.GetItem(
                       cacheKey, () => this.Build(dto, codes, codes.Count),
                       TimeSpan.FromMinutes(this.cache.Settings.MemoryCacheMinDuration),
                       this.cache.Settings.MemoryCacheSliding));
        }
        public async Task <ActionResult <IEnumerable <ScoringAssessmentDTO> > > GetCachedScoringAssessments(string sectionUniqueId)
        {
            string key    = CacheKeys.Composed(CacheKeys.AssessmentScoringsBySectionUniqueId, sectionUniqueId);
            var    result = await _cacheProvider.Get <IEnumerable <ScoringAssessmentDTO> >(key);

            return(Ok(result));
        }
示例#24
0
        public async Task UpdateSettingAsync(string settingId, string settingValue)
        {
            await settingsRepository.UpdateSettingValueAsync(settingId, settingValue);

            memoryCache.Remove(CacheKeys.SettingId(settingId));
            memoryCache.Remove(CacheKeys.SettingsId);
        }
示例#25
0
        /// <summary>
        /// Provides an assertion that the customer cookie is associated with the correct customer Umbraco member relation.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <remarks>
        /// http://issues.merchello.com/youtrack/issue/M-454
        /// </remarks>
        private void EnsureIsLoggedInCustomer(ICustomerBase customer)
        {
            if (_cache.RequestCache.GetCacheItem(CacheKeys.EnsureIsLoggedInCustomerValidated(customer.Key)) != null)
            {
                return;
            }

            var memberId  = _membershipHelper.GetCurrentMemberId();
            var dataValue = ContextData.Values.FirstOrDefault(x => x.Key == UmbracoMemberIdDataKey);

            // If the dataValues do not contain the umbraco member id reinitialize
            if (!string.IsNullOrEmpty(dataValue.Value))
            {
                // Assert are equal
                if (!dataValue.Value.Equals(memberId.ToString(CultureInfo.InvariantCulture)))
                {
                    this.Reinitialize(customer);
                }
                return;
            }

            if (dataValue.Value != memberId.ToString(CultureInfo.InvariantCulture))
            {
                this.Reinitialize(customer);
            }
        }
示例#26
0
        private void EnsureIsLoggedInCustomer(ICustomerBase customer, string membershipId)
        {
            if (this._cache.RequestCache.GetCacheItem(CacheKeys.EnsureIsLoggedInCustomerValidated(customer.Key)) != null)
            {
                return;
            }

            var dataValue = this.ContextData.Values.FirstOrDefault(x => x.Key == UmbracoMemberIdDataKey);

            // If the dataValues do not contain the umbraco member id reinitialize
            if (!string.IsNullOrEmpty(dataValue.Value))
            {
                // Assert are equal
                if (!dataValue.Value.Equals(membershipId))
                {
                    this.Reinitialize(customer);
                }
                return;
            }

            if (dataValue.Value != membershipId)
            {
                this.Reinitialize(customer);
            }
        }
示例#27
0
        public async Task <PokemonDto?> GetPokemon(int pokeNumber)
        {
            var rawCachedPokemon = await Cache.GetStringAsync(CacheKeys.Pokemon(pokeNumber));

            if (rawCachedPokemon != null)
            {
                Logger.LogTrace("Found pokemon {@PokemonId} in cache.", pokeNumber);

                var cachedPokemon = JsonConvert.DeserializeObject <PokemonDto>(rawCachedPokemon);

                return(cachedPokemon);
            }

            Pokemon        pokemon;
            PokemonSpecies species;

            try
            {
                pokemon = await DataFetcher.GetApiObject <Pokemon>(pokeNumber);

                species = await DataFetcher.GetApiObject <PokemonSpecies>(pokeNumber);
            }
            catch (Exception e)
            {
                if (e.Message == "Response status code does not indicate success: 404 (Not Found).")
                {
                    return(default);
示例#28
0
        public async Task UpdateAsync(UpdateCategory command)
        {
            await _updateValidator.ValidateCommandAsync(command);

            var category = await _dbContext.Categories
                           .FirstOrDefaultAsync(x =>
                                                x.SiteId == command.SiteId &&
                                                x.Id == command.Id &&
                                                x.Status != StatusType.Deleted);

            if (category == null)
            {
                throw new DataException($"Category with Id {command.Id} not found.");
            }

            category.UpdateDetails(command.Name, command.PermissionSetId);
            _dbContext.Events.Add(new Event(command.SiteId,
                                            command.UserId,
                                            EventType.Updated,
                                            typeof(Category),
                                            category.Id,
                                            new
            {
                category.Name,
                category.PermissionSetId
            }));

            await _dbContext.SaveChangesAsync();

            _cacheManager.Remove(CacheKeys.Categories(command.SiteId));
            _cacheManager.Remove(CacheKeys.CurrentForums(command.SiteId));
        }
        /// <summary>
        /// Read Through Cache
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private MarkerInfoResponse GetMarkerInfoResponse(int uid, string pointType = null)
        {
            try
            {
                var cacheKey = CacheKeys.GetMarkerInfo(uid);
                var reply    = _memCache.Get <MarkerInfoResponse>(cacheKey);
                if (reply != null)
                {
                    // return cached data
                    reply.IsCached = true;
                    return(reply);
                }

                MapPoint marker = _pointCollection.Get(pointType).SingleOrDefault(i => i.MarkerId == uid);

                reply = new MarkerInfoResponse {
                    Id = uid.ToString()
                };
                reply.BuildContent(marker);

                if (GmcConfiguration.Get.CacheServices)
                {
                    _memCache.Set(cacheKey, reply, TimeSpan.FromMinutes(10)); // cache data
                }
                return(reply);
            }
            catch (Exception ex)
            {
                return(new MarkerInfoResponse
                {
                    OperationResult = "0",
                    ErrorMessage = string.Format("MapService says: Parsing error param: {0}", ex.Message)
                });
            }
        }
示例#30
0
        public async Task CreateAsync(CreateCategory command)
        {
            await _createValidator.ValidateCommandAsync(command);

            var categoriesCount = await _dbContext.Categories
                                  .Where(x => x.SiteId == command.SiteId && x.Status != StatusType.Deleted)
                                  .CountAsync();

            var sortOrder = categoriesCount + 1;

            var category = new Category(command.Id,
                                        command.SiteId,
                                        command.Name,
                                        sortOrder,
                                        command.PermissionSetId);

            _dbContext.Categories.Add(category);
            _dbContext.Events.Add(new Event(command.SiteId,
                                            command.UserId,
                                            EventType.Created,
                                            typeof(Category),
                                            category.Id,
                                            new
            {
                category.Name,
                category.PermissionSetId,
                category.SortOrder
            }));

            await _dbContext.SaveChangesAsync();

            _cacheManager.Remove(CacheKeys.Categories(command.SiteId));
            _cacheManager.Remove(CacheKeys.CurrentForums(command.SiteId));
        }
示例#31
0
 // ----------------------------------------------------------------------------
 // (Private)
 // ----------------------------------------------------------------------------
 // **************************************
 // Cache
 // **************************************
 private static object Cache(CacheKeys key)
 {
     return Cache(key.ToString());
 }
示例#32
0
        public void UpdateCache(CacheKeys CacheKeyName, object CacheItem, int priority = (int)CacheItemPriority.NotRemovable)
        {
            lock (_lock)
            {
                var policy = new CacheItemPolicy();
                policy.Priority = (CacheItemPriority)priority;
                //policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.00);

                // Add inside cache 
                MainCache.Set(CacheKeyName.ToString(), CacheItem, policy);
            }
        }
示例#33
0
 public void RemoveCachedItem(CacheKeys CacheKeyName)
 {
     if (MainCache.Contains(CacheKeyName.ToString()))
     {
         MainCache.Remove(CacheKeyName.ToString());
     }
 }
示例#34
0
        public object GetCachedItem(CacheKeys CacheKeyName)
        {
            lock (_lock)
            {
                if (!MainCache.Contains(CacheKeyName.ToString()))
                {
                    switch (CacheKeyName)
                    {
                        case CacheKeys.Settings:
                            var setting = SettingService.Queryable().FirstOrDefault();
                            UpdateCache(CacheKeys.Settings, setting);
                            break;
                        case CacheKeys.SettingDictionary:
                            var settingDictionary = SettingDictionaryService.Queryable().ToList();
                            UpdateCache(CacheKeys.SettingDictionary, settingDictionary);
                            break;
                        case CacheKeys.Categories:
                            var categories = CategoryService.Queryable().Where(x => x.Enabled).OrderBy(x => x.Ordering).ToList();
                            UpdateCache(CacheKeys.Categories, categories);
                            break;
                        case CacheKeys.ListingTypes:
                            var ListingTypes = ListingTypeService.Query().Include(x => x.CategoryListingTypes).Select().ToList();
                            UpdateCache(CacheKeys.ListingTypes, ListingTypes);
                            break;
                        case CacheKeys.ContentPages:
                            var contentPages = ContentPageService.Queryable().Where(x => x.Published).OrderBy(x => x.Ordering).ToList();
                            UpdateCache(CacheKeys.ContentPages, contentPages);
                            break;
                        case CacheKeys.EmailTemplates:
                            var emailTemplates = EmailTemplateService.Queryable().ToList();
                            UpdateCache(CacheKeys.EmailTemplates, emailTemplates);
                            break;
                        case CacheKeys.Statistics:
                            SaveCategoryStats();

                            var statistics = new Statistics();
                            statistics.CategoryStats = CategoryStatService.Query().Include(x => x.Category).Select().ToList();

                            statistics.ListingCount = ListingService.Queryable().Count();
                            statistics.UserCount = AspNetUserService.Queryable().Count();
                            statistics.OrderCount = OrderService.Queryable().Count();
                            statistics.TransactionCount = 0;

                            statistics.ItemsCountDictionary = ListingService.GetItemsCount(DateTime.Now.AddDays(-10));

                            UpdateCache(CacheKeys.Statistics, statistics);
                            break;
                        default:
                            break;
                    }
                };

                return MainCache[CacheKeyName.ToString()] as Object;
            }
        }
示例#35
0
 private void SessionUpdateUserActiveCart(CacheKeys key, params object[] list)
 {
     var obj = GetDataUserActiveCart(list[0] as string);
     SessionUpdate(obj, key);
 }
示例#36
0
 //private static void CacheUpdateContentRepresentationFields(CacheKeys key, params object[] list) {
 //    CacheUpdate(GetDataContentRepresentationFields(), key);
 //}
 private static void CacheUpdateTerritories(CacheKeys key, params object[] list)
 {
     CacheUpdate(GetDataTerritories(), key);
 }
示例#37
0
 private static void CacheUpdateSearchProperties(CacheKeys key, params object[] list)
 {
     CacheUpdate(GetDataSearchProperties(), key);
 }
示例#38
0
 private static void CacheUpdateContentFields(CacheKeys key, params object[] list)
 {
     CacheUpdate(GetDataContentFields(), key);
 }
示例#39
0
 private static void CacheUpdatePricingPlans(CacheKeys key, params object[] list)
 {
     CacheUpdate(GetDataPricingPlans(), key);
 }
示例#40
0
 // **************************************
 // CacheUpdate
 // **************************************
 public static void CacheUpdate(CacheKeys cacheKey)
 {
     _cacheMatrix[cacheKey](cacheKey);
 }
示例#41
0
 private static void CacheUpdateSiteProfiles(CacheKeys key, params object[] list)
 {
     CacheUpdate(GetDataSiteProfiles(), key);
 }
示例#42
0
 public void SessionUpdate(object cacheObject, CacheKeys cacheKey)
 {
     SessionUpdate(cacheObject, cacheKey.ToString());
 }
示例#43
0
 private static void CacheUpdateUsers(CacheKeys key, params object[] list)
 {
     CacheUpdate(GetDataUsers(), key);
 }
示例#44
0
 // ----------------------------------------------------------------------------
 // (Private)
 // ----------------------------------------------------------------------------
 // **************************************
 // DataSession
 // **************************************
 private object Session(CacheKeys key)
 {
     return Session(key.ToString());
 }
示例#45
0
 public static void CacheUpdate(object cacheObject, CacheKeys cacheKey)
 {
     CacheUpdate(cacheObject, cacheKey.ToString());
 }
示例#46
0
 // **************************************
 // SessionUpdate
 // **************************************
 public void SessionUpdate(CacheKeys cacheKey)
 {
     _sessionMatrix[cacheKey](cacheKey);
 }