public override bool ProcessSource() { var metadata = DefineMetadata; Invocation.Proceed(); ICache queryCache = RepositoryFramework.GetCacherForQuery(metadata); ICache cache = RepositoryFramework.GetCacher(metadata); //IList接口 PagingResult <TEntity> paging = (PagingResult <TEntity>)Invocation.ReturnValue; var ta = TypeAccessor.GetAccessor(metadata.EntityType); var idGetter = ta.GetPropertyGetter(metadata.IdMember.Name); var spec = (ISpecification <TEntity>)Invocation.Arguments[0]; if (spec == null) { throw new ArgumentException("第一个参数类型必须为 ISpecification<TEntity>"); } //加入缓存 cache.SetBatch(paging.Items.Cast <object>().Select(o => new CacheItem <object>(metadata.GetCacheKey(o), metadata.CloneEntity(o))), 1200); queryCache.Set(CacheKey, new PagingCacheData(paging.Items.Select(o => idGetter(o))) { ShardParams = spec.ShardParams, TotalCount = paging.TotalCount }); return(true); }
bool IsCacheValid(ClassDefineMetadata metadata, IQueryTimestamp cacheData) { ICache dependCache = RepositoryFramework.GetCacher(metadata, "cache:region"); var values = dependCache.GetBatch <long>(regions.Select(o => o.CacheKey)); return(values.Count() == 0 || values.All(o => o < cacheData.Timestamp)); }
public override bool ProcessSource() { var metadata = DefineMetadata; Invocation.Proceed(); ICache queryCache = RepositoryFramework.GetCacherForQuery(metadata); ICache cache = RepositoryFramework.GetCacher(metadata); //IList接口 TEntity item = (TEntity)Invocation.ReturnValue; if (item != null) { var ta = TypeAccessor.GetAccessor(metadata.EntityType); var idGetter = ta.GetPropertyGetter(metadata.IdMember.Name); var spec = (ISpecification <TEntity>)Invocation.Arguments[0]; if (spec == null) { throw new ArgumentException("第一个参数类型必须为 ISpecification<TEntity>"); } //加入缓存 cache.Set(metadata.GetCacheKey(item), metadata.CloneEntity(item), 1200); queryCache.Set(CacheKey, new ListCacheData(new object[] { idGetter(item) }) { ShardParams = spec.ShardParams }); } return(item != null); }
void CheckCacheRegion <TRegionEntity>(CacheRegion region) { var entityType = typeof(TRegionEntity); var metadata = RepositoryFramework.GetDefineMetadataAndCheck(entityType); metadata.CheckCacheRegions(new CacheRegion[] { region }); }
public object Poco(object entity, Func <object, object> subPocoHandler) { var metadata = RepositoryFramework.GetDefineMetadata(entity.GetType()); var pa = PropertyAccessorFactory.GetPropertyAccess(metadata.EntityType); var poco = entity; var pocoed = false; if (ProxyProvider.IsProxy(entity) && metadata.ClassJoinDefines.Count > 0) { poco = pa.CreateInstance(); metadata.MergeData(entity, poco); pocoed = true; } foreach (var property in metadata.CascadeProperties) { var value = pa.GetGetter(property.Name).Get(entity); if (value != null) { var valuePoco = subPocoHandler(value); if (valuePoco != value || pocoed) { pa.GetSetter(property.Name).Set(poco, valuePoco); } } } return(poco); }
public object Proxy(object entity, Func <object, object> subProxyHandler) { var metadata = RepositoryFramework.GetDefineMetadata(entity.GetType()); var proxy = entity; var proxyed = false; if (!ProxyProvider.IsProxy(entity) && metadata.ClassJoinDefines.Count > 0) { proxy = ProxyProvider.CreateEntityProxy(metadata.EntityType); metadata.MergeData(entity, proxy); proxyed = true; } var pa = PropertyAccessorFactory.GetPropertyAccess(metadata.EntityType); foreach (var property in metadata.CascadeProperties) { if (EntityInterceptor.PropertyInited(entity, property.Name)) { var value = pa.GetGetter(property.Name).Get(entity); if (value != null) { var valueProxy = subProxyHandler(value); if (valueProxy != value || proxyed) { pa.GetSetter(property.Name).Set(proxy, valueProxy); } } } } return(proxy); }
internal static void Proxy(object instance) { if (instance == null) { throw new ArgumentNullException("instance"); } var type = instance.GetType(); if (EntityUtil.IsPagingResult(type)) { var ta = TypeAccessor.GetAccessor(type); IEnumerable items = (IEnumerable)ta.GetProperty("Items", instance); foreach (var item in items) { Proxy(item); } } else if (EntityUtil.IsGenericList(type)) { IEnumerable items = (IEnumerable)instance; foreach (var item in items) { Proxy(item); } } else if (RepositoryFramework.GetDefineMetadata(type) != null) { ProxyJoins(instance); } }
/// <summary> /// 引发数据变更的操作,通过改操作可以进行缓存及缓存依赖的通知 /// </summary> /// <param name="entity"></param> public static void RaisePersistent(object entity) { if (entity == null) { throw new ArgumentNullException("entity"); } var metadata = GetDefineMetadata(entity.GetType()); if (metadata == null) { throw new PlatformException("无法获取对象的定义 {0}", entity.GetType().FullName); } // 如果启用缓存,则通知过期 if (metadata.IsCacheable) { var cacheKey = metadata.GetCacheKey(entity); ICache cache = GetCacher(metadata); cache.Remove(metadata.EntityType, cacheKey); } // 更新依赖缓存的时间戳 var depends = metadata.GetCacheRegionKeys(entity); if (depends.Count > 0) { var time = NetworkTime.Now.Ticks; ICache dependCache = RepositoryFramework.GetCacherForCacheRegion(); var items = depends.Select(o => new CacheItem <long>(o, time)).ToList(); dependCache.SetBatch(items, DateTime.MaxValue); } }
static void Fetch(object entity, Func <object, bool> cancelFetchFunc) { if (entity == null) { return; } var type = entity.GetType(); var metadata = RepositoryFramework.GetDefineMetadata(type); if (metadata != null) { if (metadata.FetchableObject != null) { (metadata.FetchableObject).Fetch(entity); } var joins = metadata.ClassJoinDefines.Values.Cast <ClassJoinDefineMetadata>().Where(o => o.JoinType == MethodJoinType.PropertyGet); var ta = TypeAccessor.GetAccessor(metadata.EntityType); foreach (var join in joins) { var value = ta.GetProperty(join.JoinName, entity); if (cancelFetchFunc != null && cancelFetchFunc(value)) { return; } var entityType = join.Method.ReturnType; if (EntityUtil.IsGenericList(entityType)) { var items = (IList)value; for (var i = 0; i < items.Count; i++) { var v = items[i]; var sv = GetSource(v); Fetch(sv, cancelFetchFunc); if (sv != v) { items[i] = sv; } } } else { var sv = GetSource(value); Fetch(sv, cancelFetchFunc); if (value != sv) { ta.SetProperty(join.JoinName, entity, sv); } } } } }
ClassDefineMetadata GetClassDefineMetadata(object entity) { if (entity != null) { return(RepositoryFramework.GetDefineMetadata(entity.GetType())); } return(null); }
public static IPersister CreatePersister(IInvocation invocation, ClassDefineMetadata metadata) { DataSourcePersister dataSource = new DataSourcePersister(invocation, null); SecondLevelPersister secondLevel = new SecondLevelPersister(metadata, RepositoryFramework.GetCacher(metadata), dataSource); SessionPersister session = new SessionPersister(SessionCache.Current, secondLevel); return(session); }
static IEnumerable <IClassJoinCascadeProcessor> GetCascadeProcessors(Type type) { var metadata = RepositoryFramework.GetDefineMetadata(type); if (metadata == null) { throw new ArgumentNullException("metadata"); } return(metadata.ClassJoinDefines.Where(o => o.Value.JoinType == MethodJoinType.PropertyGet && o.Value.JoinCascade.CascataType != CascadeType.None) .Select(o => o.Value.JoinCascade.Processor)); }
public static object GetId(object entity) { if (entity == null) { throw new ArgumentNullException("entity"); } var metadata = RepositoryFramework.GetDefineMetadataAndCheck(entity.GetType()); var ta = TypeAccessor.GetAccessor(metadata.EntityType); return(ta.GetProperty(metadata.IdMember.Name, entity)); }
public void Fetch(object entity, Action <object> subFetchHandler) { var metadata = RepositoryFramework.GetDefineMetadata(entity.GetType()); var pa = PropertyAccessorFactory.GetPropertyAccess(metadata.EntityType); foreach (var property in metadata.CascadeProperties) { var value = pa.GetGetter(property.Name).Get(entity); if (value != null) { subFetchHandler(value); } } }
public void SetRegions(List <CacheRegion> regions) { this.regions = regions; //验证缓存区域设置 foreach (var region in regions) { var metadata = RepositoryFramework.GetDefineMetadata(region.EntityType); if (metadata == null) { throw new NotSupportedException(String.Format("类型 {0} 未进行定义,因此无法实现仓储扩展。", region.EntityType.FullName)); } metadata.CheckCacheRegions(new[] { region }); } }
public void Intercept(IInvocation invocation) { var methodName = invocation.Method.Name; bool skip = methodName == "OpenSession" || methodName == "GetShardParams" || methodName == "CreateSpecification"; if (!skip && (methodName == "GetList" || methodName == "Get")) { var arguments = invocation.Method.GetParameters(); skip = arguments.Length != 2 || arguments[0].ParameterType != typeof(ShardParams); } if (!skip) { ProfilerContext.BeginWatch(invocation.TargetType.FullName + "." + invocation.Method.Name); } try { var entityType = ReflectionHelper.GetEntityTypeFromRepositoryType(invocation.TargetType); var metadata = RepositoryFramework.GetDefineMetadata(entityType); if (metadata != null) { var mi = invocations.FirstOrDefault(o => o.IsMatch(invocation)); if (mi != null) { mi.Process(invocation, metadata); ProxyEntity(invocation); return; } } if (skip) { invocation.Proceed(); } else { using (MonitorContext.Repository(invocation.Method)) invocation.Proceed(); } ProxyEntity(invocation); } finally { if (!skip) { ProfilerContext.EndWatch(); } } }
bool IsIdentityExpression(Expression <Func <TJoin, bool> > expression, out object value) { value = null; var metadata = RepositoryFramework.GetDefineMetadata(typeof(TJoin)); if (metadata == null || metadata.IdMember == null) { return(false); } var valider = new IdentityExpressionValider(metadata.IdMember, expression); value = valider.Value; return(valider.IsValid); }
public void Intercept(IInvocation invocation) { var entityType = ReflectionHelper.GetEntityTypeFromRepositoryType(invocation.TargetType); var metadata = RepositoryFramework.GetDefineMetadata(entityType); if (metadata == null) { throw new NotSupportedException(String.Format("类型 {0} 未进行定义,因此无法实现仓储扩展。", entityType.FullName)); } foreach (var type in providers) { AbstractCacheableRepositoryProvider <T> provider = (AbstractCacheableRepositoryProvider <T>)Projects.Tool.Reflection.FastActivator.Create(type); provider.Invocation = invocation; if (provider.IsMatch()) { provider.CacheKey = cacheKey; var regionStr = String.Join(",", regions.Select(o => o.CacheKey)); var cacheData = provider.GetCacheData(); if (cacheData != null && IsCacheValid(metadata, cacheData)) { log.DebugFormat("{0}.{1} query cache hit. #{2}", invocation.Method.DeclaringType.ToPrettyString(), invocation.Method.Name, provider.CacheKey); if (ProfilerContext.Current.Enabled) { ProfilerContext.Current.Trace("platform", String.Format("hit {1}\r\n{0}", ProfilerUtil.JsonFormat(provider.CacheKey), regionStr)); } //处理缓存 using (MonitorContext.Repository(invocation.Method, true)) provider.ProcessCache(cacheData); return; } //处理原始 var hasSource = provider.ProcessSource(); log.DebugFormat("{0}.{1} query cache missing. #{2}", invocation.Method.DeclaringType.ToPrettyString(), invocation.Method.Name, provider.CacheKey); if (ProfilerContext.Current.Enabled) { ProfilerContext.Current.Trace("platform", String.Format("missing {1}{2}\r\n{0}", ProfilerUtil.JsonFormat(provider.CacheKey), regionStr, hasSource ? "" : " for null")); } return; } } invocation.Proceed(); }
public static object CreateEntityProxy(Type entityType) { ClassDefineMetadata metadata = RepositoryFramework.GetDefineMetadataAndCheck(entityType); return(CreateProxy(entityType, metadata)); //var ei = new EntityInterceptor(metadata); //ProxyGenerationOptions options = new ProxyGenerationOptions(new InnerHook(metadata)); ////var t = generator.ProxyBuilder.CreateClassProxyType(entityType,new Type[0], options); //// //var proxy = generator.CreateClassProxy(entityType, options, ei); //ei.Inited = true; //return proxy; }
public void Process(IInvocation invocation, ClassDefineMetadata metadata) { if (metadata == null) { throw new ArgumentNullException("metadata"); } if (metadata.IsCacheable) { var cacheKey = metadata.GetCacheKeyById(invocation.Arguments[1]); ICache cache = RepositoryFramework.GetCacher(metadata); //CacheData value = cache.Get(cacheKey); var value = cache.Get(metadata.EntityType, cacheKey); if (value == null) { // 调用源接口,并将结果写入缓存 using (MonitorContext.Repository(invocation.Method)) invocation.Proceed(); var entity = invocation.ReturnValue; if (entity != null) { cache.Set(cacheKey, metadata.CloneEntity(entity)); } if (ProfilerContext.Current.Enabled) { ProfilerContext.Current.Trace("platform", String.Format("missing get{1}\r\n{0}", cacheKey, entity == null ? " for null" : "")); } } else { //if (ProfilerContext.Current.Enabled) // ProfilerContext.Current.Trace("platform", String.Format("hit get\r\n{0}", cacheKey)); //invocation.ReturnValue = value.Convert(metadata.EntityType); using (MonitorContext.Repository(invocation.Method, true)) { } invocation.ReturnValue = value; } } else { using (MonitorContext.Repository(invocation.Method)) invocation.Proceed(); } }
public void Process(IInvocation invocation, ClassDefineMetadata metadata) { if (metadata == null) { throw new ArgumentNullException("metadata"); } var entity = invocation.Arguments[0]; if (entity == null) { throw new ArgumentNullException("entity"); } var interceptors = RepositoryFramework.GetInterceptors(metadata.EntityType); //invoke pre event var preUr = new UniqueRaise(GetRaiseType(invocation, true), metadata, entity, false); var postUr = new UniqueRaise(GetRaiseType(invocation, false), metadata, entity, false); //invoke cascade delete or update var preRaiseType = GetRaiseType(invocation, true); if (preRaiseType == RaiseType.PreDelete || preRaiseType == RaiseType.PreUpdate) { Cascade(invocation, entity); } RepositoryFramework.Raise(entity, preRaiseType, preUr); using (MonitorContext.Repository(invocation.Method)) invocation.Proceed(); //invoke post event var postRaiseType = GetRaiseType(invocation, false); RepositoryFramework.Raise(entity, postRaiseType, postUr); //invoke cascade create if (postRaiseType == RaiseType.PostCreate) { Cascade(invocation, entity); } preUr.Dispose(); postUr.Dispose(); }
public override bool ProcessSource() { var metadata = DefineMetadata; Invocation.Proceed(); ICache cache = RepositoryFramework.GetCacher(DefineMetadata); object data = Invocation.ReturnValue; if (data != null) { cache.Set(CacheKey, new QueryCacheData() { Data = data }); } return(data != null); }
public static TJoin GetJoin <TJoin>(object entity, Expression <Func <TJoin> > memberExpr) { if (entity == null) { throw new ArgumentNullException("entity"); } var metadata = RepositoryFramework.GetDefineMetadata(entity.GetType()); var method = ReflectionHelper.GetMethod(memberExpr.Body); var joinDefine = metadata.GetClassJoinDefineMetadata(method); if (joinDefine == null) { throw new PlatformException("类型 {1} 方法 {0} 未进行关联的定义。", method.Name, method.DeclaringType.FullName); } return((TJoin)joinDefine.DataProcesser.Process(entity)); }
public static object GetId(object entity) { if (entity == null) { throw new ArgumentNullException("entity"); } var entityType = entity.GetType(); var metadata = RepositoryFramework.GetDefineMetadata(entityType); if (metadata == null) { throw new ArgumentNullException("metadata"); } var pa = GetPropertyAccess(metadata.EntityType); return(pa.GetGetter(metadata.IdMember.Name).Get(entity)); }
internal static void ProxyJoins(object entity) { ClassDefineMetadata metadata = RepositoryFramework.GetDefineMetadataAndCheck(entity.GetType()); var joins = metadata.ClassJoinDefines.Values.Cast <ClassJoinDefineMetadata>().Where(o => o.JoinType == MethodJoinType.PropertyGet); var ta = TypeAccessor.GetAccessor(metadata.EntityType); foreach (var join in joins) { var value = ta.GetProperty(join.JoinName, entity); //已经为代理对象,直接忽略 if (IsProxy(value)) { ((IProxy)value).Reset(); continue; } var type = join.Method.ReturnType; if (EntityUtil.IsGenericList(type)) { var itemType = type.GetGenericArguments()[0]; var proxyType = typeof(ProxyCollection <>).MakeGenericType(itemType); IProxyCollection proxy = (IProxyCollection)FastActivator.Create(proxyType); proxy.Init(entity, join); ta.SetProperty(join.JoinName, entity, proxy); } else { var ei = new EntityProxyInterceptor(entity, join); var proxy = ProxyProvider.GetCreateFunc(type)(new IInterceptor[] { ei }); ei.IsConstructed = true; ta.SetProperty(join.JoinName, entity, proxy); } } }
bool CheckEntity(TKey key, IQueryTimestamp data) { if (data == null) { return(true); } var cdd = new CacheDependDefine(); dependAction(cdd, key); var keys = cdd.GetCacheKey(); ICache dependCache = RepositoryFramework.GetCacherForCacheRegion(); var values = dependCache.GetBatch <long>(keys); var isValid = values.Count() == 0 || values.All(o => o < data.Timestamp); if (!isValid) { RemoveCache(key); } return(isValid); }
public static void Fetch(object entity) { if (entity == null) { return; } var type = entity.GetType(); var metadata = RepositoryFramework.GetDefineMetadata(type); if (metadata != null) { if (metadata.FetchableObject != null) { metadata.FetchableObject.Fetch(entity); Fetch(entity, metadata.FetchableObject.CheckFetchCancel); } else { Fetch(entity, null); } } }
internal static object Raise(object entity, RaiseType raiseType, UniqueRaise ur = null) { if (entity == null) { throw new ArgumentNullException("entity"); } var metadata = GetDefineMetadata(entity.GetType()); if (metadata == null) { throw new PlatformException("无法获取对象的定义 {0}", entity.GetType().FullName); } var interceptors = RepositoryFramework.GetInterceptors(metadata.EntityType); if (ur == null) { ur = new UniqueRaise(raiseType, metadata, entity, true); } if (ur.NotRaised) { foreach (var interceptor in interceptors) { switch (raiseType) { case RaiseType.PreCreate: interceptor.PreCreate(entity); break; case RaiseType.PreUpdate: interceptor.PreUpdate(entity); break; case RaiseType.PreDelete: interceptor.PreDelete(entity); break; case RaiseType.PostCreate: interceptor.PostCreate(entity); break; case RaiseType.PostUpdate: interceptor.PostUpdate(entity); break; case RaiseType.PostDelete: interceptor.PostDelete(entity); break; case RaiseType.PostLoad: interceptor.PostLoad(entity); break; } } } if (ur.NotRaised && ur.AutoDisposed) { ur.Dispose(); } return(entity); }
public override IQueryTimestamp GetCacheData() { return(RepositoryFramework.GetCacher(DefineMetadata).Get <QueryCacheData>(CacheKey)); }
public void Process(IInvocation invocation, ClassDefineMetadata metadata) { if (metadata == null) { throw new ArgumentNullException("metadata"); } if (metadata.IsCacheable) { IEnumerable ids = (IEnumerable)invocation.Arguments[1]; var cache = RepositoryFramework.GetCacher(metadata); var idKeys = ids.Cast <object>().Distinct().Select(o => new IdKey(o, metadata.GetCacheKeyById(o))); //访问缓存并获取不在缓存中的 CacheKey IEnumerable <string> missing; //var cacheItems = cache.GetBatch<CacheData>(idKeys.Select(o => o.Key), out missing).Select(o => o.Convert(metadata.EntityType)).ToList(); var cacheItems = cache.GetBatch(metadata.EntityType, idKeys.Select(o => o.Key), out missing).Cast <object>().ToList(); if (missing.Count() > 0) { var missIds = missing.Select(o => idKeys.First(ik => ik.Key == o).Id); invocation.SetArgumentValue(1, missIds); using (MonitorContext.Repository(invocation.Method)) invocation.Proceed(); var sourceItems = ((IEnumerable)invocation.ReturnValue).Cast <object>(); cacheItems.AddRange(sourceItems); if (sourceItems.Count() > 0) { //加入缓存 cache.SetBatch(sourceItems.Select(o => new CacheItem <object>(metadata.GetCacheKey(o), metadata.CloneEntity(o))), 1200); } else { if (ProfilerContext.Current.Enabled) { ProfilerContext.Current.Trace("platform", String.Format("missing get list for null\r\n{0}", String.Join(",", missing))); } } } else { using (MonitorContext.Repository(invocation.Method, true)) { } } var ta = TypeAccessor.GetAccessor(metadata.EntityType); var idGetter = ta.GetPropertyGetter(metadata.IdMember.Name); //按ID排序并进行类型转化 invocation.ReturnValue = cacheItems .OrderBy(entity => idGetter(entity), ids.Cast <object>()) .Cast(metadata.EntityType); //按ID排序并进行类型转化 invocation.ReturnValue = cacheItems .OrderBy(entity => idGetter(entity), ids.Cast <object>()) .Cast(metadata.EntityType); } else { using (MonitorContext.Repository(invocation.Method)) invocation.Proceed(); } }