public async Task GetOrAddAsyncWithCallbackOnRemovedReturnsTheOriginalCachedObjectEvenIfNotGettedBeforehand() { Func <Task <int> > fetch = () => Task.FromResult(123); CacheEntryRemovedArguments removedCallbackArgs = null; CacheEntryRemovedCallback callback = args => removedCallbackArgs = args; await sut.GetOrAddAsync(TestKey, fetch, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(100), RemovedCallback = callback }); sut.Remove(TestKey); //force removed callback to fire while (removedCallbackArgs == null) { Thread.Sleep(500); } var callbackResult = removedCallbackArgs.CacheItem.Value; Assert.That(callbackResult, Is.AssignableTo <Task <int> >()); var callbackResultValue = await(Task <int>) removedCallbackArgs.CacheItem.Value; Assert.AreEqual(123, callbackResultValue); }
public JsonNetResult GetActiveFranchises() { List <FranchiseSelectViewModel> _listFranchises = new List <FranchiseSelectViewModel>(); IAppCache cache = new CachingService(); _listFranchises = cache.GetOrAdd("Active_Franchises", () => GetActiveFranchisesPrivate(), new TimeSpan(8, 0, 0)); if (_listFranchises == null || _listFranchises.Count == 0) { LogHelper log = new LogHelper(); log.Log(LogHelper.LogLevels.Warning, "Error loading active franchises - Franchise cache will be reset and attempted again", nameof(GetActiveFranchises)); cache.Remove("Active_Franchises"); _listFranchises = cache.GetOrAdd("Active_Franchises", () => GetActiveFranchisesPrivate(), new TimeSpan(8, 0, 0)); } if (_listFranchises == null || _listFranchises.Count == 0) { throw new ApplicationException($"Active franchise list could not be loaded."); } return(new JsonNetResult() { Data = new { list = _listFranchises }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public ActionResult Logout() { _cachingService.Remove(UserContext.User.Id.ToString()); SessionContainer.ClearUserContext(this.HttpContext); return(RedirectToAction("Login")); }
public void RemovedItemCannotBeRetrievedFromCache() { var sut = new CachingService(); sut.Add(TestKey, new object()); Assert.NotNull(sut.Get <object>(TestKey)); sut.Remove(TestKey); Assert.Null(sut.Get <object>(TestKey)); }
public void DeleteFromCache(string contextUsername) { IAppCache appCache = new CachingService(); KerberosReceiverSecurityToken token = appCache.Get <KerberosReceiverSecurityToken>(contextUsername.ToLower()); if (token != null) { appCache.Remove(contextUsername.ToLower()); } }
/// <summary> /// Removes a configuration from cache /// </summary> /// <typeparam name="T">The configuration type</typeparam> /// <typeparam name="Tm">The configuration metadata type</typeparam> /// <param name="configurationMetadata">The metadata related to the configuration, default gathered from Type Data</param> protected internal virtual void ClearConfiguration <T, Tm>(Tm configurationMetadata = default(Tm)) where T : IConfiguration <T, Tm>, new() where Tm : IConfigurationMetadata <T, Tm>, new() { Tm metadata = GetMetadataForConfiguration <T, Tm>(configurationMetadata); if (CachingService.ContainsKey(metadata.ConfigurationName)) { CachingService.Remove(metadata.ConfigurationName); } }
//https://codeshare.co.uk/blog/how-to-show-utc-time-relative-to-the-users-local-time-on-a-net-website/ private static IEnumerable <String> GetTimeZonesByCountry() { String countryCode = UserCountryCode(); IAppCache cache = new CachingService(); IEnumerable <String> zoneIds = cache.GetOrAdd($"dateTimeZoneList-{countryCode}", () => GetTimeZonesByCountryPrivate(countryCode), new TimeSpan(0, 30, 0)); if (zoneIds == null || zoneIds.Count() == 0) { cache.Remove($"dateTimeZoneList-{countryCode}"); return(new List <String>()); } return(zoneIds.ToList()); }
public ComplexObject Init_CRUD() { var cache = new CachingService(new MemoryCacheProvider(new MemoryCache(new MemoryCacheOptions()))) as IAppCache; cache.Add(CacheKey, ComplexObject1); var obj = cache.Get <ComplexObject>(CacheKey); obj.Int = 256; cache.Add(CacheKey, obj); cache.Remove(CacheKey); return(obj); }
public void GetOrAddWithCallbackOnRemovedReturnsTheOriginalCachedObjectEvenIfNotGettedBeforehand() { var sut = new CachingService(); Func <int> fetch = () => 123; CacheEntryRemovedArguments removedCallbackArgs = null; CacheEntryRemovedCallback callback = (args) => removedCallbackArgs = args; sut.GetOrAdd(TestKey, fetch, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(100), RemovedCallback = callback }); sut.Remove(TestKey); //force removed callback to fire while (removedCallbackArgs == null) { Thread.Sleep(500); } Assert.AreEqual(123, removedCallbackArgs.CacheItem.Value); }
public ActionResult Logout() { if (UserContext != null) { _cachingService.Remove(UserContext.Token); } return(SuccessfulResult()); //MemberLoginArgs args = RequestArgs<MemberLoginArgs>(); //if (args == null) //{ // return FailedResult("参数无效。"); //} ////根据用户名注销用户 //bool flag = _cachingService.Remove(UserContext.Token); //return ApiResult(flag, flag ? "注销成功" : "注销失败"); }
/// <summary> /// Returns list of zones for a given suburb /// </summary> /// <returns>The zone list by suburb.</returns> /// <param name="suburbName">Suburb name.</param> public static List <string> GetZoneListBySuburb(this string suburbName, Boolean withDefaults) { if (String.IsNullOrWhiteSpace(suburbName)) { return(new List <string>()); } IAppCache cache = new CachingService(); List <string> zoneList = cache.GetOrAdd($"SuburbZones_{suburbName}", () => GetZoneList(suburbName), new TimeSpan(0, 20, 0)); if (zoneList.Count == 0) { cache.Remove($"SuburbZones_{suburbName}"); if (withDefaults) { zoneList = cache.GetOrAdd($"SuburbZones_Defaults", () => GetDefaultZoneList(), new TimeSpan(0, 20, 0)); } } return(zoneList); }
public void Remove(string key) { _cachingService.Remove(key); }
public ActionResult SaveFranchise(UpdateFranchisesViewModel dataItem) { //https://stackoverflow.com/questions/13541225/asp-net-mvc-how-to-display-success-confirmation-message-after-server-side-proce if (dataItem == null) { ModelState.AddModelError(string.Empty, "Valid franchise data not found."); } if (!dataItem.HasAnyValidAddress) { ModelState.AddModelError(string.Empty, "Please ensure at least a valid physical address is supplied."); } else { if (dataItem.PhysicalAddress != null && (dataItem.PhysicalAddress.IsPartialAddress || dataItem.HasValidPhysicalAddress)) { var _physValidator = new AddressValidator(); var results = _physValidator.Validate(dataItem.PhysicalAddress); results.AddToModelState(ModelState, ""); } } if (!dataItem.HasAnyPhoneNumbers) { ModelState.AddModelError(string.Empty, "Please provide at least one valid phone number."); } if (ModelState.IsValid) { String _id = dataItem.Id; var bIsNew = (dataItem.IsNewItem); //https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud //https://stackoverflow.com/questions/21286538/asp-net-mvc-5-model-binding-edit-view //https://www.mikesdotnetting.com/article/248/mvc-5-with-ef-6-in-visual-basic-updating-related-data try { Franchise _objToUpdate = null; using (DBManager db = new DBManager()) { if (bIsNew) { _objToUpdate = UpdateFranchise(null, dataItem); StringBuilder _sql = new StringBuilder(); if (_objToUpdate.PhysicalAddress != null) { _sql.Append("Insert into Addresses (Id, CreatedAt, UpdatedAt, UpdatedBy, IsActive, RowVersion, "); _sql.Append("AddressType, AddressLine1, AddressLine2, AddressLine3, Suburb, State, PostCode, Country)"); _sql.Append(" values ("); _sql.Append($"'{_objToUpdate.PhysicalAddress.Id}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.CreatedAt.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.UpdatedAt.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.UpdatedBy}',"); _sql.Append($"{_objToUpdate.PhysicalAddress.IsActive},"); _sql.Append($"'{_objToUpdate.PhysicalAddress.RowVersion.FormatDatabaseDateTime()}',"); _sql.Append($"{(int)_objToUpdate.PhysicalAddress.AddressType},"); _sql.Append($"'{_objToUpdate.PhysicalAddress.AddressLine1}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.AddressLine2}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.AddressLine3}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.Suburb}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.State}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.PostCode}',"); _sql.Append($"'{_objToUpdate.PhysicalAddress.Country}'"); _sql.Append(")"); db.getConnection().Execute(_sql.ToString()); } _sql.Clear(); _sql.Append("Insert into Franchises (Id, CreatedAt, UpdatedAt, UpdatedBy, IsActive, RowVersion, "); _sql.Append("Name, TradingName, MasterFranchiseCode, EmailAddress, PhysicalAddressRefId, "); _sql.Append("BusinessPhoneNumber, MobileNumber, OtherNumber, CodeOfConductURL, ManagementFeePercentage, RoyaltyFeePercentage, MetroRegion)"); _sql.Append(" values ("); _sql.Append($"'{_objToUpdate.Id}',"); _sql.Append($"'{_objToUpdate.CreatedAt.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.UpdatedAt.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.UpdatedBy}',"); _sql.Append($"{_objToUpdate.IsActive},"); _sql.Append($"'{_objToUpdate.RowVersion.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.Name}',"); _sql.Append($"'{_objToUpdate.TradingName}',"); _sql.Append($"'{_objToUpdate.MasterFranchiseCode}',"); _sql.Append($"'{_objToUpdate.EmailAddress}',"); _sql.Append($"'{_objToUpdate.PhysicalAddressRefId}',"); _sql.Append($"'{_objToUpdate.BusinessPhoneNumber}',"); _sql.Append($"'{_objToUpdate.MobileNumber}',"); _sql.Append($"'{_objToUpdate.OtherNumber}',"); _sql.Append($"'{_objToUpdate.CodeOfConductURL}',"); if (_objToUpdate.ManagementFeePercentage == null) { _sql.Append($"null,"); } else { _sql.Append($"{_objToUpdate.ManagementFeePercentage},"); } if (_objToUpdate.RoyaltyFeePercentage == null) { _sql.Append($"null,"); } else { _sql.Append($"{_objToUpdate.RoyaltyFeePercentage},"); } _sql.Append($"'{_objToUpdate.MetroRegion}'"); _sql.Append(")"); db.getConnection().Execute(_sql.ToString()); //var newId = db.Insert<Franchise>(UpdateAuditTracking(_objToUpdate)); } else { string sql = @"select * from Franchises C inner join Addresses Ph on C.PhysicalAddressRefId = Ph.ID where C.ID = '" + _id + "'"; _objToUpdate = db.getConnection().Query <Franchise, Address, Franchise>(sql, (clnt, phys) => { clnt.PhysicalAddress = phys; return(clnt); }).SingleOrDefault(); if (_objToUpdate == null) { ModelState.AddModelError(string.Empty, $"Franchise [{_id.ToString()}] not found. Please try again."); return(JsonFormResponse()); } StringBuilder _sql = new StringBuilder(); _objToUpdate = UpdateFranchise(_objToUpdate, dataItem); _sql.Append("Update Franchises set "); _sql.Append($"UpdatedAt = '{_objToUpdate.UpdatedAt.FormatDatabaseDateTime()}'"); _sql.Append($",RowVersion = '{_objToUpdate.RowVersion.FormatDatabaseDateTime()}'"); _sql.Append($",UpdatedBy = '{_objToUpdate.UpdatedBy}'"); _sql.Append($",IsActive = {_objToUpdate.IsActive}"); _sql.Append($",Name = '{_objToUpdate.Name}'"); _sql.Append($",TradingName = '{_objToUpdate.TradingName}'"); _sql.Append($",MasterFranchiseCode = '{_objToUpdate.MasterFranchiseCode}'"); _sql.Append($",EmailAddress = '{_objToUpdate.EmailAddress}'"); _sql.Append($",BusinessPhoneNumber = '{_objToUpdate.BusinessPhoneNumber}'"); _sql.Append($",MobileNumber = '{_objToUpdate.MobileNumber}'"); _sql.Append($",OtherNumber = '{_objToUpdate.OtherNumber}'"); _sql.Append($",CodeOfConductURL = '{_objToUpdate.CodeOfConductURL}'"); if (_objToUpdate.ManagementFeePercentage != null) { _sql.Append($",ManagementFeePercentage = {_objToUpdate.ManagementFeePercentage}"); } if (_objToUpdate.RoyaltyFeePercentage != null) { _sql.Append($",RoyaltyFeePercentage = {_objToUpdate.RoyaltyFeePercentage}"); } _sql.Append($",MetroRegion = '{_objToUpdate.MetroRegion}'"); _sql.Append($" where Id = '{_objToUpdate.Id}'"); db.getConnection().Execute(_sql.ToString()); _sql.Clear(); _sql.Append("Update Addresses set "); _sql.Append($"UpdatedAt = '{_objToUpdate.UpdatedAt.FormatDatabaseDateTime()}'"); _sql.Append($",RowVersion = '{_objToUpdate.RowVersion.FormatDatabaseDateTime()}'"); _sql.Append($",UpdatedBy = '{_objToUpdate.UpdatedBy}'"); _sql.Append($",IsActive = {_objToUpdate.IsActive}"); _sql.Append($",AddressLine1 = '{_objToUpdate.PhysicalAddress.AddressLine1}'"); _sql.Append($",AddressLine2 = '{_objToUpdate.PhysicalAddress.AddressLine2}'"); _sql.Append($",AddressLine3 = '{_objToUpdate.PhysicalAddress.AddressLine3}'"); _sql.Append($",Suburb = '{_objToUpdate.PhysicalAddress.Suburb}'"); _sql.Append($",State = '{_objToUpdate.PhysicalAddress.State}'"); _sql.Append($",PostCode = '{_objToUpdate.PhysicalAddress.PostCode}'"); _sql.Append($",Country = '{_objToUpdate.PhysicalAddress.Country}'"); _sql.Append($" where Id = '{_objToUpdate.PhysicalAddress.Id}' "); db.getConnection().Execute(_sql.ToString()); } IAppCache cache = new CachingService(); cache.Remove("Active_Franchises"); return(JsonSuccessResponse("Franchise saved successfully", _objToUpdate)); } } //catch (DbUpdateConcurrencyException ex) //{ // var entry = ex.Entries.Single(); // var clientValues = (Franchise)entry.Entity; // var databaseEntry = entry.GetDatabaseValues(); // if (databaseEntry == null) // { // ModelState.AddModelError(string.Empty, "Unable to save changes. The franchise was deleted by another user."); // } // else // { // var databaseValues = (Franchise)databaseEntry.ToObject(); // if (databaseValues.Name != clientValues.Name) // ModelState.AddModelError("Name", "Current database value for franchise name: " + databaseValues.Name); // if (databaseValues.TradingName != clientValues.TradingName) // ModelState.AddModelError("TradingName", "Current database value for trading name: " + databaseValues.TradingName); // ModelState.AddModelError(string.Empty, "The record you attempted to edit " // + "was modified by another user after you got the original value. The edit operation " // + "was canceled. If you still want to edit this record, click the Save button again."); // } //} catch (Exception ex) { ModelState.AddModelError(string.Empty, Helpers.FormatModelError("Error saving franchise", ex)); LogHelper log = new LogHelper(); log.Log(LogHelper.LogLevels.Error, "Error saving franchise", nameof(SaveFranchise), ex, dataItem, Helpers.ParseValidationErrors(ex)); } } if (!ModelState.IsValid) { Helpers.LogFormValidationErrors(ModelState, nameof(SaveFranchise), dataItem); } return(JsonFormResponse()); }
public ActionResult SaveSettings(UpdateSettingsViewModel setting) { //https://stackoverflow.com/questions/13541225/asp-net-mvc-how-to-display-success-confirmation-message-after-server-side-proce if (setting == null) { ModelState.AddModelError(string.Empty, "Valid setting not found."); } if (ModelState.IsValid) { String _id = setting.Id; using (DBManager db = new DBManager()) { StringBuilder _sql = new StringBuilder(); _sql.Append($"Select * from SystemSettings where Id = '{_id}'"); SystemSetting _objToUpdate = db.getConnection().Query <SystemSetting>(_sql.ToString()).SingleOrDefault(); if (_objToUpdate == null) { ModelState.AddModelError(string.Empty, $"Setting [{_id.ToString()}] not found. Please try again."); return(JsonFormResponse()); } if (TryUpdateModel <SystemSetting>(_objToUpdate)) { try { _objToUpdate = UpdateAuditTracking(_objToUpdate); _sql.Clear(); _sql.Append("Update SystemSettings set "); _sql.Append($"UpdatedAt = '{_objToUpdate.UpdatedAt.FormatDatabaseDateTime()}'"); _sql.Append($",RowVersion = '{_objToUpdate.RowVersion.FormatDatabaseDateTime()}'"); _sql.Append($",UpdatedBy = '{_objToUpdate.UpdatedBy}'"); _sql.Append($",IsActive = {_objToUpdate.IsActive}"); _sql.Append($",SettingName = '{_objToUpdate.SettingName}'"); _sql.Append($",SettingValue = '{_objToUpdate.SettingValue}'"); _sql.Append($",CodeIdentifier = '{_objToUpdate.CodeIdentifier}'"); _sql.Append($" where Id = '{_objToUpdate.Id}'"); db.getConnection().Execute(_sql.ToString()); SystemSettings.Reset(); IAppCache cache = new CachingService(); cache.Remove("System_Settings_All"); cache.Remove("System_Settings_Active"); return(JsonSuccessResponse("Setting saved successfully", _objToUpdate)); } //catch (DbUpdateConcurrencyException ex) //{ // var entry = ex.Entries.Single(); // var clientValues = (SystemSetting)entry.Entity; // var databaseEntry = entry.GetDatabaseValues(); // if (databaseEntry == null) // { // ModelState.AddModelError(string.Empty, "Unable to save changes. The system setting was deleted by another user."); // } // else // { // var databaseValues = (SystemSetting)databaseEntry.ToObject(); // ModelState.AddModelError(string.Empty, "The record you attempted to edit " // + "was modified by another user after you got the original value. The " // + "edit operation was canceled and the current values in the database " // + "have been displayed. If you still want to edit this record, click " // + "the Save button again."); // if (databaseValues.SettingName != clientValues.SettingName) // ModelState.AddModelError("SettingName", "Current database value for setting name: " + databaseValues.SettingName); // if (databaseValues.SettingValue != clientValues.SettingValue) // ModelState.AddModelError("SettingValue", "Current database value for setting value: " + databaseValues.SettingValue); // if (databaseValues.CodeIdentifier != clientValues.CodeIdentifier) // ModelState.AddModelError("CodeIdentifier", "Current database value for code identifier: " + databaseValues.CodeIdentifier); // } //} catch (Exception ex) { ModelState.AddModelError(string.Empty, Helpers.FormatModelError("Error saving setting", ex)); LogHelper log = new LogHelper(); log.Log(LogHelper.LogLevels.Error, "Error saving setting", nameof(SaveSettings), ex, setting, Helpers.ParseValidationErrors(ex)); } } } } if (!ModelState.IsValid) { Helpers.LogFormValidationErrors(ModelState, nameof(SaveSettings), setting); } return(JsonFormResponse()); }
public ActionResult SavePostCodes(UpdateSuburbZonesVM formValues) { string _objDesc = "Suburb/zone"; if (formValues == null) { ModelState.AddModelError(string.Empty, $"Valid {_objDesc.ToLower()} data not found."); } if (ModelState.IsValid) { // validate for unique suburb / zone for //SuburbZoneValidator validator = new SuburbZoneValidator(formValues.OtherZones); //ValidationResult results = validator.Validate(formValues); //if (!results.IsValid) //{ // ModelState.AddModelError(string.Empty, results.Errors.FirstOrDefault().ErrorMessage); //} } if (ModelState.IsValid) { String _id = formValues.Id; var bIsNew = formValues.IsNewItem; try { SuburbZone _objToUpdate = null; using (DBManager db = new DBManager()) { if (bIsNew) { _objToUpdate = UpdateAuditTracking(UpdateSettings(null, formValues)); StringBuilder _sql = new StringBuilder(); _sql.Append("Insert into SuburbZones (Id, CreatedAt, UpdatedAt, UpdatedBy, IsActive,"); _sql.Append("RowVersion, SuburbName, PostCode, Zone, LinkedZones, FranchiseId)"); _sql.Append(" values ("); _sql.Append($"'{_objToUpdate.Id}',"); _sql.Append($"'{_objToUpdate.CreatedAt.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.UpdatedAt.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.UpdatedBy}',"); _sql.Append($"{_objToUpdate.IsActive},"); _sql.Append($"'{_objToUpdate.RowVersion.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.SuburbName}',"); _sql.Append($"'{_objToUpdate.PostCode}',"); _sql.Append($"'{_objToUpdate.Zone}',"); _sql.Append($"'{_objToUpdate.LinkedZones}',"); _sql.Append($"'{_objToUpdate.FranchiseId}'"); _sql.Append(")"); db.getConnection().Execute(_sql.ToString()); //https://github.com/ericdc1/Dapper.SimpleCRUD/blob/master/Dapper.SimpleCRUD/SimpleCRUD.cs#L320 //var _key = db.Insert<SuburbZone>(UpdateAuditTracking(_objToUpdate)); } else { StringBuilder _sql = new StringBuilder(); _sql.Append($"Select * from SuburbZones where Id = '{_id}'"); _objToUpdate = db.getConnection().Query <SuburbZone>(_sql.ToString()).SingleOrDefault(); if (_objToUpdate == null) { ModelState.AddModelError(string.Empty, $"{_objDesc} [{_id.ToString()}] not found. Please try again."); return(JsonFormResponse()); } _objToUpdate = UpdateAuditTracking(UpdateSettings(_objToUpdate, formValues)); _sql.Clear(); _sql.Append("Update SuburbZones set "); _sql.Append($"UpdatedAt = '{_objToUpdate.UpdatedAt.FormatDatabaseDateTime()}'"); _sql.Append($",RowVersion = '{_objToUpdate.RowVersion.FormatDatabaseDateTime()}'"); _sql.Append($",UpdatedBy = '{_objToUpdate.UpdatedBy}'"); _sql.Append($",IsActive = {_objToUpdate.IsActive}"); _sql.Append($",SuburbName = '{_objToUpdate.SuburbName}'"); _sql.Append($",PostCode = '{_objToUpdate.PostCode}'"); _sql.Append($",Zone = '{_objToUpdate.Zone}'"); _sql.Append($",LinkedZones = '{_objToUpdate.LinkedZones}'"); _sql.Append($",FranchiseId = '{_objToUpdate.FranchiseId}'"); _sql.Append($" where Id = '{_objToUpdate.Id}'"); db.getConnection().Execute(_sql.ToString()); } IAppCache cache = new CachingService(); var cacheName = "Postcodes"; if (Helpers.IsValidGuid(_objToUpdate.FranchiseId)) { cacheName += $"_{_objToUpdate.FranchiseId}"; } cache.Remove(cacheName); cache.Remove($"SuburbNames"); } return(JsonSuccessResponse($"{_objDesc} saved successfully", _objToUpdate)); } //catch (DbUpdateConcurrencyException ex) //{ // var entry = ex.Entries.Single(); // var clientValues = (SuburbZone)entry.Entity; // var databaseEntry = entry.GetDatabaseValues(); // if (databaseEntry == null) // { // ModelState.AddModelError(string.Empty, $"Unable to save changes. The {_objDesc.ToLower()} was deleted by another user."); // } // else // { // var databaseValues = (SuburbZone)databaseEntry.ToObject(); // if (databaseValues.SuburbName != clientValues.SuburbName) // { // ModelState.AddModelError("SuburbName", "Current database value for suburb name: " + databaseValues.SuburbName); // } // if (databaseValues.PostCode != clientValues.PostCode) // { // ModelState.AddModelError("PostCode", "Current database value for post code: " + databaseValues.PostCode); // } // ModelState.AddModelError(string.Empty, "The record you attempted to edit " // + "was modified by another user after you got the original value. The edit operation " // + "was canceled. If you still want to edit this record, click the Save button again."); // } //} catch (Exception ex) { ModelState.AddModelError(string.Empty, Helpers.FormatModelError($"Error saving {_objDesc.ToLower()}", ex)); LogHelper log = new LogHelper(); log.Log(LogHelper.LogLevels.Error, $"Error saving {_objDesc.ToLower()}", nameof(SavePostCodes), ex, formValues, Helpers.ParseValidationErrors(ex)); } } if (!ModelState.IsValid) { Helpers.LogFormValidationErrors(ModelState, nameof(SavePostCodes), formValues); } return(JsonFormResponse()); }
public void RemovedItemCannotBeRetrievedFromCache() { var sut = new CachingService(); sut.Add(TestKey, new object()); Assert.NotNull(sut.Get<object>(TestKey)); sut.Remove(TestKey); Assert.Null(sut.Get<object>(TestKey)); }
public ActionResult SaveRate(RateDetailsVM formValues) { string _objDesc = "Rate"; int _selection = 0; if (formValues == null) { ModelState.AddModelError(string.Empty, $"Valid {_objDesc.ToLower()} data not found."); } if (String.IsNullOrWhiteSpace(formValues.SelectedRatesJson)) { ModelState.AddModelError(string.Empty, $"Valid {_objDesc.ToLower()} selections not found."); } else { List <SelectedRateItem> _selectionList = JsonConvert.DeserializeObject <List <SelectedRateItem> >(formValues.SelectedRatesJson); foreach (SelectedRateItem _item in _selectionList) { _selection += _item.Id; } } if (ModelState.IsValid) { String _id = formValues.Id; var bIsNew = formValues.IsNewItem; try { Rate _objToUpdate = null; using (DBManager db = new DBManager()) { if (bIsNew) { _objToUpdate = UpdateRates(null, formValues, _selection); StringBuilder _sql = new StringBuilder(); _sql.Append("Insert into Rates (Id, CreatedAt, UpdatedAt, UpdatedBy, IsActive, RowVersion, "); _sql.Append("RateCode, RateAmount, RateApplications, FranchiseId)"); _sql.Append(" values ("); _sql.Append($"'{_objToUpdate.Id}',"); _sql.Append($"'{_objToUpdate.CreatedAt.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.UpdatedAt.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.UpdatedBy}',"); _sql.Append($"{_objToUpdate.IsActive},"); _sql.Append($"'{_objToUpdate.RowVersion.FormatDatabaseDateTime()}',"); _sql.Append($"'{_objToUpdate.RateCode}',"); _sql.Append($"{_objToUpdate.RateAmount},"); _sql.Append($"{(int)_objToUpdate.RateApplications},"); _sql.Append($"'{_objToUpdate.FranchiseId}'"); _sql.Append(")"); db.getConnection().Execute(_sql.ToString()); //var newId = db.Insert<Rate>(_objToUpdate); } else { StringBuilder _sql = new StringBuilder(); _sql.Append($"Select * from Rates where id = '{_id}'"); _objToUpdate = db.getConnection().Query <Rate>(_sql.ToString()).SingleOrDefault(); if (_objToUpdate == null) { ModelState.AddModelError(string.Empty, $"{_objDesc} [{_id.ToString()}] not found. Please try again."); return(JsonFormResponse()); } _objToUpdate = UpdateRates(_objToUpdate, formValues, _selection); _sql.Clear(); _sql.Append("Update Rates set "); _sql.Append($"UpdatedAt = '{_objToUpdate.UpdatedAt.FormatDatabaseDateTime()}'"); _sql.Append($",RowVersion = '{_objToUpdate.RowVersion.FormatDatabaseDateTime()}'"); _sql.Append($",UpdatedBy = '{_objToUpdate.UpdatedBy}'"); _sql.Append($",IsActive = {_objToUpdate.IsActive}"); _sql.Append($",RateCode = '{_objToUpdate.RateCode}'"); _sql.Append($",RateAmount = {_objToUpdate.RateAmount}"); _sql.Append($",RateApplications = '{(int)_objToUpdate.RateApplications}'"); _sql.Append($",FranchiseId = '{_objToUpdate.FranchiseId}'"); _sql.Append($" where Id = '{_objToUpdate.Id}'"); db.getConnection().Execute(_sql.ToString()); } IAppCache cache = new CachingService(); var cacheName = "Rates"; if (Helpers.IsValidGuid(_objToUpdate.FranchiseId)) { cacheName += $"_{_objToUpdate.FranchiseId.ToString()}"; } cache.Remove(cacheName); } return(JsonSuccessResponse($"{_objDesc} saved successfully", _objToUpdate)); } //catch (DbUpdateConcurrencyException ex) //{ // var entry = ex.Entries.Single(); // var clientValues = (Rate)entry.Entity; // var databaseEntry = entry.GetDatabaseValues(); // if (databaseEntry == null) // { // ModelState.AddModelError(string.Empty, $"Unable to save changes. The {_objDesc.ToLower()} was deleted by another user."); // } // else // { // var databaseValues = (Rate)databaseEntry.ToObject(); // if (databaseValues.RateCode != clientValues.RateCode) // { // ModelState.AddModelError("RateCode", "Current database value for rate code: " + databaseValues.RateCode); // } // if (databaseValues.RateAmount != clientValues.RateAmount) // { // ModelState.AddModelError("RateAmount", "Current database value for rate amount: " + databaseValues.RateAmount); // } // ModelState.AddModelError(string.Empty, "The record you attempted to edit " // + "was modified by another user after you got the original value. The edit operation " // + "was canceled. If you still want to edit this record, click the Save button again."); // } //} catch (Exception ex) { ModelState.AddModelError(string.Empty, Helpers.FormatModelError($"Error saving {_objDesc.ToLower()}", ex)); LogHelper log = new LogHelper(); log.Log(LogHelper.LogLevels.Error, $"Error saving {_objDesc.ToLower()}", nameof(Rate), ex, formValues, Helpers.ParseValidationErrors(ex)); } } if (!ModelState.IsValid) { Helpers.LogFormValidationErrors(ModelState, nameof(Rate), formValues); } return(JsonFormResponse()); }
public void Logout(string token) { _cachingService.Remove(token); }
public void GetOrAddWithPolicyWithCallbackOnRemovedReturnsTheOriginalCachedObject() { var sut = new CachingService(); Func<int> fetch = () => 123; CacheEntryRemovedArguments removedCallbackArgs = null; CacheEntryRemovedCallback callback = (args) => removedCallbackArgs = args; sut.GetOrAdd(TestKey, fetch, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(100), RemovedCallback = callback}); var actual = sut.Get<int>(TestKey); sut.Remove(TestKey); //force removed callback to fire while(removedCallbackArgs == null) Thread.Sleep(500); Assert.AreEqual(123, removedCallbackArgs.CacheItem.Value); }