public void Add <TValue>(bool saveAttribute, bool saveGet, bool saveSet, bool saveProperties) { string typeName = typeof(TValue).Name; PropertyInfo[] properties = typeof(TValue).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); if (saveGet && !CacheGet.ContainsKey(typeName)) { CacheGet.Add(typeName, properties.ToDictionary(g => g.Name, m => CacheFacade.CreateFunction <TValue>(m))); } if (saveSet && !CacheSet.ContainsKey(typeName)) { CacheSet.Add(typeName, properties.ToDictionary(s => s.Name, m => CacheFacade.CreateAction <TValue>(m))); } if (saveProperties && !CacheProperties.ContainsKey(typeName)) { CacheProperties.Add(typeName, properties.ToDictionary(p => p.Name, p => p)); } if (saveAttribute && !CacheAttribute.ContainsKey(typeName)) { CacheAttribute.Add(typeName, new Dictionary <string, Dictionary <string, CustomAttributeTypedArgument> >(properties.Length)); foreach (var property in properties) { CachingAttribute(property, typeName); } } }
public void OnAuditing(ApplicationDbContext context, EntityAudit <AuditValue>[] audits) { var levelCaches = new CacheSet <Guid, AuditLevel>(id => () => context.AuditLevels.Include(x => x.RootLink).First(x => x.Id == id)); foreach (var audit in audits) { var level = levelCaches[audit.Current.Level].Value; switch (audit.State) { case EntityState.Added: level.ValueCount += 1; level.RootLink.TotalQuantity += audit.Current.Quantity; break; case EntityState.Modified: level.RootLink.TotalQuantity += audit.Current.Quantity - audit.Origin.Quantity; break; case EntityState.Deleted: level.ValueCount -= 1; level.RootLink.TotalQuantity -= audit.Current.Quantity; break; } } }
public static async Task BuildCache <TEntity, TCache>(TreasureEntities entities, IMapper mapper, CacheItemType type, DateTimeOffset timestamp) where TEntity : class { Debug.WriteLine("Building cache for " + type); var data = entities.Set <TEntity>().AsQueryable(); var cast = await data.ProjectTo <TCache>(mapper.ConfigurationProvider).ToListAsync(); var json = JsonConvert.SerializeObject(cast, JsonSettings); var existing = await entities.CacheSets.SingleOrDefaultAsync(x => x.Type == type); var existed = existing != null; if (!existed) { existing = new CacheSet { Type = type }; entities.CacheSets.Add(existing); } existing.JSON = json; existing.EditedDate = timestamp; await entities.SaveChangesAsync(); Debug.WriteLine("Cache built."); }
public CacheSet<string> SelectByIDs(string EntityName, System.Collections.Generic.IEnumerable<string> EntityIDs) { CacheSet<string> Result = new CacheSet<string>(); if (!EntityNames.Contains(EntityName)) { Result.WantIDs = EntityIDs.ToList<string>(); return Result; } List<string> IDs = new List<string>(); List<string> Contents = new List<string>(); StringBuilder QueryBuilder = new StringBuilder(); QueryBuilder.AppendFormat("select * from {0} where ID in ({1}) order by ID", EntityName, ToCommaList(EntityIDs)); DataTable Table = SQLLite.GetDataTable(QueryBuilder.ToString()); for (int i=0; i < Table.Rows.Count; i++) { IDs.Add(Table.Rows[i][0].ToString()); Contents.Add(Table.Rows[i][1].ToString()); } Result.Records = Contents; Result.WantIDs = EntityIDs.Except<string>(IDs).ToList<string>(); return Result; }
public ObjectMapperFactory(CacheSet mapperScopedCacheSet) { _mappingExpressionFactories = new[] { QueryProjectionExpressionFactory.Instance, DictionaryMappingExpressionFactory.Instance, EnumerableMappingExpressionFactory.Instance, ComplexTypeMappingExpressionFactory.Instance }; _rootMappersCache = mapperScopedCacheSet.CreateScoped <IRootMapperKey, IObjectMapper>(default(RootMapperKeyComparer)); }
public MapperContext() { Cache = new CacheSet(); Naming = new NamingSettings(Cache); QualifiedMemberFactory = new QualifiedMemberFactory(this); RootMembersSource = new RootMembersSource(QualifiedMemberFactory); ObjectMapperFactory = new ObjectMapperFactory(Cache); UserConfigurations = new UserConfigurationSet(this); ConstructionFactory = new ComplexTypeConstructionFactory(Cache); ValueConverters = new ConverterSet(UserConfigurations); RuleSets = MappingRuleSetCollection.Default; }
public MapperContext(NamingSettings namingSettings = null) { Cache = new CacheSet(); DataSources = new DataSourceFinder(); NamingSettings = namingSettings ?? new NamingSettings(); RootMembersSource = new RootMembersSource(new RootQualifiedMemberFactory(this)); ObjectMapperFactory = new ObjectMapperFactory(this); ObjectFlattener = new ObjectFlattener(); DerivedTypes = new DerivedTypesCache(); UserConfigurations = new UserConfigurationSet(); ValueConverters = new ConverterSet(); RuleSets = new MappingRuleSetCollection(); }
public SignatureCacher(TypeInfoProvider typeInfo, bool localCachingEnabled, bool preferLocalCacheForGenericMethodSignatures, bool preferLocalCacheForGenericInterfaceMethodSignatures, bool useMethodSignaturePerMethod) { Global = new CacheSet(useMethodSignaturePerMethod); LocalCachedSets = new Dictionary <MemberIdentifier, CacheSet>( new MemberIdentifier.Comparer(typeInfo) ); VisitNestedFunctions = true; LocalCachingEnabled = localCachingEnabled; PreferLocalCacheForGenericMethodSignatures = preferLocalCacheForGenericMethodSignatures; PreferLocalCacheForGenericInterfaceMethodSignatures = preferLocalCacheForGenericInterfaceMethodSignatures; UseMethodSignaturePerMethod = useMethodSignaturePerMethod; }
public void MRUCache_MostRecentlyItemShouldBeAtTheEndWithEviction() { var cacheSet = new CacheSet <string, string>(new MRUCachePolicy <string, string>(), 4); cacheSet.AddItemToCacheSet("W", "dataW"); cacheSet.AddItemToCacheSet("X", "dataX"); cacheSet.AddItemToCacheSet("W", "dataWW"); cacheSet.AddItemToCacheSet("Y", "dataY"); cacheSet.AddItemToCacheSet("Z", "dataZ"); cacheSet.AddItemToCacheSet("W", "dataWWW"); cacheSet.AddItemToCacheSet("T", "dataT"); var expected = new List <string>() { "T", "Z", "Y", "X" }; var actual = cacheSet.GetAllKeys(); Assert.AreEqual(expected[0], actual[0]); Assert.AreEqual(expected[3], actual[3]); cacheSet.AddItemToCacheSet("Y", "dataYY"); cacheSet.AddItemToCacheSet("Z", "dataZZ"); cacheSet.AddItemToCacheSet("W", "dataWWW"); cacheSet.AddItemToCacheSet("Y", "dataYYY"); cacheSet.AddItemToCacheSet("X", "dataXX"); expected = new List <string>() { "X", "Y", "W", "T" }; actual = cacheSet.GetAllKeys(); Assert.AreEqual(expected[0], actual[0]); Assert.AreEqual(expected[3], actual[3]); cacheSet.AddItemToCacheSet("X", "dataXX"); cacheSet.AddItemToCacheSet("Y", "dataYYYY"); cacheSet.AddItemToCacheSet("X", "dataXXX"); cacheSet.AddItemToCacheSet("Y", "dataYY"); expected = new List <string>() { "Y", "X", "W", "T" }; actual = cacheSet.GetAllKeys(); Assert.AreEqual(expected[0], actual[0]); Assert.AreEqual(expected[3], actual[3]); }
public NamingSettings(CacheSet mapperScopedCache) { _idMemberCache = mapperScopedCache.CreateScopedWithHashCodes <TypeKey, Member>(); _matchingNameFactories = new List <ConfiguredNamingPattern> { ConfiguredNamingPattern.Global(member => IsTypeIdentifier(member) ? "Id" : null), ConfiguredNamingPattern.ForGetOrSetMethod, ConfiguredNamingPattern.ForIdentifierName }; _joinedNameFactories = new List <Func <IEnumerable <string>, string> > { names => names.Join(string.Empty), names => names.Join(".") }; }
public void MRUCache_MostRecentlyItemShouldBeAtTheEnd() { var cacheSet = new CacheSet <string, string>(new MRUCachePolicy <string, string>(), 4); cacheSet.AddItemToCacheSet("A", "dataA"); cacheSet.AddItemToCacheSet("B", "dataB"); cacheSet.AddItemToCacheSet("C", "dataC"); cacheSet.AddItemToCacheSet("D", "dataD"); List <string> expected = new List <string>() { "D", "C", "B", "A" }; List <string> actual = cacheSet.GetAllKeys(); Assert.AreEqual(expected[0], actual[0]); Assert.AreEqual(expected[3], actual[3]); }
public NamingSettings(CacheSet mapperScopedCache) { _idMemberCache = mapperScopedCache.CreateScoped <TypeKey, Member>(default(HashCodeComparer <TypeKey>)); _matchingNameFactories = new List <Func <Member, string> > { member => IsTypeIdentifier(member) ? "Id" : null, GetGetOrSetMethodName, GetIdentifierName }; _joinedNameFactories = new List <Func <IEnumerable <string>, string> > { names => names.Join(string.Empty), names => names.Join(".") }; }
public void Test1() { var cacheContainer = new CacheSet <string, Guid> { CacheMethodBuilder = key => () => Guid.NewGuid(), UpdateExpirationMethod = cacheTime => cacheTime.Add(TimeSpan.FromMilliseconds(100)), }; var a0 = cacheContainer["a"].Value; var a1 = cacheContainer["a"].Value; var b0 = cacheContainer["b"].Value; Thread.Sleep(100); var b1 = cacheContainer["b"].Value; Assert.Equal(a0, a1); Assert.NotEqual(b0, b1); }
public async Task <string> GetOrCreate(string key, URLShortenDBContext context) { var _channel = Channel.CreateUnbounded <string>(new UnboundedChannelOptions() { SingleWriter = true, SingleReader = false }); var _crequest = new CacheRequest(_channel.Writer, 1); var _cset = new CacheSet(_channel.Reader, 1); var _cset2 = new CacheSet(_channel.Reader, 2); var _cset3 = new CacheSet(_channel.Reader, 3); await _crequest.GetCache(key) .ContinueWith(_ => _channel.Writer.Complete()); var address = await Task.WhenAny(_cset.GetOrCreate(context), _cset2.GetOrCreate(context), _cset3.GetOrCreate(context)); return(await address); }
private CacheSet GetCacheSet(bool cacheLocally) { CacheSet result = Global; if (cacheLocally && LocalCachingEnabled) { var fn = FunctionStack.Peek(); if ((fn.Method == null) || (fn.Method.Method == null)) { return(Global); } var functionIdentifier = fn.Method.Method.Identifier; if (!LocalCachedSets.TryGetValue(functionIdentifier, out result)) { result = LocalCachedSets[functionIdentifier] = new CacheSet(); } } return(result); }
public DerivedTypesCache(CacheSet cacheSet) { _assemblies = new List <Assembly>(); _typesByAssembly = cacheSet.CreateScoped <Assembly, IEnumerable <Type> >(default(HashCodeComparer <Assembly>)); _derivedTypesByType = cacheSet.CreateScoped <Type, IList <Type> >(default(HashCodeComparer <Type>)); }
public ComplexTypeConstructionFactory(CacheSet mapperScopedCacheSet) { _constructorsCache = mapperScopedCacheSet.CreateScoped <ConstructionKey, Construction>(); }
public DerivedTypesCache(CacheSet cacheSet) { _assemblies = new List <Assembly>(); _typesByAssembly = cacheSet.CreateScopedWithHashCodes <Assembly, IEnumerable <Type> >(); _derivedTypesByType = cacheSet.CreateScopedWithHashCodes <Type, IList <Type> >(); }
public ComplexTypeConstructionFactory(CacheSet mapperScopedCacheSet) { _constructionInfosCache = mapperScopedCacheSet.CreateScoped <ConstructionKey, IList <IConstructionInfo> >(); _constructionsCache = mapperScopedCacheSet.CreateScoped <ConstructionKey, Construction>(); }
public MemberCache(CacheSet cacheSet) { _membersCache = cacheSet.CreateScoped <TypeKey, IList <Member> >(default(HashCodeComparer <TypeKey>)); }
private GlobalContext() { Cache = new CacheSet(); _memberFinderLoader = new Lazy <MemberFinder>(() => new MemberFinder(), isThreadSafe: true); }
public ObjectMapperFactory(CacheSet mapperScopedCacheSet) { _rootMappersCache = mapperScopedCacheSet .CreateScoped <IRootMapperKey, IObjectMapper>(CompareRootMapperKeys); }
private GlobalContext() { Cache = new CacheSet(); MemberCache = new MemberCache(Cache); DerivedTypes = new DerivedTypesCache(Cache); }
/// <summary> /// This method should be called before 'base.SaveChanges'. /// </summary> /// <param name="context"></param> /// <param name="acceptAllChangesOnSuccess"></param> /// <returns></returns> public static void IntelliTrack(DbContext context, bool acceptAllChangesOnSuccess) { EntityEntry[] entries; IGrouping <Type, EntityEntry>[] auditEntriesByTypes; void RefreshEntries() { entries = context.ChangeTracker.Entries() .Where(x => new[] { EntityState.Added, EntityState.Modified, EntityState.Deleted }.Contains(x.State)) .ToArray(); auditEntriesByTypes = entries .GroupBy(x => x.Entity.GetType()) .Where(x => x.Key.HasAttribute <EntityAuditAttribute>()) .ToArray(); } var auditorCaches = new CacheSet <Type, Reflector>(auditType => () => Activator.CreateInstance(auditType).GetReflector()); RefreshEntries(); foreach (var entry in entries) { // Resolve AutoAttributes var entity = entry.Entity; var entityType = entity.GetType(); if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { var props = entityType.GetProperties().Where(x => x.CanWrite).ToArray(); ResolveAutoAttributes(entry, props); } } // Resolve BeforeAudit foreach (var entriesByType in auditEntriesByTypes) { var entityType = entriesByType.Key; var attr = entityType.GetCustomAttribute <EntityAuditAttribute>(); var auditType = typeof(EntityAudit <>).MakeGenericType(entityType); var audits = Array.CreateInstance(auditType, entriesByType.Count()); foreach (var kv in entriesByType.AsKvPairs()) { audits.SetValue(EntityAudit.Parse(kv.Value), kv.Key); } auditorCaches[attr.EntityAuditorType].Value .DeclaredMethod(nameof(IEntityAuditor <DbContext, object> .BeforeAudit)).Call(context, audits); } // Resolve OnAuditing RefreshEntries(); foreach (var entriesByType in auditEntriesByTypes) { var entityType = entriesByType.Key; var attr = entityType.GetCustomAttribute <EntityAuditAttribute>(); var auditType = typeof(EntityAudit <>).MakeGenericType(entityType); var audits = Array.CreateInstance(auditType, entriesByType.Count()); foreach (var kv in entriesByType.AsKvPairs()) { audits.SetValue(EntityAudit.Parse(kv.Value), kv.Key); } auditorCaches[attr.EntityAuditorType].Value .DeclaredMethod(nameof(IEntityAuditor <DbContext, object> .OnAuditing)).Call(context, audits); } // Resolve OnAudited CompleteAudit(context); }
public MemberCache(CacheSet cacheSet) { _membersCache = cacheSet.CreateScopedWithHashCodes <TypeKey, IList <Member> >(); }
public ObjectMapperFactory(CacheSet mapperScopedCacheSet) { _rootMappersCache = mapperScopedCacheSet.CreateScoped <IRootMapperKey, IObjectMapper>(default(RootMapperKeyComparer)); }