public async Task <IActionResult> GetBookingCountByYear() { Request.Headers.TryGetValue("Authorization", out var token); string role = await AuthHelper.GetRoleFromTokenAsync(token); if (role != "admin") { Log.Error("401 Error. Unauthorized in Analytical Controller: Get()"); return(StatusCode(401, new { Error = "Unauthorized" })); } Log.Information("Getting Booking Count By Year for Admin."); IEnumerable <CountByDateNumber> data = new List <CountByDateNumber>(); string cachedDataString = string.Empty; cachedDataString = await DistributedCache.GetStringAsync("_count_by_year"); if (!string.IsNullOrEmpty(cachedDataString)) { Log.Information("Returned cached results."); // loaded data from the redis cache. data = JsonSerializer.Deserialize <IEnumerable <CountByDateNumber> >(cachedDataString); return(Ok(new BaseResponse <IEnumerable <CountByDateNumber> >(data, true))); // IsCached = true } else { Log.Information("Cached new results."); var baseResponse = await Mediator.Send(new GetBookingCountByYearQuery()); // loading from code (in real-time from database) // then saving to the redis cache data = baseResponse.Data; cachedDataString = JsonSerializer.Serialize <IEnumerable <CountByDateNumber> >(baseResponse.Data); var expiryOptions = new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(600), SlidingExpiration = TimeSpan.FromSeconds(300) }; await DistributedCache.SetStringAsync("_count_by_year", cachedDataString); return(Ok(baseResponse)); // IsCached = false } }
public async Task <IActionResult> GetBookingByStudent(int id, int PageNumber, int PageSize) { /** Request.Headers.TryGetValue("Authorization", out var token); * string role = await AuthHelper.GetRoleFromTokenAsync(token); * Console.WriteLine("role", role); * if (role != "student" || role != "admin") * return StatusCode(401, new { Error = "Unauthorized" });*/ var validFilter = new PaginationFilter(PageNumber, PageSize); IEnumerable <Booking> data = new List <Booking>(); string cachedDataString = string.Empty; cachedDataString = await DistributedCache.GetStringAsync("_bookings_by_students_" + id + "_" + validFilter.PageNumber); if (!string.IsNullOrEmpty(cachedDataString)) { // loaded data from the redis cache. data = JsonSerializer.Deserialize <IEnumerable <Booking> >(cachedDataString); return(Ok(new BaseResponse <IEnumerable <Booking> >(data, true))); // IsCached = true } else { var baseResponse = await Mediator.Send(new GetBookingByStudentQuery { Id = id, PageNumber = validFilter.PageNumber, PageSize = validFilter.PageSize }); // loading from code (in real-time from database) // then saving to the redis cache if (baseResponse.Success) { data = baseResponse.Data; cachedDataString = JsonSerializer.Serialize <IEnumerable <Booking> >(baseResponse.Data); var expiryOptions = new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(600), SlidingExpiration = TimeSpan.FromSeconds(300) }; await DistributedCache.SetStringAsync("_bookings_by_students_" + id + "_" + validFilter.PageNumber, cachedDataString); return(Ok(baseResponse)); // IsCached = false } return(StatusCode(baseResponse.Error.StatusCode, baseResponse.Error)); } }
public void DistributedCache_Get_UsesRegisteredDistributedCacheProvider() { using (new MunqContext()) { var registrar = Dependency.Resolve <IDependencyRegistrar>(); var cache = A.Fake <IDistributedCache>(); registrar.RegisterInstance(cache); A.CallTo(() => cache.Get <int>("SomeKey")) .Returns(13579); var actual = DistributedCache.Get <int>("SomeKey"); Assert.Equal(13579, actual); A.CallTo(() => cache.Get <int>("SomeKey")) .MustHaveHappened(1, Times.Exactly); } }
public ActionResult Login(string userName, string password) { var users = ConfigCenterBusiness.WebUser; string accesskey = Guid.NewGuid().ToString(); var user = users.Where(t => t.UserName.Equals(userName) && t.PassWord.Equals(password)).FirstOrDefault(); if (user == null) { ViewData["result"] = "用户名或密码错误"; return(View()); } Session[CacheKeys.WebUserCacheKey] = user; DistributedCache.Set(string.Format(CacheKeys.UserSessionKey_Arg1, accesskey), user, DateTime.Now.AddHours(8)); HttpCookie cookie = new HttpCookie("accesskey", accesskey); cookie.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(cookie); return(RedirectToAction("Index", "Home")); }
public async Task Remove(int id) { try { var payMethods = await LoadFromRedis(); var payMethod = payMethods.FirstOrDefault(c => c.Id == id); if (payMethod != null) { payMethods.Remove(payMethod); await DistributedCache.Set(_cacheKey, payMethods); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task Remove(int id) { try { var invoiceStatuses = await LoadFromRedis(); var invoiceStatus = invoiceStatuses.FirstOrDefault(c => c.Id == id); if (invoiceStatus != null) { invoiceStatuses.Remove(invoiceStatus); await DistributedCache.Set(_cacheKey, invoiceStatuses); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task Remove(int id) { try { var crmUsers = await LoadFromRedis(); var crmUser = crmUsers.FirstOrDefault(c => c.Id == id); if (crmUser != null) { crmUsers.Remove(crmUser); await DistributedCache.Set(_cacheKey, crmUsers); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task Remove(int id) { try { var appConfigs = await LoadFromRedis(); var appConfig = appConfigs.FirstOrDefault(c => c.Id == id); if (appConfig != null) { appConfigs.Remove(appConfig); await DistributedCache.Set(_cacheKey, appConfigs); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task Remove(int id) { try { var branches = await LoadFromRedis(); var branch = branches.FirstOrDefault(c => c.Id == id); if (branch != null) { branches.Remove(branch); await DistributedCache.Set(_cacheKey, branches); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task Remove(int id) { try { var taskPriorities = await LoadFromRedis(); var taskPriority = taskPriorities.FirstOrDefault(c => c.Id == id); if (taskPriority != null) { taskPriorities.Remove(taskPriority); await DistributedCache.Set(_cacheKey, taskPriorities); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task Remove(int id) { try { var customerSources = await LoadFromRedis(); var customerSource = customerSources.FirstOrDefault(c => c.Id == id); if (customerSource != null) { customerSources.Remove(customerSource); await DistributedCache.Set(_cacheKey, customerSources); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
protected void Initialize() { EngineContext.Initialize(false); //set dependency resolver var dependencyResolver = new GrouponDependencyResolver(); DependencyResolver.SetResolver(dependencyResolver); // initialize cache //普通缓存(可以是EntLib、Memcached Or Redis) Cache.InitializeWith(new CacheProviderFactory(ConfigurationManager.AppSettings["CacheProvider"])); //分布式缓存(Memcached Or Redis) DistributedCache.InitializeWith(new CacheProviderFactory(ConfigurationManager.AppSettings["DistributedCacheProvider"])); Config.SetSystemCode("S012"); var typeAdapterFactory = EngineContext.Current.Resolve <ITypeAdapterFactory>(); TypeAdapterFactory.SetCurrent(typeAdapterFactory); }
public async Task Remove(int id) { try { var receiptDescriptions = await LoadFromRedis(); var receiptDescription = receiptDescriptions.FirstOrDefault(c => c.Id == id); if (receiptDescription != null) { receiptDescriptions.Remove(receiptDescription); await DistributedCache.Set(_cacheKey, receiptDescriptions); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task Remove(int id) { try { var productGroups = await LoadFromRedis(); var productGroup = productGroups.FirstOrDefault(c => c.Id == id); if (productGroup != null) { productGroups.Remove(productGroup); await DistributedCache.Set(_cacheKey, productGroups); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task Remove(int id) { try { var districts = await LoadFromRedis(); var district = districts.FirstOrDefault(c => c.Id == id); if (district != null) { districts.Remove(district); await DistributedCache.Set(_cacheKey, districts); } } catch (Exception exception) { _logger.Info(exception.ToString); } }
public async Task <IActionResult> SearchStudentByName(string Query) { Request.Headers.TryGetValue("Authorization", out var token); string role = await AuthHelper.GetRoleFromTokenAsync(token); if (role != "admin") { return(StatusCode(401, new { Error = "Unauthorized" })); } IEnumerable <StudentDTO> data = new List <StudentDTO>(); string cachedDataString = string.Empty; cachedDataString = await DistributedCache.GetStringAsync("_students_search_" + Query); if (!string.IsNullOrEmpty(cachedDataString)) { // loaded data from the redis cache. data = JsonSerializer.Deserialize <IEnumerable <StudentDTO> >(cachedDataString); return(Ok(new BaseResponse <IEnumerable <StudentDTO> >(data, true))); // IsCached = true } else { var baseResponse = await Mediator.Send(new GetStudentByNameQuery { Query = Query }); // loading from code (in real-time from database) // then saving to the redis cache data = baseResponse.Data; cachedDataString = JsonSerializer.Serialize <IEnumerable <StudentDTO> >(baseResponse.Data); var expiryOptions = new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(600), SlidingExpiration = TimeSpan.FromSeconds(300) }; await DistributedCache.SetStringAsync("_students_search_" + Query, cachedDataString); return(Ok(baseResponse)); // IsCached = false } }
/// <exception cref="System.Exception"/> public virtual void TestSetupDistributedCache() { Configuration conf = new Configuration(); conf.SetClass("fs.mockfs.impl", typeof(TestMRApps.MockFileSystem), typeof(FileSystem )); URI mockUri = URI.Create("mockfs://mock/"); FileSystem mockFs = ((FilterFileSystem)FileSystem.Get(mockUri, conf)).GetRawFileSystem (); URI archive = new URI("mockfs://mock/tmp/something.zip"); Path archivePath = new Path(archive); URI file = new URI("mockfs://mock/tmp/something.txt#something"); Path filePath = new Path(file); Org.Mockito.Mockito.When(mockFs.ResolvePath(archivePath)).ThenReturn(archivePath); Org.Mockito.Mockito.When(mockFs.ResolvePath(filePath)).ThenReturn(filePath); DistributedCache.AddCacheArchive(archive, conf); conf.Set(MRJobConfig.CacheArchivesTimestamps, "10"); conf.Set(MRJobConfig.CacheArchivesSizes, "10"); conf.Set(MRJobConfig.CacheArchivesVisibilities, "true"); DistributedCache.AddCacheFile(file, conf); conf.Set(MRJobConfig.CacheFileTimestamps, "11"); conf.Set(MRJobConfig.CacheFilesSizes, "11"); conf.Set(MRJobConfig.CacheFileVisibilities, "true"); IDictionary <string, LocalResource> localResources = new Dictionary <string, LocalResource >(); MRApps.SetupDistributedCache(conf, localResources); NUnit.Framework.Assert.AreEqual(2, localResources.Count); LocalResource lr = localResources["something.zip"]; NUnit.Framework.Assert.IsNotNull(lr); NUnit.Framework.Assert.AreEqual(10l, lr.GetSize()); NUnit.Framework.Assert.AreEqual(10l, lr.GetTimestamp()); NUnit.Framework.Assert.AreEqual(LocalResourceType.Archive, lr.GetType()); lr = localResources["something"]; NUnit.Framework.Assert.IsNotNull(lr); NUnit.Framework.Assert.AreEqual(11l, lr.GetSize()); NUnit.Framework.Assert.AreEqual(11l, lr.GetTimestamp()); NUnit.Framework.Assert.AreEqual(LocalResourceType.File, lr.GetType()); }
public async Task <IActionResult> Get(int PageNumber, int PageSize) { Request.Headers.TryGetValue("Authorization", out var token); string role = await AuthHelper.GetRoleFromTokenAsync(token); if (role != "admin") { return(StatusCode(401, new { Error = "Invalid token." })); } var validFilter = new PaginationFilter(PageNumber, PageSize); IEnumerable <BookingDTO> data = new List <BookingDTO>(); string cachedDataString = string.Empty; cachedDataString = await DistributedCache.GetStringAsync("_bookings_" + validFilter.PageNumber); if (!string.IsNullOrEmpty(cachedDataString)) { // loaded data from the redis cache. data = JsonSerializer.Deserialize <IEnumerable <BookingDTO> >(cachedDataString); return(Ok(new BaseResponse <IEnumerable <BookingDTO> >(data, true))); // IsCached = true } else { BaseResponse <IEnumerable <BookingDTO> > baseResponse = await Mediator.Send(new GetBookingQuery { PageNumber = validFilter.PageNumber, PageSize = validFilter.PageSize }); // loading from code (in real-time from database) // then saving to the redis cache data = baseResponse.Data; cachedDataString = JsonSerializer.Serialize <IEnumerable <BookingDTO> >(baseResponse.Data); var expiryOptions = new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(600), SlidingExpiration = TimeSpan.FromSeconds(300) }; await DistributedCache.SetStringAsync("_bookings_" + validFilter.PageNumber, cachedDataString); return(Ok(baseResponse)); // IsCached = false } }
public async Task GetAsync_ReturnsBoolCachedValue() { // Arrange var key = Guid.NewGuid().ToString(); const bool cachedValue = true; var cache = new FakeDistributedCache(new MemoryCache(new MemoryCacheOptions())); cache.SetString(key, JsonConvert.SerializeObject(cachedValue)); var logger = Substitute.For <ILogger <DistributedCache> >(); var sut = new DistributedCache(cache, logger); // Act var result = await sut.GetAsync <bool>(key); // Assert Assert.AreEqual(cachedValue, result); }
public async Task AddOrUpdate(CustomerCacheModel model) { try { var customers = await LoadFromRedis(); var customer = customers.FirstOrDefault(c => c.Id == model.Id); if (customer == null) { customers.Add(model); } else { //customer.Code = model.Code; customer.Name = model.Name; customer.Phone = model.Phone; customer.Phone2 = model.Phone2; customer.Phone3 = model.Phone3; customer.Email = model.Email; customer.Address = model.Address; customer.ProvinceId = model.ProvinceId; customer.DistrictId = model.DistrictId; customer.WardId = model.WardId; customer.CustomerGroupId = model.CustomerGroupId; //customer.CustomerVipId = model.CustomerVipId; //customer.Profit = model.Profit; customer.ProfitUpdate = model.ProfitUpdate; customer.Description = model.Description; customer.UserUpdated = model.UserUpdated; customer.DateUpdated = model.DateUpdated; } await DistributedCache.Set(_cacheKey, customers); } catch (Exception exception) { _logger.Info(exception.ToString); } }
/// <exception cref="System.IO.IOException"/> private static void AddMRFrameworkToDistributedCache(Configuration conf) { string framework = conf.Get(MRJobConfig.MapreduceApplicationFrameworkPath, string.Empty ); if (!framework.IsEmpty()) { URI uri; try { uri = new URI(framework); } catch (URISyntaxException e) { throw new ArgumentException("Unable to parse '" + framework + "' as a URI, check the setting for " + MRJobConfig.MapreduceApplicationFrameworkPath, e); } string linkedName = uri.GetFragment(); // resolve any symlinks in the URI path so using a "current" symlink // to point to a specific version shows the specific version // in the distributed cache configuration FileSystem fs = FileSystem.Get(conf); Path frameworkPath = fs.MakeQualified(new Path(uri.GetScheme(), uri.GetAuthority( ), uri.GetPath())); FileContext fc = FileContext.GetFileContext(frameworkPath.ToUri(), conf); frameworkPath = fc.ResolvePath(frameworkPath); uri = frameworkPath.ToUri(); try { uri = new URI(uri.GetScheme(), uri.GetAuthority(), uri.GetPath(), null, linkedName ); } catch (URISyntaxException e) { throw new ArgumentException(e); } DistributedCache.AddCacheArchive(uri, conf); } }
public async Task CacheResponseAsync(string cacheKey, object response, TimeSpan timeToLive) { if (cacheKey == null) { return; } if (response == null) { return; } var serializedResponse = JsonConvert.SerializeObject(response); await DistributedCache.SetStringAsync( cacheKey, serializedResponse, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = timeToLive }); }
public async Task RemoveAsync( string key, CancellationToken cancellationToken = default(CancellationToken)) { lock (await GetOrCreateLockAsync( key, null, cancellationToken)) { DistributedCache.Remove(key); MemoryCache.Remove( $"{KeyPrefix}{key}"); Subscriber.Publish( Channel, JsonSerializer.Serialize( new CacheMessage { Key = key, PublisherId = PublisherId, }, JsonSerializerOptions)); MemoryCache.Remove($"{LockKeyPrefix}{key}"); } }
public void Set( string key, byte[] value, DistributedCacheEntryOptions distributedCacheEntryOptions) { lock (GetOrCreateLock(key, distributedCacheEntryOptions)) { DistributedCache.Set( key, value, distributedCacheEntryOptions); SetMemoryCache( key, value, distributedCacheEntryOptions); Subscriber.Publish( Channel, JsonSerializer.Serialize( new CacheMessage { Key = key, PublisherId = PublisherId, }, JsonSerializerOptions)); } }
public void GetIfCached_ReturnsCachedValue() { // Arrange var key = Guid.NewGuid().ToString(); var cachedValue = new AClass(); var cache = new FakeDistributedCache(new MemoryCache(new MemoryCacheOptions())); cache.SetString(key, JsonConvert.SerializeObject(cachedValue)); var logger = Substitute.For <ILogger <DistributedCache> >(); var sut = new DistributedCache(cache, logger); // Act var wasCached = sut.GetIfCached <AClass>(key, out var result); // Assert Assert.True(wasCached); Assert.AreEqual(cachedValue.Value, result.Value); }
public async Task GetIfCachedAsync_ReturnsCachedValue() { // Arrange var key = Guid.NewGuid().ToString(); var cachedValue = new AClass(); var cache = new FakeDistributedCache(new MemoryCache(new MemoryCacheOptions())); cache.SetString(key, JsonConvert.SerializeObject(cachedValue)); var logger = Substitute.For <ILogger <DistributedCache> >(); var sut = new DistributedCache(cache, logger); // Act var result = await sut.GetIfCachedAsync <AClass>(key); // Assert Assert.True(result.wasInCache); Assert.AreEqual(cachedValue.Value, result.value.Value); }
public async Task SearchByClient() { await StartServer(); var client = await GetClient(); var baseDir = AppDomain.CurrentDomain.BaseDirectory; if (baseDir == null) { throw new NullReferenceException("baseDirectory of test app is null"); } var sampleFilePath = Path.Combine(baseDir, "sampleResponse.txt"); string resultHtml = File.ReadAllText(sampleFilePath); DistributedCache.Setup(ca => ca.GetAsync("777x", It.IsAny <CancellationToken>())) .Returns <string, CancellationToken>((key, token) => { var bytes = Encoding.UTF8.GetBytes(resultHtml); return(Task.FromResult(bytes)); }); var response = await client.GetAsync("/v1/AirTeam/Search?keyword=777x"); var jsonResult = await response.Content.ReadAsStringAsync(); Assert.IsTrue(response.IsSuccessStatusCode); var jArray = JArray.Parse(jsonResult); Assert.AreEqual(25, jArray.Count); var firstItem = jArray[0].ToObject <ImageDto>(); Assert.AreEqual("353153", firstItem.ImageId); Assert.AreEqual("Boeing 777-9X", firstItem.Title); StringAssert.EndsWith(firstItem.BaseImageUrl, "pics/353/353153_200.jpg"); }
/// <summary> /// 创建任务 /// </summary> /// <param name="taskMessage"></param> /// <returns></returns> public bool CreateTask(TaskMessage taskMessage) { lock (_lockObj) { long batchNumber = DateTime.Now.Ticks; DateTime currentTime = DateTime.Now; _servers = GetAllServers(); foreach (var item in _servers) { TaskMessage task = new TaskMessage(); task.BatchNumber = batchNumber; task.TaskID = Guid.NewGuid().ToString(); task.TaskExecutor = item; task.TaskType = taskMessage.TaskType; task.TaskParam = taskMessage.TaskParam; task.Status = TaskMessageStatusEnum.None; task.CreateTime = currentTime; _taskList.Add(task); } DistributedCache.Set(CacheKeys.InstuctionTaskListCacheKey, _taskList, DateTime.Now.AddYears(1)); } return(true); }
public void Should_return_user_exception_for_other_responses() { var expectedGroup = new Group { Id = _groupId, DisplayName = JudgeGroupName }; DistributedCache.Setup(x => x.GetOrAddAsync(It.IsAny <string>(), It.IsAny <Func <Task <Group> > >())).ReturnsAsync(expectedGroup); _graphQueryResponse.Value.Add(_group); SecureHttpRequest.Setup(x => x.GetAsync(It.IsAny <string>(), _judgesGroup)) .ReturnsAsync(ApiRequestHelper.CreateHttpResponseMessage(_graphQueryResponse, HttpStatusCode.OK)); const string reason = "User not authorised"; SecureHttpRequest.Setup(x => x.GetAsync(It.IsAny <string>(), _accessUri)) .ReturnsAsync(ApiRequestHelper.CreateHttpResponseMessage(reason, HttpStatusCode.Unauthorized)); var response = Assert.ThrowsAsync <UserServiceException>(async() => await Service.GetJudgesAsync()); response.Should().NotBeNull(); response.Message.Should().Be($"Failed to get users for group {_groupId}: {reason}"); response.Reason.Should().Be(reason); }
private void Initialize() { EngineContext.Initialize(false); //set dependency resolver var dependencyResolver = new MVCDependencyResolver(); DependencyResolver.SetResolver(dependencyResolver); // initialize cache Cache.InitializeWith(new CacheProviderFactory(ConfigurationManager.AppSettings["CacheProvider"])); //分布式缓存(Memcached Or Redis) DistributedCache.InitializeWith(new CacheProviderFactory(ConfigurationManager.AppSettings["DistributedCacheProvider"])); Config.SetSystemCode("S012"); ////initialize AutoMapper //Mapper.Initialize(x => x.AddProfile<AutoMapperProfile>()); var typeAdapterFactory = EngineContext.Current.Resolve <ITypeAdapterFactory>(); TypeAdapterFactory.SetCurrent(typeAdapterFactory); //ConfigureFluentValidation(); }