public void WhenNotConfiguredAndLog4NetExistsThenUseLog4NetFactory()
        {
            Assume.That(TestsContext.ExecutingWithVsTest, Is.False);

            // NoLoggingNHibernateLogger is internal
            Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.Not.EqualTo("NoLoggingNHibernateLogger"));
        }
        public void WhenNoLoggingFactoryIsUsedThenNoLoggingNHibernateLoggerIsReturned()
        {
            LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());

            // NoLoggingNHibernateLogger is internal
            Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.EqualTo("NoLoggingNHibernateLogger"));
        }
        public void WhenConfiguredAsNullThenNoLoggingFactoryIsUsed()
        {
            NHibernateLogger.SetLoggersFactory(default(INHibernateLoggerFactory));

            // NoLoggingNHibernateLogger is internal
            Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.EqualTo("NoLoggingNHibernateLogger"));
        }
        static CoreMemoryCacheProvider()
        {
            Log = NHibernateLogger.For(typeof(CoreMemoryCacheProvider));
            ConfiguredCachesProperties = new Dictionary <string, IDictionary <string, string> >();

            if (!(ConfigurationManager.GetSection("corememorycache") is CacheConfig config))
            {
                return;
            }

            if (config.ExpirationScanFrequency != null)
            {
                if (int.TryParse(config.ExpirationScanFrequency, out var minutes))
                {
                    ExpirationScanFrequency = TimeSpan.FromMinutes(minutes);
                }
                else if (TimeSpan.TryParse(config.ExpirationScanFrequency, out var expirationScanFrequency))
                {
                    ExpirationScanFrequency = expirationScanFrequency;
                }
                if (!ExpirationScanFrequency.HasValue)
                {
                    Log.Warn(
                        "Invalid value '{0}' for expiration-scan-frequency setting: it is neither an int nor a TimeSpan. Ignoring.",
                        config.ExpirationScanFrequency);
                }
            }

            foreach (var cache in config.Regions)
            {
                ConfiguredCachesProperties.Add(cache.Region, cache.Properties);
            }
        }
        /// <summary>
        /// Initializes the <see cref="SysCacheProvider"/> class.
        /// </summary>
        static SysCacheProvider()
        {
            Log = NHibernateLogger.For(typeof(SysCacheProvider));
            // We need to determine which cache regions are configured in the configuration file, but we cant create the
            // cache regions at this time because there could be nhibernate configuration values
            // that we need for the cache regions such as connection info to be used for data dependencies. But this info
            // isn't available until build cache is called. So allocate space but only create them on demand.

            var configSection = SysCacheSection.GetSection();

            if (configSection != null && configSection.CacheRegions.Count > 0)
            {
                CacheRegionSettings = new Dictionary <string, CacheRegionElement>(configSection.CacheRegions.Count);
                foreach (var cacheRegion in configSection.CacheRegions)
                {
                    if (cacheRegion is CacheRegionElement element)
                    {
                        CacheRegionSettings.Add(element.Name, element);
                    }
                }
            }
            else
            {
                CacheRegionSettings = new Dictionary <string, CacheRegionElement>(0);
                Log.Info(
                    "No cache regions specified. Cache regions can be specified in sysCache configuration section with custom settings.");
            }
        }
Пример #6
0
        private static Configuration AddSchemaValidationAndMigration(this Configuration config)
        {
            var logger = NHibernateLogger.For(typeof(SessionFactory));

            System.Action <string> updateExport = x =>
            {
                if (logger != null)
                {
                    logger.Info(x);
                }
            };

            var update = new SchemaUpdate(config);

            try
            {
                update.Execute(updateExport, true);
                if (update.Exceptions != null && update.Exceptions.Count > 0)
                {
                    throw new AggregateException("Multiple exceptions occurred while executing database migrations. Check the inner list of exceptions.", update.Exceptions.ToArray());
                }
            }
            catch (Exception)
            {
                throw;
            }

            return(config);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AssertionFailureException"/> class.
        /// </summary>
        public AssertionFailureException()
            : base(string.Empty)
        {
#if NETFX
            LoggerProvider.LoggerFor(typeof(AssertionFailureException)).Error(defMessage);
#else
            NHibernateLogger.For(typeof(AssertionFailureException)).Error(defMessage);
#endif
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AssertionFailureException"/> class.
        /// </summary>
        /// <param name="message">The message that describes the error. </param>
        /// <param name="innerException">
        /// The exception that is the cause of the current exception. If the innerException parameter
        /// is not a null reference, the current exception is raised in a catch block that handles
        /// the inner exception.
        /// </param>
        public AssertionFailureException(string message, Exception innerException)
            : base(message, innerException)
        {
#if NETFX
            LoggerProvider.LoggerFor(typeof(AssertionFailureException)).Error(defMessage);
#else
            NHibernateLogger.For(typeof(AssertionFailureException)).Error(defMessage);
#endif
        }
Пример #9
0
        public void WhenNotConfiguredAndLog4NetExistsThenUseLog4NetFactory()
        {
#pragma warning disable 618
            Assert.That(NHibernateLogger.For("pizza"), Is.Not.InstanceOf <NoLoggingInternalLogger>());
#pragma warning restore 618

            // NoLoggingNHibernateLogger is internal
            Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.Not.EqualTo("NoLoggingNHibernateLogger"));
        }
 static MemCacheProvider()
 {
     log    = NHibernateLogger.For(typeof(MemCacheProvider));
     config = ConfigurationManager.GetSection("enyim.com/memcached") as IMemcachedClientConfiguration;
     if (config == null)
     {
         log.Info("enyim.com/memcached configuration section not found, using default configuration (127.0.0.1:11211).");
         config = new MemcachedClientConfiguration();
         config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11211));
     }
 }
Пример #11
0
        /// <summary>
        /// Get the batch size of a entity persister.
        /// </summary>
        //6.0 TODO: Merge into IEntityPersister.
        public static int GetBatchSize(this IEntityPersister persister)
        {
            if (persister is AbstractEntityPersister acp)
            {
                return(acp.BatchSize);
            }

            NHibernateLogger
            .For(typeof(EntityPersisterExtensions))
            .Warn("Entity persister of {0} type is not supported, returning 1 as a batch size.", persister?.GetType());

            return(1);
        }
        static SysCacheProvider()
        {
            Log = NHibernateLogger.For(typeof(SysCacheProvider));
            ConfiguredCachesProperties = new Dictionary <string, IDictionary <string, string> >();

            if (!(ConfigurationManager.GetSection("syscache") is CacheConfig[] list))
            {
                return;
            }
            foreach (var cache in list)
            {
                ConfiguredCachesProperties.Add(cache.Region, cache.Properties);
            }
        }
Пример #13
0
 /// <summary>
 /// The constructor for creating the region strategy.
 /// </summary>
 /// <param name="connectionMultiplexer">The Redis connection.</param>
 /// <param name="configuration">The region configuration.</param>
 /// <param name="properties">The NHibernate configuration properties.</param>
 protected AbstractRegionStrategy(IConnectionMultiplexer connectionMultiplexer,
                                  RedisCacheRegionConfiguration configuration, IDictionary <string, string> properties)
 {
     Log                   = NHibernateLogger.For(GetType());
     RegionName            = configuration.RegionName;
     Expiration            = configuration.Expiration;
     UseSlidingExpiration  = configuration.UseSlidingExpiration;
     AppendHashcode        = configuration.AppendHashcode;
     RegionKey             = configuration.RegionKey;
     ConnectionMultiplexer = connectionMultiplexer;
     Database              = configuration.DatabaseProvider.Get(connectionMultiplexer, configuration.Database);
     Serializer            = configuration.Serializer;
     LockTimeout           = configuration.LockConfiguration.KeyTimeout;
     _keyLocker            = new RedisKeyLocker(RegionName, Database, configuration.LockConfiguration);
 }
Пример #14
0
        private int _maxResults = 20;  //Environment.MaxResults;

        #region Constructors

        /// <summary>
        /// classes must be immutable
        /// </summary>
        public FullTextQueryImpl(Lucene.Net.Search.Query query,
                                 System.Type[] classes,
                                 ISession session,
                                 ParameterMetadata parameterMetadata,
                                 INHibernateLogger log = null)
            : base(query?.ToString() ?? throw new ArgumentNullException(nameof(query)),
                   FlushMode.Unspecified,
                   session?.GetSessionImplementation() ?? throw new ArgumentNullException(nameof(session)),
                   parameterMetadata) // ?? throw new ArgumentNullException(nameof(parameterMetadata)))
        {
            this.log               = log ?? NHibernateLogger.For(typeof(FullTextQueryImpl));
            luceneQuery            = query;
            resultSize             = -1;
            this.classes           = classes;
            this.filterDefinitions = new Dictionary <string, FullTextFilterImpl>();
        }
        public CompositeCustomType(System.Type userTypeClass, IDictionary <string, string> parameters)
        {
            name = userTypeClass.FullName;

            try
            {
                userType = (ICompositeUserType)Cfg.Environment.ObjectsFactory.CreateInstance(userTypeClass);
            }
            catch (MethodAccessException mae)
            {
                throw new MappingException("MethodAccessException trying to instantiate custom type: " + name, mae);
            }
            catch (TargetInvocationException tie)
            {
                throw new MappingException("TargetInvocationException trying to instantiate custom type: " + name, tie);
            }
            catch (ArgumentException ae)
            {
                throw new MappingException("ArgumentException trying to instantiate custom type: " + name, ae);
            }
            catch (InvalidCastException ice)
            {
                throw new MappingException(name + " must implement NHibernate.UserTypes.ICompositeUserType", ice);
            }
            TypeFactory.InjectParameters(userType, parameters);
            if (!userType.ReturnedClass.IsSerializable)
            {
                NHibernateLogger.For(typeof(CustomType)).Warn("the custom composite class '{0}' handled by '{1}' is not Serializable: ", userType.ReturnedClass, userTypeClass);
            }

            // This is to be nice to an application developer.
            if (userType.PropertyTypes == null)
            {
                throw new InvalidOperationException(String.Format("ICompositeUserType {0} returned a null value for 'PropertyTypes'.", userType.GetType()));
            }
            if (userType.PropertyNames == null)
            {
                throw new InvalidOperationException(String.Format("ICompositeUserType {0} returned a null value for 'PropertyNames'.", userType.GetType()));
            }
        }
        static MemCacheProvider()
        {
            log = NHibernateLogger.For(typeof(MemCacheProvider));
            var configs = ConfigurationManager.GetSection("memcache") as MemCacheConfig[];

            if (configs != null)
            {
                var myWeights = new ArrayList();
                var myServers = new ArrayList();
                foreach (MemCacheConfig config in configs)
                {
                    myServers.Add(string.Format("{0}:{1}", config.Host, config.Port));
                    log.Debug("adding config for memcached on host {0}", config.Host);
                    if (config.Weight > 0)
                    {
                        myWeights.Add(config.Weight);
                    }
                }
                servers = (string[])myServers.ToArray(typeof(string));
                weights = (int[])myWeights.ToArray(typeof(int));
            }
        }
Пример #17
0
        public void NewLoggerFactoryTimingsForNoLogging(int iteration)
        {
            ResetCounts();
            NHibernateLogger.SetLoggersFactory((INHibernateLoggerFactory)null);
            INHibernateLogger logger2 = NHibernateLogger.For(this.GetType());

            var stopwatch      = Stopwatch.StartNew();
            var iterationCount = 10000000;

            for (int i = 0; i < iterationCount; i++)
            {
                logger2.Debug("message");
                logger2.Debug("message with parameters {0}, {1}", "string", 5);
            }

            stopwatch.Stop();
            Console.WriteLine(
                "{0} wrote {1:N0} characters to log in {2} ms",
                nameof(NewLoggerFactoryTimingsForDisabledLogging),
                GetCounts(),
                stopwatch.ElapsedMilliseconds);
        }
Пример #18
0
        static CoreDistributedCacheProvider()
        {
            Log = NHibernateLogger.For(typeof(CoreDistributedCacheProvider));
            ConfiguredCachesProperties = new Dictionary <string, IDictionary <string, string> >();

            if (!(ConfigurationManager.GetSection("coredistributedcache") is CacheConfig config))
            {
                return;
            }

            if (!string.IsNullOrEmpty(config.FactoryClass))
            {
                try
                {
                    var factoryClass       = ReflectHelper.ClassForName(config.FactoryClass);
                    var ctorWithProperties = factoryClass.GetConstructor(CacheFactoryCtorWithPropertiesSignature);

                    CacheFactory = (IDistributedCacheFactory)(ctorWithProperties != null ?
                                                              ctorWithProperties.Invoke(new object[] { config.Properties }):
                                                              Cfg.Environment.ObjectsFactory.CreateInstance(factoryClass));
                }
                catch (Exception e)
                {
                    throw new HibernateException(
                              $"Could not create the {nameof(IDistributedCacheFactory)} factory from '{config.FactoryClass}'. " +
                              $"(It must implement {nameof(IDistributedCacheFactory)} and have a constructor accepting a " +
                              $"{nameof(IDictionary<string, string>)} or have a parameterless constructor.)",
                              e);
                }
            }

            foreach (var cache in config.Regions)
            {
                ConfiguredCachesProperties.Add(cache.Region, cache.Properties);
            }

            AppendHashcodeToKey = config.AppendHashcodeToKey;
        }
Пример #19
0
        public void OldLoggerFactoryThunkedTimingsForEnabledLogging(int iteration)
        {
            ResetCounts();
            ILoggerFactory loggerFactory = new MockLoggerFactory();

            LoggerProvider.SetLoggersFactory(loggerFactory);
            INHibernateLogger logger2 = NHibernateLogger.For(this.GetType());

            var stopwatch      = Stopwatch.StartNew();
            var iterationCount = 10000000;

            for (int i = 0; i < iterationCount; i++)
            {
                logger2.Warn("message");
                logger2.Warn("message with parameters {0}, {1}", "string", 5);
            }

            stopwatch.Stop();
            Console.WriteLine(
                "{0} wrote {1:N0} characters to log in {2} ms",
                nameof(OldLoggerFactoryThunkedTimingsForEnabledLogging),
                GetCounts(),
                stopwatch.ElapsedMilliseconds);
        }
Пример #20
0
 static SharedCacheProvider()
 {
     log = NHibernateLogger.For(typeof(SharedCacheProvider));
     var configs = ConfigurationManager.GetSection("sharedcache") as SharedCacheConfig[];
 }
 /// <summary></summary>
 static SessionFactoryObjectFactory()
 {
     log = NHibernateLogger.For(typeof(SessionFactoryObjectFactory));
     log.Debug("initializing class SessionFactoryObjectFactory");
 }
Пример #22
0
 static NullableType()
 {
     //cache this, because it was a significant performance cost
     IsDebugEnabled = NHibernateLogger.For(typeof(IType).Namespace).IsDebugEnabled();
 }
Пример #23
0
 static SharedCacheClient()
 {
     log = NHibernateLogger.For(typeof(SharedCacheClient));
 }
Пример #24
0
 static VelocityProvider()
 {
     log = NHibernateLogger.For(typeof(VelocityProvider));
     var configs = ConfigurationManager.GetSection("velocity") as VelocityConfig[];
 }
Пример #25
0
 static MemCacheClient()
 {
     log = NHibernateLogger.For(typeof(MemCacheClient));
 }
 public void WhenNotConfiguredAndLog4NetExistsThenUseLog4NetFactory()
 {
     // NoLoggingNHibernateLogger is internal
     Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.Not.EqualTo("NoLoggingNHibernateLogger"));
 }
Пример #27
0
 public Logger(System.Type type)
 {
     this.log = NHibernateLogger.For(type);
 }
 public void LoggerProviderCanCreateLoggers()
 {
     Assert.That(NHibernateLogger.For("pizza"), Is.Not.Null);
     Assert.That(NHibernateLogger.For(typeof(LoggerProviderTest)), Is.Not.Null);
 }
Пример #29
0
 public ILogger CreateLogger(string categoryName)
 {
     return(new LoggerWrapper(NHibernateLogger.For(categoryName)));
 }
Пример #30
0
 static VelocityClientBase()
 {
     log = NHibernateLogger.For(typeof(VelocityClient));
 }