/// <summary> /// Gets the latest blogs. /// </summary> /// <returns>List<BlogPost>.</returns> public async Task <List <BlogPost> > GetLatestBlogs() { IEnumerable <BlogPost> cacheResult; TableContinuationToken token; //// Check in cache first. Retry operation on first failure. Product Issue :( try { cacheResult = ApplicationCache.Get <IEnumerable <BlogPost> >(ApplicationConstants.BlogsCacheKey); token = ApplicationCache.Get <TableContinuationToken>(ApplicationConstants.BlogsFirstTokenCacheKey); } catch (Exception) { cacheResult = ApplicationCache.Get <IEnumerable <BlogPost> >(ApplicationConstants.BlogsCacheKey); token = ApplicationCache.Get <TableContinuationToken>(ApplicationConstants.BlogsFirstTokenCacheKey); } if (null != cacheResult) { //// We need to add token to user page dictionary as well. if (null != token) { UserPageDictionary.PageDictionary.AddPage(token); } return(cacheResult.ToList()); } var result = await this.GetPagedBlogPreviews(null, true); var firstPageBlogs = result.Select(TableBlogEntity.GetBlogPost).ToList(); ApplicationCache.Set(ApplicationConstants.BlogsCacheKey, firstPageBlogs); return(firstPageBlogs); }
public void LoadGlobalCalendar(DateTime start, DateTime end) { var globalCalendar = ApplicationCache.Get <Dictionary <DateTime, Dictionary <string, bool> > >(Global.GlobalCalendar); foreach (var calendarEvent in _calendarEventRepository.GetByRange <CalendarEvent>(start, end)) { var dateKey = calendarEvent.Start.Date; while (dateKey < calendarEvent.End.Date) { if (!globalCalendar.ContainsKey(dateKey)) { globalCalendar[dateKey] = new Dictionary <string, bool>(); } calendarEvent.SaftyInvoke <Holiday>(h => { globalCalendar[dateKey][h.Country] = true; }); calendarEvent.SaftyInvoke <DaylightSavingTime>(d => { globalCalendar[dateKey][d.TimeZone.Id] = true; }); dateKey = dateKey.AddDays(1); } } }
public JiraAgileService(AssistantSettings configuration, ApplicationCache applicationCache, IJiraServerApi metadataRetriever, IssuesFinder issuesFinder) : base(configuration) { _applicationCache = applicationCache; _metadataRetriever = metadataRetriever; _issuesFinder = issuesFinder; }
public async Task UsesCachedValueUntilTimeHasPassed_WhenAbsoluteExpirationIsSpecifiedAsync() { // Arrange - Setup ApplicationCache, Mock & put initial cache value that will expire in 100 milliseconds using var cache = new ApplicationCache(); const string cacheName = "CacheTests-AbsoluteExp1"; const string initialCacheValue = "Message-0"; var functionMock = new Mock <Func <Task <string> > >(); functionMock.Setup(x => x()).Returns(Task.FromResult(initialCacheValue)); await cache.GetOrAddWithAbsoluteExpirationAsync(cacheName, functionMock.Object, CacheDuration).ConfigureAwait(false); functionMock.Invocations.Clear(); await Task.Delay(LessThanCacheDuration).ConfigureAwait(false); // Act - put new cache value and get cached value var newCacheValue = "Message-1"; functionMock.Setup(x => x()).Returns(Task.FromResult(newCacheValue)); var cachedValue = await cache.GetOrAddWithAbsoluteExpirationAsync(cacheName, functionMock.Object, CacheDuration).ConfigureAwait(false); // Assert that the cached value still holds the initial value because the cache has not expired Assert.That(cachedValue, Is.EqualTo(initialCacheValue)); functionMock.Verify(x => x(), Times.Never); }
public async Task <InvokeResult> UpdateApplicationCacheAsync(ApplicationCache cache, EntityHeader org, EntityHeader user) { await AuthorizeAsync(cache, AuthorizeResult.AuthorizeActions.Update, user, org); ValidationCheck(cache, Actions.Update); if (cache.CacheType.Value == CacheTypes.Redis) { if (!String.IsNullOrEmpty(cache.Password)) { var addSecretResult = await _secureStorage.AddSecretAsync(org, cache.Password); if (!addSecretResult.Successful) { return(addSecretResult.ToInvokeResult()); } if (!string.IsNullOrEmpty(cache.PasswordSecretId)) { await _secureStorage.RemoveSecretAsync(org, cache.PasswordSecretId); } cache.PasswordSecretId = addSecretResult.Result; cache.Password = null; } } await _applicationCacheRepo.UpdateApplicationCacheAsync(cache); return(InvokeResult.Success); }
public async Task RecalculatesCachedValueAfterTimeHasPassed_WhenSlidingExpirationIsSpecifiedAsync() { // Arrange - Setup ApplicationCache, Mock & put initial cache value that will expire in 100 milliseconds using var cache = new ApplicationCache(); const string cacheName = "CacheTests-SlidingExp2"; // Arrange - put initial cache value that will expire in 100 milliseconds var functionMock = new Mock <Func <Task <string> > >(); const string initialCacheValue = "Message-0"; functionMock.Setup(x => x()).Returns(Task.FromResult(initialCacheValue)); await cache.GetOrAddWithSlidingExpirationAsync(cacheName, functionMock.Object, CacheDuration).ConfigureAwait(false); functionMock.Invocations.Clear(); await Task.Delay(GreaterThanCacheDuration).ConfigureAwait(false); // Act - put new cache value and get cached value var newCacheValue = "Message-1"; functionMock.Setup(x => x()).Returns(Task.FromResult(newCacheValue)); var cachedValue = await cache.GetOrAddWithSlidingExpirationAsync(cacheName, functionMock.Object, CacheDuration).ConfigureAwait(false); // Assert that the cached value has the new value because the cache has expired Assert.That(cachedValue, Is.EqualTo(newCacheValue)); functionMock.Verify(x => x(), Times.Once); }
public async Task UsesCachedValueAfterTimeHasPassed_AndCachedValueWasRetrieved_WhenSlidingExpirationIsSpecifiedAsync() { // Arrange - Setup ApplicationCache, Mock & put initial cache value that will expire in 100 milliseconds using var cache = new ApplicationCache(); const string cacheName = "CacheTests-SlidingExp3"; // Arrange - put initial cache value that will expire in 100 milliseconds var functionMock = new Mock <Func <Task <string> > >(); const string initialCacheValue = "Message-0"; functionMock.Setup(x => x()).Returns(Task.FromResult(initialCacheValue)); await cache.GetOrAddWithSlidingExpirationAsync(cacheName, functionMock.Object, CacheDuration).ConfigureAwait(false); await Task.Delay(LessThanCacheDuration).ConfigureAwait(false); await cache.GetOrAddWithSlidingExpirationAsync(cacheName, functionMock.Object, CacheDuration).ConfigureAwait(false); functionMock.Invocations.Clear(); await Task.Delay(AdditionalLessThanCacheDuration).ConfigureAwait(false); // delay for another 70 milliseconds so the total delay is 120 (50 + 70) milliseconds since the 1st cache call // Act - put new cache value and get the cached value var newCacheValue = "Message-1"; functionMock.Setup(x => x()).Returns(Task.FromResult(newCacheValue)); var cachedValue = await cache.GetOrAddWithSlidingExpirationAsync(cacheName, functionMock.Object, CacheDuration).ConfigureAwait(false); // Assert that the cached value should still holds the initial value because the limit was slided thus cache has not expired Assert.That(cachedValue, Is.EqualTo(initialCacheValue)); functionMock.Verify(x => x(), Times.Never); }
public TagService(ITagRepository tagRepository, IArticleRepository articleRepository, IMapper mapper, ApplicationCache cache) { this.tagRepository = tagRepository; this.articleRepository = articleRepository; this.mapper = mapper; this.cache = cache; }
/// <summary> /// Gets the paged blog previews. /// </summary> /// <param name="token">The token.</param> /// <param name="shouldAddPage">if set to <c>true</c> [should add page].</param> /// <returns>IEnumerable<TableBlogEntity>.</returns> private async Task <IEnumerable <TableBlogEntity> > GetPagedBlogPreviews( TableContinuationToken token, bool shouldAddPage) { var activeTable = this.blogContext.CustomOperation(); var query = (from record in activeTable.CreateQuery <DynamicTableEntity>() where record.PartitionKey == ApplicationConstants.BlogKey && record.Properties["IsDraft"].BooleanValue == false && record.Properties["IsDeleted"].BooleanValue == false && string.Compare(record.RowKey, this.rowKeyToUse, StringComparison.OrdinalIgnoreCase) > 0 select record).Take(this.pageSize); var result = await Task.Run(() => query.AsTableQuery().ExecuteSegmented(token, this.blogContext.TableRequestOptions)); if (!shouldAddPage || null == result.ContinuationToken) { return(result.Select(element => element.ConvertDynamicEntityToEntity <TableBlogEntity>())); } UserPageDictionary.PageDictionary.AddPage(result.ContinuationToken); //// If this is the first page response. Add it to cache as well. if (null == token) { ApplicationCache.Set(ApplicationConstants.BlogsFirstTokenCacheKey, result.ContinuationToken); } return(result.Select(element => element.ConvertDynamicEntityToEntity <TableBlogEntity>())); }
public void Execute(IRoutedMessage message, IInteractionNode handlingNode, MessageProcessingOutcome outcome) { var content = LanguageKey.IsNullOrEmpty() ? Message : LanguageReader.GetValue(LanguageKey); ServiceLocator.Current.GetInstance <IAuditLogModel>().Write(new AuditLog { Action = content, CurrentUser = ApplicationCache.Get <string>(Global.LoggerId) }); }
public CommentService(ApplicationContextActivityDecorator traceActivityDecorator, ICommentRepository commentRepository, IMapper mapper, ApplicationCache cache, IMessageBus messageBus) { this.traceActivityDecorator = traceActivityDecorator; this.commentRepository = commentRepository; this.mapper = mapper; this.cache = cache; this.messageBus = messageBus; }
//private static void LoadDefaultTrayIcon() //{ // var bi = new BitmapImage(); // bi.BeginInit(); // bi.UriSource = new Uri(@"pack://application:,,,/Resources/Images/WMSLogo.ico", UriKind.RelativeOrAbsolute); // bi.EndInit(); // App.Current.TrayIcon.Icon = bi; //} public static void LoadCultureInfo() { var language = ConfigurationManager.AppSettings["Language"]; LanguageReader.Load(language); Country.Local = new Country(Application.Current.Dispatcher.Thread.CurrentCulture, new string[0]).ToString(); ApplicationCache.Set(Global.GlobalCalendar, new Dictionary <DateTime, Dictionary <string, bool> >(365)); }
public virtual LaborRule SetDefaultProperty() { //TODO:Verify who set DefaultMaxLaborHour value to cache this.MaxLaborHour = new TimeSpan(ApplicationCache.Get <int>(Global.DefaultMaxLaborHour), 0, 0); this.MinLaborHour = new TimeSpan(ApplicationCache.Get <int>(Global.DefaultMinLaborHour), 0, 0); //xGroupingArrangeShift = new GroupingArrangeShift(); DayOffRule = new DayOffRule(); DayOffMask = new MaskOfDay(); return(this); }
public ArticleService(ApplicationContextActivityDecorator traceActivityDecorator, IArticleRepository articleRepository, ITagRepository tagRepository, TagService tagService, IVisitorRepository visitorRepository, IMapper mapper, ApplicationCache cache) { this.traceActivityDecorator = traceActivityDecorator; this.articleRepository = articleRepository; this.tagRepository = tagRepository; this.tagService = tagService; this.visitorRepository = visitorRepository; this.mapper = mapper; this.cache = cache; }
public void AddAdherenceEvents(IEnumerable <AdherenceEvent> itmes) { var currentAgentId = ApplicationCache.Get <string>(Global.LoggerId); foreach (var o in itmes) { o.Assigner = currentAgentId; o.Remark = string.Empty; _adherenceEventRepository.MakePersistent(o); } }
private static bool Is(this DateTime dateTime, string key) { var globalCalendar = ApplicationCache.Get <Dictionary <DateTime, Dictionary <string, bool> > >(Global.GlobalCalendar); if (globalCalendar == null || !globalCalendar.ContainsKey(dateTime) || string.IsNullOrEmpty(key)) { return(false); } return(globalCalendar[dateTime].ContainsKey(key) && globalCalendar[dateTime][key]); }
public bool Execute(IRoutedMessage message, IInteractionNode handlingNode, object[] parameters) { message.AvailabilityEffect = Effect; var functionKeys = ApplicationCache.Get <ICollection <string> >(Global.LoginUserFunctionKeys); if (functionKeys == null || functionKeys.Count == 0) { //Admin return(true); } return(functionKeys.Contains(FunctionKey)); }
public void AddStoresItem() { Cache cache = HttpRuntime.Cache; ApplicationCache appCache = new ApplicationCache(cache); string key = "key"; string item = "item"; appCache.Add(key, item, TimeSpan.FromMinutes(5)); Assert.NotNull(cache[key]); }
public void GetReturnsNullIfNotFound() { Cache cache = HttpRuntime.Cache; ApplicationCache appCache = new ApplicationCache(cache); string key = "key"; cache.Remove(key); string actual = appCache.Get <string>(key); Assert.Null(actual); }
public void GetReturnsDefaultIfNotFoundValueType() { Cache cache = HttpRuntime.Cache; ApplicationCache appCache = new ApplicationCache(cache); string key = "key"; cache.Remove(key); int actual = appCache.Get <int>(key); Assert.Equal(default(int), actual); }
public async Task <AppBuildState> BuildLocalCacheAsync(AppBuildState state, IEnumerable <string> cacheList) { var appBaseDir = $"./{state.AppCode}/{state.BuildNumber}/Caches"; Directory.CreateDirectory(appBaseDir); var applicationCache = new ApplicationCache(_appHostBase.ToString(), appBaseDir); var fileCaches = new List <string>(); var unsucessfullCaches = new List <string>(); foreach (var cacheUrl in cacheList) { try { var url = new Uri(_appHostBase, $"{cacheUrl}").ToString(); var fileName = $"Caches{cacheUrl.GetGUID()}"; var filePath = $"{appBaseDir}/{fileName}"; Console.WriteLine($"{fileName} <== {cacheUrl}"); var remoteCache = await applicationCache.CheckRemoteCacheAsync(url, string.Empty).ConfigureAwait(false); if (remoteCache != null) { using (var cache = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { var outputStreams = new List <Stream> { cache }; await applicationCache.WriteRemoteCacheAsync(remoteCache, cache, outputStreams).ConfigureAwait(false); fileCaches.Add(fileName); } } } catch { unsucessfullCaches.Add(cacheUrl); } } foreach (var url in unsucessfullCaches) { Console.WriteLine($"Unable to cache {url}"); } state.Caches = fileCaches; return(state); }
public void Login(Employee employee, string role) { ApplicationCache.Set(Global.LoginEmployee, employee); ApplicationCache.Set(Global.LoggerId, employee.AgentId); if (role.IsNotNullOrEmpty()) { //Set Rules SetFunctionKeys(role); } //Log AuditLoginLog(new AuditLog { Action = LanguageReader.GetValue("Logging_Admin_Login"), CurrentUser = employee.AgentId }); }
public void GetReturnsItem() { Cache cache = HttpRuntime.Cache; ApplicationCache appCache = new ApplicationCache(cache); string key = "key"; string item = "item"; cache.Insert(key, item); string actual = appCache.Get <string>(key); Assert.Equal(item, actual); }
public DatabaseModel UpdateApplicationCacheValue(ApplicationCache applicationCache, DatabaseModel databaseInfoModel) { int returnError; Guid returnGuid; string returnErrorMessage; Boolean canDebug = Convert.ToBoolean((GlobalCachingProvider.Instance.GetItem("LOGdbOperation") as string).ToLower()); this._IAdminRepository.UpdateApplicationCacheValue(applicationCache, databaseInfoModel.UserId, canDebug, out returnError, out returnErrorMessage, out returnGuid); databaseInfoModel.ReturnError = returnError; databaseInfoModel.ReturnErrorMessage = returnErrorMessage; databaseInfoModel.ReturnGuid = returnGuid; return(databaseInfoModel); }
public void Login(string agentId, Guid roleId) { var employee = _loginRepository.FirstOrDefault(o => o.AgentId == agentId); ApplicationCache.Set(Global.LoginEmployee, employee); ApplicationCache.Set(Global.LoggerId, employee.AgentId); if (roleId != Guid.Empty) { //Set Rules SetFunctionKeys(roleId); } //Log AuditLoginLog(new AuditLog { Action = LanguageReader.GetValue("Logging_Admin_Login"), CurrentUser = employee.AgentId }); }
public void Setup() { var nonDebugStatusReader = new StubDebugStatusReader(false); var debugStatusReader = new StubDebugStatusReader(true); currentDirectoryWrapper = new StubCurrentDirectoryWrapper(); stubBundleCache = new ApplicationCache(); var retryableFileOpener = new RetryableFileOpener(); hasher = new Hasher(retryableFileOpener); //fileReaderFactory.SetContents(javaScript); javaScriptBundle = new JavaScriptBundle(nonDebugStatusReader, fileWriterFactory, fileReaderFactory, currentDirectoryWrapper, hasher, stubBundleCache); javaScriptBundle2 = new JavaScriptBundle(nonDebugStatusReader, fileWriterFactory, fileReaderFactory, currentDirectoryWrapper, hasher, stubBundleCache); debugJavaScriptBundle = new JavaScriptBundle(debugStatusReader, fileWriterFactory, fileReaderFactory, currentDirectoryWrapper, hasher, stubBundleCache); debugJavaScriptBundle2 = new JavaScriptBundle(debugStatusReader, fileWriterFactory, fileReaderFactory, currentDirectoryWrapper, hasher, stubBundleCache); outputFileNumber += 1; currentOutputFile = outputFileRoot + outputFileNumber + ".js"; }
/// <summary> /// This will dispose and reset all resources used to run the application /// </summary> /// <remarks> /// IMPORTANT: Never dispose this object if you require the Umbraco application to run, disposing this object /// is generally used for unit testing and when your application is shutting down after you have booted Umbraco. /// </remarks> void IDisposable.Dispose() { // Only operate if we haven't already disposed if (_disposed) { return; } using (new WriteLock(_disposalLocker)) { // Check again now we're inside the lock if (_disposed) { return; } //clear the cache if (ApplicationCache != null) { ApplicationCache.ClearAllCache(); } //reset all resolvers ResolverCollection.ResetAll(); //reset resolution itself (though this should be taken care of by resetting any of the resolvers above) Resolution.Reset(); //reset the instance objects this.ApplicationCache = null; if (_databaseContext != null) //need to check the internal field here { if (DatabaseContext.IsDatabaseConfigured) { DatabaseContext.Database.Dispose(); } } this.DatabaseContext = null; this.Services = null; this._isReady = false; //set the internal field // Indicate that the instance has been disposed. _disposed = true; } }
public LoginController( ApplicationContextActivityDecorator traceActivityDecorator, ConfigPreloader configPreloader, ApplicationCache cache, RecaptchaManager recaptchaManager, ITwoFactorAuthenticator twoFactorAuthenticator, ILogger <LoginController> logger, IMessageBus messageBus, IHttpContextAccessor httpContextAccessor) { this.traceActivityDecorator = traceActivityDecorator; this.configPreloader = configPreloader; this.cache = cache; this.recaptchaManager = recaptchaManager; this.twoFactorAuthenticator = twoFactorAuthenticator; this.logger = logger; this.messageBus = messageBus; this.httpContextAccessor = httpContextAccessor; }
private void SaveLog(IStatelessSession session, TermLog entity) { if (session == null) { return; } using (var tx = session.BeginTransaction()) { var currentEmployee = ApplicationCache.Get <Entity>(Global.LoginEmployee); if (currentEmployee != null) { entity.AlterEmployeeId = currentEmployee.Id; } session.Insert(entity); tx.Commit(); } }
public string GetApplicationCacheValueForEdit(string Key) { List <ApplicationCache> applicationCaches = new List <ApplicationCache>(); ApplicationCache applicationCache = new ApplicationCache(); // List<ApplicationCacheViewModel> applicationCacheViewModel = new List<ApplicationCacheViewModel>(); ApplicationCacheViewModel applicationCacheViewModel = new ApplicationCacheViewModel(); applicationCaches = this._ICacheOrchestrator.GetAllApplicationCacheConfig(); applicationCache = applicationCaches.AsParallel().Where(x => x.Key.ToLower() == Key.ToLower()).FirstOrDefault(); Mapper.Map(applicationCache, applicationCacheViewModel); //string ret = RenderPartialToString("~/Areas/Management/Views/CacheManage/_GetAppCacheValueForEdit", applicationCacheViewModel); string ret = RenderPartialToString("_GetAppCacheValueForEdit", applicationCacheViewModel, ControllerContext); return(ret); }