private IInterceptor[] SelectMethodInterceptors(IInterceptorSelector selector,
		                                                IInterceptor[] methodInterceptors,
		                                                Type targetType)
		{
			return methodInterceptors ??
			       selector.SelectInterceptors(targetType, Method, interceptors) ??
			       new IInterceptor[0];
		}
        /// <summary>
        /// Add the interceptor in the argument as the first interceptor
        /// and set its next to the interceptor that we have. In the first
        /// execution it will be the TailInterceptor.
        /// </summary>
        /// <param name="interceptor"></param>
        public virtual void Add(IInterceptor interceptor)
        {
            AssertUtil.ArgumentNotNull(interceptor, "interceptor");

            interceptor.Next = m_interceptor;
            m_interceptor = interceptor;
        }
Beispiel #3
0
        /// <summary>
        /// Registrations the activating.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Autofac.Core.ActivatingEventArgs&lt;System.Object&gt;"/> instance containing the event data.</param>
        private static void RegistrationActivating(object sender, ActivatingEventArgs<object> e)
        {
            // Ignore AspectConfiguration and IInterceptor types since they're being referenced via the Autofac
            // registration context. Otherwise calling e.Context.Resolve<IInterceptor> will fail when
            // the code below executes.
            if (e.Instance.GetType() == typeof (MasterProxy) || e.Instance is IInterceptor)
            {
                return;
            }

            var proxy = (MasterProxy)e.Context.Resolve(typeof(MasterProxy));

            if (!e.Instance.IsDecorated(proxy.Configuration))
            {
                return;
            }

            var pseudoList = new IInterceptor[proxy.Configuration.Interceptors.Count];
            pseudoList[0] = proxy;

            for (var i = 1; i < pseudoList.Length; i++)
            {
                pseudoList[i] = new PseudoInterceptor();
            }

            var interfaceTypes = e.Instance.GetType().GetInterfaces();
            var targetInterface =
                interfaceTypes.FirstMatch(proxy.Configuration.Namespaces);

            e.Instance = new ProxyGenerator().CreateInterfaceProxyWithTargetInterface(targetInterface, e.Instance, pseudoList);
        }
 private StaticInterceptorStub(MethodInfo method, IInterceptor[] interceptors,
     MethodInfo methodInvocationTarget)
 {
     this.method = method;
     this.interceptors = interceptors;
     this.methodInvocationTarget = methodInvocationTarget;
 }
 public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
 {
     if (method.IsAddMethod()) return interceptors.Where(x => x is ListAddInterceptor).ToArray();
     if (method.IsSetMethod()) return interceptors.Where(x => x is ListSetInterceptor).ToArray();
     if (method.IsRemoveMethod()) return interceptors.Where(x => x is ListRemoveInterceptor).ToArray();
     return new IInterceptor[0];
 }
Beispiel #6
0
        /// <summary>Select interceptors which must be applied to the method.</summary>
        /// <param name="type">The type.</param>
        /// <param name="method">The method.</param>
        /// <param name="interceptors">The interceptors.</param>
        /// <returns>The interceptors after filtering.</returns>
        public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
            if (method.IsGetter())
            {
                var propertyInfo = type.GetProperty(method);
                if (propertyInfo.IsPropertyWithSelectorAttribute())
                {
                    return typeof(BaseHtmlElement).IsAssignableFrom(method.ReturnType) 
                        ? interceptors.Where(x => x is PropertyInterceptor).ToArray() 
                        : interceptors.Where(x => x is CollectionPropertyInterceptor).ToArray();
                }
            }

            if (method.IsSetter())
            {
                var propertyInfo = type.GetProperty(method);
                if (propertyInfo.IsPropertyWithSelectorAttribute())
                {
                    return interceptors.Where(x => x is InvalidWriteOperationInterceptor).ToArray();
                }
            }

            return interceptors.Where(x => !(x is PropertyInterceptor) 
                && !(x is CollectionPropertyInterceptor)
                && !(x is InvalidWriteOperationInterceptor)).ToArray();
        }
		public EFCustomerRepository(string connectionStringName, ICustomerEntityFactory entityFactory, IInterceptor[] interceptors = null)
			: base(connectionStringName, factory: entityFactory, interceptors: interceptors)
		{
			this.Configuration.AutoDetectChangesEnabled = true;
			this.Configuration.ProxyCreationEnabled = false;
			Database.SetInitializer(new ValidateDatabaseInitializer<EFCustomerRepository>());
		}
        /// <summary>
        ///     The select interceptors.
        /// </summary>
        /// <param name="type">
        ///     The type.
        /// </param>
        /// <param name="method">
        ///     The method.
        /// </param>
        /// <param name="interceptors">
        ///     The interceptors.
        /// </param>
        /// <returns>
        ///     The <see cref="IInterceptor[]" />.
        /// </returns>
        public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
            string name = method.Name;
            if (method.IsSpecialName)
            {
                if (name.StartsWith(AopConstants.PropertyGetter, StringComparison.Ordinal)) name = name.Remove(0, AopConstants.PropertyGetter.Length);

                if (name.StartsWith(AopConstants.PropertySetter, StringComparison.Ordinal)) name = name.Remove(0, AopConstants.PropertySetter.Length);

                if (name.StartsWith(AopConstants.EventAdder, StringComparison.Ordinal)) name = name.Remove(0, AopConstants.EventAdder.Length);

                if (name.StartsWith(AopConstants.EventRemover, StringComparison.Ordinal)) name = name.Remove(0, AopConstants.EventRemover.Length);
            }

            return interceptors.Where(
                inter =>
                {
                    var sinter = inter as ISpecificInterceptor;
                    if (sinter != null)
                    {
                        return sinter.Name == name ||
                               sinter.Name == AopConstants.InternalUniversalInterceptorName;
                    }

                    return true;
                }).OrderBy(
                    inter =>
                    {
                        var sinter = inter as ISpecificInterceptor;
                        return sinter == null ? 0 : sinter.Order;
                    }).ToArray();
        }
        protected NhConfigurationBase(IInterceptor interceptor, INhProperties nhProperties, IMappingAssemblies mappingAssemblies, IRegisterEventListener[] registerEventListeners)
        {
            if (interceptor == null)
            {
                throw new ArgumentNullException("interceptor");
            }
            if (nhProperties == null)
            {
                throw new ArgumentNullException("nhProperties");
            }
            if (mappingAssemblies == null)
            {
                throw new ArgumentNullException("mappingAssemblies");
            }
            if (registerEventListeners == null)
            {
                throw new ArgumentNullException("registerEventListeners");
            }
            Contract.EndContractBlock();

            m_Interceptor = interceptor;
            m_NhProperties = nhProperties;
            m_MappingAssemblies = mappingAssemblies;
            m_RegisterEventListeners = registerEventListeners;
        }
        IInterceptor[] IInterceptorSelector.SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
            if (interceptors.Length == 0)
                return interceptors;

            var markers = new List<MarkerBaseAttribute>();
            if (type != null)
                markers.AddRange(type.GetCustomAttributes(typeof(MarkerBaseAttribute), true).Cast<MarkerBaseAttribute>());

            if (method != null)
                markers.AddRange(method.GetCustomAttributes(typeof(MarkerBaseAttribute), true).Cast<MarkerBaseAttribute>());

            if (markers.Count == 0) // no marker attributes found, no ordering required
                return interceptors;

            markers.Sort((a, b) => a.Order.CompareTo(b.Order));

            var sorted = new List<IInterceptor>();
            for (int i = 0; i < markers.Count; ++i)
            {
                var providers = interceptors.OfType<IInterceptorMarkerProvider>();
                var markerType = markers[i].GetType();
                var matchingInterceptor = providers.FirstOrDefault(x => x.MarkerType == markerType) as IInterceptor;
                if (matchingInterceptor != null)
                    sorted.Add(matchingInterceptor);
            }
            return sorted.ToArray();
        }
Beispiel #11
0
 public SessionProvider(IConfigurationBuilder builder, IInterceptor interceptor, IWebContext webContext)
 {
     nhSessionFactory = builder.BuildSessionFactory();
     Debug.WriteLine("Built Session Factory " + DateTime.Now);
     this.webContext = webContext;
     this.interceptor = interceptor;
 }
 public virtual object GetProxy(Type type, IInterceptor interceptor)
 {
     if (cache.ContainsKey(type))
         return cache[type];
     cache[type] = CreateProxy(interceptor, type);
     return cache[type];
 }
        public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
        {
            var serviceWithType = service as IServiceWithType;
            if (serviceWithType == null)
                yield break;

            var serviceType = serviceWithType.ServiceType;
            if (!serviceType.IsInterface || !typeof(IEventHandler).IsAssignableFrom(serviceType) || serviceType == typeof(IEventHandler))
                yield break;

            var interfaceProxyType = _proxyBuilder.CreateInterfaceProxyTypeWithoutTarget(
                serviceType,
                new Type[0],
                ProxyGenerationOptions.Default);

            var rb = RegistrationBuilder
                .ForDelegate((ctx, parameters) => {
                    var interceptors = new IInterceptor[] { new EventsInterceptor(ctx.Resolve<IEventBus>()) };
                    var args = new object[] { interceptors, null };
                    return Activator.CreateInstance(interfaceProxyType, args);
                })
                .As(service);

            yield return rb.CreateRegistration();
        }
Beispiel #14
0
        public void PostProcess(IServiceRequestResult result)
        {
            var instance = result.ActualResult;
            var instanceTypeName = instance.GetType().FullName;

            // Ignore any LinFu factories or Snap-specific instances.
            if (instanceTypeName.Contains("LinFu.") || instanceTypeName == "Snap.AspectConfiguration"
                || instanceTypeName == "Snap.IMasterProxy" || instanceTypeName == "Snap.MasterProxy")
            {
                return;
            }

            var proxy = result.Container.GetService<IMasterProxy>();

            if (!instance.IsDecorated(proxy.Configuration))
            {
                return;
            }

            var pseudoList = new IInterceptor[proxy.Configuration.Interceptors.Count];
            pseudoList[0] = proxy;

            for (var i = 1; i < pseudoList.Length; i++)
            {
                pseudoList[i] = new PseudoInterceptor();
            }

            var interfaceTypes = instance.GetType().GetInterfaces();
            var targetInterface =
                interfaceTypes.FirstMatch(proxy.Configuration.Namespaces);

            result.ActualResult = new ProxyGenerator().CreateInterfaceProxyWithTargetInterface(targetInterface, instance, pseudoList);
        }
 public SessionFactoryBuilder(IDatabaseMappingScheme<MappingConfiguration> mappingScheme,
     IPersistenceConfigurer persistenceConfigurer, IInterceptor interceptor = null)
 {
     _mappingScheme = mappingScheme;
     _persistenceConfigurer = persistenceConfigurer;
     _interceptor = interceptor;
 }
 public IInterceptor[] SelectInterceptors(Type type, System.Reflection.MethodInfo method, IInterceptor[] interceptors)
 {
     if (method.Name == "FunA")
         return interceptors;
     return new IInterceptor[0];
     // ...
 }
        public IInterceptor[] SelectInterceptors( Type type, MethodInfo method, IInterceptor[] interceptors )
        {
            if( method.Name.StartsWith( "set_" ) )
                return interceptors;

            return null;
        }
Beispiel #18
0
 protected Invocation(object proxy, MethodInfo proxiedMethod, object[] arguments, IInterceptor[] interceptors)
 {
     _proxy = proxy;
     _proxiedMethod = proxiedMethod;
     _arguments = arguments;
     _interceptors = interceptors ?? new IInterceptor[0];
 }
Beispiel #19
0
		public MockingProxy(MarshalByRefObject wrappedInstance, IInterceptor interceptor, IMockMixin mockMixin)
			: base(wrappedInstance.GetType())
		{
			this.WrappedInstance = wrappedInstance;
			this.interceptor = interceptor;
			this.mockMixin = mockMixin;
		}
		public InterceptionContext(IInterceptor[] interceptors)
		{
            //if (interceptors != null)
            {
                _interceptors = new List<IInterceptor>(interceptors);
            }
		}
		public object Generate(IProxyBuilder builder, ProxyGenerationOptions options, IInterceptor[] interceptors)
		{
			var type = GetProxyType(builder);
			var instance = GetProxyInstance(type,interceptors);
			var method = GetInvokeDelegate(instance);
			return method;
		}
        public EFDynamicContentRepository(string nameOrConnectionString, DynamicContentEntityFactory entityFactory, IInterceptor[] interceptors = null)
            : base(nameOrConnectionString, factory: entityFactory, interceptors: interceptors)
        {
            this.Configuration.AutoDetectChangesEnabled = true;
            this.Configuration.ProxyCreationEnabled = false;

            Database.SetInitializer(new ValidateDatabaseInitializer<EFDynamicContentRepository>());
        }
Beispiel #23
0
        public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
            var isCollection =
                IsCollectionReturnType(method) ||
                IsCollectionParameterType(method);

            return _Interceptors.Where(e => e.InterceptCollections == isCollection).ToArray();
        }
Beispiel #24
0
		protected AbstractInvocation(
			object target, object proxy, IInterceptor[] interceptors,
			Type targetType, MethodInfo targetMethod, MethodInfo interfMethod,
			object[] arguments)
			: this(target, proxy, interceptors, targetType, targetMethod, arguments)
		{
			this.interfMethod = interfMethod;
		}
        public EFAppConfigRepository(string connectionStringName, IAppConfigEntityFactory entityFactory, IInterceptor[] interceptors = null)
            : base(connectionStringName, entityFactory, interceptors: interceptors)
        {
            Database.SetInitializer(new ValidateDatabaseInitializer<EFAppConfigRepository>());

            Configuration.AutoDetectChangesEnabled = true;
            Configuration.ProxyCreationEnabled = false;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="InterceptorAdapter"/> class.
        /// </summary>
        /// <param name="interceptor">The interceptor.</param>
        /// <param name="target">The target.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="interceptor"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="target"/> is <c>null</c>.</exception>
        public InterceptorAdapter(IInterceptor interceptor, object target)
        {
            Argument.IsNotNull("interceptor", interceptor);
            Argument.IsNotNull("target", target);

            _interceptor = interceptor;
            _target = target;
        }
        public static IProxy CreateProxy(this Type type, 
            IInterceptor interceptor, params Type[] baseInterfaces)
        {
            IProxy proxy = type.CreateProxy(baseInterfaces);
            proxy.Interceptor = interceptor;

            return proxy;
        }
Beispiel #28
0
 public Redirector(Func<object> getActualTarget, IInterceptor targetInterceptor, IProxyFactory factory,
     IMethodInvoke<MethodInfo> methodInvoke)
     : base(methodInvoke)
 {
     _getActualTarget = getActualTarget;
     _interceptor = targetInterceptor;
     _proxyFactory = factory;
 }
        public ProfiledSqlClientBatchingBatcher(ConnectionManager connectionManager, IInterceptor interceptor) : base(connectionManager, interceptor)
        {
            _batchSize = Factory.Settings.AdoBatchSize;
            _defaultTimeout = PropertiesHelper.GetInt32(global::NHibernate.Cfg.Environment.CommandTimeout, global::NHibernate.Cfg.Environment.Properties, -1);

            _currentBatch = CreateConfiguredBatch();
            _currentBatchCommandsLog = new StringBuilder().AppendLine("Batch commands:");
        }
 public void SetUp()
 {
     mocks = new MockRepository();
     expectedSessionFactory = mocks.StrictMock<ISessionFactory>();
     expectedEntityInterceptor = mocks.StrictMock<IInterceptor>();
     expectedSingleSession = SessionScopeSettings.SINGLESESSION_DEFAULT;
     expectedDefaultFlushMode = SessionScopeSettings.FLUSHMODE_DEFAULT;
 }
Beispiel #31
0
 public GetCatalogPageTask(IInterceptor interceptor, int pageId, string mode)
     : base(interceptor)
 {
     _pageId = pageId;
     _mode   = mode;
 }
Beispiel #32
0
 public DatabaseFactoryConfig WithInterceptor(IInterceptor interceptor)
 {
     _options.Interceptors.Add(interceptor);
     return(this);
 }
Beispiel #33
0
 public ISession OpenSession(IDbConnection conn, IInterceptor sessionLocalInterceptor)
 {
     return(_inner.OpenSession(_liveConnection, sessionLocalInterceptor));
 }
Beispiel #34
0
 public WrappingInterceptor(IInterceptor interfaceInterceptor)
 {
     _interfaceInterceptor = interfaceInterceptor;
 }
Beispiel #35
0
 /// <summary>
 /// Actually register the interceptor against this type.
 /// </summary>
 /// <param name="container">Container to configure.</param>
 /// <param name="interceptor">interceptor to register.</param>
 internal abstract void RegisterInterceptor(IUnityContainer container, IInterceptor interceptor);
Beispiel #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DynamicProxyInterceptor"/> class.
 /// </summary>
 /// <param name="interceptor">An <see cref="IInterceptor"/> instance.</param>
 public DynamicProxyInterceptor(IInterceptor interceptor)
 {
     this.interceptor = interceptor;
 }
        private DbConnectionMetaInfo MapToDatabseConfig(PureDataConfiguration config, IDatabaseConfig databaseConfig)
        {
            DbConnectionMetaInfo metaInfo = null;

            if (config != null && databaseConfig != null)
            {
                if (config.Settings != null)
                {
                    var settings = config.Settings;
                    databaseConfig.ParameterPrefix            = settings.ParameterPrefix;
                    databaseConfig.ParameterSuffix            = settings.ParameterSuffix;
                    databaseConfig.GlobalTablePrefix          = settings.GlobalTablePrefix;
                    databaseConfig.ExecuteTimeout             = settings.ExecuteTimeout;
                    databaseConfig.DefaultPageSize            = settings.DefaultPageSize;
                    databaseConfig.AutoDisposeConnection      = settings.AutoDisposeConnection;
                    databaseConfig.ValidateStopOnFirstFailure = settings.ValidateStopOnFirstFailure;
                    databaseConfig.LoadMapperMode             = settings.LoadMapperMode;


                    databaseConfig.EnableDebug       = settings.EnableDebug;
                    databaseConfig.EnableIntercept   = settings.EnableIntercept;
                    databaseConfig.EnableLogError    = settings.EnableLogError;
                    databaseConfig.EnableOrmLog      = settings.EnableOrmLog;
                    databaseConfig.EnableInternalLog = settings.EnableInternalLog;
                    databaseConfig.LogWithRawSql     = settings.LogWithRawSql;
                    databaseConfig.CategoryLogType   = settings.CategoryLogType;
                    if (!string.IsNullOrEmpty(settings.OrmLogsPath))
                    {
                        databaseConfig.OrmLogsPath = settings.OrmLogsPath;
                    }
                    databaseConfig.MaxServerLogSize = settings.MaxServerLogSize;

                    databaseConfig.EnableOrmCache      = settings.EnableOrmCache;
                    databaseConfig.CacheOrmTime        = settings.CacheOrmTime;
                    databaseConfig.CacheOrmSingleTime  = settings.CacheOrmSingleTime;
                    databaseConfig.OrmCacheCheckPeriod = settings.OrmCacheCheckPeriod;

                    databaseConfig.EnableSqlMap        = settings.EnableSqlMap;
                    databaseConfig.NameSpacePrefix     = settings.NameSpacePrefix;
                    databaseConfig.FormatSql           = settings.FormatSql;
                    databaseConfig.IsWatchSqlMapFile   = settings.IsWatchSqlMapFile;
                    databaseConfig.WatchSqlMapInterval = settings.WatchSqlMapInterval;

                    databaseConfig.AutoMigrate = settings.AutoMigrate;
                    databaseConfig.AutoRemoveUnuseColumnInTable = settings.AutoRemoveUnuseColumnInTable;
                    databaseConfig.CanUpdatedWhenTableExisted   = settings.CanUpdatedWhenTableExisted;
                    databaseConfig.EnableAutoMigrateLog         = settings.EnableAutoMigrateLog;
                    databaseConfig.EnableAutoMigrateDebug       = settings.EnableAutoMigrateDebug;
                    databaseConfig.AutoMigrateOnContainTable    = settings.AutoMigrateOnContainTable;
                    databaseConfig.AutoMigrateWithoutTable      = settings.AutoMigrateWithoutTable;
                    if (!string.IsNullOrEmpty(settings.GlobalIgnoreUpdatedColumns))
                    {
                        databaseConfig.GlobalIgnoreUpdatedColumns = settings.GlobalIgnoreUpdatedColumns;
                    }
                    databaseConfig.EnableGlobalIgnoreUpdatedColumns     = settings.EnableGlobalIgnoreUpdatedColumns;
                    databaseConfig.AutoFilterEmptyValueColumnsWhenTrack = settings.AutoFilterEmptyValueColumnsWhenTrack;

                    //代码生成设置
                    databaseConfig.EnableCodeGen           = settings.EnableCodeGen;
                    databaseConfig.CodeGenType             = settings.CodeGenType;
                    databaseConfig.CodeGenClassNameMode    = settings.CodeGenClassNameMode;
                    databaseConfig.CodeGenPropertyNameMode = settings.CodeGenPropertyNameMode;

                    databaseConfig.CodeGenProjectName = settings.CodeGenProjectName;
                    databaseConfig.CodeGenNameSpace   = settings.CodeGenNameSpace;
                    databaseConfig.CodeGenTableFilter = settings.CodeGenTableFilter;
                    string _basePath = "";

                    //if (databaseConfig.EnableCodeGen)
                    //{
                    string[] basePaths = settings.CodeGenBaseDirectory.Split(';');
                    if (basePaths.Length > 0)
                    {
                        foreach (var basePath in basePaths)
                        {
                            if (System.IO.Directory.Exists(basePath))
                            {
                                _basePath = basePath;
                                break;
                            }
                        }
                    }

                    if (_basePath == "")
                    {
                        string baseRootPath = System.IO.Path.Combine(PathHelper.GetBaseDirectory(), "generate");
                        //if (Directory.Exists(baseRootPath))
                        //{
                        //    DirectoryInfo info = new DirectoryInfo(baseRootPath);
                        //    _basePath = info.Parent.FullName;
                        //}
                        _basePath = baseRootPath;
                    }
                    //}

                    databaseConfig.CodeGenBaseDirectory = _basePath;



                    //databaseConfig.EnableConnectionPool = settings.EnableConnectionPool;
                    //databaseConfig.EnableLogConnectionPool = settings.EnableLogConnectionPool;
                    //databaseConfig.MinIdle = settings.MinIdle;
                    //databaseConfig.MaxIdle = settings.MaxIdle;
                    //databaseConfig.InitialSize = settings.InitialSize;

                    //databaseConfig.MaxWaitMillis = settings.MaxWaitMillis;
                    //databaseConfig.MaxTotal = settings.MaxTotal;
                    //databaseConfig.TimeBetweenEvictionRunsMillis = settings.TimeBetweenEvictionRunsMillis;
                    //databaseConfig.MinEvictableIdleTimeMillis = settings.MinEvictableIdleTimeMillis;
                    //databaseConfig.EnableRemoveAbandoned = settings.EnableRemoveAbandoned;
                    //databaseConfig.RemoveAbandonedOnBorrow = settings.RemoveAbandonedOnBorrow;
                    //databaseConfig.RemoveAbandonedOnMaintenance = settings.RemoveAbandonedOnMaintenance;
                    //databaseConfig.RemoveAbandonedTimeout = settings.RemoveAbandonedTimeout;
                    //databaseConfig.NumTestsPerEvictionRun = settings.NumTestsPerEvictionRun;
                    //databaseConfig.SoftMinEvictableIdleTimeMillis = settings.SoftMinEvictableIdleTimeMillis;
                    //databaseConfig.TestOnBorrow = settings.TestOnBorrow;
                    //databaseConfig.TestOnCreate = settings.TestOnCreate;
                    //databaseConfig.TestOnReturn = settings.TestOnReturn;
                    //databaseConfig.TestWhileIdle = settings.TestWhileIdle;
                    //databaseConfig.ValidationQuery = settings.ValidationQuery;



                    databaseConfig.EnableLobConverter    = settings.EnableLobConverter;
                    databaseConfig.LobConverterClassName = settings.LobConverterClassName;
                    if (databaseConfig.EnableLobConverter == true)
                    {
                        try
                        {
                            Type type = Type.GetType(databaseConfig.LobConverterClassName);

                            if (type != null)
                            {
                                object obj = Activator.CreateInstance(type, true);

                                LobConverter.Init((ILobParameterConverter)(obj), databaseConfig.EnableLobConverter);
                            }
                            else
                            {
                                Log("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName, new ArgumentException("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName), MessageType.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName, new ArgumentException("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName), MessageType.Error);

                            throw new ArgumentException("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName, ex);
                        }
                    }
                    databaseConfig.BulkOperateClassName = settings.BulkOperateClassName;
                    databaseConfig.EnableDefaultPropertySecurityValidate = settings.EnableDefaultPropertySecurityValidate;

                    databaseConfig.PropertySecurityValidateClassName = settings.PropertySecurityValidateClassName;

                    if (!string.IsNullOrEmpty(settings.BulkOperateClassName))
                    {
                        try
                        {
                            Type type = Type.GetType(settings.BulkOperateClassName);

                            if (type != null)
                            {
                                IBulkOperate obj = (IBulkOperate)Activator.CreateInstance(type, true);
                                BulkOperateManage.Instance.Register(settings.BulkOperateClassName, obj);
                            }
                            else
                            {
                                Log("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName, new ArgumentException("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName), MessageType.Error);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName, new ArgumentException("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName), MessageType.Error);

                            throw new ArgumentException("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName, ex);
                        }
                    }


                    if (!string.IsNullOrEmpty(settings.PropertySecurityValidateClassName))
                    {
                        try
                        {
                            Type type = Type.GetType(settings.PropertySecurityValidateClassName);

                            if (type != null)
                            {
                                IPropertySecurityValidate obj = (IPropertySecurityValidate)Activator.CreateInstance(type, true);
                                PropertySecurityValidateManage.Instance.Register(settings.PropertySecurityValidateClassName, obj);
                            }
                            else
                            {
                                Log("IPropertySecurityValidate 无法找到实现类, 将启用默认的安全校验器!");
                            }
                        }
                        catch (Exception ex)
                        {
                            Log("IPropertySecurityValidate 无法找到实现类, 将启用默认的安全校验器!");

                            // throw new ArgumentException("没有找到相关IBulkOperate实现类,PropertySecurityValidateClassName: " + settings.PropertySecurityValidateClassName, ex);
                        }
                    }
                }

                try
                {
                    if (config.DataSources != null)
                    {
                        string ConnectionString = "", ProviderName = "";
                        databaseConfig.DataSources = config.DataSources;

                        foreach (var item in config.DataSources)
                        {
                            if (item.IsMaster == true)//是否主数据库
                            {
                                ConnectionString = item.ConnectionString;
                                ProviderName     = item.Provider;
                                break;
                            }
                        }

                        metaInfo = DbConnectionFactory.CreateConnection(ConnectionString, ProviderName);
                    }
                    else
                    {
                        Log("DataSources 不能为空,且必须存在一个Master的数据源!", new ArgumentException("DataSources 不能为空,且必须存在一个Master的数据源!"), MessageType.Error);
                    }
                }
                catch (Exception ex)
                {
                    Log("DataSources 不能为空,且必须存在一个Master的数据源!", ex, MessageType.Error);

                    throw new ArgumentException("DataSources 不能为空,且必须存在一个Master的数据源!", ex);
                }



                if (config.MapperSources != null)
                {
                    Assembly ass = null;
                    string   _MapperSourcePath = "";
                    string   path = "";
                    MapperSource.MapperAssemblyType _MapperAssemblyType = MapperSource.MapperAssemblyType.ClassType;
                    try
                    {
                        databaseConfig.MappingAssemblies.Clear();

                        foreach (var item in config.MapperSources)
                        {
                            _MapperAssemblyType = item.Type;
                            if (item.Type == MapperSource.MapperAssemblyType.File)
                            {
                                _MapperSourcePath = item.Path;
                                path = FileLoader.GetPath(item.Path);
                                ass  = Assembly.LoadFrom(path);
                                databaseConfig.MappingAssemblies.Add(ass);
                            }
                            else if (item.Type == MapperSource.MapperAssemblyType.ClassType)
                            {
                                path = item.ClassName;

                                Type type = Type.GetType(item.ClassName);
                                if (type != null)
                                {
                                    ass = type.Assembly;
                                    if (ass != null)
                                    {
                                        databaseConfig.MappingAssemblies.Add(ass);
                                    }
                                }
                                else
                                {
                                    Log("MapperSource 中存在不正确的Type:" + item.ClassName, new ArgumentException("MapperSource 中存在不正确的Type:" + item.ClassName), MessageType.Error);
                                }
                            }
                        }


                        foreach (var item in PureDataConfigurationLoader.MapperSourceAssemblies)
                        {
                            if (item != null)
                            {
                                databaseConfig.MappingAssemblies.Add(item);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log("Load MapperSource error on :" + _MapperAssemblyType + ", " + _MapperSourcePath + " , path:" + path, ex, MessageType.Error);
                        throw new ArgumentException("Load MapperSource error on :" + _MapperAssemblyType + ", " + _MapperSourcePath, ex);
                    }
                }



                if (config.SqlMapSources != null)
                {
                    var dirSqlMappers  = config.SqlMapSources.Where(p => p.Type == ResourceType.Directory);
                    var fileSqlMappers = config.SqlMapSources.Where(p => p.Type == ResourceType.File);

                    databaseConfig.SqlMapDirPaths  = dirSqlMappers.Select(p => p.Path).ToList();
                    databaseConfig.SqlMapFilePaths = fileSqlMappers.Select(p => p.Path).ToList();

                    foreach (var item in PureDataConfigurationLoader.SqlMapDirPaths)
                    {
                        if (item != null)
                        {
                            databaseConfig.SqlMapDirPaths.Add(item);
                        }
                    }
                    foreach (var item in PureDataConfigurationLoader.SqlMapFilePaths)
                    {
                        if (item != null)
                        {
                            databaseConfig.SqlMapFilePaths.Add(item);
                        }
                    }
                }

                try
                {
                    if (databaseConfig.EnableIntercept == true)
                    {
                        databaseConfig.Interceptors.Clear();

                        //if (databaseConfig.EnableDebug && databaseConfig.EnableIntercept)
                        //{
                        //    databaseConfig.Interceptors.Add(OutputSQLIntercept.Instance);
                        //    databaseConfig.Interceptors.Add(OutputExceptionIntercept.Instance);
                        //}

                        if (config.Interceptors != null)
                        {
                            IInterceptor ass  = null;
                            string       path = "";

                            foreach (var item in config.Interceptors)
                            {
                                ass = null;
                                if (string.IsNullOrEmpty(item.ClassFullName) || string.IsNullOrEmpty(item.AssemblyName))
                                {
                                    continue;
                                }
                                if (item.Type == InterceptorSource.InterceptorType.ConnectionInterceptor)
                                {
                                    ass = ReflectionHelper.CreateInstance <IConnectionInterceptor>(item.ClassFullName, item.AssemblyName);
                                }
                                else if (item.Type == InterceptorSource.InterceptorType.ExecutingInterceptor)
                                {
                                    ass = ReflectionHelper.CreateInstance <IExecutingInterceptor>(item.ClassFullName, item.AssemblyName);
                                }
                                else if (item.Type == InterceptorSource.InterceptorType.ExceptionInterceptor)
                                {
                                    ass = ReflectionHelper.CreateInstance <IExceptionInterceptor>(item.ClassFullName, item.AssemblyName);
                                }
                                else if (item.Type == InterceptorSource.InterceptorType.DataInterceptor)
                                {
                                    ass = ReflectionHelper.CreateInstance <IDataInterceptor>(item.ClassFullName, item.AssemblyName);
                                }
                                else if (item.Type == InterceptorSource.InterceptorType.TransactionInterceptor)
                                {
                                    ass = ReflectionHelper.CreateInstance <ITransactionInterceptor>(item.ClassFullName, item.AssemblyName);
                                }

                                if (ass != null)
                                {
                                    databaseConfig.Interceptors.Add(ass);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log("Load Intercept error  !", ex, MessageType.Error);
                    throw new ArgumentException("Load Intercept error  !", ex);
                }



                if (config.CodeGenTemplates != null)
                {
                    databaseConfig.CodeGenTemplates = config.CodeGenTemplates;
                }
            }

            return(metaInfo);
        }
Beispiel #38
0
 protected virtual ISession OpenSession(IInterceptor sessionLocalInterceptor)
 {
     return(Sfi.WithOptions().Interceptor(sessionLocalInterceptor).OpenSession());
 }
Beispiel #39
0
 public Interceptor(MethodInfo method, IInterceptor <TRequest, TResponse> interceptor)
 {
     this.method      = method;
     this.interceptor = interceptor;
 }
Beispiel #40
0
 /// <summary>
 /// Delegate opening session to <see cref="IConversation"/>
 /// </summary>
 /// <param name="sessionFactory">The factory to use for this type</param>
 /// <param name="interceptor">An interceptor to include</param>
 /// <returns>A valid session from the <see cref="ISessionFactory"/>.</returns>
 public override ISession OpenSession(ISessionFactory sessionFactory, IInterceptor interceptor)
 {
     return(conversation.GetSession(sessionFactory, interceptor));
 }
 public Container(IInterceptor interceptor)
 {
     _interceptor = interceptor;
 }
 /// <summary>
 /// Generates a proxy implementing all the specified interfaces and
 /// redirecting method invocations to the specifed interceptor.
 /// </summary>
 /// <param name="theInterface">Interface to be implemented</param>
 /// <param name="interceptor">instance of <see cref="IInterceptor"/></param>
 /// <param name="target">The target object.</param>
 /// <returns>Proxy instance</returns>
 public override object CreateProxy(Type theInterface, IInterceptor interceptor, object target)
 {
     return(CreateProxy(new Type[] { theInterface }, interceptor, target));
 }
Beispiel #43
0
        public void AfterPropertiesSet(IBeanContextFactory beanContextFactory)
        {
            ParamChecker.AssertNotNull(ProxyFactory, "ProxyFactory");

            IBeanConfiguration serviceResultcache = beanContextFactory.RegisterBean <ServiceResultCache>().Autowireable <IServiceResultCache>();

            beanContextFactory.Link(serviceResultcache, "HandleClearAllCaches").To <IEventListenerExtendable>().With(typeof(ClearAllCachesEvent));

            beanContextFactory.RegisterBean <ValueHolderIEC>().Autowireable(typeof(ValueHolderIEC), typeof(IProxyHelper));

            beanContextFactory.RegisterBean <CacheHelper>().Autowireable(typeof(ICacheHelper), typeof(ICachePathHelper), typeof(IPrefetchHelper));

            IBeanConfiguration prioMembersProvider = beanContextFactory.RegisterBean <PrioMembersProvider>().Autowireable <IPrioMembersProvider>();

            beanContextFactory.Link(prioMembersProvider, PrioMembersProvider.handleMetaDataAddedEvent).To <IEventListenerExtendable>()
            .With(typeof(IEntityMetaDataEvent));

            beanContextFactory.RegisterBean <CacheWalker>().Autowireable <ICacheWalker>();

            beanContextFactory.RegisterAutowireableBean <ICacheMapEntryTypeProvider, CacheMapEntryTypeProvider>();

            beanContextFactory.RegisterAutowireableBean <IRootCacheValueFactory, RootCacheValueFactory>();

            //IBeanConfiguration rootCache = beanContextFactory.registerBean<RootCache>("rootCache").autowireable(typeof(RootCache), typeof(IWritableCache));
            //if (IsUseSingleChildCache)
            //{
            //    beanContextFactory.registerBean<SingletonCacheFactory>("cacheFactory")
            //        .propertyRefs("singletonChildCache")
            //        .autowireable<ICacheFactory>();

            //    IWritableCache childCache = (IWritableCache)beanContextFactory.registerBean<ChildCache>("singletonChildCache")
            //        .propertyRefs("rootCache")
            //        .autowireable(typeof(ICache)).GetInstance();

            //    ((RootCache)rootCache.GetInstance()).AddChildCache(childCache);
            //}
            //else
            //{
            //    rootCache.autowireable(typeof(ICache), typeof(IWritableCache), typeof(ICacheFactory));
            //}

            //beanContextFactory.registerBean<RootCache>(ROOT_CACHE).autowireable<RootCache>();
            //beanContextFactory.Link("rootCache").To<IOfflineListenerExtendable>();

            beanContextFactory.RegisterBean <CacheRetrieverRegistry>(ROOT_CACHE_RETRIEVER).Autowireable(typeof(ICacheServiceByNameExtendable), typeof(ICacheRetrieverExtendable));

            beanContextFactory.RegisterBean <FirstLevelCacheManager>("firstLevelCacheManager").Autowireable(typeof(IFirstLevelCacheExtendable), typeof(IFirstLevelCacheManager));

            String rootCacheBridge = "rootCacheBridge";

            beanContextFactory.RegisterBean <RootCacheBridge>(rootCacheBridge).PropertyRefs(COMMITTED_ROOT_CACHE, ROOT_CACHE_RETRIEVER);

            TransactionalRootCacheInterceptor txRcInterceptor = new TransactionalRootCacheInterceptor();

            beanContextFactory.RegisterWithLifecycle("txRootCacheInterceptor", txRcInterceptor).PropertyRefs(COMMITTED_ROOT_CACHE, rootCacheBridge)
            .Autowireable(typeof(ITransactionalRootCache), typeof(ISecondLevelCacheManager));

            Object txRcProxy = ProxyFactory.CreateProxy(new Type[] { typeof(IRootCache), typeof(ICacheIntern), typeof(IOfflineListener) }, txRcInterceptor);

            beanContextFactory.RegisterExternalBean(ROOT_CACHE, txRcProxy).Autowireable(typeof(IRootCache), typeof(ICacheIntern));

            if (IsSecondLevelCacheActive)
            {
                // One single root cache instance for whole context
                beanContextFactory.RegisterBean <RootCache>(COMMITTED_ROOT_CACHE).PropertyRef("CacheRetriever", ROOT_CACHE_RETRIEVER)
                .PropertyValue("Privileged", true);
                beanContextFactory.Link(CacheModule.COMMITTED_ROOT_CACHE).To <IOfflineListenerExtendable>();
            }
            else
            {
                // One root cache instance per thread sequence. Most often used in server environment where the "deactivated"
                // second level cache means that each thread hold his own, isolated root cache (which gets cleared with each service
                // request. Effectively this means that the root cache itself only lives per-request and does not hold a longer state
                IInterceptor threadLocalRootCacheInterceptor = (IInterceptor)beanContextFactory
                                                               .RegisterBean <ThreadLocalRootCacheInterceptor>("threadLocalRootCacheInterceptor")
                                                               .PropertyRef("StoredCacheRetriever", CacheModule.ROOT_CACHE_RETRIEVER).PropertyValue("Privileged", true).GetInstance();

                RootCache rootCacheProxy = ProxyFactory.CreateProxy <RootCache>(threadLocalRootCacheInterceptor);

                beanContextFactory.RegisterExternalBean(CacheModule.COMMITTED_ROOT_CACHE, rootCacheProxy).Autowireable <RootCache>();
            }
            beanContextFactory.RegisterBean <CacheEventTargetExtractor>("cacheEventTargetExtractor");
            beanContextFactory.Link("cacheEventTargetExtractor").To <IEventTargetExtractorExtendable>().With(typeof(ICache));

            beanContextFactory.RegisterBean <CacheFactory>().Autowireable <ICacheFactory>();

            IInterceptor cacheProviderInterceptor = (IInterceptor)beanContextFactory
                                                    .RegisterBean <CacheProviderInterceptor>("cacheProviderInterceptor")
                                                    .Autowireable(typeof(ICacheProviderExtendable), typeof(ICacheProvider), typeof(ICacheContext)).GetInstance();

            ICache cacheProxy = ProxyFactory.CreateProxy <ICache>(new Type[] { typeof(ICacheProvider), typeof(IWritableCache) }, cacheProviderInterceptor);

            beanContextFactory.RegisterExternalBean("cache", cacheProxy).Autowireable <ICache>();

            beanContextFactory.RegisterBean <PagingQueryServiceResultProcessor>("pagingQuerySRP");
            beanContextFactory.Link("pagingQuerySRP").To <IServiceResultProcessorExtendable>().With(typeof(IPagingResponse));

            beanContextFactory.RegisterBean <CacheProvider>(CacheNamedBeans.CacheProviderSingleton).PropertyValue("CacheType", CacheType.SINGLETON);

            beanContextFactory.RegisterBean <CacheProvider>(CacheNamedBeans.CacheProviderThreadLocal).PropertyValue("CacheType", CacheType.THREAD_LOCAL);

            beanContextFactory.RegisterBean <CacheProvider>(CacheNamedBeans.CacheProviderPrototype).PropertyValue("CacheType", CacheType.PROTOTYPE);

            String defaultCacheProviderBeanName;

            switch (DefaultCacheType)
            {
            case CacheType.PROTOTYPE:
            {
                defaultCacheProviderBeanName = CacheNamedBeans.CacheProviderPrototype;
                break;
            }

            case CacheType.SINGLETON:
            {
                defaultCacheProviderBeanName = CacheNamedBeans.CacheProviderSingleton;
                break;
            }

            case CacheType.THREAD_LOCAL:
            {
                defaultCacheProviderBeanName = CacheNamedBeans.CacheProviderThreadLocal;
                break;
            }

            case CacheType.DEFAULT:
            {
                defaultCacheProviderBeanName = CacheNamedBeans.CacheProviderThreadLocal;
                break;
            }

            default:
                throw new Exception("Not supported type: " + DefaultCacheType);
            }
            beanContextFactory.Link(defaultCacheProviderBeanName).To <ICacheProviderExtendable>();

            // CacheContextPostProcessor must be registered AFTER CachePostProcessor...
            Object cachePostProcessor = beanContextFactory.RegisterBean <CachePostProcessor>().GetInstance();

            beanContextFactory.RegisterBean <CacheContextPostProcessor>().PropertyValue("CachePostProcessor", cachePostProcessor);

            if (IsNetworkClientMode && IsCacheServiceBeanActive)
            {
                IBeanConfiguration remoteCacheService = beanContextFactory.RegisterBean <ClientServiceBean>(CacheModule.EXTERNAL_CACHE_SERVICE)
                                                        .PropertyValue("Interface", typeof(ICacheService))
                                                        .PropertyValue("SyncRemoteInterface", typeof(ICacheServiceWCF))
                                                        .PropertyValue("AsyncRemoteInterface", typeof(ICacheClient)).Autowireable <ICacheService>();

                beanContextFactory.RegisterAlias(CacheModule.DEFAULT_CACHE_RETRIEVER, CacheModule.EXTERNAL_CACHE_SERVICE);

                // register to all entities in a "most-weak" manner
                beanContextFactory.Link(remoteCacheService).To <ICacheRetrieverExtendable>().With(typeof(Object));
                //beanContextFactory.RegisterAlias(CacheModule.ROOT_CACHE_RETRIEVER, CacheModule.EXTERNAL_CACHE_SERVICE);
                //beanContextFactory.registerBean<CacheServiceDelegate>("cacheService").autowireable<ICacheService>();
            }
            beanContextFactory.RegisterBean <DataObjectMixin>().Autowireable <DataObjectMixin>();
            beanContextFactory.RegisterBean <EntityEqualsMixin>().Autowireable <EntityEqualsMixin>();
            beanContextFactory.RegisterBean <EmbeddedTypeMixin>().Autowireable <EmbeddedTypeMixin>();
            beanContextFactory.RegisterBean <PropertyChangeMixin>().Autowireable(typeof(PropertyChangeMixin),
                                                                                 typeof(IPropertyChangeExtensionExtendable), typeof(ICollectionChangeExtensionExtendable));
            beanContextFactory.RegisterBean <ValueHolderContainerMixin>().Autowireable <ValueHolderContainerMixin>();
        }
Beispiel #44
0
        /// <summary>
        /// Begin a new transaction with the given transaction definition.
        /// </summary>
        /// <param name="transaction">
        /// Transaction object returned by
        /// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.
        /// </param>
        /// <param name="definition">
        /// <see cref="Spring.Transaction.ITransactionDefinition"/> instance, describing
        /// propagation behavior, isolation level, timeout etc.
        /// </param>
        /// <remarks>
        /// Does not have to care about applying the propagation behavior,
        /// as this has already been handled by this abstract manager.
        /// </remarks>
        /// <exception cref="Spring.Transaction.TransactionException">
        /// In the case of creation or system errors.
        /// </exception>
        protected override void DoBegin(object transaction, ITransactionDefinition definition)
        {
            TxScopeTransactionManager.PromotableTxScopeTransactionObject promotableTxScopeTransactionObject =
                ((HibernateTransactionObject)transaction).PromotableTxScopeTransactionObject;
            try
            {
                DoTxScopeBegin(promotableTxScopeTransactionObject, definition);
            }
            catch (Exception e)
            {
                throw new CannotCreateTransactionException("Transaction Scope failure on begin", e);
            }

            HibernateTransactionObject txObject = (HibernateTransactionObject)transaction;

            if (DbProvider != null && TransactionSynchronizationManager.HasResource(DbProvider) &&
                !txObject.ConnectionHolder.SynchronizedWithTransaction)
            {
                throw new IllegalTransactionStateException(
                          "Pre-bound ADO.NET Connection found - HibernateTransactionManager does not support " +
                          "running within AdoTransactionManager if told to manage the DbProvider itself. " +
                          "It is recommended to use a single HibernateTransactionManager for all transactions " +
                          "on a single DbProvider, no matter whether Hibernate or ADO.NET access.");
            }
            ISession session = null;

            try
            {
                if (txObject.SessionHolder == null || txObject.SessionHolder.SynchronizedWithTransaction)
                {
                    IInterceptor interceptor = EntityInterceptor;
                    ISession     newSession  = (interceptor != null ?
                                                SessionFactory.OpenSession(interceptor) : SessionFactory.OpenSession());

                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Opened new Session [" + newSession + "] for Hibernate transaction");
                    }
                    txObject.SetSessionHolder(new SessionHolder(newSession), true);
                }
                txObject.SessionHolder.SynchronizedWithTransaction = true;
                session = txObject.SessionHolder.Session;

                IDbConnection con = session.Connection;
                //TODO isolation level mgmt
                //IsolationLevel previousIsolationLevel =

                if (definition.ReadOnly && txObject.NewSessionHolder)
                {
                    // Just set to NEVER in case of a new Session for this transaction.
                    session.FlushMode = FlushMode.Never;
                }

                if (!definition.ReadOnly && !txObject.NewSessionHolder)
                {
                    // We need AUTO or COMMIT for a non-read-only transaction.
                    FlushMode flushMode = session.FlushMode;
                    if (FlushMode.Never == flushMode)
                    {
                        session.FlushMode = FlushMode.Auto;
                        txObject.SessionHolder.PreviousFlushMode = flushMode;
                    }
                }

                // Add the Hibernate transaction to the session holder.
                // for now pass in tx options isolation level.
                ITransaction   hibernateTx = session.BeginTransaction(definition.TransactionIsolationLevel);
                IDbTransaction adoTx       = GetIDbTransaction(hibernateTx);

                // Add the Hibernate transaction to the session holder.
                txObject.SessionHolder.Transaction = hibernateTx;

                // Register transaction timeout.
                int timeout = DetermineTimeout(definition);
                if (timeout != DefaultTransactionDefinition.TIMEOUT_DEFAULT)
                {
                    txObject.SessionHolder.TimeoutInSeconds = timeout;
                }

                // Register the Hibernate Session's ADO.NET Connection/TX pair for the DbProvider, if set.
                if (DbProvider != null)
                {
                    //investigate passing null for tx.
                    ConnectionHolder conHolder = new ConnectionHolder(con, adoTx);
                    if (timeout != DefaultTransactionDefinition.TIMEOUT_DEFAULT)
                    {
                        conHolder.TimeoutInSeconds = timeout;
                    }
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Exposing Hibernate transaction as ADO transaction [" + con + "]");
                    }
                    TransactionSynchronizationManager.BindResource(DbProvider, conHolder);
                    txObject.ConnectionHolder = conHolder;
                }

                // Bind the session holder to the thread.
                if (txObject.NewSessionHolder)
                {
                    TransactionSynchronizationManager.BindResource(SessionFactory, txObject.SessionHolder);
                }
            }
            catch (Exception ex)
            {
                SessionFactoryUtils.CloseSession(session);
                throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
            }
        }
Beispiel #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AbstractBatcher"/> class.
 /// </summary>
 /// <param name="connectionManager">The <see cref="ConnectionManager"/> owning this batcher.</param>
 /// <param name="interceptor"></param>
 protected AbstractBatcher(ConnectionManager connectionManager, IInterceptor interceptor)
 {
     this.connectionManager = connectionManager;
     this.interceptor       = interceptor;
     factory = connectionManager.Factory;
 }
Beispiel #46
0
        public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
        {
            Init();
            log.Info("building session factory");

            properties          = new Dictionary <string, string>(cfg.Properties);
            interceptor         = cfg.Interceptor;
            this.settings       = settings;
            sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions);
            eventListeners      = listeners;
            filters             = new Dictionary <string, FilterDefinition>(cfg.FilterDefinitions);
            if (log.IsDebugEnabled)
            {
                log.Debug("Session factory constructed with filter configurations : " + CollectionPrinter.ToString(filters));
            }

            if (log.IsDebugEnabled)
            {
                log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties));
            }

            try
            {
                if (settings.IsKeywordsImportEnabled)
                {
                    SchemaMetadataUpdater.Update(this);
                }
                if (settings.IsAutoQuoteEnabled)
                {
                    SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
                }
            }
            catch (NotSupportedException)
            {
                // Ignore if the Dialect does not provide DataBaseSchema
            }

            #region Caches
            settings.CacheProvider.Start(properties);
            #endregion

            #region Generators
            identifierGenerators = new Dictionary <string, IIdentifierGenerator>();
            foreach (PersistentClass model in cfg.ClassMappings)
            {
                if (!model.IsInherited)
                {
                    IIdentifierGenerator generator =
                        model.Identifier.CreateIdentifierGenerator(settings.Dialect, settings.DefaultCatalogName,
                                                                   settings.DefaultSchemaName, (RootClass)model);

                    identifierGenerators[model.EntityName] = generator;
                }
            }
            #endregion

            #region Persisters

            Dictionary <string, ICacheConcurrencyStrategy> caches = new Dictionary <string, ICacheConcurrencyStrategy>();
            entityPersisters        = new Dictionary <string, IEntityPersister>();
            implementorToEntityName = new Dictionary <System.Type, string>();

            Dictionary <string, IClassMetadata> classMeta = new Dictionary <string, IClassMetadata>();

            foreach (PersistentClass model in cfg.ClassMappings)
            {
                model.PrepareTemporaryTables(mapping, settings.Dialect);
                string cacheRegion = model.RootClazz.CacheRegionName;
                ICacheConcurrencyStrategy cache;
                if (!caches.TryGetValue(cacheRegion, out cache))
                {
                    cache =
                        CacheFactory.CreateCache(model.CacheConcurrencyStrategy, cacheRegion, model.IsMutable, settings, properties);
                    if (cache != null)
                    {
                        caches.Add(cacheRegion, cache);
                        if (!allCacheRegions.TryAdd(cache.RegionName, cache.Cache))
                        {
                            throw new HibernateException("An item with the same key has already been added to allCacheRegions.");
                        }
                    }
                }
                IEntityPersister cp = PersisterFactory.CreateClassPersister(model, cache, this, mapping);
                entityPersisters[model.EntityName] = cp;
                classMeta[model.EntityName]        = cp.ClassMetadata;

                if (model.HasPocoRepresentation)
                {
                    implementorToEntityName[model.MappedClass] = model.EntityName;
                }
            }
            classMetadata = new UnmodifiableDictionary <string, IClassMetadata>(classMeta);

            Dictionary <string, ISet <string> > tmpEntityToCollectionRoleMap = new Dictionary <string, ISet <string> >();
            collectionPersisters = new Dictionary <string, ICollectionPersister>();
            foreach (Mapping.Collection model in cfg.CollectionMappings)
            {
                ICacheConcurrencyStrategy cache =
                    CacheFactory.CreateCache(model.CacheConcurrencyStrategy, model.CacheRegionName, model.Owner.IsMutable, settings,
                                             properties);
                if (cache != null)
                {
                    allCacheRegions[cache.RegionName] = cache.Cache;
                }
                ICollectionPersister persister = PersisterFactory.CreateCollectionPersister(cfg, model, cache, this);
                collectionPersisters[model.Role] = persister;
                IType indexType = persister.IndexType;
                if (indexType != null && indexType.IsAssociationType && !indexType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)indexType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
                IType elementType = persister.ElementType;
                if (elementType.IsAssociationType && !elementType.IsAnyType)
                {
                    string        entityName = ((IAssociationType)elementType).GetAssociatedEntityName(this);
                    ISet <string> roles;
                    if (!tmpEntityToCollectionRoleMap.TryGetValue(entityName, out roles))
                    {
                        roles = new HashSet <string>();
                        tmpEntityToCollectionRoleMap[entityName] = roles;
                    }
                    roles.Add(persister.Role);
                }
            }
            Dictionary <string, ICollectionMetadata> tmpcollectionMetadata = new Dictionary <string, ICollectionMetadata>(collectionPersisters.Count);
            foreach (KeyValuePair <string, ICollectionPersister> collectionPersister in collectionPersisters)
            {
                tmpcollectionMetadata.Add(collectionPersister.Key, collectionPersister.Value.CollectionMetadata);
            }
            collectionMetadata = new UnmodifiableDictionary <string, ICollectionMetadata>(tmpcollectionMetadata);
            collectionRolesByEntityParticipant = new UnmodifiableDictionary <string, ISet <string> >(tmpEntityToCollectionRoleMap);
            #endregion

            #region Named Queries
            namedQueries         = new Dictionary <string, NamedQueryDefinition>(cfg.NamedQueries);
            namedSqlQueries      = new Dictionary <string, NamedSQLQueryDefinition>(cfg.NamedSQLQueries);
            sqlResultSetMappings = new Dictionary <string, ResultSetMappingDefinition>(cfg.SqlResultSetMappings);
            #endregion

            imports = new Dictionary <string, string>(cfg.Imports);

            #region after *all* persisters and named queries are registered
            foreach (IEntityPersister persister in entityPersisters.Values)
            {
                persister.PostInstantiate();
            }
            foreach (ICollectionPersister persister in collectionPersisters.Values)
            {
                persister.PostInstantiate();
            }
            #endregion

            #region Serialization info

            name = settings.SessionFactoryName;
            try
            {
                uuid = (string)UuidGenerator.Generate(null, null);
            }
            catch (Exception)
            {
                throw new AssertionFailure("Could not generate UUID");
            }

            SessionFactoryObjectFactory.AddInstance(uuid, name, this, properties);

            #endregion

            log.Debug("Instantiated session factory");

            #region Schema management
            if (settings.IsAutoCreateSchema)
            {
                new SchemaExport(cfg).Create(false, true);
            }

            if (settings.IsAutoUpdateSchema)
            {
                new SchemaUpdate(cfg).Execute(false, true);
            }
            if (settings.IsAutoValidateSchema)
            {
                new SchemaValidator(cfg, settings).Validate();
            }
            if (settings.IsAutoDropSchema)
            {
                schemaExport = new SchemaExport(cfg);
            }
            #endregion

            #region Obtaining TransactionManager
            // not ported yet
            #endregion

            currentSessionContext = BuildCurrentSessionContext();

            if (settings.IsQueryCacheEnabled)
            {
                updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
                queryCache            = settings.QueryCacheFactory.GetQueryCache(null, updateTimestampsCache, settings, properties);
                queryCaches           = new ConcurrentDictionary <string, IQueryCache>();
            }
            else
            {
                updateTimestampsCache = null;
                queryCache            = null;
                queryCaches           = null;
            }

            #region Checking for named queries
            if (settings.IsNamedQueryStartupCheckingEnabled)
            {
                IDictionary <string, HibernateException> errors = CheckNamedQueries();
                if (errors.Count > 0)
                {
                    StringBuilder failingQueries = new StringBuilder("Errors in named queries: ");
                    foreach (KeyValuePair <string, HibernateException> pair in errors)
                    {
                        failingQueries.Append('{').Append(pair.Key).Append('}');
                        log.Error("Error in named query: " + pair.Key, pair.Value);
                    }
                    throw new HibernateException(failingQueries.ToString());
                }
            }
            #endregion

            Statistics.IsStatisticsEnabled = settings.IsStatisticsEnabled;

            // EntityNotFoundDelegate
            IEntityNotFoundDelegate enfd = cfg.EntityNotFoundDelegate;
            if (enfd == null)
            {
                enfd = new DefaultEntityNotFoundDelegate();
            }
            entityNotFoundDelegate = enfd;
        }
Beispiel #47
0
 protected virtual ISession OpenSession(IInterceptor sessionLocalInterceptor)
 {
     lastOpenedSession = sessions.OpenSession(sessionLocalInterceptor);
     return(lastOpenedSession);
 }
Beispiel #48
0
        private SessionImpl OpenSession(IDbConnection connection, bool autoClose, long timestamp, IInterceptor sessionLocalInterceptor)
        {
#pragma warning disable 618
            var isInterceptorsBeforeTransactionCompletionIgnoreExceptionsEnabled = settings.IsInterceptorsBeforeTransactionCompletionIgnoreExceptionsEnabled;
#pragma warning restore 618

            SessionImpl session = new SessionImpl(connection, this, autoClose, timestamp, sessionLocalInterceptor ?? interceptor,
                                                  settings.DefaultEntityMode, settings.IsFlushBeforeCompletionEnabled,
                                                  settings.IsAutoCloseSessionEnabled, isInterceptorsBeforeTransactionCompletionIgnoreExceptionsEnabled,
                                                  settings.ConnectionReleaseMode, settings.DefaultFlushMode);

            if (sessionLocalInterceptor != null)
            {
                // NH specific feature
                sessionLocalInterceptor.SetSession(session);
            }
            return(session);
        }
        public TReturn Get <TQuery, TReturn>(Func <IQueryable <TQuery>, TReturn> query, IInterceptor queryInterceptor, bool stateless = true) where TQuery : class
        {
            TReturn result;

            if (stateless)
            {
                using (var session = _sessionFactory.OpenStatelessSession())
                {
                    result = query.Invoke(session.Query <TQuery>());
                }
            }
            else
            {
                using (var session = _sessionFactory.OpenSession(queryInterceptor))
                {
                    result = query.Invoke(session.Query <TQuery>());
                }
            }

            return(result);
        }
 /// <summary>
 /// Initialize a new instance of <see cref="SessionPerConversationScopeSettings"/> with the given values and references.
 /// </summary>
 /// <param name="entityInterceptor">
 /// Specify the <see cref="IInterceptor"/> to be set on each session provided by the <see cref="SessionPerConversationScope"/> instance.
 /// </param>
 /// <param name="defaultFlushMode">
 /// Specify the flushmode to be applied on each session provided by the <see cref="SessionScope"/> instance.
 /// </param>
 /// <remarks>
 /// Calling this constructor marks all properties initialized.
 /// </remarks>
 public SessionPerConversationScopeSettings(IInterceptor entityInterceptor, FlushMode defaultFlushMode)
 {
     this.entityInterceptor = entityInterceptor;
     this.defaultFlushMode  = defaultFlushMode;
 }
 public List <T> Get <T>(Func <IQueryable <T>, List <T> > query, IInterceptor queryInterceptor, bool stateless = true) where T : class
 {
     return(Get <T, List <T> >(query, queryInterceptor, stateless));
 }
 /// <summary>
 /// Initialize a new instance of <see cref="SessionScopeSettings"/> with default values.
 /// </summary>
 /// <remarks>
 /// Calling this constructor from your derived class leaves <see cref="EntityInterceptor"/>
 /// uninitialized. See <see cref="ResolveEntityInterceptor"/> for more.
 /// </remarks>
 public SessionPerConversationScopeSettings()
 {
     this.entityInterceptor = null;
     this.defaultFlushMode  = FLUSHMODE_DEFAULT;
 }
Beispiel #53
0
 public object Adapt(object value, IInterceptor interceptor)
 {
     return(_inner.Adapt(value, interceptor));
 }
        /// <summary>
        /// Allows you to set the interceptor which will be used in all subsequent sessions
        /// </summary>
        public void RegisterInterceptor(IInterceptor interceptor)
        {
            Check.Require(interceptor != null, "interceptor may not be null");

            _registeredInterceptor = interceptor;
        }
Beispiel #55
0
 public MyUserServiceProxy(User user, IInterceptor interceptor)
 {
     _user        = user;
     _interceptor = interceptor;
 }
 ISessionBuilder ISessionBuilder <ISessionBuilder> .Interceptor(IInterceptor interceptor)
 {
     _actualBuilder.Interceptor(interceptor);
     return(this);
 }
Beispiel #57
0
 public NHibernateConfig AddInterceptor(IInterceptor interceptor)
 {
     interceptors.Add(interceptor);
     return(this);
 }
Beispiel #58
0
 public ExampleInstaller(IInterceptor interceptor)
 {
     this.interceptor = Maybe.Some(interceptor);
 }
 public void AddChild(IInterceptor interceptor)
 {
     _childs.Add(interceptor);
 }
        private static ISession DoGetSession(
            ISessionFactory sessionFactory, IInterceptor entityInterceptor,
            IAdoExceptionTranslator adoExceptionTranslator, bool allowCreate)
        {
            AssertUtils.ArgumentNotNull(sessionFactory, "sessionFactory", "SessionFactory can not be null");

            SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(sessionFactory);

            if (sessionHolder != null && !sessionHolder.IsEmpty)
            {
                // pre-bound Hibernate Session
                ISession session = null;
                if (TransactionSynchronizationManager.SynchronizationActive &&
                    sessionHolder.DoesNotHoldNonDefaultSession)
                {
                    // Spring transaction management is active ->
                    // register pre-bound Session with it for transactional flushing.
                    session = sessionHolder.ValidatedSession;
                    if (!sessionHolder.SynchronizedWithTransaction)
                    {
                        log.Debug("Registering Spring transaction synchronization for existing Hibernate Session");
                        TransactionSynchronizationManager.RegisterSynchronization(
                            new SpringSessionSynchronization(sessionHolder, sessionFactory, adoExceptionTranslator, false));
                        sessionHolder.SynchronizedWithTransaction = true;
                        // Switch to FlushMode.AUTO if we're not within a read-only transaction.
                        FlushMode flushMode = session.FlushMode;
                        if (FlushMode.Never == flushMode &&
                            !TransactionSynchronizationManager.CurrentTransactionReadOnly)
                        {
                            session.FlushMode = FlushMode.Auto;
                            sessionHolder.PreviousFlushMode = flushMode;
                        }
                    }
                }
                else
                {
                    // No Spring transaction management active -> simply return default thread-bound Session, if any
                    // (possibly from OpenSessionInViewModule)
                    session = sessionHolder.ValidatedSession;
                }

                if (session != null)
                {
                    return(session);
                }
            }


            ISession sess = OpenSession(sessionFactory, entityInterceptor);

            // Set Session to FlushMode.Never if we're within a read-only transaction.
            // Use same Session for further Hibernate actions within the transaction.
            // Thread object will get removed by synchronization at transaction completion.
            if (TransactionSynchronizationManager.SynchronizationActive)
            {
                log.Debug("Registering Spring transaction synchronization for new Hibernate Session");
                SessionHolder holderToUse = sessionHolder;
                if (holderToUse == null)
                {
                    holderToUse = new SessionHolder(sess);
                }
                else
                {
                    holderToUse.AddSession(sess);
                }
                if (TransactionSynchronizationManager.CurrentTransactionReadOnly)
                {
                    sess.FlushMode = FlushMode.Never;
                }
                TransactionSynchronizationManager.RegisterSynchronization(
                    new SpringSessionSynchronization(holderToUse, sessionFactory, adoExceptionTranslator, true));
                holderToUse.SynchronizedWithTransaction = true;
                if (holderToUse != sessionHolder)
                {
                    TransactionSynchronizationManager.BindResource(sessionFactory, holderToUse);
                }
            }



            // Check whether we are allowed to return the Session.
            if (!allowCreate && !IsSessionTransactional(sess, sessionFactory))
            {
                CloseSession(sess);
                throw new InvalidOperationException("No Hibernate Session bound to thread, " +
                                                    "and configuration does not allow creation of non-transactional one here");
            }

            return(sess);
        }