public virtual async Task SaveEntitySettingsValuesAsync(IHaveSettings entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } if (string.IsNullOrEmpty(entity.Id)) { throw new ArgumentException("entity must have Id"); } var haveSettingsObjects = entity.GetFlatObjectsListWithInterface <IHaveSettings>(); foreach (var haveSettingsObject in haveSettingsObjects) { var settings = new List <SettingEntry>(); if (haveSettingsObject.Settings != null) { //Save settings foreach (var setting in haveSettingsObject.Settings) { setting.ObjectId = haveSettingsObject.Id; setting.ObjectType = haveSettingsObject.TypeName; settings.Add(setting); } } await SaveSettingsAsync(settings.ToArray()); } }
public virtual async Task LoadEntitySettingsValuesAsync(IHaveSettings entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } if (string.IsNullOrEmpty(entity.Id)) { throw new ArgumentException("entity must have Id"); } //Deep load settings values for all object contains settings var haveSettingsObjects = entity.GetFlatObjectsListWithInterface <IHaveSettings>(); foreach (var haveSettingsObject in haveSettingsObjects) { var cacheKey = CacheKey.With(GetType(), "LoadEntitySettingsValues", entity.TypeName, entity.Id); var storedSettings = await _memoryCache.GetOrCreateExclusiveAsync(cacheKey, async (cacheEntry) => { var settingEntries = new List <SettingEntry>(); using (var repository = _repositoryFactory()) { foreach (var settingEntry in (await repository.GetAllObjectSettingsAsync(entity.TypeName, entity.Id)).Select(x => x.ToModel(AbstractTypeFactory <SettingEntry> .TryCreateInstance()))) { //Add cache expiration token for setting cacheEntry.AddExpirationToken(SettingsCacheRegion.CreateChangeToken(settingEntry)); settingEntries.Add(settingEntry); } return(settingEntries); } }); // Replace settings values with stored in database if (haveSettingsObject.Settings != null) { //Need clone settings entry because it may be shared for multiple instances haveSettingsObject.Settings = haveSettingsObject.Settings.Select(x => (SettingEntry)x.Clone()).ToList(); foreach (var setting in haveSettingsObject.Settings) { var storedSetting = storedSettings.Find(x => x == setting); //First try to used stored object setting values if (storedSetting != null) { setting.Value = storedSetting.Value; setting.ArrayValues = storedSetting.ArrayValues; } else if (setting.Value == null && setting.ArrayValues == null) { //try to use global setting value var globalSetting = await GetSettingByNameAsync(setting.Name); var defaultValue = (globalSetting ?? setting).DefaultValue; if (setting.IsArray) { setting.ArrayValues = globalSetting?.ArrayValues ?? new[] { defaultValue }; } else { setting.Value = globalSetting?.Value ?? defaultValue; } } } } } }