From 00d78cb6a968ca0bb7b8174e19101e48d705ce8b Mon Sep 17 00:00:00 2001 From: Konstantin Fedorchenko Date: Wed, 29 Nov 2017 11:19:28 +0200 Subject: [PATCH 01/32] NH-2534 - Join-fetching a many-to-one with property-ref results in select n+1 problem (#1226) fixed #1226 --- .../NHSpecificTest/GH1226/Fixture.cs | 79 +++++++++++++++++++ .../NHSpecificTest/GH1226/Mappings.hbm.xml | 18 +++++ .../NHSpecificTest/GH1226/Model.cs | 14 ++++ src/NHibernate.Test/NHibernate.Test.csproj | 6 ++ src/NHibernate/Loader/Loader.cs | 29 +++++++ 5 files changed, 146 insertions(+) create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs new file mode 100644 index 00000000000..132e702676a --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs @@ -0,0 +1,79 @@ +namespace NHibernate.Test.NHSpecificTest.GH1226 +{ + using System; + using System.Collections.Generic; + using System.Linq; + using NUnit.Framework; + + [TestFixture] + public class Fixture : BugTestCase { + protected override void OnSetUp() { + base.OnSetUp(); + + using (var session = OpenSession()) { + using (var tx = session.BeginTransaction()) { + Bank bank = new Bank(); + bank.Id = Guid.NewGuid(); + bank.Code = "01234"; + session.Save(bank); + + Account account = new Account(); + account.Id = Guid.NewGuid(); + account.Bank = bank; + session.Save(account); + + Account account2 = new Account(); + account2.Bank = bank; + session.Save(account2); + + tx.Commit(); + } + } + } + + [Test] + public void BankShouldBeJoinFetched() { + using (var session = OpenSession()) { + bool wasStatisticsEnabled = session.SessionFactory.Statistics.IsStatisticsEnabled; + session.SessionFactory.Statistics.IsStatisticsEnabled = true; + + long statementCount; + + using (var tx = session.BeginTransaction()) { + // Bug only occurs if the Banks are already in the session cache. + IList preloadedBanks = session.CreateQuery("from Bank").List(); + + long countBeforeQuery = session.SessionFactory.Statistics.PrepareStatementCount; + + Console.WriteLine("Query: -------------------------------------------------------"); + + IList accounts = session.CreateQuery("from Account a left join fetch a.Bank").List(); + IList associatedBanks = accounts.Select(x => x.Bank).ToList(); + + long countAfterQuery = session.SessionFactory.Statistics.PrepareStatementCount; + statementCount = countAfterQuery - countBeforeQuery; + + Console.WriteLine("End ----------------------------------------------------------"); + + tx.Commit(); + } + + session.SessionFactory.Statistics.IsStatisticsEnabled = wasStatisticsEnabled; + + Assert.AreEqual(1, statementCount); + } + } + + protected override void OnTearDown() { + base.OnTearDown(); + + using (var session = OpenSession()) { + using (var tx = session.BeginTransaction()) { + session.Delete("from Account"); + session.Delete("from Bank"); + tx.Commit(); + } + } + } + } +} diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml b/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml new file mode 100644 index 00000000000..412bf8a135f --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs b/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs new file mode 100644 index 00000000000..1bcae5da2c9 --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs @@ -0,0 +1,14 @@ +namespace NHibernate.Test.NHSpecificTest.GH1226 +{ + using System; + + public class Account { + public virtual Guid Id { get; set; } + public virtual Bank Bank { get; set; } + } + + public class Bank { + public virtual Guid Id { get; set; } + public virtual string Code { get; set; } + } +} diff --git a/src/NHibernate.Test/NHibernate.Test.csproj b/src/NHibernate.Test/NHibernate.Test.csproj index 1ccfb066999..f4b681c0a6c 100644 --- a/src/NHibernate.Test/NHibernate.Test.csproj +++ b/src/NHibernate.Test/NHibernate.Test.csproj @@ -10,8 +10,11 @@ + + + Always @@ -56,4 +59,7 @@ + + + \ No newline at end of file diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index 1fa0fc79960..3bc24fd745c 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -972,6 +972,35 @@ private void InstanceAlreadyLoaded(DbDataReader rs, int i, IEntityPersister pers entry.LockMode = lockMode; } } + + //save object to EntityUnique cache + //see LoadFromResultSet func + IAssociationType[] ownerAssociationTypes = OwnerAssociationTypes; + if (ownerAssociationTypes != null && ownerAssociationTypes[i] != null) + { + string ukName = ownerAssociationTypes[i].RHSUniqueKeyPropertyName; + if (ukName != null) + { + int index = ((IUniqueKeyLoadable) persister).GetPropertyIndex(ukName); + IType type = persister.PropertyTypes[index]; + + object id = key.Identifier; + bool eagerPropertyFetch = IsEagerPropertyFetchEnabled(i); + ILoadable entityPersister = (ILoadable) persister; + string[][] cols = EntityAliases[i].SuffixedPropertyAliases; + + object[] values = entityPersister.Hydrate(rs, id, obj, entityPersister, cols, eagerPropertyFetch, session); + + // polymorphism not really handled completely correctly, + // perhaps...well, actually its ok, assuming that the + // entity name used in the lookup is the same as the + // the one used here, which it will be + + EntityUniqueKey euk = + new EntityUniqueKey(entityPersister.EntityName, ukName, type.SemiResolve(values[index], session, obj), type, session.Factory); + session.PersistenceContext.AddEntity(euk, obj); + } + } } /// From b967fc0a2fac038a0d99fb2217020d7630a90fad Mon Sep 17 00:00:00 2001 From: Konstantin Fedorchenko Date: Wed, 29 Nov 2017 13:57:43 +0200 Subject: [PATCH 02/32] NH-2534 - Join-fetching a many-to-one with property-ref results in select n+1 problem (#1226) fix NHibernate.Test.csproj --- src/NHibernate.Test/NHibernate.Test.csproj | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/NHibernate.Test/NHibernate.Test.csproj b/src/NHibernate.Test/NHibernate.Test.csproj index f4b681c0a6c..4f25f7c2cb9 100644 --- a/src/NHibernate.Test/NHibernate.Test.csproj +++ b/src/NHibernate.Test/NHibernate.Test.csproj @@ -10,11 +10,8 @@ - - - Always From 8c0d711d7270de2b674c41d45c92ec315cab0be0 Mon Sep 17 00:00:00 2001 From: Konstantin Fedorchenko Date: Wed, 29 Nov 2017 14:20:34 +0200 Subject: [PATCH 03/32] NH-2534 - Join-fetching a many-to-one with property-ref results in select n+1 problem (#1226) fix NHibernate.Test.csproj --- src/NHibernate.Test/NHibernate.Test.csproj | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/NHibernate.Test/NHibernate.Test.csproj b/src/NHibernate.Test/NHibernate.Test.csproj index 4f25f7c2cb9..1ccfb066999 100644 --- a/src/NHibernate.Test/NHibernate.Test.csproj +++ b/src/NHibernate.Test/NHibernate.Test.csproj @@ -56,7 +56,4 @@ - - - \ No newline at end of file From ef86fdf4a50fb7de19cdc6c2679daa7ef40579fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Wed, 29 Nov 2017 13:34:36 +0100 Subject: [PATCH 04/32] Fix merging of 5.0.2 See #1459 --- src/NHibernate/Impl/SessionIdLoggingContext.cs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/NHibernate/Impl/SessionIdLoggingContext.cs b/src/NHibernate/Impl/SessionIdLoggingContext.cs index 8acea28ae89..5560b8f1d3a 100644 --- a/src/NHibernate/Impl/SessionIdLoggingContext.cs +++ b/src/NHibernate/Impl/SessionIdLoggingContext.cs @@ -20,17 +20,11 @@ public class SessionIdLoggingContext : IDisposable public SessionIdLoggingContext(Guid id) { - _tracking = id != Guid.Empty; - if (!_tracking) - { - return; - } + if (id == Guid.Empty) return; _oldSessonId = SessionId; - _hasChanged = _oldSessonId != id; - if (_hasChanged) - { - SessionId = id; - } + if (id == _oldSessonId) return; + _hasChanged = true; + SessionId = id; } /// From 63dee05a69acedb1bf64e66a0787c863ca5fd452 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Thu, 30 Nov 2017 15:35:39 +1300 Subject: [PATCH 05/32] Fix disposing SessionIdLoggingContext if CheckAndUpdateSessionStatus is failed (#1462) --- src/NHibernate/Impl/AbstractSessionImpl.cs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/NHibernate/Impl/AbstractSessionImpl.cs b/src/NHibernate/Impl/AbstractSessionImpl.cs index 6f013a8a994..40178607584 100644 --- a/src/NHibernate/Impl/AbstractSessionImpl.cs +++ b/src/NHibernate/Impl/AbstractSessionImpl.cs @@ -313,17 +313,26 @@ public ProcessHelper(AbstractSessionImpl session) { _session = session; _context = new SessionIdLoggingContext(session.SessionId); - session.CheckAndUpdateSessionStatus(); - _session._processing = true; + try + { + _session.CheckAndUpdateSessionStatus(); + _session._processing = true; + } + catch + { + _context.Dispose(); + _context = null; + throw; + } } public void Dispose() { + _context.Dispose(); + _context = null; if (_session == null) throw new ObjectDisposedException("The session process helper has been disposed already"); _session._processing = false; - _context.Dispose(); - _context = null; _session = null; } } From 942b61bbb4f712df7a866d5522a33ce82a267c31 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Thu, 30 Nov 2017 15:41:44 +1300 Subject: [PATCH 06/32] Release 5.0.3 --- build-common/NHibernate.props | 2 +- build-common/common.xml | 4 ++-- releasenotes.txt | 10 +++++++++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/build-common/NHibernate.props b/build-common/NHibernate.props index 6fd6f167d5f..1c4f9de5b17 100644 --- a/build-common/NHibernate.props +++ b/build-common/NHibernate.props @@ -2,7 +2,7 @@ 5 0 - 2 + 3 $(VersionMajor).$(VersionMinor).$(VersionPatch) diff --git a/build-common/common.xml b/build-common/common.xml index 809899a1f13..2b69e9167c0 100644 --- a/build-common/common.xml +++ b/build-common/common.xml @@ -30,8 +30,8 @@ - - + + diff --git a/releasenotes.txt b/releasenotes.txt index 82e5fa16756..fae23a92f4c 100644 --- a/releasenotes.txt +++ b/releasenotes.txt @@ -1,4 +1,12 @@ -Build 5.0.2 +Build 5.0.3 +============================= + +Release notes - NHibernate - Version 5.0.3 + +** Bug + * #1462 Fix disposing SessionIdLoggingContext if CheckAndUpdateSessionStatus is failed + +Build 5.0.2 ============================= Release notes - NHibernate - Version 5.0.2 From 338a827efcca0fd404178f94948e937049083261 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Thu, 30 Nov 2017 11:40:43 +0100 Subject: [PATCH 07/32] Fix a null reference case in session context --- .../NHSpecificTest/Logs/LogsFixture.cs | 11 +++++++++++ src/NHibernate/Impl/AbstractSessionImpl.cs | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/NHibernate.Test/NHSpecificTest/Logs/LogsFixture.cs b/src/NHibernate.Test/NHSpecificTest/Logs/LogsFixture.cs index b69bee02597..525535fbbb0 100644 --- a/src/NHibernate.Test/NHSpecificTest/Logs/LogsFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/Logs/LogsFixture.cs @@ -192,6 +192,17 @@ public void WillGetSessionIdFromSessionLogsConcurrent() } } + [Test] + public void WillCleanlyFailOnDoubleProcessDispose() + { + using (var s = OpenSession()) + { + var p = ((AbstractSessionImpl) s).BeginProcess(); + p.Dispose(); + Assert.That(() => p.Dispose(), Throws.TypeOf()); + } + } + // IFixingRequired interface ensures the value is evaluated at log time rather than at log buffer flush time. public class SessionIdCapturer : IFixingRequired { diff --git a/src/NHibernate/Impl/AbstractSessionImpl.cs b/src/NHibernate/Impl/AbstractSessionImpl.cs index 5c0357e007b..8ac235df64e 100644 --- a/src/NHibernate/Impl/AbstractSessionImpl.cs +++ b/src/NHibernate/Impl/AbstractSessionImpl.cs @@ -329,7 +329,7 @@ public ProcessHelper(AbstractSessionImpl session) public void Dispose() { - _context.Dispose(); + _context?.Dispose(); _context = null; if (_session == null) throw new ObjectDisposedException("The session process helper has been disposed already"); From 7af6f4cc5f8221f35d17bae3e83c09493824d210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Thu, 30 Nov 2017 12:15:31 +0100 Subject: [PATCH 08/32] Obsolete an unused method. --- src/NHibernate/Engine/ISessionImplementor.cs | 3 ++- src/NHibernate/Impl/AbstractSessionImpl.cs | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/NHibernate/Engine/ISessionImplementor.cs b/src/NHibernate/Engine/ISessionImplementor.cs index 43f6dde729b..f32306fde2d 100644 --- a/src/NHibernate/Engine/ISessionImplementor.cs +++ b/src/NHibernate/Engine/ISessionImplementor.cs @@ -43,10 +43,11 @@ internal static IDisposable BeginProcess(this ISessionImplementor session) /// public partial interface ISessionImplementor { - // 5.1 TODO: obsolete Initialize, it has no more usages. /// /// Initialize the session after its construction was complete /// + // Since v5.1 + [Obsolete("This method has no more usages in NHibernate and will be removed.")] void Initialize(); /// diff --git a/src/NHibernate/Impl/AbstractSessionImpl.cs b/src/NHibernate/Impl/AbstractSessionImpl.cs index 8ac235df64e..f7d730c9bd4 100644 --- a/src/NHibernate/Impl/AbstractSessionImpl.cs +++ b/src/NHibernate/Impl/AbstractSessionImpl.cs @@ -55,6 +55,8 @@ protected internal AbstractSessionImpl(ISessionFactoryImplementor factory, ISess #region ISessionImplementor Members + // Since v5.1 + [Obsolete("This method has no more usages in NHibernate and will be removed.")] public void Initialize() { BeginProcess()?.Dispose(); From dfe5dec6e60e1a00e8015d26155349d8d233b428 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Fri, 1 Dec 2017 11:43:21 +1300 Subject: [PATCH 09/32] Obsolete EqualsHelper --- src/NHibernate.DomainModel/Async/CustomPersister.cs | 4 ++-- src/NHibernate.DomainModel/CustomPersister.cs | 4 ++-- src/NHibernate/Type/AbstractType.cs | 2 +- src/NHibernate/Type/NullableType.cs | 2 +- src/NHibernate/Util/EqualsHelper.cs | 5 ++++- 5 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/NHibernate.DomainModel/Async/CustomPersister.cs b/src/NHibernate.DomainModel/Async/CustomPersister.cs index 5fac317eb77..889471e0441 100644 --- a/src/NHibernate.DomainModel/Async/CustomPersister.cs +++ b/src/NHibernate.DomainModel/Async/CustomPersister.cs @@ -37,7 +37,7 @@ public Task FindDirtyAsync(object[] currentState, object[] previousState, { try { - if (!EqualsHelper.Equals(currentState[0], previousState[0])) + if (!Equals(currentState[0], previousState[0])) { return Task.FromResult(new int[] { 0 }); } @@ -56,7 +56,7 @@ public Task FindModifiedAsync(object[] old, object[] current, object enti { try { - if (!EqualsHelper.Equals(old[0], current[0])) + if (!Equals(old[0], current[0])) { return Task.FromResult(new int[] { 0 }); } diff --git a/src/NHibernate.DomainModel/CustomPersister.cs b/src/NHibernate.DomainModel/CustomPersister.cs index cb2c413f558..473f136b94c 100644 --- a/src/NHibernate.DomainModel/CustomPersister.cs +++ b/src/NHibernate.DomainModel/CustomPersister.cs @@ -254,7 +254,7 @@ public IType GetPropertyType(string propertyName) public int[] FindDirty(object[] currentState, object[] previousState, object entity, ISessionImplementor session) { - if (!EqualsHelper.Equals(currentState[0], previousState[0])) + if (!Equals(currentState[0], previousState[0])) { return new int[] { 0 }; } @@ -266,7 +266,7 @@ public int[] FindDirty(object[] currentState, object[] previousState, object ent public int[] FindModified(object[] old, object[] current, object entity, ISessionImplementor session) { - if (!EqualsHelper.Equals(old[0], current[0])) + if (!Equals(old[0], current[0])) { return new int[] { 0 }; } diff --git a/src/NHibernate/Type/AbstractType.cs b/src/NHibernate/Type/AbstractType.cs index 4b7f95fabec..4ed8f103b16 100644 --- a/src/NHibernate/Type/AbstractType.cs +++ b/src/NHibernate/Type/AbstractType.cs @@ -208,7 +208,7 @@ public virtual bool IsSame(object x, object y) public virtual bool IsEqual(object x, object y) { - return EqualsHelper.Equals(x, y); + return Equals(x, y); } public virtual bool IsEqual(object x, object y, ISessionFactoryImplementor factory) diff --git a/src/NHibernate/Type/NullableType.cs b/src/NHibernate/Type/NullableType.cs index 6903eb26af6..93de6489f0d 100644 --- a/src/NHibernate/Type/NullableType.cs +++ b/src/NHibernate/Type/NullableType.cs @@ -332,7 +332,7 @@ public override bool[] ToColumnNullness(object value, IMapping mapping) public override bool IsEqual(object x, object y) { - return EqualsHelper.Equals(x, y); + return Equals(x, y); } #region override of System.Object Members diff --git a/src/NHibernate/Util/EqualsHelper.cs b/src/NHibernate/Util/EqualsHelper.cs index 64adf569db6..5262f26f638 100644 --- a/src/NHibernate/Util/EqualsHelper.cs +++ b/src/NHibernate/Util/EqualsHelper.cs @@ -1,10 +1,13 @@ +using System; + namespace NHibernate.Util { public static class EqualsHelper { + [Obsolete("Please use object.Equals(object, object) instead.")] public new static bool Equals(object x, object y) { - return x == y || (x != null && y != null && x.Equals(y)); + return object.Equals(x, y); } } } From 524d06ab4c7b78ac394843be5eb0441f806298ba Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Fri, 1 Dec 2017 14:26:54 +1300 Subject: [PATCH 10/32] Obsolete EnumerableExtensions (#1465) --- .../Async/NHSpecificTest/NH3050/Fixture.cs | 4 +- .../NHSpecificTest/NH3050/Fixture.cs | 4 +- .../AnyExtensionTests.cs | 4 +- .../FirstExtensionTests.cs | 2 + .../FirstOrNullExtensionTests.cs | 2 + src/NHibernate/Async/Engine/Cascade.cs | 4 +- src/NHibernate/Engine/Cascade.cs | 8 +- src/NHibernate/Impl/AbstractQueryImpl.cs | 4 +- src/NHibernate/Util/EnumerableExtensions.cs | 127 +++--------------- 9 files changed, 35 insertions(+), 124 deletions(-) diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3050/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3050/Fixture.cs index 0a9a7a3c4df..c8aedc6450f 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH3050/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3050/Fixture.cs @@ -127,7 +127,7 @@ where personIds.Contains(person.Id) var softReferenceCache = (IEnumerable) field.GetValue(cache); // Since the cache only contains one item, the first one will be our key - var queryPlanCacheKey = ((DictionaryEntry) softReferenceCache.First()).Key; + var queryPlanCacheKey = ((DictionaryEntry) softReferenceCache.Cast().First()).Key; // Setup an action that will be run on another thread and that will do nothing more than clearing the cache as long // as the value stored behind the cachekey is not of type ExpandedQueryExpression, which triggers the error. @@ -172,4 +172,4 @@ where personIds.Contains(person.Id) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH3050/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3050/Fixture.cs index 70415b79ff1..ef66f7cb5ef 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3050/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3050/Fixture.cs @@ -117,7 +117,7 @@ where personIds.Contains(person.Id) var softReferenceCache = (IEnumerable) field.GetValue(cache); // Since the cache only contains one item, the first one will be our key - var queryPlanCacheKey = ((DictionaryEntry) softReferenceCache.First()).Key; + var queryPlanCacheKey = ((DictionaryEntry) softReferenceCache.Cast().First()).Key; // Setup an action that will be run on another thread and that will do nothing more than clearing the cache as long // as the value stored behind the cachekey is not of type ExpandedQueryExpression, which triggers the error. @@ -162,4 +162,4 @@ where personIds.Contains(person.Id) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/AnyExtensionTests.cs b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/AnyExtensionTests.cs index b66275025f2..8fce55fa569 100644 --- a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/AnyExtensionTests.cs +++ b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/AnyExtensionTests.cs @@ -5,6 +5,8 @@ namespace NHibernate.Test.UtilityTest.EnumerableExtensionsTests { + //Since v5.1 + [Obsolete] [TestFixture] public class AnyExtensionTests { @@ -72,4 +74,4 @@ public void WhenDisposableListThenCallDispose() Assert.That(disposeCalled, Is.True); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstExtensionTests.cs b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstExtensionTests.cs index 4afd88a688c..25aec547ca4 100644 --- a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstExtensionTests.cs +++ b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstExtensionTests.cs @@ -5,6 +5,8 @@ namespace NHibernate.Test.UtilityTest.EnumerableExtensionsTests { + //Since v5.1 + [Obsolete] [TestFixture] public class FirstExtensionTests { diff --git a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstOrNullExtensionTests.cs b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstOrNullExtensionTests.cs index 85a7fcd3464..3e308db71ec 100644 --- a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstOrNullExtensionTests.cs +++ b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstOrNullExtensionTests.cs @@ -5,6 +5,8 @@ namespace NHibernate.Test.UtilityTest.EnumerableExtensionsTests { + //Since v5.1 + [Obsolete] [TestFixture] public class FirstOrNullExtensionTests { diff --git a/src/NHibernate/Async/Engine/Cascade.cs b/src/NHibernate/Async/Engine/Cascade.cs index 48de0224591..b56d9d18ad6 100644 --- a/src/NHibernate/Async/Engine/Cascade.cs +++ b/src/NHibernate/Async/Engine/Cascade.cs @@ -125,7 +125,7 @@ private Task CascadePropertyAsync(object parent, object child, IType type, Casca { EntityType entityType = (EntityType)type; object loadedValue; - if (!componentPathStack.Any()) + if (componentPathStack.Count == 0) { // association defined on entity loadedValue = entry.GetLoadedValue(propertyName); @@ -306,4 +306,4 @@ private async Task DeleteOrphansAsync(string entityName, IPersistentCollection p } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Engine/Cascade.cs b/src/NHibernate/Engine/Cascade.cs index fca9c0f995f..a78109016ae 100644 --- a/src/NHibernate/Engine/Cascade.cs +++ b/src/NHibernate/Engine/Cascade.cs @@ -1,5 +1,5 @@ using System.Collections; - +using System.Collections.Generic; using NHibernate.Collection; using NHibernate.Event; using NHibernate.Persister.Collection; @@ -76,7 +76,7 @@ public sealed partial class Cascade private readonly IEventSource eventSource; private readonly CascadingAction action; - private readonly Stack componentPathStack = new Stack(); + private readonly Stack componentPathStack = new Stack(); public Cascade(CascadingAction action, CascadePoint point, IEventSource eventSource) { @@ -172,7 +172,7 @@ private void CascadeProperty(object parent, object child, IType type, CascadeSty { EntityType entityType = (EntityType)type; object loadedValue; - if (!componentPathStack.Any()) + if (componentPathStack.Count == 0) { // association defined on entity loadedValue = entry.GetLoadedValue(propertyName); @@ -335,4 +335,4 @@ private void DeleteOrphans(string entityName, IPersistentCollection pc) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Impl/AbstractQueryImpl.cs b/src/NHibernate/Impl/AbstractQueryImpl.cs index e894c339d4d..f5af71c6c2c 100644 --- a/src/NHibernate/Impl/AbstractQueryImpl.cs +++ b/src/NHibernate/Impl/AbstractQueryImpl.cs @@ -719,7 +719,7 @@ public IQuery SetParameterList(string name, IEnumerable vals, IType type) { throw new ArgumentNullException("type","Can't determine the type of parameter-list elements."); } - if(!vals.Any()) + if(!vals.Cast().Any()) { throw new QueryException(string.Format("An empty parameter-list generates wrong SQL; parameter name '{0}'", name)); } @@ -740,7 +740,7 @@ public IQuery SetParameterList(string name, IEnumerable vals) return this; } - object firstValue = vals.FirstOrNull(); + object firstValue = vals.Cast().FirstOrDefault(); SetParameterList(name, vals, firstValue == null ? GuessType(vals.GetCollectionElementType()) : DetermineType(name, firstValue)); return this; diff --git a/src/NHibernate/Util/EnumerableExtensions.cs b/src/NHibernate/Util/EnumerableExtensions.cs index f17a7dd94a8..505fb0e7f62 100644 --- a/src/NHibernate/Util/EnumerableExtensions.cs +++ b/src/NHibernate/Util/EnumerableExtensions.cs @@ -1,138 +1,43 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; namespace NHibernate.Util { + //Since v5.1 + [Obsolete("This class has no more usages and will be removed in next major version.")] public static class EnumerableExtensions { + //Since v5.1 + [Obsolete("Please use Enumerable.Any(IEnumerable) instead.")] public static bool Any(this IEnumerable source) { - if (source == null) - { - throw new ArgumentNullException("source"); - } - using (DisposableEnumerator enumerator = source.GetDisposableEnumerator()) - { - if (enumerator.MoveNext()) - { - return true; - } - } - return false; + return Enumerable.Any(source.Cast()); } + //Since v5.1 + [Obsolete("Please use Enumerable.First(IEnumerable) instead.")] public static object First(this IEnumerable source) { - if (source == null) - { - throw new ArgumentNullException("source"); - } - IList collection = source as IList; - if (collection != null) - { - if (collection.Count > 0) - { - return collection[0]; - } - } - else - { - using (DisposableEnumerator enumerator = source.GetDisposableEnumerator()) - { - if (enumerator.MoveNext()) - { - return enumerator.Current; - } - } - } - throw new InvalidOperationException("Sequence contains no elements"); + return Enumerable.First(source.Cast()); } + //Since v5.1 + [Obsolete("Please use Enumerable.FirstOrDefault(IEnumerable) instead.")] public static object FirstOrNull(this IEnumerable source) { - if (source == null) - { - throw new ArgumentNullException("source"); - } - IList collection = source as IList; - if (collection != null) - { - if (collection.Count > 0) - { - return collection[0]; - } - } - else - { - using (DisposableEnumerator enumerator = source.GetDisposableEnumerator()) - { - if (enumerator.MoveNext()) - { - return enumerator.Current; - } - } - } - return null; + return Enumerable.FirstOrDefault(source.Cast()); } + //Since v5.1 + [Obsolete("Please use a loop instead.")] public static void ForEach(this IEnumerable query, Action method) { - foreach (T item in query) + foreach (var item in query) { method(item); } } - - private static DisposableEnumerator GetDisposableEnumerator(this IEnumerable source) - { - return new DisposableEnumerator(source); - } - - #region Nested type: DisposableEnumerator - - internal class DisposableEnumerator : IDisposable, IEnumerator - { - private readonly IEnumerator wrapped; - - public DisposableEnumerator(IEnumerable source) - { - wrapped = source.GetEnumerator(); - } - - #region IDisposable Members - - public void Dispose() - { - var disposable = wrapped as IDisposable; - if (disposable != null) - { - disposable.Dispose(); - } - } - - #endregion - - #region IEnumerator Members - - public bool MoveNext() - { - return wrapped.MoveNext(); - } - - public void Reset() - { - wrapped.Reset(); - } - - public object Current - { - get { return wrapped.Current; } - } - - #endregion - } - - #endregion } -} \ No newline at end of file +} From 196a1c456609103451f19524943c2089418bee87 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Sun, 3 Dec 2017 23:12:18 +1300 Subject: [PATCH 11/32] Fix generating coalesce for Boolean expressions Fixes #1468 --- .../Issues/GH1468/Entity.vb | 7 ++ .../Issues/GH1468/Fixture.vb | 81 +++++++++++++++++++ .../GH1468/Issues.GH1468.Mappings.hbm.xml | 11 +++ .../Functions/GetValueOrDefaultGenerator.cs | 4 +- .../Visitors/HqlGeneratorExpressionVisitor.cs | 3 +- 5 files changed, 102 insertions(+), 4 deletions(-) create mode 100644 src/NHibernate.Test.VisualBasic/Issues/GH1468/Entity.vb create mode 100644 src/NHibernate.Test.VisualBasic/Issues/GH1468/Fixture.vb create mode 100644 src/NHibernate.Test.VisualBasic/Issues/GH1468/Issues.GH1468.Mappings.hbm.xml diff --git a/src/NHibernate.Test.VisualBasic/Issues/GH1468/Entity.vb b/src/NHibernate.Test.VisualBasic/Issues/GH1468/Entity.vb new file mode 100644 index 00000000000..6d537e9ae36 --- /dev/null +++ b/src/NHibernate.Test.VisualBasic/Issues/GH1468/Entity.vb @@ -0,0 +1,7 @@ +Namespace Issues.GH1468 + Public Class Entity + Public Overridable Property Id As Guid + + Public Overridable Property Date1 As Date? + End Class +End Namespace diff --git a/src/NHibernate.Test.VisualBasic/Issues/GH1468/Fixture.vb b/src/NHibernate.Test.VisualBasic/Issues/GH1468/Fixture.vb new file mode 100644 index 00000000000..91458176244 --- /dev/null +++ b/src/NHibernate.Test.VisualBasic/Issues/GH1468/Fixture.vb @@ -0,0 +1,81 @@ +Imports NUnit.Framework + +Namespace Issues.GH1468 + + Public Class Fixture + Inherits IssueTestCase + + Protected Overrides Sub OnSetUp() + + Using session As ISession = OpenSession() + + Using transaction As ITransaction = session.BeginTransaction() + + Dim e1 = New Entity + e1.Date1 = new Date(2017, 12, 3) + session.Save(e1) + + Dim e2 = New Entity + e2.Date1 = new Date(2017, 12, 1) + session.Save(e2) + + Dim e3 = New Entity + session.Save(e3) + + session.Flush() + transaction.Commit() + + End Using + + End Using + End Sub + + Protected Overrides Sub OnTearDown() + + Using session As ISession = OpenSession() + + Using transaction As ITransaction = session.BeginTransaction() + + session.Delete("from System.Object") + + session.Flush() + transaction.Commit() + + End Using + + End Using + End Sub + + + Public Sub ShouldBeAbleToCompareNullableDate() + + Using session As ISession = OpenSession() + Using session.BeginTransaction() + + Dim d = New Date(2017, 12, 2) + Dim result = (From e In session.Query (Of Entity) + Where e.Date1 >= d + Select e).ToList() + + Assert.AreEqual(1, result.Count) + End Using + End Using + End Sub + + + Public Sub ShouldBeAbleToCompareNullableDateGetValueOrDefault() + + Using session As ISession = OpenSession() + Using session.BeginTransaction() + + Dim d = New Date(2017, 12, 2) + Dim result = (From e In session.Query (Of Entity) + Where (e.Date1 >= d).GetValueOrDefault() + Select e).ToList() + + Assert.AreEqual(1, result.Count) + End Using + End Using + End Sub + End Class +End Namespace diff --git a/src/NHibernate.Test.VisualBasic/Issues/GH1468/Issues.GH1468.Mappings.hbm.xml b/src/NHibernate.Test.VisualBasic/Issues/GH1468/Issues.GH1468.Mappings.hbm.xml new file mode 100644 index 00000000000..2199c157ea4 --- /dev/null +++ b/src/NHibernate.Test.VisualBasic/Issues/GH1468/Issues.GH1468.Mappings.hbm.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/NHibernate/Linq/Functions/GetValueOrDefaultGenerator.cs b/src/NHibernate/Linq/Functions/GetValueOrDefaultGenerator.cs index 760b029e22f..87c8efb01a9 100644 --- a/src/NHibernate/Linq/Functions/GetValueOrDefaultGenerator.cs +++ b/src/NHibernate/Linq/Functions/GetValueOrDefaultGenerator.cs @@ -28,13 +28,13 @@ public IEnumerable SupportedMethods public HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) { - return treeBuilder.Coalesce(visitor.Visit(targetObject).AsExpression(), GetRhs(method, arguments, treeBuilder, visitor)); + return treeBuilder.Coalesce(visitor.Visit(targetObject).ToArithmeticExpression(), GetRhs(method, arguments, treeBuilder, visitor)); } private static HqlExpression GetRhs(MethodInfo method, ReadOnlyCollection arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) { if (arguments.Count > 0) - return visitor.Visit(arguments[0]).AsExpression(); + return visitor.Visit(arguments[0]).ToArithmeticExpression(); var returnType = method.ReturnType; var instance = returnType.IsValueType ? Activator.CreateInstance(returnType) : null; diff --git a/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionVisitor.cs b/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionVisitor.cs index cb4ec1cca66..0b707fb52db 100644 --- a/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionVisitor.cs +++ b/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionVisitor.cs @@ -8,7 +8,6 @@ using NHibernate.Param; using NHibernate.Util; using Remotion.Linq.Clauses.Expressions; -using Remotion.Linq.Clauses.ResultOperators; namespace NHibernate.Linq.Visitors { @@ -316,7 +315,7 @@ protected HqlTreeNode VisitBinaryExpression(BinaryExpression expression) return _hqlTreeBuilder.GreaterThanOrEqual(lhs, rhs); case ExpressionType.Coalesce: - return _hqlTreeBuilder.Coalesce(lhs, rhs); + return _hqlTreeBuilder.Coalesce(lhs.ToArithmeticExpression(), rhs.ToArithmeticExpression()); } throw new InvalidOperationException(); From 970e9fa51757f2dcdde4836b721498356089fe57 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Wed, 6 Dec 2017 09:48:48 +1300 Subject: [PATCH 12/32] Fix ProxyFactory cache (#1454) * Fix ProxyFactory cache - use a correct implementation of cache - reduce the number of allocations of ProxyCacheEntry - reduce memory flow --- .../NHSpecificTest/NH3954/EqualsFixture.cs | 15 +-- .../NH3954/ProxyCacheFixture.cs | 34 +++---- src/NHibernate/Async/Engine/Cascade.cs | 2 +- .../DynamicProxy/DefaultMethodEmitter.cs | 22 +---- .../Proxy/DynamicProxy/HashSetExtensions.cs | 5 +- .../Proxy/DynamicProxy/IProxyCache.cs | 5 +- .../Proxy/DynamicProxy/ProxyCache.cs | 20 ++-- .../Proxy/DynamicProxy/ProxyCacheEntry.cs | 35 +++---- .../Proxy/DynamicProxy/ProxyFactory.cs | 96 ++++++------------- 9 files changed, 93 insertions(+), 141 deletions(-) diff --git a/src/NHibernate.Test/NHSpecificTest/NH3954/EqualsFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3954/EqualsFixture.cs index 51cf0323634..5b1c896da1d 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3954/EqualsFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3954/EqualsFixture.cs @@ -1,5 +1,6 @@ using System; using System.Reflection; +using System.Runtime.Serialization; using NHibernate.Proxy; using NHibernate.Proxy.DynamicProxy; using NHibernate.Type; @@ -48,9 +49,9 @@ public void TypeInequality() [Test] public void InterfaceEquality() { - var entry1 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(INHibernateProxy), typeof(IProxy) }); + var entry1 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(INHibernateProxy), typeof(ISerializable) }); // Interfaces order inverted on purpose: must be supported. - var entry2 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(IProxy), typeof(INHibernateProxy) }); + var entry2 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(ISerializable), typeof(INHibernateProxy) }); Assert.IsTrue(entry1.Equals(entry2)); Assert.IsTrue(entry2.Equals(entry1)); } @@ -59,9 +60,9 @@ public void InterfaceEquality() [Test] public void InterfaceEqualityWithLotOfUnordererdAndDupInterfaces() { - var entry1 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(INHibernateProxy), typeof(IProxy), typeof(IType), typeof(IDisposable), typeof(IFilter) }); + var entry1 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(INHibernateProxy), typeof(ISerializable), typeof(IType), typeof(IDisposable), typeof(IFilter) }); // Interfaces order inverted and duplicated on purpose: must be supported. - var entry2 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(IType), typeof(IProxy), typeof(IFilter), typeof(IDisposable), typeof(IType), typeof(IFilter), typeof(INHibernateProxy) }); + var entry2 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(IType), typeof(ISerializable), typeof(IFilter), typeof(IDisposable), typeof(IType), typeof(IFilter), typeof(INHibernateProxy) }); Assert.IsTrue(entry1.Equals(entry2)); Assert.IsTrue(entry2.Equals(entry1)); } @@ -69,11 +70,11 @@ public void InterfaceEqualityWithLotOfUnordererdAndDupInterfaces() [Test] public void InterfaceInequality() { - var entry1 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(INHibernateProxy), typeof(IProxy) }); - var entry2 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(IProxy) }); + var entry1 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(INHibernateProxy), typeof(ISerializable) }); + var entry2 = new ProxyCacheEntry(typeof(Entity1), new[] { typeof(ISerializable) }); TweakEntry(entry2, entry1.GetHashCode()); Assert.IsFalse(entry1.Equals(entry2)); Assert.IsFalse(entry2.Equals(entry1)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH3954/ProxyCacheFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3954/ProxyCacheFixture.cs index 5692f49fc8f..0583f96a0b1 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3954/ProxyCacheFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3954/ProxyCacheFixture.cs @@ -1,34 +1,36 @@ -using System.Collections.Concurrent; +using System; +using System.Collections.Concurrent; using System.Reflection; +using System.Runtime.Serialization; using NHibernate.Proxy; using NHibernate.Proxy.DynamicProxy; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.NH3954 { - [TestFixture, Explicit("Demonstrates bug impact on cache, but which tests will fail is a bit unpredictable")] + [TestFixture, Explicit("Demonstrates bug impact on cache, but which tests will fail is a bit unpredictable"), Obsolete] public class ProxyCacheFixture { private ProxyCache _cache; - private ConcurrentDictionary _internalCache; + private ConcurrentDictionary _internalCache; private int _hashCode1; private int _hashCode2; private static readonly FieldInfo InternalCacheField = - typeof(ProxyCache).GetField("cache", BindingFlags.Static | BindingFlags.NonPublic); + typeof(ProxyFactory).GetField("_cache", BindingFlags.Static | BindingFlags.NonPublic); [SetUp] public void SetUp() { _cache = new ProxyCache(); - _internalCache = (ConcurrentDictionary)InternalCacheField.GetValue(null); + _internalCache = (ConcurrentDictionary)InternalCacheField.GetValue(null); _cache.StoreProxyType(typeof(Entity1FakeProxy).GetTypeInfo(), typeof(Entity1)); _cache.StoreProxyType(typeof(Entity2FakeProxy).GetTypeInfo(), typeof(Entity2), typeof(INHibernateProxy)); _cache.StoreProxyType(typeof(Entity3FakeProxy).GetTypeInfo(), typeof(Entity3)); - _cache.StoreProxyType(typeof(Entity4FakeProxy).GetTypeInfo(), typeof(Entity4), typeof(IProxy)); - _cache.StoreProxyType(typeof(Entity5FakeProxy).GetTypeInfo(), typeof(Entity5), typeof(INHibernateProxy), typeof(IProxy)); + _cache.StoreProxyType(typeof(Entity4FakeProxy).GetTypeInfo(), typeof(Entity4), typeof(ISerializable)); + _cache.StoreProxyType(typeof(Entity5FakeProxy).GetTypeInfo(), typeof(Entity5), typeof(INHibernateProxy), typeof(ISerializable)); // Artificially inject other entries with same hashcodes _hashCode1 = new ProxyCacheEntry(typeof(Entity1), null).GetHashCode(); @@ -37,14 +39,14 @@ public void SetUp() _hashCode2 = new ProxyCacheEntry(typeof(Entity2), new[] { typeof(INHibernateProxy) }).GetHashCode(); Inject(new ProxyCacheEntry(typeof(Entity2), null), _hashCode2, typeof(Entity2FakeProxy2)); - Inject(new ProxyCacheEntry(typeof(Entity4), new[] { typeof(IProxy) }), _hashCode2, typeof(Entity4FakeProxy2)); - Inject(new ProxyCacheEntry(typeof(Entity5), new[] { typeof(INHibernateProxy), typeof(IProxy) }), _hashCode2, typeof(Entity5FakeProxy2)); + Inject(new ProxyCacheEntry(typeof(Entity4), new[] { typeof(ISerializable) }), _hashCode2, typeof(Entity4FakeProxy2)); + Inject(new ProxyCacheEntry(typeof(Entity5), new[] { typeof(INHibernateProxy), typeof(ISerializable) }), _hashCode2, typeof(Entity5FakeProxy2)); } private void Inject(ProxyCacheEntry entryToTweak, int hashcode, System.Type result) { TweakEntry(entryToTweak, hashcode); - _internalCache[entryToTweak] = result; + _internalCache[entryToTweak] = result.GetTypeInfo(); } private static readonly FieldInfo HashCodeField = @@ -112,14 +114,14 @@ public void ProxyCacheEntity3FakeProxy2() [Test] public void ProxyCacheEntity4FakeProxy() { - var result = _cache.GetProxyType(typeof(Entity4), typeof(IProxy)); + var result = _cache.GetProxyType(typeof(Entity4), typeof(ISerializable)); Assert.AreEqual(typeof(Entity4FakeProxy), result); } [Test] public void ProxyCacheEntity4FakeProxy2() { - var entry = new ProxyCacheEntry(typeof(Entity4), new[] { typeof(IProxy) }); + var entry = new ProxyCacheEntry(typeof(Entity4), new[] { typeof(ISerializable) }); TweakEntry(entry, _hashCode2); var result = _internalCache[entry]; Assert.AreEqual(typeof(Entity4FakeProxy2), result); @@ -128,7 +130,7 @@ public void ProxyCacheEntity4FakeProxy2() [Test] public void ProxyCacheEntity5FakeProxy() { - var result = _cache.GetProxyType(typeof(Entity5), typeof(IProxy), typeof(INHibernateProxy)); + var result = _cache.GetProxyType(typeof(Entity5), typeof(ISerializable), typeof(INHibernateProxy)); Assert.AreEqual(typeof(Entity5FakeProxy), result); } @@ -136,7 +138,7 @@ public void ProxyCacheEntity5FakeProxy() public void ProxyCacheEntity5FakeProxy2() { // Interfaces order inverted on purpose: must be supported. - var entry = new ProxyCacheEntry(typeof(Entity5), new[] { typeof(IProxy), typeof(INHibernateProxy) }); + var entry = new ProxyCacheEntry(typeof(Entity5), new[] { typeof(ISerializable), typeof(INHibernateProxy) }); TweakEntry(entry, _hashCode2); var result = _internalCache[entry]; Assert.AreEqual(typeof(Entity5FakeProxy2), result); @@ -149,7 +151,7 @@ public void ProxyCacheNone() // (Otherwise the test may starts failing unexpectedly sometimes, as the original bug ...) // This one was not added in anyway. TypeInfo result; - Assert.IsFalse(_cache.TryGetProxyType(typeof(Entity2), new[] { typeof(IProxy) }, out result)); + Assert.IsFalse(_cache.TryGetProxyType(typeof(Entity2), new[] { typeof(ISerializable) }, out result)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Engine/Cascade.cs b/src/NHibernate/Async/Engine/Cascade.cs index b56d9d18ad6..1ccc4ef3bfc 100644 --- a/src/NHibernate/Async/Engine/Cascade.cs +++ b/src/NHibernate/Async/Engine/Cascade.cs @@ -9,7 +9,7 @@ using System.Collections; - +using System.Collections.Generic; using NHibernate.Collection; using NHibernate.Event; using NHibernate.Persister.Collection; diff --git a/src/NHibernate/Proxy/DynamicProxy/DefaultMethodEmitter.cs b/src/NHibernate/Proxy/DynamicProxy/DefaultMethodEmitter.cs index 48f64bbd14b..7433f00072c 100644 --- a/src/NHibernate/Proxy/DynamicProxy/DefaultMethodEmitter.cs +++ b/src/NHibernate/Proxy/DynamicProxy/DefaultMethodEmitter.cs @@ -10,15 +10,12 @@ using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; -using NHibernate.Linq; using NHibernate.Util; namespace NHibernate.Proxy.DynamicProxy { internal class DefaultMethodEmitter : IMethodBodyEmitter { - private static readonly MethodInfo getInterceptor; - private static readonly MethodInfo handlerMethod = ReflectHelper.GetMethod( i => i.Intercept(null)); private static readonly MethodInfo getArguments = typeof(InvocationInfo).GetMethod("get_Arguments"); @@ -33,17 +30,8 @@ internal class DefaultMethodEmitter : IMethodBodyEmitter typeof (object[]) }); - private static readonly PropertyInfo interceptorProperty = typeof (IProxy).GetProperty("Interceptor"); - - private static readonly ConstructorInfo notImplementedConstructor = typeof(NotImplementedException).GetConstructor(new System.Type[0]); - private readonly IArgumentHandler _argumentHandler; - static DefaultMethodEmitter() - { - getInterceptor = interceptorProperty.GetGetMethod(); - } - public DefaultMethodEmitter() : this(new DefaultArgumentHandler()) {} public DefaultMethodEmitter(IArgumentHandler argumentHandler) @@ -60,12 +48,12 @@ public void EmitMethodBody(MethodBuilder proxyMethod, MethodBuilder callbackMeth ParameterInfo[] parameters = method.GetParameters(); IL.DeclareLocal(typeof (object[])); IL.DeclareLocal(typeof (InvocationInfo)); - IL.DeclareLocal(typeof(System.Type[])); + IL.DeclareLocal(typeof (System.Type[])); IL.Emit(OpCodes.Ldarg_0); - IL.Emit(OpCodes.Callvirt, getInterceptor); + IL.Emit(OpCodes.Ldfld, field); - // if (interceptor == null) + // if (this.__interceptor == null) // return base.method(...); Label skipBaseCall = IL.DefineLabel(); @@ -90,9 +78,9 @@ public void EmitMethodBody(MethodBuilder proxyMethod, MethodBuilder callbackMeth IL.Emit(OpCodes.Newobj, infoConstructor); IL.Emit(OpCodes.Stloc_1); - // this.Interceptor.Intercept(info); + // this.__interceptor.Intercept(info); IL.Emit(OpCodes.Ldarg_0); - IL.Emit(OpCodes.Callvirt, getInterceptor); + IL.Emit(OpCodes.Ldfld, field); IL.Emit(OpCodes.Ldloc_1); IL.Emit(OpCodes.Callvirt, handlerMethod); diff --git a/src/NHibernate/Proxy/DynamicProxy/HashSetExtensions.cs b/src/NHibernate/Proxy/DynamicProxy/HashSetExtensions.cs index 681d0ee2074..92b96f92e8d 100644 --- a/src/NHibernate/Proxy/DynamicProxy/HashSetExtensions.cs +++ b/src/NHibernate/Proxy/DynamicProxy/HashSetExtensions.cs @@ -1,9 +1,12 @@ +using System; using System.Collections.Generic; namespace NHibernate.Proxy.DynamicProxy { + [Obsolete("This class is not used anymore and will be removed in a next major version")] public static class HashSetExtensions { + [Obsolete("This method is not used anymore and will be removed in a next major version")] public static HashSet Merge(this HashSet source, IEnumerable toMerge) { foreach (T item in toMerge) @@ -13,4 +16,4 @@ public static HashSet Merge(this HashSet source, IEnumerable toMerge return source; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/IProxyCache.cs b/src/NHibernate/Proxy/DynamicProxy/IProxyCache.cs index 8a86d1cb3e0..cf3e6654941 100644 --- a/src/NHibernate/Proxy/DynamicProxy/IProxyCache.cs +++ b/src/NHibernate/Proxy/DynamicProxy/IProxyCache.cs @@ -11,13 +11,16 @@ namespace NHibernate.Proxy.DynamicProxy { + //Since v5.1 + [Obsolete("This interface is not used anymore and will be removed in a next major version")] public interface IProxyCache { bool Contains(System.Type baseType, params System.Type[] baseInterfaces); + TypeInfo GetProxyType(System.Type baseType, params System.Type[] baseInterfaces); bool TryGetProxyType(System.Type baseType, System.Type[] baseInterfaces, out TypeInfo proxyType); void StoreProxyType(TypeInfo result, System.Type baseType, params System.Type[] baseInterfaces); } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyCache.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyCache.cs index f6588df3364..546bd5a9809 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyCache.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyCache.cs @@ -6,32 +6,28 @@ #endregion -using System.Collections.Concurrent; +using System; using System.Reflection; namespace NHibernate.Proxy.DynamicProxy { + //Since v5.1 + [Obsolete("This class is not used anymore and will be removed in a next major version")] public class ProxyCache : IProxyCache { - private static readonly ConcurrentDictionary cache = new ConcurrentDictionary(); - - #region IProxyCache Members - public bool Contains(System.Type baseType, params System.Type[] baseInterfaces) { if (baseType == null) - { return false; - } var entry = new ProxyCacheEntry(baseType, baseInterfaces); - return cache.ContainsKey(entry); + return ProxyFactory._cache.ContainsKey(entry); } public TypeInfo GetProxyType(System.Type baseType, params System.Type[] baseInterfaces) { var entry = new ProxyCacheEntry(baseType, baseInterfaces); - return cache[entry]; + return ProxyFactory._cache[entry]; } public bool TryGetProxyType(System.Type baseType, System.Type[] baseInterfaces, out TypeInfo proxyType) @@ -42,15 +38,13 @@ public bool TryGetProxyType(System.Type baseType, System.Type[] baseInterfaces, return false; var entry = new ProxyCacheEntry(baseType, baseInterfaces); - return cache.TryGetValue(entry, out proxyType); + return ProxyFactory._cache.TryGetValue(entry, out proxyType); } public void StoreProxyType(TypeInfo result, System.Type baseType, params System.Type[] baseInterfaces) { var entry = new ProxyCacheEntry(baseType, baseInterfaces); - cache[entry] = result; + ProxyFactory._cache[entry] = result; } - - #endregion } } diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyCacheEntry.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyCacheEntry.cs index e3e69fe0fa9..e8118925729 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyCacheEntry.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyCacheEntry.cs @@ -8,29 +8,32 @@ using System; using System.Collections.Generic; +using System.Linq; namespace NHibernate.Proxy.DynamicProxy { public class ProxyCacheEntry : IEquatable { private readonly int _hashCode; + private readonly HashSet _uniqueInterfaces; public ProxyCacheEntry(System.Type baseType, System.Type[] interfaces) { - if (baseType == null) - throw new ArgumentNullException(nameof(baseType)); - BaseType = baseType; - _uniqueInterfaces = new HashSet(interfaces ?? new System.Type[0]); + BaseType = baseType ?? throw new ArgumentNullException(nameof(baseType)); - if (_uniqueInterfaces.Count == 0) + var uniqueInterfaces = new HashSet(); + if (interfaces != null && interfaces.Length > 0) { - _hashCode = baseType.GetHashCode(); - return; + uniqueInterfaces.UnionWith(interfaces.Where(i => i != null)); } - - var allTypes = new List(_uniqueInterfaces) { baseType }; - _hashCode = 59; - foreach (System.Type type in allTypes) + _uniqueInterfaces = uniqueInterfaces; + + _hashCode = 59 ^ baseType.GetHashCode(); + + if (_uniqueInterfaces.Count == 0) + return; + + foreach (var type in _uniqueInterfaces) { // This simple implementation is nonsensitive to list order. If changing it for a sensitive one, // take care of ordering the list. @@ -39,14 +42,12 @@ public ProxyCacheEntry(System.Type baseType, System.Type[] interfaces) } public System.Type BaseType { get; } - public IReadOnlyCollection Interfaces { get { return _uniqueInterfaces; } } - - private HashSet _uniqueInterfaces; + + public IReadOnlyCollection Interfaces => _uniqueInterfaces; public override bool Equals(object obj) { - var that = obj as ProxyCacheEntry; - return Equals(that); + return Equals(obj as ProxyCacheEntry); } public bool Equals(ProxyCacheEntry other) @@ -64,4 +65,4 @@ public bool Equals(ProxyCacheEntry other) public override int GetHashCode() => _hashCode; } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs index 7ac74dbf668..4f35eb0d35a 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs @@ -7,18 +7,20 @@ #endregion using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Serialization; -using NHibernate.Linq; using NHibernate.Util; namespace NHibernate.Proxy.DynamicProxy { public sealed class ProxyFactory { + internal static readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); + private static readonly ConstructorInfo defaultBaseConstructor = typeof(object).GetConstructor(new System.Type[0]); private static readonly MethodInfo getValue = ReflectHelper.GetMethod( @@ -35,24 +37,21 @@ public ProxyFactory(IProxyAssemblyBuilder proxyAssemblyBuilder) : this(new DefaultyProxyMethodBuilder(), proxyAssemblyBuilder) {} public ProxyFactory(IProxyMethodBuilder proxyMethodBuilder) - : this(new DefaultyProxyMethodBuilder(), new DefaultProxyAssemblyBuilder()) {} + : this(proxyMethodBuilder, new DefaultProxyAssemblyBuilder()) {} public ProxyFactory(IProxyMethodBuilder proxyMethodBuilder, IProxyAssemblyBuilder proxyAssemblyBuilder) { - if (proxyMethodBuilder == null) - { - throw new ArgumentNullException("proxyMethodBuilder"); - } - ProxyMethodBuilder = proxyMethodBuilder; + ProxyMethodBuilder = proxyMethodBuilder ?? throw new ArgumentNullException(nameof(proxyMethodBuilder)); ProxyAssemblyBuilder = proxyAssemblyBuilder; - Cache = new ProxyCache(); } - public IProxyCache Cache { get; private set; } + //Since v5.1 + [Obsolete("This property is not used anymore and will be removed in a next major version")] + public IProxyCache Cache { get; } = new ProxyCache(); - public IProxyMethodBuilder ProxyMethodBuilder { get; private set; } + public IProxyMethodBuilder ProxyMethodBuilder { get; } - public IProxyAssemblyBuilder ProxyAssemblyBuilder { get; private set; } + public IProxyAssemblyBuilder ProxyAssemblyBuilder { get; } public object CreateProxy(System.Type instanceType, IInterceptor interceptor, params System.Type[] baseInterfaces) { @@ -60,37 +59,21 @@ public object CreateProxy(System.Type instanceType, IInterceptor interceptor, pa object result = Activator.CreateInstance(proxyType); var proxy = (IProxy) result; proxy.Interceptor = interceptor; - return result; } public System.Type CreateProxyType(System.Type baseType, params System.Type[] interfaces) { - System.Type[] baseInterfaces = ReferenceEquals(null, interfaces) ? new System.Type[0] : interfaces.Where(t => t != null).ToArray(); - - TypeInfo proxyTypeInfo; + if (baseType == null) throw new ArgumentNullException(nameof(baseType)); - // Reuse the previous results, if possible, Fast path without locking. - if (Cache.TryGetProxyType(baseType, baseInterfaces, out proxyTypeInfo)) - return proxyTypeInfo; + var typeFactory = _cache.GetOrAdd( + new ProxyCacheEntry(baseType, interfaces), + k => CreateUncachedProxyType(k.BaseType, k.Interfaces)); - lock (Cache) - { - // Recheck in case we got interrupted. - if (!Cache.TryGetProxyType(baseType, baseInterfaces, out proxyTypeInfo)) - { - proxyTypeInfo = CreateUncachedProxyType(baseType, baseInterfaces); - - // Cache the proxy type - if (proxyTypeInfo != null && Cache != null) - Cache.StoreProxyType(proxyTypeInfo, baseType, baseInterfaces); - } - - return proxyTypeInfo; - } + return typeFactory; } - private TypeInfo CreateUncachedProxyType(System.Type baseType, System.Type[] baseInterfaces) + private TypeInfo CreateUncachedProxyType(System.Type baseType, IReadOnlyCollection baseInterfaces) { AppDomain currentDomain = AppDomain.CurrentDomain; string typeName = string.Format("{0}Proxy", baseType.Name); @@ -102,10 +85,11 @@ private TypeInfo CreateUncachedProxyType(System.Type baseType, System.Type[] bas ModuleBuilder moduleBuilder = ProxyAssemblyBuilder.DefineDynamicModule(assemblyBuilder, moduleName); TypeAttributes typeAttributes = TypeAttributes.AutoClass | TypeAttributes.Class | - TypeAttributes.Public | TypeAttributes.BeforeFieldInit; + TypeAttributes.Public | TypeAttributes.BeforeFieldInit; var interfaces = new HashSet(); - interfaces.Merge(baseInterfaces); + interfaces.UnionWith(baseInterfaces); + interfaces.UnionWith(baseInterfaces.SelectMany(i => i.GetInterfaces())); // Use the proxy dummy as the base type // since we're not inheriting from any class type @@ -115,13 +99,7 @@ private TypeInfo CreateUncachedProxyType(System.Type baseType, System.Type[] bas parentType = typeof (ProxyDummy); interfaces.Add(baseType); } - - // Add any inherited interfaces - System.Type[] computedInterfaces = interfaces.ToArray(); - foreach (System.Type interfaceType in computedInterfaces) - { - interfaces.Merge(GetInterfaces(interfaceType)); - } + interfaces.UnionWith(baseType.GetInterfaces()); // Add the ISerializable interface so that it can be implemented interfaces.Add(typeof (ISerializable)); @@ -151,32 +129,14 @@ private TypeInfo CreateUncachedProxyType(System.Type baseType, System.Type[] bas return proxyType; } - private IEnumerable GetInterfaces(System.Type currentType) - { - return GetAllInterfaces(currentType); - } - - private IEnumerable GetAllInterfaces(System.Type currentType) - { - System.Type[] interfaces = currentType.GetInterfaces(); - - foreach (System.Type current in interfaces) - { - yield return current; - foreach (System.Type @interface in GetAllInterfaces(current)) - { - yield return @interface; - } - } - } - private IEnumerable GetProxiableMethods(System.Type type, IEnumerable interfaces) { const BindingFlags candidateMethodsBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - return + return type.GetMethods(candidateMethodsBindingFlags) - .Where(method=> method.IsProxiable()) - .Concat(interfaces.SelectMany(interfaceType => interfaceType.GetMethods())).Distinct(); + .Where(method => method.IsProxiable()) + .Concat(interfaces.SelectMany(interfaceType => interfaceType.GetMethods())) + .Distinct(); } private static ConstructorBuilder DefineConstructor(TypeBuilder typeBuilder, System.Type parentType) @@ -206,7 +166,7 @@ private static ConstructorBuilder DefineConstructor(TypeBuilder typeBuilder, Sys return constructor; } - private static void ImplementGetObjectData(System.Type baseType, System.Type[] baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField) + private static void ImplementGetObjectData(System.Type baseType, IReadOnlyCollection baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField) { const MethodAttributes attributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual; @@ -236,7 +196,7 @@ private static void ImplementGetObjectData(System.Type baseType, System.Type[] b IL.Emit(OpCodes.Ldstr, baseType.AssemblyQualifiedName); IL.Emit(OpCodes.Callvirt, addValue); - int baseInterfaceCount = baseInterfaces.Length; + int baseInterfaceCount = baseInterfaces.Count; // Save the number of base interfaces IL.Emit(OpCodes.Ldarg_1); @@ -294,7 +254,7 @@ private static void DefineSerializationConstructor(TypeBuilder typeBuilder, Fiel IL.Emit(OpCodes.Ret); } - private static void AddSerializationSupport(System.Type baseType, System.Type[] baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField, ConstructorBuilder defaultConstructor) + private static void AddSerializationSupport(System.Type baseType, IReadOnlyCollection baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField, ConstructorBuilder defaultConstructor) { ConstructorInfo serializableConstructor = typeof(SerializableAttribute).GetConstructor(new System.Type[0]); var customAttributeBuilder = new CustomAttributeBuilder(serializableConstructor, new object[0]); @@ -304,4 +264,4 @@ private static void AddSerializationSupport(System.Type baseType, System.Type[] ImplementGetObjectData(baseType, baseInterfaces, typeBuilder, interceptorField); } } -} \ No newline at end of file +} From a058d38eee7d23488a377248b903e1b90ef2e554 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Wed, 6 Dec 2017 01:35:18 -0700 Subject: [PATCH 13/32] Logging refactoring (#1377) * Always pass format arguments to the logger. * Enable better structured logging. * Update NHibernate.Example.Web to use new INHibernateLoggerFactory. --- .../Infrastructure/AppSessionFactory.cs | 2 +- .../NHibernateToMicrosoftLogger.cs | 127 +---- .../NHibernateToMicrosoftLoggerFactory.cs | 8 +- .../NHibernate.Example.Web.csproj | 2 + src/NHibernate.Example.Web/Program.cs | 10 + .../NHSpecificTest/CriteriaFromHql/Fixture.cs | 4 +- .../Async/NHSpecificTest/NH1144/Fixture.cs | 2 +- .../Async/NHSpecificTest/NH1347/Fixture.cs | 2 +- .../IdentityInsertWithStoredProcsTest.cs | 4 +- .../Logging/LoggerPerformanceTest.cs | 389 +++++++++++++ .../Logging/LoggerProviderTest.cs | 20 +- .../NHSpecificTest/CriteriaFromHql/Fixture.cs | 4 +- .../NHSpecificTest/NH1144/Fixture.cs | 2 +- .../NHSpecificTest/NH1347/Fixture.cs | 2 +- .../NHSpecificTest/NH1587/Fixture.cs | 4 +- .../IdentityInsertWithStoredProcsTest.cs | 4 +- src/NHibernate/AdoNet/AbstractBatcher.cs | 62 +-- src/NHibernate/AdoNet/ConnectionManager.cs | 2 +- .../AdoNet/MySqlClientBatchingBatcher.cs | 14 +- .../AdoNet/OracleDataClientBatchingBatcher.cs | 8 +- .../AdoNet/SqlClientBatchingBatcher.cs | 18 +- .../AdoNet/Util/SqlStatementLogger.cs | 6 +- src/NHibernate/AssertionFailure.cs | 6 +- .../Async/AdoNet/AbstractBatcher.cs | 28 +- .../AdoNet/MySqlClientBatchingBatcher.cs | 10 +- .../AdoNet/OracleDataClientBatchingBatcher.cs | 8 +- .../Async/AdoNet/SqlClientBatchingBatcher.cs | 10 +- .../Async/Cache/NonstrictReadWriteCache.cs | 28 +- src/NHibernate/Async/Cache/ReadOnlyCache.cs | 12 +- src/NHibernate/Async/Cache/ReadWriteCache.cs | 56 +- .../Async/Cache/StandardQueryCache.cs | 20 +- .../Async/Cache/UpdateTimestampsCache.cs | 4 +- .../Context/ThreadLocalSessionContext.cs | 6 +- .../Dialect/Lock/UpdateLockingStrategy.cs | 2 +- .../Async/Driver/NHybridDataReader.cs | 6 +- src/NHibernate/Async/Engine/ActionQueue.cs | 2 +- src/NHibernate/Async/Engine/Cascade.cs | 14 +- .../Async/Engine/CascadingAction.cs | 36 +- .../Async/Engine/CollectionEntry.cs | 6 +- src/NHibernate/Async/Engine/Collections.cs | 16 +- src/NHibernate/Async/Engine/ForeignKeys.cs | 7 +- .../Engine/Loading/CollectionLoadContext.cs | 31 +- .../Async/Engine/Query/HQLQueryPlan.cs | 14 +- src/NHibernate/Async/Engine/TwoPhaseLoad.cs | 12 +- src/NHibernate/Async/Engine/Versioning.cs | 18 +- .../Default/AbstractFlushingEventListener.cs | 31 +- .../AbstractLockUpgradeEventListener.cs | 4 +- .../AbstractReassociateEventListener.cs | 4 +- .../Default/AbstractSaveEventListener.cs | 28 +- .../Default/DefaultAutoFlushEventListener.cs | 4 +- .../Default/DefaultDeleteEventListener.cs | 4 +- .../Default/DefaultEvictEventListener.cs | 4 +- .../DefaultFlushEntityEventListener.cs | 10 +- ...efaultInitializeCollectionEventListener.cs | 8 +- .../Event/Default/DefaultLoadEventListener.cs | 34 +- .../Default/DefaultMergeEventListener.cs | 12 +- .../Default/DefaultRefreshEventListener.cs | 8 +- .../Default/DefaultReplicateEventListener.cs | 12 +- .../DefaultSaveOrUpdateEventListener.cs | 8 +- .../Async/Event/Default/ReattachVisitor.cs | 2 +- .../ANTLR/Exec/AbstractStatementExecutor.cs | 8 +- .../ANTLR/Exec/MultiTableDeleteExecutor.cs | 2 +- .../ANTLR/Exec/MultiTableUpdateExecutor.cs | 2 +- .../Async/Id/Enhanced/OptimizerFactory.cs | 4 +- .../Async/Id/Enhanced/SequenceStructure.cs | 6 +- .../Id/Enhanced/SequenceStyleGenerator.cs | 2 +- .../Async/Id/Enhanced/TableGenerator.cs | 4 +- .../Async/Id/Enhanced/TableStructure.cs | 11 +- .../Async/Id/IdentifierGeneratorFactory.cs | 6 +- src/NHibernate/Async/Id/IncrementGenerator.cs | 6 +- .../Async/Id/NativeGuidGenerator.cs | 4 +- src/NHibernate/Async/Id/SequenceGenerator.cs | 6 +- .../Async/Id/SequenceHiLoGenerator.cs | 6 +- src/NHibernate/Async/Id/TableGenerator.cs | 22 +- src/NHibernate/Async/Id/TableHiLoGenerator.cs | 4 +- .../Async/Impl/MultiCriteriaImpl.cs | 9 +- src/NHibernate/Async/Impl/MultiQueryImpl.cs | 27 +- .../Async/Impl/SessionFactoryImpl.cs | 24 +- src/NHibernate/Async/Impl/SessionImpl.cs | 20 +- .../Async/Impl/StatelessSessionImpl.cs | 4 +- .../Loader/Entity/CollectionElementLoader.cs | 2 +- .../Async/Loader/Entity/EntityLoader.cs | 2 +- src/NHibernate/Async/Loader/Loader.cs | 46 +- .../Collection/AbstractCollectionPersister.cs | 38 +- .../NamedQueryCollectionInitializer.cs | 6 +- .../Entity/AbstractEntityPersister.cs | 62 +-- .../Persister/Entity/NamedQueryLoader.cs | 6 +- .../Async/Tool/hbm2ddl/SchemaExport.cs | 14 +- .../Async/Tool/hbm2ddl/SchemaUpdate.cs | 12 +- .../Async/Tool/hbm2ddl/SchemaValidator.cs | 8 +- .../Transaction/AdoNetTransactionFactory.cs | 4 +- .../Async/Transaction/AdoTransaction.cs | 8 +- src/NHibernate/Async/Type/CollectionType.cs | 4 +- src/NHibernate/Async/Type/DbTimestampType.cs | 4 +- src/NHibernate/Cache/CacheFactory.cs | 10 +- src/NHibernate/Cache/NoCacheProvider.cs | 2 +- .../Cache/NonstrictReadWriteCache.cs | 32 +- src/NHibernate/Cache/ReadOnlyCache.cs | 24 +- src/NHibernate/Cache/ReadWriteCache.cs | 60 +- src/NHibernate/Cache/StandardQueryCache.cs | 26 +- src/NHibernate/Cache/UpdateTimestampsCache.cs | 10 +- src/NHibernate/Cfg/Configuration.cs | 54 +- .../HibernateConfiguration.cs | 6 +- .../SessionFactoryConfiguration.cs | 2 +- src/NHibernate/Cfg/Environment.cs | 15 +- src/NHibernate/Cfg/Mappings.cs | 8 +- src/NHibernate/Cfg/SettingsFactory.cs | 58 +- src/NHibernate/Cfg/XmlHbmBinding/Binder.cs | 2 +- .../Cfg/XmlHbmBinding/ClassBinder.cs | 2 +- .../Cfg/XmlHbmBinding/CollectionBinder.cs | 24 +- .../XmlHbmBinding/FilterDefinitionFactory.cs | 10 +- .../Cfg/XmlHbmBinding/FiltersBinder.cs | 4 +- .../Cfg/XmlHbmBinding/JoinedSubclassBinder.cs | 2 +- .../Cfg/XmlHbmBinding/MappingLogExtensions.cs | 4 +- .../Cfg/XmlHbmBinding/MappingRootBinder.cs | 2 +- .../Cfg/XmlHbmBinding/NamedQueryBinder.cs | 2 +- .../Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs | 2 +- .../Cfg/XmlHbmBinding/RootClassBinder.cs | 2 +- .../Cfg/XmlHbmBinding/SubclassBinder.cs | 2 +- .../Cfg/XmlHbmBinding/UnionSubclassBinder.cs | 2 +- .../Collection/PersistentArrayHolder.cs | 4 +- .../Connection/ConnectionProvider.cs | 2 +- .../Connection/ConnectionProviderFactory.cs | 8 +- .../Connection/DriverConnectionProvider.cs | 2 +- .../UserSuppliedConnectionProvider.cs | 2 +- .../Context/ThreadLocalSessionContext.cs | 8 +- src/NHibernate/Dialect/Dialect.cs | 4 +- .../Dialect/Lock/UpdateLockingStrategy.cs | 6 +- .../Dialect/Schema/AbstractTableMetadata.cs | 17 +- .../Driver/BasicResultSetsCommand.cs | 2 +- src/NHibernate/Driver/DriverBase.cs | 8 +- src/NHibernate/Driver/NHybridDataReader.cs | 8 +- src/NHibernate/Driver/OdbcDriver.cs | 6 +- src/NHibernate/Engine/ActionQueue.cs | 12 +- src/NHibernate/Engine/Cascade.cs | 16 +- src/NHibernate/Engine/CascadingAction.cs | 38 +- src/NHibernate/Engine/CollectionEntry.cs | 8 +- src/NHibernate/Engine/Collections.cs | 18 +- src/NHibernate/Engine/ForeignKeys.cs | 9 +- src/NHibernate/Engine/IdentifierValue.cs | 16 +- .../Engine/Loading/CollectionLoadContext.cs | 44 +- src/NHibernate/Engine/Loading/LoadContexts.cs | 20 +- src/NHibernate/Engine/Query/HQLQueryPlan.cs | 16 +- .../Engine/Query/NativeSQLQueryPlan.cs | 2 +- src/NHibernate/Engine/Query/QueryPlanCache.cs | 22 +- src/NHibernate/Engine/QueryParameters.cs | 6 +- .../Engine/StatefulPersistenceContext.cs | 12 +- src/NHibernate/Engine/Transaction/Isolater.cs | 2 +- src/NHibernate/Engine/TwoPhaseLoad.cs | 18 +- src/NHibernate/Engine/VersionValue.cs | 14 +- src/NHibernate/Engine/Versioning.cs | 20 +- .../Default/AbstractFlushingEventListener.cs | 37 +- .../AbstractLockUpgradeEventListener.cs | 6 +- .../AbstractReassociateEventListener.cs | 6 +- .../Default/AbstractSaveEventListener.cs | 30 +- .../Default/DefaultAutoFlushEventListener.cs | 6 +- .../Default/DefaultDeleteEventListener.cs | 6 +- .../Default/DefaultDirtyCheckEventListener.cs | 2 +- .../Default/DefaultEvictEventListener.cs | 6 +- .../DefaultFlushEntityEventListener.cs | 12 +- ...efaultInitializeCollectionEventListener.cs | 10 +- .../Event/Default/DefaultLoadEventListener.cs | 36 +- .../Default/DefaultMergeEventListener.cs | 14 +- .../Default/DefaultPersistEventListener.cs | 2 +- .../Default/DefaultRefreshEventListener.cs | 10 +- .../Default/DefaultReplicateEventListener.cs | 14 +- .../DefaultSaveOrUpdateEventListener.cs | 16 +- src/NHibernate/Event/Default/EvictVisitor.cs | 6 +- .../Event/Default/ReattachVisitor.cs | 8 +- src/NHibernate/Event/Default/WrapVisitor.cs | 6 +- .../SQLExceptionConverterFactory.cs | 8 +- src/NHibernate/Hql/Ast/ANTLR/ErrorCounter.cs | 10 +- .../ANTLR/Exec/AbstractStatementExecutor.cs | 20 +- .../Hql/Ast/ANTLR/Exec/BasicExecutor.cs | 2 +- .../ANTLR/Exec/MultiTableDeleteExecutor.cs | 6 +- .../ANTLR/Exec/MultiTableUpdateExecutor.cs | 6 +- .../Hql/Ast/ANTLR/HqlFilterPreprocessor.cs | 4 +- src/NHibernate/Hql/Ast/ANTLR/HqlParser.cs | 22 +- src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs | 32 +- .../Hql/Ast/ANTLR/QueryTranslatorImpl.cs | 20 +- .../Tree/AbstractRestrictableStatement.cs | 2 +- .../Hql/Ast/ANTLR/Tree/DeleteStatement.cs | 4 +- src/NHibernate/Hql/Ast/ANTLR/Tree/DotNode.cs | 42 +- .../Hql/Ast/ANTLR/Tree/FromClause.cs | 10 +- .../Hql/Ast/ANTLR/Tree/FromElement.cs | 23 +- .../Hql/Ast/ANTLR/Tree/FromElementFactory.cs | 22 +- .../Hql/Ast/ANTLR/Tree/FromElementType.cs | 8 +- .../Hql/Ast/ANTLR/Tree/FromReferenceNode.cs | 6 +- .../Hql/Ast/ANTLR/Tree/IndexNode.cs | 17 +- .../Hql/Ast/ANTLR/Tree/MethodNode.cs | 8 +- .../Hql/Ast/ANTLR/Tree/QueryNode.cs | 4 +- .../Hql/Ast/ANTLR/Tree/UpdateStatement.cs | 4 +- .../Hql/Ast/ANTLR/Util/JoinProcessor.cs | 8 +- .../Hql/Ast/ANTLR/Util/LiteralProcessor.cs | 22 +- .../Hql/Ast/ANTLR/Util/PathHelper.cs | 6 +- .../Hql/Ast/ANTLR/Util/SyntheticAndFactory.cs | 6 +- src/NHibernate/Hql/QuerySplitter.cs | 6 +- .../Id/Enhanced/OptimizerFactory.cs | 22 +- .../Id/Enhanced/SequenceStructure.cs | 8 +- .../Id/Enhanced/SequenceStyleGenerator.cs | 7 +- src/NHibernate/Id/Enhanced/TableGenerator.cs | 8 +- src/NHibernate/Id/Enhanced/TableStructure.cs | 13 +- .../Id/IdentifierGeneratorFactory.cs | 8 +- src/NHibernate/Id/IncrementGenerator.cs | 8 +- src/NHibernate/Id/NativeGuidGenerator.cs | 6 +- src/NHibernate/Id/SequenceGenerator.cs | 8 +- src/NHibernate/Id/SequenceHiLoGenerator.cs | 8 +- src/NHibernate/Id/TableGenerator.cs | 24 +- src/NHibernate/Id/TableHiLoGenerator.cs | 6 +- src/NHibernate/Impl/AbstractSessionImpl.cs | 2 +- src/NHibernate/Impl/EnumerableImpl.cs | 2 +- src/NHibernate/Impl/MultiCriteriaImpl.cs | 11 +- src/NHibernate/Impl/MultiQueryImpl.cs | 29 +- src/NHibernate/Impl/Printer.cs | 4 +- src/NHibernate/Impl/SessionFactoryImpl.cs | 48 +- .../Impl/SessionFactoryObjectFactory.cs | 22 +- src/NHibernate/Impl/SessionImpl.cs | 32 +- src/NHibernate/Impl/StatelessSessionImpl.cs | 10 +- src/NHibernate/LazyInitializationException.cs | 2 +- .../LinqToHqlGeneratorsRegistryFactory.cs | 8 +- src/NHibernate/Linq/LinqLogging.cs | 6 +- .../Collection/BasicCollectionLoader.cs | 6 +- .../Loader/Collection/OneToManyLoader.cs | 6 +- .../Loader/Criteria/CriteriaJoinWalker.cs | 2 +- .../Criteria/CriteriaQueryTranslator.cs | 12 +- .../Loader/Custom/Sql/SQLCustomQuery.cs | 6 +- .../Custom/Sql/SQLQueryReturnProcessor.cs | 8 +- .../Loader/Entity/AbstractEntityLoader.cs | 2 +- .../Loader/Entity/CascadeEntityLoader.cs | 4 +- .../Loader/Entity/CollectionElementLoader.cs | 6 +- src/NHibernate/Loader/Entity/EntityLoader.cs | 4 +- src/NHibernate/Loader/Loader.cs | 58 +- src/NHibernate/Logging.cs | 520 ++++++------------ src/NHibernate/Logging.extensions.cs | 154 ++++++ src/NHibernate/Logging.log4net.cs | 238 ++++++++ src/NHibernate/Logging.obsolete.cs | 435 +++++++++++++++ src/NHibernate/Mapping/RootClass.cs | 6 +- src/NHibernate/NonUniqueResultException.cs | 5 +- .../Collection/AbstractCollectionPersister.cs | 52 +- .../NamedQueryCollectionInitializer.cs | 8 +- .../Entity/AbstractEntityPersister.cs | 102 ++-- .../Persister/Entity/NamedQueryLoader.cs | 8 +- src/NHibernate/Proxy/DefaultProxyFactory.cs | 4 +- src/NHibernate/SqlCommand/InsertSelect.cs | 2 +- .../SqlCommand/Parser/SqlParserUtils.cs | 2 +- src/NHibernate/SqlCommand/SqlDeleteBuilder.cs | 20 +- src/NHibernate/SqlCommand/SqlInsertBuilder.cs | 18 +- src/NHibernate/SqlCommand/SqlSelectBuilder.cs | 18 +- src/NHibernate/SqlCommand/SqlUpdateBuilder.cs | 18 +- src/NHibernate/Stat/StatisticsImpl.cs | 60 +- .../Tool/hbm2ddl/DatabaseMetadata.cs | 4 +- src/NHibernate/Tool/hbm2ddl/SchemaExport.cs | 16 +- src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs | 14 +- .../Tool/hbm2ddl/SchemaValidator.cs | 10 +- .../Transaction/AdoNetTransactionFactory.cs | 6 +- .../AdoNetWithSystemTransactionFactory.cs | 14 +- src/NHibernate/Transaction/AdoTransaction.cs | 22 +- .../DistinctRootEntityResultTransformer.cs | 9 +- .../Component/AbstractComponentTuplizer.cs | 6 +- .../Tuple/Entity/AbstractEntityTuplizer.cs | 6 +- .../Tuple/Entity/DynamicMapEntityTuplizer.cs | 4 +- .../Tuple/Entity/EntityMetamodel.cs | 16 +- .../Tuple/Entity/PocoEntityTuplizer.cs | 20 +- src/NHibernate/Tuple/PocoInstantiator.cs | 6 +- src/NHibernate/Type/CollectionType.cs | 6 +- src/NHibernate/Type/CompositeCustomType.cs | 2 +- src/NHibernate/Type/DateType.cs | 4 +- src/NHibernate/Type/DbTimestampType.cs | 6 +- src/NHibernate/Type/NullableType.cs | 14 +- src/NHibernate/Type/TypeFactory.cs | 6 +- src/NHibernate/Util/ADOExceptionReporter.cs | 13 +- src/NHibernate/Util/FilterHelper.cs | 4 +- src/NHibernate/Util/JoinedEnumerable.cs | 2 +- src/NHibernate/Util/ReflectHelper.cs | 16 +- 274 files changed, 3088 insertions(+), 2136 deletions(-) create mode 100644 src/NHibernate.Test/Logging/LoggerPerformanceTest.cs create mode 100644 src/NHibernate/Logging.extensions.cs create mode 100644 src/NHibernate/Logging.log4net.cs create mode 100644 src/NHibernate/Logging.obsolete.cs diff --git a/src/NHibernate.Example.Web/Infrastructure/AppSessionFactory.cs b/src/NHibernate.Example.Web/Infrastructure/AppSessionFactory.cs index 663b9dfcbe8..38265648eda 100644 --- a/src/NHibernate.Example.Web/Infrastructure/AppSessionFactory.cs +++ b/src/NHibernate.Example.Web/Infrastructure/AppSessionFactory.cs @@ -13,7 +13,7 @@ public class AppSessionFactory public AppSessionFactory(Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { - NHibernate.LoggerProvider.SetLoggersFactory(new NHibernateToMicrosoftLoggerFactory(loggerFactory)); + NHibernate.NHibernateLogger.SetLoggersFactory(new NHibernateToMicrosoftLoggerFactory(loggerFactory)); var mapper = new ModelMapper(); mapper.AddMapping(); diff --git a/src/NHibernate.Example.Web/Infrastructure/NHibernateToMicrosoftLogger.cs b/src/NHibernate.Example.Web/Infrastructure/NHibernateToMicrosoftLogger.cs index 829cd67b903..f83a7f20ef6 100644 --- a/src/NHibernate.Example.Web/Infrastructure/NHibernateToMicrosoftLogger.cs +++ b/src/NHibernate.Example.Web/Infrastructure/NHibernateToMicrosoftLogger.cs @@ -1,9 +1,11 @@ using System; +using System.Collections.Generic; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Internal; namespace NHibernate.Example.Web.Infrastructure { - public class NHibernateToMicrosoftLogger : IInternalLogger + public class NHibernateToMicrosoftLogger : INHibernateLogger { private readonly ILogger _msLogger; @@ -12,122 +14,29 @@ public NHibernateToMicrosoftLogger(ILogger msLogger) _msLogger = msLogger ?? throw new ArgumentNullException(nameof(msLogger)); } - public void Error(object message) + private static readonly Dictionary MapLevels = new Dictionary { - if (IsErrorEnabled) - { - _msLogger.LogError(message.ToString()); - } - } - - public void Error(object message, Exception exception) - { - if (IsErrorEnabled) - { - _msLogger.LogError(exception, message.ToString()); - } - } - - public void ErrorFormat(string format, params object[] args) - { - if (IsErrorEnabled) - { - _msLogger.LogError(format, args); - } - } - - public void Fatal(object message) - { - if (IsFatalEnabled) - { - _msLogger.LogCritical(message.ToString()); - } - } - - public void Fatal(object message, Exception exception) - { - if (IsFatalEnabled) - { - _msLogger.LogCritical(exception, message.ToString()); - } - } - - public void Debug(object message) - { - if (IsDebugEnabled) - { - _msLogger.LogDebug(message.ToString()); - } - } + { NHibernateLogLevel.Trace, LogLevel.Trace }, + { NHibernateLogLevel.Debug, LogLevel.Debug }, + { NHibernateLogLevel.Warn, LogLevel.Warning }, + { NHibernateLogLevel.Error, LogLevel.Error }, + { NHibernateLogLevel.Fatal, LogLevel.Critical }, + { NHibernateLogLevel.None, LogLevel.None }, + }; - public void Debug(object message, Exception exception) + public void Log(NHibernateLogLevel logLevel, NHibernateLogValues state, Exception exception) { - if (IsDebugEnabled) - { - _msLogger.LogDebug(exception, message.ToString()); - } + _msLogger.Log(MapLevels[logLevel], 0, new FormattedLogValues(state.Format, state.Args), exception, MessageFormatter); } - public void DebugFormat(string format, params object[] args) + public bool IsEnabled(NHibernateLogLevel logLevel) { - if (IsDebugEnabled) - { - _msLogger.LogDebug(format, args); - } + return _msLogger.IsEnabled(MapLevels[logLevel]); } - public void Info(object message) + private static string MessageFormatter(object state, Exception error) { - if (IsInfoEnabled) - { - _msLogger.LogInformation(message.ToString()); - } + return state.ToString(); } - - public void Info(object message, Exception exception) - { - if (IsInfoEnabled) - { - _msLogger.LogInformation(exception, message.ToString()); - } - } - - public void InfoFormat(string format, params object[] args) - { - if (IsInfoEnabled) - { - _msLogger.LogInformation(format, args); - } - } - - public void Warn(object message) - { - if (IsWarnEnabled) - { - _msLogger.LogWarning(message.ToString()); - } - } - - public void Warn(object message, Exception exception) - { - if (IsWarnEnabled) - { - _msLogger.LogWarning(exception, message.ToString()); - } - } - - public void WarnFormat(string format, params object[] args) - { - if (IsWarnEnabled) - { - _msLogger.LogWarning(format, args); - } - } - - public bool IsErrorEnabled => _msLogger.IsEnabled(LogLevel.Error); - public bool IsFatalEnabled => _msLogger.IsEnabled(LogLevel.Critical); - public bool IsDebugEnabled => _msLogger.IsEnabled(LogLevel.Debug); - public bool IsInfoEnabled => _msLogger.IsEnabled(LogLevel.Information); - public bool IsWarnEnabled => _msLogger.IsEnabled(LogLevel.Warning); } -} \ No newline at end of file +} diff --git a/src/NHibernate.Example.Web/Infrastructure/NHibernateToMicrosoftLoggerFactory.cs b/src/NHibernate.Example.Web/Infrastructure/NHibernateToMicrosoftLoggerFactory.cs index e6293ca5624..0e732127cd4 100644 --- a/src/NHibernate.Example.Web/Infrastructure/NHibernateToMicrosoftLoggerFactory.cs +++ b/src/NHibernate.Example.Web/Infrastructure/NHibernateToMicrosoftLoggerFactory.cs @@ -2,7 +2,7 @@ namespace NHibernate.Example.Web.Infrastructure { - public class NHibernateToMicrosoftLoggerFactory : NHibernate.ILoggerFactory + public class NHibernateToMicrosoftLoggerFactory : INHibernateLoggerFactory { private readonly Microsoft.Extensions.Logging.ILoggerFactory _loggerFactory; @@ -11,16 +11,16 @@ public NHibernateToMicrosoftLoggerFactory(Microsoft.Extensions.Logging.ILoggerFa _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); } - public IInternalLogger LoggerFor(string keyName) + public INHibernateLogger LoggerFor(string keyName) { var msLogger = _loggerFactory.CreateLogger(keyName); return new NHibernateToMicrosoftLogger(msLogger); } - public IInternalLogger LoggerFor(System.Type type) + public INHibernateLogger LoggerFor(System.Type type) { return LoggerFor( Microsoft.Extensions.Logging.Abstractions.Internal.TypeNameHelper.GetTypeDisplayName(type)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Example.Web/NHibernate.Example.Web.csproj b/src/NHibernate.Example.Web/NHibernate.Example.Web.csproj index 31a677cf481..72eaca60cb2 100644 --- a/src/NHibernate.Example.Web/NHibernate.Example.Web.csproj +++ b/src/NHibernate.Example.Web/NHibernate.Example.Web.csproj @@ -14,6 +14,8 @@ + + diff --git a/src/NHibernate.Example.Web/Program.cs b/src/NHibernate.Example.Web/Program.cs index f3bbe60d2e4..bf57dbb80fe 100644 --- a/src/NHibernate.Example.Web/Program.cs +++ b/src/NHibernate.Example.Web/Program.cs @@ -7,6 +7,8 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; +using Serilog; +using Serilog.Events; namespace NHibernate.Example.Web { @@ -14,12 +16,20 @@ public class Program { public static void Main(string[] args) { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Debug() + .MinimumLevel.Override("Microsoft", LogEventLevel.Information) + .Enrich.FromLogContext() + .WriteTo.Console() + .CreateLogger(); + BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup() + .UseSerilog() .Build(); } } diff --git a/src/NHibernate.Test/Async/NHSpecificTest/CriteriaFromHql/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/CriteriaFromHql/Fixture.cs index f19fce7514b..4064356a623 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/CriteriaFromHql/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/CriteriaFromHql/Fixture.cs @@ -48,7 +48,7 @@ join fetch c.Children gc where p.Parent is null") .UniqueResultAsync()); - string hqlQuery = spy.Appender.GetEvents()[0].MessageObject.ToString(); + string hqlQuery = spy.Appender.GetEvents()[0].RenderedMessage; Debug.WriteLine("HQL: " + hqlQuery); Assertions(result); } @@ -62,7 +62,7 @@ join fetch c.Children gc .SetFetchMode("Children", FetchMode.Join) .SetFetchMode("Children.Children", FetchMode.Join) .UniqueResultAsync()); - string criteriaQuery = spy.Appender.GetEvents()[0].MessageObject.ToString(); + string criteriaQuery = spy.Appender.GetEvents()[0].RenderedMessage; Debug.WriteLine("Criteria: " + criteriaQuery); Assertions(result); } diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1144/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1144/Fixture.cs index 1e7ecd3c116..1e8dc255183 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1144/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1144/Fixture.cs @@ -64,7 +64,7 @@ public async Task CanSaveInSingleBatchAsync() await (tx.CommitAsync()); foreach (LoggingEvent loggingEvent in spy.Appender.GetEvents()) { - if ("Executing batch".Equals(loggingEvent.MessageObject)) + if ("Executing batch".Equals(loggingEvent.RenderedMessage)) { executedBatch = true; break; diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1347/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1347/Fixture.cs index b7994c7cb68..44942d103fa 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1347/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1347/Fixture.cs @@ -49,7 +49,7 @@ public async Task BugAsync() .UniqueResultAsync()); Assert.AreEqual("1", a.Name); Assert.IsTrue( - spy.Appender.GetEvents()[0].MessageObject.ToString().Contains("limit") + spy.Appender.GetEvents()[0].RenderedMessage.Contains("limit") ); } diff --git a/src/NHibernate.Test/Async/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs b/src/NHibernate.Test/Async/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs index 423153bc6c4..ac20468608c 100644 --- a/src/NHibernate.Test/Async/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs +++ b/src/NHibernate.Test/Async/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs @@ -51,7 +51,7 @@ public async Task InsertUsesStoredProcAsync() Assert.AreEqual(1, spy.Appender.GetEvents().Length, "Num loggedEvents"); Assert.AreEqual(1, ifa.Id, "ifa.Id"); - Assert.AreEqual(GetExpectedInsertOrgLogStatement("IFA"), spy.Appender.GetEvents()[0].MessageObject, "Message 1"); + Assert.AreEqual(GetExpectedInsertOrgLogStatement("IFA"), spy.Appender.GetEvents()[0].RenderedMessage, "Message 1"); using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { @@ -73,7 +73,7 @@ public async Task InsertUsesStoredProcAsync() Assert.AreEqual(1, spy.Appender.GetEvents().Length, "Num loggedEvents"); Assert.AreEqual(2, efa.Id, "efa.Id"); - Assert.AreEqual(GetExpectedInsertOrgLogStatement("EFA"), spy.Appender.GetEvents()[0].MessageObject, "Message 2"); + Assert.AreEqual(GetExpectedInsertOrgLogStatement("EFA"), spy.Appender.GetEvents()[0].RenderedMessage, "Message 2"); using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { diff --git a/src/NHibernate.Test/Logging/LoggerPerformanceTest.cs b/src/NHibernate.Test/Logging/LoggerPerformanceTest.cs new file mode 100644 index 00000000000..a945c0fcd47 --- /dev/null +++ b/src/NHibernate.Test/Logging/LoggerPerformanceTest.cs @@ -0,0 +1,389 @@ +using System; +using System.Diagnostics; +using NUnit.Framework; + +namespace NHibernate.Test.Logging +{ + [TestFixture] + public class LoggerPerformanceTest + { + private static int errorLoggedCount = 0; + private static int fatalLoggedCount = 0; + private static int debugLoggedCount = 0; + private static int infoLoggedCount = 0; + private static int warnLoggedCount = 0; + + [Obsolete("Tests obsolete methods")] + private class MockLoggerFactory : ILoggerFactory + { + public IInternalLogger LoggerFor(string keyName) + { + return new MockLogger(); + } + + public IInternalLogger LoggerFor(System.Type type) + { + return new MockLogger(); + } + } + + [Obsolete("Tests obsolete methods")] + private class MockLogger : IInternalLogger + { + public bool IsErrorEnabled { get; } = true; + public bool IsFatalEnabled { get; } = true; + public bool IsDebugEnabled { get; } = false; + public bool IsInfoEnabled { get; } = false; + public bool IsWarnEnabled { get; } = true; + + public void Error(object message) + { + if (IsErrorEnabled) errorLoggedCount += message.ToString().Length; + } + + public void Error(object message, Exception exception) + { + if (IsErrorEnabled) errorLoggedCount += message.ToString().Length; + } + + public void ErrorFormat(string format, params object[] args) + { + if (IsErrorEnabled) errorLoggedCount += string.Format(format, args).Length; + } + + public void Fatal(object message) + { + if (IsFatalEnabled) fatalLoggedCount += message.ToString().Length; + } + + public void Fatal(object message, Exception exception) + { + if (IsFatalEnabled) fatalLoggedCount += message.ToString().Length; + } + + public void Debug(object message) + { + if (IsDebugEnabled) debugLoggedCount += message.ToString().Length; + } + + public void Debug(object message, Exception exception) + { + if (IsDebugEnabled) debugLoggedCount += message.ToString().Length; + } + + public void DebugFormat(string format, params object[] args) + { + if (IsDebugEnabled) debugLoggedCount += string.Format(format, args).Length; + } + + public void Info(object message) + { + if (IsInfoEnabled) infoLoggedCount += message.ToString().Length; + } + + public void Info(object message, Exception exception) + { + if (IsInfoEnabled) infoLoggedCount += message.ToString().Length; + } + + public void InfoFormat(string format, params object[] args) + { + if (IsInfoEnabled) infoLoggedCount += string.Format(format, args).Length; + } + + public void Warn(object message) + { + if (IsWarnEnabled) warnLoggedCount += message.ToString().Length; + } + + public void Warn(object message, Exception exception) + { + if (IsWarnEnabled) warnLoggedCount += message.ToString().Length; + } + + public void WarnFormat(string format, params object[] args) + { + if (IsWarnEnabled) warnLoggedCount += string.Format(format, args).Length; + } + } + + private class MockNHibernateLoggerFactory : INHibernateLoggerFactory + { + public INHibernateLogger LoggerFor(string keyName) + { + return new MockLogger2(); + } + + public INHibernateLogger LoggerFor(System.Type type) + { + return new MockLogger2(); + } + } + + private class MockLogger2 : INHibernateLogger + { + private bool IsErrorEnabled { get; } = true; + private bool IsFatalEnabled { get; } = true; + private bool IsDebugEnabled { get; } = false; + private bool IsInfoEnabled { get; } = false; + private bool IsWarnEnabled { get; } = true; + + public void Log(NHibernateLogLevel logLevel, NHibernateLogValues state, Exception exception) + { + if (!IsEnabled(logLevel)) return; + + if (state.Args?.Length > 0) + { + errorLoggedCount += string.Format(state.Format, state.Args).Length; + } + else + { + errorLoggedCount += state.Format.Length; + } + } + + public bool IsEnabled(NHibernateLogLevel logLevel) + { + switch (logLevel) + { + case NHibernateLogLevel.Trace: + case NHibernateLogLevel.Debug: + return IsDebugEnabled; + case NHibernateLogLevel.Info: + return IsInfoEnabled; + case NHibernateLogLevel.Warn: + return IsWarnEnabled; + case NHibernateLogLevel.Error: + return IsErrorEnabled; + case NHibernateLogLevel.Fatal: + return IsFatalEnabled; + case NHibernateLogLevel.None: + return !IsFatalEnabled; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + } + } + + private static void ResetCounts() + { + errorLoggedCount = 0; + fatalLoggedCount = 0; + debugLoggedCount = 0; + infoLoggedCount = 0; + warnLoggedCount = 0; + } + + private static long GetCounts() + { + return (long) errorLoggedCount + fatalLoggedCount + debugLoggedCount + infoLoggedCount + warnLoggedCount; + } + + [Test, Explicit("High-iteration performance test")] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [Obsolete("Tests obsolete methods")] + public void OldLoggerFactoryTimingsForDisabledLogging(int iteration) + { + ResetCounts(); + ILoggerFactory loggerFactory = new MockLoggerFactory(); + IInternalLogger logger = loggerFactory.LoggerFor(this.GetType()); + + var stopwatch = Stopwatch.StartNew(); + var iterationCount = 10000000; + for (int i = 0; i < iterationCount; i++) + { + logger.Debug("message"); + logger.DebugFormat("message with parameters {0}, {1}", "string", 5); + } + + stopwatch.Stop(); + Console.WriteLine( + "{0} wrote {1:N0} characters to log in {2} ms", + nameof(OldLoggerFactoryTimingsForDisabledLogging), + GetCounts(), + stopwatch.ElapsedMilliseconds); + } + + [Test, Explicit("High-iteration performance test")] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [Obsolete("Tests obsolete methods")] + public void OldLoggerFactoryTimingsForEnabledLogging(int iteration) + { + ResetCounts(); + ILoggerFactory loggerFactory = new MockLoggerFactory(); + IInternalLogger logger = loggerFactory.LoggerFor(this.GetType()); + + var stopwatch = Stopwatch.StartNew(); + var iterationCount = 10000000; + for (int i = 0; i < iterationCount; i++) + { + logger.Warn("message"); + logger.WarnFormat("message with parameters {0}, {1}", "string", 5); + } + + stopwatch.Stop(); + Console.WriteLine( + "{0} wrote {1:N0} characters to log in {2} ms", + nameof(OldLoggerFactoryTimingsForEnabledLogging), + GetCounts(), + stopwatch.ElapsedMilliseconds); + } + + [Test, Explicit("High-iteration performance test")] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [Obsolete("Tests obsolete methods")] + public void OldLoggerFactoryThunkedTimingsForDisabledLogging(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.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(OldLoggerFactoryThunkedTimingsForDisabledLogging), + GetCounts(), + stopwatch.ElapsedMilliseconds); + } + + [Test, Explicit("High-iteration performance test")] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [Obsolete("Tests obsolete methods")] + 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); + } + + [Test, Explicit("High-iteration performance test")] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [Obsolete("Tests obsolete methods")] + public void NewLoggerFactoryTimingsForDisabledLogging(int iteration) + { + ResetCounts(); + INHibernateLoggerFactory loggerFactory = new MockNHibernateLoggerFactory(); + NHibernateLogger.SetLoggersFactory(loggerFactory); + 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); + } + + [Test, Explicit("High-iteration performance test")] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [Obsolete("Tests obsolete methods")] + public void NewLoggerFactoryTimingsForEnabledLogging(int iteration) + { + ResetCounts(); + INHibernateLoggerFactory loggerFactory = new MockNHibernateLoggerFactory(); + NHibernateLogger.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(NewLoggerFactoryTimingsForEnabledLogging), + GetCounts(), + stopwatch.ElapsedMilliseconds); + } + + [Test, Explicit("High-iteration performance test")] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + [Obsolete("Tests obsolete methods")] + 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); + } + } +} diff --git a/src/NHibernate.Test/Logging/LoggerProviderTest.cs b/src/NHibernate.Test/Logging/LoggerProviderTest.cs index 617246053fd..75c01b6148d 100644 --- a/src/NHibernate.Test/Logging/LoggerProviderTest.cs +++ b/src/NHibernate.Test/Logging/LoggerProviderTest.cs @@ -8,14 +8,28 @@ public class LoggerProviderTest [Test] public void LoggerProviderCanCreateLoggers() { - Assert.That(LoggerProvider.LoggerFor("pizza"), Is.Not.Null); - Assert.That(LoggerProvider.LoggerFor(typeof (LoggerProviderTest)), Is.Not.Null); + Assert.That(NHibernateLogger.For("pizza"), Is.Not.Null); + Assert.That(NHibernateLogger.For(typeof (LoggerProviderTest)), Is.Not.Null); } [Test] public void WhenNotConfiguredAndLog4NetExistsThenUseLog4NetFactory() { - Assert.That(LoggerProvider.LoggerFor("pizza"), Is.InstanceOf()); +#pragma warning disable 618 + Assert.That(NHibernateLogger.For("pizza"), Is.Not.InstanceOf()); +#pragma warning restore 618 + + // NoLoggingNHibernateLogger is internal + Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.Not.EqualTo("NoLoggingNHibernateLogger")); + } + + [Test, Explicit("Changes global state.")] + public void WhenConfiguredAsNullThenNoLoggingFactoryIsUsed() + { + NHibernateLogger.SetLoggersFactory(default(INHibernateLoggerFactory)); + + // NoLoggingNHibernateLogger is internal + Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.EqualTo("NoLoggingNHibernateLogger")); } } } diff --git a/src/NHibernate.Test/NHSpecificTest/CriteriaFromHql/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/CriteriaFromHql/Fixture.cs index 8e240b5b718..0d7c224de6c 100644 --- a/src/NHibernate.Test/NHSpecificTest/CriteriaFromHql/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/CriteriaFromHql/Fixture.cs @@ -36,7 +36,7 @@ join fetch c.Children gc where p.Parent is null") .UniqueResult(); - string hqlQuery = spy.Appender.GetEvents()[0].MessageObject.ToString(); + string hqlQuery = spy.Appender.GetEvents()[0].RenderedMessage; Debug.WriteLine("HQL: " + hqlQuery); Assertions(result); } @@ -50,7 +50,7 @@ join fetch c.Children gc .SetFetchMode("Children", FetchMode.Join) .SetFetchMode("Children.Children", FetchMode.Join) .UniqueResult(); - string criteriaQuery = spy.Appender.GetEvents()[0].MessageObject.ToString(); + string criteriaQuery = spy.Appender.GetEvents()[0].RenderedMessage; Debug.WriteLine("Criteria: " + criteriaQuery); Assertions(result); } diff --git a/src/NHibernate.Test/NHSpecificTest/NH1144/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1144/Fixture.cs index d65ec9606ea..be3b8d7a7b0 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1144/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1144/Fixture.cs @@ -53,7 +53,7 @@ public void CanSaveInSingleBatch() tx.Commit(); foreach (LoggingEvent loggingEvent in spy.Appender.GetEvents()) { - if ("Executing batch".Equals(loggingEvent.MessageObject)) + if ("Executing batch".Equals(loggingEvent.RenderedMessage)) { executedBatch = true; break; diff --git a/src/NHibernate.Test/NHSpecificTest/NH1347/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1347/Fixture.cs index 9d91f06c6df..c439bb59caa 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1347/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1347/Fixture.cs @@ -39,7 +39,7 @@ public void Bug() .UniqueResult(); Assert.AreEqual("1", a.Name); Assert.IsTrue( - spy.Appender.GetEvents()[0].MessageObject.ToString().Contains("limit") + spy.Appender.GetEvents()[0].RenderedMessage.Contains("limit") ); } diff --git a/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs index 6bb204eb031..6a716ce5a66 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1587/Fixture.cs @@ -25,7 +25,7 @@ public void Bug() cfg.BuildSessionFactory(); foreach (LoggingEvent loggingEvent in ls.Appender.GetEvents()) { - if (((string)(loggingEvent.MessageObject)).StartsWith("Create Instantiator using optimizer")) + if (loggingEvent.RenderedMessage.StartsWith("Create Instantiator using optimizer")) { useOptimizer = true; break; @@ -35,4 +35,4 @@ public void Bug() Assert.That(useOptimizer); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs b/src/NHibernate.Test/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs index cef8c84d521..97dd424543b 100644 --- a/src/NHibernate.Test/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs +++ b/src/NHibernate.Test/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs @@ -40,7 +40,7 @@ public void InsertUsesStoredProc() Assert.AreEqual(1, spy.Appender.GetEvents().Length, "Num loggedEvents"); Assert.AreEqual(1, ifa.Id, "ifa.Id"); - Assert.AreEqual(GetExpectedInsertOrgLogStatement("IFA"), spy.Appender.GetEvents()[0].MessageObject, "Message 1"); + Assert.AreEqual(GetExpectedInsertOrgLogStatement("IFA"), spy.Appender.GetEvents()[0].RenderedMessage, "Message 1"); using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { @@ -62,7 +62,7 @@ public void InsertUsesStoredProc() Assert.AreEqual(1, spy.Appender.GetEvents().Length, "Num loggedEvents"); Assert.AreEqual(2, efa.Id, "efa.Id"); - Assert.AreEqual(GetExpectedInsertOrgLogStatement("EFA"), spy.Appender.GetEvents()[0].MessageObject, "Message 2"); + Assert.AreEqual(GetExpectedInsertOrgLogStatement("EFA"), spy.Appender.GetEvents()[0].RenderedMessage, "Message 2"); using (ISession s = OpenSession()) using (ITransaction t = s.BeginTransaction()) { diff --git a/src/NHibernate/AdoNet/AbstractBatcher.cs b/src/NHibernate/AdoNet/AbstractBatcher.cs index 00820420d52..f31862b6662 100644 --- a/src/NHibernate/AdoNet/AbstractBatcher.cs +++ b/src/NHibernate/AdoNet/AbstractBatcher.cs @@ -20,7 +20,7 @@ namespace NHibernate.AdoNet /// public abstract partial class AbstractBatcher : IBatcher { - protected static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(AbstractBatcher)); + protected static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(AbstractBatcher)); private static int _openCommandCount; private static int _openReaderCount; @@ -73,9 +73,9 @@ public DbCommand Generate(CommandType type, SqlString sqlString, SqlType[] param var cmd = _factory.ConnectionProvider.Driver.GenerateCommand(type, sql, parameterTypes); LogOpenPreparedCommand(); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Building an DbCommand object for the SqlString: " + sql); + Log.Debug("Building an DbCommand object for the SqlString: {0}", sql); } _commandsToClose.Add(cmd); return cmd; @@ -122,9 +122,9 @@ public virtual DbCommand PrepareBatchCommand(CommandType type, SqlString sql, Sq { if (sql.Equals(_batchCommandSql) && ArrayHelper.ArrayEquals(parameterTypes, _batchCommandParameterTypes)) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("reusing command " + _batchCommand.CommandText); + Log.Debug("reusing command {0}", _batchCommand.CommandText); } } else @@ -190,7 +190,7 @@ public int ExecuteNonQuery(DbCommand cmd) LogCommand(cmd); Prepare(cmd); Stopwatch duration = null; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) duration = Stopwatch.StartNew(); try { @@ -199,13 +199,13 @@ public int ExecuteNonQuery(DbCommand cmd) catch (Exception e) { e.Data["actual-sql-query"] = cmd.CommandText; - Log.Error("Could not execute command: " + cmd.CommandText, e); + Log.Error(e, "Could not execute command: {0}", cmd.CommandText); throw; } finally { - if (Log.IsDebugEnabled && duration != null) - Log.DebugFormat("ExecuteNonQuery took {0} ms", duration.ElapsedMilliseconds); + if (Log.IsDebugEnabled() && duration != null) + Log.Debug("ExecuteNonQuery took {0} ms", duration.ElapsedMilliseconds); } } @@ -215,7 +215,7 @@ public virtual DbDataReader ExecuteReader(DbCommand cmd) LogCommand(cmd); Prepare(cmd); Stopwatch duration = null; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) duration = Stopwatch.StartNew(); DbDataReader reader = null; try @@ -225,14 +225,14 @@ public virtual DbDataReader ExecuteReader(DbCommand cmd) catch (Exception e) { e.Data["actual-sql-query"] = cmd.CommandText; - Log.Error("Could not execute query: " + cmd.CommandText, e); + Log.Error(e, "Could not execute query: {0}", cmd.CommandText); throw; } finally { - if (Log.IsDebugEnabled && duration != null && reader != null) + if (Log.IsDebugEnabled() && duration != null && reader != null) { - Log.DebugFormat("ExecuteReader took {0} ms", duration.ElapsedMilliseconds); + Log.Debug("ExecuteReader took {0} ms", duration.ElapsedMilliseconds); _readersDuration[reader] = duration; } } @@ -278,7 +278,7 @@ public virtual void CloseCommands() } catch (Exception e) { - Log.Warn("Could not close DbDataReader", e); + Log.Warn(e, "Could not close DbDataReader"); } } @@ -291,7 +291,7 @@ public virtual void CloseCommands() catch (Exception e) { // no big deal - Log.Warn("Could not close ADO.NET Command", e); + Log.Warn(e, "Could not close ADO.NET Command"); } } _commandsToClose.Clear(); @@ -312,7 +312,7 @@ private void CloseCommand(DbCommand cmd) } catch (Exception e) { - Log.Warn("exception clearing maxRows/queryTimeout", e); + Log.Warn(e, "exception clearing maxRows/queryTimeout"); return; // NOTE: early exit! } finally @@ -368,7 +368,7 @@ public void CloseReader(DbDataReader reader) catch (Exception e) { // NH2205 - prevent exceptions when closing the reader from hiding any original exception - Log.Warn("exception closing reader", e); + Log.Warn(e, "exception closing reader"); } LogCloseReader(); @@ -388,9 +388,9 @@ private Stopwatch GetReaderStopwatch(DbDataReader reader) private static void LogDuration(Stopwatch duration) { - if (!Log.IsDebugEnabled || duration == null) return; + if (!Log.IsDebugEnabled() || duration == null) return; - Log.DebugFormat("DataReader was closed after {0} ms", duration.ElapsedMilliseconds); + Log.Debug("DataReader was closed after {0} ms", duration.ElapsedMilliseconds); } public void ExecuteBatch() @@ -415,12 +415,12 @@ public void ExecuteBatch() protected void ExecuteBatchWithTiming(DbCommand ps) { Stopwatch duration = null; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) duration = Stopwatch.StartNew(); var countBeforeExecutingBatch = CountOfStatementsInCurrentBatch; DoExecuteBatch(ps); - if (Log.IsDebugEnabled && duration != null) - Log.DebugFormat("ExecuteBatch for {0} statements took {1} ms", + if (Log.IsDebugEnabled() && duration != null) + Log.Debug("ExecuteBatch for {0} statements took {1} ms", countBeforeExecutingBatch, duration.ElapsedMilliseconds); } @@ -478,10 +478,10 @@ protected void LogCommand(DbCommand command) private void LogOpenPreparedCommand() { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { int currentOpenCommandCount = Interlocked.Increment(ref _openCommandCount); - Log.Debug("Opened new DbCommand, open DbCommands: " + currentOpenCommandCount); + Log.Debug("Opened new DbCommand, open DbCommands: {0}", currentOpenCommandCount); } if (_factory.Statistics.IsStatisticsEnabled) @@ -492,10 +492,10 @@ private void LogOpenPreparedCommand() private void LogClosePreparedCommand() { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { int currentOpenCommandCount = Interlocked.Decrement(ref _openCommandCount); - Log.Debug("Closed DbCommand, open DbCommands: " + currentOpenCommandCount); + Log.Debug("Closed DbCommand, open DbCommands: {0}", currentOpenCommandCount); } if (_factory.Statistics.IsStatisticsEnabled) @@ -506,19 +506,19 @@ private void LogClosePreparedCommand() private static void LogOpenReader() { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { int currentOpenReaderCount = Interlocked.Increment(ref _openReaderCount); - Log.Debug("Opened DbDataReader, open DbDataReaders: " + currentOpenReaderCount); + Log.Debug("Opened DbDataReader, open DbDataReaders: {0}", currentOpenReaderCount); } } private static void LogCloseReader() { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { int currentOpenReaderCount = Interlocked.Decrement(ref _openReaderCount); - Log.Debug("Closed DbDataReader, open DbDataReaders :" + currentOpenReaderCount); + Log.Debug("Closed DbDataReader, open DbDataReaders :{0}", currentOpenReaderCount); } } @@ -623,4 +623,4 @@ protected SqlString GetSQL(SqlString sql) return sql; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/AdoNet/ConnectionManager.cs b/src/NHibernate/AdoNet/ConnectionManager.cs index e9881c737fd..80674df3cf5 100644 --- a/src/NHibernate/AdoNet/ConnectionManager.cs +++ b/src/NHibernate/AdoNet/ConnectionManager.cs @@ -19,7 +19,7 @@ namespace NHibernate.AdoNet [Serializable] public partial class ConnectionManager : ISerializable, IDeserializationCallback { - private static readonly IInternalLogger _log = LoggerProvider.LoggerFor(typeof(ConnectionManager)); + private static readonly INHibernateLogger _log = NHibernateLogger.For(typeof(ConnectionManager)); [NonSerialized] private DbConnection _connection; diff --git a/src/NHibernate/AdoNet/MySqlClientBatchingBatcher.cs b/src/NHibernate/AdoNet/MySqlClientBatchingBatcher.cs index 9bcead2ed17..3a24de6a914 100644 --- a/src/NHibernate/AdoNet/MySqlClientBatchingBatcher.cs +++ b/src/NHibernate/AdoNet/MySqlClientBatchingBatcher.cs @@ -45,7 +45,7 @@ public override void AddToBatch(IExpectation expectation) Driver.AdjustCommand(batchUpdate); string lineWithParameters = null; var sqlStatementLogger = Factory.Settings.SqlStatementLogger; - if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled) + if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled()) { lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate); var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic); @@ -55,9 +55,9 @@ public override void AddToBatch(IExpectation expectation) .Append(":") .AppendLine(lineWithParameters); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Adding to batch:" + lineWithParameters); + Log.Debug("Adding to batch:{0}", lineWithParameters); } currentBatch.Append(batchUpdate); @@ -71,7 +71,7 @@ protected override void DoExecuteBatch(DbCommand ps) { try { - Log.DebugFormat("Executing batch"); + Log.Debug("Executing batch"); CheckReaders(); if (Factory.Settings.SqlStatementLogger.IsDebugEnabled) { @@ -125,7 +125,7 @@ public override void CloseCommands() { // Prevent exceptions when clearing the batch from hiding any original exception // (We do not know here if this batch closing occurs after a failure or not.) - Log.Warn("Exception clearing batch", e); + Log.Warn(e, "Exception clearing batch"); } } @@ -140,8 +140,8 @@ protected override void Dispose(bool isDisposing) } catch (Exception e) { - Log.Warn("Exception closing batcher", e); + Log.Warn(e, "Exception closing batcher"); } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs b/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs index a9fff5425be..f2b536d1ec1 100644 --- a/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs +++ b/src/NHibernate/AdoNet/OracleDataClientBatchingBatcher.cs @@ -38,7 +38,7 @@ public override void AddToBatch(IExpectation expectation) _totalExpectedRowsAffected += expectation.ExpectedRowCount; string lineWithParameters = null; var sqlStatementLogger = Factory.Settings.SqlStatementLogger; - if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled) + if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled()) { lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(CurrentCommand); var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic); @@ -48,9 +48,9 @@ public override void AddToBatch(IExpectation expectation) .Append(":") .AppendLine(lineWithParameters); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Adding to batch:" + lineWithParameters); + Log.Debug("Adding to batch:{0}", lineWithParameters); } if (_currentBatch == null) @@ -167,4 +167,4 @@ public override int BatchSize set { _batchSize = value; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs b/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs index b7dd94e8a1b..716bf24fc85 100644 --- a/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs +++ b/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs @@ -47,7 +47,7 @@ public override void AddToBatch(IExpectation expectation) Driver.AdjustCommand(batchUpdate); string lineWithParameters = null; var sqlStatementLogger = Factory.Settings.SqlStatementLogger; - if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled) + if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled()) { lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate); var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic); @@ -57,9 +57,9 @@ public override void AddToBatch(IExpectation expectation) .Append(":") .AppendLine(lineWithParameters); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Adding to batch:" + lineWithParameters); + Log.Debug("Adding to batch:{0}", lineWithParameters); } _currentBatch.Append((System.Data.SqlClient.SqlCommand)batchUpdate); @@ -73,7 +73,7 @@ protected override void DoExecuteBatch(DbCommand ps) { try { - Log.DebugFormat("Executing batch"); + Log.Debug("Executing batch"); CheckReaders(); Prepare(_currentBatch.BatchCommand); if (Factory.Settings.SqlStatementLogger.IsDebugEnabled) @@ -109,9 +109,9 @@ private SqlClientSqlCommandSet CreateConfiguredBatch() } catch (Exception e) { - if (Log.IsWarnEnabled) + if (Log.IsWarnEnabled()) { - Log.Warn(e.ToString()); + Log.Warn(e, e.ToString()); } } } @@ -143,7 +143,7 @@ public override void CloseCommands() } catch (Exception e) { - Log.Warn("Exception clearing batch", e); + Log.Warn(e, "Exception clearing batch"); } } @@ -158,8 +158,8 @@ protected override void Dispose(bool isDisposing) } catch (Exception e) { - Log.Warn("Exception closing batcher", e); + Log.Warn(e, "Exception closing batcher"); } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/AdoNet/Util/SqlStatementLogger.cs b/src/NHibernate/AdoNet/Util/SqlStatementLogger.cs index cc0dd277e79..b911fd9f94b 100644 --- a/src/NHibernate/AdoNet/Util/SqlStatementLogger.cs +++ b/src/NHibernate/AdoNet/Util/SqlStatementLogger.cs @@ -8,7 +8,7 @@ namespace NHibernate.AdoNet.Util /// Centralize logging handling for SQL statements. public class SqlStatementLogger { - private static readonly IInternalLogger Logger = LoggerProvider.LoggerFor("NHibernate.SQL"); + private static readonly INHibernateLogger Logger = NHibernateLogger.For("NHibernate.SQL"); /// Constructs a new SqlStatementLogger instance. public SqlStatementLogger() : this(false, false) @@ -30,7 +30,7 @@ public SqlStatementLogger(bool logToStdout, bool formatSql) public bool IsDebugEnabled { - get { return Logger.IsDebugEnabled; } + get { return Logger.IsDebugEnabled(); } } /// Log a DbCommand. @@ -39,7 +39,7 @@ public bool IsDebugEnabled /// The requested formatting style. public virtual void LogCommand(string message, DbCommand command, FormatStyle style) { - if (!Logger.IsDebugEnabled && !LogToStdout || string.IsNullOrEmpty(command.CommandText)) + if (!Logger.IsDebugEnabled() && !LogToStdout || string.IsNullOrEmpty(command.CommandText)) { return; } diff --git a/src/NHibernate/AssertionFailure.cs b/src/NHibernate/AssertionFailure.cs index ba5a61b254e..ca4963d7dc6 100644 --- a/src/NHibernate/AssertionFailure.cs +++ b/src/NHibernate/AssertionFailure.cs @@ -17,7 +17,7 @@ public class AssertionFailure : Exception /// public AssertionFailure() : base(String.Empty) { - LoggerProvider.LoggerFor(typeof(AssertionFailure)).Error(DefaultMessage); + NHibernateLogger.For(typeof(AssertionFailure)).Error(DefaultMessage); } /// @@ -26,7 +26,7 @@ public AssertionFailure() : base(String.Empty) /// The message that describes the error. public AssertionFailure(string message) : base(message) { - LoggerProvider.LoggerFor(typeof(AssertionFailure)).Error(DefaultMessage, this); + NHibernateLogger.For(typeof(AssertionFailure)).Error(this, DefaultMessage); } /// @@ -40,7 +40,7 @@ public AssertionFailure(string message) : base(message) /// public AssertionFailure(string message, Exception innerException) : base(message, innerException) { - LoggerProvider.LoggerFor(typeof(AssertionFailure)).Error(DefaultMessage, innerException); + NHibernateLogger.For(typeof(AssertionFailure)).Error(innerException, DefaultMessage); } /// diff --git a/src/NHibernate/Async/AdoNet/AbstractBatcher.cs b/src/NHibernate/Async/AdoNet/AbstractBatcher.cs index ea85ee19dc3..af6e471c854 100644 --- a/src/NHibernate/Async/AdoNet/AbstractBatcher.cs +++ b/src/NHibernate/Async/AdoNet/AbstractBatcher.cs @@ -72,9 +72,9 @@ public virtual async Task PrepareBatchCommandAsync(CommandType type, cancellationToken.ThrowIfCancellationRequested(); if (sql.Equals(_batchCommandSql) && ArrayHelper.ArrayEquals(parameterTypes, _batchCommandParameterTypes)) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("reusing command " + _batchCommand.CommandText); + Log.Debug("reusing command {0}", _batchCommand.CommandText); } } else @@ -117,7 +117,7 @@ public async Task ExecuteNonQueryAsync(DbCommand cmd, CancellationToken can LogCommand(cmd); await (PrepareAsync(cmd, cancellationToken)).ConfigureAwait(false); Stopwatch duration = null; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) duration = Stopwatch.StartNew(); try { @@ -126,13 +126,13 @@ public async Task ExecuteNonQueryAsync(DbCommand cmd, CancellationToken can catch (Exception e) { e.Data["actual-sql-query"] = cmd.CommandText; - Log.Error("Could not execute command: " + cmd.CommandText, e); + Log.Error(e, "Could not execute command: {0}", cmd.CommandText); throw; } finally { - if (Log.IsDebugEnabled && duration != null) - Log.DebugFormat("ExecuteNonQuery took {0} ms", duration.ElapsedMilliseconds); + if (Log.IsDebugEnabled() && duration != null) + Log.Debug("ExecuteNonQuery took {0} ms", duration.ElapsedMilliseconds); } } @@ -143,7 +143,7 @@ public virtual async Task ExecuteReaderAsync(DbCommand cmd, Cancel LogCommand(cmd); await (PrepareAsync(cmd, cancellationToken)).ConfigureAwait(false); Stopwatch duration = null; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) duration = Stopwatch.StartNew(); DbDataReader reader = null; try @@ -153,14 +153,14 @@ public virtual async Task ExecuteReaderAsync(DbCommand cmd, Cancel catch (Exception e) { e.Data["actual-sql-query"] = cmd.CommandText; - Log.Error("Could not execute query: " + cmd.CommandText, e); + Log.Error(e, "Could not execute query: {0}", cmd.CommandText); throw; } finally { - if (Log.IsDebugEnabled && duration != null && reader != null) + if (Log.IsDebugEnabled() && duration != null && reader != null) { - Log.DebugFormat("ExecuteReader took {0} ms", duration.ElapsedMilliseconds); + Log.Debug("ExecuteReader took {0} ms", duration.ElapsedMilliseconds); _readersDuration[reader] = duration; } } @@ -219,12 +219,12 @@ protected async Task ExecuteBatchWithTimingAsync(DbCommand ps, CancellationToken { cancellationToken.ThrowIfCancellationRequested(); Stopwatch duration = null; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) duration = Stopwatch.StartNew(); var countBeforeExecutingBatch = CountOfStatementsInCurrentBatch; await (DoExecuteBatchAsync(ps, cancellationToken)).ConfigureAwait(false); - if (Log.IsDebugEnabled && duration != null) - Log.DebugFormat("ExecuteBatch for {0} statements took {1} ms", + if (Log.IsDebugEnabled() && duration != null) + Log.Debug("ExecuteBatch for {0} statements took {1} ms", countBeforeExecutingBatch, duration.ElapsedMilliseconds); } @@ -242,4 +242,4 @@ protected async Task ExecuteBatchWithTimingAsync(DbCommand ps, CancellationToken /// public abstract Task AddToBatchAsync(IExpectation expectation, CancellationToken cancellationToken); } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/AdoNet/MySqlClientBatchingBatcher.cs b/src/NHibernate/Async/AdoNet/MySqlClientBatchingBatcher.cs index 781680434a0..048670495b0 100644 --- a/src/NHibernate/Async/AdoNet/MySqlClientBatchingBatcher.cs +++ b/src/NHibernate/Async/AdoNet/MySqlClientBatchingBatcher.cs @@ -30,7 +30,7 @@ public override async Task AddToBatchAsync(IExpectation expectation, Cancellatio Driver.AdjustCommand(batchUpdate); string lineWithParameters = null; var sqlStatementLogger = Factory.Settings.SqlStatementLogger; - if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled) + if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled()) { lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate); var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic); @@ -40,9 +40,9 @@ public override async Task AddToBatchAsync(IExpectation expectation, Cancellatio .Append(":") .AppendLine(lineWithParameters); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Adding to batch:" + lineWithParameters); + Log.Debug("Adding to batch:{0}", lineWithParameters); } currentBatch.Append(batchUpdate); @@ -57,7 +57,7 @@ protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToke cancellationToken.ThrowIfCancellationRequested(); try { - Log.DebugFormat("Executing batch"); + Log.Debug("Executing batch"); await (CheckReadersAsync(cancellationToken)).ConfigureAwait(false); if (Factory.Settings.SqlStatementLogger.IsDebugEnabled) { @@ -82,4 +82,4 @@ protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToke } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/AdoNet/OracleDataClientBatchingBatcher.cs b/src/NHibernate/Async/AdoNet/OracleDataClientBatchingBatcher.cs index 1f426d910bc..c0921ad3d96 100644 --- a/src/NHibernate/Async/AdoNet/OracleDataClientBatchingBatcher.cs +++ b/src/NHibernate/Async/AdoNet/OracleDataClientBatchingBatcher.cs @@ -34,7 +34,7 @@ public override Task AddToBatchAsync(IExpectation expectation, CancellationToken _totalExpectedRowsAffected += expectation.ExpectedRowCount; string lineWithParameters = null; var sqlStatementLogger = Factory.Settings.SqlStatementLogger; - if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled) + if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled()) { lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(CurrentCommand); var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic); @@ -44,9 +44,9 @@ public override Task AddToBatchAsync(IExpectation expectation, CancellationToken .Append(":") .AppendLine(lineWithParameters); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Adding to batch:" + lineWithParameters); + Log.Debug("Adding to batch:{0}", lineWithParameters); } if (_currentBatch == null) @@ -151,4 +151,4 @@ protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToke } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/AdoNet/SqlClientBatchingBatcher.cs b/src/NHibernate/Async/AdoNet/SqlClientBatchingBatcher.cs index 0430b1290fb..6c84e3f517f 100644 --- a/src/NHibernate/Async/AdoNet/SqlClientBatchingBatcher.cs +++ b/src/NHibernate/Async/AdoNet/SqlClientBatchingBatcher.cs @@ -35,7 +35,7 @@ public override Task AddToBatchAsync(IExpectation expectation, CancellationToken Driver.AdjustCommand(batchUpdate); string lineWithParameters = null; var sqlStatementLogger = Factory.Settings.SqlStatementLogger; - if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled) + if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled()) { lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate); var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic); @@ -45,9 +45,9 @@ public override Task AddToBatchAsync(IExpectation expectation, CancellationToken .Append(":") .AppendLine(lineWithParameters); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Adding to batch:" + lineWithParameters); + Log.Debug("Adding to batch:{0}", lineWithParameters); } _currentBatch.Append((System.Data.SqlClient.SqlCommand)batchUpdate); @@ -68,7 +68,7 @@ protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToke cancellationToken.ThrowIfCancellationRequested(); try { - Log.DebugFormat("Executing batch"); + Log.Debug("Executing batch"); await (CheckReadersAsync(cancellationToken)).ConfigureAwait(false); await (PrepareAsync(_currentBatch.BatchCommand, cancellationToken)).ConfigureAwait(false); if (Factory.Settings.SqlStatementLogger.IsDebugEnabled) @@ -93,4 +93,4 @@ protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToke } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Cache/NonstrictReadWriteCache.cs b/src/NHibernate/Async/Cache/NonstrictReadWriteCache.cs index 22e1ac0139e..0fad6274303 100644 --- a/src/NHibernate/Async/Cache/NonstrictReadWriteCache.cs +++ b/src/NHibernate/Async/Cache/NonstrictReadWriteCache.cs @@ -25,9 +25,9 @@ public partial class NonstrictReadWriteCache : ICacheConcurrencyStrategy public async Task GetAsync(CacheKey key, long txTimestamp, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cache lookup: " + key); + log.Debug("Cache lookup: {0}", key); } object result = await (cache.GetAsync(key, cancellationToken)).ConfigureAwait(false); @@ -57,15 +57,15 @@ public async Task PutAsync(CacheKey key, object value, long txTimestamp, o if (minimalPut && await (cache.GetAsync(key, cancellationToken)).ConfigureAwait(false) != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("item already cached: " + key); + log.Debug("item already cached: {0}", key); } return false; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Caching: " + key); + log.Debug("Caching: {0}", key); } await (cache.PutAsync(key, value, cancellationToken)).ConfigureAwait(false); return true; @@ -98,9 +98,9 @@ public Task RemoveAsync(CacheKey key, CancellationToken cancellationToken) } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Removing: " + key); + log.Debug("Removing: {0}", key); } return cache.RemoveAsync(key, cancellationToken); } @@ -118,7 +118,7 @@ public Task ClearAsync(CancellationToken cancellationToken) } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("Clearing"); } @@ -141,9 +141,9 @@ public Task EvictAsync(CacheKey key, CancellationToken cancellationToken) } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Invalidating: " + key); + log.Debug("Invalidating: {0}", key); } return cache.RemoveAsync(key, cancellationToken); } @@ -174,9 +174,9 @@ public Task ReleaseAsync(CacheKey key, ISoftLock @lock, CancellationToken cancel } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Invalidating (again): " + key); + log.Debug("Invalidating (again): {0}", key); } return cache.RemoveAsync(key, cancellationToken); @@ -216,4 +216,4 @@ public Task AfterInsertAsync(CacheKey key, object value, object version, C } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Cache/ReadOnlyCache.cs b/src/NHibernate/Async/Cache/ReadOnlyCache.cs index 81f58dd8c05..7eec0fd2ef6 100644 --- a/src/NHibernate/Async/Cache/ReadOnlyCache.cs +++ b/src/NHibernate/Async/Cache/ReadOnlyCache.cs @@ -23,9 +23,9 @@ public async Task GetAsync(CacheKey key, long timestamp, CancellationTok { cancellationToken.ThrowIfCancellationRequested(); object result = await (cache.GetAsync(key, cancellationToken)).ConfigureAwait(false); - if (result != null && log.IsDebugEnabled) + if (result != null && log.IsDebugEnabled()) { - log.Debug("Cache hit: " + key); + log.Debug("Cache hit: {0}", key); } return result; } @@ -61,15 +61,15 @@ public async Task PutAsync(CacheKey key, object value, long timestamp, obj if (minimalPut && await (cache.GetAsync(key, cancellationToken)).ConfigureAwait(false) != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("item already cached: " + key); + log.Debug("item already cached: {0}", key); } return false; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Caching: " + key); + log.Debug("Caching: {0}", key); } await (cache.PutAsync(key, value, cancellationToken)).ConfigureAwait(false); return true; diff --git a/src/NHibernate/Async/Cache/ReadWriteCache.cs b/src/NHibernate/Async/Cache/ReadWriteCache.cs index adc9ba8b508..4ec55ec9558 100644 --- a/src/NHibernate/Async/Cache/ReadWriteCache.cs +++ b/src/NHibernate/Async/Cache/ReadWriteCache.cs @@ -42,9 +42,9 @@ public async Task GetAsync(CacheKey key, long txTimestamp, CancellationT cancellationToken.ThrowIfCancellationRequested(); using (await _lockObjectAsync.LockAsync()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cache lookup: " + key); + log.Debug("Cache lookup: {0}", key); } // commented out in H3.1 @@ -58,24 +58,24 @@ public async Task GetAsync(CacheKey key, long txTimestamp, CancellationT if (gettable) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cache hit: " + key); + log.Debug("Cache hit: {0}", key); } return ((CachedItem) lockable).Value; } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (lockable == null) { - log.Debug("Cache miss: " + key); + log.Debug("Cache miss: {0}", key); } else { - log.Debug("Cached item was locked: " + key); + log.Debug("Cached item was locked: {0}", key); } } return null; @@ -100,9 +100,9 @@ public async Task LockAsync(CacheKey key, object version, Cancellatio cancellationToken.ThrowIfCancellationRequested(); using (await _lockObjectAsync.LockAsync()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Invalidating: " + key); + log.Debug("Invalidating: {0}", key); } try @@ -143,9 +143,9 @@ public async Task PutAsync(CacheKey key, object value, long txTimestamp, o using (await _lockObjectAsync.LockAsync()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Caching: " + key); + log.Debug("Caching: {0}", key); } try @@ -160,23 +160,23 @@ public async Task PutAsync(CacheKey key, object value, long txTimestamp, o if (puttable) { await (cache.PutAsync(key, new CachedItem(value, cache.NextTimestamp(), version), cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cached: " + key); + log.Debug("Cached: {0}", key); } return true; } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (lockable.IsLock) { - log.Debug("Item was locked: " + key); + log.Debug("Item was locked: {0}", key); } else { - log.Debug("Item was already cached: " + key); + log.Debug("Item was already cached: {0}", key); } } return false; @@ -215,9 +215,9 @@ public async Task ReleaseAsync(CacheKey key, ISoftLock clientLock, CancellationT cancellationToken.ThrowIfCancellationRequested(); using (await _lockObjectAsync.LockAsync()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Releasing: " + key); + log.Debug("Releasing: {0}", key); } try @@ -249,7 +249,7 @@ internal Task HandleLockExpiryAsync(object key, CancellationToken cancellationTo } try { - log.Warn("An item was expired by the cache while it was locked (increase your cache timeout): " + key); + log.Warn("An item was expired by the cache while it was locked (increase your cache timeout): {0}", key); long ts = cache.NextTimestamp() + cache.Timeout; // create new lock that times out immediately CacheLock @lock = new CacheLock(ts, NextLockId(), null); @@ -289,9 +289,9 @@ public async Task AfterUpdateAsync(CacheKey key, object value, object vers cancellationToken.ThrowIfCancellationRequested(); using (await _lockObjectAsync.LockAsync()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Updating: " + key); + log.Debug("Updating: {0}", key); } try @@ -312,9 +312,9 @@ public async Task AfterUpdateAsync(CacheKey key, object value, object vers { //recache the updated state await (cache.PutAsync(key, new CachedItem(value, cache.NextTimestamp(), version), cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Updated: " + key); + log.Debug("Updated: {0}", key); } } return true; @@ -337,9 +337,9 @@ public async Task AfterInsertAsync(CacheKey key, object value, object vers cancellationToken.ThrowIfCancellationRequested(); using (await _lockObjectAsync.LockAsync()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting: " + key); + log.Debug("Inserting: {0}", key); } try @@ -350,9 +350,9 @@ public async Task AfterInsertAsync(CacheKey key, object value, object vers if (lockable == null) { await (cache.PutAsync(key, new CachedItem(value, cache.NextTimestamp(), version), cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserted: " + key); + log.Debug("Inserted: {0}", key); } return true; } @@ -402,4 +402,4 @@ public Task UpdateAsync(CacheKey key, object value, object currentVersion, } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Cache/StandardQueryCache.cs b/src/NHibernate/Async/Cache/StandardQueryCache.cs index af4b6f4372a..471abc23ede 100644 --- a/src/NHibernate/Async/Cache/StandardQueryCache.cs +++ b/src/NHibernate/Async/Cache/StandardQueryCache.cs @@ -43,8 +43,8 @@ public async Task PutAsync(QueryKey key, ICacheAssembler[] returnTypes, IL long ts = session.Timestamp; - if (Log.IsDebugEnabled) - Log.DebugFormat("caching query results in region: '{0}'; {1}", _regionName, key); + if (Log.IsDebugEnabled()) + Log.Debug("caching query results in region: '{0}'; {1}", _regionName, key); IList cacheable = new List(result.Count + 1) {ts}; for (int i = 0; i < result.Count; i++) @@ -67,28 +67,28 @@ public async Task PutAsync(QueryKey key, ICacheAssembler[] returnTypes, IL public async Task GetAsync(QueryKey key, ICacheAssembler[] returnTypes, bool isNaturalKeyLookup, ISet spaces, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (Log.IsDebugEnabled) - Log.DebugFormat("checking cached query results in region: '{0}'; {1}", _regionName, key); + if (Log.IsDebugEnabled()) + Log.Debug("checking cached query results in region: '{0}'; {1}", _regionName, key); var cacheable = (IList)await (_queryCache.GetAsync(key, cancellationToken)).ConfigureAwait(false); if (cacheable == null) { - Log.DebugFormat("query results were not found in cache: {0}", key); + Log.Debug("query results were not found in cache: {0}", key); return null; } var timestamp = (long)cacheable[0]; - if (Log.IsDebugEnabled) - Log.DebugFormat("Checking query spaces for up-to-dateness [{0}]", StringHelper.CollectionToString(spaces)); + if (Log.IsDebugEnabled()) + Log.Debug("Checking query spaces for up-to-dateness [{0}]", StringHelper.CollectionToString(spaces)); if (!isNaturalKeyLookup && !await (IsUpToDateAsync(spaces, timestamp, cancellationToken)).ConfigureAwait(false)) { - Log.DebugFormat("cached query results were not up to date for: {0}", key); + Log.Debug("cached query results were not up to date for: {0}", key); return null; } - Log.DebugFormat("returning cached query results for: {0}", key); + Log.Debug("returning cached query results for: {0}", key); for (int i = 1; i < cacheable.Count; i++) { if (returnTypes.Length == 1) @@ -145,4 +145,4 @@ protected virtual Task IsUpToDateAsync(ISet spaces, long timestamp return _updateTimestampsCache.IsUpToDateAsync(spaces, timestamp, cancellationToken); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Cache/UpdateTimestampsCache.cs b/src/NHibernate/Async/Cache/UpdateTimestampsCache.cs index 86a89e211ae..5a1867189fd 100644 --- a/src/NHibernate/Async/Cache/UpdateTimestampsCache.cs +++ b/src/NHibernate/Async/Cache/UpdateTimestampsCache.cs @@ -62,7 +62,7 @@ public async Task InvalidateAsync(object[] spaces, CancellationToken cancellatio //TODO: if lock.getTimestamp().equals(ts) for (int i = 0; i < spaces.Length; i++) { - log.Debug(string.Format("Invalidating space [{0}]", spaces[i])); + log.Debug("Invalidating space [{0}]", spaces[i]); await (updateTimestamps.PutAsync(spaces[i], ts, cancellationToken)).ConfigureAwait(false); } } @@ -108,4 +108,4 @@ public async Task IsUpToDateAsync(ISet spaces, long timestamp /* H } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Context/ThreadLocalSessionContext.cs b/src/NHibernate/Async/Context/ThreadLocalSessionContext.cs index ae76a4bccca..a2ebec50be5 100644 --- a/src/NHibernate/Async/Context/ThreadLocalSessionContext.cs +++ b/src/NHibernate/Async/Context/ThreadLocalSessionContext.cs @@ -40,14 +40,14 @@ private static async Task CleanupAnyOrphanedSessionAsync(ISessionFactory factory } catch (Exception ex) { - log.Debug("Unable to rollback transaction for orphaned session", ex); + log.Debug(ex, "Unable to rollback transaction for orphaned session"); } } orphan.Close(); } catch (Exception ex) { - log.Debug("Unable to close orphaned session", ex); + log.Debug(ex, "Unable to close orphaned session"); } } } @@ -60,4 +60,4 @@ public static async Task BindAsync(ISession session, CancellationToken cancellat DoBind(session, factory); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Dialect/Lock/UpdateLockingStrategy.cs b/src/NHibernate/Async/Dialect/Lock/UpdateLockingStrategy.cs index b7bb6004d96..0d39ebf758f 100644 --- a/src/NHibernate/Async/Dialect/Lock/UpdateLockingStrategy.cs +++ b/src/NHibernate/Async/Dialect/Lock/UpdateLockingStrategy.cs @@ -92,4 +92,4 @@ async Task InternalLockAsync() #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Driver/NHybridDataReader.cs b/src/NHibernate/Async/Driver/NHybridDataReader.cs index fd2de793da4..1706b3913a8 100644 --- a/src/NHibernate/Async/Driver/NHybridDataReader.cs +++ b/src/NHibernate/Async/Driver/NHybridDataReader.cs @@ -68,12 +68,12 @@ public async Task ReadIntoMemoryAsync(CancellationToken cancellationToken) cancellationToken.ThrowIfCancellationRequested(); if (_reader.IsClosed == false && _reader.GetType() != typeof(NDataReader)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Moving DbDataReader into an NDataReader. It was converted in midstream " + _isMidstream.ToString()); + log.Debug("Moving DbDataReader into an NDataReader. It was converted in midstream {0}", _isMidstream); } _reader = await (NDataReader.CreateAsync(_reader, _isMidstream, cancellationToken)).ConfigureAwait(false); } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Engine/ActionQueue.cs b/src/NHibernate/Async/Engine/ActionQueue.cs index 40bab6dfba4..26d53443fb2 100644 --- a/src/NHibernate/Async/Engine/ActionQueue.cs +++ b/src/NHibernate/Async/Engine/ActionQueue.cs @@ -151,7 +151,7 @@ public async Task AfterTransactionCompletionAsync(bool success, CancellationToke } catch (CacheException e) { - log.Error( "could not release a cache lock", e); + log.Error(e, "could not release a cache lock"); // continue loop } catch (Exception e) diff --git a/src/NHibernate/Async/Engine/Cascade.cs b/src/NHibernate/Async/Engine/Cascade.cs index 1ccc4ef3bfc..ce8d79cd0ba 100644 --- a/src/NHibernate/Async/Engine/Cascade.cs +++ b/src/NHibernate/Async/Engine/Cascade.cs @@ -55,7 +55,7 @@ public async Task CascadeOnAsync(IEntityPersister persister, object parent, obje cancellationToken.ThrowIfCancellationRequested(); if (persister.HasCascades || action.RequiresNoCascadeChecking) { - log.Info("processing cascade " + action + " for: " + persister.EntityName); + log.Info("processing cascade {0} for: {1}", action, persister.EntityName); IType[] types = persister.PropertyTypes; CascadeStyle[] cascadeStyles = persister.PropertyCascadeStyles; @@ -80,7 +80,7 @@ public async Task CascadeOnAsync(IEntityPersister persister, object parent, obje } } - log.Info("done processing cascade " + action + " for: " + persister.EntityName); + log.Info("done processing cascade {0} for: {1}", action, persister.EntityName); } } @@ -252,12 +252,12 @@ private async Task CascadeCollectionElementsAsync(object parent, object child, C if (reallyDoCascade) { - log.Info("cascade " + action + " for collection: " + collectionType.Role); + log.Info("cascade {0} for collection: {1}", action, collectionType.Role); foreach (object o in action.GetCascadableChildrenIterator(eventSource, collectionType, child)) await (CascadePropertyAsync(parent, o, elemType, style, null, anything, isCascadeDeleteEnabled, cancellationToken)).ConfigureAwait(false); - log.Info("done cascade " + action + " for collection: " + collectionType.Role); + log.Info("done cascade {0} for collection: {1}", action, collectionType.Role); } var childAsPersColl = child as IPersistentCollection; @@ -267,7 +267,7 @@ private async Task CascadeCollectionElementsAsync(object parent, object child, C if (deleteOrphans) { // handle orphaned entities!! - log.Info("deleting orphans for collection: " + collectionType.Role); + log.Info("deleting orphans for collection: {0}", collectionType.Role); // we can do the cast since orphan-delete does not apply to: // 1. newly instantiated collections @@ -275,7 +275,7 @@ private async Task CascadeCollectionElementsAsync(object parent, object child, C string entityName = collectionType.GetAssociatedEntityName(eventSource.Factory); await (DeleteOrphansAsync(entityName, childAsPersColl, cancellationToken)).ConfigureAwait(false); - log.Info("done deleting orphans for collection: " + collectionType.Role); + log.Info("done deleting orphans for collection: {0}", collectionType.Role); } } @@ -299,7 +299,7 @@ private async Task DeleteOrphansAsync(string entityName, IPersistentCollection p { if (orphan != null) { - log.Info("deleting orphaned entity instance: " + entityName); + log.Info("deleting orphaned entity instance: {0}", entityName); await (eventSource.DeleteAsync(entityName, orphan, false, null, cancellationToken)).ConfigureAwait(false); } diff --git a/src/NHibernate/Async/Engine/CascadingAction.cs b/src/NHibernate/Async/Engine/CascadingAction.cs index 23b14a4307f..b0670576aee 100644 --- a/src/NHibernate/Async/Engine/CascadingAction.cs +++ b/src/NHibernate/Async/Engine/CascadingAction.cs @@ -74,9 +74,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to delete: " + entityName); + log.Debug("cascading to delete: {0}", entityName); } return session.DeleteAsync(entityName, child, isCascadeDeleteEnabled, (ISet)anything, cancellationToken); } @@ -97,9 +97,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to lock: " + entityName); + log.Debug("cascading to lock: {0}", entityName); } return session.LockAsync(entityName, child, LockMode.None, cancellationToken); } @@ -120,9 +120,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to refresh: " + entityName); + log.Debug("cascading to refresh: {0}", entityName); } return session.RefreshAsync(child, (IDictionary)anything, cancellationToken); } @@ -143,9 +143,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to evict: " + entityName); + log.Debug("cascading to evict: {0}", entityName); } return session.EvictAsync(child, cancellationToken); } @@ -166,9 +166,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to saveOrUpdate: " + entityName); + log.Debug("cascading to saveOrUpdate: {0}", entityName); } return session.SaveOrUpdateAsync(entityName, child, cancellationToken); } @@ -189,9 +189,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to merge: " + entityName); + log.Debug("cascading to merge: {0}", entityName); } return session.MergeAsync(entityName, child, (IDictionary)anything, cancellationToken); } @@ -212,9 +212,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to persist: " + entityName); + log.Debug("cascading to persist: {0}", entityName); } return session.PersistAsync(entityName, child, (IDictionary)anything, cancellationToken); } @@ -235,9 +235,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to persistOnFlush: " + entityName); + log.Debug("cascading to persistOnFlush: {0}", entityName); } return session.PersistOnFlushAsync(entityName, child, (IDictionary)anything, cancellationToken); } @@ -282,9 +282,9 @@ public override Task CascadeAsync(IEventSource session, object child, string ent } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to replicate: " + entityName); + log.Debug("cascading to replicate: {0}", entityName); } return session.ReplicateAsync(entityName, child, (ReplicationMode)anything, cancellationToken); } diff --git a/src/NHibernate/Async/Engine/CollectionEntry.cs b/src/NHibernate/Async/Engine/CollectionEntry.cs index d7f15ee42a2..300f6191aed 100644 --- a/src/NHibernate/Async/Engine/CollectionEntry.cs +++ b/src/NHibernate/Async/Engine/CollectionEntry.cs @@ -57,9 +57,9 @@ public async Task PreFlushAsync(IPersistentCollection collection, CancellationTo } await (DirtyAsync(collection, cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled && collection.IsDirty && loadedPersister != null) + if (log.IsDebugEnabled() && collection.IsDirty && loadedPersister != null) { - log.Debug("Collection dirty: " + MessageHelper.CollectionInfoString(loadedPersister, loadedKey)); + log.Debug("Collection dirty: {0}", MessageHelper.CollectionInfoString(loadedPersister, loadedKey)); } // reset all of these values so any previous flush status @@ -84,4 +84,4 @@ public Task GetOrphansAsync(string entityName, IPersistentCollectio return collection.GetOrphansAsync(snapshot, entityName, cancellationToken); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Engine/Collections.cs b/src/NHibernate/Async/Engine/Collections.cs index d10985dfa6b..5c031d4d046 100644 --- a/src/NHibernate/Async/Engine/Collections.cs +++ b/src/NHibernate/Async/Engine/Collections.cs @@ -62,8 +62,8 @@ private static Task ProcessDereferencedCollectionAsync(IPersistentCollection col CollectionEntry entry = persistenceContext.GetCollectionEntry(coll); ICollectionPersister loadedPersister = entry.LoadedPersister; - if (log.IsDebugEnabled && loadedPersister != null) - log.Debug("Collection dereferenced: " + MessageHelper.CollectionInfoString(loadedPersister, coll, entry.LoadedKey, session)); + if (log.IsDebugEnabled() && loadedPersister != null) + log.Debug("Collection dereferenced: {0}", MessageHelper.CollectionInfoString(loadedPersister, coll, entry.LoadedKey, session)); // do a check bool hasOrphanDelete = loadedPersister != null && loadedPersister.HasOrphanDelete; @@ -124,7 +124,7 @@ private static Task ProcessNeverReferencedCollectionAsync(IPersistentCollection { CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(coll); - log.Debug("Found collection with unloaded owner: " + MessageHelper.CollectionInfoString(entry.LoadedPersister, coll, entry.LoadedKey, session)); + log.Debug("Found collection with unloaded owner: {0}", MessageHelper.CollectionInfoString(entry.LoadedPersister, coll, entry.LoadedKey, session)); entry.CurrentPersister = entry.LoadedPersister; entry.CurrentKey = entry.LoadedKey; @@ -176,12 +176,12 @@ public static Task ProcessReachableCollectionAsync(IPersistentCollection collect ce.CurrentPersister = persister; ce.CurrentKey = type.GetKeyOfOwner(entity, session); //TODO: better to pass the id in as an argument? - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Collection found: " + - MessageHelper.CollectionInfoString(persister, collection, ce.CurrentKey, session) + ", was: " + - MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, session) + - (collection.WasInitialized ? " (initialized)" : " (uninitialized)")); + log.Debug("Collection found: {0}, was: {1}{2}", + MessageHelper.CollectionInfoString(persister, collection, ce.CurrentKey, session), + MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, session), + (collection.WasInitialized ? " (initialized)" : " (uninitialized)")); } return PrepareCollectionForUpdateAsync(collection, ce, factory, cancellationToken); diff --git a/src/NHibernate/Async/Engine/ForeignKeys.cs b/src/NHibernate/Async/Engine/ForeignKeys.cs index 4982933c2a1..11597f5fcd1 100644 --- a/src/NHibernate/Async/Engine/ForeignKeys.cs +++ b/src/NHibernate/Async/Engine/ForeignKeys.cs @@ -209,11 +209,8 @@ static async Task HasDbSnapshotAsync(string entityName, object entity, ISe // When using assigned identifiers we cannot tell if an entity // is transient or detached without querying the database. // This could potentially cause Select N+1 in cascaded saves, so warn the user. - log.Warn( - "Unable to determine if " + entity.ToString() - + " with assigned identifier " + persister.GetIdentifier(entity) - + " is transient or detached; querying the database." - + " Use explicit Save() or Update() in session to prevent this."); + log.Warn("Unable to determine if {0} with assigned identifier {1} is transient or detached; querying the database. Use explicit Save() or Update() in session to prevent this.", + entity, persister.GetIdentifier(entity)); } // hit the database, after checking the session cache for a snapshot diff --git a/src/NHibernate/Async/Engine/Loading/CollectionLoadContext.cs b/src/NHibernate/Async/Engine/Loading/CollectionLoadContext.cs index 047e49414a6..b4f81ed2c74 100644 --- a/src/NHibernate/Async/Engine/Loading/CollectionLoadContext.cs +++ b/src/NHibernate/Async/Engine/Loading/CollectionLoadContext.cs @@ -56,7 +56,8 @@ public async Task EndLoadingCollectionsAsync(ICollectionPersister persister, Can LoadingCollectionEntry lce = loadContexts.LocateLoadingCollectionEntry(collectionKey); if (lce == null) { - log.Warn("In CollectionLoadContext#endLoadingCollections, localLoadingCollectionKeys contained [" + collectionKey + "], but no LoadingCollectionEntry was found in loadContexts"); + log.Warn("In CollectionLoadContext#endLoadingCollections, localLoadingCollectionKeys contained [{0}], but no LoadingCollectionEntry was found in loadContexts", + collectionKey); } else if (lce.ResultSet == resultSet && lce.Persister == persister) { @@ -66,9 +67,9 @@ public async Task EndLoadingCollectionsAsync(ICollectionPersister persister, Can session.PersistenceContext.AddUnownedCollection(new CollectionKey(persister, lce.Key), lce.Collection); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("removing collection load entry [" + lce + "]"); + log.Debug("removing collection load entry [{0}]", lce); } // todo : i'd much rather have this done from #endLoadingCollection(CollectionPersister,LoadingCollectionEntry)... @@ -96,17 +97,17 @@ private async Task EndLoadingCollectionsAsync(ICollectionPersister persister, IL cancellationToken.ThrowIfCancellationRequested(); if (matchedCollectionEntries == null || matchedCollectionEntries.Count == 0) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("no collections were found in result set for role: " + persister.Role); + log.Debug("no collections were found in result set for role: {0}", persister.Role); } return; } int count = matchedCollectionEntries.Count; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(count + " collections were found in result set for role: " + persister.Role); + log.Debug("{0} collections were found in result set for role: {1}", count, persister.Role); } for (int i = 0; i < count; i++) @@ -114,18 +115,18 @@ private async Task EndLoadingCollectionsAsync(ICollectionPersister persister, IL await (EndLoadingCollectionAsync(matchedCollectionEntries[i], persister, cancellationToken)).ConfigureAwait(false); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(count + " collections initialized for role: " + persister.Role); + log.Debug("{0} collections initialized for role: {1}", count, persister.Role); } } private async Task EndLoadingCollectionAsync(LoadingCollectionEntry lce, ICollectionPersister persister, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("ending loading collection [" + lce + "]"); + log.Debug("ending loading collection [{0}]", lce); } ISessionImplementor session = LoadContext.PersistenceContext.Session; @@ -161,9 +162,9 @@ private async Task EndLoadingCollectionAsync(LoadingCollectionEntry lce, ICollec await (AddCollectionToCacheAsync(lce, persister, cancellationToken)).ConfigureAwait(false); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("collection fully initialized: " + MessageHelper.CollectionInfoString(persister, lce.Collection, lce.Key, session)); + log.Debug("collection fully initialized: {0}", MessageHelper.CollectionInfoString(persister, lce.Collection, lce.Key, session)); } if (statsEnabled) @@ -183,9 +184,9 @@ private async Task AddCollectionToCacheAsync(LoadingCollectionEntry lce, ICollec ISessionImplementor session = LoadContext.PersistenceContext.Session; ISessionFactoryImplementor factory = session.Factory; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Caching collection: " + MessageHelper.CollectionInfoString(persister, lce.Collection, lce.Key, session)); + log.Debug("Caching collection: {0}", MessageHelper.CollectionInfoString(persister, lce.Collection, lce.Key, session)); } if (!(session.EnabledFilters.Count == 0) && persister.IsAffectedByEnabledFilters(session)) diff --git a/src/NHibernate/Async/Engine/Query/HQLQueryPlan.cs b/src/NHibernate/Async/Engine/Query/HQLQueryPlan.cs index 017d489879c..853d1ad1261 100644 --- a/src/NHibernate/Async/Engine/Query/HQLQueryPlan.cs +++ b/src/NHibernate/Async/Engine/Query/HQLQueryPlan.cs @@ -35,9 +35,9 @@ public partial class HQLQueryPlan : IQueryPlan public async Task PerformListAsync(QueryParameters queryParameters, ISessionImplementor session, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("find: " + _sourceQuery); + Log.Debug("find: {0}", _sourceQuery); queryParameters.LogParameters(session.Factory); } @@ -103,9 +103,9 @@ public async Task PerformListAsync(QueryParameters queryParameters, ISessionImpl public async Task PerformIterateAsync(QueryParameters queryParameters, IEventSource session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("enumerable: " + _sourceQuery); + Log.Debug("enumerable: {0}", _sourceQuery); queryParameters.LogParameters(session.Factory); } if (Translators.Length == 0) @@ -134,14 +134,14 @@ public async Task> PerformIterateAsync(QueryParameters queryPa public async Task PerformExecuteUpdateAsync(QueryParameters queryParameters, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("executeUpdate: " + _sourceQuery); + Log.Debug("executeUpdate: {0}", _sourceQuery); queryParameters.LogParameters(session.Factory); } if (Translators.Length != 1) { - Log.Warn("manipulation query [" + _sourceQuery + "] resulted in [" + Translators.Length + "] split queries"); + Log.Warn("manipulation query [{0}] resulted in [{1}] split queries", _sourceQuery, Translators.Length); } int result = 0; for (int i = 0; i < Translators.Length; i++) diff --git a/src/NHibernate/Async/Engine/TwoPhaseLoad.cs b/src/NHibernate/Async/Engine/TwoPhaseLoad.cs index c03958e9157..6579b270c6f 100644 --- a/src/NHibernate/Async/Engine/TwoPhaseLoad.cs +++ b/src/NHibernate/Async/Engine/TwoPhaseLoad.cs @@ -55,8 +55,8 @@ public static async Task InitializeEntityAsync(object entity, bool readOnly, ISe object id = entityEntry.Id; object[] hydratedState = entityEntry.LoadedState; - if (log.IsDebugEnabled) - log.Debug("resolving associations for " + MessageHelper.InfoString(persister, id, session.Factory)); + if (log.IsDebugEnabled()) + log.Debug("resolving associations for {0}", MessageHelper.InfoString(persister, id, session.Factory)); IType[] types = persister.PropertyTypes; for (int i = 0; i < hydratedState.Length; i++) @@ -88,8 +88,8 @@ public static async Task InitializeEntityAsync(object entity, bool readOnly, ISe if (persister.HasCache && session.CacheMode.HasFlag(CacheMode.Put)) { - if (log.IsDebugEnabled) - log.Debug("adding entity to second-level cache: " + MessageHelper.InfoString(persister, id, session.Factory)); + if (log.IsDebugEnabled()) + log.Debug("adding entity to second-level cache: {0}", MessageHelper.InfoString(persister, id, session.Factory)); object version = Versioning.GetVersion(hydratedState, persister); CacheEntry entry = @@ -152,8 +152,8 @@ public static async Task InitializeEntityAsync(object entity, bool readOnly, ISe } } - if (log.IsDebugEnabled) - log.Debug("done materializing entity " + MessageHelper.InfoString(persister, id, session.Factory)); + if (log.IsDebugEnabled()) + log.Debug("done materializing entity {0}", MessageHelper.InfoString(persister, id, session.Factory)); if (statsEnabled) { diff --git a/src/NHibernate/Async/Engine/Versioning.cs b/src/NHibernate/Async/Engine/Versioning.cs index 0ff9eb29ab7..69db5134409 100644 --- a/src/NHibernate/Async/Engine/Versioning.cs +++ b/src/NHibernate/Async/Engine/Versioning.cs @@ -31,11 +31,11 @@ public static async Task IncrementAsync(object version, IVersionType ver { cancellationToken.ThrowIfCancellationRequested(); object next = await (versionType.NextAsync(version, session, cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug( - string.Format("Incrementing: {0} to {1}", versionType.ToLoggableString(version, session.Factory), - versionType.ToLoggableString(next, session.Factory))); + log.Debug("Incrementing: {0} to {1}", + versionType.ToLoggableString(version, session.Factory), + versionType.ToLoggableString(next, session.Factory)); } return next; } @@ -51,9 +51,9 @@ public static async Task SeedAsync(IVersionType versionType, ISessionImp { cancellationToken.ThrowIfCancellationRequested(); object seed = await (versionType.SeedAsync(session, cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Seeding: " + seed); + log.Debug("Seeding: {0}", seed); } return seed; } @@ -80,12 +80,12 @@ public static async Task SeedVersionAsync(object[] fields, int versionProp } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("using initial version: " + initialVersion); + log.Debug("using initial version: {0}", initialVersion); } return false; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Event/Default/AbstractFlushingEventListener.cs b/src/NHibernate/Async/Event/Default/AbstractFlushingEventListener.cs index 588ba1ef541..dcea3f46739 100644 --- a/src/NHibernate/Async/Event/Default/AbstractFlushingEventListener.cs +++ b/src/NHibernate/Async/Event/Default/AbstractFlushingEventListener.cs @@ -66,20 +66,21 @@ protected virtual async Task FlushEverythingToExecutionsAsync(FlushEvent @event, } //some statistics - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - StringBuilder sb = new StringBuilder(100); + log.Debug( + "Flushed: {0} insertions, {1} updates, {2} deletions to {3} objects", + session.ActionQueue.InsertionsCount, + session.ActionQueue.UpdatesCount, + session.ActionQueue.DeletionsCount, + persistenceContext.EntityEntries.Count); - sb.Append("Flushed: ").Append(session.ActionQueue.InsertionsCount).Append(" insertions, ").Append( - session.ActionQueue.UpdatesCount).Append(" updates, ").Append(session.ActionQueue.DeletionsCount).Append( - " deletions to ").Append(persistenceContext.EntityEntries.Count).Append(" objects"); - log.Debug(sb.ToString()); - sb = new StringBuilder(100); - sb.Append("Flushed: ").Append(session.ActionQueue.CollectionCreationsCount).Append(" (re)creations, ").Append( - session.ActionQueue.CollectionUpdatesCount).Append(" updates, ").Append(session.ActionQueue.CollectionRemovalsCount) - .Append(" removals to ").Append(persistenceContext.CollectionEntries.Count).Append(" collections"); - - log.Debug(sb.ToString()); + log.Debug( + "Flushed: {0} (re)creations, {1} updates, {2} removals to {3} collections", + session.ActionQueue.CollectionCreationsCount, + session.ActionQueue.CollectionUpdatesCount, + session.ActionQueue.CollectionRemovalsCount, + persistenceContext.CollectionEntries.Count); new Printer(session.Factory).ToString(persistenceContext.EntitiesByKey.Values.ToArray()); } } @@ -234,7 +235,7 @@ protected virtual async Task CascadeOnFlushAsync(IEventSource session, IEntityPe protected virtual async Task PerformExecutionsAsync(IEventSource session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("executing flush"); } @@ -255,9 +256,9 @@ protected virtual async Task PerformExecutionsAsync(IEventSource session, Cancel } catch (HibernateException he) { - if (log.IsErrorEnabled) + if (log.IsErrorEnabled()) { - log.Error("Could not synchronize database state with session", he); + log.Error(he, "Could not synchronize database state with session"); } throw; } diff --git a/src/NHibernate/Async/Event/Default/AbstractLockUpgradeEventListener.cs b/src/NHibernate/Async/Event/Default/AbstractLockUpgradeEventListener.cs index 29b4dbfd181..9688ab10663 100644 --- a/src/NHibernate/Async/Event/Default/AbstractLockUpgradeEventListener.cs +++ b/src/NHibernate/Async/Event/Default/AbstractLockUpgradeEventListener.cs @@ -46,9 +46,9 @@ protected virtual async Task UpgradeLockAsync(object entity, EntityEntry entry, IEntityPersister persister = entry.Persister; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("locking {0} in mode: {1}", MessageHelper.InfoString(persister, entry.Id, source.Factory), requestedLockMode)); + log.Debug("locking {0} in mode: {1}", MessageHelper.InfoString(persister, entry.Id, source.Factory), requestedLockMode); } ISoftLock slock; diff --git a/src/NHibernate/Async/Event/Default/AbstractReassociateEventListener.cs b/src/NHibernate/Async/Event/Default/AbstractReassociateEventListener.cs index 079f41e8ce2..30b74e9089b 100644 --- a/src/NHibernate/Async/Event/Default/AbstractReassociateEventListener.cs +++ b/src/NHibernate/Async/Event/Default/AbstractReassociateEventListener.cs @@ -35,9 +35,9 @@ public partial class AbstractReassociateEventListener protected async Task ReassociateAsync(AbstractEvent @event, object entity, object id, IEntityPersister persister, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Reassociating transient instance: " + MessageHelper.InfoString(persister, id, @event.Session.Factory)); + log.Debug("Reassociating transient instance: {0}", MessageHelper.InfoString(persister, id, @event.Session.Factory)); } IEventSource source = @event.Session; diff --git a/src/NHibernate/Async/Event/Default/AbstractSaveEventListener.cs b/src/NHibernate/Async/Event/Default/AbstractSaveEventListener.cs index d0f0611ec77..72513f781c3 100644 --- a/src/NHibernate/Async/Event/Default/AbstractSaveEventListener.cs +++ b/src/NHibernate/Async/Event/Default/AbstractSaveEventListener.cs @@ -91,11 +91,11 @@ protected virtual async Task SaveWithGeneratedIdAsync(object entity, str } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("generated identifier: {0}, using strategy: {1}", - persister.IdentifierType.ToLoggableString(generatedId, source.Factory), - persister.IdentifierGenerator.GetType().FullName)); + log.Debug("generated identifier: {0}, using strategy: {1}", + persister.IdentifierType.ToLoggableString(generatedId, source.Factory), + persister.IdentifierGenerator.GetType().FullName); } return await (PerformSaveAsync(entity, generatedId, persister, false, anything, source, true, cancellationToken)).ConfigureAwait(false); } @@ -125,9 +125,9 @@ protected virtual async Task SaveWithGeneratedIdAsync(object entity, str protected virtual async Task PerformSaveAsync(object entity, object id, IEntityPersister persister, bool useIdentityColumn, object anything, IEventSource source, bool requiresImmediateIdAccess, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("saving " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("saving {0}", MessageHelper.InfoString(persister, id, source.Factory)); } EntityKey key; @@ -371,18 +371,18 @@ protected virtual async Task GetEntityStateAsync(object entity, str if (entry.Status != Status.Deleted) { // do nothing for persistent instances - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("persistent instance of: " + GetLoggableName(entityName, entity)); + log.Debug("persistent instance of: {0}", GetLoggableName(entityName, entity)); } return EntityState.Persistent; } else { //ie. e.status==DELETED - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("deleted instance of: " + GetLoggableName(entityName, entity)); + log.Debug("deleted instance of: {0}", GetLoggableName(entityName, entity)); } return EntityState.Deleted; } @@ -397,17 +397,17 @@ protected virtual async Task GetEntityStateAsync(object entity, str ? (await (ForeignKeys.IsTransientFastAsync(entityName, entity, source, cancellationToken)).ConfigureAwait(false)).GetValueOrDefault(assumed.Value) : await (ForeignKeys.IsTransientSlowAsync(entityName, entity, source, cancellationToken)).ConfigureAwait(false)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("transient instance of: " + GetLoggableName(entityName, entity)); + log.Debug("transient instance of: {0}", GetLoggableName(entityName, entity)); } return EntityState.Transient; } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("detached instance of: " + GetLoggableName(entityName, entity)); + log.Debug("detached instance of: {0}", GetLoggableName(entityName, entity)); } return EntityState.Detached; } diff --git a/src/NHibernate/Async/Event/Default/DefaultAutoFlushEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultAutoFlushEventListener.cs index c53c119a9db..fed30c185b7 100644 --- a/src/NHibernate/Async/Event/Default/DefaultAutoFlushEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultAutoFlushEventListener.cs @@ -41,7 +41,7 @@ public virtual async Task OnAutoFlushAsync(AutoFlushEvent @event, CancellationTo if (FlushIsReallyNeeded(@event, source)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) log.Debug("Need to execute flush"); await (PerformExecutionsAsync(source, cancellationToken)).ConfigureAwait(false); @@ -57,7 +57,7 @@ public virtual async Task OnAutoFlushAsync(AutoFlushEvent @event, CancellationTo else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) log.Debug("Dont need to execute flush"); source.ActionQueue.ClearFromFlushNeededCheck(oldSize); } diff --git a/src/NHibernate/Async/Event/Default/DefaultDeleteEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultDeleteEventListener.cs index a66fcb011bf..afd64e3a6b2 100644 --- a/src/NHibernate/Async/Event/Default/DefaultDeleteEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultDeleteEventListener.cs @@ -172,9 +172,9 @@ protected virtual async Task DeleteTransientEntityAsync(IEventSource session, ob protected virtual async Task DeleteEntityAsync(IEventSource session, object entity, EntityEntry entityEntry, bool isCascadeDeleteEnabled, IEntityPersister persister, ISet transientEntities, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("deleting " + MessageHelper.InfoString(persister, entityEntry.Id, session.Factory)); + log.Debug("deleting {0}", MessageHelper.InfoString(persister, entityEntry.Id, session.Factory)); } IPersistenceContext persistenceContext = session.PersistenceContext; diff --git a/src/NHibernate/Async/Event/Default/DefaultEvictEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultEvictEventListener.cs index d64c2c257c5..8a21bbe5602 100644 --- a/src/NHibernate/Async/Event/Default/DefaultEvictEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultEvictEventListener.cs @@ -66,9 +66,9 @@ protected virtual async Task DoEvictAsync(object obj, EntityKey key, IEntityPers { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting " + MessageHelper.InfoString(persister)); + log.Debug("evicting {0}", MessageHelper.InfoString(persister)); } // remove all collections for the entity from the session-level cache diff --git a/src/NHibernate/Async/Event/Default/DefaultFlushEntityEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultFlushEntityEventListener.cs index 0a15fb76741..17780c6411e 100644 --- a/src/NHibernate/Async/Event/Default/DefaultFlushEntityEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultFlushEntityEventListener.cs @@ -192,26 +192,26 @@ private async Task ScheduleUpdateAsync(FlushEntityEvent @event, Cancellati IEntityPersister persister = entry.Persister; object[] values = @event.PropertyValues; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (status == Status.Deleted) { if (!persister.IsMutable) { - log.Debug("Updating immutable, deleted entity: " + MessageHelper.InfoString(persister, entry.Id, session.Factory)); + log.Debug("Updating immutable, deleted entity: {0}", MessageHelper.InfoString(persister, entry.Id, session.Factory)); } else if (!entry.IsModifiableEntity()) { - log.Debug("Updating non-modifiable, deleted entity: " + MessageHelper.InfoString(persister, entry.Id, session.Factory)); + log.Debug("Updating non-modifiable, deleted entity: {0}", MessageHelper.InfoString(persister, entry.Id, session.Factory)); } else { - log.Debug("Updating deleted entity: " + MessageHelper.InfoString(persister, entry.Id, session.Factory)); + log.Debug("Updating deleted entity: {0}", MessageHelper.InfoString(persister, entry.Id, session.Factory)); } } else { - log.Debug("Updating entity: " + MessageHelper.InfoString(persister, entry.Id, session.Factory)); + log.Debug("Updating entity: {0}", MessageHelper.InfoString(persister, entry.Id, session.Factory)); } } diff --git a/src/NHibernate/Async/Event/Default/DefaultInitializeCollectionEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultInitializeCollectionEventListener.cs index f8450dc9faf..d62cac434c8 100644 --- a/src/NHibernate/Async/Event/Default/DefaultInitializeCollectionEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultInitializeCollectionEventListener.cs @@ -44,9 +44,9 @@ public virtual async Task OnInitializeCollectionAsync(InitializeCollectionEvent throw new HibernateException("collection was evicted"); if (!collection.WasInitialized) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("initializing collection " + MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, source)); + log.Debug("initializing collection {0}", MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, source)); } log.Debug("checking second-level cache"); @@ -109,11 +109,11 @@ private async Task InitializeCollectionFromCacheAsync(object id, ICollecti if (ce == null) { - log.DebugFormat("Collection cache miss: {0}", ck); + log.Debug("Collection cache miss: {0}", ck); } else { - log.DebugFormat("Collection cache hit: {0}", ck); + log.Debug("Collection cache hit: {0}", ck); } if (ce == null) diff --git a/src/NHibernate/Async/Event/Default/DefaultLoadEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultLoadEventListener.cs index 014729d1cf8..8247333e98c 100644 --- a/src/NHibernate/Async/Event/Default/DefaultLoadEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultLoadEventListener.cs @@ -93,7 +93,7 @@ public virtual async Task OnLoadAsync(LoadEvent @event, LoadType loadType, Cance } catch (HibernateException e) { - log.Info("Error performing load command", e); + log.Info(e, "Error performing load command"); throw; } } @@ -145,9 +145,9 @@ protected virtual Task ProxyOrLoadAsync(LoadEvent @event, IEntityPersist } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("loading entity: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("loading entity: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } if (!persister.HasProxy) @@ -269,9 +269,9 @@ protected virtual async Task LockAndLoadAsync(LoadEvent @event, IEntityP protected virtual async Task DoLoadAsync(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("attempting to resolve: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("attempting to resolve: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } object entity = await (LoadFromSessionCacheAsync(@event, keyToLoad, options, cancellationToken)).ConfigureAwait(false); @@ -287,9 +287,9 @@ protected virtual async Task DoLoadAsync(LoadEvent @event, IEntityPersis } if (entity != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("resolved object in session cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("resolved object in session cache: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } return entity; } @@ -297,16 +297,16 @@ protected virtual async Task DoLoadAsync(LoadEvent @event, IEntityPersis entity = await (LoadFromSecondLevelCacheAsync(@event, persister, options, cancellationToken)).ConfigureAwait(false); if (entity != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("resolved object in second-level cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("resolved object in second-level cache: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } return entity; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("object not resolved in any cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("object not resolved in any cache: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } return await (LoadFromDatasourceAsync(@event, persister, keyToLoad, options, cancellationToken)).ConfigureAwait(false); @@ -417,12 +417,12 @@ protected virtual async Task LoadFromSecondLevelCacheAsync(LoadEvent @ev if (ce == null) { factory.StatisticsImplementor.SecondLevelCacheMiss(persister.Cache.RegionName); - log.DebugFormat("Entity cache miss: {0}", ck); + log.Debug("Entity cache miss: {0}", ck); } else { factory.StatisticsImplementor.SecondLevelCacheHit(persister.Cache.RegionName); - log.DebugFormat("Entity cache hit: {0}", ck); + log.Debug("Entity cache hit: {0}", ck); } } @@ -449,9 +449,9 @@ private async Task AssembleCacheEntryAsync(CacheEntry entry, object id, IEventSource session = @event.Session; ISessionFactoryImplementor factory = session.Factory; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("assembling entity from second-level cache: " + MessageHelper.InfoString(persister, id, factory)); + log.Debug("assembling entity from second-level cache: {0}", MessageHelper.InfoString(persister, id, factory)); } IEntityPersister subclassPersister = factory.GetEntityPersister(entry.Subclass); @@ -466,9 +466,9 @@ private async Task AssembleCacheEntryAsync(CacheEntry entry, object id, TypeHelper.DeepCopy(values, types, subclassPersister.PropertyUpdateability, values, session); object version = Versioning.GetVersion(values, subclassPersister); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cached Version: " + version); + log.Debug("Cached Version: {0}", version); } IPersistenceContext persistenceContext = session.PersistenceContext; diff --git a/src/NHibernate/Async/Event/Default/DefaultMergeEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultMergeEventListener.cs index 8a036cc4c5b..047ea413ba3 100644 --- a/src/NHibernate/Async/Event/Default/DefaultMergeEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultMergeEventListener.cs @@ -69,7 +69,7 @@ public virtual async Task OnMergeAsync(MergeEvent @event, CancellationToken canc transientEntityNames.Add(transientEntityName); - log.InfoFormat( + log.Info( "transient instance could not be processed by merge: {0} [{1}]", transientEntityName, transientEntity.ToString()); @@ -251,23 +251,23 @@ private async Task MergeTransientEntityAsync(object entity, string entit if (propertyFromCopy == null || !propertyType.IsEntityType) { - log.InfoFormat("property '{0}.{1}' is null or not an entity; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromCopy); + log.Info("property '{0}.{1}' is null or not an entity; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromCopy); throw; } if (!copyCache.Contains(propertyFromEntity)) { - log.InfoFormat("property '{0}.{1}' from original entity is not in copyCache; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); + log.Info("property '{0}.{1}' from original entity is not in copyCache; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); throw; } if (((EventCache)copyCache).IsOperatedOn(propertyFromEntity)) { - log.InfoFormat("property '{0}.{1}' from original entity is in copyCache and is in the process of being merged; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); + log.Info("property '{0}.{1}' from original entity is in copyCache and is in the process of being merged; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); } else { - log.InfoFormat("property '{0}.{1}' from original entity is in copyCache and is not in the process of being merged; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); + log.Info("property '{0}.{1}' from original entity is in copyCache and is not in the process of being merged; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); } // continue...; we'll find out if it ends up not getting saved later @@ -485,7 +485,7 @@ protected async Task GetTransientCopyCacheAsync(MergeEvent @event, E { // entity name will not be available for non-POJO entities // TODO: cache the entity name somewhere so that it is available to this exception - log.InfoFormat( + log.Info( "transient instance could not be processed by merge: {0} [{1}]", @event.Session.GuessEntityName(entityCopy), entity); diff --git a/src/NHibernate/Async/Event/Default/DefaultRefreshEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultRefreshEventListener.cs index 4b44638e7f1..780ebf7dd73 100644 --- a/src/NHibernate/Async/Event/Default/DefaultRefreshEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultRefreshEventListener.cs @@ -70,9 +70,9 @@ public virtual async Task OnRefreshAsync(RefreshEvent @event, IDictionary refres { persister = source.GetEntityPersister(null, obj); //refresh() does not pass an entityName id = persister.GetIdentifier(obj); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("refreshing transient " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("refreshing transient {0}", MessageHelper.InfoString(persister, id, source.Factory)); } EntityKey key = source.GenerateEntityKey(id, persister); if (source.PersistenceContext.GetEntry(key) != null) @@ -83,9 +83,9 @@ public virtual async Task OnRefreshAsync(RefreshEvent @event, IDictionary refres } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("refreshing " + MessageHelper.InfoString(e.Persister, e.Id, source.Factory)); + log.Debug("refreshing {0}", MessageHelper.InfoString(e.Persister, e.Id, source.Factory)); } if (!e.ExistsInDatabase) { diff --git a/src/NHibernate/Async/Event/Default/DefaultReplicateEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultReplicateEventListener.cs index e8ef54497e7..04f646f475c 100644 --- a/src/NHibernate/Async/Event/Default/DefaultReplicateEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultReplicateEventListener.cs @@ -67,9 +67,9 @@ public virtual async Task OnReplicateAsync(ReplicateEvent @event, CancellationTo if (oldVersion != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("found existing row for " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("found existing row for {0}", MessageHelper.InfoString(persister, id, source.Factory)); } // HHH-2378 @@ -96,9 +96,9 @@ public virtual async Task OnReplicateAsync(ReplicateEvent @event, CancellationTo else { // no existing row - do an insert - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("no existing row, replicating new instance " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("no existing row, replicating new instance {0}", MessageHelper.InfoString(persister, id, source.Factory)); } bool regenerate = persister.IsIdentifierAssignedByInsert; // prefer re-generation of identity! @@ -111,9 +111,9 @@ public virtual async Task OnReplicateAsync(ReplicateEvent @event, CancellationTo private async Task PerformReplicationAsync(object entity, object id, object version, IEntityPersister persister, ReplicationMode replicationMode, IEventSource source, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("replicating changes to " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("replicating changes to {0}", MessageHelper.InfoString(persister, id, source.Factory)); } await (new OnReplicateVisitor(source, id, entity, true).ProcessAsync(entity, persister, cancellationToken)).ConfigureAwait(false); diff --git a/src/NHibernate/Async/Event/Default/DefaultSaveOrUpdateEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultSaveOrUpdateEventListener.cs index 5ea1179b7c3..5bb29def684 100644 --- a/src/NHibernate/Async/Event/Default/DefaultSaveOrUpdateEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultSaveOrUpdateEventListener.cs @@ -182,9 +182,9 @@ protected virtual async Task PerformUpdateAsync(SaveOrUpdateEvent @event, object log.Debug("immutable instance passed to PerformUpdate(), locking"); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("updating " + MessageHelper.InfoString(persister, @event.RequestedId, @event.Session.Factory)); + log.Debug("updating {0}", MessageHelper.InfoString(persister, @event.RequestedId, @event.Session.Factory)); } IEventSource source = @event.Session; @@ -228,9 +228,9 @@ protected virtual async Task PerformUpdateAsync(SaveOrUpdateEvent @event, object //persister.AfterReassociate(entity, source); TODO H3.2 not ported - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("updating " + MessageHelper.InfoString(persister, @event.RequestedId, source.Factory)); + log.Debug("updating {0}", MessageHelper.InfoString(persister, @event.RequestedId, source.Factory)); } await (CascadeOnUpdateAsync(@event, persister, entity, cancellationToken)).ConfigureAwait(false); diff --git a/src/NHibernate/Async/Event/Default/ReattachVisitor.cs b/src/NHibernate/Async/Event/Default/ReattachVisitor.cs index c227a101fc2..c6a81a49ee5 100644 --- a/src/NHibernate/Async/Event/Default/ReattachVisitor.cs +++ b/src/NHibernate/Async/Event/Default/ReattachVisitor.cs @@ -38,4 +38,4 @@ internal override async Task ProcessComponentAsync(object component, IAb return null; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs index 0a963d30894..1016b79807b 100644 --- a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs +++ b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs @@ -116,7 +116,7 @@ protected virtual async Task DropTemporaryTableIfNecessaryAsync(IQueryable persi } catch (Exception t) { - log.Warn("unable to cleanup temporary id table after use [" + t + "]"); + log.Warn(t, "unable to cleanup temporary id table after use [{0}]", t); } finally { @@ -152,7 +152,7 @@ public async Task DoWorkAsync(DbConnection connection, DbTransaction transaction } catch (Exception t) { - log.Debug("unable to create temporary id table [" + t.Message + "]"); + log.Debug(t, "unable to create temporary id table [{0}]", t.Message); } finally { @@ -188,7 +188,7 @@ public async Task DoWorkAsync(DbConnection connection, DbTransaction transaction } catch (Exception t) { - log.Warn("unable to drop temporary id table after use [" + t.Message + "]"); + log.Warn("unable to drop temporary id table after use [{0}]", t.Message); } finally { @@ -207,4 +207,4 @@ public async Task DoWorkAsync(DbConnection connection, DbTransaction transaction } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs index 85a7777d6d9..3d3b269fbd4 100644 --- a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs +++ b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs @@ -101,4 +101,4 @@ public override async Task ExecuteAsync(QueryParameters parameters, ISessio } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableUpdateExecutor.cs b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableUpdateExecutor.cs index aeefbdffb9f..71de9bb7c59 100644 --- a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableUpdateExecutor.cs +++ b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableUpdateExecutor.cs @@ -123,4 +123,4 @@ public override async Task ExecuteAsync(QueryParameters parameters, ISessio } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/Enhanced/OptimizerFactory.cs b/src/NHibernate/Async/Id/Enhanced/OptimizerFactory.cs index d91c9dd5bef..63f63c9ff6c 100644 --- a/src/NHibernate/Async/Id/Enhanced/OptimizerFactory.cs +++ b/src/NHibernate/Async/Id/Enhanced/OptimizerFactory.cs @@ -118,7 +118,7 @@ public override async Task GenerateAsync(IAccessCallback callback, Cance // to 1 as an initial value like we do the others // because we would not be able to control this if // we are using a sequence... - Log.Info("pooled optimizer source reported [" + _value + "] as the initial value; use of 1 or greater highly recommended"); + Log.Info("pooled optimizer source reported [{0}] as the initial value; use of 1 or greater highly recommended", _value); } if ((_initialValue == -1 && _value < IncrementSize) || _value == _initialValue) @@ -168,4 +168,4 @@ public override async Task GenerateAsync(IAccessCallback callback, Cance #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/Enhanced/SequenceStructure.cs b/src/NHibernate/Async/Id/Enhanced/SequenceStructure.cs index c223f2b06e6..a3a7fd57d54 100644 --- a/src/NHibernate/Async/Id/Enhanced/SequenceStructure.cs +++ b/src/NHibernate/Async/Id/Enhanced/SequenceStructure.cs @@ -46,9 +46,9 @@ public virtual async Task GetNextValueAsync(CancellationToken cancellation { await (rs.ReadAsync(cancellationToken)).ConfigureAwait(false); long result = Convert.ToInt64(rs.GetValue(0)); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Sequence value obtained: " + result); + Log.Debug("Sequence value obtained: {0}", result); } return result; } @@ -80,4 +80,4 @@ public virtual async Task GetNextValueAsync(CancellationToken cancellation #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/Enhanced/SequenceStyleGenerator.cs b/src/NHibernate/Async/Id/Enhanced/SequenceStyleGenerator.cs index 4fa555a925d..7817e7ed9eb 100644 --- a/src/NHibernate/Async/Id/Enhanced/SequenceStyleGenerator.cs +++ b/src/NHibernate/Async/Id/Enhanced/SequenceStyleGenerator.cs @@ -41,4 +41,4 @@ public virtual Task GenerateAsync(ISessionImplementor session, object ob #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/Enhanced/TableGenerator.cs b/src/NHibernate/Async/Id/Enhanced/TableGenerator.cs index e7810ed7c5d..887a6064f32 100644 --- a/src/NHibernate/Async/Id/Enhanced/TableGenerator.cs +++ b/src/NHibernate/Async/Id/Enhanced/TableGenerator.cs @@ -103,7 +103,7 @@ public override async Task DoWorkInCurrentTransactionAsync(ISessionImple } catch (Exception ex) { - log.Error("Unable to read or initialize hi value in " + TableName, ex); + log.Error(ex, "Unable to read or initialize hi value in {0}", TableName); throw; } @@ -126,7 +126,7 @@ public override async Task DoWorkInCurrentTransactionAsync(ISessionImple } catch (Exception ex) { - log.Error("Unable to update hi value in " + TableName, ex); + log.Error(ex, "Unable to update hi value in {0}", TableName); throw; } } diff --git a/src/NHibernate/Async/Id/Enhanced/TableStructure.cs b/src/NHibernate/Async/Id/Enhanced/TableStructure.cs index 3ffe419da73..7e109008d20 100644 --- a/src/NHibernate/Async/Id/Enhanced/TableStructure.cs +++ b/src/NHibernate/Async/Id/Enhanced/TableStructure.cs @@ -50,15 +50,14 @@ public override async Task DoWorkInCurrentTransactionAsync(ISessionImple if (selectedValue ==null) { - string err = "could not read a hi value - you need to populate the table: " + _tableName; - Log.Error(err); - throw new IdentifierGenerationException(err); + Log.Error("could not read a hi value - you need to populate the table: {0}", _tableName); + throw new IdentifierGenerationException("could not read a hi value - you need to populate the table: " + _tableName); } result = Convert.ToInt64(selectedValue); } catch (Exception sqle) { - Log.Error("could not read a hi value", sqle); + Log.Error(sqle, "could not read a hi value"); throw; } @@ -79,7 +78,7 @@ public override async Task DoWorkInCurrentTransactionAsync(ISessionImple } catch (Exception sqle) { - Log.Error("could not update hi value in: " + _tableName, sqle); + Log.Error(sqle, "could not update hi value in: {0}", _tableName); throw; } } @@ -110,4 +109,4 @@ public virtual async Task GetNextValueAsync(CancellationToken cancellation #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/IdentifierGeneratorFactory.cs b/src/NHibernate/Async/Id/IdentifierGeneratorFactory.cs index 86d91f6e4d0..4157080eea4 100644 --- a/src/NHibernate/Async/Id/IdentifierGeneratorFactory.cs +++ b/src/NHibernate/Async/Id/IdentifierGeneratorFactory.cs @@ -40,9 +40,9 @@ public static async Task GetGeneratedIdentityAsync(DbDataReader rs, ITyp } object id = await (GetAsync(rs, type, session, cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Natively generated identity: " + id); + log.Debug("Natively generated identity: {0}", id); } return id; } @@ -78,4 +78,4 @@ public static async Task GetAsync(DbDataReader rs, IType type, ISessionI } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/IncrementGenerator.cs b/src/NHibernate/Async/Id/IncrementGenerator.cs index 061b92f40ee..0fd915d15cf 100644 --- a/src/NHibernate/Async/Id/IncrementGenerator.cs +++ b/src/NHibernate/Async/Id/IncrementGenerator.cs @@ -52,7 +52,7 @@ public async Task GenerateAsync(ISessionImplementor session, object obj, private async Task GetNextAsync(ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - Logger.Debug("fetching initial value: " + _sql); + Logger.Debug("fetching initial value: {0}", _sql); try { @@ -72,7 +72,7 @@ private async Task GetNextAsync(ISessionImplementor session, CancellationToken c _next = 1L; } _sql = null; - Logger.Debug("first free id: " + _next); + Logger.Debug("first free id: {0}", _next); } finally { @@ -86,7 +86,7 @@ private async Task GetNextAsync(ISessionImplementor session, CancellationToken c } catch (DbException sqle) { - Logger.Error("could not get increment value", sqle); + Logger.Error(sqle, "could not get increment value"); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "could not fetch initial value for increment generator"); } diff --git a/src/NHibernate/Async/Id/NativeGuidGenerator.cs b/src/NHibernate/Async/Id/NativeGuidGenerator.cs index dbd3a068460..50484fcd52a 100644 --- a/src/NHibernate/Async/Id/NativeGuidGenerator.cs +++ b/src/NHibernate/Async/Id/NativeGuidGenerator.cs @@ -48,7 +48,7 @@ public async Task GenerateAsync(ISessionImplementor session, object obj, { reader.Close(); } - log.Debug("GUID identifier generated: " + result); + log.Debug("GUID identifier generated: {0}", result); return result; } finally @@ -64,4 +64,4 @@ public async Task GenerateAsync(ISessionImplementor session, object obj, #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/SequenceGenerator.cs b/src/NHibernate/Async/Id/SequenceGenerator.cs index 882e5496c80..5cb811a7e45 100644 --- a/src/NHibernate/Async/Id/SequenceGenerator.cs +++ b/src/NHibernate/Async/Id/SequenceGenerator.cs @@ -52,9 +52,9 @@ public virtual async Task GenerateAsync(ISessionImplementor session, obj { await (reader.ReadAsync(cancellationToken)).ConfigureAwait(false); object result = await (IdentifierGeneratorFactory.GetAsync(reader, identifierType, session, cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Sequence identifier generated: " + result); + log.Debug("Sequence identifier generated: {0}", result); } return result; } @@ -70,7 +70,7 @@ public virtual async Task GenerateAsync(ISessionImplementor session, obj } catch (DbException sqle) { - log.Error("error generating sequence", sqle); + log.Error(sqle, "error generating sequence"); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "could not get next sequence value"); } } diff --git a/src/NHibernate/Async/Id/SequenceHiLoGenerator.cs b/src/NHibernate/Async/Id/SequenceHiLoGenerator.cs index 5cb8996e0c0..94ee6d72da5 100644 --- a/src/NHibernate/Async/Id/SequenceHiLoGenerator.cs +++ b/src/NHibernate/Async/Id/SequenceHiLoGenerator.cs @@ -55,8 +55,8 @@ public override async Task GenerateAsync(ISessionImplementor session, ob long hival = Convert.ToInt64(await (base.GenerateAsync(session, obj, cancellationToken)).ConfigureAwait(false)); lo = (hival == 0) ? 1 : 0; hi = hival * (maxLo + 1); - if (log.IsDebugEnabled) - log.Debug("new hi value: " + hival); + if (log.IsDebugEnabled()) + log.Debug("new hi value: {0}", hival); } return IdentifierGeneratorFactory.CreateNumber(hi + lo++, returnClass); } @@ -64,4 +64,4 @@ public override async Task GenerateAsync(ISessionImplementor session, ob #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/TableGenerator.cs b/src/NHibernate/Async/Id/TableGenerator.cs index 30853fa1211..15707b36549 100644 --- a/src/NHibernate/Async/Id/TableGenerator.cs +++ b/src/NHibernate/Async/Id/TableGenerator.cs @@ -79,23 +79,17 @@ public override async Task DoWorkInCurrentTransactionAsync(ISessionImple rs = await (qps.ExecuteReaderAsync(cancellationToken)).ConfigureAwait(false); if (!await (rs.ReadAsync(cancellationToken)).ConfigureAwait(false)) { - string err; - if (string.IsNullOrEmpty(whereClause)) - { - err = "could not read a hi value - you need to populate the table: " + tableName; - } - else - { - err = string.Format("could not read a hi value from table '{0}' using the where clause ({1})- you need to populate the table.", tableName, whereClause); - } - log.Error(err); - throw new IdentifierGenerationException(err); + var errFormat = string.IsNullOrEmpty(whereClause) + ? "could not read a hi value - you need to populate the table: {0}" + : "could not read a hi value from table '{0}' using the where clause ({1})- you need to populate the table."; + log.Error(errFormat, tableName, whereClause); + throw new IdentifierGenerationException(string.Format(errFormat, tableName, whereClause)); } result = Convert.ToInt64(columnType.Get(rs, 0, session)); } catch (Exception e) { - log.Error("could not read a hi value", e); + log.Error(e, "could not read a hi value"); throw; } finally @@ -122,7 +116,7 @@ public override async Task DoWorkInCurrentTransactionAsync(ISessionImple } catch (Exception e) { - log.Error("could not update hi value in: " + tableName, e); + log.Error(e, "could not update hi value in: {0}", tableName); throw; } finally @@ -135,4 +129,4 @@ public override async Task DoWorkInCurrentTransactionAsync(ISessionImple return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Id/TableHiLoGenerator.cs b/src/NHibernate/Async/Id/TableHiLoGenerator.cs index 09f8ed8cf07..8302dad5e98 100644 --- a/src/NHibernate/Async/Id/TableHiLoGenerator.cs +++ b/src/NHibernate/Async/Id/TableHiLoGenerator.cs @@ -53,7 +53,7 @@ public override async Task GenerateAsync(ISessionImplementor session, ob long hival = Convert.ToInt64(await (base.GenerateAsync(session, obj, cancellationToken)).ConfigureAwait(false)); lo = (hival == 0) ? 1 : 0; hi = hival * (maxLo + 1); - log.Debug("New high value: " + hival); + log.Debug("New high value: {0}", hival); } return IdentifierGeneratorFactory.CreateNumber(hi + lo++, returnClass); @@ -62,4 +62,4 @@ public override async Task GenerateAsync(ISessionImplementor session, ob #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs b/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs index 7fa5ea1175f..893d59a9d26 100644 --- a/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs +++ b/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs @@ -40,12 +40,12 @@ public partial class MultiCriteriaImpl : IMultiCriteria CreateCriteriaLoaders(); CombineCriteriaQueries(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("Multi criteria with {0} criteria queries.", criteriaQueries.Count); + log.Debug("Multi criteria with {0} criteria queries.", criteriaQueries.Count); for (int i = 0; i < criteriaQueries.Count; i++) { - log.DebugFormat("Query #{0}: {1}", i, criteriaQueries[i]); + log.Debug("Query #{0}: {1}", i, criteriaQueries[i]); } } @@ -207,8 +207,7 @@ private async Task GetResultsFromDatabaseAsync(IList results, CancellationToken } catch (Exception sqle) { - var message = string.Format("Failed to execute multi criteria: [{0}]", resultSetsCommand.Sql); - log.Error(message, sqle); + log.Error(sqle, "Failed to execute multi criteria: [{0}]", resultSetsCommand.Sql); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi criteria", resultSetsCommand.Sql); } if (statsEnabled) diff --git a/src/NHibernate/Async/Impl/MultiQueryImpl.cs b/src/NHibernate/Async/Impl/MultiQueryImpl.cs index 06281206c97..8a11f631a00 100644 --- a/src/NHibernate/Async/Impl/MultiQueryImpl.cs +++ b/src/NHibernate/Async/Impl/MultiQueryImpl.cs @@ -44,12 +44,12 @@ public partial class MultiQueryImpl : IMultiQuery bool cacheable = session.Factory.Settings.IsQueryCacheEnabled && isCacheable; combinedParameters = CreateCombinedQueryParameters(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("Multi query with {0} queries.", queries.Count); + log.Debug("Multi query with {0} queries.", queries.Count); for (int i = 0; i < queries.Count; i++) { - log.DebugFormat("Query #{0}: {1}", i, queries[i]); + log.Debug("Query #{0}: {1}", i, queries[i]); } } @@ -86,9 +86,9 @@ protected async Task> DoListAsync(CancellationToken cancellationTok { using (var reader = await (resultSetsCommand.GetReaderAsync(commandTimeout != RowSelection.NoValue ? commandTimeout : (int?)null, cancellationToken)).ConfigureAwait(false)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("Executing {0} queries", translators.Count); + log.Debug("Executing {0} queries", translators.Count); } for (int i = 0; i < translators.Count; i++) { @@ -118,7 +118,7 @@ protected async Task> DoListAsync(CancellationToken cancellationTok translator.Loader.HandleEmptyCollections(parameter.CollectionKeys, reader, session); EntityKey[] keys = new EntityKey[entitySpan]; // we can reuse it each time - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("processing result set"); } @@ -127,9 +127,9 @@ protected async Task> DoListAsync(CancellationToken cancellationTok int count; for (count = 0; count < maxRows && await (reader.ReadAsync(cancellationToken)).ConfigureAwait(false); count++) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("result set row: " + count); + log.Debug("result set row: {0}", count); } rowCount++; @@ -144,16 +144,16 @@ protected async Task> DoListAsync(CancellationToken cancellationTok } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("done processing result set ({0} rows)", count)); + log.Debug("done processing result set ({0} rows)", count); } results.Add(tempResults); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("Query {0} returned {1} results", i, tempResults.Count); + log.Debug("Query {0} returned {1} results", i, tempResults.Count); } await (reader.NextResultAsync(cancellationToken)).ConfigureAwait(false); @@ -175,8 +175,7 @@ protected async Task> DoListAsync(CancellationToken cancellationTok } catch (Exception sqle) { - var message = string.Format("Failed to execute multi query: [{0}]", resultSetsCommand.Sql); - log.Error(message, sqle); + log.Error(sqle, "Failed to execute multi query: [{0}]", resultSetsCommand.Sql); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi query", resultSetsCommand.Sql); } diff --git a/src/NHibernate/Async/Impl/SessionFactoryImpl.cs b/src/NHibernate/Async/Impl/SessionFactoryImpl.cs index 0e1cf628866..7f5a7a7cce2 100644 --- a/src/NHibernate/Async/Impl/SessionFactoryImpl.cs +++ b/src/NHibernate/Async/Impl/SessionFactoryImpl.cs @@ -124,9 +124,9 @@ public sealed partial class SessionFactoryImpl : ISessionFactoryImplementor, IOb IEntityPersister p = GetEntityPersister(persistentClass.FullName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + MessageHelper.InfoString(p, id)); + log.Debug("evicting second-level cache: {0}", MessageHelper.InfoString(p, id)); } CacheKey ck = GenerateCacheKeyForEvict(id, p.IdentifierType, p.RootEntityName); return p.Cache.RemoveAsync(ck, cancellationToken); @@ -150,9 +150,9 @@ public sealed partial class SessionFactoryImpl : ISessionFactoryImplementor, IOb IEntityPersister p = GetEntityPersister(persistentClass.FullName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + p.EntityName); + log.Debug("evicting second-level cache: {0}", p.EntityName); } return p.Cache.ClearAsync(cancellationToken); } @@ -175,9 +175,9 @@ public sealed partial class SessionFactoryImpl : ISessionFactoryImplementor, IOb IEntityPersister p = GetEntityPersister(entityName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + p.EntityName); + log.Debug("evicting second-level cache: {0}", p.EntityName); } return p.Cache.ClearAsync(cancellationToken); } @@ -200,9 +200,9 @@ public sealed partial class SessionFactoryImpl : ISessionFactoryImplementor, IOb IEntityPersister p = GetEntityPersister(entityName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + MessageHelper.InfoString(p, id, this)); + log.Debug("evicting second-level cache: {0}", MessageHelper.InfoString(p, id, this)); } CacheKey cacheKey = GenerateCacheKeyForEvict(id, p.IdentifierType, p.RootEntityName); return p.Cache.RemoveAsync(cacheKey, cancellationToken); @@ -226,9 +226,9 @@ public sealed partial class SessionFactoryImpl : ISessionFactoryImplementor, IOb ICollectionPersister p = GetCollectionPersister(roleName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + MessageHelper.CollectionInfoString(p, id)); + log.Debug("evicting second-level cache: {0}", MessageHelper.CollectionInfoString(p, id)); } CacheKey ck = GenerateCacheKeyForEvict(id, p.KeyType, p.Role); return p.Cache.RemoveAsync(ck, cancellationToken); @@ -252,9 +252,9 @@ public sealed partial class SessionFactoryImpl : ISessionFactoryImplementor, IOb ICollectionPersister p = GetCollectionPersister(roleName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + p.Role); + log.Debug("evicting second-level cache: {0}", p.Role); } return p.Cache.ClearAsync(cancellationToken); } diff --git a/src/NHibernate/Async/Impl/SessionImpl.cs b/src/NHibernate/Async/Impl/SessionImpl.cs index 68cc9b4d6f1..d3d7a100bf4 100644 --- a/src/NHibernate/Async/Impl/SessionImpl.cs +++ b/src/NHibernate/Async/Impl/SessionImpl.cs @@ -67,7 +67,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa } catch (Exception t) { - log.Error("exception in interceptor afterTransactionCompletion()", t); + log.Error(t, "exception in interceptor afterTransactionCompletion()"); } if (IsClosed) @@ -359,12 +359,12 @@ public override async Task EnumerableAsync(IQueryExpression queryEx throw new ArgumentNullException("query", "attempt to perform delete-by-query with null query"); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("delete: " + query); + log.Debug("delete: {0}", query); if (values.Length != 0) { - log.Debug("parameters: " + StringHelper.ToString(values)); + log.Debug("parameters: {0}", StringHelper.ToString(values)); } } @@ -510,10 +510,10 @@ public async Task ForceFlushAsync(EntityEntry entityEntry, CancellationToken can cancellationToken.ThrowIfCancellationRequested(); using (BeginProcess()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("flushing to force deletion of re-saved object: " + - MessageHelper.InfoString(entityEntry.Persister, entityEntry.Id, Factory)); + log.Debug("flushing to force deletion of re-saved object: {0}", + MessageHelper.InfoString(entityEntry.Persister, entityEntry.Id, Factory)); } if (persistenceContext.CascadeLevel > 0) @@ -910,10 +910,10 @@ public override async Task ImmediateLoadAsync(string entityName, object cancellationToken.ThrowIfCancellationRequested(); using (BeginProcess()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { IEntityPersister persister = Factory.GetEntityPersister(entityName); - log.Debug("initializing proxy: " + MessageHelper.InfoString(persister, id, Factory)); + log.Debug("initializing proxy: {0}", MessageHelper.InfoString(persister, id, Factory)); } LoadEvent loadEvent = new LoadEvent(id, entityName, true, this); @@ -1249,7 +1249,7 @@ public override async Task BeforeTransactionCompletionAsync(ITransaction tx, Can } catch (Exception e) { - log.Error("exception in interceptor BeforeTransactionCompletion()", e); + log.Error(e, "exception in interceptor BeforeTransactionCompletion()"); throw; } diff --git a/src/NHibernate/Async/Impl/StatelessSessionImpl.cs b/src/NHibernate/Async/Impl/StatelessSessionImpl.cs index 03b8bb20832..1872e963450 100644 --- a/src/NHibernate/Async/Impl/StatelessSessionImpl.cs +++ b/src/NHibernate/Async/Impl/StatelessSessionImpl.cs @@ -570,9 +570,9 @@ private Task GetAsync(System.Type persistentClass, object id, Cancellati { IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.GetIdentifier(entity); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("refreshing transient " + MessageHelper.InfoString(persister, id, Factory)); + log.Debug("refreshing transient {0}", MessageHelper.InfoString(persister, id, Factory)); } //from H3.2 TODO : can this ever happen??? // EntityKey key = new EntityKey( id, persister, source.getEntityMode() ); diff --git a/src/NHibernate/Async/Loader/Entity/CollectionElementLoader.cs b/src/NHibernate/Async/Loader/Entity/CollectionElementLoader.cs index d7bf0596aff..45b53501d9c 100644 --- a/src/NHibernate/Async/Loader/Entity/CollectionElementLoader.cs +++ b/src/NHibernate/Async/Loader/Entity/CollectionElementLoader.cs @@ -71,4 +71,4 @@ protected override Task GetResultColumnOrRowAsync(object[] row, IResultT } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Loader/Entity/EntityLoader.cs b/src/NHibernate/Async/Loader/Entity/EntityLoader.cs index 5c006127190..37d957999e7 100644 --- a/src/NHibernate/Async/Loader/Entity/EntityLoader.cs +++ b/src/NHibernate/Async/Loader/Entity/EntityLoader.cs @@ -29,4 +29,4 @@ public Task LoadByUniqueKeyAsync(ISessionImplementor session, object key return LoadAsync(session, key, null, null, cancellationToken); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Loader/Loader.cs b/src/NHibernate/Async/Loader/Loader.cs index f8a85bfebd0..da2bab6d5a6 100644 --- a/src/NHibernate/Async/Loader/Loader.cs +++ b/src/NHibernate/Async/Loader/Loader.cs @@ -269,7 +269,7 @@ private async Task DoQueryAsync(ISessionImplementor session, QueryParamet HandleEmptyCollections(queryParameters.CollectionKeys, rs, session); EntityKey[] keys = new EntityKey[entitySpan]; // we can reuse it each time - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { Log.Debug("processing result set"); } @@ -277,9 +277,9 @@ private async Task DoQueryAsync(ISessionImplementor session, QueryParamet int count; for (count = 0; count < maxRows && await (rs.ReadAsync(cancellationToken)).ConfigureAwait(false); count++) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("result set row: " + count); + Log.Debug("result set row: {0}", count); } object result = await (GetRowFromResultSetAsync(rs, session, queryParameters, lockModeArray, optionalObjectKey, @@ -294,9 +294,9 @@ private async Task DoQueryAsync(ISessionImplementor session, QueryParamet } } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug(string.Format("done processing result set ({0} rows)", count)); + Log.Debug("done processing result set ({0} rows)", count); } } catch (Exception e) @@ -358,9 +358,9 @@ internal async Task InitializeEntitiesAndCollectionsAsync(IList hydratedObjects, { int hydratedObjectsSize = hydratedObjects.Count; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug(string.Format("total objects hydrated: {0}", hydratedObjectsSize)); + Log.Debug("total objects hydrated: {0}", hydratedObjectsSize); } for (int i = 0; i < hydratedObjectsSize; i++) @@ -458,9 +458,9 @@ private static async Task ReadCollectionElementAsync(object optionalOwner, objec { // we found a collection element in the result set - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("found row of collection: " + MessageHelper.CollectionInfoString(persister, collectionRowKey)); + Log.Debug("found row of collection: {0}", MessageHelper.CollectionInfoString(persister, collectionRowKey)); } object owner = optionalOwner; @@ -490,9 +490,9 @@ private static async Task ReadCollectionElementAsync(object optionalOwner, objec // ensure that a collection is created with the owner's identifier, // since what we have is an empty collection - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("result set contains (possibly empty) collection: " + MessageHelper.CollectionInfoString(persister, optionalKey)); + Log.Debug("result set contains (possibly empty) collection: {0}", MessageHelper.CollectionInfoString(persister, optionalKey)); } persistenceContext.LoadContexts.GetCollectionLoadContext(rs).GetLoadingCollection(persister, optionalKey); // handle empty collection @@ -579,9 +579,9 @@ private async Task GetRowAsync(DbDataReader rs, ILoadable[] persisters int cols = persisters.Length; IEntityAliases[] descriptors = EntityAliases; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("result row: " + StringHelper.ToString(keys)); + Log.Debug("result row: {0}", StringHelper.ToString(keys)); } object[] rowResults = new object[cols]; @@ -703,9 +703,9 @@ private async Task LoadFromResultSetAsync(DbDataReader rs, int i, object obj, st // Get the persister for the _subclass_ ILoadable persister = (ILoadable)Factory.GetEntityPersister(instanceClass); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Initializing object from DataReader: " + MessageHelper.InfoString(persister, id)); + Log.Debug("Initializing object from DataReader: {0}", MessageHelper.InfoString(persister, id)); } bool eagerPropertyFetch = IsEagerPropertyFetchEnabled(i); @@ -895,9 +895,9 @@ protected async Task LoadEntityAsync(ISessionImplementor session, object string optionalEntityName, object optionalIdentifier, IEntityPersister persister, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("loading entity: " + MessageHelper.InfoString(persister, id, identifierType, Factory)); + Log.Debug("loading entity: {0}", MessageHelper.InfoString(persister, id, identifierType, Factory)); } IList result; @@ -961,9 +961,9 @@ protected internal async Task LoadEntityBatchAsync(ISessionImplementor se IEntityPersister persister, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("batch loading entity: " + MessageHelper.InfoString(persister, ids, Factory)); + Log.Debug("batch loading entity: {0}", MessageHelper.InfoString(persister, ids, Factory)); } IType[] types = new IType[ids.Length]; @@ -998,9 +998,9 @@ protected internal async Task LoadEntityBatchAsync(ISessionImplementor se public async Task LoadCollectionAsync(ISessionImplementor session, object id, IType type, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("loading collection: " + MessageHelper.CollectionInfoString(CollectionPersisters[0], id)); + Log.Debug("loading collection: {0}", MessageHelper.CollectionInfoString(CollectionPersisters[0], id)); } object[] ids = new object[] { id }; @@ -1029,9 +1029,9 @@ public async Task LoadCollectionAsync(ISessionImplementor session, object id, IT public async Task LoadCollectionBatchAsync(ISessionImplementor session, object[] ids, IType type, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("batch loading collection: " + MessageHelper.CollectionInfoString(CollectionPersisters[0], ids)); + Log.Debug("batch loading collection: {0}", MessageHelper.CollectionInfoString(CollectionPersisters[0], ids)); } IType[] idTypes = new IType[ids.Length]; diff --git a/src/NHibernate/Async/Persister/Collection/AbstractCollectionPersister.cs b/src/NHibernate/Async/Persister/Collection/AbstractCollectionPersister.cs index 26e328dcb42..eaee0545ee1 100644 --- a/src/NHibernate/Async/Persister/Collection/AbstractCollectionPersister.cs +++ b/src/NHibernate/Async/Persister/Collection/AbstractCollectionPersister.cs @@ -188,9 +188,9 @@ public async Task RemoveAsync(object id, ISessionImplementor session, Cancellati cancellationToken.ThrowIfCancellationRequested(); if (!isInverse && RowDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Deleting collection: " + MessageHelper.CollectionInfoString(this, id, Factory)); + log.Debug("Deleting collection: {0}", MessageHelper.CollectionInfoString(this, id, Factory)); } // Remove all the old entries @@ -233,7 +233,7 @@ public async Task RemoveAsync(object id, ISessionImplementor session, Cancellati } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("done deleting collection"); } @@ -251,9 +251,9 @@ public async Task RecreateAsync(IPersistentCollection collection, object id, ISe cancellationToken.ThrowIfCancellationRequested(); if (!isInverse && RowInsertEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting collection: " + MessageHelper.CollectionInfoString(this, collection, id, session)); + log.Debug("Inserting collection: {0}", MessageHelper.CollectionInfoString(this, collection, id, session)); } try @@ -293,10 +293,10 @@ public async Task RecreateAsync(IPersistentCollection collection, object id, ISe i++; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (count > 0) - log.Debug(string.Format("done inserting collection: {0} rows inserted", count)); + log.Debug("done inserting collection: {0} rows inserted", count); else log.Debug("collection was empty"); } @@ -314,9 +314,9 @@ public async Task DeleteRowsAsync(IPersistentCollection collection, object id, I cancellationToken.ThrowIfCancellationRequested(); if (!isInverse && RowDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Deleting rows of collection: " + MessageHelper.CollectionInfoString(this, collection, id, session)); + log.Debug("Deleting rows of collection: {0}", MessageHelper.CollectionInfoString(this, collection, id, session)); } bool deleteByIndex = !IsOneToMany && hasIndex && !indexContainsFormula; @@ -393,10 +393,10 @@ public async Task DeleteRowsAsync(IPersistentCollection collection, object id, I } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (count > 0) - log.Debug("done deleting collection rows: " + count + " deleted"); + log.Debug("done deleting collection rows: {0} deleted", count); else log.Debug("no rows to delete"); } @@ -414,9 +414,9 @@ public async Task InsertRowsAsync(IPersistentCollection collection, object id, I cancellationToken.ThrowIfCancellationRequested(); if (!isInverse && RowInsertEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting rows of collection: " + MessageHelper.CollectionInfoString(this, collection, id, session)); + log.Debug("Inserting rows of collection: {0}", MessageHelper.CollectionInfoString(this, collection, id, session)); } try @@ -450,9 +450,9 @@ public async Task InsertRowsAsync(IPersistentCollection collection, object id, I i++; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("done inserting rows: {0} inserted", count)); + log.Debug("done inserting rows: {0} inserted", count); } } catch (DbException sqle) @@ -468,17 +468,17 @@ public async Task UpdateRowsAsync(IPersistentCollection collection, object id, I cancellationToken.ThrowIfCancellationRequested(); if (!isInverse && collection.RowUpdatePossible) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("Updating rows of collection: {0}#{1}", role, id)); + log.Debug("Updating rows of collection: {0}#{1}", role, id); } // update all the modified entries int count = await (DoUpdateRowsAsync(id, collection, session, cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("done updating rows: {0} updated", count)); + log.Debug("done updating rows: {0} updated", count); } } } diff --git a/src/NHibernate/Async/Persister/Collection/NamedQueryCollectionInitializer.cs b/src/NHibernate/Async/Persister/Collection/NamedQueryCollectionInitializer.cs index 47e8e0fc780..7349bbdf4c8 100644 --- a/src/NHibernate/Async/Persister/Collection/NamedQueryCollectionInitializer.cs +++ b/src/NHibernate/Async/Persister/Collection/NamedQueryCollectionInitializer.cs @@ -28,9 +28,9 @@ public Task InitializeAsync(object key, ISessionImplementor session, Cancellatio } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("initializing collection: {0} using named query: {1}", persister.Role, queryName)); + log.Debug("initializing collection: {0} using named query: {1}", persister.Role, queryName); } //TODO: is there a more elegant way than downcasting? @@ -51,4 +51,4 @@ public Task InitializeAsync(object key, ISessionImplementor session, Cancellatio } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs b/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs index 87772eff5b5..788554e9d56 100644 --- a/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs +++ b/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs @@ -62,9 +62,9 @@ public virtual Task BindValuesAsync(DbCommand ps, CancellationToken cancellation public async Task GetDatabaseSnapshotAsync(object id, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Getting current persistent state for: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Getting current persistent state for: {0}", MessageHelper.InfoString(this, id, Factory)); } using (session.BeginProcess()) @@ -135,12 +135,12 @@ async Task InternalForceVersionIncrementAsync() { object nextVersion = await (VersionType.NextAsync(currentVersion, session, cancellationToken)).ConfigureAwait(false); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Forcing version increment [" + - MessageHelper.InfoString(this, id, Factory) + "; " + - VersionType.ToLoggableString(currentVersion, Factory) + " -> " + - VersionType.ToLoggableString(nextVersion, Factory) + "]"); + log.Debug("Forcing version increment [{0}; {1} -> {2}]", + MessageHelper.InfoString(this, id, Factory), + VersionType.ToLoggableString(currentVersion, Factory), + VersionType.ToLoggableString(nextVersion, Factory)); } IExpectation expectation = Expectations.AppropriateExpectation(updateResultCheckStyles[0]); @@ -183,9 +183,9 @@ async Task InternalForceVersionIncrementAsync() public async Task GetCurrentVersionAsync(object id, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Getting version: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Getting version: {0}", MessageHelper.InfoString(this, id, Factory)); } using (session.BeginProcess()) try @@ -271,9 +271,9 @@ protected async Task DehydrateAsync(object id, object[] fields, object rowI DbCommand statement, ISessionImplementor session, int index, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Dehydrating entity: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Dehydrating entity: {0}", MessageHelper.InfoString(this, id, Factory)); } // there's a pretty strong coupling between the order of the SQL parameter @@ -320,9 +320,9 @@ public async Task HydrateAsync(DbDataReader rs, object id, object obj, string[][] suffixedPropertyColumns, bool allProperties, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Hydrating entity: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Hydrating entity: {0}", MessageHelper.InfoString(this, id, Factory)); } AbstractEntityPersister rootPersister = (AbstractEntityPersister)rootLoadable; @@ -435,12 +435,12 @@ protected Task InsertAsync(object[] fields, bool[] notNull, SqlCommandIn } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting entity: " + EntityName + " (native id)"); + log.Debug("Inserting entity: {0} (native id)", EntityName); if (IsVersioned) { - log.Debug("Version: " + Versioning.GetVersion(fields, this)); + log.Debug("Version: {0}", Versioning.GetVersion(fields, this)); } } IBinder binder = new GeneratedIdentifierBinder(fields, notNull, session, obj, this); @@ -478,12 +478,12 @@ protected async Task InsertAsync(object id, object[] fields, bool[] notNull, int return; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting entity: " + MessageHelper.InfoString(this, tableId, Factory)); + log.Debug("Inserting entity: {0}", MessageHelper.InfoString(this, tableId, Factory)); if (j == 0 && IsVersioned) { - log.Debug("Version: " + Versioning.GetVersion(fields, this)); + log.Debug("Version: {0}", Versioning.GetVersion(fields, this)); } } @@ -598,12 +598,12 @@ protected async Task UpdateAsync(object id, object[] fields, object[] oldF //bool callable = IsUpdateCallable(j); bool useBatch = j == 0 && expectation.CanBeBatched && IsBatchable; //note: updates to joined tables can't be batched... - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Updating entity: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Updating entity: {0}", MessageHelper.InfoString(this, id, Factory)); if (useVersion) { - log.Debug("Existing version: " + oldVersion + " -> New Version: " + fields[VersionProperty]); + log.Debug("Existing version: {0} -> New Version: {1}", oldVersion, fields[VersionProperty]); } } @@ -720,20 +720,20 @@ public async Task DeleteAsync(object id, object version, int j, object obj, SqlC IExpectation expectation = Expectations.AppropriateExpectation(deleteResultCheckStyles[j]); bool useBatch = j == 0 && expectation.CanBeBatched && IsBatchable; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Deleting entity: " + MessageHelper.InfoString(this, tableId, Factory)); + log.Debug("Deleting entity: {0}", MessageHelper.InfoString(this, tableId, Factory)); if (useVersion) { - log.Debug("Version: " + version); + log.Debug("Version: {0}", version); } } if (IsTableCascadeDeleteEnabled(j)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("delete handled by foreign key constraint: " + GetTableName(j)); + log.Debug("delete handled by foreign key constraint: {0}", GetTableName(j)); } return; //EARLY EXIT! } @@ -987,9 +987,9 @@ public Task LoadAsync(object id, object optionalObject, LockMode lockMod } try { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Fetching entity: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Fetching entity: {0}", MessageHelper.InfoString(this, id, Factory)); } IUniqueEntityLoader loader = GetAppropriateLoader(lockMode, session); @@ -1245,9 +1245,9 @@ public virtual Task GetNaturalIdentifierSnapshotAsync(object id, ISess return InternalGetNaturalIdentifierSnapshotAsync(); async Task InternalGetNaturalIdentifierSnapshotAsync() { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Getting current natural-id snapshot state for: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Getting current natural-id snapshot state for: {0}", MessageHelper.InfoString(this, id, Factory)); } int[] naturalIdPropertyIndexes = NaturalIdentifierProperties; diff --git a/src/NHibernate/Async/Persister/Entity/NamedQueryLoader.cs b/src/NHibernate/Async/Persister/Entity/NamedQueryLoader.cs index c77b848ff4c..67bb866837f 100644 --- a/src/NHibernate/Async/Persister/Entity/NamedQueryLoader.cs +++ b/src/NHibernate/Async/Persister/Entity/NamedQueryLoader.cs @@ -23,9 +23,9 @@ public partial class NamedQueryLoader : IUniqueEntityLoader public async Task LoadAsync(object id, object optionalObject, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("loading entity: {0} using named query: {1}", persister.EntityName, queryName)); + log.Debug("loading entity: {0} using named query: {1}", persister.EntityName, queryName); } AbstractQueryImpl query = (AbstractQueryImpl) session.GetNamedQuery(queryName); @@ -49,4 +49,4 @@ public async Task LoadAsync(object id, object optionalObject, ISessionIm return session.PersistenceContext.GetEntity(session.GenerateEntityKey(id, persister)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Tool/hbm2ddl/SchemaExport.cs b/src/NHibernate/Async/Tool/hbm2ddl/SchemaExport.cs index c04e38dd66f..807e50786d8 100644 --- a/src/NHibernate/Async/Tool/hbm2ddl/SchemaExport.cs +++ b/src/NHibernate/Async/Tool/hbm2ddl/SchemaExport.cs @@ -174,8 +174,8 @@ private async Task ExecuteAsync(Action scriptAction, bool execute, bool } catch (Exception e) { - log.Warn("Unsuccessful: " + sql); - log.Warn(e.Message); + log.Warn("Unsuccessful: {0}", sql); + log.Warn(e, e.Message); if (throwOnError) { throw; @@ -193,7 +193,7 @@ private async Task ExecuteAsync(Action scriptAction, bool execute, bool foreach (string stmt in splitter) { - log.DebugFormat("SQL Batch: {0}", stmt); + log.Debug("SQL Batch: {0}", stmt); cmd.CommandText = stmt; cmd.CommandType = CommandType.Text; await (cmd.ExecuteNonQueryAsync(cancellationToken)).ConfigureAwait(false); @@ -290,7 +290,7 @@ public async Task ExecuteAsync(Action scriptAction, bool execute, bool j } catch (Exception e) { - log.Error("Could not close connection: " + e.Message, e); + log.Error(e, "Could not close connection: {0}", e.Message); } if (exportOutput != null) { @@ -300,7 +300,7 @@ public async Task ExecuteAsync(Action scriptAction, bool execute, bool j } catch (Exception ioe) { - log.Error("Error closing output file " + outputFile + ": " + ioe.Message, ioe); + log.Error(ioe, "Error closing output file {0}: {1}", outputFile, ioe.Message); } } } @@ -394,7 +394,7 @@ public async Task ExecuteAsync(Action scriptAction, bool execute, bool j } catch (Exception e) { - log.Error(e.Message, e); + log.Error(e, e.Message); throw new HibernateException(e.Message, e); } finally @@ -407,4 +407,4 @@ public async Task ExecuteAsync(Action scriptAction, bool execute, bool j } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Tool/hbm2ddl/SchemaUpdate.cs b/src/NHibernate/Async/Tool/hbm2ddl/SchemaUpdate.cs index 49686df38dc..2f7b5e9098c 100644 --- a/src/NHibernate/Async/Tool/hbm2ddl/SchemaUpdate.cs +++ b/src/NHibernate/Async/Tool/hbm2ddl/SchemaUpdate.cs @@ -100,7 +100,7 @@ public partial class SchemaUpdate } catch (Exception e) { - log.Error("Error running schema update", e); + log.Error(e, "Error running schema update"); Console.WriteLine(e); } } @@ -163,7 +163,7 @@ public partial class SchemaUpdate catch (Exception sqle) { exceptions.Add(sqle); - log.Error("could not get database metadata", sqle); + log.Error(sqle, "could not get database metadata"); throw; } @@ -191,7 +191,7 @@ public partial class SchemaUpdate catch (Exception e) { exceptions.Add(e); - log.Error("Unsuccessful: " + sql, e); + log.Error(e, "Unsuccessful: {0}", sql); } } @@ -200,7 +200,7 @@ public partial class SchemaUpdate catch (Exception e) { exceptions.Add(e); - log.Error("could not complete schema update", e); + log.Error(e, "could not complete schema update"); } finally { @@ -215,9 +215,9 @@ public partial class SchemaUpdate catch (Exception e) { exceptions.Add(e); - log.Error("Error closing connection", e); + log.Error(e, "Error closing connection"); } } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Tool/hbm2ddl/SchemaValidator.cs b/src/NHibernate/Async/Tool/hbm2ddl/SchemaValidator.cs index 78b684876c9..844de97b4d3 100644 --- a/src/NHibernate/Async/Tool/hbm2ddl/SchemaValidator.cs +++ b/src/NHibernate/Async/Tool/hbm2ddl/SchemaValidator.cs @@ -68,7 +68,7 @@ public partial class SchemaValidator } catch (Exception e) { - log.Error("Error running schema update", e); + log.Error(e, "Error running schema update"); Console.WriteLine(e); } } @@ -90,14 +90,14 @@ public partial class SchemaValidator } catch (Exception sqle) { - log.Error("could not get database metadata", sqle); + log.Error(sqle, "could not get database metadata"); throw; } configuration.ValidateSchema(dialect, meta); } catch (Exception e) { - log.Error("could not complete schema validation", e); + log.Error(e, "could not complete schema validation"); throw; } finally @@ -108,7 +108,7 @@ public partial class SchemaValidator } catch (Exception e) { - log.Error("Error closing connection", e); + log.Error(e, "Error closing connection"); } } } diff --git a/src/NHibernate/Async/Transaction/AdoNetTransactionFactory.cs b/src/NHibernate/Async/Transaction/AdoNetTransactionFactory.cs index add13d2a768..ec3ea6bc578 100644 --- a/src/NHibernate/Async/Transaction/AdoNetTransactionFactory.cs +++ b/src/NHibernate/Async/Transaction/AdoNetTransactionFactory.cs @@ -84,7 +84,7 @@ async Task InternalExecuteWorkInIsolationAsync() } catch (Exception ignore) { - isolaterLog.Debug("Unable to rollback transaction", ignore); + isolaterLog.Debug(ignore, "Unable to rollback transaction"); } if (t is HibernateException) @@ -123,7 +123,7 @@ async Task InternalExecuteWorkInIsolationAsync() } catch (Exception ignore) { - isolaterLog.Warn("Unable to dispose transaction", ignore); + isolaterLog.Warn(ignore, "Unable to dispose transaction"); } if (session.Factory.Dialect is SQLiteDialect == false) diff --git a/src/NHibernate/Async/Transaction/AdoTransaction.cs b/src/NHibernate/Async/Transaction/AdoTransaction.cs index 77156a210b6..6d39973d7ef 100644 --- a/src/NHibernate/Async/Transaction/AdoTransaction.cs +++ b/src/NHibernate/Async/Transaction/AdoTransaction.cs @@ -72,7 +72,7 @@ private async Task AfterTransactionCompletionAsync(bool successful, Cancellation } catch (HibernateException e) { - log.Error("Commit failed", e); + log.Error(e, "Commit failed"); await (AfterTransactionCompletionAsync(false, cancellationToken)).ConfigureAwait(false); commitFailed = true; // Don't wrap HibernateExceptions @@ -80,7 +80,7 @@ private async Task AfterTransactionCompletionAsync(bool successful, Cancellation } catch (Exception e) { - log.Error("Commit failed", e); + log.Error(e, "Commit failed"); await (AfterTransactionCompletionAsync(false, cancellationToken)).ConfigureAwait(false); commitFailed = true; throw new TransactionException("Commit failed with SQL exception", e); @@ -123,13 +123,13 @@ private async Task AfterTransactionCompletionAsync(bool successful, Cancellation } catch (HibernateException e) { - log.Error("Rollback failed", e); + log.Error(e, "Rollback failed"); // Don't wrap HibernateExceptions throw; } catch (Exception e) { - log.Error("Rollback failed", e); + log.Error(e, "Rollback failed"); throw new TransactionException("Rollback failed with SQL Exception", e); } finally diff --git a/src/NHibernate/Async/Type/CollectionType.cs b/src/NHibernate/Async/Type/CollectionType.cs index c1f9283f4cc..773e5396c2d 100644 --- a/src/NHibernate/Async/Type/CollectionType.cs +++ b/src/NHibernate/Async/Type/CollectionType.cs @@ -214,9 +214,9 @@ public async Task GetCollectionAsync(object key, ISessionImplementor ses } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Created collection wrapper: " + MessageHelper.CollectionInfoString(persister, collection, key, session)); + log.Debug("Created collection wrapper: {0}", MessageHelper.CollectionInfoString(persister, collection, key, session)); } } collection.Owner = owner; diff --git a/src/NHibernate/Async/Type/DbTimestampType.cs b/src/NHibernate/Async/Type/DbTimestampType.cs index 74609fb18a3..c0671e97460 100644 --- a/src/NHibernate/Async/Type/DbTimestampType.cs +++ b/src/NHibernate/Async/Type/DbTimestampType.cs @@ -66,7 +66,7 @@ protected virtual async Task UsePreparedStatementAsync(string timestam rs = await (session.Batcher.ExecuteReaderAsync(ps, cancellationToken)).ConfigureAwait(false); await (rs.ReadAsync(cancellationToken)).ConfigureAwait(false); var ts = rs.GetDateTime(0); - log.DebugFormat("current timestamp retreived from db : {0} (ticks={1})", ts, ts.Ticks); + log.Debug("current timestamp retreived from db : {0} (ticks={1})", ts, ts.Ticks); return ts; } catch (DbException sqle) @@ -87,7 +87,7 @@ protected virtual async Task UsePreparedStatementAsync(string timestam } catch (DbException sqle) { - log.Warn("unable to clean up prepared statement", sqle); + log.Warn(sqle, "unable to clean up prepared statement"); } } } diff --git a/src/NHibernate/Cache/CacheFactory.cs b/src/NHibernate/Cache/CacheFactory.cs index 75ac5ebdbe0..f79db5383a7 100644 --- a/src/NHibernate/Cache/CacheFactory.cs +++ b/src/NHibernate/Cache/CacheFactory.cs @@ -9,7 +9,7 @@ namespace NHibernate.Cache /// public static class CacheFactory { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(CacheFactory)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(CacheFactory)); public const string ReadOnly = "read-only"; public const string ReadWrite = "read-write"; @@ -38,9 +38,9 @@ public static ICacheConcurrencyStrategy CreateCache(string usage, string name, b string prefix = settings.CacheRegionPrefix; if (prefix != null) name = prefix + '.' + name; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("cache for: {0} usage strategy: {1}", name, usage)); + log.Debug("cache for: {0} usage strategy: {1}", name, usage); } ICacheConcurrencyStrategy ccs; @@ -49,7 +49,7 @@ public static ICacheConcurrencyStrategy CreateCache(string usage, string name, b case ReadOnly: if (mutable) { - log.Warn("read-only cache configured for mutable: " + name); + log.Warn("read-only cache configured for mutable: {0}", name); } ccs = new ReadOnlyCache(); break; @@ -81,4 +81,4 @@ public static ICacheConcurrencyStrategy CreateCache(string usage, string name, b return ccs; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cache/NoCacheProvider.cs b/src/NHibernate/Cache/NoCacheProvider.cs index f6c8a3231f2..357b30eb27a 100644 --- a/src/NHibernate/Cache/NoCacheProvider.cs +++ b/src/NHibernate/Cache/NoCacheProvider.cs @@ -9,7 +9,7 @@ namespace NHibernate.Cache /// public class NoCacheProvider : ICacheProvider { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(NoCacheProvider)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(NoCacheProvider)); public const string WarnMessage = "Second-level cache is enabled in a class, but no cache provider was selected. Fake cache used."; diff --git a/src/NHibernate/Cache/NonstrictReadWriteCache.cs b/src/NHibernate/Cache/NonstrictReadWriteCache.cs index c7e158f82a4..f131ac41902 100644 --- a/src/NHibernate/Cache/NonstrictReadWriteCache.cs +++ b/src/NHibernate/Cache/NonstrictReadWriteCache.cs @@ -16,7 +16,7 @@ public partial class NonstrictReadWriteCache : ICacheConcurrencyStrategy { private ICache cache; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(NonstrictReadWriteCache)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(NonstrictReadWriteCache)); /// /// Gets the cache region name. @@ -37,9 +37,9 @@ public ICache Cache /// public object Get(CacheKey key, long txTimestamp) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cache lookup: " + key); + log.Debug("Cache lookup: {0}", key); } object result = cache.Get(key); @@ -68,15 +68,15 @@ public bool Put(CacheKey key, object value, long txTimestamp, object version, IC if (minimalPut && cache.Get(key) != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("item already cached: " + key); + log.Debug("item already cached: {0}", key); } return false; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Caching: " + key); + log.Debug("Caching: {0}", key); } cache.Put(key, value); return true; @@ -92,16 +92,16 @@ public ISoftLock Lock(CacheKey key, object version) public void Remove(CacheKey key) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Removing: " + key); + log.Debug("Removing: {0}", key); } cache.Remove(key); } public void Clear() { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("Clearing"); } @@ -116,7 +116,7 @@ public void Destroy() } catch (Exception e) { - log.Warn("Could not destroy cache", e); + log.Warn(e, "Could not destroy cache"); } } @@ -125,9 +125,9 @@ public void Destroy() /// public void Evict(CacheKey key) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Invalidating: " + key); + log.Debug("Invalidating: {0}", key); } cache.Remove(key); } @@ -154,9 +154,9 @@ public bool Insert(CacheKey key, object value, object currentVersion) /// public void Release(CacheKey key, ISoftLock @lock) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Invalidating (again): " + key); + log.Debug("Invalidating (again): {0}", key); } cache.Remove(key); @@ -179,4 +179,4 @@ public bool AfterInsert(CacheKey key, object value, object version) return false; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cache/ReadOnlyCache.cs b/src/NHibernate/Cache/ReadOnlyCache.cs index a68a6cdc31f..5bce536d4b9 100644 --- a/src/NHibernate/Cache/ReadOnlyCache.cs +++ b/src/NHibernate/Cache/ReadOnlyCache.cs @@ -10,7 +10,7 @@ namespace NHibernate.Cache public partial class ReadOnlyCache : ICacheConcurrencyStrategy { private ICache cache; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ReadOnlyCache)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ReadOnlyCache)); /// /// Gets the cache region name. @@ -29,9 +29,9 @@ public ICache Cache public object Get(CacheKey key, long timestamp) { object result = cache.Get(key); - if (result != null && log.IsDebugEnabled) + if (result != null && log.IsDebugEnabled()) { - log.Debug("Cache hit: " + key); + log.Debug("Cache hit: {0}", key); } return result; } @@ -41,7 +41,7 @@ public object Get(CacheKey key, long timestamp) /// public ISoftLock Lock(CacheKey key, object version) { - log.Error("Application attempted to edit read only item: " + key); + log.Error("Application attempted to edit read only item: {0}", key); throw new InvalidOperationException("ReadOnlyCache: Can't write to a readonly object " + key.EntityOrRoleName); } @@ -56,15 +56,15 @@ public bool Put(CacheKey key, object value, long timestamp, object version, ICom if (minimalPut && cache.Get(key) != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("item already cached: " + key); + log.Debug("item already cached: {0}", key); } return false; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Caching: " + key); + log.Debug("Caching: {0}", key); } cache.Put(key, value); return true; @@ -75,7 +75,7 @@ public bool Put(CacheKey key, object value, long timestamp, object version, ICom /// public void Release(CacheKey key, ISoftLock @lock) { - log.Error("Application attempted to edit read only item: " + key); + log.Error("Application attempted to edit read only item: {0}", key); } public void Clear() @@ -96,7 +96,7 @@ public void Destroy() } catch (Exception e) { - log.Warn("Could not destroy cache", e); + log.Warn(e, "Could not destroy cache"); } } @@ -105,7 +105,7 @@ public void Destroy() /// public bool AfterUpdate(CacheKey key, object value, object version, ISoftLock @lock) { - log.Error("Application attempted to edit read only item: " + key); + log.Error("Application attempted to edit read only item: {0}", key); throw new InvalidOperationException("ReadOnlyCache: Can't write to a readonly object " + key.EntityOrRoleName); } @@ -139,7 +139,7 @@ public bool Insert(CacheKey key, object value, object currentVersion) /// public bool Update(CacheKey key, object value, object currentVersion, object previousVersion) { - log.Error("Application attempted to edit read only item: " + key); + log.Error("Application attempted to edit read only item: {0}", key); throw new InvalidOperationException("ReadOnlyCache: Can't write to a readonly object " + key.EntityOrRoleName); } } diff --git a/src/NHibernate/Cache/ReadWriteCache.cs b/src/NHibernate/Cache/ReadWriteCache.cs index 7ab8b32624d..98da04caa17 100644 --- a/src/NHibernate/Cache/ReadWriteCache.cs +++ b/src/NHibernate/Cache/ReadWriteCache.cs @@ -30,7 +30,7 @@ public interface ILockable bool IsPuttable(long txTimestamp, object newVersion, IComparer comparator); } - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ReadWriteCache)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ReadWriteCache)); private readonly object _lockObject = new object(); private ICache cache; @@ -90,9 +90,9 @@ public object Get(CacheKey key, long txTimestamp) { lock (_lockObject) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cache lookup: " + key); + log.Debug("Cache lookup: {0}", key); } // commented out in H3.1 @@ -106,24 +106,24 @@ public object Get(CacheKey key, long txTimestamp) if (gettable) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cache hit: " + key); + log.Debug("Cache hit: {0}", key); } return ((CachedItem) lockable).Value; } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (lockable == null) { - log.Debug("Cache miss: " + key); + log.Debug("Cache miss: {0}", key); } else { - log.Debug("Cached item was locked: " + key); + log.Debug("Cached item was locked: {0}", key); } } return null; @@ -147,9 +147,9 @@ public ISoftLock Lock(CacheKey key, object version) { lock (_lockObject) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Invalidating: " + key); + log.Debug("Invalidating: {0}", key); } try @@ -189,9 +189,9 @@ public bool Put(CacheKey key, object value, long txTimestamp, object version, IC lock (_lockObject) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Caching: " + key); + log.Debug("Caching: {0}", key); } try @@ -206,23 +206,23 @@ public bool Put(CacheKey key, object value, long txTimestamp, object version, IC if (puttable) { cache.Put(key, new CachedItem(value, cache.NextTimestamp(), version)); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cached: " + key); + log.Debug("Cached: {0}", key); } return true; } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (lockable.IsLock) { - log.Debug("Item was locked: " + key); + log.Debug("Item was locked: {0}", key); } else { - log.Debug("Item was already cached: " + key); + log.Debug("Item was already cached: {0}", key); } } return false; @@ -249,9 +249,9 @@ public void Release(CacheKey key, ISoftLock clientLock) { lock (_lockObject) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Releasing: " + key); + log.Debug("Releasing: {0}", key); } try @@ -277,7 +277,7 @@ public void Release(CacheKey key, ISoftLock clientLock) internal void HandleLockExpiry(object key) { - log.Warn("An item was expired by the cache while it was locked (increase your cache timeout): " + key); + log.Warn("An item was expired by the cache while it was locked (increase your cache timeout): {0}", key); long ts = cache.NextTimestamp() + cache.Timeout; // create new lock that times out immediately CacheLock @lock = new CacheLock(ts, NextLockId(), null); @@ -303,7 +303,7 @@ public void Destroy() } catch (Exception e) { - log.Warn("Could not destroy cache", e); + log.Warn(e, "Could not destroy cache"); } } @@ -315,9 +315,9 @@ public bool AfterUpdate(CacheKey key, object value, object version, ISoftLock cl { lock (_lockObject) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Updating: " + key); + log.Debug("Updating: {0}", key); } try @@ -338,9 +338,9 @@ public bool AfterUpdate(CacheKey key, object value, object version, ISoftLock cl { //recache the updated state cache.Put(key, new CachedItem(value, cache.NextTimestamp(), version)); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Updated: " + key); + log.Debug("Updated: {0}", key); } } return true; @@ -362,9 +362,9 @@ public bool AfterInsert(CacheKey key, object value, object version) { lock (_lockObject) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting: " + key); + log.Debug("Inserting: {0}", key); } try @@ -375,9 +375,9 @@ public bool AfterInsert(CacheKey key, object value, object version) if (lockable == null) { cache.Put(key, new CachedItem(value, cache.NextTimestamp(), version)); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserted: " + key); + log.Debug("Inserted: {0}", key); } return true; } @@ -422,4 +422,4 @@ private bool IsUnlockable(ISoftLock clientLock, ILockable myLock) ((CacheLock) clientLock).Id == ((CacheLock) myLock).Id; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cache/StandardQueryCache.cs b/src/NHibernate/Cache/StandardQueryCache.cs index 6278d938ae4..cce2de498d0 100644 --- a/src/NHibernate/Cache/StandardQueryCache.cs +++ b/src/NHibernate/Cache/StandardQueryCache.cs @@ -17,7 +17,7 @@ namespace NHibernate.Cache /// public partial class StandardQueryCache : IQueryCache { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof (StandardQueryCache)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof (StandardQueryCache)); private readonly ICache _queryCache; private readonly string _regionName; private readonly UpdateTimestampsCache _updateTimestampsCache; @@ -31,7 +31,7 @@ public StandardQueryCache(Settings settings, IDictionary props, if (!string.IsNullOrEmpty(prefix)) regionName = prefix + '.' + regionName; - Log.Info("starting query cache at region: " + regionName); + Log.Info("starting query cache at region: {0}", regionName); _queryCache = settings.CacheProvider.BuildCache(regionName, props); _updateTimestampsCache = updateTimestampsCache; @@ -62,8 +62,8 @@ public bool Put(QueryKey key, ICacheAssembler[] returnTypes, IList result, bool long ts = session.Timestamp; - if (Log.IsDebugEnabled) - Log.DebugFormat("caching query results in region: '{0}'; {1}", _regionName, key); + if (Log.IsDebugEnabled()) + Log.Debug("caching query results in region: '{0}'; {1}", _regionName, key); IList cacheable = new List(result.Count + 1) {ts}; for (int i = 0; i < result.Count; i++) @@ -85,28 +85,28 @@ public bool Put(QueryKey key, ICacheAssembler[] returnTypes, IList result, bool public IList Get(QueryKey key, ICacheAssembler[] returnTypes, bool isNaturalKeyLookup, ISet spaces, ISessionImplementor session) { - if (Log.IsDebugEnabled) - Log.DebugFormat("checking cached query results in region: '{0}'; {1}", _regionName, key); + if (Log.IsDebugEnabled()) + Log.Debug("checking cached query results in region: '{0}'; {1}", _regionName, key); var cacheable = (IList)_queryCache.Get(key); if (cacheable == null) { - Log.DebugFormat("query results were not found in cache: {0}", key); + Log.Debug("query results were not found in cache: {0}", key); return null; } var timestamp = (long)cacheable[0]; - if (Log.IsDebugEnabled) - Log.DebugFormat("Checking query spaces for up-to-dateness [{0}]", StringHelper.CollectionToString(spaces)); + if (Log.IsDebugEnabled()) + Log.Debug("Checking query spaces for up-to-dateness [{0}]", StringHelper.CollectionToString(spaces)); if (!isNaturalKeyLookup && !IsUpToDate(spaces, timestamp)) { - Log.DebugFormat("cached query results were not up to date for: {0}", key); + Log.Debug("cached query results were not up to date for: {0}", key); return null; } - Log.DebugFormat("returning cached query results for: {0}", key); + Log.Debug("returning cached query results for: {0}", key); for (int i = 1; i < cacheable.Count; i++) { if (returnTypes.Length == 1) @@ -160,7 +160,7 @@ public void Destroy() } catch (Exception e) { - Log.Warn("could not destroy query cache: " + _regionName, e); + Log.Warn(e, "could not destroy query cache: {0}", _regionName); } } @@ -171,4 +171,4 @@ protected virtual bool IsUpToDate(ISet spaces, long timestamp) return _updateTimestampsCache.IsUpToDate(spaces, timestamp); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cache/UpdateTimestampsCache.cs b/src/NHibernate/Cache/UpdateTimestampsCache.cs index 10c49e2b498..5af4365299c 100644 --- a/src/NHibernate/Cache/UpdateTimestampsCache.cs +++ b/src/NHibernate/Cache/UpdateTimestampsCache.cs @@ -15,7 +15,7 @@ namespace NHibernate.Cache /// public partial class UpdateTimestampsCache { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(UpdateTimestampsCache)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(UpdateTimestampsCache)); private ICache updateTimestamps; private readonly string regionName = typeof(UpdateTimestampsCache).Name; @@ -29,7 +29,7 @@ public UpdateTimestampsCache(Settings settings, IDictionary prop { string prefix = settings.CacheRegionPrefix; regionName = prefix == null ? regionName : prefix + '.' + regionName; - log.Info("starting update timestamps cache at region: " + regionName); + log.Info("starting update timestamps cache at region: {0}", regionName); updateTimestamps = settings.CacheProvider.BuildCache(regionName, props); } @@ -54,7 +54,7 @@ public void Invalidate(object[] spaces) //TODO: if lock.getTimestamp().equals(ts) for (int i = 0; i < spaces.Length; i++) { - log.Debug(string.Format("Invalidating space [{0}]", spaces[i])); + log.Debug("Invalidating space [{0}]", spaces[i]); updateTimestamps.Put(spaces[i], ts); } } @@ -103,8 +103,8 @@ public void Destroy() } catch (Exception e) { - log.Warn("could not destroy UpdateTimestamps cache", e); + log.Warn(e, "could not destroy UpdateTimestamps cache"); } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/Configuration.cs b/src/NHibernate/Cfg/Configuration.cs index b209b6d201e..1ecdca22e22 100644 --- a/src/NHibernate/Cfg/Configuration.cs +++ b/src/NHibernate/Cfg/Configuration.cs @@ -75,7 +75,7 @@ public class Configuration : ISerializable protected IDictionary tableNameBinding; protected IDictionary columnNameBindingPerTable; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(Configuration)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Configuration)); protected internal SettingsFactory settingsFactory; @@ -337,9 +337,9 @@ public Configuration AddFile(FileInfo xmlFile) private static void LogAndThrow(Exception exception) { - if (log.IsErrorEnabled) + if (log.IsErrorEnabled()) { - log.Error(exception.Message, exception); + log.Error(exception, exception.Message); } throw exception; @@ -352,7 +352,7 @@ private static void LogAndThrow(Exception exception) /// This configuration object. public Configuration AddXmlFile(string xmlFile) { - log.Info("Mapping file: " + xmlFile); + log.Info("Mapping file: {0}", xmlFile); XmlTextReader textReader = null; try { @@ -391,9 +391,9 @@ public Configuration AddXml(string xml) /// This configuration object. public Configuration AddXml(string xml, string name) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Mapping XML:\n" + xml); + log.Debug("Mapping XML:\n{0}", xml); } XmlTextReader reader = null; try @@ -466,9 +466,9 @@ public Configuration AddDocument(XmlDocument doc) /// This configuration object. public Configuration AddDocument(XmlDocument doc, string name) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Mapping XML:\n" + doc.OuterXml); + log.Debug("Mapping XML:\n{0}", doc.OuterXml); } try @@ -663,7 +663,7 @@ public Configuration AddInputStream(Stream xmlInputStream, string name) public Configuration AddResource(string path, Assembly assembly) { string debugName = path; - log.Info("Mapping resource: " + debugName); + log.Info("Mapping resource: {0}", debugName); Stream rsrc = assembly.GetManifestResourceStream(path); if (rsrc == null) { @@ -740,7 +740,7 @@ public Configuration AddClass(System.Type persistentClass) /// public Configuration AddAssembly(string assemblyName) { - log.Info("Searching for mapped documents in assembly: " + assemblyName); + log.Info("Searching for mapped documents in assembly: {0}", assemblyName); Assembly assembly = null; try @@ -765,7 +765,7 @@ public Configuration AddAssembly(Assembly assembly) IList resourceNames = GetAllHbmXmlResourceNames(assembly); if (resourceNames.Count == 0) { - log.Warn("No mapped documents found in assembly: " + assembly.FullName); + log.Warn("No mapped documents found in assembly: {0}", assembly.FullName); } foreach (var name in resourceNames) { @@ -1009,7 +1009,7 @@ private void ValidateFilterDefs() // if you are going to remove this exception at least add a log.Error // because the usage of filter-def, outside its scope, may cause unexpected behaviour // during queries. - log.ErrorFormat("filter-def for filter named '{0}' was never used to filter classes nor collections.\r\nThis may result in unexpected behavior during queries", filterName); + log.Error("filter-def for filter named '{0}' was never used to filter classes nor collections.\r\nThis may result in unexpected behavior during queries", filterName); } } } @@ -1159,9 +1159,9 @@ private void SecondPassCompileForeignKeys(Table table, ISet done) string.Format("An association from the table {0} does not specify the referenced entity", fk.Table.Name)); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("resolving reference to class: " + referencedEntityName); + log.Debug("resolving reference to class: {0}", referencedEntityName); } PersistentClass referencedClass; @@ -1403,9 +1403,9 @@ private void AddProperties(ISessionFactoryConfiguration factoryConfiguration) { foreach (var kvp in factoryConfiguration.Properties) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(kvp.Key + "=" + kvp.Value); + log.Debug("{0}={1}", kvp.Key, kvp.Value); } properties[kvp.Key] = kvp.Value; } @@ -1542,7 +1542,7 @@ public Configuration Configure(XmlReader textReader) } catch (Exception e) { - log.Error("Problem parsing configuration", e); + log.Error(e, "Problem parsing configuration"); throw; } } @@ -1567,17 +1567,17 @@ protected Configuration DoConfigure(ISessionFactoryConfiguration factoryConfigur } if (!string.IsNullOrEmpty(mc.Resource) && !string.IsNullOrEmpty(mc.Assembly)) { - log.Debug(factoryConfiguration.Name + "<-" + mc.Resource + " in " + mc.Assembly); + log.Debug("{0}<-{1} in {2}", factoryConfiguration.Name, mc.Resource, mc.Assembly); AddResource(mc.Resource, Assembly.Load(mc.Assembly)); } else if (!string.IsNullOrEmpty(mc.Assembly)) { - log.Debug(factoryConfiguration.Name + "<-" + mc.Assembly); + log.Debug("{0}<-{1}", factoryConfiguration.Name, mc.Assembly); AddAssembly(mc.Assembly); } else if (!string.IsNullOrEmpty(mc.File)) { - log.Debug(factoryConfiguration.Name + "<-" + mc.File); + log.Debug("{0}<-{1}", factoryConfiguration.Name, mc.File); AddFile(mc.File); } } @@ -1613,21 +1613,21 @@ protected Configuration DoConfigure(ISessionFactoryConfiguration factoryConfigur { listenerClasses[i] = ec.Listeners[i].Class; } - log.Debug("Event listeners: " + ec.Type + "=" + StringHelper.ToString(listenerClasses)); + log.Debug("Event listeners: {0}={1}", ec.Type, StringHelper.ToString(listenerClasses)); SetListeners(ec.Type, listenerClasses); } // Listeners foreach (var lc in factoryConfiguration.Listeners) { - log.Debug("Event listener: " + lc.Type + "=" + lc.Class); + log.Debug("Event listener: {0}={1}", lc.Type, lc.Class); SetListeners(lc.Type, new[] { lc.Class }); } if (!string.IsNullOrEmpty(factoryConfiguration.Name)) { - log.Info("Configured SessionFactory: " + factoryConfiguration.Name); + log.Info("Configured SessionFactory: {0}", factoryConfiguration.Name); } - log.Debug("properties: " + properties); + log.Debug("properties: {0}", properties); return this; } @@ -2063,7 +2063,7 @@ private void ClearListeners(ListenerType type) eventListeners.PostCollectionUpdateEventListeners = new IPostCollectionUpdateEventListener[] { }; break; default: - log.Warn("Unrecognized listener type [" + type + "]"); + log.Warn("Unrecognized listener type [{0}]", type); break; } } @@ -2186,7 +2186,7 @@ public void SetListeners(ListenerType type, object[] listeners) eventListeners.PostCollectionUpdateEventListeners = (IPostCollectionUpdateEventListener[])listeners; break; default: - log.Warn("Unrecognized listener type [" + type + "]"); + log.Warn("Unrecognized listener type [{0}]", type); break; } } @@ -2303,7 +2303,7 @@ public void AppendListeners(ListenerType type, object[] listeners) eventListeners.PostCollectionUpdateEventListeners = AppendListeners(eventListeners.PostCollectionUpdateEventListeners, (IPostCollectionUpdateEventListener[])listeners); break; default: - log.Warn("Unrecognized listener type [" + type + "]"); + log.Warn("Unrecognized listener type [{0}]", type); break; } } diff --git a/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs b/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs index ab67d68cc75..83c34a89ea1 100644 --- a/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs +++ b/src/NHibernate/Cfg/ConfigurationSchema/HibernateConfiguration.cs @@ -21,7 +21,7 @@ public enum BytecodeProviderType /// public class HibernateConfiguration : IHibernateConfiguration { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(HibernateConfiguration)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(HibernateConfiguration)); /// /// Initializes a new instance of the class. @@ -105,8 +105,8 @@ private void ParseByteCodeProvider(XPathNavigator navigator, bool fromAppConfig) private static void LogWarnIgnoredProperty(string propName) { - if (log.IsWarnEnabled) - log.Warn(string.Format("{0} property is ignored out of application configuration file.", propName)); + if (log.IsWarnEnabled()) + log.Warn("{0} property is ignored out of application configuration file.", propName); } private void ParseReflectionOptimizer(XPathNavigator navigator, bool fromAppConfig) diff --git a/src/NHibernate/Cfg/ConfigurationSchema/SessionFactoryConfiguration.cs b/src/NHibernate/Cfg/ConfigurationSchema/SessionFactoryConfiguration.cs index 4d5854231c3..3e96946feca 100644 --- a/src/NHibernate/Cfg/ConfigurationSchema/SessionFactoryConfiguration.cs +++ b/src/NHibernate/Cfg/ConfigurationSchema/SessionFactoryConfiguration.cs @@ -8,7 +8,7 @@ namespace NHibernate.Cfg.ConfigurationSchema /// public class SessionFactoryConfiguration : SessionFactoryConfigurationBase { - //private static readonly ILogger log = LoggerProvider.LoggerFor(typeof(SessionFactoryConfiguration)); + //private static readonly ILogger log = NHibernateLogger.For(typeof(SessionFactoryConfiguration)); internal SessionFactoryConfiguration(XPathNavigator hbConfigurationSection) { diff --git a/src/NHibernate/Cfg/Environment.cs b/src/NHibernate/Cfg/Environment.cs index 2003f695914..ce55bead051 100644 --- a/src/NHibernate/Cfg/Environment.cs +++ b/src/NHibernate/Cfg/Environment.cs @@ -275,7 +275,7 @@ public static string Version private static IBytecodeProvider BytecodeProviderInstance; private static bool EnableReflectionOptimizer; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(Environment)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Environment)); /// /// Issue warnings to user when any obsolete property names are used. @@ -287,9 +287,9 @@ public static void VerifyProperties(IDictionary props) { } static Environment() { // Computing the version string is a bit expensive, so do it only if logging is enabled. - if (log.IsInfoEnabled) + if (log.IsInfoEnabled()) { - log.Info("NHibernate " + Version); + log.Info("NHibernate {0}", Version); } GlobalProperties = new Dictionary(); @@ -312,7 +312,7 @@ private static void LoadGlobalPropertiesFromAppConfig() if (config == null) { - log.Info(string.Format("{0} section not found in application configuration file", CfgXmlHelper.CfgSectionName)); + log.Info("{0} section not found in application configuration file", CfgXmlHelper.CfgSectionName); return; } @@ -320,9 +320,8 @@ private static void LoadGlobalPropertiesFromAppConfig() if (nhConfig == null) { log.Info( - string.Format( "{0} section handler, in application configuration file, is not IHibernateConfiguration, section ignored", - CfgXmlHelper.CfgSectionName)); + CfgXmlHelper.CfgSectionName); return; } @@ -410,7 +409,7 @@ public static IBytecodeProvider BuildBytecodeProvider(IDictionary classes; private readonly IDictionary collections; @@ -247,7 +247,7 @@ public void AddImport(string className, string rename) { if (existing.Equals(className)) { - log.Info("duplicate import: " + className + "->" + rename); + log.Info("duplicate import: {0}->{1}", className, rename); } else { @@ -509,7 +509,7 @@ public void AddTypeDef(string typeName, string typeClass, IDictionary properties) @@ -48,7 +48,7 @@ public Settings BuildSettings(IDictionary properties) } catch (HibernateException he) { - log.Warn("No dialect set - using GenericDialect: " + he.Message); + log.Warn(he, "No dialect set - using GenericDialect: {0}", he.Message); dialect = new GenericDialect(); } settings.Dialect = dialect; @@ -72,13 +72,13 @@ public Settings BuildSettings(IDictionary properties) #endregion bool comments = PropertiesHelper.GetBoolean(Environment.UseSqlComments, properties); - log.Info("Generate SQL with comments: " + EnabledDisabled(comments)); + log.Info("Generate SQL with comments: {0}", EnabledDisabled(comments)); settings.IsCommentsEnabled = comments; int maxFetchDepth = PropertiesHelper.GetInt32(Environment.MaxFetchDepth, properties, -1); if (maxFetchDepth != -1) { - log.Info("Maximum outer join fetch depth: " + maxFetchDepth); + log.Info("Maximum outer join fetch depth: {0}", maxFetchDepth); } IConnectionProvider connectionProvider = ConnectionProviderFactory.NewConnectionProvider(properties); @@ -88,10 +88,10 @@ public Settings BuildSettings(IDictionary properties) // Not ported: useGetGeneratedKeys, useScrollableResultSets bool useMinimalPuts = PropertiesHelper.GetBoolean(Environment.UseMinimalPuts, properties, false); - log.Info("Optimize cache for minimal puts: " + useMinimalPuts); + log.Info("Optimize cache for minimal puts: {0}", useMinimalPuts); string releaseModeName = PropertiesHelper.GetString(Environment.ReleaseConnections, properties, "auto"); - log.Info("Connection release mode: " + releaseModeName); + log.Info("Connection release mode: {0}", releaseModeName); ConnectionReleaseMode releaseMode; if ("auto".Equals(releaseModeName)) { @@ -106,14 +106,14 @@ public Settings BuildSettings(IDictionary properties) string defaultSchema = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null); string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null); if (defaultSchema != null) - log.Info("Default schema: " + defaultSchema); + log.Info("Default schema: {0}", defaultSchema); if (defaultCatalog != null) - log.Info("Default catalog: " + defaultCatalog); + log.Info("Default catalog: {0}", defaultCatalog); settings.DefaultSchemaName = defaultSchema; settings.DefaultCatalogName = defaultCatalog; int batchFetchSize = PropertiesHelper.GetInt32(Environment.DefaultBatchFetchSize, properties, 1); - log.Info("Default batch fetch size: " + batchFetchSize); + log.Info("Default batch fetch size: {0}", batchFetchSize); settings.DefaultBatchFetchSize = batchFetchSize; //Statistics and logging: @@ -126,11 +126,11 @@ public Settings BuildSettings(IDictionary properties) bool formatSql = PropertiesHelper.GetBoolean(Environment.FormatSql, properties); bool useStatistics = PropertiesHelper.GetBoolean(Environment.GenerateStatistics, properties); - log.Info("Statistics: " + EnabledDisabled(useStatistics)); + log.Info("Statistics: {0}", EnabledDisabled(useStatistics)); settings.IsStatisticsEnabled = useStatistics; bool useIdentifierRollback = PropertiesHelper.GetBoolean(Environment.UseIdentifierRollBack, properties); - log.Info("Deleted entity synthetic identifier rollback: " + EnabledDisabled(useIdentifierRollback)); + log.Info("Deleted entity synthetic identifier rollback: {0}", EnabledDisabled(useIdentifierRollback)); settings.IsIdentifierRollbackEnabled = useIdentifierRollback; // queries: @@ -141,9 +141,9 @@ public Settings BuildSettings(IDictionary properties) IDictionary querySubstitutions = PropertiesHelper.ToDictionary(Environment.QuerySubstitutions, " ,=;:\n\t\r\f", properties); - if (log.IsInfoEnabled) + if (log.IsInfoEnabled()) { - log.Info("Query language substitutions: " + CollectionPrinter.ToString((IDictionary) querySubstitutions)); + log.Info("Query language substitutions: {0}", CollectionPrinter.ToString((IDictionary) querySubstitutions)); } #region Hbm2DDL @@ -206,14 +206,14 @@ public Settings BuildSettings(IDictionary properties) string cacheRegionPrefix = PropertiesHelper.GetString(Environment.CacheRegionPrefix, properties, null); if (string.IsNullOrEmpty(cacheRegionPrefix)) cacheRegionPrefix = null; - if (cacheRegionPrefix != null) log.Info("Cache region prefix: " + cacheRegionPrefix); + if (cacheRegionPrefix != null) log.Info("Cache region prefix: {0}", cacheRegionPrefix); if (useQueryCache) { string queryCacheFactoryClassName = PropertiesHelper.GetString(Environment.QueryCacheFactory, properties, typeof (StandardQueryCacheFactory).FullName); - log.Info("query cache factory: " + queryCacheFactoryClassName); + log.Info("query cache factory: {0}", queryCacheFactoryClassName); try { settings.QueryCacheFactory = @@ -232,19 +232,19 @@ public Settings BuildSettings(IDictionary properties) settings.AdoBatchSize = PropertiesHelper.GetInt32(Environment.BatchSize, properties, 0); bool orderInserts = PropertiesHelper.GetBoolean(Environment.OrderInserts, properties, (settings.AdoBatchSize > 0)); - log.Info("Order SQL inserts for batching: " + EnabledDisabled(orderInserts)); + log.Info("Order SQL inserts for batching: {0}", EnabledDisabled(orderInserts)); settings.IsOrderInsertsEnabled = orderInserts; bool orderUpdates = PropertiesHelper.GetBoolean(Environment.OrderUpdates, properties, false); - log.Info("Order SQL updates for batching: " + EnabledDisabled(orderUpdates)); + log.Info("Order SQL updates for batching: {0}", EnabledDisabled(orderUpdates)); settings.IsOrderUpdatesEnabled = orderUpdates; bool wrapResultSets = PropertiesHelper.GetBoolean(Environment.WrapResultSets, properties, false); - log.Debug("Wrap result sets: " + EnabledDisabled(wrapResultSets)); + log.Debug("Wrap result sets: {0}", EnabledDisabled(wrapResultSets)); settings.IsWrapResultSetsEnabled = wrapResultSets; bool batchVersionedData = PropertiesHelper.GetBoolean(Environment.BatchVersionedData, properties, false); - log.Debug("Batch versioned data: " + EnabledDisabled(batchVersionedData)); + log.Debug("Batch versioned data: {0}", EnabledDisabled(batchVersionedData)); settings.IsBatchVersionedDataEnabled = batchVersionedData; settings.BatcherFactory = CreateBatcherFactory(properties, settings.AdoBatchSize, connectionProvider); @@ -256,11 +256,11 @@ public Settings BuildSettings(IDictionary properties) try { isolation = (IsolationLevel) Enum.Parse(typeof (IsolationLevel), isolationString); - log.Info("Using Isolation Level: " + isolation); + log.Info("Using Isolation Level: {0}", isolation); } catch (ArgumentException ae) { - log.Error("error configuring IsolationLevel " + isolationString, ae); + log.Error(ae, "error configuring IsolationLevel {0}", isolationString); throw new HibernateException( "The isolation level of " + isolationString + " is not a valid IsolationLevel. Please " + "use one of the Member Names from the IsolationLevel.", ae); @@ -269,7 +269,7 @@ public Settings BuildSettings(IDictionary properties) //NH-3619 FlushMode defaultFlushMode = (FlushMode) Enum.Parse(typeof(FlushMode), PropertiesHelper.GetString(Environment.DefaultFlushMode, properties, FlushMode.Auto.ToString()), false); - log.Info("Default flush mode: " + defaultFlushMode); + log.Info("Default flush mode: {0}", defaultFlushMode); settings.DefaultFlushMode = defaultFlushMode; #pragma warning disable CS0618 // Type or member is obsolete @@ -279,7 +279,7 @@ public Settings BuildSettings(IDictionary properties) #pragma warning restore CS0618 // Type or member is obsolete bool namedQueryChecking = PropertiesHelper.GetBoolean(Environment.QueryStartupChecking, properties, true); - log.Info("Named query checking : " + EnabledDisabled(namedQueryChecking)); + log.Info("Named query checking : {0}", EnabledDisabled(namedQueryChecking)); settings.IsNamedQueryStartupCheckingEnabled = namedQueryChecking; // Not ported - settings.StatementFetchSize = statementFetchSize; @@ -329,7 +329,7 @@ private static IBatcherFactory CreateBatcherFactory(IDictionary { tBatcher = ReflectHelper.ClassForName(batcherClass); } - log.Info("Batcher factory: " + tBatcher.AssemblyQualifiedName); + log.Info("Batcher factory: {0}", tBatcher.AssemblyQualifiedName); try { return (IBatcherFactory) Environment.BytecodeProvider.ObjectsFactory.CreateInstance(tBatcher); @@ -348,7 +348,7 @@ private static string EnabledDisabled(bool value) private static ICacheProvider CreateCacheProvider(IDictionary properties) { string cacheClassName = PropertiesHelper.GetString(Environment.CacheProvider, properties, DefaultCacheProvider); - log.Info("cache provider: " + cacheClassName); + log.Info("cache provider: {0}", cacheClassName); try { return @@ -366,7 +366,7 @@ private static IQueryTranslatorFactory CreateQueryTranslatorFactory(IDictionary< { string className = PropertiesHelper.GetString( Environment.QueryTranslator, properties, typeof(Hql.Ast.ANTLR.ASTQueryTranslatorFactory).FullName); - log.Info("Query translator: " + className); + log.Info("Query translator: {0}", className); try { return @@ -383,7 +383,7 @@ private static System.Type CreateLinqQueryProviderType(IDictionary EmptyMeta = new CollectionHelper.EmptyMapClass(); diff --git a/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs index 22b8a0eedff..4efd92ff782 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/ClassBinder.cs @@ -179,7 +179,7 @@ private void BindJoin(HbmJoin joinMapping, Join join, IDictionary {1}", persistentClass.EntityName, join.Table.Name); + log.Info("Mapping class join: {0} -> {1}", persistentClass.EntityName, @join.Table.Name); // KEY SimpleValue key; diff --git a/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs index 7353478d59d..c5800e7abb4 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/CollectionBinder.cs @@ -201,7 +201,7 @@ private void BindCollection(ICollectionPropertiesMapping collectionMapping, Mapp // TODO NH : add schema-action to the xsd model.CollectionTable = mappings.AddTable(schema, catalog, tableName, collectionMapping.Subselect, false, "all"); - log.InfoFormat("Mapping collection: {0} -> {1}", model.Role, model.CollectionTable.Name); + log.Info("Mapping collection: {0} -> {1}", model.Role, model.CollectionTable.Name); } //SORT @@ -482,27 +482,27 @@ private void HandleCustomSQL(ICollectionSqlsMapping collection, Mapping.Collecti private static void PreCollectionSecondPass(Mapping.Collection collection) { - if (log.IsDebugEnabled) - log.Debug("Second pass for collection: " + collection.Role); + if (log.IsDebugEnabled()) + log.Debug("Second pass for collection: {0}", collection.Role); } private static void PostCollectionSecondPass(Mapping.Collection collection) { collection.CreateAllKeys(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - string msg = "Mapped collection key: " + string.Join(",", collection.Key.ColumnIterator.Select(c => c.Text).ToArray()); + string info = ""; if (collection.IsIndexed) - msg += ", index: " + string.Join(",", ((IndexedCollection)collection).Index.ColumnIterator.Select(c => c.Text).ToArray()); + info += ", index: " + string.Join(",", ((IndexedCollection)collection).Index.ColumnIterator.Select(c => c.Text).ToArray()); if (collection.IsOneToMany) - msg += ", one-to-many: " + collection.Element.Type.Name; + info += ", one-to-many: " + collection.Element.Type.Name; else { - msg += ", element: " + string.Join(",", collection.Element.ColumnIterator.Select(c => c.Text).ToArray()); - msg += ", type: " + collection.Element.Type.Name; + info += ", element: " + string.Join(",", collection.Element.ColumnIterator.Select(c => c.Text).ToArray()); + info += ", type: " + collection.Element.Type.Name; } - log.Debug(msg); + log.Debug("Mapped collection key: {0}{1}", string.Join(",", collection.Key.ColumnIterator.Select(c => c.Text).ToArray()), info); } } @@ -753,8 +753,8 @@ private void BindCollectionSecondPass(ICollectionPropertiesMapping collectionMap } } - if (log.IsInfoEnabled) - log.Info("mapping collection: " + model.Role + " -> " + model.CollectionTable.Name); + if (log.IsInfoEnabled()) + log.Info("mapping collection: {0} -> {1}", model.Role, model.CollectionTable.Name); } //CHECK diff --git a/src/NHibernate/Cfg/XmlHbmBinding/FilterDefinitionFactory.cs b/src/NHibernate/Cfg/XmlHbmBinding/FilterDefinitionFactory.cs index 47de93a5e2a..1765f46e12a 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/FilterDefinitionFactory.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/FilterDefinitionFactory.cs @@ -8,16 +8,16 @@ namespace NHibernate.Cfg.XmlHbmBinding { public class FilterDefinitionFactory { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (FilterDefinitionFactory)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (FilterDefinitionFactory)); public static FilterDefinition CreateFilterDefinition(HbmFilterDef filterDefSchema) { - log.DebugFormat("Parsing filter-def [{0}]", filterDefSchema.name); + log.Debug("Parsing filter-def [{0}]", filterDefSchema.name); string defaultCondition = filterDefSchema.GetDefaultCondition(); IDictionary parameterTypes = GetFilterParameterTypes(filterDefSchema); - log.DebugFormat("Parsed filter-def [{0}]", filterDefSchema.name); + log.Debug("Parsed filter-def [{0}]", filterDefSchema.name); return new FilterDefinition(filterDefSchema.name, defaultCondition, parameterTypes, filterDefSchema.usemanytoone); } @@ -28,11 +28,11 @@ private static IDictionary GetFilterParameterTypes(HbmFilterDef f foreach (HbmFilterParam paramSchema in filterDefSchema.ListParameters()) { - log.DebugFormat("Adding filter parameter : {0} -> {1}", paramSchema.name, paramSchema.type); + log.Debug("Adding filter parameter : {0} -> {1}", paramSchema.name, paramSchema.type); IType heuristicType = TypeFactory.HeuristicType(paramSchema.type); - log.DebugFormat("Parameter heuristic type : {0}", heuristicType); + log.Debug("Parameter heuristic type : {0}", heuristicType); parameterTypes.Add(paramSchema.name, heuristicType); } diff --git a/src/NHibernate/Cfg/XmlHbmBinding/FiltersBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/FiltersBinder.cs index cb5a22ad178..0c1308e7311 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/FiltersBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/FiltersBinder.cs @@ -49,9 +49,9 @@ public void Bind(IEnumerable filters, Action addFilte mappings.ExpectedFilterDefinition(filterable, name, condition); - log.Debug(string.Format("Applying filter [{0}] as [{1}]", name, condition)); + log.Debug("Applying filter [{0}] as [{1}]", name, condition); addFilterDelegate(name, condition); } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/XmlHbmBinding/JoinedSubclassBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/JoinedSubclassBinder.cs index b4b8a4c3428..bccabf5e937 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/JoinedSubclassBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/JoinedSubclassBinder.cs @@ -41,7 +41,7 @@ public void HandleJoinedSubclass(PersistentClass model, HbmJoinedSubclass joined Table mytable = mappings.AddTable(schema, catalog, GetClassTableName(subclass, joinedSubclassMapping.table), joinedSubclassMapping.Subselect, false, joinedSubclassMapping.schemaaction); ((ITableOwner)subclass).Table = mytable; - log.InfoFormat("Mapping joined-subclass: {0} -> {1}", subclass.EntityName, subclass.Table.Name); + log.Info("Mapping joined-subclass: {0} -> {1}", subclass.EntityName, subclass.Table.Name); // KEY BindKey(subclass, joinedSubclassMapping.key, mytable); diff --git a/src/NHibernate/Cfg/XmlHbmBinding/MappingLogExtensions.cs b/src/NHibernate/Cfg/XmlHbmBinding/MappingLogExtensions.cs index d40f64b3a30..d212e89e5ed 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/MappingLogExtensions.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/MappingLogExtensions.cs @@ -8,9 +8,9 @@ namespace NHibernate.Cfg.XmlHbmBinding { public static class MappingLogExtensions { - public static void LogMapped(this Property property, IInternalLogger log) + public static void LogMapped(this Property property, INHibernateLogger log) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { var msg = "Mapped property: " + property.Name; var columns = string.Join(",", property.Value.ColumnIterator.Select(c => c.Text).ToArray()); diff --git a/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs index a68eef4fbad..7dcd61b7c73 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs @@ -125,7 +125,7 @@ public void AddImports(HbmMapping mappingSchema) string fullClassName = FullQualifiedClassName(importSchema.@class, mappings); string rename = importSchema.rename ?? StringHelper.GetClassname(fullClassName); - log.DebugFormat("Import: {0} -> {1}", rename, fullClassName); + log.Debug("Import: {0} -> {1}", rename, fullClassName); mappings.AddImport(fullClassName, rename); } } diff --git a/src/NHibernate/Cfg/XmlHbmBinding/NamedQueryBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/NamedQueryBinder.cs index e93f1b1e3ba..b008b52d4f5 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/NamedQueryBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/NamedQueryBinder.cs @@ -17,7 +17,7 @@ public void AddQuery(HbmQuery querySchema) string queryName = querySchema.name; string queryText = querySchema.GetText(); - log.DebugFormat("Named query: {0} -> {1}", queryName, queryText); + log.Debug("Named query: {0} -> {1}", queryName, queryText); bool cacheable = querySchema.cacheable; string region = querySchema.cacheregion; diff --git a/src/NHibernate/Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs index 04316365db4..db6f6e06b37 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs @@ -52,7 +52,7 @@ public void AddSqlQuery(HbmSqlQuery querySchema) resultSetRef, synchronizedTables, cacheable, region, timeout, fetchSize, flushMode, cacheMode, readOnly, comment, parameterTypes, callable); - log.DebugFormat("Named SQL query: {0} -> {1}", queryName, namedQuery.QueryString); + log.Debug("Named SQL query: {0} -> {1}", queryName, namedQuery.QueryString); mappings.AddSQLQuery(queryName, namedQuery); }); } diff --git a/src/NHibernate/Cfg/XmlHbmBinding/RootClassBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/RootClassBinder.cs index 61092f74dac..d78c125a17e 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/RootClassBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/RootClassBinder.cs @@ -37,7 +37,7 @@ public void Bind(HbmClass classSchema, IDictionary inheri Table table = mappings.AddTable(schema, catalog, tableName, classSchema.Subselect, rootClass.IsAbstract.GetValueOrDefault(), classSchema.schemaaction); ((ITableOwner) rootClass).Table = table; - log.InfoFormat("Mapping class: {0} -> {1}", rootClass.EntityName, rootClass.Table.Name); + log.Info("Mapping class: {0} -> {1}", rootClass.EntityName, rootClass.Table.Name); rootClass.IsMutable = classSchema.mutable; rootClass.Where = classSchema.where ?? rootClass.Where; diff --git a/src/NHibernate/Cfg/XmlHbmBinding/SubclassBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/SubclassBinder.cs index 933ea74c6af..3aba499bf0d 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/SubclassBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/SubclassBinder.cs @@ -33,7 +33,7 @@ public void HandleSubclass(PersistentClass model, HbmSubclass subClassMapping, I if (subclass.EntityPersisterClass == null) subclass.RootClazz.EntityPersisterClass = typeof(SingleTableEntityPersister); - log.InfoFormat("Mapping subclass: {0} -> {1}", subclass.EntityName, subclass.Table.Name); + log.Info("Mapping subclass: {0} -> {1}", subclass.EntityName, subclass.Table.Name); // properties new PropertiesBinder(mappings, subclass, dialect).Bind(subClassMapping.Properties, inheritedMetas); diff --git a/src/NHibernate/Cfg/XmlHbmBinding/UnionSubclassBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/UnionSubclassBinder.cs index 6baaf223a07..0583594b08c 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/UnionSubclassBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/UnionSubclassBinder.cs @@ -44,7 +44,7 @@ public void HandleUnionSubclass(PersistentClass model, HbmUnionSubclass unionSub unionSubclass.IsAbstract.GetValueOrDefault(), unionSubclassMapping.Subselect, denormalizedSuperTable); ((ITableOwner)unionSubclass).Table = mytable; - log.InfoFormat("Mapping union-subclass: {0} -> {1}", unionSubclass.EntityName, unionSubclass.Table.Name); + log.Info("Mapping union-subclass: {0} -> {1}", unionSubclass.EntityName, unionSubclass.Table.Name); // properties new PropertiesBinder(mappings, unionSubclass, dialect).Bind(unionSubclassMapping.Properties, inheritedMetas); diff --git a/src/NHibernate/Collection/PersistentArrayHolder.cs b/src/NHibernate/Collection/PersistentArrayHolder.cs index 87a3173dbb5..60739da6e96 100644 --- a/src/NHibernate/Collection/PersistentArrayHolder.cs +++ b/src/NHibernate/Collection/PersistentArrayHolder.cs @@ -20,7 +20,7 @@ namespace NHibernate.Collection [DebuggerTypeProxy(typeof (CollectionProxy))] public partial class PersistentArrayHolder : AbstractPersistentCollection, ICollection { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (PersistentArrayHolder)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (PersistentArrayHolder)); private Array array; @@ -80,7 +80,7 @@ public override object GetSnapshot(ICollectionPersister persister) } catch (Exception e) { - log.Error("Array element type error", e); + log.Error(e, "Array element type error"); throw new HibernateException("Array element type error", e); } } diff --git a/src/NHibernate/Connection/ConnectionProvider.cs b/src/NHibernate/Connection/ConnectionProvider.cs index 902af83e99b..6a1882515b6 100644 --- a/src/NHibernate/Connection/ConnectionProvider.cs +++ b/src/NHibernate/Connection/ConnectionProvider.cs @@ -15,7 +15,7 @@ namespace NHibernate.Connection /// public abstract partial class ConnectionProvider : IConnectionProvider { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ConnectionProvider)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ConnectionProvider)); private string connString; private IDriver driver; diff --git a/src/NHibernate/Connection/ConnectionProviderFactory.cs b/src/NHibernate/Connection/ConnectionProviderFactory.cs index c831294c057..79116f8230f 100644 --- a/src/NHibernate/Connection/ConnectionProviderFactory.cs +++ b/src/NHibernate/Connection/ConnectionProviderFactory.cs @@ -11,7 +11,7 @@ namespace NHibernate.Connection /// public static class ConnectionProviderFactory { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ConnectionProviderFactory)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ConnectionProviderFactory)); // cannot be instantiated public static IConnectionProvider NewConnectionProvider(IDictionary settings) @@ -22,14 +22,14 @@ public static IConnectionProvider NewConnectionProvider(IDictionary public partial class DriverConnectionProvider : ConnectionProvider { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DriverConnectionProvider)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DriverConnectionProvider)); /// /// Closes and Disposes of the . diff --git a/src/NHibernate/Connection/UserSuppliedConnectionProvider.cs b/src/NHibernate/Connection/UserSuppliedConnectionProvider.cs index ffb8eac4abe..076b3b0b3ad 100644 --- a/src/NHibernate/Connection/UserSuppliedConnectionProvider.cs +++ b/src/NHibernate/Connection/UserSuppliedConnectionProvider.cs @@ -14,7 +14,7 @@ namespace NHibernate.Connection /// public partial class UserSuppliedConnectionProvider : ConnectionProvider { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(UserSuppliedConnectionProvider)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(UserSuppliedConnectionProvider)); /// /// Throws an if this method is called diff --git a/src/NHibernate/Context/ThreadLocalSessionContext.cs b/src/NHibernate/Context/ThreadLocalSessionContext.cs index b843bf2cfad..52735306949 100644 --- a/src/NHibernate/Context/ThreadLocalSessionContext.cs +++ b/src/NHibernate/Context/ThreadLocalSessionContext.cs @@ -33,7 +33,7 @@ namespace NHibernate.Context [Serializable] public partial class ThreadLocalSessionContext : ICurrentSessionContext { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ThreadLocalSessionContext)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ThreadLocalSessionContext)); [ThreadStatic] protected static IDictionary context; @@ -86,14 +86,14 @@ private static void CleanupAnyOrphanedSession(ISessionFactory factory) } catch (Exception ex) { - log.Debug("Unable to rollback transaction for orphaned session", ex); + log.Debug(ex, "Unable to rollback transaction for orphaned session"); } } orphan.Close(); } catch (Exception ex) { - log.Debug("Unable to close orphaned session", ex); + log.Debug(ex, "Unable to close orphaned session"); } } } @@ -188,4 +188,4 @@ private static ISession ExistingSession(ISessionFactory factory) return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/Dialect.cs b/src/NHibernate/Dialect/Dialect.cs index a4b5075f13c..212cc1327e5 100644 --- a/src/NHibernate/Dialect/Dialect.cs +++ b/src/NHibernate/Dialect/Dialect.cs @@ -30,7 +30,7 @@ namespace NHibernate.Dialect /// public abstract partial class Dialect { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(Dialect)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(Dialect)); protected const string DefaultBatchSize = "15"; protected const string NoBatch = "0"; @@ -78,7 +78,7 @@ static Dialect() /// protected Dialect() { - Log.Info("Using dialect: " + this); + Log.Info("Using dialect: {0}", this); _sqlFunctions = CollectionHelper.CreateCaseInsensitiveHashtable(StandardAggregateFunctions); diff --git a/src/NHibernate/Dialect/Lock/UpdateLockingStrategy.cs b/src/NHibernate/Dialect/Lock/UpdateLockingStrategy.cs index e98f3099fc7..6d5183ebbcc 100644 --- a/src/NHibernate/Dialect/Lock/UpdateLockingStrategy.cs +++ b/src/NHibernate/Dialect/Lock/UpdateLockingStrategy.cs @@ -16,7 +16,7 @@ namespace NHibernate.Dialect.Lock /// This strategy is not valid for read style locks. public partial class UpdateLockingStrategy : ILockingStrategy { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(UpdateLockingStrategy)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(UpdateLockingStrategy)); private readonly ILockable lockable; private readonly LockMode lockMode; private readonly SqlString sql; @@ -39,7 +39,7 @@ public UpdateLockingStrategy(ILockable lockable, LockMode lockMode) } if (!lockable.IsVersioned) { - log.Warn("write locks via update not supported for non-versioned entities [" + lockable.EntityName + "]"); + log.Warn("write locks via update not supported for non-versioned entities [{0}]", lockable.EntityName); sql = null; } else @@ -122,4 +122,4 @@ public void Lock(object id, object version, object obj, ISessionImplementor sess #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Dialect/Schema/AbstractTableMetadata.cs b/src/NHibernate/Dialect/Schema/AbstractTableMetadata.cs index f550b6bee92..d76092ab569 100644 --- a/src/NHibernate/Dialect/Schema/AbstractTableMetadata.cs +++ b/src/NHibernate/Dialect/Schema/AbstractTableMetadata.cs @@ -6,7 +6,7 @@ namespace NHibernate.Dialect.Schema { public abstract class AbstractTableMetadata : ITableMetadata { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ITableMetadata)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ITableMetadata)); private string catalog; private string schema; private string name; @@ -25,12 +25,15 @@ public AbstractTableMetadata(DataRow rs, IDataBaseSchema meta, bool extras) } string cat = catalog == null ? "" : catalog + '.'; string schem = schema == null ? "" : schema + '.'; - log.Info("table found: " + cat + schem + name); - log.Info("columns: " + StringHelper.CollectionToString(columns.Keys)); - if (extras) + if (log.IsInfoEnabled()) { - log.Info("foreign keys: " + StringHelper.CollectionToString(foreignKeys.Keys)); - log.Info("indexes: " + StringHelper.CollectionToString(indexes.Keys)); + log.Info("table found: {0}{1}{2}", cat, schem, name); + log.Info("columns: {0}", StringHelper.CollectionToString(columns.Keys)); + if (extras) + { + log.Info("foreign keys: {0}", StringHelper.CollectionToString(foreignKeys.Keys)); + log.Info("indexes: {0}", StringHelper.CollectionToString(indexes.Keys)); + } } } @@ -167,4 +170,4 @@ private void InitColumns(IDataBaseSchema meta) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Driver/BasicResultSetsCommand.cs b/src/NHibernate/Driver/BasicResultSetsCommand.cs index 70a6112ea91..f03c891d75d 100644 --- a/src/NHibernate/Driver/BasicResultSetsCommand.cs +++ b/src/NHibernate/Driver/BasicResultSetsCommand.cs @@ -14,7 +14,7 @@ namespace NHibernate.Driver { public partial class BasicResultSetsCommand: IResultSetsCommand { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(BasicResultSetsCommand)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(BasicResultSetsCommand)); private SqlString sqlString = SqlString.Empty; public BasicResultSetsCommand(ISessionImplementor session) diff --git a/src/NHibernate/Driver/DriverBase.cs b/src/NHibernate/Driver/DriverBase.cs index efc8629f1a2..45228121e11 100644 --- a/src/NHibernate/Driver/DriverBase.cs +++ b/src/NHibernate/Driver/DriverBase.cs @@ -16,7 +16,7 @@ namespace NHibernate.Driver /// public abstract class DriverBase : IDriver, ISqlParameterFormatter { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DriverBase)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DriverBase)); private int commandTimeout; private bool prepareSql; @@ -25,7 +25,7 @@ public virtual void Configure(IDictionary settings) { // Command timeout commandTimeout = PropertiesHelper.GetInt32(Environment.CommandTimeout, settings, -1); - if (commandTimeout > -1 && log.IsInfoEnabled) + if (commandTimeout > -1 && log.IsInfoEnabled()) { log.Info(string.Format("setting ADO.NET command timeout to {0} seconds", commandTimeout)); } @@ -148,9 +148,9 @@ protected virtual void SetCommandTimeout(DbCommand cmd) } catch (Exception e) { - if (log.IsWarnEnabled) + if (log.IsWarnEnabled()) { - log.Warn(e.ToString()); + log.Warn(e, e.ToString()); } } } diff --git a/src/NHibernate/Driver/NHybridDataReader.cs b/src/NHibernate/Driver/NHybridDataReader.cs index 9a148a6d8c7..e63da67cf9b 100644 --- a/src/NHibernate/Driver/NHybridDataReader.cs +++ b/src/NHibernate/Driver/NHybridDataReader.cs @@ -25,7 +25,7 @@ namespace NHibernate.Driver /// public partial class NHybridDataReader : DbDataReader { - private readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(NHybridDataReader)); + private readonly INHibernateLogger log = NHibernateLogger.For(typeof(NHybridDataReader)); private DbDataReader _reader; private bool _isMidstream; @@ -73,9 +73,9 @@ public void ReadIntoMemory() { if (_reader.IsClosed == false && _reader.GetType() != typeof(NDataReader)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Moving DbDataReader into an NDataReader. It was converted in midstream " + _isMidstream.ToString()); + log.Debug("Moving DbDataReader into an NDataReader. It was converted in midstream {0}", _isMidstream); } _reader = NDataReader.Create(_reader, _isMidstream); } @@ -439,4 +439,4 @@ public override short GetInt16(int i) return _reader.GetInt16(i); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Driver/OdbcDriver.cs b/src/NHibernate/Driver/OdbcDriver.cs index 7bf904daf75..73ec475166d 100644 --- a/src/NHibernate/Driver/OdbcDriver.cs +++ b/src/NHibernate/Driver/OdbcDriver.cs @@ -17,7 +17,7 @@ namespace NHibernate.Driver /// public class OdbcDriver : DriverBase { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(OdbcDriver)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(OdbcDriver)); private byte? _dbDateTimeScale; @@ -28,9 +28,9 @@ public override void Configure(IDictionary settings) // Explicit scale for DbType.DateTime. Seems required for at least MS SQL Server 2008+. _dbDateTimeScale = PropertiesHelper.GetByte(Environment.OdbcDateTimeScale, settings, null); - if (_dbDateTimeScale != null && Log.IsInfoEnabled) + if (_dbDateTimeScale != null && Log.IsInfoEnabled()) { - Log.Info(string.Format("Will use scale {0} for DbType.DateTime parameters.", _dbDateTimeScale)); + Log.Info("Will use scale {0} for DbType.DateTime parameters.", _dbDateTimeScale); } } diff --git a/src/NHibernate/Engine/ActionQueue.cs b/src/NHibernate/Engine/ActionQueue.cs index 1d2b7ef32d4..24bce5c7dda 100644 --- a/src/NHibernate/Engine/ActionQueue.cs +++ b/src/NHibernate/Engine/ActionQueue.cs @@ -21,7 +21,7 @@ namespace NHibernate.Engine [Serializable] public partial class ActionQueue { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ActionQueue)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ActionQueue)); private const int InitQueueListSize = 5; private ISessionImplementor session; @@ -245,8 +245,8 @@ private static bool AreTablesToUpdated(IList executables, ICollection ta { if(tablespaces.Contains(o)) { - if(log.IsDebugEnabled) - log.Debug("changes must be flushed to space: " + o); + if(log.IsDebugEnabled()) + log.Debug("changes must be flushed to space: {0}", o); return true; } @@ -486,7 +486,7 @@ public void AfterTransactionCompletion(bool success) } catch (CacheException e) { - log.Error( "could not release a cache lock", e); + log.Error(e, "could not release a cache lock"); // continue loop } catch (Exception e) @@ -594,7 +594,7 @@ private bool RequireNewBatch(EntityInsertAction action, int latestBatchNumberFor var propertyTypes = action.Persister.EntityMetamodel?.PropertyTypes; if (propertyTypes == null) { - log.InfoFormat( + log.Info( "Entity {0} persister does not provide meta-data, giving up batching grouping optimization for this entity.", action.EntityName); // Cancel grouping optimization for this entity. @@ -644,7 +644,7 @@ private void UpdateChildrenDependencies(int batchNumber, EntityInsertAction acti var propertyTypes = action.Persister.EntityMetamodel?.PropertyTypes; if (propertyTypes == null) { - log.WarnFormat( + log.Warn( "Entity {0} persister does not provide meta-data: if there is dependent entities providing " + "meta-data, they may get batched before this one and cause a failure.", action.EntityName); diff --git a/src/NHibernate/Engine/Cascade.cs b/src/NHibernate/Engine/Cascade.cs index a78109016ae..6dfd9f7c354 100644 --- a/src/NHibernate/Engine/Cascade.cs +++ b/src/NHibernate/Engine/Cascade.cs @@ -70,7 +70,7 @@ public enum CascadePoint /// public sealed partial class Cascade { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(Cascade)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Cascade)); private CascadePoint point; private readonly IEventSource eventSource; @@ -108,7 +108,7 @@ public void CascadeOn(IEntityPersister persister, object parent, object anything { if (persister.HasCascades || action.RequiresNoCascadeChecking) { - log.Info("processing cascade " + action + " for: " + persister.EntityName); + log.Info("processing cascade {0} for: {1}", action, persister.EntityName); IType[] types = persister.PropertyTypes; CascadeStyle[] cascadeStyles = persister.PropertyCascadeStyles; @@ -133,7 +133,7 @@ public void CascadeOn(IEntityPersister persister, object parent, object anything } } - log.Info("done processing cascade " + action + " for: " + persister.EntityName); + log.Info("done processing cascade {0} for: {1}", action, persister.EntityName); } } @@ -282,12 +282,12 @@ private void CascadeCollectionElements(object parent, object child, CollectionTy if (reallyDoCascade) { - log.Info("cascade " + action + " for collection: " + collectionType.Role); + log.Info("cascade {0} for collection: {1}", action, collectionType.Role); foreach (object o in action.GetCascadableChildrenIterator(eventSource, collectionType, child)) CascadeProperty(parent, o, elemType, style, null, anything, isCascadeDeleteEnabled); - log.Info("done cascade " + action + " for collection: " + collectionType.Role); + log.Info("done cascade {0} for collection: {1}", action, collectionType.Role); } var childAsPersColl = child as IPersistentCollection; @@ -297,7 +297,7 @@ private void CascadeCollectionElements(object parent, object child, CollectionTy if (deleteOrphans) { // handle orphaned entities!! - log.Info("deleting orphans for collection: " + collectionType.Role); + log.Info("deleting orphans for collection: {0}", collectionType.Role); // we can do the cast since orphan-delete does not apply to: // 1. newly instantiated collections @@ -305,7 +305,7 @@ private void CascadeCollectionElements(object parent, object child, CollectionTy string entityName = collectionType.GetAssociatedEntityName(eventSource.Factory); DeleteOrphans(entityName, childAsPersColl); - log.Info("done deleting orphans for collection: " + collectionType.Role); + log.Info("done deleting orphans for collection: {0}", collectionType.Role); } } @@ -328,7 +328,7 @@ private void DeleteOrphans(string entityName, IPersistentCollection pc) { if (orphan != null) { - log.Info("deleting orphaned entity instance: " + entityName); + log.Info("deleting orphaned entity instance: {0}", entityName); eventSource.Delete(entityName, orphan, false, null); } diff --git a/src/NHibernate/Engine/CascadingAction.cs b/src/NHibernate/Engine/CascadingAction.cs index 574be7a3280..14f8af2d173 100644 --- a/src/NHibernate/Engine/CascadingAction.cs +++ b/src/NHibernate/Engine/CascadingAction.cs @@ -14,7 +14,7 @@ namespace NHibernate.Engine /// public abstract partial class CascadingAction { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(CascadingAction)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(CascadingAction)); #region The CascadingAction contract @@ -147,9 +147,9 @@ private partial class DeleteCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to delete: " + entityName); + log.Debug("cascading to delete: {0}", entityName); } session.Delete(entityName, child, isCascadeDeleteEnabled, (ISet)anything); } @@ -170,9 +170,9 @@ private partial class LockCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to lock: " + entityName); + log.Debug("cascading to lock: {0}", entityName); } session.Lock(entityName, child, LockMode.None); } @@ -192,9 +192,9 @@ private partial class RefreshCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to refresh: " + entityName); + log.Debug("cascading to refresh: {0}", entityName); } session.Refresh(child, (IDictionary)anything); } @@ -213,9 +213,9 @@ private partial class EvictCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to evict: " + entityName); + log.Debug("cascading to evict: {0}", entityName); } session.Evict(child); } @@ -238,9 +238,9 @@ private partial class SaveUpdateCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to saveOrUpdate: " + entityName); + log.Debug("cascading to saveOrUpdate: {0}", entityName); } session.SaveOrUpdate(entityName, child); } @@ -264,9 +264,9 @@ private partial class MergeCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to merge: " + entityName); + log.Debug("cascading to merge: {0}", entityName); } session.Merge(entityName, child, (IDictionary)anything); } @@ -287,9 +287,9 @@ private partial class PersistCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to persist: " + entityName); + log.Debug("cascading to persist: {0}", entityName); } session.Persist(entityName, child, (IDictionary)anything); } @@ -312,9 +312,9 @@ private partial class PersistOnFlushCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to persistOnFlush: " + entityName); + log.Debug("cascading to persistOnFlush: {0}", entityName); } session.PersistOnFlush(entityName, child, (IDictionary)anything); } @@ -370,9 +370,9 @@ private partial class ReplicateCascadingAction : CascadingAction { public override void Cascade(IEventSource session, object child, string entityName, object anything, bool isCascadeDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("cascading to replicate: " + entityName); + log.Debug("cascading to replicate: {0}", entityName); } session.Replicate(entityName, child, (ReplicationMode)anything); } diff --git a/src/NHibernate/Engine/CollectionEntry.cs b/src/NHibernate/Engine/CollectionEntry.cs index f2769d7adf2..7d8ee06aa45 100644 --- a/src/NHibernate/Engine/CollectionEntry.cs +++ b/src/NHibernate/Engine/CollectionEntry.cs @@ -14,7 +14,7 @@ namespace NHibernate.Engine [Serializable] public partial class CollectionEntry { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (CollectionEntry)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (CollectionEntry)); /// session-start/post-flush persistent state private object snapshot; @@ -279,9 +279,9 @@ public void PreFlush(IPersistentCollection collection) } Dirty(collection); - if (log.IsDebugEnabled && collection.IsDirty && loadedPersister != null) + if (log.IsDebugEnabled() && collection.IsDirty && loadedPersister != null) { - log.Debug("Collection dirty: " + MessageHelper.CollectionInfoString(loadedPersister, loadedKey)); + log.Debug("Collection dirty: {0}", MessageHelper.CollectionInfoString(loadedPersister, loadedKey)); } // reset all of these values so any previous flush status @@ -384,4 +384,4 @@ public override string ToString() return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Engine/Collections.cs b/src/NHibernate/Engine/Collections.cs index 85542c127fb..69de56655c2 100644 --- a/src/NHibernate/Engine/Collections.cs +++ b/src/NHibernate/Engine/Collections.cs @@ -8,7 +8,7 @@ namespace NHibernate.Engine { public static partial class Collections { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(Collections)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Collections)); /// /// Record the fact that this collection was dereferenced @@ -33,8 +33,8 @@ private static void ProcessDereferencedCollection(IPersistentCollection coll, IS CollectionEntry entry = persistenceContext.GetCollectionEntry(coll); ICollectionPersister loadedPersister = entry.LoadedPersister; - if (log.IsDebugEnabled && loadedPersister != null) - log.Debug("Collection dereferenced: " + MessageHelper.CollectionInfoString(loadedPersister, coll, entry.LoadedKey, session)); + if (log.IsDebugEnabled() && loadedPersister != null) + log.Debug("Collection dereferenced: {0}", MessageHelper.CollectionInfoString(loadedPersister, coll, entry.LoadedKey, session)); // do a check bool hasOrphanDelete = loadedPersister != null && loadedPersister.HasOrphanDelete; @@ -84,7 +84,7 @@ private static void ProcessNeverReferencedCollection(IPersistentCollection coll, { CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(coll); - log.Debug("Found collection with unloaded owner: " + MessageHelper.CollectionInfoString(entry.LoadedPersister, coll, entry.LoadedKey, session)); + log.Debug("Found collection with unloaded owner: {0}", MessageHelper.CollectionInfoString(entry.LoadedPersister, coll, entry.LoadedKey, session)); entry.CurrentPersister = entry.LoadedPersister; entry.CurrentKey = entry.LoadedKey; @@ -124,12 +124,12 @@ public static void ProcessReachableCollection(IPersistentCollection collection, ce.CurrentPersister = persister; ce.CurrentKey = type.GetKeyOfOwner(entity, session); //TODO: better to pass the id in as an argument? - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Collection found: " + - MessageHelper.CollectionInfoString(persister, collection, ce.CurrentKey, session) + ", was: " + - MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, session) + - (collection.WasInitialized ? " (initialized)" : " (uninitialized)")); + log.Debug("Collection found: {0}, was: {1}{2}", + MessageHelper.CollectionInfoString(persister, collection, ce.CurrentKey, session), + MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, session), + (collection.WasInitialized ? " (initialized)" : " (uninitialized)")); } PrepareCollectionForUpdate(collection, ce, factory); diff --git a/src/NHibernate/Engine/ForeignKeys.cs b/src/NHibernate/Engine/ForeignKeys.cs index 2fce5fff627..3c6df63a815 100644 --- a/src/NHibernate/Engine/ForeignKeys.cs +++ b/src/NHibernate/Engine/ForeignKeys.cs @@ -9,7 +9,7 @@ namespace NHibernate.Engine /// Algorithms related to foreign key constraint transparency public static partial class ForeignKeys { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ForeignKeys)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ForeignKeys)); public partial class Nullifier { @@ -204,11 +204,8 @@ static bool HasDbSnapshot(string entityName, object entity, ISessionImplementor // When using assigned identifiers we cannot tell if an entity // is transient or detached without querying the database. // This could potentially cause Select N+1 in cascaded saves, so warn the user. - log.Warn( - "Unable to determine if " + entity.ToString() - + " with assigned identifier " + persister.GetIdentifier(entity) - + " is transient or detached; querying the database." - + " Use explicit Save() or Update() in session to prevent this."); + log.Warn("Unable to determine if {0} with assigned identifier {1} is transient or detached; querying the database. Use explicit Save() or Update() in session to prevent this.", + entity, persister.GetIdentifier(entity)); } // hit the database, after checking the session cache for a snapshot diff --git a/src/NHibernate/Engine/IdentifierValue.cs b/src/NHibernate/Engine/IdentifierValue.cs index 00b12ce2093..734616ccae6 100644 --- a/src/NHibernate/Engine/IdentifierValue.cs +++ b/src/NHibernate/Engine/IdentifierValue.cs @@ -9,7 +9,7 @@ namespace NHibernate.Engine /// public class IdentifierValue { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(IdentifierValue)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(IdentifierValue)); private readonly object value; @@ -34,9 +34,9 @@ public IdentifierValue(object value) /// public virtual bool? IsUnsaved(object id) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("unsaved-value: " + value); + log.Debug("unsaved-value: {0}", value); } return id == null || id.Equals(value); } @@ -46,6 +46,8 @@ public virtual object GetDefaultValue(object currentValue) return value; } + private const string UnsavedStrategyLog = "unsaved-value strategy {0}"; + /// /// Always assume the transient instance is newly instantiated /// @@ -55,7 +57,7 @@ private class SaveAnyClass : IdentifierValue { public override bool? IsUnsaved(object id) { - log.Debug("unsaved-value strategy ANY"); + log.Debug(UnsavedStrategyLog, "ANY"); return true; } @@ -74,7 +76,7 @@ private class SaveNoneClass : IdentifierValue { public override bool? IsUnsaved(object id) { - log.Debug("unsaved-value strategy NONE"); + log.Debug(UnsavedStrategyLog, "NONE"); return false; } @@ -94,7 +96,7 @@ private class SaveNullClass : IdentifierValue { public override bool? IsUnsaved(object id) { - log.Debug("unsaved-value strategy NULL"); + log.Debug(UnsavedStrategyLog, "NULL"); return id == null; } @@ -111,7 +113,7 @@ public class UndefinedClass : IdentifierValue { public override bool? IsUnsaved(object id) { - log.Debug("id unsaved-value strategy UNDEFINED"); + log.Debug(UnsavedStrategyLog, "UNDEFINED"); return null; } public override object GetDefaultValue(object currentValue) diff --git a/src/NHibernate/Engine/Loading/CollectionLoadContext.cs b/src/NHibernate/Engine/Loading/CollectionLoadContext.cs index 0a9c4ec223b..9d87fc4d044 100644 --- a/src/NHibernate/Engine/Loading/CollectionLoadContext.cs +++ b/src/NHibernate/Engine/Loading/CollectionLoadContext.cs @@ -21,7 +21,7 @@ namespace NHibernate.Engine.Loading /// public partial class CollectionLoadContext { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(CollectionLoadContext)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(CollectionLoadContext)); private readonly LoadContexts loadContexts; private readonly DbDataReader resultSet; private readonly ISet localLoadingCollectionKeys = new HashSet(); @@ -70,9 +70,9 @@ public DbDataReader ResultSet public IPersistentCollection GetLoadingCollection(ICollectionPersister persister, object key) { CollectionKey collectionKey = new CollectionKey(persister, key); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("starting attempt to find loading collection [" + MessageHelper.InfoString(persister.Role, key) + "]"); + log.Debug("starting attempt to find loading collection [{0}]", MessageHelper.InfoString(persister.Role, key)); } LoadingCollectionEntry loadingCollectionEntry = loadContexts.LocateLoadingCollectionEntry(collectionKey); if (loadingCollectionEntry == null) @@ -106,9 +106,9 @@ public IPersistentCollection GetLoadingCollection(ICollectionPersister persister else { // create one - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("instantiating new collection [key=" + key + ", rs=" + resultSet + "]"); + log.Debug("instantiating new collection [key={0}, rs={1}]", key, resultSet); } collection = persister.CollectionType.Instantiate(loadContexts.PersistenceContext.Session, persister, key); } @@ -164,7 +164,8 @@ public void EndLoadingCollections(ICollectionPersister persister) LoadingCollectionEntry lce = loadContexts.LocateLoadingCollectionEntry(collectionKey); if (lce == null) { - log.Warn("In CollectionLoadContext#endLoadingCollections, localLoadingCollectionKeys contained [" + collectionKey + "], but no LoadingCollectionEntry was found in loadContexts"); + log.Warn("In CollectionLoadContext#endLoadingCollections, localLoadingCollectionKeys contained [{0}], but no LoadingCollectionEntry was found in loadContexts", + collectionKey); } else if (lce.ResultSet == resultSet && lce.Persister == persister) { @@ -174,9 +175,9 @@ public void EndLoadingCollections(ICollectionPersister persister) session.PersistenceContext.AddUnownedCollection(new CollectionKey(persister, lce.Key), lce.Collection); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("removing collection load entry [" + lce + "]"); + log.Debug("removing collection load entry [{0}]", lce); } // todo : i'd much rather have this done from #endLoadingCollection(CollectionPersister,LoadingCollectionEntry)... @@ -203,17 +204,17 @@ private void EndLoadingCollections(ICollectionPersister persister, IList public class LoadContexts { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(LoadContexts)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(LoadContexts)); [NonSerialized] private readonly IPersistenceContext persistenceContext; @@ -88,7 +88,7 @@ public void Cleanup() { foreach (CollectionLoadContext collectionLoadContext in collectionLoadContexts.Values) { - log.Warn("fail-safe cleanup (collections) : " + collectionLoadContext); + log.Warn("fail-safe cleanup (collections) : {0}", collectionLoadContext); collectionLoadContext.Cleanup(); } collectionLoadContexts.Clear(); @@ -134,9 +134,9 @@ public CollectionLoadContext GetCollectionLoadContext(DbDataReader resultSet) } if (context == null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("constructing collection load context for result set [" + resultSet + "]"); + log.Debug("constructing collection load context for result set [{0}]", resultSet); } context = new CollectionLoadContext(this, resultSet); collectionLoadContexts[resultSet] = context; @@ -156,9 +156,9 @@ public IPersistentCollection LocateLoadingCollection(ICollectionPersister persis LoadingCollectionEntry lce = LocateLoadingCollectionEntry(new CollectionKey(persister, ownerKey)); if (lce != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("returning loading collection:" + MessageHelper.CollectionInfoString(persister, ownerKey, Session.Factory)); + log.Debug("returning loading collection:{0}", MessageHelper.CollectionInfoString(persister, ownerKey, Session.Factory)); } return lce.Collection; } @@ -229,15 +229,15 @@ internal LoadingCollectionEntry LocateLoadingCollectionEntry(CollectionKey key) { return null; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("attempting to locate loading collection entry [" + key + "] in any result-set context"); + log.Debug("attempting to locate loading collection entry [{0}] in any result-set context", key); } LoadingCollectionEntry rtn; xrefLoadingCollectionEntries.TryGetValue(key, out rtn); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("collection [{0}] {1} in load context", key, (rtn == null ? "located" : "not located"))); + log.Debug("collection [{0}] {1} in load context", key, (rtn == null ? "located" : "not located")); } return rtn; } diff --git a/src/NHibernate/Engine/Query/HQLQueryPlan.cs b/src/NHibernate/Engine/Query/HQLQueryPlan.cs index 3945541f405..ee1062a26e9 100644 --- a/src/NHibernate/Engine/Query/HQLQueryPlan.cs +++ b/src/NHibernate/Engine/Query/HQLQueryPlan.cs @@ -31,7 +31,7 @@ public interface IQueryExpressionPlan : IQueryPlan [Serializable] public partial class HQLQueryPlan : IQueryPlan { - protected static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(HQLQueryPlan)); + protected static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(HQLQueryPlan)); private readonly string _sourceQuery; @@ -85,9 +85,9 @@ public IQueryTranslator[] Translators public void PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("find: " + _sourceQuery); + Log.Debug("find: {0}", _sourceQuery); queryParameters.LogParameters(session.Factory); } @@ -152,9 +152,9 @@ public void PerformList(QueryParameters queryParameters, ISessionImplementor ses public IEnumerable PerformIterate(QueryParameters queryParameters, IEventSource session) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("enumerable: " + _sourceQuery); + Log.Debug("enumerable: {0}", _sourceQuery); queryParameters.LogParameters(session.Factory); } if (Translators.Length == 0) @@ -181,14 +181,14 @@ public IEnumerable PerformIterate(QueryParameters queryParameters, IEventS public int PerformExecuteUpdate(QueryParameters queryParameters, ISessionImplementor session) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("executeUpdate: " + _sourceQuery); + Log.Debug("executeUpdate: {0}", _sourceQuery); queryParameters.LogParameters(session.Factory); } if (Translators.Length != 1) { - Log.Warn("manipulation query [" + _sourceQuery + "] resulted in [" + Translators.Length + "] split queries"); + Log.Warn("manipulation query [{0}] resulted in [{1}] split queries", _sourceQuery, Translators.Length); } int result = 0; for (int i = 0; i < Translators.Length; i++) diff --git a/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs b/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs index 2037c1d1d60..622885d932f 100644 --- a/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs +++ b/src/NHibernate/Engine/Query/NativeSQLQueryPlan.cs @@ -23,7 +23,7 @@ namespace NHibernate.Engine.Query [Serializable] public partial class NativeSQLQueryPlan { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(NativeSQLQueryPlan)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(NativeSQLQueryPlan)); private readonly string sourceQuery; private readonly SQLCustomQuery customQuery; diff --git a/src/NHibernate/Engine/Query/QueryPlanCache.cs b/src/NHibernate/Engine/Query/QueryPlanCache.cs index a7083916f45..09556fa5a64 100644 --- a/src/NHibernate/Engine/Query/QueryPlanCache.cs +++ b/src/NHibernate/Engine/Query/QueryPlanCache.cs @@ -11,7 +11,7 @@ namespace NHibernate.Engine.Query [Serializable] public class QueryPlanCache { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(QueryPlanCache)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(QueryPlanCache)); private readonly ISessionFactoryImplementor factory; @@ -54,18 +54,18 @@ public IQueryExpressionPlan GetHQLQueryPlan(IQueryExpression queryExpression, bo if (plan == null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("unable to locate HQL query plan in cache; generating (" + queryExpression.Key + ")"); + log.Debug("unable to locate HQL query plan in cache; generating ({0})", queryExpression.Key); } plan = new QueryExpressionPlan(queryExpression, shallow, enabledFilters, factory); planCache.Put(key, plan); } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("located HQL query plan in cache (" + queryExpression.Key + ")"); + log.Debug("located HQL query plan in cache ({0})", queryExpression.Key); } plan = CopyIfRequired(plan, queryExpression); } @@ -108,13 +108,13 @@ public IQueryExpressionPlan GetFilterQueryPlan(IQueryExpression queryExpression, if (plan == null) { - log.DebugFormat("unable to locate collection-filter query plan in cache; generating ({0} : {1})", collectionRole, queryExpression.Key); + log.Debug("unable to locate collection-filter query plan in cache; generating ({0} : {1})", collectionRole, queryExpression.Key); plan = new FilterQueryPlan(queryExpression, collectionRole, shallow, enabledFilters, factory); planCache.Put(key, plan); } else { - log.DebugFormat("located collection-filter query plan in cache ({0} : {1})", collectionRole, queryExpression.Key); + log.Debug("located collection-filter query plan in cache ({0} : {1})", collectionRole, queryExpression.Key); plan = CopyIfRequired(plan, queryExpression); } @@ -127,18 +127,18 @@ public NativeSQLQueryPlan GetNativeSQLQueryPlan(NativeSQLQuerySpecification spec if (plan == null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("unable to locate native-sql query plan in cache; generating (" + spec.QueryString + ")"); + log.Debug("unable to locate native-sql query plan in cache; generating ({0})", spec.QueryString); } plan = new NativeSQLQueryPlan(spec, factory); planCache.Put(spec, plan); } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("located native-sql query plan in cache (" + spec.QueryString + ")"); + log.Debug("located native-sql query plan in cache ({0})", spec.QueryString); } } diff --git a/src/NHibernate/Engine/QueryParameters.cs b/src/NHibernate/Engine/QueryParameters.cs index db4d1a36fd7..6af67a3d685 100644 --- a/src/NHibernate/Engine/QueryParameters.cs +++ b/src/NHibernate/Engine/QueryParameters.cs @@ -17,7 +17,7 @@ namespace NHibernate.Engine [Serializable] public sealed class QueryParameters { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (QueryParameters)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (QueryParameters)); private bool readOnly; @@ -171,12 +171,12 @@ public void LogParameters(ISessionFactoryImplementor factory) var print = new Printer(factory); if (PositionalParameterValues.Length != 0) { - log.Debug("parameters: " + print.ToString(PositionalParameterTypes, PositionalParameterValues)); + log.Debug("parameters: {0}", print.ToString(PositionalParameterTypes, PositionalParameterValues)); } if (NamedParameters != null) { - log.Debug("named parameters: " + print.ToString(NamedParameters)); + log.Debug("named parameters: {0}", print.ToString(NamedParameters)); } } diff --git a/src/NHibernate/Engine/StatefulPersistenceContext.cs b/src/NHibernate/Engine/StatefulPersistenceContext.cs index 0c47bcb8ba0..27f62db3477 100644 --- a/src/NHibernate/Engine/StatefulPersistenceContext.cs +++ b/src/NHibernate/Engine/StatefulPersistenceContext.cs @@ -30,8 +30,8 @@ namespace NHibernate.Engine public partial class StatefulPersistenceContext : IPersistenceContext, ISerializable, IDeserializationCallback { private const int InitCollectionSize = 8; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(StatefulPersistenceContext)); - private static readonly IInternalLogger ProxyWarnLog = LoggerProvider.LoggerFor(typeof(StatefulPersistenceContext).FullName + ".ProxyWarnLog"); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(StatefulPersistenceContext)); + private static readonly INHibernateLogger ProxyWarnLog = NHibernateLogger.For(typeof(StatefulPersistenceContext).FullName + ".ProxyWarnLog"); public static readonly object NoRow = new object(); @@ -592,9 +592,9 @@ public void ReassociateProxy(object value, object id) { var proxy = value as INHibernateProxy; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("setting proxy identifier: " + id); + log.Debug("setting proxy identifier: {0}", id); } ILazyInitializer li = proxy.HibernateLazyInitializer; li.Identifier = id; @@ -712,9 +712,9 @@ public object NarrowProxy(INHibernateProxy proxy, IEntityPersister persister, En if (!alreadyNarrow) { - if (ProxyWarnLog.IsWarnEnabled) + if (ProxyWarnLog.IsWarnEnabled()) { - ProxyWarnLog.Warn("Narrowing proxy to " + persister.ConcreteProxyClass + " - this operation breaks =="); + ProxyWarnLog.Warn("Narrowing proxy to {0} - this operation breaks ==", persister.ConcreteProxyClass); } if (obj != null) diff --git a/src/NHibernate/Engine/Transaction/Isolater.cs b/src/NHibernate/Engine/Transaction/Isolater.cs index 127a21d7ecb..5f4600dadcb 100644 --- a/src/NHibernate/Engine/Transaction/Isolater.cs +++ b/src/NHibernate/Engine/Transaction/Isolater.cs @@ -27,7 +27,7 @@ namespace NHibernate.Engine.Transaction /// public partial class Isolater { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(Isolater)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Isolater)); /// /// Ensures that all processing actually performed by the given work will diff --git a/src/NHibernate/Engine/TwoPhaseLoad.cs b/src/NHibernate/Engine/TwoPhaseLoad.cs index bf51706928c..54786a29d4e 100644 --- a/src/NHibernate/Engine/TwoPhaseLoad.cs +++ b/src/NHibernate/Engine/TwoPhaseLoad.cs @@ -19,7 +19,7 @@ namespace NHibernate.Engine /// public static partial class TwoPhaseLoad { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(TwoPhaseLoad)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(TwoPhaseLoad)); /// /// Register the "hydrated" state of an entity instance, after the first step of 2-phase loading. @@ -33,10 +33,10 @@ public static void PostHydrate(IEntityPersister persister, object id, object[] v object version = Versioning.GetVersion(values, persister); session.PersistenceContext.AddEntry(obj, Status.Loading, values, rowId, id, version, lockMode, true, persister, false, lazyPropertiesAreUnfetched); - if (log.IsDebugEnabled && version != null) + if (log.IsDebugEnabled() && version != null) { System.String versionStr = persister.IsVersioned ? persister.VersionType.ToLoggableString(version, session.Factory) : "null"; - log.Debug("Version: " + versionStr); + log.Debug("Version: {0}", versionStr); } } @@ -67,8 +67,8 @@ public static void InitializeEntity(object entity, bool readOnly, ISessionImplem object id = entityEntry.Id; object[] hydratedState = entityEntry.LoadedState; - if (log.IsDebugEnabled) - log.Debug("resolving associations for " + MessageHelper.InfoString(persister, id, session.Factory)); + if (log.IsDebugEnabled()) + log.Debug("resolving associations for {0}", MessageHelper.InfoString(persister, id, session.Factory)); IType[] types = persister.PropertyTypes; for (int i = 0; i < hydratedState.Length; i++) @@ -100,8 +100,8 @@ public static void InitializeEntity(object entity, bool readOnly, ISessionImplem if (persister.HasCache && session.CacheMode.HasFlag(CacheMode.Put)) { - if (log.IsDebugEnabled) - log.Debug("adding entity to second-level cache: " + MessageHelper.InfoString(persister, id, session.Factory)); + if (log.IsDebugEnabled()) + log.Debug("adding entity to second-level cache: {0}", MessageHelper.InfoString(persister, id, session.Factory)); object version = Versioning.GetVersion(hydratedState, persister); CacheEntry entry = @@ -164,8 +164,8 @@ public static void InitializeEntity(object entity, bool readOnly, ISessionImplem } } - if (log.IsDebugEnabled) - log.Debug("done materializing entity " + MessageHelper.InfoString(persister, id, session.Factory)); + if (log.IsDebugEnabled()) + log.Debug("done materializing entity {0}", MessageHelper.InfoString(persister, id, session.Factory)); if (statsEnabled) { diff --git a/src/NHibernate/Engine/VersionValue.cs b/src/NHibernate/Engine/VersionValue.cs index 48d6a8a91cf..43cb8e53158 100644 --- a/src/NHibernate/Engine/VersionValue.cs +++ b/src/NHibernate/Engine/VersionValue.cs @@ -11,7 +11,7 @@ namespace NHibernate.Engine /// public class VersionValue { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(VersionValue)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(VersionValue)); private readonly object value; @@ -36,9 +36,9 @@ public VersionValue(object value) /// public virtual bool? IsUnsaved(object version) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("unsaved-value: " + value); + log.Debug("unsaved-value: {0}", value); } return version == null || version.Equals(value); } @@ -48,6 +48,8 @@ public virtual object GetDefaultValue(object currentValue) return value; } + private const string UnsavedStrategyLog = "version unsaved-value strategy {0}"; + /// /// Assume the transient instance is newly instantiated if the version /// is null, otherwise assume it is a detached instance. @@ -58,7 +60,7 @@ private class VersionSaveNullClass : VersionValue { public override bool? IsUnsaved(object version) { - log.Debug("version unsaved-value strategy NULL"); + log.Debug(UnsavedStrategyLog, "NULL"); return version == null; } @@ -78,7 +80,7 @@ private class VersionUndefinedClass : VersionValue { public override bool? IsUnsaved(object version) { - log.Debug("version unsaved-value strategy UNDEFINED"); + log.Debug(UnsavedStrategyLog, "UNDEFINED"); if (version == null) return true; else @@ -101,7 +103,7 @@ private class VersionNegativeClass : VersionValue { public override bool? IsUnsaved(object version) { - log.Debug("version unsaved-value strategy NEGATIVE"); + log.Debug(UnsavedStrategyLog, "NEGATIVE"); if (version is short || version is int || version is long) { return Convert.ToInt64(version) < 0L; diff --git a/src/NHibernate/Engine/Versioning.cs b/src/NHibernate/Engine/Versioning.cs index c8ec4e8f42a..c9c293d3204 100644 --- a/src/NHibernate/Engine/Versioning.cs +++ b/src/NHibernate/Engine/Versioning.cs @@ -17,7 +17,7 @@ public enum OptimisticLock All = 2 } - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(Versioning)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Versioning)); /// /// Increment the given version number @@ -29,11 +29,11 @@ public enum OptimisticLock public static object Increment(object version, IVersionType versionType, ISessionImplementor session) { object next = versionType.Next(version, session); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug( - string.Format("Incrementing: {0} to {1}", versionType.ToLoggableString(version, session.Factory), - versionType.ToLoggableString(next, session.Factory))); + log.Debug("Incrementing: {0} to {1}", + versionType.ToLoggableString(version, session.Factory), + versionType.ToLoggableString(next, session.Factory)); } return next; } @@ -47,9 +47,9 @@ public static object Increment(object version, IVersionType versionType, ISessio public static object Seed(IVersionType versionType, ISessionImplementor session) { object seed = versionType.Seed(session); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Seeding: " + seed); + log.Debug("Seeding: {0}", seed); } return seed; } @@ -74,9 +74,9 @@ public static bool SeedVersion(object[] fields, int versionProperty, IVersionTyp } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("using initial version: " + initialVersion); + log.Debug("using initial version: {0}", initialVersion); } return false; } @@ -128,4 +128,4 @@ public static bool IsVersionIncrementRequired(int[] dirtyProperties, bool hasDir return false; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Event/Default/AbstractFlushingEventListener.cs b/src/NHibernate/Event/Default/AbstractFlushingEventListener.cs index c4bcfc6b295..f9f968a4b2a 100644 --- a/src/NHibernate/Event/Default/AbstractFlushingEventListener.cs +++ b/src/NHibernate/Event/Default/AbstractFlushingEventListener.cs @@ -19,7 +19,7 @@ namespace NHibernate.Event.Default [Serializable] public abstract partial class AbstractFlushingEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (AbstractFlushingEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (AbstractFlushingEventListener)); protected virtual object Anything { @@ -67,20 +67,21 @@ protected virtual void FlushEverythingToExecutions(FlushEvent @event) } //some statistics - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - StringBuilder sb = new StringBuilder(100); - - sb.Append("Flushed: ").Append(session.ActionQueue.InsertionsCount).Append(" insertions, ").Append( - session.ActionQueue.UpdatesCount).Append(" updates, ").Append(session.ActionQueue.DeletionsCount).Append( - " deletions to ").Append(persistenceContext.EntityEntries.Count).Append(" objects"); - log.Debug(sb.ToString()); - sb = new StringBuilder(100); - sb.Append("Flushed: ").Append(session.ActionQueue.CollectionCreationsCount).Append(" (re)creations, ").Append( - session.ActionQueue.CollectionUpdatesCount).Append(" updates, ").Append(session.ActionQueue.CollectionRemovalsCount) - .Append(" removals to ").Append(persistenceContext.CollectionEntries.Count).Append(" collections"); - - log.Debug(sb.ToString()); + log.Debug( + "Flushed: {0} insertions, {1} updates, {2} deletions to {3} objects", + session.ActionQueue.InsertionsCount, + session.ActionQueue.UpdatesCount, + session.ActionQueue.DeletionsCount, + persistenceContext.EntityEntries.Count); + + log.Debug( + "Flushed: {0} (re)creations, {1} updates, {2} removals to {3} collections", + session.ActionQueue.CollectionCreationsCount, + session.ActionQueue.CollectionUpdatesCount, + session.ActionQueue.CollectionRemovalsCount, + persistenceContext.CollectionEntries.Count); new Printer(session.Factory).ToString(persistenceContext.EntitiesByKey.Values.ToArray()); } } @@ -228,7 +229,7 @@ protected virtual void CascadeOnFlush(IEventSource session, IEntityPersister per /// The session being flushed protected virtual void PerformExecutions(IEventSource session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("executing flush"); } @@ -249,9 +250,9 @@ protected virtual void PerformExecutions(IEventSource session) } catch (HibernateException he) { - if (log.IsErrorEnabled) + if (log.IsErrorEnabled()) { - log.Error("Could not synchronize database state with session", he); + log.Error(he, "Could not synchronize database state with session"); } throw; } @@ -269,7 +270,7 @@ protected virtual void PerformExecutions(IEventSource session) /// protected virtual void PostFlush(ISessionImplementor session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("post flush"); } diff --git a/src/NHibernate/Event/Default/AbstractLockUpgradeEventListener.cs b/src/NHibernate/Event/Default/AbstractLockUpgradeEventListener.cs index d61a3ab673f..f30c88d4162 100644 --- a/src/NHibernate/Event/Default/AbstractLockUpgradeEventListener.cs +++ b/src/NHibernate/Event/Default/AbstractLockUpgradeEventListener.cs @@ -16,7 +16,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class AbstractLockUpgradeEventListener : AbstractReassociateEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(AbstractLockUpgradeEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AbstractLockUpgradeEventListener)); /// /// Performs a pessimistic lock upgrade on a given entity, if needed. @@ -38,9 +38,9 @@ protected virtual void UpgradeLock(object entity, EntityEntry entry, LockMode re IEntityPersister persister = entry.Persister; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("locking {0} in mode: {1}", MessageHelper.InfoString(persister, entry.Id, source.Factory), requestedLockMode)); + log.Debug("locking {0} in mode: {1}", MessageHelper.InfoString(persister, entry.Id, source.Factory), requestedLockMode); } ISoftLock slock; diff --git a/src/NHibernate/Event/Default/AbstractReassociateEventListener.cs b/src/NHibernate/Event/Default/AbstractReassociateEventListener.cs index fc900ea5596..81b37054009 100644 --- a/src/NHibernate/Event/Default/AbstractReassociateEventListener.cs +++ b/src/NHibernate/Event/Default/AbstractReassociateEventListener.cs @@ -15,7 +15,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class AbstractReassociateEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(AbstractReassociateEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AbstractReassociateEventListener)); /// /// Associates a given entity (either transient or associated with another session) to the given session. @@ -27,9 +27,9 @@ public partial class AbstractReassociateEventListener /// An EntityEntry representing the entity within this session. protected EntityEntry Reassociate(AbstractEvent @event, object entity, object id, IEntityPersister persister) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Reassociating transient instance: " + MessageHelper.InfoString(persister, id, @event.Session.Factory)); + log.Debug("Reassociating transient instance: {0}", MessageHelper.InfoString(persister, id, @event.Session.Factory)); } IEventSource source = @event.Session; diff --git a/src/NHibernate/Event/Default/AbstractSaveEventListener.cs b/src/NHibernate/Event/Default/AbstractSaveEventListener.cs index 55f616751e0..63e94980222 100644 --- a/src/NHibernate/Event/Default/AbstractSaveEventListener.cs +++ b/src/NHibernate/Event/Default/AbstractSaveEventListener.cs @@ -28,7 +28,7 @@ public enum EntityState [Serializable] public abstract partial class AbstractSaveEventListener : AbstractReassociateEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(AbstractSaveEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AbstractSaveEventListener)); protected virtual bool? AssumedUnsaved { @@ -120,11 +120,11 @@ protected virtual object SaveWithGeneratedId(object entity, string entityName, o } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("generated identifier: {0}, using strategy: {1}", - persister.IdentifierType.ToLoggableString(generatedId, source.Factory), - persister.IdentifierGenerator.GetType().FullName)); + log.Debug("generated identifier: {0}, using strategy: {1}", + persister.IdentifierType.ToLoggableString(generatedId, source.Factory), + persister.IdentifierGenerator.GetType().FullName); } return PerformSave(entity, generatedId, persister, false, anything, source, true); } @@ -152,9 +152,9 @@ protected virtual object SaveWithGeneratedId(object entity, string entityName, o /// protected virtual object PerformSave(object entity, object id, IEntityPersister persister, bool useIdentityColumn, object anything, IEventSource source, bool requiresImmediateIdAccess) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("saving " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("saving {0}", MessageHelper.InfoString(persister, id, source.Factory)); } EntityKey key; @@ -401,18 +401,18 @@ protected virtual EntityState GetEntityState(object entity, string entityName, E if (entry.Status != Status.Deleted) { // do nothing for persistent instances - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("persistent instance of: " + GetLoggableName(entityName, entity)); + log.Debug("persistent instance of: {0}", GetLoggableName(entityName, entity)); } return EntityState.Persistent; } else { //ie. e.status==DELETED - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("deleted instance of: " + GetLoggableName(entityName, entity)); + log.Debug("deleted instance of: {0}", GetLoggableName(entityName, entity)); } return EntityState.Deleted; } @@ -427,17 +427,17 @@ protected virtual EntityState GetEntityState(object entity, string entityName, E ? ForeignKeys.IsTransientFast(entityName, entity, source).GetValueOrDefault(assumed.Value) : ForeignKeys.IsTransientSlow(entityName, entity, source)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("transient instance of: " + GetLoggableName(entityName, entity)); + log.Debug("transient instance of: {0}", GetLoggableName(entityName, entity)); } return EntityState.Transient; } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("detached instance of: " + GetLoggableName(entityName, entity)); + log.Debug("detached instance of: {0}", GetLoggableName(entityName, entity)); } return EntityState.Detached; } diff --git a/src/NHibernate/Event/Default/DefaultAutoFlushEventListener.cs b/src/NHibernate/Event/Default/DefaultAutoFlushEventListener.cs index 3133c7ec3ee..70a8bd898da 100644 --- a/src/NHibernate/Event/Default/DefaultAutoFlushEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultAutoFlushEventListener.cs @@ -11,7 +11,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultAutoFlushEventListener : AbstractFlushingEventListener, IAutoFlushEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultAutoFlushEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultAutoFlushEventListener)); #region IAutoFlushEventListener Members @@ -33,7 +33,7 @@ public virtual void OnAutoFlush(AutoFlushEvent @event) if (FlushIsReallyNeeded(@event, source)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) log.Debug("Need to execute flush"); PerformExecutions(source); @@ -49,7 +49,7 @@ public virtual void OnAutoFlush(AutoFlushEvent @event) else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) log.Debug("Dont need to execute flush"); source.ActionQueue.ClearFromFlushNeededCheck(oldSize); } diff --git a/src/NHibernate/Event/Default/DefaultDeleteEventListener.cs b/src/NHibernate/Event/Default/DefaultDeleteEventListener.cs index e341e94235e..6a0df1b5665 100644 --- a/src/NHibernate/Event/Default/DefaultDeleteEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultDeleteEventListener.cs @@ -18,7 +18,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultDeleteEventListener : IDeleteEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultDeleteEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultDeleteEventListener)); #region IDeleteEventListener Members @@ -168,9 +168,9 @@ protected virtual void DeleteTransientEntity(IEventSource session, object entity /// A cache of already deleted entities. protected virtual void DeleteEntity(IEventSource session, object entity, EntityEntry entityEntry, bool isCascadeDeleteEnabled, IEntityPersister persister, ISet transientEntities) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("deleting " + MessageHelper.InfoString(persister, entityEntry.Id, session.Factory)); + log.Debug("deleting {0}", MessageHelper.InfoString(persister, entityEntry.Id, session.Factory)); } IPersistenceContext persistenceContext = session.PersistenceContext; diff --git a/src/NHibernate/Event/Default/DefaultDirtyCheckEventListener.cs b/src/NHibernate/Event/Default/DefaultDirtyCheckEventListener.cs index 3a333a4ee33..482968352d3 100644 --- a/src/NHibernate/Event/Default/DefaultDirtyCheckEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultDirtyCheckEventListener.cs @@ -10,7 +10,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultDirtyCheckEventListener : AbstractFlushingEventListener, IDirtyCheckEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultDirtyCheckEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultDirtyCheckEventListener)); public virtual void OnDirtyCheck(DirtyCheckEvent @event) { diff --git a/src/NHibernate/Event/Default/DefaultEvictEventListener.cs b/src/NHibernate/Event/Default/DefaultEvictEventListener.cs index 7ba5e6083c8..c19bc54fd90 100644 --- a/src/NHibernate/Event/Default/DefaultEvictEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultEvictEventListener.cs @@ -16,7 +16,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultEvictEventListener : IEvictEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultEvictEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultEvictEventListener)); public virtual void OnEvict(EvictEvent @event) { @@ -60,9 +60,9 @@ public virtual void OnEvict(EvictEvent @event) protected virtual void DoEvict(object obj, EntityKey key, IEntityPersister persister, IEventSource session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting " + MessageHelper.InfoString(persister)); + log.Debug("evicting {0}", MessageHelper.InfoString(persister)); } // remove all collections for the entity from the session-level cache diff --git a/src/NHibernate/Event/Default/DefaultFlushEntityEventListener.cs b/src/NHibernate/Event/Default/DefaultFlushEntityEventListener.cs index 9bbc10188b6..43ad4f10064 100644 --- a/src/NHibernate/Event/Default/DefaultFlushEntityEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultFlushEntityEventListener.cs @@ -16,7 +16,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultFlushEntityEventListener : IFlushEntityEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultFlushEntityEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultFlushEntityEventListener)); /// /// Flushes a single entity's state to the database, by scheduling an update action, if necessary @@ -209,26 +209,26 @@ private bool ScheduleUpdate(FlushEntityEvent @event) IEntityPersister persister = entry.Persister; object[] values = @event.PropertyValues; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (status == Status.Deleted) { if (!persister.IsMutable) { - log.Debug("Updating immutable, deleted entity: " + MessageHelper.InfoString(persister, entry.Id, session.Factory)); + log.Debug("Updating immutable, deleted entity: {0}", MessageHelper.InfoString(persister, entry.Id, session.Factory)); } else if (!entry.IsModifiableEntity()) { - log.Debug("Updating non-modifiable, deleted entity: " + MessageHelper.InfoString(persister, entry.Id, session.Factory)); + log.Debug("Updating non-modifiable, deleted entity: {0}", MessageHelper.InfoString(persister, entry.Id, session.Factory)); } else { - log.Debug("Updating deleted entity: " + MessageHelper.InfoString(persister, entry.Id, session.Factory)); + log.Debug("Updating deleted entity: {0}", MessageHelper.InfoString(persister, entry.Id, session.Factory)); } } else { - log.Debug("Updating entity: " + MessageHelper.InfoString(persister, entry.Id, session.Factory)); + log.Debug("Updating entity: {0}", MessageHelper.InfoString(persister, entry.Id, session.Factory)); } } diff --git a/src/NHibernate/Event/Default/DefaultInitializeCollectionEventListener.cs b/src/NHibernate/Event/Default/DefaultInitializeCollectionEventListener.cs index 1c1201ec2ad..c2d65277a60 100644 --- a/src/NHibernate/Event/Default/DefaultInitializeCollectionEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultInitializeCollectionEventListener.cs @@ -13,7 +13,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultInitializeCollectionEventListener : IInitializeCollectionEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultInitializeCollectionEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultInitializeCollectionEventListener)); /// called by a collection that wants to initialize itself public virtual void OnInitializeCollection(InitializeCollectionEvent @event) @@ -33,9 +33,9 @@ public virtual void OnInitializeCollection(InitializeCollectionEvent @event) throw new HibernateException("collection was evicted"); if (!collection.WasInitialized) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("initializing collection " + MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, source)); + log.Debug("initializing collection {0}", MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, source)); } log.Debug("checking second-level cache"); @@ -97,11 +97,11 @@ private bool InitializeCollectionFromCache(object id, ICollectionPersister persi if (ce == null) { - log.DebugFormat("Collection cache miss: {0}", ck); + log.Debug("Collection cache miss: {0}", ck); } else { - log.DebugFormat("Collection cache hit: {0}", ck); + log.Debug("Collection cache hit: {0}", ck); } if (ce == null) diff --git a/src/NHibernate/Event/Default/DefaultLoadEventListener.cs b/src/NHibernate/Event/Default/DefaultLoadEventListener.cs index 643c8760642..b919263755d 100644 --- a/src/NHibernate/Event/Default/DefaultLoadEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultLoadEventListener.cs @@ -19,7 +19,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultLoadEventListener : AbstractLockUpgradeEventListener, ILoadEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultLoadEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultLoadEventListener)); public static readonly object RemovedEntityMarker = new object(); public static readonly object InconsistentRTNClassMarker= new object(); public static readonly LockMode DefaultLockMode = LockMode.None; @@ -89,7 +89,7 @@ public virtual void OnLoad(LoadEvent @event, LoadType loadType) } catch (HibernateException e) { - log.Info("Error performing load command", e); + log.Info(e, "Error performing load command"); throw; } } @@ -134,9 +134,9 @@ protected virtual object Load(LoadEvent @event, IEntityPersister persister, Enti /// The result of the proxy/load operation. protected virtual object ProxyOrLoad(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("loading entity: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("loading entity: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } if (!persister.HasProxy) @@ -286,9 +286,9 @@ protected virtual object LockAndLoad(LoadEvent @event, IEntityPersister persiste /// The loaded entity, or null. protected virtual object DoLoad(LoadEvent @event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("attempting to resolve: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("attempting to resolve: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } object entity = LoadFromSessionCache(@event, keyToLoad, options); @@ -304,9 +304,9 @@ protected virtual object DoLoad(LoadEvent @event, IEntityPersister persister, En } if (entity != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("resolved object in session cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("resolved object in session cache: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } return entity; } @@ -314,16 +314,16 @@ protected virtual object DoLoad(LoadEvent @event, IEntityPersister persister, En entity = LoadFromSecondLevelCache(@event, persister, options); if (entity != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("resolved object in second-level cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("resolved object in second-level cache: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } return entity; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("object not resolved in any cache: " + MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); + log.Debug("object not resolved in any cache: {0}", MessageHelper.InfoString(persister, @event.EntityId, @event.Session.Factory)); } return LoadFromDatasource(@event, persister, keyToLoad, options); @@ -428,12 +428,12 @@ protected virtual object LoadFromSecondLevelCache(LoadEvent @event, IEntityPersi if (ce == null) { factory.StatisticsImplementor.SecondLevelCacheMiss(persister.Cache.RegionName); - log.DebugFormat("Entity cache miss: {0}", ck); + log.Debug("Entity cache miss: {0}", ck); } else { factory.StatisticsImplementor.SecondLevelCacheHit(persister.Cache.RegionName); - log.DebugFormat("Entity cache hit: {0}", ck); + log.Debug("Entity cache hit: {0}", ck); } } @@ -459,9 +459,9 @@ private object AssembleCacheEntry(CacheEntry entry, object id, IEntityPersister IEventSource session = @event.Session; ISessionFactoryImplementor factory = session.Factory; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("assembling entity from second-level cache: " + MessageHelper.InfoString(persister, id, factory)); + log.Debug("assembling entity from second-level cache: {0}", MessageHelper.InfoString(persister, id, factory)); } IEntityPersister subclassPersister = factory.GetEntityPersister(entry.Subclass); @@ -476,9 +476,9 @@ private object AssembleCacheEntry(CacheEntry entry, object id, IEntityPersister TypeHelper.DeepCopy(values, types, subclassPersister.PropertyUpdateability, values, session); object version = Versioning.GetVersion(values, subclassPersister); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Cached Version: " + version); + log.Debug("Cached Version: {0}", version); } IPersistenceContext persistenceContext = session.PersistenceContext; diff --git a/src/NHibernate/Event/Default/DefaultMergeEventListener.cs b/src/NHibernate/Event/Default/DefaultMergeEventListener.cs index 24645dda4e1..9803fb3fd43 100644 --- a/src/NHibernate/Event/Default/DefaultMergeEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultMergeEventListener.cs @@ -18,7 +18,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultMergeEventListener : AbstractSaveEventListener, IMergeEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultMergeEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultMergeEventListener)); protected override CascadingAction CascadeAction { @@ -76,7 +76,7 @@ public virtual void OnMerge(MergeEvent @event) transientEntityNames.Add(transientEntityName); - log.InfoFormat( + log.Info( "transient instance could not be processed by merge: {0} [{1}]", transientEntityName, transientEntity.ToString()); @@ -254,23 +254,23 @@ private object MergeTransientEntity(object entity, string entityName, object req if (propertyFromCopy == null || !propertyType.IsEntityType) { - log.InfoFormat("property '{0}.{1}' is null or not an entity; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromCopy); + log.Info("property '{0}.{1}' is null or not an entity; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromCopy); throw; } if (!copyCache.Contains(propertyFromEntity)) { - log.InfoFormat("property '{0}.{1}' from original entity is not in copyCache; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); + log.Info("property '{0}.{1}' from original entity is not in copyCache; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); throw; } if (((EventCache)copyCache).IsOperatedOn(propertyFromEntity)) { - log.InfoFormat("property '{0}.{1}' from original entity is in copyCache and is in the process of being merged; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); + log.Info("property '{0}.{1}' from original entity is in copyCache and is in the process of being merged; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); } else { - log.InfoFormat("property '{0}.{1}' from original entity is in copyCache and is not in the process of being merged; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); + log.Info("property '{0}.{1}' from original entity is in copyCache and is not in the process of being merged; {1} =[{2}]", copyEntry.EntityName, propertyName, propertyFromEntity); } // continue...; we'll find out if it ends up not getting saved later @@ -547,7 +547,7 @@ protected EventCache GetTransientCopyCache(MergeEvent @event, EventCache copyCac { // entity name will not be available for non-POJO entities // TODO: cache the entity name somewhere so that it is available to this exception - log.InfoFormat( + log.Info( "transient instance could not be processed by merge: {0} [{1}]", @event.Session.GuessEntityName(entityCopy), entity); diff --git a/src/NHibernate/Event/Default/DefaultPersistEventListener.cs b/src/NHibernate/Event/Default/DefaultPersistEventListener.cs index 74b77ced82c..3f6262b5403 100644 --- a/src/NHibernate/Event/Default/DefaultPersistEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultPersistEventListener.cs @@ -15,7 +15,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultPersistEventListener : AbstractSaveEventListener, IPersistEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultPersistEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultPersistEventListener)); protected override CascadingAction CascadeAction { diff --git a/src/NHibernate/Event/Default/DefaultRefreshEventListener.cs b/src/NHibernate/Event/Default/DefaultRefreshEventListener.cs index a9c64530ea9..08c4f40da61 100644 --- a/src/NHibernate/Event/Default/DefaultRefreshEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultRefreshEventListener.cs @@ -17,7 +17,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultRefreshEventListener : IRefreshEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultRefreshEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultRefreshEventListener)); public virtual void OnRefresh(RefreshEvent @event) { @@ -52,9 +52,9 @@ public virtual void OnRefresh(RefreshEvent @event, IDictionary refreshedAlready) { persister = source.GetEntityPersister(null, obj); //refresh() does not pass an entityName id = persister.GetIdentifier(obj); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("refreshing transient " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("refreshing transient {0}", MessageHelper.InfoString(persister, id, source.Factory)); } EntityKey key = source.GenerateEntityKey(id, persister); if (source.PersistenceContext.GetEntry(key) != null) @@ -65,9 +65,9 @@ public virtual void OnRefresh(RefreshEvent @event, IDictionary refreshedAlready) } else { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("refreshing " + MessageHelper.InfoString(e.Persister, e.Id, source.Factory)); + log.Debug("refreshing {0}", MessageHelper.InfoString(e.Persister, e.Id, source.Factory)); } if (!e.ExistsInDatabase) { diff --git a/src/NHibernate/Event/Default/DefaultReplicateEventListener.cs b/src/NHibernate/Event/Default/DefaultReplicateEventListener.cs index 359e4b589c4..b274eb929eb 100644 --- a/src/NHibernate/Event/Default/DefaultReplicateEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultReplicateEventListener.cs @@ -13,7 +13,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultReplicateEventListener : AbstractSaveEventListener, IReplicateEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultReplicateEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultReplicateEventListener)); public virtual void OnReplicate(ReplicateEvent @event) { @@ -60,9 +60,9 @@ public virtual void OnReplicate(ReplicateEvent @event) if (oldVersion != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("found existing row for " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("found existing row for {0}", MessageHelper.InfoString(persister, id, source.Factory)); } // HHH-2378 @@ -89,9 +89,9 @@ public virtual void OnReplicate(ReplicateEvent @event) else { // no existing row - do an insert - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("no existing row, replicating new instance " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("no existing row, replicating new instance {0}", MessageHelper.InfoString(persister, id, source.Factory)); } bool regenerate = persister.IsIdentifierAssignedByInsert; // prefer re-generation of identity! @@ -103,9 +103,9 @@ public virtual void OnReplicate(ReplicateEvent @event) private void PerformReplication(object entity, object id, object version, IEntityPersister persister, ReplicationMode replicationMode, IEventSource source) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("replicating changes to " + MessageHelper.InfoString(persister, id, source.Factory)); + log.Debug("replicating changes to {0}", MessageHelper.InfoString(persister, id, source.Factory)); } new OnReplicateVisitor(source, id, entity, true).Process(entity, persister); diff --git a/src/NHibernate/Event/Default/DefaultSaveOrUpdateEventListener.cs b/src/NHibernate/Event/Default/DefaultSaveOrUpdateEventListener.cs index 249e1c8702c..ac654e6afe2 100644 --- a/src/NHibernate/Event/Default/DefaultSaveOrUpdateEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultSaveOrUpdateEventListener.cs @@ -14,7 +14,7 @@ namespace NHibernate.Event.Default [Serializable] public partial class DefaultSaveOrUpdateEventListener : AbstractSaveEventListener, ISaveOrUpdateEventListener { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DefaultSaveOrUpdateEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DefaultSaveOrUpdateEventListener)); protected override CascadingAction CascadeAction { @@ -111,10 +111,10 @@ protected virtual object EntityIsPersistent(SaveOrUpdateEvent @event) savedId = requestedId; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("object already associated with session: " + - MessageHelper.InfoString(entityEntry.Persister, savedId, factory)); + log.Debug("object already associated with session: {0}", + MessageHelper.InfoString(entityEntry.Persister, savedId, factory)); } return savedId; @@ -221,9 +221,9 @@ protected virtual void PerformUpdate(SaveOrUpdateEvent @event, object entity, IE log.Debug("immutable instance passed to PerformUpdate(), locking"); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("updating " + MessageHelper.InfoString(persister, @event.RequestedId, @event.Session.Factory)); + log.Debug("updating {0}", MessageHelper.InfoString(persister, @event.RequestedId, @event.Session.Factory)); } IEventSource source = @event.Session; @@ -267,9 +267,9 @@ protected virtual void PerformUpdate(SaveOrUpdateEvent @event, object entity, IE //persister.AfterReassociate(entity, source); TODO H3.2 not ported - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("updating " + MessageHelper.InfoString(persister, @event.RequestedId, source.Factory)); + log.Debug("updating {0}", MessageHelper.InfoString(persister, @event.RequestedId, source.Factory)); } CascadeOnUpdate(@event, persister, entity); diff --git a/src/NHibernate/Event/Default/EvictVisitor.cs b/src/NHibernate/Event/Default/EvictVisitor.cs index 0de9c1b3984..82501c24d07 100644 --- a/src/NHibernate/Event/Default/EvictVisitor.cs +++ b/src/NHibernate/Event/Default/EvictVisitor.cs @@ -13,7 +13,7 @@ namespace NHibernate.Event.Default /// public partial class EvictVisitor : AbstractVisitor { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(EvictVisitor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(EvictVisitor)); public EvictVisitor(IEventSource session) : base(session) { } @@ -51,8 +51,8 @@ private void EvictCollection(IPersistentCollection collection) { CollectionEntry ce = (CollectionEntry)Session.PersistenceContext.CollectionEntries[collection]; Session.PersistenceContext.CollectionEntries.Remove(collection); - if (log.IsDebugEnabled) - log.Debug("evicting collection: " + MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, Session)); + if (log.IsDebugEnabled()) + log.Debug("evicting collection: {0}", MessageHelper.CollectionInfoString(ce.LoadedPersister, collection, ce.LoadedKey, Session)); if (ce.LoadedPersister != null && ce.LoadedKey != null) { //TODO: is this 100% correct? diff --git a/src/NHibernate/Event/Default/ReattachVisitor.cs b/src/NHibernate/Event/Default/ReattachVisitor.cs index 5beaa009f2c..e2d14ac7d61 100644 --- a/src/NHibernate/Event/Default/ReattachVisitor.cs +++ b/src/NHibernate/Event/Default/ReattachVisitor.cs @@ -14,7 +14,7 @@ public abstract partial class ReattachVisitor : ProxyVisitor { private readonly object ownerIdentifier; private readonly object owner; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(AbstractFlushingEventListener)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AbstractFlushingEventListener)); protected ReattachVisitor(IEventSource session, object ownerIdentifier, object owner) : base(session) @@ -56,9 +56,9 @@ internal override object ProcessComponent(object component, IAbstractComponentTy /// The session from which the request originated. internal void RemoveCollection(ICollectionPersister role, object collectionKey, IEventSource source) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("collection dereferenced while transient " + MessageHelper.CollectionInfoString(role, ownerIdentifier, source.Factory)); + log.Debug("collection dereferenced while transient {0}", MessageHelper.CollectionInfoString(role, ownerIdentifier, source.Factory)); } source.ActionQueue.AddAction(new CollectionRemoveAction(owner, role, collectionKey, false, source)); } @@ -82,4 +82,4 @@ internal object ExtractCollectionKeyFromOwner(ICollectionPersister role) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Event/Default/WrapVisitor.cs b/src/NHibernate/Event/Default/WrapVisitor.cs index 79992853c58..309367aaea2 100644 --- a/src/NHibernate/Event/Default/WrapVisitor.cs +++ b/src/NHibernate/Event/Default/WrapVisitor.cs @@ -12,7 +12,7 @@ namespace NHibernate.Event.Default /// public partial class WrapVisitor : ProxyVisitor { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(WrapVisitor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(WrapVisitor)); private bool substitute = false; public WrapVisitor(IEventSource session) : base(session) { } @@ -85,8 +85,8 @@ private object ProcessArrayOrNewCollection(object collection, CollectionType col IPersistentCollection persistentCollection = collectionType.Wrap(session, collection); persistenceContext.AddNewCollection(persister, persistentCollection); - if (log.IsDebugEnabled) - log.Debug("Wrapped collection in role: " + collectionType.Role); + if (log.IsDebugEnabled()) + log.Debug("Wrapped collection in role: {0}", collectionType.Role); return persistentCollection; //Force a substitution! } diff --git a/src/NHibernate/Exceptions/SQLExceptionConverterFactory.cs b/src/NHibernate/Exceptions/SQLExceptionConverterFactory.cs index e5a7b60c671..5721590e3a2 100644 --- a/src/NHibernate/Exceptions/SQLExceptionConverterFactory.cs +++ b/src/NHibernate/Exceptions/SQLExceptionConverterFactory.cs @@ -9,7 +9,7 @@ namespace NHibernate.Exceptions /// A factory for building SQLExceptionConverter instances. public static class SQLExceptionConverterFactory { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SQLExceptionConverterFactory)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SQLExceptionConverterFactory)); private class MinimalSQLExceptionConverter : ISQLExceptionConverter { @@ -59,7 +59,7 @@ public static ISQLExceptionConverter BuildSQLExceptionConverter(Dialect.Dialect } catch (HibernateException e) { - log.Warn("Unable to configure SQLExceptionConverter", e); + log.Warn(e, "Unable to configure SQLExceptionConverter"); throw; } } @@ -80,7 +80,7 @@ private static ISQLExceptionConverter ConstructConverter(string converterClassNa { try { - log.Debug("Attempting to construct instance of specified SQLExceptionConverter [" + converterClassName + "]"); + log.Debug("Attempting to construct instance of specified SQLExceptionConverter [{0}]", converterClassName); System.Type converterClass = ReflectHelper.ClassForName(converterClassName); // First, try to find a matching constructor accepting a ViolatedConstraintNameExtracter param... @@ -109,7 +109,7 @@ private static ISQLExceptionConverter ConstructConverter(string converterClassNa } catch (Exception t) { - log.Warn("Unable to construct instance of specified SQLExceptionConverter", t); + log.Warn(t, "Unable to construct instance of specified SQLExceptionConverter"); } return null; diff --git a/src/NHibernate/Hql/Ast/ANTLR/ErrorCounter.cs b/src/NHibernate/Hql/Ast/ANTLR/ErrorCounter.cs index 73200662790..0c57c7f33f9 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/ErrorCounter.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/ErrorCounter.cs @@ -11,8 +11,8 @@ namespace NHibernate.Hql.Ast.ANTLR /// internal class ErrorCounter : IParseErrorHandler { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ErrorCounter)); - private static readonly IInternalLogger hqlLog = LoggerProvider.LoggerFor("NHibernate.Hql.Parser"); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ErrorCounter)); + private static readonly INHibernateLogger hqlLog = NHibernateLogger.For("NHibernate.Hql.Parser"); private readonly List _errorList = new List(); private readonly List _warningList = new List(); @@ -22,8 +22,8 @@ public void ReportError(RecognitionException e) { ReportError( e.ToString() ); _recognitionExceptions.Add( e ); - if ( log.IsDebugEnabled ) { - log.Debug( e.ToString(), e ); + if ( log.IsDebugEnabled() ) { + log.Debug(e, e.ToString()); } } @@ -76,7 +76,7 @@ public void ThrowQueryException() else { // all clear - if ( log.IsDebugEnabled ) + if ( log.IsDebugEnabled() ) { log.Debug( "throwQueryException() : no errors" ); } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs b/src/NHibernate/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs index aef68e36729..10954da9925 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs @@ -20,9 +20,9 @@ namespace NHibernate.Hql.Ast.ANTLR.Exec [CLSCompliant(false)] public abstract partial class AbstractStatementExecutor : IStatementExecutor { - private readonly IInternalLogger log; + private readonly INHibernateLogger log; - protected AbstractStatementExecutor(IStatement statement, IInternalLogger log) + protected AbstractStatementExecutor(IStatement statement, INHibernateLogger log) { Statement = statement; Walker = statement.Walker; @@ -202,7 +202,7 @@ protected virtual void DropTemporaryTableIfNecessary(IQueryable persister, ISess } catch (Exception t) { - log.Warn("unable to cleanup temporary id table after use [" + t + "]"); + log.Warn(t, "unable to cleanup temporary id table after use [{0}]", t); } finally { @@ -224,10 +224,10 @@ protected virtual void DropTemporaryTableIfNecessary(IQueryable persister, ISess private partial class TmpIdTableCreationIsolatedWork : IIsolatedWork { private readonly IQueryable persister; - private readonly IInternalLogger log; + private readonly INHibernateLogger log; private readonly ISessionImplementor session; - public TmpIdTableCreationIsolatedWork(IQueryable persister, IInternalLogger log, ISessionImplementor session) + public TmpIdTableCreationIsolatedWork(IQueryable persister, INHibernateLogger log, ISessionImplementor session) { this.persister = persister; this.log = log; @@ -247,7 +247,7 @@ public void DoWork(DbConnection connection, DbTransaction transaction) } catch (Exception t) { - log.Debug("unable to create temporary id table [" + t.Message + "]"); + log.Debug(t, "unable to create temporary id table [{0}]", t.Message); } finally { @@ -268,7 +268,7 @@ public void DoWork(DbConnection connection, DbTransaction transaction) private partial class TmpIdTableDropIsolatedWork : IIsolatedWork { - public TmpIdTableDropIsolatedWork(IQueryable persister, IInternalLogger log, ISessionImplementor session) + public TmpIdTableDropIsolatedWork(IQueryable persister, INHibernateLogger log, ISessionImplementor session) { this.persister = persister; this.log = log; @@ -276,7 +276,7 @@ public TmpIdTableDropIsolatedWork(IQueryable persister, IInternalLogger log, ISe } private readonly IQueryable persister; - private readonly IInternalLogger log; + private readonly INHibernateLogger log; private readonly ISessionImplementor session; public void DoWork(DbConnection connection, DbTransaction transaction) @@ -292,7 +292,7 @@ public void DoWork(DbConnection connection, DbTransaction transaction) } catch (Exception t) { - log.Warn("unable to drop temporary id table after use [" + t.Message + "]"); + log.Warn("unable to drop temporary id table after use [{0}]", t.Message); } finally { @@ -311,4 +311,4 @@ public void DoWork(DbConnection connection, DbTransaction transaction) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Hql/Ast/ANTLR/Exec/BasicExecutor.cs b/src/NHibernate/Hql/Ast/ANTLR/Exec/BasicExecutor.cs index 157b98ed418..f2d87361151 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Exec/BasicExecutor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Exec/BasicExecutor.cs @@ -20,7 +20,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Exec public partial class BasicExecutor : AbstractStatementExecutor { private readonly IQueryable persister; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(BasicExecutor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(BasicExecutor)); private readonly SqlString sql; public BasicExecutor(IStatement statement, IQueryable persister) diff --git a/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs b/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs index 5f0bbcb6503..35c5390d856 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs @@ -16,7 +16,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Exec [CLSCompliant(false)] public partial class MultiTableDeleteExecutor : AbstractStatementExecutor { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(MultiTableDeleteExecutor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(MultiTableDeleteExecutor)); private readonly IQueryable persister; private readonly SqlString idInsertSelect; private readonly SqlString[] deletes; @@ -36,7 +36,7 @@ public MultiTableDeleteExecutor(IStatement statement) persister = fromElement.Queryable; idInsertSelect = GenerateIdInsertSelect(persister, bulkTargetAlias, deleteStatement.WhereClause); - log.Debug("Generated ID-INSERT-SELECT SQL (multi-table delete) : " + idInsertSelect); + log.Debug("Generated ID-INSERT-SELECT SQL (multi-table delete) : {0}", idInsertSelect); string[] tableNames = persister.ConstraintOrderedTableNameClosure; string[][] columnNames = persister.ConstraintOrderedTableKeyColumnClosure; @@ -143,4 +143,4 @@ protected override IQueryable[] AffectedQueryables get { return new[] { persister }; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableUpdateExecutor.cs b/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableUpdateExecutor.cs index 1637b109f10..f658eda198b 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableUpdateExecutor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableUpdateExecutor.cs @@ -18,7 +18,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Exec [CLSCompliant(false)] public partial class MultiTableUpdateExecutor : AbstractStatementExecutor { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (MultiTableDeleteExecutor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (MultiTableDeleteExecutor)); private readonly IQueryable persister; private readonly SqlString idInsertSelect; private readonly SqlString[] updates; @@ -37,7 +37,7 @@ public MultiTableUpdateExecutor(IStatement statement) : base(statement, log) persister = fromElement.Queryable; idInsertSelect = GenerateIdInsertSelect(persister, bulkTargetAlias, updateStatement.WhereClause); - log.Debug("Generated ID-INSERT-SELECT SQL (multi-table update) : " + idInsertSelect); + log.Debug("Generated ID-INSERT-SELECT SQL (multi-table update) : {0}", idInsertSelect); string[] tableNames = persister.ConstraintOrderedTableNameClosure; string[][] columnNames = persister.ConstraintOrderedTableKeyColumnClosure; @@ -185,4 +185,4 @@ protected override IQueryable[] AffectedQueryables get { return new[] {persister}; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Hql/Ast/ANTLR/HqlFilterPreprocessor.cs b/src/NHibernate/Hql/Ast/ANTLR/HqlFilterPreprocessor.cs index d47294c5632..ccb8c9a9fd2 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/HqlFilterPreprocessor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/HqlFilterPreprocessor.cs @@ -13,7 +13,7 @@ namespace NHibernate.Hql.Ast.ANTLR { internal static class HqlFilterPreprocessor { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(HqlFilterPreprocessor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(HqlFilterPreprocessor)); /// /// Handles HQL AST transformation for collection filters (which are created with ). @@ -67,7 +67,7 @@ private static void AddImpliedFromToFromNode(IASTNode fromClause, string collect fromClause.AddChild(alias); // Show the modified AST. - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("AddImpliedFormToFromNode() : Filter - Added 'this' as a from element..."); } diff --git a/src/NHibernate/Hql/Ast/ANTLR/HqlParser.cs b/src/NHibernate/Hql/Ast/ANTLR/HqlParser.cs index ef84f9d8d20..393af308102 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/HqlParser.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/HqlParser.cs @@ -9,7 +9,7 @@ namespace NHibernate.Hql.Ast.ANTLR { public partial class HqlParser { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(HqlParser)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(HqlParser)); internal static readonly bool[] possibleIds; @@ -125,9 +125,9 @@ public void WeakKeywords() if (input.LA(2) != LITERAL_by) { input.LT(1).Type = IDENT; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("weakKeywords() : new LT(1) token - " + input.LT(1)); + log.Debug("weakKeywords() : new LT(1) token - {0}", input.LT(1)); } } break; @@ -139,9 +139,9 @@ public void WeakKeywords() if (hqlToken != null && hqlToken.PossibleId) { hqlToken.Type = IDENT; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("weakKeywords() : new LT(1) token - " + input.LT(1)); + log.Debug("weakKeywords() : new LT(1) token - {0}", input.LT(1)); } } } @@ -170,9 +170,9 @@ public void WeakKeywords2() if (input.LA(2) != LITERAL_by) { input.LT(1).Type = IDENT; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("weakKeywords() : new LT(1) token - " + input.LT(1)); + log.Debug("weakKeywords() : new LT(1) token - {0}", input.LT(1)); } } break; @@ -184,9 +184,9 @@ public void WeakKeywords2() if (hqlToken.PossibleId) { hqlToken.Type = IDENT; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("weakKeywords() : new LT(1) token - " + input.LT(1)); + log.Debug("weakKeywords() : new LT(1) token - {0}", input.LT(1)); } } } @@ -329,9 +329,9 @@ public void HandleDotIdent() { // Set it! input.LT(2).Type = IDENT; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("handleDotIdent() : new LT(2) token - " + input.LT(1)); + log.Debug("handleDotIdent() : new LT(2) token - {0}", input.LT(1)); } } } diff --git a/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs b/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs index e2c66a91f2d..e61542b62ee 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs @@ -19,7 +19,7 @@ namespace NHibernate.Hql.Ast.ANTLR { public partial class HqlSqlWalker { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(HqlSqlWalker)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(HqlSqlWalker)); // Fields private readonly string _collectionFilterRole; @@ -175,17 +175,17 @@ void BeforeStatement(string statementName, int statementType) _statementType = statementType; } _currentStatementType = statementType; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(statementName + " << begin [level=" + _level + ", statement=" + _statementTypeName + "]"); + log.Debug("{0} << begin [level={1}, statement={2}]", statementName, _level, _statementTypeName); } } void BeforeStatementCompletion(string statementName) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(statementName + " : finishing up [level=" + _level + ", statement=" + _statementTypeName + "]"); + log.Debug("{0} : finishing up [level={1}, statement={2}]", statementName, _level, _statementTypeName); } } @@ -399,9 +399,9 @@ private void PostProcessDML(IRestrictableStatement statement) void AfterStatementCompletion(string statementName) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(statementName + " >> end [level=" + _level + ", statement=" + _statementTypeName + "]"); + log.Debug("{0} >> end [level={1}, statement={2}]", statementName, _level, _statementTypeName); } _level--; } @@ -456,8 +456,8 @@ IASTNode Resolve(IASTNode node) void ProcessQuery(IASTNode select, IASTNode query) { - if ( log.IsDebugEnabled ) { - log.Debug( "processQuery() : " + query.ToStringTree() ); + if ( log.IsDebugEnabled() ) { + log.Debug("processQuery() : {0}", query.ToStringTree()); } try { @@ -529,7 +529,7 @@ private void CreateSelectClauseFromFromClause(IASTNode qn) _selectClause = ( SelectClause ) qn.GetChild(0); _selectClause.InitializeDerivedSelectClause( _currentFromClause ); - if ( log.IsDebugEnabled ) + if ( log.IsDebugEnabled() ) { log.Debug( "Derived SELECT clause created." ); } @@ -715,9 +715,9 @@ void CreateFromJoinElement( } } - if ( log.IsDebugEnabled ) + if ( log.IsDebugEnabled() ) { - log.Debug( "createFromJoinElement() : " + _printer.ShowAsString( fromElement, "-- join tree --" ) ); + log.Debug("createFromJoinElement() : {0}", _printer.ShowAsString( fromElement, "-- join tree --" )); } } @@ -766,7 +766,7 @@ IASTNode CreateFromFilterElement(IASTNode filterEntity, IASTNode alias) fromElement.JoinSequence = join; fromElement.Filter = true; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("createFromFilterElement() : processed filter FROM element."); } @@ -844,7 +844,7 @@ bool IsNonQualifiedPropertyRef(IASTNode ident) { FromElement fromElement = (FromElement) fromElements[0]; - log.Info( "attempting to resolve property [" + identText + "] as a non-qualified ref" ); + log.Info("attempting to resolve property [{0}] as a non-qualified ref", identText); IType type; return fromElement.GetPropertyMapping(identText).TryToType(identText, out type); @@ -1067,9 +1067,9 @@ private void HandleWithFragment(FromElement fromElement, IASTNode hqlWithNode) IASTNode hqlSqlWithNode = (IASTNode) withClause().Tree; input = old; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("handleWithFragment() : " + _printer.ShowAsString(hqlSqlWithNode, "-- with clause --")); + log.Debug("handleWithFragment() : {0}", _printer.ShowAsString(hqlSqlWithNode, "-- with clause --")); } WithClauseVisitor visitor = new WithClauseVisitor(fromElement); NodeTraverser traverser = new NodeTraverser(visitor); diff --git a/src/NHibernate/Hql/Ast/ANTLR/QueryTranslatorImpl.cs b/src/NHibernate/Hql/Ast/ANTLR/QueryTranslatorImpl.cs index 18e3e68e33b..9f0a412921d 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/QueryTranslatorImpl.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/QueryTranslatorImpl.cs @@ -23,7 +23,7 @@ namespace NHibernate.Hql.Ast.ANTLR [CLSCompliant(false)] public partial class QueryTranslatorImpl : IFilterTranslator { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(QueryTranslatorImpl)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(QueryTranslatorImpl)); private readonly string _queryIdentifier; private readonly IASTNode _stageOneAst; @@ -310,7 +310,7 @@ private void DoCompile(IDictionary replacements, bool shallow, S // If the query is already compiled, skip the compilation. if ( _compiled ) { - if ( log.IsDebugEnabled ) + if ( log.IsDebugEnabled() ) { log.Debug( "compile() : The query is already compiled, skipping..." ); } @@ -364,9 +364,9 @@ private void DoCompile(IDictionary replacements, bool shallow, S { // we do not actually propogate ANTLRExceptions as a cause, so // log it here for diagnostic purposes - if ( log.IsInfoEnabled ) + if ( log.IsInfoEnabled() ) { - log.Info( "converted antlr.RecognitionException", e ); + log.Info(e, "converted antlr.RecognitionException"); } throw QuerySyntaxException.Convert(e, _queryIdentifier); } @@ -436,7 +436,7 @@ private void ErrorIfDML() public class HqlParseEngine { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(HqlParseEngine)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(HqlParseEngine)); private readonly string _hql; private CommonTokenStream _tokens; @@ -458,9 +458,9 @@ public IASTNode Parse() var parser = new HqlParser(_tokens) {TreeAdaptor = new ASTTreeAdaptor(), Filter = _filter}; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("parse() - HQL: " + _hql); + log.Debug("parse() - HQL: {0}", _hql); } try @@ -580,7 +580,7 @@ public IStatement Translate() internal class HqlSqlGenerator { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(HqlSqlGenerator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(HqlSqlGenerator)); private readonly IASTNode _ast; private readonly ISessionFactoryImplementor _sfi; @@ -615,9 +615,9 @@ public SqlString Generate() _sql = gen.GetSQL(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("SQL: " + _sql); + log.Debug("SQL: {0}", _sql); } } finally diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/AbstractRestrictableStatement.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/AbstractRestrictableStatement.cs index 779db12d5f3..2d5b1f429d9 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/AbstractRestrictableStatement.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/AbstractRestrictableStatement.cs @@ -15,7 +15,7 @@ protected AbstractRestrictableStatement(IToken token) : base(token) { } - protected abstract IInternalLogger GetLog(); + protected abstract INHibernateLogger GetLog(); protected abstract int GetWhereClauseParentTokenType(); public FromClause FromClause diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/DeleteStatement.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/DeleteStatement.cs index 84633d87348..a1b485a2c43 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/DeleteStatement.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/DeleteStatement.cs @@ -11,7 +11,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class DeleteStatement : AbstractRestrictableStatement { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(DeleteStatement)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(DeleteStatement)); public DeleteStatement(IToken token) : base(token) {} @@ -25,7 +25,7 @@ public override int StatementType get { return HqlSqlWalker.DELETE; } } - protected override IInternalLogger GetLog() + protected override INHibernateLogger GetLog() { return Log; } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/DotNode.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/DotNode.cs index 5ad151a4da5..8e25ba37fd9 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/DotNode.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/DotNode.cs @@ -20,7 +20,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class DotNode : FromReferenceNode { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(DotNode)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(DotNode)); private const int DerefUnknown = 0; private const int DerefEntity = 1; @@ -268,9 +268,9 @@ private IType GetDataType() // If the lhs is a collection, use CollectionPropertyMapping IType propertyType = fromElement.GetPropertyType(_propertyName, _propertyPath); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("getDataType() : " + _propertyPath + " -> " + propertyType); + Log.Debug("getDataType() : {0} -> {1}", _propertyPath, propertyType); } DataType = propertyType; @@ -334,9 +334,9 @@ private void DereferenceCollection(CollectionType collectionType, bool implicitJ ); FromElement elem = factory.CreateCollection( queryableCollection, role, _joinType, _fetch, indexed ); - if ( Log.IsDebugEnabled ) + if ( Log.IsDebugEnabled() ) { - Log.Debug( "dereferenceCollection() : Created new FROM element for " + propName + " : " + elem ); + Log.Debug("dereferenceCollection() : Created new FROM element for {0} : {1}", propName, elem); } SetImpliedJoin( elem ); @@ -426,11 +426,11 @@ private void DereferenceEntityIdentifier(string propertyName, DotNode dotParent) { // special shortcut for id properties, skip the join! // this must only occur at the _end_ of a path expression - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("dereferenceShortcut() : property " + - propertyName + " in " + FromElement.ClassName + - " does not require a join."); + Log.Debug("dereferenceShortcut() : property {0} in {1} does not require a join.", + propertyName, + FromElement.ClassName); } InitText(); @@ -447,13 +447,13 @@ private void DereferenceEntityIdentifier(string propertyName, DotNode dotParent) private void DereferenceEntityJoin(string classAlias, EntityType propertyType, bool impliedJoin, IASTNode parent) { _dereferenceType = DerefEntity; - if ( Log.IsDebugEnabled ) + if ( Log.IsDebugEnabled() ) { - Log.Debug( "dereferenceEntityJoin() : generating join for " + _propertyName + " in " - + FromElement.ClassName + " " - + ( ( classAlias == null ) ? "{no alias}" : "(" + classAlias + ")" ) - + " parent = " + ASTUtil.GetDebugstring( parent ) - ); + Log.Debug( "dereferenceEntityJoin() : generating join for {0} in {1} {2} parent = {3}", + _propertyName, + FromElement.ClassName, + ( ( classAlias == null ) ? "{no alias}" : "(" + classAlias + ")" ), + ASTUtil.GetDebugstring( parent )); } // Create a new FROM node for the referenced class. @@ -599,9 +599,9 @@ private void CheckForCorrelatedSubquery(string methodName) { if (IsCorrelatedSubselect) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug(methodName + "() : correlated subquery"); + Log.Debug("{0}() : correlated subquery", methodName); } } } @@ -644,16 +644,16 @@ private void SetPropertyNameAndPath(IASTNode parent) _propertyName = rhs.Text; _propertyPath = _propertyPath + "." + _propertyName; // Append the new property name onto the unresolved path. dotNode._propertyPath = _propertyPath; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Unresolved property path is now '" + dotNode._propertyPath + "'"); + Log.Debug("Unresolved property path is now '{0}'", dotNode._propertyPath); } } else { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("terminal propertyPath = [" + _propertyPath + "]"); + Log.Debug("terminal propertyPath = [{0}]", _propertyPath); } } } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromClause.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromClause.cs index 0707c72c694..4f182051a85 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromClause.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromClause.cs @@ -17,7 +17,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class FromClause : HqlSqlWalkerNode, IDisplayableNode { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(FromClause)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(FromClause)); private const int RootLevel = 1; private int _level = RootLevel; @@ -130,9 +130,9 @@ public bool ContainsTableAlias(String alias) public void AddJoinByPathMap(string path, FromElement destination) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("addJoinByPathMap() : " + path + " -> " + destination); + Log.Debug("addJoinByPathMap() : {0} -> {1}", path, destination); } _fromElementsByPath.Add(path, destination); @@ -140,9 +140,9 @@ public void AddJoinByPathMap(string path, FromElement destination) public void AddCollectionJoinFromElementByPath(string path, FromElement destination) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("addCollectionJoinFromElementByPath() : " + path + " -> " + destination); + Log.Debug("addCollectionJoinFromElementByPath() : {0} -> {1}", path, destination); } _collectionJoinFromElementsByPath.Add(path, destination); // Add the new node to the map so that we don't create it twice. } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElement.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElement.cs index b81162e8617..cb33b0a6052 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElement.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElement.cs @@ -18,7 +18,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class FromElement : HqlSqlWalkerNode, IDisplayableNode, IParameterContainer { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(FromElement)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(FromElement)); private bool _isAllPropertyFetch; private FromElementType _elementType; @@ -389,9 +389,9 @@ public virtual bool IncludeSubclasses { if (IsDereferencedBySuperclassOrSubclassProperty) { - if (!_includeSubclasses && Log.IsInfoEnabled) + if (!_includeSubclasses && Log.IsInfoEnabled()) { - Log.Info("attempt to disable subclass-inclusions", new Exception("stack-trace source")); + Log.Info(new Exception("stack-trace source"), "attempt to disable subclass-inclusions"); } } _includeSubclasses = value; @@ -530,9 +530,9 @@ public void HandlePropertyBeingDereferenced(IType propertySource, string propert { Declarer propertyDeclarer = persister.GetSubclassPropertyDeclarer(propertyName); - if (Log.IsInfoEnabled) + if (Log.IsInfoEnabled()) { - Log.Info("handling property dereference [" + persister.EntityName + " (" + ClassAlias + ") -> " + propertyName + " (" + propertyDeclarer + ")]"); + Log.Info("handling property dereference [{0} ({1}) -> {2} ({3})]", persister.EntityName, ClassAlias, propertyName, propertyDeclarer); } if (propertyDeclarer == Declarer.SubClass) { @@ -595,9 +595,9 @@ public void SetIncludeSubclasses(bool includeSubclasses) { if (IsDereferencedBySuperclassOrSubclassProperty) { - if (!includeSubclasses && Log.IsInfoEnabled) + if (!includeSubclasses && Log.IsInfoEnabled()) { - Log.Info("attempt to disable subclass-inclusions", new Exception("stack-trace source")); + Log.Info(new Exception("stack-trace source"), "attempt to disable subclass-inclusions"); } } _includeSubclasses = includeSubclasses; @@ -688,10 +688,13 @@ private void DoInitialize(FromClause fromClause, string tableAlias, string class // Register the FromElement with the FROM clause, now that we have the names and aliases. fromClause.RegisterFromElement(this); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug(fromClause + " : " + className + " (" - + (classAlias ?? "no alias") + ") -> " + tableAlias); + Log.Debug("{0} : {1} ({2}) -> {3}", + fromClause, + className, + (classAlias ?? "no alias"), + tableAlias); } } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElementFactory.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElementFactory.cs index 98349e7f739..509d9cbbd4a 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElementFactory.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElementFactory.cs @@ -13,7 +13,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class FromElementFactory { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(FromElementFactory)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(FromElementFactory)); private readonly FromClause _fromClause; private readonly FromElement _origin; @@ -107,9 +107,9 @@ private FromElement CreateFromElementInSubselect( FromElement parentFromElement, string classAlias) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("createFromElementInSubselect() : path = " + path); + Log.Debug("createFromElementInSubselect() : path = {0}", path); } // Create an DotNode AST for the path and resolve it. @@ -126,7 +126,7 @@ private FromElement CreateFromElementInSubselect( // If the from element isn't in the same clause, create a new from element. if (fromElement.FromClause != _fromClause) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { Log.Debug("createFromElementInSubselect() : creating a new FROM element..."); } @@ -141,9 +141,9 @@ private FromElement CreateFromElementInSubselect( tableAlias ); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("createFromElementInSubselect() : " + path + " -> " + fromElement); + Log.Debug("createFromElementInSubselect() : {0} -> {1}", path, fromElement); } return fromElement; @@ -298,7 +298,7 @@ public FromElement CreateEntityJoin( // multi-table entity if (_implied && !elem.UseFromFragment) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { Log.Debug("createEntityJoin() : Implied entity join"); } @@ -343,9 +343,9 @@ private FromElement CreateEntityAssociation( // Get the class name of the associated entity. if (_queryableCollection.IsOneToMany) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("createEntityAssociation() : One to many - path = " + _path + " role = " + role + " associatedEntityName = " + associatedEntityName); + Log.Debug("createEntityAssociation() : One to many - path = {0} role = {1} associatedEntityName = {2}", _path, role, associatedEntityName); } var joinSequence = CreateJoinSequence(roleAlias, joinType); @@ -355,9 +355,9 @@ private FromElement CreateEntityAssociation( } else { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("createManyToMany() : path = " + _path + " role = " + role + " associatedEntityName = " + associatedEntityName); + Log.Debug("createManyToMany() : path = {0} role = {1} associatedEntityName = {2}", _path, role, associatedEntityName); } elem = CreateManyToMany(role, associatedEntityName, roleAlias, entityPersister, (EntityType)_queryableCollection.ElementType, joinType); diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElementType.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElementType.cs index 2cfa0c8fda6..8be86e92808 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElementType.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromElementType.cs @@ -19,7 +19,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class FromElementType { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(FromElementType)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(FromElementType)); private readonly FromElement _fromElement; private readonly IEntityPersister _persister; @@ -373,9 +373,9 @@ public string[] ToColumns(string tableAlias, string path, bool inSelect, bool fo enabledFilters, propertyMapping.ToColumns(tableAlias, path) ); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("toColumns(" + tableAlias + "," + path + ") : subquery = " + subquery); + Log.Debug("toColumns({0},{1}) : subquery = {2}", tableAlias, path, subquery); } return new [] { "(" + subquery + ")" }; } @@ -427,7 +427,7 @@ public string[] ToColumns(string tableAlias, string path, bool inSelect, bool fo else { string[] columns = propertyMapping.ToColumns(path); - Log.Info("Using non-qualified column reference [" + path + " -> (" + ArrayHelper.ToString(columns) + ")]"); + Log.Info("Using non-qualified column reference [{0} -> ({1})]", path, ArrayHelper.ToString(columns)); return columns; } } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromReferenceNode.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromReferenceNode.cs index 3100014f370..94ecc061188 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/FromReferenceNode.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/FromReferenceNode.cs @@ -8,7 +8,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public abstract class FromReferenceNode : AbstractSelectExpression, IResolvableNode, IDisplayableNode, IPathNode { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(FromReferenceNode)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(FromReferenceNode)); public const int RootLevel = 0; private FromElement _fromElement; @@ -35,9 +35,9 @@ public bool IsResolved set { _resolved = true; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Resolved : " + Path + " -> " + Text); + Log.Debug("Resolved : {0} -> {1}", Path, Text); } } } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/IndexNode.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/IndexNode.cs index cbf13aed98c..f938c173b93 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/IndexNode.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/IndexNode.cs @@ -19,7 +19,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class IndexNode : FromReferenceNode { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(IndexNode)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(IndexNode)); public IndexNode(IToken token) : base(token) { @@ -70,17 +70,18 @@ public override void Resolve(bool generateJoin, bool implicitJoin, string class { FromElementFactory factory = new FromElementFactory( fromClause, fromElement, path ); elem = factory.CreateCollectionElementsJoin( queryableCollection, elementTable ); - if ( Log.IsDebugEnabled ) + if ( Log.IsDebugEnabled() ) { - Log.Debug( "No FROM element found for the elements of collection join path " + path - + ", created " + elem ); + Log.Debug( "No FROM element found for the elements of collection join path {0}, created {1}", + path, + elem); } } else { - if ( Log.IsDebugEnabled ) + if ( Log.IsDebugEnabled() ) { - Log.Debug( "FROM element found for collection join path " + path ); + Log.Debug("FROM element found for collection join path {0}", path); } } @@ -170,9 +171,9 @@ public override void PrepareForDot(string propertyName) FromReferenceNode collectionNode = ( FromReferenceNode ) GetChild(0); String path = collectionNode.Path + "[]." + propertyName; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug( "Creating join for many-to-many elements for " + path ); + Log.Debug("Creating join for many-to-many elements for {0}", path); } FromElementFactory factory = new FromElementFactory( fromElement.FromClause, fromElement, path ); diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/MethodNode.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/MethodNode.cs index 97df3b405f0..f36ac08ff69 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/MethodNode.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/MethodNode.cs @@ -16,7 +16,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class MethodNode : AbstractSelectExpression { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(MethodNode)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(MethodNode)); private string[] _selectColumns; private string _methodName; @@ -146,9 +146,9 @@ private void CollectionProperty(IASTNode path, IASTNode name) var expr = ( SqlNode ) path; IType type = expr.DataType; - if ( Log.IsDebugEnabled ) + if ( Log.IsDebugEnabled() ) { - Log.Debug( "collectionProperty() : name=" + name + " type=" + type ); + Log.Debug("collectionProperty() : name={0} type={1}", name, type); } ResolveCollectionProperty( expr ); @@ -176,7 +176,7 @@ private void HandleElements(FromReferenceNode collectionNode, String propertyNam IQueryableCollection queryableCollection = collectionFromElement.QueryableCollection; String path = collectionNode.Path + "[]." + propertyName; - Log.Debug("Creating elements for " + path); + Log.Debug("Creating elements for {0}", path); _fromElement = collectionFromElement; if (!collectionFromElement.IsCollectionOfValuesOrComponents) diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/QueryNode.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/QueryNode.cs index 0e43b810af7..f6f002f38fe 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/QueryNode.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/QueryNode.cs @@ -9,7 +9,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class QueryNode : AbstractRestrictableStatement, ISelectExpression { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(QueryNode)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(QueryNode)); private OrderByClause _orderByClause; @@ -19,7 +19,7 @@ public QueryNode(IToken token) : base(token) { } - protected override IInternalLogger GetLog() + protected override INHibernateLogger GetLog() { return Log; } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/UpdateStatement.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/UpdateStatement.cs index 7106944227b..476c322413a 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/UpdateStatement.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/UpdateStatement.cs @@ -12,7 +12,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Tree [CLSCompliant(false)] public class UpdateStatement : AbstractRestrictableStatement { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof (UpdateStatement)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof (UpdateStatement)); public UpdateStatement(IToken token) : base(token) {} @@ -31,7 +31,7 @@ public IASTNode SetClause get { return ASTUtil.FindTypeInChildren(this, HqlSqlWalker.SET); } } - protected override IInternalLogger GetLog() + protected override INHibernateLogger GetLog() { return Log; } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Util/JoinProcessor.cs b/src/NHibernate/Hql/Ast/ANTLR/Util/JoinProcessor.cs index 2774ea39477..e83043d04e4 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Util/JoinProcessor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Util/JoinProcessor.cs @@ -24,7 +24,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Util [CLSCompliant(false)] public class JoinProcessor { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(JoinProcessor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(JoinProcessor)); private readonly HqlSqlWalker _walker; private readonly SyntheticAndFactory _syntheticAndFactory; @@ -124,9 +124,9 @@ private void AddJoinNodes(QueryNode query, JoinSequence join, FromElement fromEl if ( fromElement.UseFromFragment /*&& StringHelper.isNotEmpty( frag )*/ ) { SqlString fromFragment = ProcessFromFragment( frag, join ).Trim(); - if ( log.IsDebugEnabled ) + if ( log.IsDebugEnabled() ) { - log.Debug( "Using FROM fragment [" + fromFragment + "]" ); + log.Debug("Using FROM fragment [{0}]", fromFragment); } ProcessDynamicFilterParameters(fromFragment,fromElement,_walker); @@ -200,7 +200,7 @@ public bool IncludeSubclasses(string alias) if ( _fromElement.IsDereferencedBySubclassProperty) { // TODO : or should we return 'containsTableAlias'?? - log.Info( "forcing inclusion of extra joins [alias=" + alias + ", containsTableAlias=" + containsTableAlias + "]" ); + log.Info("forcing inclusion of extra joins [alias={0}, containsTableAlias={1}]", alias, containsTableAlias); return true; } bool shallowQuery = _walker.IsShallowQuery; diff --git a/src/NHibernate/Hql/Ast/ANTLR/Util/LiteralProcessor.cs b/src/NHibernate/Hql/Ast/ANTLR/Util/LiteralProcessor.cs index 8cbbab7ca44..8e84bd4ff76 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Util/LiteralProcessor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Util/LiteralProcessor.cs @@ -17,7 +17,7 @@ public class LiteralProcessor public const string ErrorCannotDetermineType = "Could not determine type of: "; public const string ErrorCannotFormatLiteral = "Could not format constant value to SQL literal: "; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(LiteralProcessor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(LiteralProcessor)); private readonly HqlSqlWalker _walker; private static readonly IDecimalFormatter[] _formatters = new IDecimalFormatter[] { @@ -95,7 +95,7 @@ public void ProcessNumericLiteral(SqlNode literal) } else { - log.Warn("Unexpected literal token type [" + literal.Type + "] passed for numeric processing"); + log.Warn("Unexpected literal token type [{0}] passed for numeric processing", literal.Type); } } @@ -223,13 +223,11 @@ private static string DetermineIntegerRepresentation(string text, int type) } catch (FormatException) { - log.Info("could not format incoming text [" + text - + "] as a NUM_INT; assuming numeric overflow and attempting as NUM_LONG"); + log.Info("could not format incoming text [{0}] as a NUM_INT; assuming numeric overflow and attempting as NUM_LONG", text); } catch (OverflowException) { - log.Info("could not format incoming text [" + text - + "] as a NUM_INT; assuming numeric overflow and attempting as NUM_LONG"); + log.Info("could not format incoming text [{0}] as a NUM_INT; assuming numeric overflow and attempting as NUM_LONG", text); } } @@ -249,9 +247,9 @@ private void ProcessLiteral(SqlNode constant) { if (replacement != null) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("processConstant() : Replacing '" + constant.Text + "' with '" + replacement + "'"); + log.Debug("processConstant() : Replacing '{0}' with '{1}'", constant.Text, replacement); } constant.Text = replacement; } @@ -260,9 +258,9 @@ private void ProcessLiteral(SqlNode constant) private static void SetSQLValue(DotNode node, string text, string value) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("setSQLValue() " + text + " -> " + value); + log.Debug("setSQLValue() {0} -> {1}", text, value); } node.ClearChildren(); // Chop off the rest of the tree. node.Type = HqlSqlWalker.SQL_TOKEN; @@ -272,9 +270,9 @@ private static void SetSQLValue(DotNode node, string text, string value) private void SetConstantValue(DotNode node, string text, object value) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("setConstantValue() " + text + " -> " + value + " " + value.GetType().Name); + log.Debug("setConstantValue() {0} -> {1} {2}", text, value, value.GetType().Name); } node.ClearChildren(); // Chop off the rest of the tree. diff --git a/src/NHibernate/Hql/Ast/ANTLR/Util/PathHelper.cs b/src/NHibernate/Hql/Ast/ANTLR/Util/PathHelper.cs index 97d7401371c..ada464887af 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Util/PathHelper.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Util/PathHelper.cs @@ -8,7 +8,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Util [CLSCompliant(false)] public static class PathHelper { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(PathHelper)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(PathHelper)); /// /// Turns a path into an AST. @@ -33,9 +33,9 @@ public static IASTNode ParsePath(string path, IASTFactory factory) lhs = factory.CreateNode(HqlSqlWalker.DOT, ".", lhs, child); } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("parsePath() : " + path + " -> " + ASTUtil.GetDebugstring(lhs)); + log.Debug("parsePath() : {0} -> {1}", path, ASTUtil.GetDebugstring(lhs)); } return lhs; } diff --git a/src/NHibernate/Hql/Ast/ANTLR/Util/SyntheticAndFactory.cs b/src/NHibernate/Hql/Ast/ANTLR/Util/SyntheticAndFactory.cs index a2033519066..b3bf94fae28 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Util/SyntheticAndFactory.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Util/SyntheticAndFactory.cs @@ -18,7 +18,7 @@ namespace NHibernate.Hql.Ast.ANTLR.Util [CLSCompliant(false)] public class SyntheticAndFactory { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SyntheticAndFactory)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SyntheticAndFactory)); private readonly HqlSqlWalker _hqlSqlWalker; private IASTNode _filters; private IASTNode _thetaJoins; @@ -58,7 +58,7 @@ public void AddWhereFragment( whereFragment = whereFragment.Substring(4); } - log.Debug("Using unprocessed WHERE-fragment [" + whereFragment +"]"); + log.Debug("Using unprocessed WHERE-fragment [{0}]", whereFragment); SqlFragment fragment = (SqlFragment) Create(HqlSqlWalker.SQL_TOKEN, whereFragment.ToString()); @@ -94,7 +94,7 @@ public void AddWhereFragment( hqlSqlWalker ); - log.Debug("Using processed WHERE-fragment [" + fragment.Text + "]"); + log.Debug("Using processed WHERE-fragment [{0}]", fragment.Text); // Filter conditions need to be inserted before the HQL where condition and the // theta join node. This is because org.hibernate.loader.Loader binds the filter parameters first, diff --git a/src/NHibernate/Hql/QuerySplitter.cs b/src/NHibernate/Hql/QuerySplitter.cs index 4a948d94c90..ab7022bafb7 100644 --- a/src/NHibernate/Hql/QuerySplitter.cs +++ b/src/NHibernate/Hql/QuerySplitter.cs @@ -10,7 +10,7 @@ namespace NHibernate.Hql { public class QuerySplitter { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(QuerySplitter)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(QuerySplitter)); private static readonly HashSet beforeClassTokens = new HashSet(); private static readonly HashSet notAfterClassTokens = new HashSet(); @@ -116,7 +116,7 @@ public static string[] ConcreteQueries(string query, ISessionFactoryImplementor StringHelper.Multiply(templateQuery.ToString(), placeholders, replacements); if (results.Length == 0) { - log.Warn("no persistent classes found for query class: " + query); + log.Warn("no persistent classes found for query class: {0}", query); } return results; } @@ -127,4 +127,4 @@ private static bool IsPossiblyClassName(string last, string next) (beforeClassTokens.Contains(last) && !notAfterClassTokens.Contains(next)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/Enhanced/OptimizerFactory.cs b/src/NHibernate/Id/Enhanced/OptimizerFactory.cs index f3da325d5f3..6305aebeb52 100644 --- a/src/NHibernate/Id/Enhanced/OptimizerFactory.cs +++ b/src/NHibernate/Id/Enhanced/OptimizerFactory.cs @@ -7,7 +7,7 @@ namespace NHibernate.Id.Enhanced { public partial class OptimizerFactory { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(OptimizerFactory)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(OptimizerFactory)); public const string None = "none"; public const string HiLo = "hilo"; @@ -74,9 +74,9 @@ private static IOptimizer BuildOptimizer(string type, System.Type returnClass, i return (IOptimizer)ctor.Invoke(new object[] { returnClass, incrementSize }); } - catch (Exception) + catch (Exception ex) { - Log.Error("Unable to instantiate id generator optimizer."); // FIXME: Review log message. + Log.Error(ex, "Unable to instantiate id generator optimizer."); // FIXME: Review log message. } // the default... @@ -108,9 +108,9 @@ public HiLoOptimizer(System.Type returnClass, int incrementSize) : base(returnCl { throw new HibernateException("increment size cannot be less than 1"); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Creating hilo optimizer with [incrementSize=" + incrementSize + "; returnClass=" + returnClass.FullName + "]"); + Log.Debug("Creating hilo optimizer with [incrementSize={0}; returnClass={1}]", incrementSize, returnClass.FullName); } } @@ -274,9 +274,9 @@ public PooledOptimizer(System.Type returnClass, int incrementSize) : base(return { throw new HibernateException("increment size cannot be less than 1"); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Creating pooled optimizer with [incrementSize=" + incrementSize + "; returnClass=" + returnClass.FullName + "]"); + Log.Debug("Creating pooled optimizer with [incrementSize={0}; returnClass={1}]", incrementSize, returnClass.FullName); } } @@ -315,7 +315,7 @@ public override object Generate(IAccessCallback callback) // to 1 as an initial value like we do the others // because we would not be able to control this if // we are using a sequence... - Log.Info("pooled optimizer source reported [" + _value + "] as the initial value; use of 1 or greater highly recommended"); + Log.Info("pooled optimizer source reported [{0}] as the initial value; use of 1 or greater highly recommended", _value); } if ((_initialValue == -1 && _value < IncrementSize) || _value == _initialValue) @@ -350,9 +350,9 @@ public PooledLoOptimizer(System.Type returnClass, int incrementSize) : base(retu { throw new HibernateException("increment size cannot be less than 1"); } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.DebugFormat("Creating pooled optimizer (lo) with [incrementSize={0}; returnClass={1}]", incrementSize, returnClass.FullName); + Log.Debug("Creating pooled optimizer (lo) with [incrementSize={0}; returnClass={1}]", incrementSize, returnClass.FullName); } } @@ -391,4 +391,4 @@ public long LastValue #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/Enhanced/SequenceStructure.cs b/src/NHibernate/Id/Enhanced/SequenceStructure.cs index 6f0b8a942d5..50d70e54964 100644 --- a/src/NHibernate/Id/Enhanced/SequenceStructure.cs +++ b/src/NHibernate/Id/Enhanced/SequenceStructure.cs @@ -14,7 +14,7 @@ namespace NHibernate.Id.Enhanced /// public partial class SequenceStructure : IDatabaseStructure { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(SequenceStructure)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(SequenceStructure)); private readonly int _incrementSize; private readonly int _initialValue; @@ -107,9 +107,9 @@ public virtual long GetNextValue() { rs.Read(); long result = Convert.ToInt64(rs.GetValue(0)); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Sequence value obtained: " + result); + Log.Debug("Sequence value obtained: {0}", result); } return result; } @@ -141,4 +141,4 @@ public virtual long GetNextValue() #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/Enhanced/SequenceStyleGenerator.cs b/src/NHibernate/Id/Enhanced/SequenceStyleGenerator.cs index 3a3d310f2ff..dd252771364 100644 --- a/src/NHibernate/Id/Enhanced/SequenceStyleGenerator.cs +++ b/src/NHibernate/Id/Enhanced/SequenceStyleGenerator.cs @@ -63,7 +63,7 @@ namespace NHibernate.Id.Enhanced /// public partial class SequenceStyleGenerator : IPersistentIdentifierGenerator, IConfigurable { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(SequenceStyleGenerator)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(SequenceStyleGenerator)); public const string DefaultSequenceName = "hibernate_sequence"; public const int DefaultInitialValue = 1; @@ -194,7 +194,8 @@ protected int DetermineAdjustedIncrementSize(string optimizationStrategy, int in { if (OptimizerFactory.None.Equals(optimizationStrategy) && incrementSize > 1) { - Log.Warn("config specified explicit optimizer of [" + OptimizerFactory.None + "], but [" + IncrementParam + "=" + incrementSize + "; honoring optimizer setting"); + Log.Warn("config specified explicit optimizer of [{0}], but [{1}={2}; honoring optimizer setting", + OptimizerFactory.None, IncrementParam, incrementSize); incrementSize = 1; } return incrementSize; @@ -253,4 +254,4 @@ public virtual string[] SqlDropString(Dialect.Dialect dialect) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/Enhanced/TableGenerator.cs b/src/NHibernate/Id/Enhanced/TableGenerator.cs index 7becfb6d7c9..ff69ab2af97 100644 --- a/src/NHibernate/Id/Enhanced/TableGenerator.cs +++ b/src/NHibernate/Id/Enhanced/TableGenerator.cs @@ -87,7 +87,7 @@ namespace NHibernate.Id.Enhanced /// public partial class TableGenerator : TransactionHelper, IPersistentIdentifierGenerator, IConfigurable { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SequenceStyleGenerator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SequenceStyleGenerator)); public const string ConfigPreferSegmentPerEntity = "prefer_entity_table_as_segment_value"; @@ -325,7 +325,7 @@ protected string DetermineDefaultSegmentValue(IDictionary parms) bool preferSegmentPerEntity = PropertiesHelper.GetBoolean(ConfigPreferSegmentPerEntity, parms, false); string defaultToUse = preferSegmentPerEntity ? parms[PersistentIdGeneratorParmsNames.Table] : DefaultSegmentValue; - log.DebugFormat("Explicit segment value for id generator [{0}.{1}] suggested; using default [{2}].", TableName, SegmentColumnName, defaultToUse); + log.Debug("Explicit segment value for id generator [{0}.{1}] suggested; using default [{2}].", TableName, SegmentColumnName, defaultToUse); return defaultToUse; } @@ -479,7 +479,7 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D } catch (Exception ex) { - log.Error("Unable to read or initialize hi value in " + TableName, ex); + log.Error(ex, "Unable to read or initialize hi value in {0}", TableName); throw; } @@ -502,7 +502,7 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D } catch (Exception ex) { - log.Error("Unable to update hi value in " + TableName, ex); + log.Error(ex, "Unable to update hi value in {0}", TableName); throw; } } diff --git a/src/NHibernate/Id/Enhanced/TableStructure.cs b/src/NHibernate/Id/Enhanced/TableStructure.cs index 3b272208e36..82c36b43a65 100644 --- a/src/NHibernate/Id/Enhanced/TableStructure.cs +++ b/src/NHibernate/Id/Enhanced/TableStructure.cs @@ -14,7 +14,7 @@ namespace NHibernate.Id.Enhanced /// public partial class TableStructure : TransactionHelper, IDatabaseStructure { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(IDatabaseStructure)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(IDatabaseStructure)); private readonly int _incrementSize; private readonly int _initialValue; @@ -120,15 +120,14 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D if (selectedValue ==null) { - string err = "could not read a hi value - you need to populate the table: " + _tableName; - Log.Error(err); - throw new IdentifierGenerationException(err); + Log.Error("could not read a hi value - you need to populate the table: {0}", _tableName); + throw new IdentifierGenerationException("could not read a hi value - you need to populate the table: " + _tableName); } result = Convert.ToInt64(selectedValue); } catch (Exception sqle) { - Log.Error("could not read a hi value", sqle); + Log.Error(sqle, "could not read a hi value"); throw; } @@ -149,7 +148,7 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D } catch (Exception sqle) { - Log.Error("could not update hi value in: " + _tableName, sqle); + Log.Error(sqle, "could not update hi value in: {0}", _tableName); throw; } } @@ -187,4 +186,4 @@ public virtual long GetNextValue() #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/IdentifierGeneratorFactory.cs b/src/NHibernate/Id/IdentifierGeneratorFactory.cs index 45746182797..5f89fcbd516 100644 --- a/src/NHibernate/Id/IdentifierGeneratorFactory.cs +++ b/src/NHibernate/Id/IdentifierGeneratorFactory.cs @@ -84,7 +84,7 @@ namespace NHibernate.Id /// public static partial class IdentifierGeneratorFactory { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (IdentifierGeneratorFactory)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (IdentifierGeneratorFactory)); /// Get the generated identifier when using identity columns /// The to read the identifier value from. @@ -99,9 +99,9 @@ public static object GetGeneratedIdentity(DbDataReader rs, IType type, ISessionI } object id = Get(rs, type, session); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Natively generated identity: " + id); + log.Debug("Natively generated identity: {0}", id); } return id; } @@ -316,4 +316,4 @@ public static System.Type GetIdentifierGeneratorClass(string strategy, Dialect.D return clazz; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/IncrementGenerator.cs b/src/NHibernate/Id/IncrementGenerator.cs index 3413b9cceba..2b70c179998 100644 --- a/src/NHibernate/Id/IncrementGenerator.cs +++ b/src/NHibernate/Id/IncrementGenerator.cs @@ -27,7 +27,7 @@ namespace NHibernate.Id /// public partial class IncrementGenerator : IIdentifierGenerator, IConfigurable { - private static readonly IInternalLogger Logger = LoggerProvider.LoggerFor(typeof(IncrementGenerator)); + private static readonly INHibernateLogger Logger = NHibernateLogger.For(typeof(IncrementGenerator)); private long _next; private SqlString _sql; @@ -97,7 +97,7 @@ public object Generate(ISessionImplementor session, object obj) private void GetNext(ISessionImplementor session) { - Logger.Debug("fetching initial value: " + _sql); + Logger.Debug("fetching initial value: {0}", _sql); try { @@ -117,7 +117,7 @@ private void GetNext(ISessionImplementor session) _next = 1L; } _sql = null; - Logger.Debug("first free id: " + _next); + Logger.Debug("first free id: {0}", _next); } finally { @@ -131,7 +131,7 @@ private void GetNext(ISessionImplementor session) } catch (DbException sqle) { - Logger.Error("could not get increment value", sqle); + Logger.Error(sqle, "could not get increment value"); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "could not fetch initial value for increment generator"); } diff --git a/src/NHibernate/Id/NativeGuidGenerator.cs b/src/NHibernate/Id/NativeGuidGenerator.cs index 3ed5f36027e..8e88f35f786 100644 --- a/src/NHibernate/Id/NativeGuidGenerator.cs +++ b/src/NHibernate/Id/NativeGuidGenerator.cs @@ -15,7 +15,7 @@ namespace NHibernate.Id /// public partial class NativeGuidGenerator : IIdentifierGenerator { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(NativeGuidGenerator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(NativeGuidGenerator)); private readonly IType identifierType = new GuidType(); #region Implementation of IIdentifierGenerator @@ -40,7 +40,7 @@ public object Generate(ISessionImplementor session, object obj) { reader.Close(); } - log.Debug("GUID identifier generated: " + result); + log.Debug("GUID identifier generated: {0}", result); return result; } finally @@ -56,4 +56,4 @@ public object Generate(ISessionImplementor session, object obj) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/SequenceGenerator.cs b/src/NHibernate/Id/SequenceGenerator.cs index 82f14e7f674..88945002dec 100644 --- a/src/NHibernate/Id/SequenceGenerator.cs +++ b/src/NHibernate/Id/SequenceGenerator.cs @@ -34,7 +34,7 @@ namespace NHibernate.Id /// public partial class SequenceGenerator : IPersistentIdentifierGenerator, IConfigurable { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SequenceGenerator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SequenceGenerator)); /// /// The name of the sequence parameter. @@ -122,9 +122,9 @@ public virtual object Generate(ISessionImplementor session, object obj) { reader.Read(); object result = IdentifierGeneratorFactory.Get(reader, identifierType, session); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Sequence identifier generated: " + result); + log.Debug("Sequence identifier generated: {0}", result); } return result; } @@ -140,7 +140,7 @@ public virtual object Generate(ISessionImplementor session, object obj) } catch (DbException sqle) { - log.Error("error generating sequence", sqle); + log.Error(sqle, "error generating sequence"); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "could not get next sequence value"); } } diff --git a/src/NHibernate/Id/SequenceHiLoGenerator.cs b/src/NHibernate/Id/SequenceHiLoGenerator.cs index 8f9c38904a8..8e07c079548 100644 --- a/src/NHibernate/Id/SequenceHiLoGenerator.cs +++ b/src/NHibernate/Id/SequenceHiLoGenerator.cs @@ -35,7 +35,7 @@ namespace NHibernate.Id /// public partial class SequenceHiLoGenerator : SequenceGenerator { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SequenceHiLoGenerator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SequenceHiLoGenerator)); /// /// The name of the maximum low value parameter. @@ -92,12 +92,12 @@ public override object Generate(ISessionImplementor session, object obj) long hival = Convert.ToInt64(base.Generate(session, obj)); lo = (hival == 0) ? 1 : 0; hi = hival * (maxLo + 1); - if (log.IsDebugEnabled) - log.Debug("new hi value: " + hival); + if (log.IsDebugEnabled()) + log.Debug("new hi value: {0}", hival); } return IdentifierGeneratorFactory.CreateNumber(hi + lo++, returnClass); } #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/TableGenerator.cs b/src/NHibernate/Id/TableGenerator.cs index 9326328aac8..045ff128511 100644 --- a/src/NHibernate/Id/TableGenerator.cs +++ b/src/NHibernate/Id/TableGenerator.cs @@ -36,7 +36,7 @@ namespace NHibernate.Id /// public partial class TableGenerator : TransactionHelper, IPersistentIdentifierGenerator, IConfigurable { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (TableGenerator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (TableGenerator)); /// /// An additional where clause that is added to @@ -232,23 +232,17 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D rs = qps.ExecuteReader(); if (!rs.Read()) { - string err; - if (string.IsNullOrEmpty(whereClause)) - { - err = "could not read a hi value - you need to populate the table: " + tableName; - } - else - { - err = string.Format("could not read a hi value from table '{0}' using the where clause ({1})- you need to populate the table.", tableName, whereClause); - } - log.Error(err); - throw new IdentifierGenerationException(err); + var errFormat = string.IsNullOrEmpty(whereClause) + ? "could not read a hi value - you need to populate the table: {0}" + : "could not read a hi value from table '{0}' using the where clause ({1})- you need to populate the table."; + log.Error(errFormat, tableName, whereClause); + throw new IdentifierGenerationException(string.Format(errFormat, tableName, whereClause)); } result = Convert.ToInt64(columnType.Get(rs, 0, session)); } catch (Exception e) { - log.Error("could not read a hi value", e); + log.Error(e, "could not read a hi value"); throw; } finally @@ -275,7 +269,7 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D } catch (Exception e) { - log.Error("could not update hi value in: " + tableName, e); + log.Error(e, "could not update hi value in: {0}", tableName); throw; } finally @@ -288,4 +282,4 @@ public override object DoWorkInCurrentTransaction(ISessionImplementor session, D return result; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Id/TableHiLoGenerator.cs b/src/NHibernate/Id/TableHiLoGenerator.cs index 2609f458fb3..2ef2d2b6a85 100644 --- a/src/NHibernate/Id/TableHiLoGenerator.cs +++ b/src/NHibernate/Id/TableHiLoGenerator.cs @@ -39,7 +39,7 @@ namespace NHibernate.Id /// public partial class TableHiLoGenerator : TableGenerator { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(TableHiLoGenerator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(TableHiLoGenerator)); /// /// The name of the max lo parameter. @@ -94,7 +94,7 @@ public override object Generate(ISessionImplementor session, object obj) long hival = Convert.ToInt64(base.Generate(session, obj)); lo = (hival == 0) ? 1 : 0; hi = hival * (maxLo + 1); - log.Debug("New high value: " + hival); + log.Debug("New high value: {0}", hival); } return IdentifierGeneratorFactory.CreateNumber(hi + lo++, returnClass); @@ -102,4 +102,4 @@ public override object Generate(ISessionImplementor session, object obj) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Impl/AbstractSessionImpl.cs b/src/NHibernate/Impl/AbstractSessionImpl.cs index f7d730c9bd4..7d946e7a978 100644 --- a/src/NHibernate/Impl/AbstractSessionImpl.cs +++ b/src/NHibernate/Impl/AbstractSessionImpl.cs @@ -38,7 +38,7 @@ public ITransactionContext TransactionContext private bool isAlreadyDisposed; - private static readonly IInternalLogger logger = LoggerProvider.LoggerFor(typeof(AbstractSessionImpl)); + private static readonly INHibernateLogger logger = NHibernateLogger.For(typeof(AbstractSessionImpl)); public Guid SessionId { get; } diff --git a/src/NHibernate/Impl/EnumerableImpl.cs b/src/NHibernate/Impl/EnumerableImpl.cs index f26870d7429..bf2ad663a95 100644 --- a/src/NHibernate/Impl/EnumerableImpl.cs +++ b/src/NHibernate/Impl/EnumerableImpl.cs @@ -23,7 +23,7 @@ namespace NHibernate.Impl /// public class EnumerableImpl : IEnumerable, IEnumerator, IDisposable { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(EnumerableImpl)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(EnumerableImpl)); private DbDataReader _reader; private IEventSource _session; diff --git a/src/NHibernate/Impl/MultiCriteriaImpl.cs b/src/NHibernate/Impl/MultiCriteriaImpl.cs index e4b4480907a..af13d7ffeba 100644 --- a/src/NHibernate/Impl/MultiCriteriaImpl.cs +++ b/src/NHibernate/Impl/MultiCriteriaImpl.cs @@ -17,7 +17,7 @@ namespace NHibernate.Impl { public partial class MultiCriteriaImpl : IMultiCriteria { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(MultiCriteriaImpl)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(MultiCriteriaImpl)); private readonly IList criteriaQueries = new List(); private readonly IList resultCollectionGenericType = new List(); @@ -67,12 +67,12 @@ public IList List() CreateCriteriaLoaders(); CombineCriteriaQueries(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("Multi criteria with {0} criteria queries.", criteriaQueries.Count); + log.Debug("Multi criteria with {0} criteria queries.", criteriaQueries.Count); for (int i = 0; i < criteriaQueries.Count; i++) { - log.DebugFormat("Query #{0}: {1}", i, criteriaQueries[i]); + log.Debug("Query #{0}: {1}", i, criteriaQueries[i]); } } @@ -277,8 +277,7 @@ private void GetResultsFromDatabase(IList results) } catch (Exception sqle) { - var message = string.Format("Failed to execute multi criteria: [{0}]", resultSetsCommand.Sql); - log.Error(message, sqle); + log.Error(sqle, "Failed to execute multi criteria: [{0}]", resultSetsCommand.Sql); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi criteria", resultSetsCommand.Sql); } if (statsEnabled) diff --git a/src/NHibernate/Impl/MultiQueryImpl.cs b/src/NHibernate/Impl/MultiQueryImpl.cs index 14d1cbbb18e..5701c842576 100644 --- a/src/NHibernate/Impl/MultiQueryImpl.cs +++ b/src/NHibernate/Impl/MultiQueryImpl.cs @@ -19,7 +19,7 @@ namespace NHibernate.Impl { public partial class MultiQueryImpl : IMultiQuery { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(MultiQueryImpl)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(MultiQueryImpl)); private readonly List queries = new List(); private readonly List translators = new List(); @@ -411,12 +411,12 @@ public IList List() bool cacheable = session.Factory.Settings.IsQueryCacheEnabled && isCacheable; combinedParameters = CreateCombinedQueryParameters(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("Multi query with {0} queries.", queries.Count); + log.Debug("Multi query with {0} queries.", queries.Count); for (int i = 0; i < queries.Count; i++) { - log.DebugFormat("Query #{0}: {1}", i, queries[i]); + log.Debug("Query #{0}: {1}", i, queries[i]); } } @@ -528,9 +528,9 @@ protected List DoList() { using (var reader = resultSetsCommand.GetReader(commandTimeout != RowSelection.NoValue ? commandTimeout : (int?)null)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("Executing {0} queries", translators.Count); + log.Debug("Executing {0} queries", translators.Count); } for (int i = 0; i < translators.Count; i++) { @@ -560,7 +560,7 @@ protected List DoList() translator.Loader.HandleEmptyCollections(parameter.CollectionKeys, reader, session); EntityKey[] keys = new EntityKey[entitySpan]; // we can reuse it each time - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("processing result set"); } @@ -569,9 +569,9 @@ protected List DoList() int count; for (count = 0; count < maxRows && reader.Read(); count++) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("result set row: " + count); + log.Debug("result set row: {0}", count); } rowCount++; @@ -586,16 +586,16 @@ protected List DoList() } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("done processing result set ({0} rows)", count)); + log.Debug("done processing result set ({0} rows)", count); } results.Add(tempResults); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("Query {0} returned {1} results", i, tempResults.Count); + log.Debug("Query {0} returned {1} results", i, tempResults.Count); } reader.NextResult(); @@ -617,8 +617,7 @@ protected List DoList() } catch (Exception sqle) { - var message = string.Format("Failed to execute multi query: [{0}]", resultSetsCommand.Sql); - log.Error(message, sqle); + log.Error(sqle, "Failed to execute multi query: [{0}]", resultSetsCommand.Sql); throw ADOExceptionHelper.Convert(session.Factory.SQLExceptionConverter, sqle, "Failed to execute multi query", resultSetsCommand.Sql); } diff --git a/src/NHibernate/Impl/Printer.cs b/src/NHibernate/Impl/Printer.cs index e73e28aaf8a..9d522e1d0e3 100644 --- a/src/NHibernate/Impl/Printer.cs +++ b/src/NHibernate/Impl/Printer.cs @@ -13,7 +13,7 @@ namespace NHibernate.Impl public sealed class Printer { private readonly ISessionFactoryImplementor _factory; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(Printer)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(Printer)); /// /// @@ -85,7 +85,7 @@ public string ToString(IDictionary namedTypedValues) public void ToString(object[] entities) { - if (!log.IsDebugEnabled || entities.Length == 0) + if (!log.IsDebugEnabled() || entities.Length == 0) { return; } diff --git a/src/NHibernate/Impl/SessionFactoryImpl.cs b/src/NHibernate/Impl/SessionFactoryImpl.cs index a729d88c557..bea503c6817 100644 --- a/src/NHibernate/Impl/SessionFactoryImpl.cs +++ b/src/NHibernate/Impl/SessionFactoryImpl.cs @@ -90,7 +90,7 @@ public void HandleEntityNotFound(string entityName, object id) #endregion - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SessionFactoryImpl)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SessionFactoryImpl)); private static readonly IIdentifierGenerator UuidGenerator = new UUIDHexGenerator(); [NonSerialized] @@ -183,14 +183,14 @@ public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings sqlFunctionRegistry = new SQLFunctionRegistry(settings.Dialect, cfg.SqlFunctions); eventListeners = listeners; filters = new Dictionary(cfg.FilterDefinitions); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Session factory constructed with filter configurations : " + CollectionPrinter.ToString(filters)); + log.Debug("Session factory constructed with filter configurations : {0}", CollectionPrinter.ToString(filters)); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("instantiating session factory with properties: " + CollectionPrinter.ToString(properties)); + log.Debug("instantiating session factory with properties: {0}", CollectionPrinter.ToString(properties)); } try @@ -398,7 +398,7 @@ public SessionFactoryImpl(Configuration cfg, IMapping mapping, Settings settings foreach (KeyValuePair pair in errors) { failingQueries.Append('{').Append(pair.Key).Append('}'); - log.Error("Error in named query: " + pair.Key, pair.Value); + log.Error(pair.Value, "Error in named query: {0}", pair.Key); } throw new HibernateException(failingQueries.ToString()); } @@ -877,9 +877,9 @@ public void Evict(System.Type persistentClass, object id) IEntityPersister p = GetEntityPersister(persistentClass.FullName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + MessageHelper.InfoString(p, id)); + log.Debug("evicting second-level cache: {0}", MessageHelper.InfoString(p, id)); } CacheKey ck = GenerateCacheKeyForEvict(id, p.IdentifierType, p.RootEntityName); p.Cache.Remove(ck); @@ -891,9 +891,9 @@ public void Evict(System.Type persistentClass) IEntityPersister p = GetEntityPersister(persistentClass.FullName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + p.EntityName); + log.Debug("evicting second-level cache: {0}", p.EntityName); } p.Cache.Clear(); } @@ -904,9 +904,9 @@ public void EvictEntity(string entityName) IEntityPersister p = GetEntityPersister(entityName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + p.EntityName); + log.Debug("evicting second-level cache: {0}", p.EntityName); } p.Cache.Clear(); } @@ -917,9 +917,9 @@ public void EvictEntity(string entityName, object id) IEntityPersister p = GetEntityPersister(entityName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + MessageHelper.InfoString(p, id, this)); + log.Debug("evicting second-level cache: {0}", MessageHelper.InfoString(p, id, this)); } CacheKey cacheKey = GenerateCacheKeyForEvict(id, p.IdentifierType, p.RootEntityName); p.Cache.Remove(cacheKey); @@ -931,9 +931,9 @@ public void EvictCollection(string roleName, object id) ICollectionPersister p = GetCollectionPersister(roleName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + MessageHelper.CollectionInfoString(p, id)); + log.Debug("evicting second-level cache: {0}", MessageHelper.CollectionInfoString(p, id)); } CacheKey ck = GenerateCacheKeyForEvict(id, p.KeyType, p.Role); p.Cache.Remove(ck); @@ -959,9 +959,9 @@ public void EvictCollection(string roleName) ICollectionPersister p = GetCollectionPersister(roleName); if (p.HasCache) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("evicting second-level cache: " + p.Role); + log.Debug("evicting second-level cache: {0}", p.Role); } p.Cache.Clear(); } @@ -1153,7 +1153,7 @@ private IDictionary CheckNamedQueries() IDictionary errors = new Dictionary(); // Check named HQL queries - log.Debug("Checking " + namedQueries.Count + " named HQL queries"); + log.Debug("Checking {0} named HQL queries", namedQueries.Count); foreach (var entry in namedQueries) { string queryName = entry.Key; @@ -1161,7 +1161,7 @@ private IDictionary CheckNamedQueries() // this will throw an error if there's something wrong. try { - log.Debug("Checking named query: " + queryName); + log.Debug("Checking named query: {0}", queryName); //TODO: BUG! this currently fails for named queries for non-POJO entities queryPlanCache.GetHQLQueryPlan(qd.QueryString.ToQueryExpression(), false, new CollectionHelper.EmptyMapClass()); } @@ -1175,7 +1175,7 @@ private IDictionary CheckNamedQueries() } } - log.Debug("Checking " + namedSqlQueries.Count + " named SQL queries"); + log.Debug("Checking {0} named SQL queries", namedSqlQueries.Count); foreach (KeyValuePair entry in namedSqlQueries) { string queryName = entry.Key; @@ -1183,7 +1183,7 @@ private IDictionary CheckNamedQueries() // this will throw an error if there's something wrong. try { - log.Debug("Checking named SQL query: " + queryName); + log.Debug("Checking named SQL query: {0}", queryName); // TODO : would be really nice to cache the spec on the query-def so as to not have to re-calc the hash; // currently not doable though because of the resultset-ref stuff... NativeSQLQuerySpecification spec; @@ -1243,7 +1243,7 @@ private ICurrentSessionContext BuildCurrentSessionContext() } catch (Exception e) { - log.Error("Unable to construct current session context [" + impl + "]", e); + log.Error(e, "Unable to construct current session context [{0}]", impl); return null; } } @@ -1282,7 +1282,7 @@ internal class SessionBuilderImpl : ISessionBuilder, ISessionCreationOptio { // NH specific: implementing return type covariance with interface is a mess in .Net. private T _this; - private static readonly IInternalLogger _log = LoggerProvider.LoggerFor(typeof(SessionBuilderImpl)); + private static readonly INHibernateLogger _log = NHibernateLogger.For(typeof(SessionBuilderImpl)); private readonly SessionFactoryImpl _sessionFactory; private IInterceptor _interceptor; diff --git a/src/NHibernate/Impl/SessionFactoryObjectFactory.cs b/src/NHibernate/Impl/SessionFactoryObjectFactory.cs index d8e279acce5..9c2ae03f6d5 100644 --- a/src/NHibernate/Impl/SessionFactoryObjectFactory.cs +++ b/src/NHibernate/Impl/SessionFactoryObjectFactory.cs @@ -20,7 +20,7 @@ namespace NHibernate.Impl /// public static class SessionFactoryObjectFactory { - private static readonly IInternalLogger log; + private static readonly INHibernateLogger log; private static readonly IDictionary Instances = new Dictionary(); private static readonly IDictionary NamedInstances = new Dictionary(); @@ -28,7 +28,7 @@ public static class SessionFactoryObjectFactory /// static SessionFactoryObjectFactory() { - log = LoggerProvider.LoggerFor(typeof(SessionFactoryObjectFactory)); + log = NHibernateLogger.For(typeof(SessionFactoryObjectFactory)); log.Debug("initializing class SessionFactoryObjectFactory"); } @@ -42,17 +42,17 @@ static SessionFactoryObjectFactory() [MethodImpl(MethodImplOptions.Synchronized)] public static void AddInstance(string uid, string name, ISessionFactory instance, IDictionary properties) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { string nameMsg = ((!string.IsNullOrEmpty(name)) ? name : "unnamed"); - log.Debug("registered: " + uid + "(" + nameMsg + ")"); + log.Debug("registered: {0}({1})", uid, nameMsg); } Instances[uid] = instance; if (!string.IsNullOrEmpty(name)) { - log.Info("Factory name:" + name); + log.Info("Factory name:{0}", name); NamedInstances[name] = instance; } else @@ -72,7 +72,7 @@ public static void RemoveInstance(string uid, string name, IDictionary 0) @@ -1277,10 +1277,10 @@ public override object ImmediateLoad(string entityName, object id) { using (BeginProcess()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { IEntityPersister persister = Factory.GetEntityPersister(entityName); - log.Debug("initializing proxy: " + MessageHelper.InfoString(persister, id, Factory)); + log.Debug("initializing proxy: {0}", MessageHelper.InfoString(persister, id, Factory)); } LoadEvent loadEvent = new LoadEvent(id, entityName, true, this); @@ -1584,7 +1584,7 @@ public void Dispose() { using (BeginContext()) { - log.DebugFormat("[session-id={0}] running ISession.Dispose()", SessionId); + log.Debug("[session-id={0}] running ISession.Dispose()", SessionId); // Ensure we are not disposing concurrently to transaction completion, which would // remove the context. (Do not store it into a local variable before the Wait.) TransactionContext?.Wait(); @@ -1621,7 +1621,7 @@ private void Dispose(bool isDisposing) return; } - log.Debug(string.Format("[session-id={0}] executing real Dispose({1})", SessionId, isDisposing)); + log.Debug("[session-id={0}] executing real Dispose({1})", SessionId, isDisposing); // free managed resources that are being managed by the session if we // know this call came through Dispose() @@ -2100,7 +2100,7 @@ public override void BeforeTransactionCompletion(ITransaction tx) } catch (Exception e) { - log.Error("exception in interceptor BeforeTransactionCompletion()", e); + log.Error(e, "exception in interceptor BeforeTransactionCompletion()"); throw; } @@ -2148,9 +2148,9 @@ public override CacheMode CacheMode set { CheckAndUpdateSessionStatus(); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("setting cache mode to: " + value); + log.Debug("setting cache mode to: {0}", value); } cacheMode = value; } diff --git a/src/NHibernate/Impl/StatelessSessionImpl.cs b/src/NHibernate/Impl/StatelessSessionImpl.cs index 44f96bc933a..3f3d9326639 100644 --- a/src/NHibernate/Impl/StatelessSessionImpl.cs +++ b/src/NHibernate/Impl/StatelessSessionImpl.cs @@ -26,7 +26,7 @@ namespace NHibernate.Impl [Serializable] public partial class StatelessSessionImpl : AbstractSessionImpl, IStatelessSession { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(StatelessSessionImpl)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(StatelessSessionImpl)); [NonSerialized] private readonly ConnectionManager connectionManager; @@ -43,9 +43,9 @@ internal StatelessSessionImpl(SessionFactoryImpl factory, ISessionCreationOption connectionManager = new ConnectionManager(this, options.UserSuppliedConnection, ConnectionReleaseMode.AfterTransaction, EmptyInterceptor.Instance, options.ShouldAutoJoinTransaction); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("[session-id={0}] opened session for session factory: [{1}/{2}]", + log.Debug("[session-id={0}] opened session for session factory: [{1}/{2}]", SessionId, factory.Name, factory.Uuid); } @@ -657,9 +657,9 @@ public void Refresh(string entityName, object entity, LockMode lockMode) { IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.GetIdentifier(entity); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("refreshing transient " + MessageHelper.InfoString(persister, id, Factory)); + log.Debug("refreshing transient {0}", MessageHelper.InfoString(persister, id, Factory)); } //from H3.2 TODO : can this ever happen??? // EntityKey key = new EntityKey( id, persister, source.getEntityMode() ); diff --git a/src/NHibernate/LazyInitializationException.cs b/src/NHibernate/LazyInitializationException.cs index 8f08a502fc2..fc4319f8f35 100644 --- a/src/NHibernate/LazyInitializationException.cs +++ b/src/NHibernate/LazyInitializationException.cs @@ -60,7 +60,7 @@ public LazyInitializationException(Exception innerException) /// public LazyInitializationException(string message, Exception innerException) : base(message, innerException) { - LoggerProvider.LoggerFor(typeof(LazyInitializationException)).Error(message, this); + NHibernateLogger.For(typeof(LazyInitializationException)).Error(this, message); } /// diff --git a/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs b/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs index be5ce86ed31..ce151033c55 100644 --- a/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs +++ b/src/NHibernate/Linq/Functions/LinqToHqlGeneratorsRegistryFactory.cs @@ -8,7 +8,7 @@ namespace NHibernate.Linq.Functions { public sealed class LinqToHqlGeneratorsRegistryFactory { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (LinqToHqlGeneratorsRegistryFactory)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (LinqToHqlGeneratorsRegistryFactory)); public static ILinqToHqlGeneratorsRegistry CreateGeneratorsRegistry(IDictionary properties) { @@ -17,16 +17,16 @@ public static ILinqToHqlGeneratorsRegistry CreateGeneratorsRegistry(IDictionary< { try { - log.Info("Initializing LinqToHqlGeneratorsRegistry: " + registry); + log.Info("Initializing LinqToHqlGeneratorsRegistry: {0}", registry); return (ILinqToHqlGeneratorsRegistry) Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(registry)); } catch (Exception e) { - log.Fatal("Could not instantiate LinqToHqlGeneratorsRegistry", e); + log.Fatal(e, "Could not instantiate LinqToHqlGeneratorsRegistry"); throw new HibernateException("Could not instantiate LinqToHqlGeneratorsRegistry: " + registry, e); } } return new DefaultLinqToHqlGeneratorsRegistry(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Linq/LinqLogging.cs b/src/NHibernate/Linq/LinqLogging.cs index 7770875e378..c6d121cf6eb 100644 --- a/src/NHibernate/Linq/LinqLogging.cs +++ b/src/NHibernate/Linq/LinqLogging.cs @@ -7,14 +7,14 @@ namespace NHibernate.Linq { internal static class LinqLogging { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor("NHibernate.Linq"); + private static readonly INHibernateLogger Log = NHibernateLogger.For("NHibernate.Linq"); /// /// If debug logging is enabled, log a string such as "msg: expression.ToString()". /// internal static void LogExpression(string msg, Expression expression) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { // If the expression contains NHibernate proxies, those will be initialized // when we call ToString() on the exception. The string representation is @@ -24,7 +24,7 @@ internal static void LogExpression(string msg, Expression expression) var visitor = new ProxyReplacingExpressionVisitor(); var preparedExpression = visitor.Visit(expression); - Log.DebugFormat("{0}: {1}", msg, preparedExpression.ToString()); + Log.Debug("{0}: {1}", msg, preparedExpression.ToString()); } } diff --git a/src/NHibernate/Loader/Collection/BasicCollectionLoader.cs b/src/NHibernate/Loader/Collection/BasicCollectionLoader.cs index 72648402fbe..39258d3cbf6 100644 --- a/src/NHibernate/Loader/Collection/BasicCollectionLoader.cs +++ b/src/NHibernate/Loader/Collection/BasicCollectionLoader.cs @@ -16,7 +16,7 @@ namespace NHibernate.Loader.Collection /// public class BasicCollectionLoader : CollectionLoader { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (BasicCollectionLoader)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (BasicCollectionLoader)); public BasicCollectionLoader(IQueryableCollection collectionPersister, ISessionFactoryImplementor session, IDictionary enabledFilters) @@ -40,7 +40,7 @@ protected virtual void InitializeFromWalker(IQueryableCollection collectionPersi PostInstantiate(); - log.Debug("Static select for collection " + collectionPersister.Role + ": " + SqlString); + log.Debug("Static select for collection {0}: {1}", collectionPersister.Role, SqlString); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Loader/Collection/OneToManyLoader.cs b/src/NHibernate/Loader/Collection/OneToManyLoader.cs index 856f117da03..2fe9c0d5a27 100644 --- a/src/NHibernate/Loader/Collection/OneToManyLoader.cs +++ b/src/NHibernate/Loader/Collection/OneToManyLoader.cs @@ -16,7 +16,7 @@ namespace NHibernate.Loader.Collection /// public class OneToManyLoader : CollectionLoader { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (OneToManyLoader)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (OneToManyLoader)); public OneToManyLoader(IQueryableCollection oneToManyPersister, ISessionFactoryImplementor session, IDictionary enabledFilters) @@ -40,7 +40,7 @@ protected virtual void InitializeFromWalker(IQueryableCollection oneToManyPersis PostInstantiate(); - log.Debug("Static select for one-to-many " + oneToManyPersister.Role + ": " + SqlString); + log.Debug("Static select for one-to-many {0}: {1}", oneToManyPersister.Role, SqlString); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Loader/Criteria/CriteriaJoinWalker.cs b/src/NHibernate/Loader/Criteria/CriteriaJoinWalker.cs index 925811ef907..65ecef6b164 100644 --- a/src/NHibernate/Loader/Criteria/CriteriaJoinWalker.cs +++ b/src/NHibernate/Loader/Criteria/CriteriaJoinWalker.cs @@ -32,7 +32,7 @@ public class CriteriaJoinWalker : AbstractEntityJoinWalker private readonly IList resultTypeList = new List(); private readonly IList includeInResultRowList = new List(); - private static readonly IInternalLogger logger = LoggerProvider.LoggerFor(typeof(CriteriaJoinWalker)); + private static readonly INHibernateLogger logger = NHibernateLogger.For(typeof(CriteriaJoinWalker)); public CriteriaJoinWalker(IOuterJoinLoadable persister, CriteriaQueryTranslator translator, ISessionFactoryImplementor factory, ICriteria criteria, string rootEntityName, diff --git a/src/NHibernate/Loader/Criteria/CriteriaQueryTranslator.cs b/src/NHibernate/Loader/Criteria/CriteriaQueryTranslator.cs index 5b02a62f3ab..731727a4e1a 100644 --- a/src/NHibernate/Loader/Criteria/CriteriaQueryTranslator.cs +++ b/src/NHibernate/Loader/Criteria/CriteriaQueryTranslator.cs @@ -17,7 +17,7 @@ namespace NHibernate.Loader.Criteria public class CriteriaQueryTranslator : ICriteriaQuery { public static readonly string RootSqlAlias = CriteriaSpecification.RootAlias + '_'; - private static readonly IInternalLogger logger = LoggerProvider.LoggerFor(typeof(CriteriaQueryTranslator)); + private static readonly INHibernateLogger logger = NHibernateLogger.For(typeof(CriteriaQueryTranslator)); private const int AliasCount = 0; @@ -263,7 +263,7 @@ public ICriteria GetCriteria(string path) { ICriteria result; associationPathCriteriaMap.TryGetValue(path, out result); - logger.DebugFormat("getCriteria for path={0} crit={1}", path, result); + logger.Debug("getCriteria for path={0} crit={1}", path, result); return result; } @@ -448,7 +448,7 @@ private ICriteriaInfoProvider GetPathInfo(string path) foreach (string token in tokens) { componentPath += token; - logger.DebugFormat("searching for {0}", componentPath); + logger.Debug("searching for {0}", componentPath); IType type = provider.GetType(componentPath); if (type.IsAssociationType) { @@ -486,7 +486,7 @@ private ICriteriaInfoProvider GetPathInfo(string path) } } - logger.DebugFormat("returning entity name={0} for path={1} class={2}", + logger.Debug("returning entity name={0} for path={1} class={2}", provider.Name, path, provider.GetType().Name); return provider; } @@ -504,7 +504,7 @@ private void CreateCriteriaSQLAliasMap() alias = me.Value.Name; // the entity name } criteriaSQLAliasMap[crit] = StringHelper.GenerateAlias(alias, i++); - logger.DebugFormat("put criteria={0} alias={1}", + logger.Debug("put criteria={0} alias={1}", crit, criteriaSQLAliasMap[crit]); } criteriaSQLAliasMap[rootCriteria] = rootSQLAlias; @@ -518,7 +518,7 @@ public bool HasProjection public string GetSQLAlias(ICriteria criteria) { String alias = criteriaSQLAliasMap[criteria]; - logger.DebugFormat("returning alias={0} for criteria={1}", alias, criteria); + logger.Debug("returning alias={0} for criteria={1}", alias, criteria); return alias; } diff --git a/src/NHibernate/Loader/Custom/Sql/SQLCustomQuery.cs b/src/NHibernate/Loader/Custom/Sql/SQLCustomQuery.cs index 2fb3371d46f..57ca5afb81c 100644 --- a/src/NHibernate/Loader/Custom/Sql/SQLCustomQuery.cs +++ b/src/NHibernate/Loader/Custom/Sql/SQLCustomQuery.cs @@ -15,7 +15,7 @@ namespace NHibernate.Loader.Custom.Sql ///This support is built on top of the notion of "custom queries"... public class SQLCustomQuery : ICustomQuery { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (SQLCustomQuery)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (SQLCustomQuery)); private readonly List customQueryReturns = new List(); private readonly ISet querySpaces = new HashSet(); @@ -25,7 +25,7 @@ public class SQLCustomQuery : ICustomQuery public SQLCustomQuery(INativeSQLQueryReturn[] queryReturns, string sqlQuery, ICollection additionalQuerySpaces, ISessionFactoryImplementor factory) { - log.Debug("starting processing of sql query [" + sqlQuery + "]"); + log.Debug("starting processing of sql query [{0}]", sqlQuery); SQLQueryReturnProcessor processor = new SQLQueryReturnProcessor(queryReturns, factory); SQLQueryReturnProcessor.ResultAliasContext aliasContext = processor.Process(); @@ -113,4 +113,4 @@ public IDictionary GetPropertyResultsMapByAlias(string alias) #endregion } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Loader/Custom/Sql/SQLQueryReturnProcessor.cs b/src/NHibernate/Loader/Custom/Sql/SQLQueryReturnProcessor.cs index 20c0c0fba65..91ac30308b4 100644 --- a/src/NHibernate/Loader/Custom/Sql/SQLQueryReturnProcessor.cs +++ b/src/NHibernate/Loader/Custom/Sql/SQLQueryReturnProcessor.cs @@ -11,7 +11,7 @@ namespace NHibernate.Loader.Custom.Sql { public class SQLQueryReturnProcessor { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (SQLQueryReturnProcessor)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (SQLQueryReturnProcessor)); private readonly INativeSQLQueryReturn[] queryReturns; @@ -198,7 +198,7 @@ private void AddPersister(string alias, IDictionary propertyRe { alias2Persister[alias] = persister; string suffix = GenerateEntitySuffix(); - log.Debug("mapping alias [" + alias + "] to entity-suffix [" + suffix + "]"); + log.Debug("mapping alias [{0}] to entity-suffix [{1}]", alias, suffix); alias2Suffix[alias] = suffix; entityPropertyResultMaps[alias] = propertyResult; } @@ -208,7 +208,7 @@ private void AddCollection(string role, string alias, IDictionary public abstract partial class AbstractEntityLoader : OuterJoinLoader, IUniqueEntityLoader { - protected static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (AbstractEntityLoader)); + protected static readonly INHibernateLogger log = NHibernateLogger.For(typeof (AbstractEntityLoader)); protected readonly IOuterJoinLoadable persister; protected readonly string entityName; private IParameterSpecification[] parametersSpecifications; diff --git a/src/NHibernate/Loader/Entity/CascadeEntityLoader.cs b/src/NHibernate/Loader/Entity/CascadeEntityLoader.cs index eed16ef2a18..d9ee4581c6f 100644 --- a/src/NHibernate/Loader/Entity/CascadeEntityLoader.cs +++ b/src/NHibernate/Loader/Entity/CascadeEntityLoader.cs @@ -14,7 +14,7 @@ public CascadeEntityLoader(IOuterJoinLoadable persister, CascadingAction action, PostInstantiate(); - log.Debug(string.Format("Static select for action {0} on entity {1}: {2}", action, entityName, SqlString)); + log.Debug("Static select for action {0} on entity {1}: {2}", action, entityName, SqlString); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Loader/Entity/CollectionElementLoader.cs b/src/NHibernate/Loader/Entity/CollectionElementLoader.cs index d651f8eda22..2e880773553 100644 --- a/src/NHibernate/Loader/Entity/CollectionElementLoader.cs +++ b/src/NHibernate/Loader/Entity/CollectionElementLoader.cs @@ -15,7 +15,7 @@ namespace NHibernate.Loader.Entity { public partial class CollectionElementLoader : OuterJoinLoader { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (CollectionElementLoader)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (CollectionElementLoader)); private readonly IOuterJoinLoadable persister; private readonly IType keyType; @@ -39,7 +39,7 @@ public CollectionElementLoader(IQueryableCollection collectionPersister, ISessio PostInstantiate(); - log.Debug("Static select for entity " + entityName + ": " + SqlString); + log.Debug("Static select for entity {0}: {1}", entityName, SqlString); } private IEnumerable CreateParameterSpecificationsAndAssignBackTrack(IEnumerable sqlPatameters) @@ -100,4 +100,4 @@ protected override object GetResultColumnOrRow(object[] row, IResultTransformer return row[row.Length - 1]; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Loader/Entity/EntityLoader.cs b/src/NHibernate/Loader/Entity/EntityLoader.cs index d767a6dbc1b..af222d4e894 100644 --- a/src/NHibernate/Loader/Entity/EntityLoader.cs +++ b/src/NHibernate/Loader/Entity/EntityLoader.cs @@ -36,7 +36,7 @@ public EntityLoader(IOuterJoinLoadable persister, string[] uniqueKey, IType uniq batchLoader = batchSize > 1; - log.Debug("Static select for entity " + entityName + ": " + SqlString); + log.Debug("Static select for entity {0}: {1}", entityName, SqlString); } public object LoadByUniqueKey(ISessionImplementor session, object key) @@ -49,4 +49,4 @@ protected override bool IsSingleRowLoader get { return !batchLoader; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index 17c7d5dfb24..89c8271202d 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -46,7 +46,7 @@ namespace NHibernate.Loader /// public abstract partial class Loader { - private static readonly IInternalLogger Log = LoggerProvider.LoggerFor(typeof(Loader)); + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(Loader)); private readonly ISessionFactoryImplementor _factory; private readonly SessionFactoryHelper _helper; @@ -453,7 +453,7 @@ private IList DoQuery(ISessionImplementor session, QueryParameters queryParamete HandleEmptyCollections(queryParameters.CollectionKeys, rs, session); EntityKey[] keys = new EntityKey[entitySpan]; // we can reuse it each time - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { Log.Debug("processing result set"); } @@ -461,9 +461,9 @@ private IList DoQuery(ISessionImplementor session, QueryParameters queryParamete int count; for (count = 0; count < maxRows && rs.Read(); count++) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("result set row: " + count); + Log.Debug("result set row: {0}", count); } object result = GetRowFromResultSet(rs, session, queryParameters, lockModeArray, optionalObjectKey, @@ -478,9 +478,9 @@ private IList DoQuery(ISessionImplementor session, QueryParameters queryParamete } } - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug(string.Format("done processing result set ({0} rows)", count)); + Log.Debug("done processing result set ({0} rows)", count); } } catch (Exception e) @@ -612,9 +612,9 @@ internal void InitializeEntitiesAndCollections(IList hydratedObjects, object res { int hydratedObjectsSize = hydratedObjects.Count; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug(string.Format("total objects hydrated: {0}", hydratedObjectsSize)); + Log.Debug("total objects hydrated: {0}", hydratedObjectsSize); } for (int i = 0; i < hydratedObjectsSize; i++) @@ -751,9 +751,9 @@ private static void ReadCollectionElement(object optionalOwner, object optionalK { // we found a collection element in the result set - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("found row of collection: " + MessageHelper.CollectionInfoString(persister, collectionRowKey)); + Log.Debug("found row of collection: {0}", MessageHelper.CollectionInfoString(persister, collectionRowKey)); } object owner = optionalOwner; @@ -783,9 +783,9 @@ private static void ReadCollectionElement(object optionalOwner, object optionalK // ensure that a collection is created with the owner's identifier, // since what we have is an empty collection - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("result set contains (possibly empty) collection: " + MessageHelper.CollectionInfoString(persister, optionalKey)); + Log.Debug("result set contains (possibly empty) collection: {0}", MessageHelper.CollectionInfoString(persister, optionalKey)); } persistenceContext.LoadContexts.GetCollectionLoadContext(rs).GetLoadingCollection(persister, optionalKey); // handle empty collection @@ -813,10 +813,10 @@ internal void HandleEmptyCollections(object[] keys, object resultSetId, ISession for (int i = 0; i < keys.Length; i++) { // handle empty collections - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("result set contains (possibly empty) collection: " - + MessageHelper.CollectionInfoString(collectionPersisters[j], keys[i])); + Log.Debug("result set contains (possibly empty) collection: {0}", + MessageHelper.CollectionInfoString(collectionPersisters[j], keys[i])); } session.PersistenceContext.LoadContexts.GetCollectionLoadContext((DbDataReader)resultSetId).GetLoadingCollection( collectionPersisters[j], keys[i]); @@ -902,9 +902,9 @@ private object[] GetRow(DbDataReader rs, ILoadable[] persisters, EntityKey[] key int cols = persisters.Length; IEntityAliases[] descriptors = EntityAliases; - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("result row: " + StringHelper.ToString(keys)); + Log.Debug("result row: {0}", StringHelper.ToString(keys)); } object[] rowResults = new object[cols]; @@ -1029,9 +1029,9 @@ private void LoadFromResultSet(DbDataReader rs, int i, object obj, string instan // Get the persister for the _subclass_ ILoadable persister = (ILoadable)Factory.GetEntityPersister(instanceClass); - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("Initializing object from DataReader: " + MessageHelper.InfoString(persister, id)); + Log.Debug("Initializing object from DataReader: {0}", MessageHelper.InfoString(persister, id)); } bool eagerPropertyFetch = IsEagerPropertyFetchEnabled(i); @@ -1298,12 +1298,12 @@ private DbDataReader WrapResultSet(DbDataReader rs) // potential deadlock issues due to nature of code. try { - Log.Debug("Wrapping result set [" + rs + "]"); + Log.Debug("Wrapping result set [{0}]", rs); return new ResultSetWrapper(rs, RetreiveColumnNameToIndexCache(rs)); } catch (Exception e) { - Log.Info("Error wrapping result set", e); + Log.Info(e, "Error wrapping result set"); return rs; } } @@ -1325,9 +1325,9 @@ private ColumnNameCache RetreiveColumnNameToIndexCache(DbDataReader rs) protected IList LoadEntity(ISessionImplementor session, object id, IType identifierType, object optionalObject, string optionalEntityName, object optionalIdentifier, IEntityPersister persister) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("loading entity: " + MessageHelper.InfoString(persister, id, identifierType, Factory)); + Log.Debug("loading entity: {0}", MessageHelper.InfoString(persister, id, identifierType, Factory)); } IList result; @@ -1389,9 +1389,9 @@ protected internal IList LoadEntityBatch(ISessionImplementor session, object[] i object optionalObject, string optionalEntityName, object optionalId, IEntityPersister persister) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("batch loading entity: " + MessageHelper.InfoString(persister, ids, Factory)); + Log.Debug("batch loading entity: {0}", MessageHelper.InfoString(persister, ids, Factory)); } IType[] types = new IType[ids.Length]; @@ -1425,9 +1425,9 @@ protected internal IList LoadEntityBatch(ISessionImplementor session, object[] i /// public void LoadCollection(ISessionImplementor session, object id, IType type) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("loading collection: " + MessageHelper.CollectionInfoString(CollectionPersisters[0], id)); + Log.Debug("loading collection: {0}", MessageHelper.CollectionInfoString(CollectionPersisters[0], id)); } object[] ids = new object[] { id }; @@ -1455,9 +1455,9 @@ public void LoadCollection(ISessionImplementor session, object id, IType type) /// public void LoadCollectionBatch(ISessionImplementor session, object[] ids, IType type) { - if (Log.IsDebugEnabled) + if (Log.IsDebugEnabled()) { - Log.Debug("batch loading collection: " + MessageHelper.CollectionInfoString(CollectionPersisters[0], ids)); + Log.Debug("batch loading collection: {0}", MessageHelper.CollectionInfoString(CollectionPersisters[0], ids)); } IType[] idTypes = new IType[ids.Length]; diff --git a/src/NHibernate/Logging.cs b/src/NHibernate/Logging.cs index 0dfd32e77fa..5d7cae37150 100644 --- a/src/NHibernate/Logging.cs +++ b/src/NHibernate/Logging.cs @@ -2,84 +2,102 @@ using System.Configuration; using System.IO; using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using NHibernate.Util; namespace NHibernate { - public interface IInternalLogger + public interface INHibernateLogger { - bool IsErrorEnabled { get; } - bool IsFatalEnabled { get; } - bool IsDebugEnabled { get; } - bool IsInfoEnabled { get; } - bool IsWarnEnabled { get; } - void Error(object message); - void Error(object message, Exception exception); - void ErrorFormat(string format, params object[] args); - - void Fatal(object message); - void Fatal(object message, Exception exception); - - void Debug(object message); - void Debug(object message, Exception exception); - void DebugFormat(string format, params object[] args); - - void Info(object message); - void Info(object message, Exception exception); - void InfoFormat(string format, params object[] args); - - void Warn(object message); - void Warn(object message, Exception exception); - void WarnFormat(string format, params object[] args); + /// Writes a log entry. + /// Entry will be written on this level. + /// The entry to be written. + /// The exception related to this entry. + void Log(NHibernateLogLevel logLevel, NHibernateLogValues state, Exception exception); + + /// + /// Checks if the given is enabled. + /// + /// level to be checked. + /// true if enabled. + bool IsEnabled(NHibernateLogLevel logLevel); } - public interface ILoggerFactory + /// + /// Factory interface for providing a . + /// + public interface INHibernateLoggerFactory { - IInternalLogger LoggerFor(string keyName); - IInternalLogger LoggerFor(System.Type type); + /// + /// Get a logger for the given log key. + /// + /// The log key. + /// A NHibernate logger. + INHibernateLogger LoggerFor(string keyName); + /// + /// Get a logger using the given type as log key. + /// + /// The type to use as log key. + /// A NHibernate logger. + INHibernateLogger LoggerFor(System.Type type); } - public class LoggerProvider + /// + /// Provide methods for getting NHibernate loggers according to supplied . + /// + /// + /// By default, it will use a if log4net is available, otherwise it will + /// use a . + /// + public static class NHibernateLogger { - private const string NhibernateLoggerConfKey = "nhibernate-logger"; - private readonly ILoggerFactory loggerFactory; - private static LoggerProvider instance; + private const string nhibernateLoggerConfKey = "nhibernate-logger"; + private static INHibernateLoggerFactory _loggerFactory; - static LoggerProvider() + static NHibernateLogger() { - string nhibernateLoggerClass = GetNhibernateLoggerClass(); - ILoggerFactory loggerFactory = string.IsNullOrEmpty(nhibernateLoggerClass) ? new NoLoggingLoggerFactory() : GetLoggerFactory(nhibernateLoggerClass); + var nhibernateLoggerClass = GetNhibernateLoggerClass(); + var loggerFactory = string.IsNullOrEmpty(nhibernateLoggerClass) ? null : GetLoggerFactory(nhibernateLoggerClass); SetLoggersFactory(loggerFactory); } - private static ILoggerFactory GetLoggerFactory(string nhibernateLoggerClass) + /// + /// Specify the logger factory to use for building loggers. + /// + /// A logger factory. + public static void SetLoggersFactory(INHibernateLoggerFactory loggerFactory) { - ILoggerFactory loggerFactory; - var loggerFactoryType = System.Type.GetType(nhibernateLoggerClass); - try - { - loggerFactory = (ILoggerFactory) Activator.CreateInstance(loggerFactoryType); - } - catch (MissingMethodException ex) - { - throw new InstantiationException("Public constructor was not found for " + loggerFactoryType, ex, loggerFactoryType); - } - catch (InvalidCastException ex) - { - throw new InstantiationException(loggerFactoryType + "Type does not implement " + typeof (ILoggerFactory), ex, loggerFactoryType); - } - catch (Exception ex) + _loggerFactory = loggerFactory ?? new NoLoggingNHibernateLoggerFactory(); + +#pragma warning disable 618 + if (!(loggerFactory is LoggerProvider.LegacyLoggerFactoryAdaptor)) { - throw new InstantiationException("Unable to instantiate: " + loggerFactoryType, ex, loggerFactoryType); + LoggerProvider.SetLoggersFactory(new LoggerProvider.ReverseLegacyLoggerFactoryAdaptor(loggerFactory)); } - return loggerFactory; +#pragma warning restore 618 + } + + /// + /// Get a logger for the given log key. + /// + /// The log key. + /// A NHibernate logger. + public static INHibernateLogger For(string keyName) + { + return _loggerFactory.LoggerFor(keyName); + } + + /// + /// Get a logger using the given type as log key. + /// + /// The type to use as log key. + /// A NHibernate logger. + public static INHibernateLogger For(System.Type type) + { + return _loggerFactory.LoggerFor(type); } private static string GetNhibernateLoggerClass() { - var nhibernateLogger = ConfigurationManager.AppSettings.Keys.Cast().FirstOrDefault(k => NhibernateLoggerConfKey.Equals(k.ToLowerInvariant())); + var nhibernateLogger = ConfigurationManager.AppSettings.Keys.Cast().FirstOrDefault(k => nhibernateLoggerConfKey.Equals(k.ToLowerInvariant())); string nhibernateLoggerClass = null; if (string.IsNullOrEmpty(nhibernateLogger)) { @@ -91,7 +109,7 @@ private static string GetNhibernateLoggerClass() if (File.Exists(log4NetDllPath) || AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == "log4net")) { - nhibernateLoggerClass = typeof (Log4NetLoggerFactory).AssemblyQualifiedName; + nhibernateLoggerClass = typeof(Log4NetLoggerFactory).AssemblyQualifiedName; } } else @@ -101,333 +119,121 @@ private static string GetNhibernateLoggerClass() return nhibernateLoggerClass; } - public static void SetLoggersFactory(ILoggerFactory loggerFactory) - { - instance = new LoggerProvider(loggerFactory); - } - - private LoggerProvider(ILoggerFactory loggerFactory) - { - this.loggerFactory = loggerFactory; - } - - public static IInternalLogger LoggerFor(string keyName) - { - return instance.loggerFactory.LoggerFor(keyName); - } - - public static IInternalLogger LoggerFor(System.Type type) + private static INHibernateLoggerFactory GetLoggerFactory(string nhibernateLoggerClass) { - return instance.loggerFactory.LoggerFor(type); + INHibernateLoggerFactory loggerFactory; + var loggerFactoryType = System.Type.GetType(nhibernateLoggerClass); + try + { + var loadedLoggerFactory = Activator.CreateInstance(loggerFactoryType); +#pragma warning disable 618 + if (loadedLoggerFactory is ILoggerFactory oldStyleFactory) + { + loggerFactory = new LoggerProvider.LegacyLoggerFactoryAdaptor(oldStyleFactory); + } +#pragma warning restore 618 + else + { + loggerFactory = (INHibernateLoggerFactory) loadedLoggerFactory; + } + } + catch (MissingMethodException ex) + { + throw new InstantiationException("Public constructor was not found for " + loggerFactoryType, ex, loggerFactoryType); + } + catch (InvalidCastException ex) + { +#pragma warning disable 618 + throw new InstantiationException(loggerFactoryType + "Type does not implement " + typeof(INHibernateLoggerFactory) + " or " + typeof(ILoggerFactory), ex, loggerFactoryType); +#pragma warning restore 618 + } + catch (Exception ex) + { + throw new InstantiationException("Unable to instantiate: " + loggerFactoryType, ex, loggerFactoryType); + } + return loggerFactory; } } - public class NoLoggingLoggerFactory: ILoggerFactory + internal class NoLoggingNHibernateLoggerFactory: INHibernateLoggerFactory { - private static readonly IInternalLogger Nologging = new NoLoggingInternalLogger(); - public IInternalLogger LoggerFor(string keyName) + private static readonly INHibernateLogger Nologging = new NoLoggingNHibernateLogger(); + public INHibernateLogger LoggerFor(string keyName) { return Nologging; } - public IInternalLogger LoggerFor(System.Type type) + public INHibernateLogger LoggerFor(System.Type type) { return Nologging; } } - public class NoLoggingInternalLogger: IInternalLogger + internal class NoLoggingNHibernateLogger: INHibernateLogger { - public bool IsErrorEnabled - { - get { return false;} - } - - public bool IsFatalEnabled - { - get { return false; } - } - - public bool IsDebugEnabled + public void Log(NHibernateLogLevel logLevel, NHibernateLogValues state, Exception exception) { - get { return false; } } - public bool IsInfoEnabled + public bool IsEnabled(NHibernateLogLevel logLevel) { - get { return false; } - } - - public bool IsWarnEnabled - { - get { return false; } - } - - public void Error(object message) - { - } - - public void Error(object message, Exception exception) - { - } + if (logLevel == NHibernateLogLevel.None) return true; - public void ErrorFormat(string format, params object[] args) - { - } - - public void Fatal(object message) - { - } - - public void Fatal(object message, Exception exception) - { - } - - public void Debug(object message) - { - } - - public void Debug(object message, Exception exception) - { - } - - public void DebugFormat(string format, params object[] args) - { - } - - public void Info(object message) - { - } - - public void Info(object message, Exception exception) - { - } - - public void InfoFormat(string format, params object[] args) - { - } - - public void Warn(object message) - { - } - - public void Warn(object message, Exception exception) - { - } - - public void WarnFormat(string format, params object[] args) - { + return false; } } - public class Log4NetLoggerFactory: ILoggerFactory + public struct NHibernateLogValues { - private static readonly System.Type LogManagerType = System.Type.GetType("log4net.LogManager, log4net"); - private static readonly Func GetLoggerByNameDelegate; - private static readonly Func GetLoggerByTypeDelegate; - static Log4NetLoggerFactory() - { - GetLoggerByNameDelegate = GetGetLoggerByNameMethodCall(); - GetLoggerByTypeDelegate = GetGetLoggerMethodCall(); - } - public IInternalLogger LoggerFor(string keyName) - { - return new Log4NetLogger(GetLoggerByNameDelegate(typeof(Log4NetLoggerFactory).Assembly, keyName)); - } - - public IInternalLogger LoggerFor(System.Type type) - { - return new Log4NetLogger(GetLoggerByTypeDelegate(type)); - } - - private static Func GetGetLoggerMethodCall() - { - var method = LogManagerType.GetMethod("GetLogger", new[] { typeof(TParameter) }); - ParameterExpression resultValue; - ParameterExpression keyParam = Expression.Parameter(typeof(TParameter), "key"); - MethodCallExpression methodCall = Expression.Call(null, method, resultValue = keyParam); - return Expression.Lambda>(methodCall, resultValue).Compile(); - } - - private static Func GetGetLoggerByNameMethodCall() - { - var method = LogManagerType.GetMethod("GetLogger", new[] {typeof(Assembly), typeof(string)}); - ParameterExpression nameParam = Expression.Parameter(typeof(string), "name"); - ParameterExpression repositoryAssemblyParam = Expression.Parameter(typeof(Assembly), "repositoryAssembly"); - MethodCallExpression methodCall = Expression.Call(null, method, repositoryAssemblyParam, nameParam); - return Expression.Lambda>(methodCall, repositoryAssemblyParam, nameParam).Compile(); + private readonly string _format; + private readonly object[] _args; + + /// + /// Instantiates a new instance of the structure. + /// + /// A composite format string + /// An object array that contains zero or more objects to format. Can be null if there are no values to format. + public NHibernateLogValues(string format, object[] args) + { + _format = format ?? "[Null]"; + _args = args; + } + + /// + /// Returns the composite format string. + /// + /// + /// A composite format string consists of zero or more runs of fixed text intermixed with + /// one or more format items, which are indicated by an index number delimited with brackets + /// (for example, {0}). The index of each format item corresponds to an argument in an object + /// list that follows the composite format string. + /// + public string Format => _format; + + /// + /// An object array that contains zero or more objects to format. Can be null if there are no values to format. + /// + public object[] Args => _args; + + /// + /// Returns the string that results from formatting the composite format string along with + /// its arguments by using the formatting conventions of the current culture. + /// + public override string ToString() + { + return _args?.Length > 0 ? string.Format(_format, _args) : Format; } } - public class Log4NetLogger: IInternalLogger + /// Defines logging severity levels. + public enum NHibernateLogLevel { - private static readonly System.Type ILogType = System.Type.GetType("log4net.ILog, log4net"); - private static readonly Func IsErrorEnabledDelegate; - private static readonly Func IsFatalEnabledDelegate; - private static readonly Func IsDebugEnabledDelegate; - private static readonly Func IsInfoEnabledDelegate; - private static readonly Func IsWarnEnabledDelegate; - - private static readonly Action ErrorDelegate; - private static readonly Action ErrorExceptionDelegate; - private static readonly Action ErrorFormatDelegate; - - private static readonly Action FatalDelegate; - private static readonly Action FatalExceptionDelegate; - - private static readonly Action DebugDelegate; - private static readonly Action DebugExceptionDelegate; - private static readonly Action DebugFormatDelegate; - - private static readonly Action InfoDelegate; - private static readonly Action InfoExceptionDelegate; - private static readonly Action InfoFormatDelegate; - - private static readonly Action WarnDelegate; - private static readonly Action WarnExceptionDelegate; - private static readonly Action WarnFormatDelegate; - - private readonly object logger; - - static Log4NetLogger() - { - IsErrorEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsErrorEnabled"); - IsFatalEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsFatalEnabled"); - IsDebugEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsDebugEnabled"); - IsInfoEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsInfoEnabled"); - IsWarnEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsWarnEnabled"); - ErrorDelegate = DelegateHelper.BuildAction(ILogType, "Error"); - ErrorExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Error"); - ErrorFormatDelegate = DelegateHelper.BuildAction(ILogType, "ErrorFormat"); - - FatalDelegate = DelegateHelper.BuildAction(ILogType, "Fatal"); - FatalExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Fatal"); - - DebugDelegate = DelegateHelper.BuildAction(ILogType, "Debug"); - DebugExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Debug"); - DebugFormatDelegate = DelegateHelper.BuildAction(ILogType, "DebugFormat"); - - InfoDelegate = DelegateHelper.BuildAction(ILogType, "Info"); - InfoExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Info"); - InfoFormatDelegate = DelegateHelper.BuildAction(ILogType, "InfoFormat"); - - WarnDelegate = DelegateHelper.BuildAction(ILogType, "Warn"); - WarnExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Warn"); - WarnFormatDelegate = DelegateHelper.BuildAction(ILogType, "WarnFormat"); - } - - public Log4NetLogger(object logger) - { - this.logger = logger; - } - - public bool IsErrorEnabled - { - get { return IsErrorEnabledDelegate(logger); } - } - - public bool IsFatalEnabled - { - get { return IsFatalEnabledDelegate(logger); } - } - - public bool IsDebugEnabled - { - get { return IsDebugEnabledDelegate(logger); } - } - - public bool IsInfoEnabled - { - get { return IsInfoEnabledDelegate(logger); } - } - - public bool IsWarnEnabled - { - get { return IsWarnEnabledDelegate(logger); } - } - - public void Error(object message) - { - if (IsErrorEnabled) - ErrorDelegate(logger, message); - } - - public void Error(object message, Exception exception) - { - if (IsErrorEnabled) - ErrorExceptionDelegate(logger, message, exception); - } - - public void ErrorFormat(string format, params object[] args) - { - if (IsErrorEnabled) - ErrorFormatDelegate(logger, format, args); - } - - public void Fatal(object message) - { - if (IsFatalEnabled) - FatalDelegate(logger, message); - } - - public void Fatal(object message, Exception exception) - { - if (IsFatalEnabled) - FatalExceptionDelegate(logger, message, exception); - } - - public void Debug(object message) - { - if (IsDebugEnabled) - DebugDelegate(logger, message); - } - - public void Debug(object message, Exception exception) - { - if (IsDebugEnabled) - DebugExceptionDelegate(logger, message, exception); - } - - public void DebugFormat(string format, params object[] args) - { - if (IsDebugEnabled) - DebugFormatDelegate(logger, format, args); - } - - public void Info(object message) - { - if (IsInfoEnabled) - InfoDelegate(logger, message); - } - - public void Info(object message, Exception exception) - { - if (IsInfoEnabled) - InfoExceptionDelegate(logger, message, exception); - } - - public void InfoFormat(string format, params object[] args) - { - if (IsInfoEnabled) - InfoFormatDelegate(logger, format, args); - } - - public void Warn(object message) - { - if (IsWarnEnabled) - WarnDelegate(logger, message); - } - - public void Warn(object message, Exception exception) - { - if (IsWarnEnabled) - WarnExceptionDelegate(logger, message, exception); - } - - public void WarnFormat(string format, params object[] args) - { - if (IsWarnEnabled) - WarnFormatDelegate(logger, format, args); - } + Trace, + Debug, + Info, + Warn, + Error, + Fatal, + None, } } diff --git a/src/NHibernate/Logging.extensions.cs b/src/NHibernate/Logging.extensions.cs new file mode 100644 index 00000000000..357fb4bff80 --- /dev/null +++ b/src/NHibernate/Logging.extensions.cs @@ -0,0 +1,154 @@ +using System; + +namespace NHibernate +{ + /// + /// Extensions method for logging. + /// + public static class NHibernateLoggerExtensions + { + public static bool IsDebugEnabled(this INHibernateLogger logger) => logger.IsEnabled(NHibernateLogLevel.Debug); + public static bool IsInfoEnabled(this INHibernateLogger logger) => logger.IsEnabled(NHibernateLogLevel.Info); + public static bool IsWarnEnabled(this INHibernateLogger logger) => logger.IsEnabled(NHibernateLogLevel.Warn); + public static bool IsErrorEnabled(this INHibernateLogger logger) => logger.IsEnabled(NHibernateLogLevel.Error); + public static bool IsFatalEnabled(this INHibernateLogger logger) => logger.IsEnabled(NHibernateLogLevel.Fatal); + + public static void Fatal(this INHibernateLogger logger, Exception exception, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Fatal, new NHibernateLogValues(format, args), exception); + } + + public static void Fatal(this INHibernateLogger logger, Exception exception, string message) + { + logger.Log(NHibernateLogLevel.Fatal, new NHibernateLogValues(message, null), exception); + } + + public static void Fatal(this INHibernateLogger logger, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Fatal, new NHibernateLogValues(format, args), null); + } + + public static void Fatal(this INHibernateLogger logger, string message) + { + logger.Log(NHibernateLogLevel.Fatal, new NHibernateLogValues(message, null), null); + } + + public static void Error(this INHibernateLogger logger, Exception exception, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Error, new NHibernateLogValues(format, args), exception); + } + + public static void Error(this INHibernateLogger logger, Exception exception, string message) + { + logger.Log(NHibernateLogLevel.Error, new NHibernateLogValues(message, null), exception); + } + + public static void Error(this INHibernateLogger logger, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Error, new NHibernateLogValues(format, args), null); + } + + public static void Error(this INHibernateLogger logger, string message) + { + logger.Log(NHibernateLogLevel.Error, new NHibernateLogValues(message, null), null); + } + + public static void Warn(this INHibernateLogger logger, Exception exception, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Warn, new NHibernateLogValues(format, args), exception); + } + + public static void Warn(this INHibernateLogger logger, Exception exception, string message) + { + logger.Log(NHibernateLogLevel.Warn, new NHibernateLogValues(message, null), exception); + } + + public static void Warn(this INHibernateLogger logger, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Warn, new NHibernateLogValues(format, args), null); + } + + public static void Warn(this INHibernateLogger logger, string message) + { + logger.Log(NHibernateLogLevel.Warn, new NHibernateLogValues(message, null), null); + } + + public static void Info(this INHibernateLogger logger, Exception exception, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Info, new NHibernateLogValues(format, args), exception); + } + + public static void Info(this INHibernateLogger logger, Exception exception, string message) + { + logger.Log(NHibernateLogLevel.Info, new NHibernateLogValues(message, null), exception); + } + + public static void Info(this INHibernateLogger logger, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Info, new NHibernateLogValues(format, args), null); + } + + public static void Info(this INHibernateLogger logger, string message) + { + logger.Log(NHibernateLogLevel.Info, new NHibernateLogValues(message, null), null); + } + + public static void Debug(this INHibernateLogger logger, Exception exception, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Debug, new NHibernateLogValues(format, args), exception); + } + + public static void Debug(this INHibernateLogger logger, Exception exception, string message) + { + logger.Log(NHibernateLogLevel.Debug, new NHibernateLogValues(message, null), exception); + } + + public static void Debug(this INHibernateLogger logger, string format, params object[] args) + { + logger.Log(NHibernateLogLevel.Debug, new NHibernateLogValues(format, args), null); + } + + public static void Debug(this INHibernateLogger logger, string message) + { + logger.Log(NHibernateLogLevel.Debug, new NHibernateLogValues(message, null), null); + } + + + // catch any method calls with an Exception argument second as they would otherwise silently be consumed by `params object[] args`. + + /// + /// Throws NotImplementedException. Calling this method is an error. Please use methods taking the exception as first argument instead. + /// + [Obsolete("Use Fatal(Exception, string, params object[])", true)] + public static void Fatal(this INHibernateLogger logger, string message, Exception ex) => ThrowNotImplemented(); + + /// + /// Throws NotImplementedException. Calling this method is an error. Please use methods taking the exception as first argument instead. + /// + [Obsolete("Use Error(Exception, string, params object[])", true)] + public static void Error(this INHibernateLogger logger, string message, Exception ex) => ThrowNotImplemented(); + + /// + /// Throws NotImplementedException. Calling this method is an error. Please use methods taking the exception as first argument instead. + /// + [Obsolete("Use Warn(Exception, string, params object[])", true)] + public static void Warn(this INHibernateLogger logger, string message, Exception ex) => ThrowNotImplemented(); + + /// + /// Throws NotImplementedException. Calling this method is an error. Please use methods taking the exception as first argument instead. + /// + [Obsolete("Use Info(Exception, string, params object[])", true)] + public static void Info(this INHibernateLogger logger, string message, Exception ex) => ThrowNotImplemented(); + + /// + /// Throws NotImplementedException. Calling this method is an error. Please use methods taking the exception as first argument instead. + /// + [Obsolete("Use Debug(Exception, string, params object[])", true)] + public static void Debug(this INHibernateLogger logger, string message, Exception ex) => ThrowNotImplemented(); + + private static void ThrowNotImplemented() + { + throw new NotImplementedException("Should not have compiled with call to this method"); + } + } +} diff --git a/src/NHibernate/Logging.log4net.cs b/src/NHibernate/Logging.log4net.cs new file mode 100644 index 00000000000..6dc14e3118c --- /dev/null +++ b/src/NHibernate/Logging.log4net.cs @@ -0,0 +1,238 @@ +using System; +using System.Linq.Expressions; +using System.Reflection; +using NHibernate.Util; + +namespace NHibernate +{ +#pragma warning disable 618 // ILoggerFactory is obsolete + /// + /// Reflection based log4net logger factory. + /// + public class Log4NetLoggerFactory: ILoggerFactory +#pragma warning restore 618 + { + private static readonly System.Type LogManagerType = System.Type.GetType("log4net.LogManager, log4net"); + private static readonly Func GetLoggerByNameDelegate; + private static readonly Func GetLoggerByTypeDelegate; + + static Log4NetLoggerFactory() + { + GetLoggerByNameDelegate = GetGetLoggerByNameMethodCall(); + GetLoggerByTypeDelegate = GetGetLoggerMethodCall(); + } + +#pragma warning disable 618 + [Obsolete("Use this as an INHibernateLoggerFactory instead.")] + public IInternalLogger LoggerFor(string keyName) + { + return new Log4NetLogger(GetLoggerByNameDelegate(typeof(Log4NetLoggerFactory).Assembly, keyName)); + } + + [Obsolete("Use this as an INHibernateLoggerFactory instead.")] + public IInternalLogger LoggerFor(System.Type type) + { + return new Log4NetLogger(GetLoggerByTypeDelegate(type)); + } +#pragma warning restore 618 + + private static Func GetGetLoggerMethodCall() + { + var method = LogManagerType.GetMethod("GetLogger", new[] { typeof(TParameter) }); + ParameterExpression resultValue; + ParameterExpression keyParam = Expression.Parameter(typeof(TParameter), "key"); + MethodCallExpression methodCall = Expression.Call(null, method, resultValue = keyParam); + return Expression.Lambda>(methodCall, resultValue).Compile(); + } + + private static Func GetGetLoggerByNameMethodCall() + { + var method = LogManagerType.GetMethod("GetLogger", new[] {typeof(Assembly), typeof(string)}); + ParameterExpression nameParam = Expression.Parameter(typeof(string), "name"); + ParameterExpression repositoryAssemblyParam = Expression.Parameter(typeof(Assembly), "repositoryAssembly"); + MethodCallExpression methodCall = Expression.Call(null, method, repositoryAssemblyParam, nameParam); + return Expression.Lambda>(methodCall, repositoryAssemblyParam, nameParam).Compile(); + } + } + +#pragma warning disable 618 // IInternalLogger is obsolete, to be removed in a upcoming major version + /// + /// Reflection based log4net logger. + /// + public class Log4NetLogger : IInternalLogger +#pragma warning restore 618 + { + private static readonly System.Type ILogType = System.Type.GetType("log4net.ILog, log4net"); + private static readonly Func IsErrorEnabledDelegate; + private static readonly Func IsFatalEnabledDelegate; + private static readonly Func IsDebugEnabledDelegate; + private static readonly Func IsInfoEnabledDelegate; + private static readonly Func IsWarnEnabledDelegate; + + private static readonly Action ErrorDelegate; + private static readonly Action ErrorExceptionDelegate; + private static readonly Action ErrorFormatDelegate; + + private static readonly Action FatalDelegate; + private static readonly Action FatalExceptionDelegate; + + private static readonly Action DebugDelegate; + private static readonly Action DebugExceptionDelegate; + private static readonly Action DebugFormatDelegate; + + private static readonly Action InfoDelegate; + private static readonly Action InfoExceptionDelegate; + private static readonly Action InfoFormatDelegate; + + private static readonly Action WarnDelegate; + private static readonly Action WarnExceptionDelegate; + private static readonly Action WarnFormatDelegate; + + private readonly object _logger; + + static Log4NetLogger() + { + IsErrorEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsErrorEnabled"); + IsFatalEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsFatalEnabled"); + IsDebugEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsDebugEnabled"); + IsInfoEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsInfoEnabled"); + IsWarnEnabledDelegate = DelegateHelper.BuildPropertyGetter(ILogType, "IsWarnEnabled"); + ErrorDelegate = DelegateHelper.BuildAction(ILogType, "Error"); + ErrorExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Error"); + ErrorFormatDelegate = DelegateHelper.BuildAction(ILogType, "ErrorFormat"); + + FatalDelegate = DelegateHelper.BuildAction(ILogType, "Fatal"); + FatalExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Fatal"); + + DebugDelegate = DelegateHelper.BuildAction(ILogType, "Debug"); + DebugExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Debug"); + DebugFormatDelegate = DelegateHelper.BuildAction(ILogType, "DebugFormat"); + + InfoDelegate = DelegateHelper.BuildAction(ILogType, "Info"); + InfoExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Info"); + InfoFormatDelegate = DelegateHelper.BuildAction(ILogType, "InfoFormat"); + + WarnDelegate = DelegateHelper.BuildAction(ILogType, "Warn"); + WarnExceptionDelegate = DelegateHelper.BuildAction(ILogType, "Warn"); + WarnFormatDelegate = DelegateHelper.BuildAction(ILogType, "WarnFormat"); + } + + /// + /// Default constructor. + /// + /// The log4net.ILog logger to use for logging. + public Log4NetLogger(object logger) + { + _logger = logger; + } + + public bool IsErrorEnabled + { + get { return IsErrorEnabledDelegate(_logger); } + } + + public bool IsFatalEnabled + { + get { return IsFatalEnabledDelegate(_logger); } + } + + public bool IsDebugEnabled + { + get { return IsDebugEnabledDelegate(_logger); } + } + + public bool IsInfoEnabled + { + get { return IsInfoEnabledDelegate(_logger); } + } + + public bool IsWarnEnabled + { + get { return IsWarnEnabledDelegate(_logger); } + } + + public void Error(object message) + { + if (IsErrorEnabled) + ErrorDelegate(_logger, message); + } + + public void Error(object message, Exception exception) + { + if (IsErrorEnabled) + ErrorExceptionDelegate(_logger, message, exception); + } + + public void ErrorFormat(string format, params object[] args) + { + if (IsErrorEnabled) + ErrorFormatDelegate(_logger, format, args); + } + + public void Fatal(object message) + { + if (IsFatalEnabled) + FatalDelegate(_logger, message); + } + + public void Fatal(object message, Exception exception) + { + if (IsFatalEnabled) + FatalExceptionDelegate(_logger, message, exception); + } + + public void Debug(object message) + { + if (IsDebugEnabled) + DebugDelegate(_logger, message); + } + + public void Debug(object message, Exception exception) + { + if (IsDebugEnabled) + DebugExceptionDelegate(_logger, message, exception); + } + + public void DebugFormat(string format, params object[] args) + { + if (IsDebugEnabled) + DebugFormatDelegate(_logger, format, args); + } + + public void Info(object message) + { + if (IsInfoEnabled) + InfoDelegate(_logger, message); + } + + public void Info(object message, Exception exception) + { + if (IsInfoEnabled) + InfoExceptionDelegate(_logger, message, exception); + } + + public void InfoFormat(string format, params object[] args) + { + if (IsInfoEnabled) + InfoFormatDelegate(_logger, format, args); + } + + public void Warn(object message) + { + if (IsWarnEnabled) + WarnDelegate(_logger, message); + } + + public void Warn(object message, Exception exception) + { + if (IsWarnEnabled) + WarnExceptionDelegate(_logger, message, exception); + } + + public void WarnFormat(string format, params object[] args) + { + if (IsWarnEnabled) + WarnFormatDelegate(_logger, format, args); + } + } +} diff --git a/src/NHibernate/Logging.obsolete.cs b/src/NHibernate/Logging.obsolete.cs new file mode 100644 index 00000000000..ff8f5f5be30 --- /dev/null +++ b/src/NHibernate/Logging.obsolete.cs @@ -0,0 +1,435 @@ +using System; + +namespace NHibernate +{ + // Since v5.1 + [Obsolete("Implement and use NHibernate.INHibernateLogger")] + public interface IInternalLogger + { + // Since v5.1 + [Obsolete("Please use IsErrorEnabled() INHibernateLogger extension method instead.")] + bool IsErrorEnabled { get; } + // Since v5.1 + [Obsolete("Please use IsFatalEnabled() INHibernateLogger extension method instead.")] + bool IsFatalEnabled { get; } + // Since v5.1 + [Obsolete("Please use IsDebugEnabled() INHibernateLogger extension method instead.")] + bool IsDebugEnabled { get; } + // Since v5.1 + [Obsolete("Please use IsInfoEnabled() INHibernateLogger extension method instead.")] + bool IsInfoEnabled { get; } + // Since v5.1 + [Obsolete("Please use IsWarnEnabled() INHibernateLogger extension method instead.")] + bool IsWarnEnabled { get; } + + // Since v5.1 + [Obsolete("Please use Error(string, params object[]) INHibernateLogger extension method instead.")] + void Error(object message); + // Since v5.1 + [Obsolete("Please use Error(Exception, string, params object[]) INHibernateLogger extension method instead.")] + void Error(object message, Exception exception); + // Since v5.1 + [Obsolete("Please use Error(string, params object[]) INHibernateLogger extension method instead.")] + void ErrorFormat(string format, params object[] args); + + // Since v5.1 + [Obsolete("Please use Fatal(string, params object[]) INHibernateLogger extension method instead.")] + void Fatal(object message); + // Since v5.1 + [Obsolete("Please use Fatal(Exception, string, params object[]) INHibernateLogger extension method instead.")] + void Fatal(object message, Exception exception); + + // Since v5.1 + [Obsolete("Please use Debug(string, params object[]) INHibernateLogger extension method instead.")] + void Debug(object message); + // Since v5.1 + [Obsolete("Please use Debug(Exception, string, params object[]) INHibernateLogger extension method instead.")] + void Debug(object message, Exception exception); + // Since v5.1 + [Obsolete("Please use Debug(string, params object[]) INHibernateLogger extension method instead.")] + void DebugFormat(string format, params object[] args); + + // Since v5.1 + [Obsolete("Please use Info(string, params object[]) INHibernateLogger extension method instead.")] + void Info(object message); + // Since v5.1 + [Obsolete("Please use Info(Exception, string, params object[]) INHibernateLogger extension method instead.")] + void Info(object message, Exception exception); + // Since v5.1 + [Obsolete("Please use Info(string, params object[]) INHibernateLogger extension method instead.")] + void InfoFormat(string format, params object[] args); + + // Since v5.1 + [Obsolete("Please use Warn(string, params object[]) INHibernateLogger extension method instead.")] + void Warn(object message); + // Since v5.1 + [Obsolete("Please use Warn(Exception, string, params object[]) INHibernateLogger extension method instead.")] + void Warn(object message, Exception exception); + // Since v5.1 + [Obsolete("Please use Warn(string, params object[]) INHibernateLogger extension method instead.")] + void WarnFormat(string format, params object[] args); + } + + // Since 5.1 + [Obsolete("Implement INHibernateLoggerFactory instead")] + public interface ILoggerFactory + { + IInternalLogger LoggerFor(string keyName); + IInternalLogger LoggerFor(System.Type type); + } + + + [Obsolete("Use NHibernateLogger instead.")] + public class LoggerProvider + { + private static ILoggerFactory _legacyLoggerFactory; + + [Obsolete("Implement INHibernateLoggerFactory and use NHibernateLogger.SetLoggersFactory() instead")] + public static void SetLoggersFactory(ILoggerFactory loggerFactory) + { + _legacyLoggerFactory = loggerFactory ?? new NoLoggingLoggerFactory(); + + if (!(loggerFactory is ReverseLegacyLoggerFactoryAdaptor)) + { + var factory = loggerFactory == null || loggerFactory is NoLoggingLoggerFactory + ? null + : (INHibernateLoggerFactory) new LegacyLoggerFactoryAdaptor(loggerFactory); + + NHibernateLogger.SetLoggersFactory(factory); + } + } + + [Obsolete("Use NHibernateLogger.For() instead.")] + public static IInternalLogger LoggerFor(string keyName) + { + return _legacyLoggerFactory.LoggerFor(keyName); + } + + [Obsolete("Use NHibernateLogger.For() instead.")] + public static IInternalLogger LoggerFor(System.Type type) + { + return _legacyLoggerFactory.LoggerFor(type); + } + + // Since 5.1 + [Obsolete("Used only in Obsolete functions to thunk to INHibernateLoggerFactory")] + internal class LegacyLoggerFactoryAdaptor : INHibernateLoggerFactory + { + private readonly ILoggerFactory _factory; + + public LegacyLoggerFactoryAdaptor(ILoggerFactory factory) + { + _factory = factory; + } + + public INHibernateLogger LoggerFor(string keyName) + { + return new NHibernateLoggerThunk(_factory.LoggerFor(keyName)); + } + + public INHibernateLogger LoggerFor(System.Type type) + { + return new NHibernateLoggerThunk(_factory.LoggerFor(type)); + } + } + + // Since 5.1 + [Obsolete("Used only in Obsolete functions to thunk to INHibernateLoggerFactory")] + internal class ReverseLegacyLoggerFactoryAdaptor : ILoggerFactory + { + private readonly INHibernateLoggerFactory _factory; + + public ReverseLegacyLoggerFactoryAdaptor(INHibernateLoggerFactory factory) + { + _factory = factory; + } + + public IInternalLogger LoggerFor(string keyName) + { + return new InternalLoggerThunk(_factory.LoggerFor(keyName)); + } + + public IInternalLogger LoggerFor(System.Type type) + { + return new InternalLoggerThunk(_factory.LoggerFor(type)); + } + } + } + + // Since 5.1 + [Obsolete("Used only in Obsolete functions to thunk to INHibernateLoggerFactory")] + internal class NHibernateLoggerThunk : INHibernateLogger + { + private readonly IInternalLogger _internalLogger; + + public NHibernateLoggerThunk(IInternalLogger internalLogger) + { + _internalLogger = internalLogger ?? throw new ArgumentNullException(nameof(internalLogger)); + } + + public void Log(NHibernateLogLevel logLevel, NHibernateLogValues state, Exception exception) + { + if (!IsEnabled(logLevel)) + return; + + switch (logLevel) + { + case NHibernateLogLevel.Debug: + case NHibernateLogLevel.Trace: + if (exception != null) + _internalLogger.Debug(state, exception); + else if (state.Args?.Length > 0) + _internalLogger.DebugFormat(state.Format, state.Args); + else + _internalLogger.Debug(state); + break; + case NHibernateLogLevel.Info: + if (exception != null) + _internalLogger.Info(state, exception); + else if (state.Args?.Length > 0) + _internalLogger.InfoFormat(state.Format, state.Args); + else + _internalLogger.Info(state); + break; + case NHibernateLogLevel.Warn: + if (exception != null) + _internalLogger.Warn(state, exception); + else if (state.Args?.Length > 0) + _internalLogger.WarnFormat(state.Format, state.Args); + else + _internalLogger.Warn(state); + break; + case NHibernateLogLevel.Error: + if (exception != null) + _internalLogger.Error(state, exception); + else if (state.Args?.Length > 0) + _internalLogger.ErrorFormat(state.Format, state.Args); + else + _internalLogger.Error(state); + break; + case NHibernateLogLevel.Fatal: + if (exception != null) + _internalLogger.Fatal(state, exception); + else + _internalLogger.Fatal(state); + break; + case NHibernateLogLevel.None: + break; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + } + + public bool IsEnabled(NHibernateLogLevel logLevel) + { + switch (logLevel) + { + case NHibernateLogLevel.Trace: + case NHibernateLogLevel.Debug: + return _internalLogger.IsDebugEnabled; + case NHibernateLogLevel.Info: + return _internalLogger.IsInfoEnabled; + case NHibernateLogLevel.Warn: + return _internalLogger.IsWarnEnabled; + case NHibernateLogLevel.Error: + return _internalLogger.IsErrorEnabled; + case NHibernateLogLevel.Fatal: + return _internalLogger.IsFatalEnabled; + case NHibernateLogLevel.None: + return !_internalLogger.IsFatalEnabled; + default: + throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); + } + } + } + + // Since 5.1 + [Obsolete("Used only in Obsolete functions to thunk to ILoggerFactory")] + internal class InternalLoggerThunk : IInternalLogger + { + private readonly INHibernateLogger _nhibernateLogger; + + public bool IsErrorEnabled => _nhibernateLogger.IsEnabled(NHibernateLogLevel.Error); + public bool IsFatalEnabled => _nhibernateLogger.IsEnabled(NHibernateLogLevel.Fatal); + public bool IsDebugEnabled => _nhibernateLogger.IsEnabled(NHibernateLogLevel.Debug); + public bool IsInfoEnabled => _nhibernateLogger.IsEnabled(NHibernateLogLevel.Info); + public bool IsWarnEnabled => _nhibernateLogger.IsEnabled(NHibernateLogLevel.Warn); + + public InternalLoggerThunk(INHibernateLogger nhibernateLogger) + { + _nhibernateLogger = nhibernateLogger; + } + + public void Error(object message) + { + _nhibernateLogger.Error(message?.ToString()); + } + + public void Error(object message, Exception exception) + { + _nhibernateLogger.Error(exception, message?.ToString()); + } + + public void ErrorFormat(string format, params object[] args) + { + _nhibernateLogger.Error(format, args); + } + + public void Fatal(object message) + { + _nhibernateLogger.Fatal(message?.ToString()); + } + + public void Fatal(object message, Exception exception) + { + _nhibernateLogger.Fatal(exception, message?.ToString()); + } + + public void Debug(object message) + { + _nhibernateLogger.Debug(message?.ToString()); + } + + public void Debug(object message, Exception exception) + { + _nhibernateLogger.Debug(exception, message?.ToString()); + } + + public void DebugFormat(string format, params object[] args) + { + _nhibernateLogger.Debug(format, args); + } + + public void Info(object message) + { + _nhibernateLogger.Info(message?.ToString()); + } + + public void Info(object message, Exception exception) + { + _nhibernateLogger.Info(exception, message?.ToString()); + } + + public void InfoFormat(string format, params object[] args) + { + _nhibernateLogger.Info(format, args); + } + + public void Warn(object message) + { + _nhibernateLogger.Warn(message?.ToString()); + } + + public void Warn(object message, Exception exception) + { + _nhibernateLogger.Warn(exception, message?.ToString()); + } + + public void WarnFormat(string format, params object[] args) + { + _nhibernateLogger.Warn(format, args); + } + } + + // Since 5.1 + [Obsolete("To set no-logging, use NHibernateLogger.SetLoggersFactory(default(INHibernateLoggerFactory))")] + public class NoLoggingLoggerFactory: ILoggerFactory + { + private static readonly IInternalLogger Nologging = new NoLoggingInternalLogger(); + public IInternalLogger LoggerFor(string keyName) + { + return Nologging; + } + + public IInternalLogger LoggerFor(System.Type type) + { + return Nologging; + } + } + + // Since 5.1 + [Obsolete("To set no-logging, use NHibernateLogger.SetLoggersFactory(default(INHibernateLoggerFactory))")] + public class NoLoggingInternalLogger: IInternalLogger + { + public bool IsErrorEnabled + { + get { return false;} + } + + public bool IsFatalEnabled + { + get { return false; } + } + + public bool IsDebugEnabled + { + get { return false; } + } + + public bool IsInfoEnabled + { + get { return false; } + } + + public bool IsWarnEnabled + { + get { return false; } + } + + public void Error(object message) + { + } + + public void Error(object message, Exception exception) + { + } + + public void ErrorFormat(string format, params object[] args) + { + } + + public void Fatal(object message) + { + } + + public void Fatal(object message, Exception exception) + { + } + + public void Debug(object message) + { + } + + public void Debug(object message, Exception exception) + { + } + + public void DebugFormat(string format, params object[] args) + { + } + + public void Info(object message) + { + } + + public void Info(object message, Exception exception) + { + } + + public void InfoFormat(string format, params object[] args) + { + } + + public void Warn(object message) + { + } + + public void Warn(object message, Exception exception) + { + } + + public void WarnFormat(string format, params object[] args) + { + } + } +} diff --git a/src/NHibernate/Mapping/RootClass.cs b/src/NHibernate/Mapping/RootClass.cs index 1aa12a3eda3..59210b16467 100644 --- a/src/NHibernate/Mapping/RootClass.cs +++ b/src/NHibernate/Mapping/RootClass.cs @@ -15,7 +15,7 @@ namespace NHibernate.Mapping [Serializable] public class RootClass : PersistentClass, ITableOwner { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(RootClass)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(RootClass)); /// /// The default name of the column for the Identifier @@ -387,11 +387,11 @@ private void CheckCompositeIdentifier() System.Type idClass = id.ComponentClass; if (idClass != null && !ReflectHelper.OverridesEquals(idClass)) { - log.Warn("composite-id class does not override Equals(): " + id.ComponentClass.FullName); + log.Warn("composite-id class does not override Equals(): {0}", id.ComponentClass.FullName); } if (!ReflectHelper.OverridesGetHashCode(idClass)) { - log.Warn("composite-id class does not override GetHashCode(): " + id.ComponentClass.FullName); + log.Warn("composite-id class does not override GetHashCode(): {0}", id.ComponentClass.FullName); } // NH: Not ported //if (!typeof(System.Runtime.Serialization.ISerializable).IsAssignableFrom(idClass)) diff --git a/src/NHibernate/NonUniqueResultException.cs b/src/NHibernate/NonUniqueResultException.cs index fee84c0109e..1dfb262a3d9 100644 --- a/src/NHibernate/NonUniqueResultException.cs +++ b/src/NHibernate/NonUniqueResultException.cs @@ -19,8 +19,7 @@ public class NonUniqueResultException : HibernateException public NonUniqueResultException(int resultCount) : base("query did not return a unique result: " + resultCount.ToString()) { - LoggerProvider.LoggerFor(typeof(NonUniqueResultException)).Error("query did not return a unique result: " + - resultCount.ToString()); + NHibernateLogger.For(typeof(NonUniqueResultException)).Error("query did not return a unique result: {0}", resultCount); } /// @@ -39,4 +38,4 @@ protected NonUniqueResultException(SerializationInfo info, StreamingContext cont { } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs b/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs index af430968a1d..1c3d000de8c 100644 --- a/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs +++ b/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs @@ -159,7 +159,7 @@ public abstract partial class AbstractCollectionPersister : ICollectionMetadata, private readonly IDictionary collectionPropertyColumnAliases = new Dictionary(); private readonly IDictionary collectionPropertyColumnNames = new Dictionary(); - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (ICollectionPersister)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (ICollectionPersister)); public AbstractCollectionPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache, ISessionFactoryImplementor factory) { @@ -565,27 +565,27 @@ public void PostInstantiate() protected void LogStaticSQL() { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Static SQL for collection: " + Role); + log.Debug("Static SQL for collection: {0}", Role); if (SqlInsertRowString != null) { - log.Debug(" Row insert: " + SqlInsertRowString.Text); + log.Debug(" Row insert: {0}", SqlInsertRowString.Text); } if (SqlUpdateRowString != null) { - log.Debug(" Row update: " + SqlUpdateRowString.Text); + log.Debug(" Row update: {0}", SqlUpdateRowString.Text); } if (SqlDeleteRowString != null) { - log.Debug(" Row delete: " + SqlDeleteRowString.Text); + log.Debug(" Row delete: {0}", SqlDeleteRowString.Text); } if (SqlDeleteString != null) { - log.Debug(" One-shot delete: " + SqlDeleteString.Text); + log.Debug(" One-shot delete: {0}", SqlDeleteString.Text); } } } @@ -1025,9 +1025,9 @@ public void Remove(object id, ISessionImplementor session) { if (!isInverse && RowDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Deleting collection: " + MessageHelper.CollectionInfoString(this, id, Factory)); + log.Debug("Deleting collection: {0}", MessageHelper.CollectionInfoString(this, id, Factory)); } // Remove all the old entries @@ -1070,7 +1070,7 @@ public void Remove(object id, ISessionImplementor session) } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { log.Debug("done deleting collection"); } @@ -1087,9 +1087,9 @@ public void Recreate(IPersistentCollection collection, object id, ISessionImplem { if (!isInverse && RowInsertEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting collection: " + MessageHelper.CollectionInfoString(this, collection, id, session)); + log.Debug("Inserting collection: {0}", MessageHelper.CollectionInfoString(this, collection, id, session)); } try @@ -1129,10 +1129,10 @@ public void Recreate(IPersistentCollection collection, object id, ISessionImplem i++; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (count > 0) - log.Debug(string.Format("done inserting collection: {0} rows inserted", count)); + log.Debug("done inserting collection: {0} rows inserted", count); else log.Debug("collection was empty"); } @@ -1149,9 +1149,9 @@ public void DeleteRows(IPersistentCollection collection, object id, ISessionImpl { if (!isInverse && RowDeleteEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Deleting rows of collection: " + MessageHelper.CollectionInfoString(this, collection, id, session)); + log.Debug("Deleting rows of collection: {0}", MessageHelper.CollectionInfoString(this, collection, id, session)); } bool deleteByIndex = !IsOneToMany && hasIndex && !indexContainsFormula; @@ -1228,10 +1228,10 @@ public void DeleteRows(IPersistentCollection collection, object id, ISessionImpl } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (count > 0) - log.Debug("done deleting collection rows: " + count + " deleted"); + log.Debug("done deleting collection rows: {0} deleted", count); else log.Debug("no rows to delete"); } @@ -1248,9 +1248,9 @@ public void InsertRows(IPersistentCollection collection, object id, ISessionImpl { if (!isInverse && RowInsertEnabled) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting rows of collection: " + MessageHelper.CollectionInfoString(this, collection, id, session)); + log.Debug("Inserting rows of collection: {0}", MessageHelper.CollectionInfoString(this, collection, id, session)); } try @@ -1284,9 +1284,9 @@ public void InsertRows(IPersistentCollection collection, object id, ISessionImpl i++; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("done inserting rows: {0} inserted", count)); + log.Debug("done inserting rows: {0} inserted", count); } } catch (DbException sqle) @@ -1377,17 +1377,17 @@ public void UpdateRows(IPersistentCollection collection, object id, ISessionImpl { if (!isInverse && collection.RowUpdatePossible) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("Updating rows of collection: {0}#{1}", role, id)); + log.Debug("Updating rows of collection: {0}#{1}", role, id); } // update all the modified entries int count = DoUpdateRows(id, collection, session); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("done updating rows: {0} updated", count)); + log.Debug("done updating rows: {0} updated", count); } } } diff --git a/src/NHibernate/Persister/Collection/NamedQueryCollectionInitializer.cs b/src/NHibernate/Persister/Collection/NamedQueryCollectionInitializer.cs index c20ff3f26fd..710ef996369 100644 --- a/src/NHibernate/Persister/Collection/NamedQueryCollectionInitializer.cs +++ b/src/NHibernate/Persister/Collection/NamedQueryCollectionInitializer.cs @@ -10,7 +10,7 @@ public partial class NamedQueryCollectionInitializer : ICollectionInitializer private readonly string queryName; private readonly ICollectionPersister persister; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(NamedQueryCollectionInitializer)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(NamedQueryCollectionInitializer)); public NamedQueryCollectionInitializer(string queryName, ICollectionPersister persister) { @@ -20,9 +20,9 @@ public NamedQueryCollectionInitializer(string queryName, ICollectionPersister pe public void Initialize(object key, ISessionImplementor session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("initializing collection: {0} using named query: {1}", persister.Role, queryName)); + log.Debug("initializing collection: {0} using named query: {1}", persister.Role, queryName); } //TODO: is there a more elegant way than downcasting? @@ -38,4 +38,4 @@ public void Initialize(object key, ISessionImplementor session) query.SetCollectionKey(key).SetFlushMode(FlushMode.Manual).List(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs index a51ef2c52c3..922137b6745 100644 --- a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs +++ b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs @@ -110,7 +110,7 @@ public virtual void BindValues(DbCommand ps) } } - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(AbstractEntityPersister)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AbstractEntityPersister)); public const string EntityClass = "class"; protected const string Discriminator_Alias = "clazz_"; @@ -1238,11 +1238,11 @@ public virtual object InitializeLazyProperty(string fieldName, object entity, IS if (entry == null) throw new HibernateException("entity is not associated with the session: " + id); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug( - string.Format("initializing lazy properties of: {0}, field access: {1}", - MessageHelper.InfoString(this, id, Factory), fieldName)); + log.Debug("initializing lazy properties of: {0}, field access: {1}", + MessageHelper.InfoString(this, id, Factory), + fieldName); } if (HasCache && session.CacheMode.HasFlag(CacheMode.Get)) @@ -1442,9 +1442,9 @@ public string PropertySelectFragment(string name, string suffix, bool allPropert public object[] GetDatabaseSnapshot(object id, ISessionImplementor session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Getting current persistent state for: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Getting current persistent state for: {0}", MessageHelper.InfoString(this, id, Factory)); } using (session.BeginProcess()) @@ -1638,12 +1638,12 @@ public object ForceVersionIncrement(object id, object currentVersion, ISessionIm } object nextVersion = VersionType.Next(currentVersion, session); - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Forcing version increment [" + - MessageHelper.InfoString(this, id, Factory) + "; " + - VersionType.ToLoggableString(currentVersion, Factory) + " -> " + - VersionType.ToLoggableString(nextVersion, Factory) + "]"); + log.Debug("Forcing version increment [{0}; {1} -> {2}]", + MessageHelper.InfoString(this, id, Factory), + VersionType.ToLoggableString(currentVersion, Factory), + VersionType.ToLoggableString(nextVersion, Factory)); } IExpectation expectation = Expectations.AppropriateExpectation(updateResultCheckStyles[0]); @@ -1698,9 +1698,9 @@ private SqlCommandInfo GenerateVersionIncrementUpdateString() /// public object GetCurrentVersion(object id, ISessionImplementor session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Getting version: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Getting version: {0}", MessageHelper.InfoString(this, id, Factory)); } using (session.BeginProcess()) try @@ -2430,9 +2430,9 @@ protected int Dehydrate(object id, object[] fields, bool[] includeProperty, bool protected int Dehydrate(object id, object[] fields, object rowId, bool[] includeProperty, bool[][] includeColumns, int table, DbCommand statement, ISessionImplementor session, int index) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Dehydrating entity: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Dehydrating entity: {0}", MessageHelper.InfoString(this, id, Factory)); } // there's a pretty strong coupling between the order of the SQL parameter @@ -2478,9 +2478,9 @@ protected int Dehydrate(object id, object[] fields, object rowId, bool[] include public object[] Hydrate(DbDataReader rs, object id, object obj, ILoadable rootLoadable, string[][] suffixedPropertyColumns, bool allProperties, ISessionImplementor session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Hydrating entity: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Hydrating entity: {0}", MessageHelper.InfoString(this, id, Factory)); } AbstractEntityPersister rootPersister = (AbstractEntityPersister)rootLoadable; @@ -2602,12 +2602,12 @@ protected virtual SqlString GetSequentialSelect(string entityName) /// protected object Insert(object[] fields, bool[] notNull, SqlCommandInfo sql, object obj, ISessionImplementor session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting entity: " + EntityName + " (native id)"); + log.Debug("Inserting entity: {0} (native id)", EntityName); if (IsVersioned) { - log.Debug("Version: " + Versioning.GetVersion(fields, this)); + log.Debug("Version: {0}", Versioning.GetVersion(fields, this)); } } IBinder binder = new GeneratedIdentifierBinder(fields, notNull, session, obj, this); @@ -2647,12 +2647,12 @@ protected void Insert(object id, object[] fields, bool[] notNull, int j, return; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Inserting entity: " + MessageHelper.InfoString(this, tableId, Factory)); + log.Debug("Inserting entity: {0}", MessageHelper.InfoString(this, tableId, Factory)); if (j == 0 && IsVersioned) { - log.Debug("Version: " + Versioning.GetVersion(fields, this)); + log.Debug("Version: {0}", Versioning.GetVersion(fields, this)); } } @@ -2765,12 +2765,12 @@ protected bool Update(object id, object[] fields, object[] oldFields, object row //bool callable = IsUpdateCallable(j); bool useBatch = j == 0 && expectation.CanBeBatched && IsBatchable; //note: updates to joined tables can't be batched... - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Updating entity: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Updating entity: {0}", MessageHelper.InfoString(this, id, Factory)); if (useVersion) { - log.Debug("Existing version: " + oldVersion + " -> New Version: " + fields[VersionProperty]); + log.Debug("Existing version: {0} -> New Version: {1}", oldVersion, fields[VersionProperty]); } } @@ -2886,20 +2886,20 @@ public void Delete(object id, object version, int j, object obj, SqlCommandInfo IExpectation expectation = Expectations.AppropriateExpectation(deleteResultCheckStyles[j]); bool useBatch = j == 0 && expectation.CanBeBatched && IsBatchable; - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Deleting entity: " + MessageHelper.InfoString(this, tableId, Factory)); + log.Debug("Deleting entity: {0}", MessageHelper.InfoString(this, tableId, Factory)); if (useVersion) { - log.Debug("Version: " + version); + log.Debug("Version: {0}", version); } } if (IsTableCascadeDeleteEnabled(j)) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("delete handled by foreign key constraint: " + GetTableName(j)); + log.Debug("delete handled by foreign key constraint: {0}", GetTableName(j)); } return; //EARLY EXIT! } @@ -3197,46 +3197,46 @@ protected SqlCommandInfo[] GenerateSQLDeleteStrings(object[] loadedState) protected void LogStaticSQL() { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Static SQL for entity: " + EntityName); + log.Debug("Static SQL for entity: {0}", EntityName); if (sqlLazySelectString != null) { - log.Debug(" Lazy select: " + sqlLazySelectString); + log.Debug(" Lazy select: {0}", sqlLazySelectString); } if (sqlVersionSelectString != null) { - log.Debug(" Version select: " + sqlVersionSelectString); + log.Debug(" Version select: {0}", sqlVersionSelectString); } if (sqlSnapshotSelectString != null) { - log.Debug(" Snapshot select: " + sqlSnapshotSelectString); + log.Debug(" Snapshot select: {0}", sqlSnapshotSelectString); } for (int j = 0; j < TableSpan; j++) { - log.Debug(" Insert " + j + ": " + SqlInsertStrings[j]); - log.Debug(" Update " + j + ": " + SqlUpdateStrings[j]); - log.Debug(" Delete " + j + ": " + SqlDeleteStrings[j]); + log.Debug(" Insert {0}: {1}", j, SqlInsertStrings[j]); + log.Debug(" Update {0}: {1}", j, SqlUpdateStrings[j]); + log.Debug(" Delete {0}: {1}", j, SqlDeleteStrings[j]); } if (sqlIdentityInsertString != null) { - log.Debug(" Identity insert: " + sqlIdentityInsertString); + log.Debug(" Identity insert: {0}", sqlIdentityInsertString); } if (sqlUpdateByRowIdString != null) { - log.Debug(" Update by row id (all fields): " + sqlUpdateByRowIdString); + log.Debug(" Update by row id (all fields): {0}", sqlUpdateByRowIdString); } if (sqlLazyUpdateByRowIdString != null) { - log.Debug(" Update by row id (non-lazy fields): " + sqlLazyUpdateByRowIdString); + log.Debug(" Update by row id (non-lazy fields): {0}", sqlLazyUpdateByRowIdString); } if (sqlInsertGeneratedValuesSelectString != null) { - log.Debug("Insert-generated property select: " + sqlInsertGeneratedValuesSelectString); + log.Debug("Insert-generated property select: {0}", sqlInsertGeneratedValuesSelectString); } if (sqlUpdateGeneratedValuesSelectString != null) { - log.Debug("Update-generated property select: " + sqlUpdateGeneratedValuesSelectString); + log.Debug("Update-generated property select: {0}", sqlUpdateGeneratedValuesSelectString); } } } @@ -3580,9 +3580,9 @@ protected void CreateQueryLoader() /// public object Load(object id, object optionalObject, LockMode lockMode, ISessionImplementor session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Fetching entity: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Fetching entity: {0}", MessageHelper.InfoString(this, id, Factory)); } IUniqueEntityLoader loader = GetAppropriateLoader(lockMode, session); @@ -3705,12 +3705,12 @@ protected bool[] GetPropertyUpdateability(object entity) private void LogDirtyProperties(int[] props) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { for (int i = 0; i < props.Length; i++) { string propertyName = entityMetamodel.Properties[props[i]].Name; - log.Debug(StringHelper.Qualify(EntityName, propertyName) + " is dirty"); + log.Debug("{0} is dirty", StringHelper.Qualify(EntityName, propertyName)); } } } @@ -4175,9 +4175,9 @@ public virtual object[] GetNaturalIdentifierSnapshot(object id, ISessionImplemen { throw new MappingException("persistent class did not define a natural-id : " + MessageHelper.InfoString(this)); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Getting current natural-id snapshot state for: " + MessageHelper.InfoString(this, id, Factory)); + log.Debug("Getting current natural-id snapshot state for: {0}", MessageHelper.InfoString(this, id, Factory)); } int[] naturalIdPropertyIndexes = NaturalIdentifierProperties; diff --git a/src/NHibernate/Persister/Entity/NamedQueryLoader.cs b/src/NHibernate/Persister/Entity/NamedQueryLoader.cs index ee2599134c5..8f8e6d44be1 100644 --- a/src/NHibernate/Persister/Entity/NamedQueryLoader.cs +++ b/src/NHibernate/Persister/Entity/NamedQueryLoader.cs @@ -13,7 +13,7 @@ public partial class NamedQueryLoader : IUniqueEntityLoader private readonly string queryName; private readonly IEntityPersister persister; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(NamedQueryLoader)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(NamedQueryLoader)); public NamedQueryLoader(string queryName, IEntityPersister persister) { @@ -23,9 +23,9 @@ public NamedQueryLoader(string queryName, IEntityPersister persister) public object Load(object id, object optionalObject, ISessionImplementor session) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("loading entity: {0} using named query: {1}", persister.EntityName, queryName)); + log.Debug("loading entity: {0} using named query: {1}", persister.EntityName, queryName); } AbstractQueryImpl query = (AbstractQueryImpl) session.GetNamedQuery(queryName); @@ -49,4 +49,4 @@ public object Load(object id, object optionalObject, ISessionImplementor session return session.PersistenceContext.GetEntity(session.GenerateEntityKey(id, persister)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/DefaultProxyFactory.cs b/src/NHibernate/Proxy/DefaultProxyFactory.cs index 3189f0ac9ba..71655dd5860 100644 --- a/src/NHibernate/Proxy/DefaultProxyFactory.cs +++ b/src/NHibernate/Proxy/DefaultProxyFactory.cs @@ -8,7 +8,7 @@ namespace NHibernate.Proxy public class DefaultProxyFactory : AbstractProxyFactory { private readonly ProxyFactory factory = new ProxyFactory(); - protected static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (DefaultProxyFactory)); + protected static readonly INHibernateLogger log = NHibernateLogger.For(typeof (DefaultProxyFactory)); public override INHibernateProxy GetProxy(object id, ISessionImplementor session) { @@ -24,7 +24,7 @@ public override INHibernateProxy GetProxy(object id, ISessionImplementor session } catch (Exception ex) { - log.Error("Creating a proxy instance failed", ex); + log.Error(ex, "Creating a proxy instance failed"); throw new HibernateException("Creating a proxy instance failed", ex); } } diff --git a/src/NHibernate/SqlCommand/InsertSelect.cs b/src/NHibernate/SqlCommand/InsertSelect.cs index c2050efc9bb..1ee65da3185 100644 --- a/src/NHibernate/SqlCommand/InsertSelect.cs +++ b/src/NHibernate/SqlCommand/InsertSelect.cs @@ -5,7 +5,7 @@ namespace NHibernate.SqlCommand { public class InsertSelect : ISqlStringBuilder { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(InsertSelect)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(InsertSelect)); private string tableName; private string comment; diff --git a/src/NHibernate/SqlCommand/Parser/SqlParserUtils.cs b/src/NHibernate/SqlCommand/Parser/SqlParserUtils.cs index 49d943e4fc6..32bd3be8270 100644 --- a/src/NHibernate/SqlCommand/Parser/SqlParserUtils.cs +++ b/src/NHibernate/SqlCommand/Parser/SqlParserUtils.cs @@ -78,7 +78,7 @@ public static int ReadMultilineComment(string text, int maxOffset, int offset) prevChar = ch; } - throw new SqlParseException(string.Format("Cannot find terminating '*/' string for multiline comment.")); + throw new SqlParseException("Cannot find terminating \'*/\' string for multiline comment."); } public static int ReadWhitespace(string text, int maxOffset, int offset) diff --git a/src/NHibernate/SqlCommand/SqlDeleteBuilder.cs b/src/NHibernate/SqlCommand/SqlDeleteBuilder.cs index 614efb5e061..861a92d36e6 100644 --- a/src/NHibernate/SqlCommand/SqlDeleteBuilder.cs +++ b/src/NHibernate/SqlCommand/SqlDeleteBuilder.cs @@ -12,7 +12,7 @@ namespace NHibernate.SqlCommand /// public class SqlDeleteBuilder : SqlBaseBuilder, ISqlStringBuilder { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SqlDeleteBuilder)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SqlDeleteBuilder)); private string tableName; private List whereStrings = new List(); @@ -146,19 +146,21 @@ public SqlString ToSqlString() sqlBuilder.Add(whereStrings[0]); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (initialCapacity < sqlBuilder.Count) { - log.Debug( - "The initial capacity was set too low at: " + initialCapacity + " for the DeleteSqlBuilder " + - "that needed a capacity of: " + sqlBuilder.Count + " for the table " + tableName); + log.Debug("The initial capacity was set too low at: {0} for the DeleteSqlBuilder that needed a capacity of: {1} for the table {2}", + initialCapacity, + sqlBuilder.Count, + tableName); } else if (initialCapacity > 16 && ((float) initialCapacity / sqlBuilder.Count) > 1.2) { - log.Debug( - "The initial capacity was set too high at: " + initialCapacity + " for the DeleteSqlBuilder " + - "that needed a capacity of: " + sqlBuilder.Count + " for the table " + tableName); + log.Debug("The initial capacity was set too high at: {0} for the DeleteSqlBuilder that needed a capacity of: {1} for the table {2}", + initialCapacity, + sqlBuilder.Count, + tableName); } } return sqlBuilder.ToSqlString(); @@ -171,4 +173,4 @@ public SqlCommandInfo ToSqlCommandInfo() return new SqlCommandInfo(ToSqlString(), parameterTypes.ToArray()); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/SqlCommand/SqlInsertBuilder.cs b/src/NHibernate/SqlCommand/SqlInsertBuilder.cs index 0eeb5a9b675..8fdd229b6cc 100644 --- a/src/NHibernate/SqlCommand/SqlInsertBuilder.cs +++ b/src/NHibernate/SqlCommand/SqlInsertBuilder.cs @@ -12,7 +12,7 @@ namespace NHibernate.SqlCommand /// public class SqlInsertBuilder : ISqlStringBuilder { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SqlInsertBuilder)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SqlInsertBuilder)); private readonly ISessionFactoryImplementor factory; private string tableName; @@ -180,19 +180,21 @@ public virtual SqlString ToSqlString() sqlBuilder.Add(")"); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (initialCapacity < sqlBuilder.Count) { - log.Debug( - "The initial capacity was set too low at: " + initialCapacity + " for the InsertSqlBuilder " + - "that needed a capacity of: " + sqlBuilder.Count + " for the table " + tableName); + log.Debug("The initial capacity was set too low at: {0} for the InsertSqlBuilder that needed a capacity of: {1} for the table {2}", + initialCapacity, + sqlBuilder.Count, + tableName); } else if (initialCapacity > 16 && ((float) initialCapacity / sqlBuilder.Count) > 1.2) { - log.Debug( - "The initial capacity was set too high at: " + initialCapacity + " for the InsertSqlBuilder " + - "that needed a capacity of: " + sqlBuilder.Count + " for the table " + tableName); + log.Debug("The initial capacity was set too high at: {0} for the InsertSqlBuilder that needed a capacity of: {1} for the table {2}", + initialCapacity, + sqlBuilder.Count, + tableName); } } diff --git a/src/NHibernate/SqlCommand/SqlSelectBuilder.cs b/src/NHibernate/SqlCommand/SqlSelectBuilder.cs index da125b5f98c..418c0295570 100644 --- a/src/NHibernate/SqlCommand/SqlSelectBuilder.cs +++ b/src/NHibernate/SqlCommand/SqlSelectBuilder.cs @@ -10,7 +10,7 @@ namespace NHibernate.SqlCommand /// public class SqlSelectBuilder : SqlBaseBuilder, ISqlStringBuilder { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SqlSelectBuilder)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SqlSelectBuilder)); private SqlString selectClause; private string fromClause; @@ -270,19 +270,21 @@ public SqlString ToSqlString() sqlBuilder.Add(Dialect.GetForUpdateString(lockMode)); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (initialCapacity < sqlBuilder.Count) { - log.Debug( - "The initial capacity was set too low at: " + initialCapacity + " for the SelectSqlBuilder " + - "that needed a capacity of: " + sqlBuilder.Count + " for the table " + fromClause); + log.Debug("The initial capacity was set too low at: {0} for the SelectSqlBuilder that needed a capacity of: {1} for the table {2}", + initialCapacity, + sqlBuilder.Count, + fromClause); } else if (initialCapacity > 16 && ((float) initialCapacity / sqlBuilder.Count) > 1.2) { - log.Debug( - "The initial capacity was set too high at: " + initialCapacity + " for the SelectSqlBuilder " + - "that needed a capacity of: " + sqlBuilder.Count + " for the table " + fromClause); + log.Debug("The initial capacity was set too high at: {0} for the SelectSqlBuilder that needed a capacity of: {1} for the table {2}", + initialCapacity, + sqlBuilder.Count, + fromClause); } } diff --git a/src/NHibernate/SqlCommand/SqlUpdateBuilder.cs b/src/NHibernate/SqlCommand/SqlUpdateBuilder.cs index 46327a4868d..d51aed776bd 100644 --- a/src/NHibernate/SqlCommand/SqlUpdateBuilder.cs +++ b/src/NHibernate/SqlCommand/SqlUpdateBuilder.cs @@ -12,7 +12,7 @@ namespace NHibernate.SqlCommand /// public class SqlUpdateBuilder : SqlBaseBuilder, ISqlStringBuilder { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(SqlUpdateBuilder)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SqlUpdateBuilder)); private string tableName; private string comment; @@ -321,19 +321,21 @@ public SqlString ToSqlString() sqlBuilder.Add(whereString); } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { if (initialCapacity < sqlBuilder.Count) { - log.Debug( - "The initial capacity was set too low at: " + initialCapacity + " for the UpdateSqlBuilder " + - "that needed a capacity of: " + sqlBuilder.Count + " for the table " + tableName); + log.Debug("The initial capacity was set too low at: {0} for the UpdateSqlBuilder that needed a capacity of: {1} for the table {2}", + initialCapacity, + sqlBuilder.Count, + tableName); } else if (initialCapacity > 16 && ((float) initialCapacity / sqlBuilder.Count) > 1.2) { - log.Debug( - "The initial capacity was set too high at: " + initialCapacity + " for the UpdateSqlBuilder " + - "that needed a capacity of: " + sqlBuilder.Count + " for the table " + tableName); + log.Debug("The initial capacity was set too high at: {0} for the UpdateSqlBuilder that needed a capacity of: {1} for the table {2}", + initialCapacity, + sqlBuilder.Count, + tableName); } } diff --git a/src/NHibernate/Stat/StatisticsImpl.cs b/src/NHibernate/Stat/StatisticsImpl.cs index 68c4d014490..9e26f905013 100644 --- a/src/NHibernate/Stat/StatisticsImpl.cs +++ b/src/NHibernate/Stat/StatisticsImpl.cs @@ -15,7 +15,7 @@ public class StatisticsImpl : IStatistics, IStatisticsImplementor { private object _syncRoot; - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(StatisticsImpl)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(StatisticsImpl)); private readonly ISessionFactoryImplementor sessionFactory; private long entityDeleteCount; private long entityInsertCount; @@ -424,34 +424,34 @@ public QueryStatistics GetQueryStatistics(string queryString) public void LogSummary() { log.Info("Logging statistics...."); - log.Info(string.Format("start time: {0}", startTime.ToString("o"))); - log.Info("sessions opened: " + sessionOpenCount); - log.Info("sessions closed: " + sessionCloseCount); - log.Info("transactions: " + transactionCount); - log.Info("successful transactions: " + commitedTransactionCount); - log.Info("optimistic lock failures: " + optimisticFailureCount); - log.Info("flushes: " + flushCount); - log.Info("connections obtained: " + connectCount); - log.Info("statements prepared: " + prepareStatementCount); - log.Info("statements closed: " + closeStatementCount); - log.Info("second level cache puts: " + secondLevelCachePutCount); - log.Info("second level cache hits: " + secondLevelCacheHitCount); - log.Info("second level cache misses: " + secondLevelCacheMissCount); - log.Info("entities loaded: " + entityLoadCount); - log.Info("entities updated: " + entityUpdateCount); - log.Info("entities inserted: " + entityInsertCount); - log.Info("entities deleted: " + entityDeleteCount); - log.Info("entities fetched (minimize this): " + entityFetchCount); - log.Info("collections loaded: " + collectionLoadCount); - log.Info("collections updated: " + collectionUpdateCount); - log.Info("collections removed: " + collectionRemoveCount); - log.Info("collections recreated: " + collectionRecreateCount); - log.Info("collections fetched (minimize this): " + collectionFetchCount); - log.Info("queries executed to database: " + queryExecutionCount); - log.Info("query cache puts: " + queryCachePutCount); - log.Info("query cache hits: " + queryCacheHitCount); - log.Info("query cache misses: " + queryCacheMissCount); - log.Info("max query time: " + queryExecutionMaxTime.TotalMilliseconds.ToString("0") + " ms"); + log.Info("start time: {0:o}", startTime); + log.Info("sessions opened: {0}", sessionOpenCount); + log.Info("sessions closed: {0}", sessionCloseCount); + log.Info("transactions: {0}", transactionCount); + log.Info("successful transactions: {0}", commitedTransactionCount); + log.Info("optimistic lock failures: {0}", optimisticFailureCount); + log.Info("flushes: {0}", flushCount); + log.Info("connections obtained: {0}", connectCount); + log.Info("statements prepared: {0}", prepareStatementCount); + log.Info("statements closed: {0}", closeStatementCount); + log.Info("second level cache puts: {0}", secondLevelCachePutCount); + log.Info("second level cache hits: {0}", secondLevelCacheHitCount); + log.Info("second level cache misses: {0}", secondLevelCacheMissCount); + log.Info("entities loaded: {0}", entityLoadCount); + log.Info("entities updated: {0}", entityUpdateCount); + log.Info("entities inserted: {0}", entityInsertCount); + log.Info("entities deleted: {0}", entityDeleteCount); + log.Info("entities fetched (minimize this): {0}", entityFetchCount); + log.Info("collections loaded: {0}", collectionLoadCount); + log.Info("collections updated: {0}", collectionUpdateCount); + log.Info("collections removed: {0}", collectionRemoveCount); + log.Info("collections recreated: {0}", collectionRecreateCount); + log.Info("collections fetched (minimize this): {0}", collectionFetchCount); + log.Info("queries executed to database: {0}", queryExecutionCount); + log.Info("query cache puts: {0}", queryCachePutCount); + log.Info("query cache hits: {0}", queryCacheHitCount); + log.Info("query cache misses: {0}", queryCacheMissCount); + log.Info("max query time: {0:0} ms", queryExecutionMaxTime.TotalMilliseconds); } public TimeSpan OperationThreshold @@ -800,7 +800,7 @@ public void OptimisticFailure(string entityName) private static void LogOperation(string operation, string entityName, TimeSpan time) { if (entityName != null) - log.Info(operation + entityName + " " + time.Milliseconds + "ms"); + log.Info("{0}{1} {2}ms", operation, entityName, time.Milliseconds); else log.Info(operation); // just log that the event occurred } diff --git a/src/NHibernate/Tool/hbm2ddl/DatabaseMetadata.cs b/src/NHibernate/Tool/hbm2ddl/DatabaseMetadata.cs index 41328e64f31..039ef4a12b4 100644 --- a/src/NHibernate/Tool/hbm2ddl/DatabaseMetadata.cs +++ b/src/NHibernate/Tool/hbm2ddl/DatabaseMetadata.cs @@ -12,7 +12,7 @@ namespace NHibernate.Tool.hbm2ddl { public class DatabaseMetadata : IDatabaseMetadata { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (DatabaseMetadata)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (DatabaseMetadata)); private readonly IDictionary tables = new Dictionary(); private readonly ISet sequences = new HashSet(); @@ -88,7 +88,7 @@ public ITableMetadata GetTableMetadata(string name, string schema, string catalo } } - log.Info("table not found: " + name); + log.Info("table not found: {0}", name); return null; } catch (DbException sqle) diff --git a/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs b/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs index 3885b658086..6e42d9ddbbb 100644 --- a/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs +++ b/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs @@ -21,7 +21,7 @@ namespace NHibernate.Tool.hbm2ddl /// public partial class SchemaExport { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (SchemaExport)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (SchemaExport)); private bool wasInitialized; private readonly Configuration cfg; private readonly IDictionary configProperties; @@ -192,8 +192,8 @@ private void Execute(Action scriptAction, bool execute, bool throwOnErro } catch (Exception e) { - log.Warn("Unsuccessful: " + sql); - log.Warn(e.Message); + log.Warn("Unsuccessful: {0}", sql); + log.Warn(e, e.Message); if (throwOnError) { throw; @@ -210,7 +210,7 @@ private void ExecuteSql(DbCommand cmd, string sql) foreach (string stmt in splitter) { - log.DebugFormat("SQL Batch: {0}", stmt); + log.Debug("SQL Batch: {0}", stmt); cmd.CommandText = stmt; cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); @@ -294,7 +294,7 @@ public void Execute(Action scriptAction, bool execute, bool justDrop, Db } catch (Exception e) { - log.Error("Could not close connection: " + e.Message, e); + log.Error(e, "Could not close connection: {0}", e.Message); } if (exportOutput != null) { @@ -304,7 +304,7 @@ public void Execute(Action scriptAction, bool execute, bool justDrop, Db } catch (Exception ioe) { - log.Error("Error closing output file " + outputFile + ": " + ioe.Message, ioe); + log.Error(ioe, "Error closing output file {0}: {1}", outputFile, ioe.Message); } } } @@ -381,7 +381,7 @@ public void Execute(Action scriptAction, bool execute, bool justDrop, Te } catch (Exception e) { - log.Error(e.Message, e); + log.Error(e, e.Message); throw new HibernateException(e.Message, e); } finally @@ -394,4 +394,4 @@ public void Execute(Action scriptAction, bool execute, bool justDrop, Te } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs b/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs index fd43107f125..1f275c2bfe8 100644 --- a/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs +++ b/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs @@ -10,7 +10,7 @@ namespace NHibernate.Tool.hbm2ddl { public partial class SchemaUpdate { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (SchemaUpdate)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (SchemaUpdate)); private bool wasInitialized; private readonly Configuration configuration; private readonly IConnectionHelper connectionHelper; @@ -127,7 +127,7 @@ public static void Main(string[] args) } catch (Exception e) { - log.Error("Error running schema update", e); + log.Error(e, "Error running schema update"); Console.WriteLine(e); } } @@ -177,7 +177,7 @@ public void Execute(Action scriptAction, bool doUpdate) catch (Exception sqle) { exceptions.Add(sqle); - log.Error("could not get database metadata", sqle); + log.Error(sqle, "could not get database metadata"); throw; } @@ -205,7 +205,7 @@ public void Execute(Action scriptAction, bool doUpdate) catch (Exception e) { exceptions.Add(e); - log.Error("Unsuccessful: " + sql, e); + log.Error(e, "Unsuccessful: {0}", sql); } } @@ -214,7 +214,7 @@ public void Execute(Action scriptAction, bool doUpdate) catch (Exception e) { exceptions.Add(e); - log.Error("could not complete schema update", e); + log.Error(e, "could not complete schema update"); } finally { @@ -229,9 +229,9 @@ public void Execute(Action scriptAction, bool doUpdate) catch (Exception e) { exceptions.Add(e); - log.Error("Error closing connection", e); + log.Error(e, "Error closing connection"); } } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs b/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs index 5074d5760f8..89c11c0745a 100644 --- a/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs +++ b/src/NHibernate/Tool/hbm2ddl/SchemaValidator.cs @@ -9,7 +9,7 @@ namespace NHibernate.Tool.hbm2ddl { public partial class SchemaValidator { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof (SchemaValidator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof (SchemaValidator)); private readonly Configuration configuration; private readonly IConnectionHelper connectionHelper; private readonly Dialect.Dialect dialect; @@ -80,7 +80,7 @@ public static void Main(string[] args) } catch (Exception e) { - log.Error("Error running schema update", e); + log.Error(e, "Error running schema update"); Console.WriteLine(e); } } @@ -101,14 +101,14 @@ public void Validate() } catch (Exception sqle) { - log.Error("could not get database metadata", sqle); + log.Error(sqle, "could not get database metadata"); throw; } configuration.ValidateSchema(dialect, meta); } catch (Exception e) { - log.Error("could not complete schema validation", e); + log.Error(e, "could not complete schema validation"); throw; } finally @@ -119,7 +119,7 @@ public void Validate() } catch (Exception e) { - log.Error("Error closing connection", e); + log.Error(e, "Error closing connection"); } } } diff --git a/src/NHibernate/Transaction/AdoNetTransactionFactory.cs b/src/NHibernate/Transaction/AdoNetTransactionFactory.cs index 0e3f093d98a..e1d485aeecb 100644 --- a/src/NHibernate/Transaction/AdoNetTransactionFactory.cs +++ b/src/NHibernate/Transaction/AdoNetTransactionFactory.cs @@ -16,7 +16,7 @@ namespace NHibernate.Transaction /// public partial class AdoNetTransactionFactory : ITransactionFactory { - private readonly IInternalLogger isolaterLog = LoggerProvider.LoggerFor(typeof(ITransactionFactory)); + private readonly INHibernateLogger isolaterLog = NHibernateLogger.For(typeof(ITransactionFactory)); /// public virtual ITransaction CreateTransaction(ISessionImplementor session) @@ -94,7 +94,7 @@ public virtual void ExecuteWorkInIsolation(ISessionImplementor session, IIsolate } catch (Exception ignore) { - isolaterLog.Debug("Unable to rollback transaction", ignore); + isolaterLog.Debug(ignore, "Unable to rollback transaction"); } if (t is HibernateException) @@ -133,7 +133,7 @@ public virtual void ExecuteWorkInIsolation(ISessionImplementor session, IIsolate } catch (Exception ignore) { - isolaterLog.Warn("Unable to dispose transaction", ignore); + isolaterLog.Warn(ignore, "Unable to dispose transaction"); } if (session.Factory.Dialect is SQLiteDialect == false) diff --git a/src/NHibernate/Transaction/AdoNetWithSystemTransactionFactory.cs b/src/NHibernate/Transaction/AdoNetWithSystemTransactionFactory.cs index 9205521dd8d..bf8f594c281 100644 --- a/src/NHibernate/Transaction/AdoNetWithSystemTransactionFactory.cs +++ b/src/NHibernate/Transaction/AdoNetWithSystemTransactionFactory.cs @@ -17,7 +17,7 @@ namespace NHibernate.Transaction /// public partial class AdoNetWithSystemTransactionFactory : AdoNetTransactionFactory { - private static readonly IInternalLogger _logger = LoggerProvider.LoggerFor(typeof(ITransactionFactory)); + private static readonly INHibernateLogger _logger = NHibernateLogger.For(typeof(ITransactionFactory)); /// /// See . @@ -100,7 +100,7 @@ protected virtual void JoinSystemTransaction(ISessionImplementor session, System var transactionContext = CreateAndEnlistMainContext(originatingSession, transaction); originatingSession.TransactionContext = transactionContext; - _logger.DebugFormat( + _logger.Debug( "Enlisted into system transaction: {0}", transaction.IsolationLevel); @@ -245,8 +245,8 @@ public virtual void Wait() catch (Exception ex) { _logger.Warn( - "Synchronization failure, assuming it has been concurrently disposed and does not need sync anymore.", - ex); + ex, + "Synchronization failure, assuming it has been concurrently disposed and does not need sync anymore."); } } @@ -293,7 +293,7 @@ protected virtual void Unlock() } catch (ObjectDisposedException ode) { - _logger.Warn("Enlisted transaction status was wrongly active, original transaction being already disposed. Will assume neither active nor committed.", ode); + _logger.Warn(ode, "Enlisted transaction status was wrongly active, original transaction being already disposed. Will assume neither active nor committed."); return null; } } @@ -346,7 +346,7 @@ public virtual void Prepare(PreparingEnlistment preparingEnlistment) } catch (Exception exception) { - _logger.Error("System transaction prepare phase failed", exception); + _logger.Error(exception, "System transaction prepare phase failed"); try { CompleteTransaction(false); @@ -445,7 +445,7 @@ protected virtual void CompleteTransaction(bool isCommitted) catch (Exception ex) { // May be run in a dedicated thread. Log any error, otherwise they could stay unlogged. - _logger.Error("Failure at transaction completion", ex); + _logger.Error(ex, "Failure at transaction completion"); throw; } finally diff --git a/src/NHibernate/Transaction/AdoTransaction.cs b/src/NHibernate/Transaction/AdoTransaction.cs index ecea5213492..c413f5757be 100644 --- a/src/NHibernate/Transaction/AdoTransaction.cs +++ b/src/NHibernate/Transaction/AdoTransaction.cs @@ -14,7 +14,7 @@ namespace NHibernate.Transaction /// public partial class AdoTransaction : ITransaction { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(AdoTransaction)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AdoTransaction)); private ISessionImplementor session; private DbTransaction trans; private bool begun; @@ -51,7 +51,7 @@ public void Enlist(DbCommand command) { if (trans == null) { - if (log.IsWarnEnabled) + if (log.IsWarnEnabled()) { if (command.Transaction != null) { @@ -64,7 +64,7 @@ public void Enlist(DbCommand command) } else { - if (log.IsWarnEnabled) + if (log.IsWarnEnabled()) { // got into here because the command was being initialized and had a null Transaction - probably // don't need to be confused by that - just a normal part of initialization... @@ -125,7 +125,7 @@ public void Begin(IsolationLevel isolationLevel) isolationLevel = session.Factory.Settings.IsolationLevel; } - log.Debug(string.Format("Begin ({0})", isolationLevel)); + log.Debug("Begin ({0})", isolationLevel); try { @@ -145,7 +145,7 @@ public void Begin(IsolationLevel isolationLevel) } catch (Exception e) { - log.Error("Begin transaction failed", e); + log.Error(e, "Begin transaction failed"); throw new TransactionException("Begin failed with SQL exception", e); } @@ -205,7 +205,7 @@ public void Commit() } catch (HibernateException e) { - log.Error("Commit failed", e); + log.Error(e, "Commit failed"); AfterTransactionCompletion(false); commitFailed = true; // Don't wrap HibernateExceptions @@ -213,7 +213,7 @@ public void Commit() } catch (Exception e) { - log.Error("Commit failed", e); + log.Error(e, "Commit failed"); AfterTransactionCompletion(false); commitFailed = true; throw new TransactionException("Commit failed with SQL exception", e); @@ -254,13 +254,13 @@ public void Rollback() } catch (HibernateException e) { - log.Error("Rollback failed", e); + log.Error(e, "Rollback failed"); // Don't wrap HibernateExceptions throw; } catch (Exception e) { - log.Error("Rollback failed", e); + log.Error(e, "Rollback failed"); throw new TransactionException("Rollback failed with SQL Exception", e); } finally @@ -425,7 +425,7 @@ private void NotifyLocalSynchsBeforeTransactionCompletion() } catch (Exception e) { - log.Error("exception calling user Synchronization", e); + log.Error(e, "exception calling user Synchronization"); throw; } } @@ -446,7 +446,7 @@ private void NotifyLocalSynchsAfterTransactionCompletion(bool success) } catch (Exception e) { - log.Error("exception calling user Synchronization", e); + log.Error(e, "exception calling user Synchronization"); } } } diff --git a/src/NHibernate/Transform/DistinctRootEntityResultTransformer.cs b/src/NHibernate/Transform/DistinctRootEntityResultTransformer.cs index 24f4ebac408..c4a65ce87cb 100644 --- a/src/NHibernate/Transform/DistinctRootEntityResultTransformer.cs +++ b/src/NHibernate/Transform/DistinctRootEntityResultTransformer.cs @@ -9,7 +9,7 @@ namespace NHibernate.Transform [Serializable] public class DistinctRootEntityResultTransformer : IResultTransformer, ITupleSubsetResultTransformer { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DistinctRootEntityResultTransformer)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DistinctRootEntityResultTransformer)); private static readonly object Hasher = new object(); internal sealed class Identity @@ -52,10 +52,9 @@ public IList TransformList(IList list) } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug(string.Format("transformed: {0} rows to: {1} distinct results", - list.Count, result.Count)); + log.Debug("transformed: {0} rows to: {1} distinct results", list.Count, result.Count); } return result; } @@ -92,4 +91,4 @@ public override int GetHashCode() return Hasher.GetHashCode(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Tuple/Component/AbstractComponentTuplizer.cs b/src/NHibernate/Tuple/Component/AbstractComponentTuplizer.cs index 49e05e5ab85..6e16b03a45c 100644 --- a/src/NHibernate/Tuple/Component/AbstractComponentTuplizer.cs +++ b/src/NHibernate/Tuple/Component/AbstractComponentTuplizer.cs @@ -9,7 +9,7 @@ namespace NHibernate.Tuple.Component [Serializable] public abstract class AbstractComponentTuplizer : IComponentTuplizer { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(AbstractComponentTuplizer)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AbstractComponentTuplizer)); protected internal int propertySpan; protected internal IGetter[] getters; @@ -35,9 +35,9 @@ protected internal AbstractComponentTuplizer(Mapping.Component component) } i++; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("{0} accessors found for component: {1}", foundCustomAccessor ? "Custom" : "No custom", + log.Debug("{0} accessors found for component: {1}", foundCustomAccessor ? "Custom" : "No custom", component.ComponentClassName); } hasCustomAccessors = foundCustomAccessor; diff --git a/src/NHibernate/Tuple/Entity/AbstractEntityTuplizer.cs b/src/NHibernate/Tuple/Entity/AbstractEntityTuplizer.cs index f663a7676cb..f4f6c4c0b60 100644 --- a/src/NHibernate/Tuple/Entity/AbstractEntityTuplizer.cs +++ b/src/NHibernate/Tuple/Entity/AbstractEntityTuplizer.cs @@ -14,7 +14,7 @@ namespace NHibernate.Tuple.Entity /// Support for tuplizers relating to entities. public abstract class AbstractEntityTuplizer : IEntityTuplizer { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(AbstractEntityTuplizer)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AbstractEntityTuplizer)); private readonly EntityMetamodel entityMetamodel; private readonly IGetter idGetter; private readonly ISetter idSetter; @@ -59,9 +59,9 @@ protected AbstractEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClas foundCustomAccessor = true; i++; } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.DebugFormat("{0} accessors found for entity: {1}", foundCustomAccessor ? "Custom" : "No custom", + log.Debug("{0} accessors found for entity: {1}", foundCustomAccessor ? "Custom" : "No custom", mappingInfo.EntityName); } hasCustomAccessors = foundCustomAccessor; diff --git a/src/NHibernate/Tuple/Entity/DynamicMapEntityTuplizer.cs b/src/NHibernate/Tuple/Entity/DynamicMapEntityTuplizer.cs index e4bec538e82..f06234f4e0c 100644 --- a/src/NHibernate/Tuple/Entity/DynamicMapEntityTuplizer.cs +++ b/src/NHibernate/Tuple/Entity/DynamicMapEntityTuplizer.cs @@ -11,7 +11,7 @@ namespace NHibernate.Tuple.Entity { public class DynamicMapEntityTuplizer : AbstractEntityTuplizer { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(PocoEntityTuplizer)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(PocoEntityTuplizer)); internal DynamicMapEntityTuplizer(EntityMetamodel entityMetamodel, PersistentClass mappingInfo) : base(entityMetamodel, mappingInfo) @@ -71,7 +71,7 @@ protected override IProxyFactory BuildProxyFactory(PersistentClass mappingInfo, } catch (HibernateException he) { - log.Warn("could not create proxy factory for:" + EntityName, he); + log.Warn(he, "could not create proxy factory for:{0}", EntityName); pf = null; } return pf; diff --git a/src/NHibernate/Tuple/Entity/EntityMetamodel.cs b/src/NHibernate/Tuple/Entity/EntityMetamodel.cs index 93523caff24..9f81571059b 100644 --- a/src/NHibernate/Tuple/Entity/EntityMetamodel.cs +++ b/src/NHibernate/Tuple/Entity/EntityMetamodel.cs @@ -14,7 +14,7 @@ namespace NHibernate.Tuple.Entity [Serializable] public class EntityMetamodel { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(EntityMetamodel)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(EntityMetamodel)); private const int NoVersionIndex = -66; @@ -155,7 +155,7 @@ public EntityMetamodel(PersistentClass persistentClass, ISessionFactoryImplement var getter = prop.GetGetter(persistentClass.MappedClass); if (getter.Method == null || getter.Method.IsDefined(typeof(CompilerGeneratedAttribute), false) == false) { - log.ErrorFormat("Lazy or no-proxy property {0}.{1} is not an auto property, which may result in uninitialized property access", persistentClass.EntityName, prop.Name); + log.Error("Lazy or no-proxy property {0}.{1} is not an auto property, which may result in uninitialized property access", persistentClass.EntityName, prop.Name); } } @@ -255,20 +255,20 @@ public EntityMetamodel(PersistentClass persistentClass, ISessionFactoryImplement if(hadLazyProperties && !hasLazy) { - log.WarnFormat("Disabled lazy property fetching for {0} because it does not support lazy at the entity level", name); + log.Warn("Disabled lazy property fetching for {0} because it does not support lazy at the entity level", name); } if (hasLazy) { - log.Info("lazy property fetching available for: " + name); + log.Info("lazy property fetching available for: {0}", name); } if(hadNoProxyRelations && !hasUnwrapProxyForProperties) { - log.WarnFormat("Disabled ghost property fetching for {0} because it does not support lazy at the entity level", name); + log.Warn("Disabled ghost property fetching for {0} because it does not support lazy at the entity level", name); } if (hasUnwrapProxyForProperties) { - log.Info("no-proxy property fetching available for: " + name); + log.Info("no-proxy property fetching available for: {0}", name); } mutable = persistentClass.IsMutable; @@ -284,8 +284,8 @@ public EntityMetamodel(PersistentClass persistentClass, ISessionFactoryImplement if (!isAbstract && persistentClass.HasPocoRepresentation && ReflectHelper.IsAbstractClass(persistentClass.MappedClass)) { - log.Warn("entity [" + type.FullName - + "] is abstract-class/interface explicitly mapped as non-abstract; be sure to supply entity-names"); + log.Warn("entity [{0}] is abstract-class/interface explicitly mapped as non-abstract; be sure to supply entity-names", + type.FullName); } } selectBeforeUpdate = persistentClass.SelectBeforeUpdate; diff --git a/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs b/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs index 2a08fff77a6..9f57cba92cf 100644 --- a/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs +++ b/src/NHibernate/Tuple/Entity/PocoEntityTuplizer.cs @@ -19,7 +19,7 @@ namespace NHibernate.Tuple.Entity /// An specific to the POCO entity mode. public class PocoEntityTuplizer : AbstractEntityTuplizer { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(PocoEntityTuplizer)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(PocoEntityTuplizer)); private readonly System.Type mappedClass; private readonly System.Type proxyInterface; private readonly bool islifecycleImplementor; @@ -110,12 +110,12 @@ protected override IInstantiator BuildInstantiator(PersistentClass persistentCla { if (optimizer == null) { - log.Debug("Create Instantiator without optimizer for:" + persistentClass.MappedClass.FullName); + log.Debug("Create Instantiator without optimizer for:{0}", persistentClass.MappedClass.FullName); return new PocoInstantiator(persistentClass, null, ProxyFactory, EntityMetamodel.HasLazyProperties || EntityMetamodel.HasUnwrapProxyForProperties); } else { - log.Debug("Create Instantiator using optimizer for:" + persistentClass.MappedClass.FullName); + log.Debug("Create Instantiator using optimizer for:{0}", persistentClass.MappedClass.FullName); return new PocoInstantiator(persistentClass, optimizer.InstantiationOptimizer, ProxyFactory, EntityMetamodel.HasLazyProperties || EntityMetamodel.HasUnwrapProxyForProperties); } } @@ -167,7 +167,7 @@ protected override IProxyFactory BuildProxyFactory(PersistentClass persistentCla * - Check if the logger is enabled * - Don't need nothing to check if the mapped-class or proxy is an interface */ - if (log.IsErrorEnabled && needAccesorCheck) + if (log.IsErrorEnabled() && needAccesorCheck) { LogPropertyAccessorsErrors(persistentClass); } @@ -190,7 +190,7 @@ protected override IProxyFactory BuildProxyFactory(PersistentClass persistentCla } catch (HibernateException he) { - log.Warn("could not create proxy factory for:" + EntityName, he); + log.Warn(he, "could not create proxy factory for:{0}", EntityName); pf = null; } return pf; @@ -210,16 +210,14 @@ private void LogPropertyAccessorsErrors(PersistentClass persistentClass) MethodInfo method = property.GetGetter(clazz).Method; if (!proxyValidator.IsProxeable(method)) { - log.Error( - string.Format("Getters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName, - property.Name)); + log.Error("Getters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName, + property.Name); } method = property.GetSetter(clazz).Method; if (!proxyValidator.IsProxeable(method)) { - log.Error( - string.Format("Setters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName, - property.Name)); + log.Error("Setters of lazy classes cannot be final: {0}.{1}", persistentClass.MappedClass.FullName, + property.Name); } } } diff --git a/src/NHibernate/Tuple/PocoInstantiator.cs b/src/NHibernate/Tuple/PocoInstantiator.cs index 63a5c9ba3a8..5085b194880 100644 --- a/src/NHibernate/Tuple/PocoInstantiator.cs +++ b/src/NHibernate/Tuple/PocoInstantiator.cs @@ -13,7 +13,7 @@ namespace NHibernate.Tuple [Serializable] public class PocoInstantiator : IInstantiator, IDeserializationCallback { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(PocoInstantiator)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(PocoInstantiator)); private readonly System.Type mappedClass; @@ -49,7 +49,7 @@ public PocoInstantiator(Mapping.Component component, IInstantiationOptimizer opt } catch (PropertyNotFoundException) { - log.Info(string.Format("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", mappedClass.FullName)); + log.Info("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", mappedClass.FullName); constructor = null; } } @@ -69,7 +69,7 @@ public PocoInstantiator(PersistentClass persistentClass, IInstantiationOptimizer } catch (PropertyNotFoundException) { - log.Info(string.Format("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", mappedClass.FullName)); + log.Info("no default (no-argument) constructor for class: {0} (class must be instantiated by Interceptor)", mappedClass.FullName); constructor = null; } } diff --git a/src/NHibernate/Type/CollectionType.cs b/src/NHibernate/Type/CollectionType.cs index ce7aa8998fa..3d8285532a3 100644 --- a/src/NHibernate/Type/CollectionType.cs +++ b/src/NHibernate/Type/CollectionType.cs @@ -21,7 +21,7 @@ namespace NHibernate.Type [Serializable] public abstract partial class CollectionType : AbstractType, IAssociationType { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(CollectionType)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(CollectionType)); private static readonly object NotNullCollection = new object(); // place holder public static readonly object UnfetchedCollection = new object(); // place holder @@ -267,9 +267,9 @@ public object GetCollection(object key, ISessionImplementor session, object owne } } - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { - log.Debug("Created collection wrapper: " + MessageHelper.CollectionInfoString(persister, collection, key, session)); + log.Debug("Created collection wrapper: {0}", MessageHelper.CollectionInfoString(persister, collection, key, session)); } } collection.Owner = owner; diff --git a/src/NHibernate/Type/CompositeCustomType.cs b/src/NHibernate/Type/CompositeCustomType.cs index 637c027b884..7cb2a82347d 100644 --- a/src/NHibernate/Type/CompositeCustomType.cs +++ b/src/NHibernate/Type/CompositeCustomType.cs @@ -49,7 +49,7 @@ public CompositeCustomType(System.Type userTypeClass, IDictionary parameters) string value; if (parameters.TryGetValue(BaseValueParameterName, out value)) { - _log.WarnFormat( + _log.Warn( "Parameter {0} is obsolete and will be remove in a future version. Explicitly affect your values to your entities properties instead.", BaseValueParameterName); customBaseDate = DateTime.Parse(value); diff --git a/src/NHibernate/Type/DbTimestampType.cs b/src/NHibernate/Type/DbTimestampType.cs index c205572823d..0fe280fed1c 100644 --- a/src/NHibernate/Type/DbTimestampType.cs +++ b/src/NHibernate/Type/DbTimestampType.cs @@ -16,7 +16,7 @@ namespace NHibernate.Type [Serializable] public partial class DbTimestampType : AbstractDateTimeType { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(DbTimestampType)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DbTimestampType)); private static readonly SqlType[] EmptyParams = new SqlType[0]; /// @@ -61,7 +61,7 @@ protected virtual DateTime UsePreparedStatement(string timestampSelectString, IS rs = session.Batcher.ExecuteReader(ps); rs.Read(); var ts = rs.GetDateTime(0); - log.DebugFormat("current timestamp retreived from db : {0} (ticks={1})", ts, ts.Ticks); + log.Debug("current timestamp retreived from db : {0} (ticks={1})", ts, ts.Ticks); return ts; } catch (DbException sqle) @@ -82,7 +82,7 @@ protected virtual DateTime UsePreparedStatement(string timestampSelectString, IS } catch (DbException sqle) { - log.Warn("unable to clean up prepared statement", sqle); + log.Warn(sqle, "unable to clean up prepared statement"); } } } diff --git a/src/NHibernate/Type/NullableType.cs b/src/NHibernate/Type/NullableType.cs index 93de6489f0d..da6597f9094 100644 --- a/src/NHibernate/Type/NullableType.cs +++ b/src/NHibernate/Type/NullableType.cs @@ -22,12 +22,12 @@ public abstract partial class NullableType : AbstractType static NullableType() { //cache this, because it was a significant performance cost - IsDebugEnabled = LoggerProvider.LoggerFor(typeof(IType).Namespace).IsDebugEnabled; + IsDebugEnabled = NHibernateLogger.For(typeof(IType).Namespace).IsDebugEnabled(); } - private IInternalLogger Log + private INHibernateLogger Log { - get { return LoggerProvider.LoggerFor(GetType()); } + get { return NHibernateLogger.For(GetType()); } } private readonly SqlType _sqlType; @@ -141,7 +141,7 @@ public sealed override void NullSafeSet(DbCommand st, object value, int index, I { if (IsDebugEnabled) { - Log.Debug("binding null to parameter: " + index); + Log.Debug("binding null to parameter: {0}", index); } //Do we check IsNullable? @@ -154,7 +154,7 @@ public sealed override void NullSafeSet(DbCommand st, object value, int index, I { if (IsDebugEnabled) { - Log.Debug("binding '" + ToString(value) + "' to parameter: " + index); + Log.Debug("binding '{0}' to parameter: {1}", ToString(value), index); } Set(st, value, index, session); @@ -219,7 +219,7 @@ public virtual object NullSafeGet(DbDataReader rs, string name, ISessionImplemen { if (IsDebugEnabled) { - Log.Debug("returning null as column: " + name); + Log.Debug("returning null as column: {0}", name); } // TODO: add a method to NullableType.GetNullValue - if we want to // use "MAGIC" numbers to indicate null values... @@ -242,7 +242,7 @@ public virtual object NullSafeGet(DbDataReader rs, string name, ISessionImplemen if (IsDebugEnabled) { - Log.Debug("returning '" + ToString(val) + "' as column: " + name); + Log.Debug("returning '{0}' as column: {1}", ToString(val), name); } return val; diff --git a/src/NHibernate/Type/TypeFactory.cs b/src/NHibernate/Type/TypeFactory.cs index e7a866ac5fa..ed10f0fe3a8 100644 --- a/src/NHibernate/Type/TypeFactory.cs +++ b/src/NHibernate/Type/TypeFactory.cs @@ -33,7 +33,7 @@ private enum TypeClassification PrecisionScale } - private static readonly IInternalLogger _log = LoggerProvider.LoggerFor(typeof(TypeFactory)); + private static readonly INHibernateLogger _log = NHibernateLogger.For(typeof(TypeFactory)); private static readonly string[] EmptyAliases= new string[0]; private static readonly char[] PrecisionScaleSplit = new[] { '(', ')', ',' }; private static readonly char[] LengthSplit = new[] { '(', ')' }; @@ -393,7 +393,7 @@ public static IType Basic(string name) if (typeByTypeOfName.TryGetValue(name, out returnType)) { if (_obsoleteMessageByAlias.TryGetValue(name, out string obsoleteMessage)) - _log.WarnFormat("{0} is obsolete. {1}", name, obsoleteMessage); + _log.Warn("{0} is obsolete. {1}", name, obsoleteMessage); return returnType; } @@ -578,7 +578,7 @@ public static IType HeuristicType(string typeName, IDictionary p var obsolete = typeClass.GetCustomAttribute(false); if (obsolete != null) { - _log.WarnFormat("{0} is obsolete. {1}", typeName, obsolete.Message); + _log.Warn("{0} is obsolete. {1}", typeName, obsolete.Message); } return type; } diff --git a/src/NHibernate/Util/ADOExceptionReporter.cs b/src/NHibernate/Util/ADOExceptionReporter.cs index 530f4d23077..3e2b787c6b2 100644 --- a/src/NHibernate/Util/ADOExceptionReporter.cs +++ b/src/NHibernate/Util/ADOExceptionReporter.cs @@ -5,7 +5,7 @@ namespace NHibernate.Util { public class ADOExceptionReporter { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ADOExceptionReporter)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ADOExceptionReporter)); public const string DefaultExceptionMsg = "SQL Exception"; private ADOExceptionReporter() @@ -19,20 +19,21 @@ public static void LogExceptions(Exception ex) public static void LogExceptions(Exception ex, string message) { - if (log.IsErrorEnabled) + if (log.IsErrorEnabled()) { - if (log.IsDebugEnabled) + if (log.IsDebugEnabled()) { message = StringHelper.IsNotEmpty(message) ? message : DefaultExceptionMsg; - log.Debug(message, ex); + log.Debug(ex, message); } + while (ex != null) { - log.Warn(ex); + log.Warn(ex, ex.Message); log.Error(ex.Message); ex = ex.InnerException; } } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Util/FilterHelper.cs b/src/NHibernate/Util/FilterHelper.cs index a5794332db6..3186f430cba 100644 --- a/src/NHibernate/Util/FilterHelper.cs +++ b/src/NHibernate/Util/FilterHelper.cs @@ -91,7 +91,7 @@ private static void AddFilterString(StringBuilder buffer, string defaultAlias, I upTo = upTo >= 0 ? upTo : condition.Length; string property = condition.Substring(startOfProperty, upTo - startOfProperty); - string fullColumn = propMap.ContainsKey(property) ? propMap[property] : string.Format(string.Format("{0}.{1}", defaultAlias, property)); + string fullColumn = propMap.ContainsKey(property) ? propMap[property] : string.Format("{0}.{1}", defaultAlias, property); buffer.Append(fullColumn); @@ -116,4 +116,4 @@ public static IDictionary GetEnabledForManyToOne(IDictionary public class JoinedEnumerable : IEnumerable { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(JoinedEnumerable)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(JoinedEnumerable)); private readonly IEnumerable[] _enumerables; diff --git a/src/NHibernate/Util/ReflectHelper.cs b/src/NHibernate/Util/ReflectHelper.cs index 2561323ac91..263764f1117 100644 --- a/src/NHibernate/Util/ReflectHelper.cs +++ b/src/NHibernate/Util/ReflectHelper.cs @@ -17,7 +17,7 @@ namespace NHibernate.Util /// public static class ReflectHelper { - private static readonly IInternalLogger log = LoggerProvider.LoggerFor(typeof(ReflectHelper)); + private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ReflectHelper)); public const BindingFlags AnyVisibilityInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; @@ -407,9 +407,9 @@ public static System.Type TypeFromAssembly(AssemblyQualifiedTypeName name, bool if (name.Assembly == null) { // No assembly was specified for the type, so just fail - string message = "Could not load type " + name + ". Possible cause: no assembly name specified."; - log.Warn(message); - if (throwOnError) throw new TypeLoadException(message); + const string noAssembly = "Could not load type {0}. Possible cause: no assembly name specified."; + log.Warn(noAssembly, name); + if (throwOnError) throw new TypeLoadException(string.Format(noAssembly, name)); return null; } @@ -417,7 +417,7 @@ public static System.Type TypeFromAssembly(AssemblyQualifiedTypeName name, bool if (assembly == null) { - log.Warn("Could not load type " + name + ". Possible cause: incorrect assembly name specified."); + log.Warn("Could not load type {0}. Possible cause: incorrect assembly name specified.", name); return null; } @@ -425,7 +425,7 @@ public static System.Type TypeFromAssembly(AssemblyQualifiedTypeName name, bool if (type == null) { - log.Warn("Could not load type " + name + "."); + log.Warn("Could not load type {0}.", name); return null; } @@ -433,9 +433,9 @@ public static System.Type TypeFromAssembly(AssemblyQualifiedTypeName name, bool } catch (Exception e) { - if (log.IsErrorEnabled) + if (log.IsErrorEnabled()) { - log.Error("Could not load type " + name + ".", e); + log.Error(e, "Could not load type {0}.", name); } if (throwOnError) throw; return null; From 433921ad6caf79e7612fe96d03d567399093c1ce Mon Sep 17 00:00:00 2001 From: Gunnar Liljas Date: Thu, 7 Dec 2017 00:12:47 +0100 Subject: [PATCH 14/32] Upgrade AsyncGenerator to 0.7.0 --- Tools/packages.config | 2 +- src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Tools/packages.config b/Tools/packages.config index abc3ac2be5f..73a899fb80c 100644 --- a/Tools/packages.config +++ b/Tools/packages.config @@ -7,6 +7,6 @@ - + diff --git a/src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs index 1a9cdefceac..71ada7ac57e 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs @@ -156,7 +156,8 @@ public async Task WillGetSessionIdFromSessionLogsConcurrentAsync() var sessionIds = new ConcurrentDictionary(); using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}")) { - await (Task.WhenAll(Enumerable.Range( 1, 12).Select( async i => + await (Task.WhenAll( + Enumerable.Range(1, 12 - 1).Select(async i => { if (i > 10) { From 293c2eb5cf688cff03428fadc52f5c54d44bead6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Thu, 7 Dec 2017 11:58:44 +0100 Subject: [PATCH 15/32] NH-3787 - Decimal truncation in Linq ternary expression (#707) * Fixes #1335 --- .../NHSpecificTest/NH3787/TestFixture.cs | 140 ++++++++++++++++++ .../NHSpecificTest/NH3787/Mappings.hbm.xml | 12 ++ .../NHSpecificTest/NH3787/RateDto.cs | 7 + .../NHSpecificTest/NH3787/TestEntity.cs | 10 ++ .../NHSpecificTest/NH3787/TestFixture.cs | 129 ++++++++++++++++ src/NHibernate/Dialect/Dialect.cs | 1 + .../Function/TransparentCastFunction.cs | 16 ++ src/NHibernate/Dialect/SQLiteDialect.cs | 3 + .../ANTLR/SessionFactoryHelperExtensions.cs | 2 +- src/NHibernate/Hql/Ast/HqlTreeBuilder.cs | 11 ++ src/NHibernate/Hql/Ast/HqlTreeNode.cs | 13 ++ .../Visitors/HqlGeneratorExpressionVisitor.cs | 9 +- 12 files changed, 349 insertions(+), 4 deletions(-) create mode 100644 src/NHibernate.Test/Async/NHSpecificTest/NH3787/TestFixture.cs create mode 100644 src/NHibernate.Test/NHSpecificTest/NH3787/Mappings.hbm.xml create mode 100644 src/NHibernate.Test/NHSpecificTest/NH3787/RateDto.cs create mode 100644 src/NHibernate.Test/NHSpecificTest/NH3787/TestEntity.cs create mode 100644 src/NHibernate.Test/NHSpecificTest/NH3787/TestFixture.cs create mode 100644 src/NHibernate/Dialect/Function/TransparentCastFunction.cs diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH3787/TestFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH3787/TestFixture.cs new file mode 100644 index 00000000000..0cc7243bf40 --- /dev/null +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH3787/TestFixture.cs @@ -0,0 +1,140 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by AsyncGenerator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +using System.Linq; +using NHibernate.Criterion; +using NHibernate.Linq; +using NHibernate.Transform; +using NHibernate.Type; +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.NH3787 +{ + using System.Threading.Tasks; + [TestFixture] + public class TestFixtureAsync : BugTestCase + { + private const decimal _testRate = 12345.1234567890123M; + + protected override bool AppliesTo(Dialect.Dialect dialect) + { + return !TestDialect.HasBrokenDecimalType; + } + + protected override void OnSetUp() + { + base.OnSetUp(); + + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var testEntity = new TestEntity + { + UsePreviousRate = true, + PreviousRate = _testRate, + Rate = 54321.1234567890123M + }; + s.Save(testEntity); + t.Commit(); + } + } + + protected override void OnTearDown() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + s.CreateQuery("delete from TestEntity").ExecuteUpdate(); + t.Commit(); + } + } + + [Test] + public async Task TestLinqQueryAsync() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var queryResult = await (s + .Query() + .Where(e => e.PreviousRate == _testRate) + .ToListAsync()); + + Assert.That(queryResult.Count, Is.EqualTo(1)); + Assert.That(queryResult[0].PreviousRate, Is.EqualTo(_testRate)); + await (t.CommitAsync()); + } + } + + [Test] + public async Task TestLinqProjectionAsync() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var queryResult = await ((from test in s.Query() + select new RateDto { Rate = test.UsePreviousRate ? test.PreviousRate : test.Rate }).ToListAsync()); + + // Check it has not been truncated to the default scale (10) of NHibernate. + Assert.That(queryResult[0].Rate, Is.EqualTo(_testRate)); + await (t.CommitAsync()); + } + } + + [Test] + public async Task TestLinqQueryOnExpressionAsync() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var queryResult = await (s + .Query() + .Where( + // Without MappedAs, the test fails for SQL Server because it would restrict its parameter to the dialect's default scale. + e => (e.UsePreviousRate ? e.PreviousRate : e.Rate) == _testRate.MappedAs(TypeFactory.Basic("decimal(18,13)"))) + .ToListAsync()); + + Assert.That(queryResult.Count, Is.EqualTo(1)); + Assert.That(queryResult[0].PreviousRate, Is.EqualTo(_testRate)); + await (t.CommitAsync()); + } + } + + [Test] + public async Task TestQueryOverProjectionAsync() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + TestEntity testEntity = null; + + var rateDto = new RateDto(); + //Generated sql + //exec sp_executesql N'SELECT (case when this_.UsePreviousRate = @p0 then this_.PreviousRate else this_.Rate end) as y0_ FROM [TestEntity] this_',N'@p0 bit',@p0=1 + var query = s + .QueryOver(() => testEntity) + .Select( + Projections + .Alias( + Projections.Conditional( + Restrictions.Eq(Projections.Property(() => testEntity.UsePreviousRate), true), + Projections.Property(() => testEntity.PreviousRate), + Projections.Property(() => testEntity.Rate)), + "Rate") + .WithAlias(() => rateDto.Rate)); + + var queryResult = await (query.TransformUsing(Transformers.AliasToBean()).ListAsync()); + + Assert.That(queryResult[0].Rate, Is.EqualTo(_testRate)); + await (t.CommitAsync()); + } + } + } +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH3787/Mappings.hbm.xml b/src/NHibernate.Test/NHSpecificTest/NH3787/Mappings.hbm.xml new file mode 100644 index 00000000000..56a52e4eb78 --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/NH3787/Mappings.hbm.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + diff --git a/src/NHibernate.Test/NHSpecificTest/NH3787/RateDto.cs b/src/NHibernate.Test/NHSpecificTest/NH3787/RateDto.cs new file mode 100644 index 00000000000..a36b9439733 --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/NH3787/RateDto.cs @@ -0,0 +1,7 @@ +namespace NHibernate.Test.NHSpecificTest.NH3787 +{ + public class RateDto + { + public decimal Rate { get; set; } + } +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH3787/TestEntity.cs b/src/NHibernate.Test/NHSpecificTest/NH3787/TestEntity.cs new file mode 100644 index 00000000000..6bad2e9c918 --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/NH3787/TestEntity.cs @@ -0,0 +1,10 @@ +namespace NHibernate.Test.NHSpecificTest.NH3787 +{ + public class TestEntity + { + public virtual int Id { get; set; } + public virtual bool UsePreviousRate { get; set; } + public virtual decimal Rate { get; set; } + public virtual decimal PreviousRate { get; set; } + } +} diff --git a/src/NHibernate.Test/NHSpecificTest/NH3787/TestFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3787/TestFixture.cs new file mode 100644 index 00000000000..91f6bbd514f --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/NH3787/TestFixture.cs @@ -0,0 +1,129 @@ +using System.Linq; +using NHibernate.Criterion; +using NHibernate.Linq; +using NHibernate.Transform; +using NHibernate.Type; +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.NH3787 +{ + [TestFixture] + public class TestFixture : BugTestCase + { + private const decimal _testRate = 12345.1234567890123M; + + protected override bool AppliesTo(Dialect.Dialect dialect) + { + return !TestDialect.HasBrokenDecimalType; + } + + protected override void OnSetUp() + { + base.OnSetUp(); + + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var testEntity = new TestEntity + { + UsePreviousRate = true, + PreviousRate = _testRate, + Rate = 54321.1234567890123M + }; + s.Save(testEntity); + t.Commit(); + } + } + + protected override void OnTearDown() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + s.CreateQuery("delete from TestEntity").ExecuteUpdate(); + t.Commit(); + } + } + + [Test] + public void TestLinqQuery() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var queryResult = s + .Query() + .Where(e => e.PreviousRate == _testRate) + .ToList(); + + Assert.That(queryResult.Count, Is.EqualTo(1)); + Assert.That(queryResult[0].PreviousRate, Is.EqualTo(_testRate)); + t.Commit(); + } + } + + [Test] + public void TestLinqProjection() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var queryResult = (from test in s.Query() + select new RateDto { Rate = test.UsePreviousRate ? test.PreviousRate : test.Rate }).ToList(); + + // Check it has not been truncated to the default scale (10) of NHibernate. + Assert.That(queryResult[0].Rate, Is.EqualTo(_testRate)); + t.Commit(); + } + } + + [Test] + public void TestLinqQueryOnExpression() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + var queryResult = s + .Query() + .Where( + // Without MappedAs, the test fails for SQL Server because it would restrict its parameter to the dialect's default scale. + e => (e.UsePreviousRate ? e.PreviousRate : e.Rate) == _testRate.MappedAs(TypeFactory.Basic("decimal(18,13)"))) + .ToList(); + + Assert.That(queryResult.Count, Is.EqualTo(1)); + Assert.That(queryResult[0].PreviousRate, Is.EqualTo(_testRate)); + t.Commit(); + } + } + + [Test] + public void TestQueryOverProjection() + { + using (var s = OpenSession()) + using (var t = s.BeginTransaction()) + { + TestEntity testEntity = null; + + var rateDto = new RateDto(); + //Generated sql + //exec sp_executesql N'SELECT (case when this_.UsePreviousRate = @p0 then this_.PreviousRate else this_.Rate end) as y0_ FROM [TestEntity] this_',N'@p0 bit',@p0=1 + var query = s + .QueryOver(() => testEntity) + .Select( + Projections + .Alias( + Projections.Conditional( + Restrictions.Eq(Projections.Property(() => testEntity.UsePreviousRate), true), + Projections.Property(() => testEntity.PreviousRate), + Projections.Property(() => testEntity.Rate)), + "Rate") + .WithAlias(() => rateDto.Rate)); + + var queryResult = query.TransformUsing(Transformers.AliasToBean()).List(); + + Assert.That(queryResult[0].Rate, Is.EqualTo(_testRate)); + t.Commit(); + } + } + } +} diff --git a/src/NHibernate/Dialect/Dialect.cs b/src/NHibernate/Dialect/Dialect.cs index 212cc1327e5..753462bbc27 100644 --- a/src/NHibernate/Dialect/Dialect.cs +++ b/src/NHibernate/Dialect/Dialect.cs @@ -98,6 +98,7 @@ protected Dialect() RegisterFunction("upper", new StandardSQLFunction("upper")); RegisterFunction("lower", new StandardSQLFunction("lower")); RegisterFunction("cast", new CastFunction()); + RegisterFunction("transparentcast", new TransparentCastFunction()); RegisterFunction("extract", new AnsiExtractFunction()); RegisterFunction("concat", new VarArgsSQLFunction(NHibernateUtil.String, "(", "||", ")")); diff --git a/src/NHibernate/Dialect/Function/TransparentCastFunction.cs b/src/NHibernate/Dialect/Function/TransparentCastFunction.cs new file mode 100644 index 00000000000..3572fc422ce --- /dev/null +++ b/src/NHibernate/Dialect/Function/TransparentCastFunction.cs @@ -0,0 +1,16 @@ +using System; + +namespace NHibernate.Dialect.Function +{ + /// + /// A HQL only cast for helping HQL knowing the type. Does not generates any actual cast in SQL code. + /// + [Serializable] + public class TransparentCastFunction : CastFunction + { + protected override bool CastingIsRequired(string sqlType) + { + return false; + } + } +} diff --git a/src/NHibernate/Dialect/SQLiteDialect.cs b/src/NHibernate/Dialect/SQLiteDialect.cs index 03748e0b022..737b8ce31e2 100644 --- a/src/NHibernate/Dialect/SQLiteDialect.cs +++ b/src/NHibernate/Dialect/SQLiteDialect.cs @@ -86,6 +86,9 @@ protected virtual void RegisterFunctions() RegisterFunction("cast", new SQLiteCastFunction()); RegisterFunction("round", new StandardSQLFunction("round")); + + // NH-3787: SQLite requires the cast in SQL too for not defaulting to string. + RegisterFunction("transparentcast", new CastFunction()); } #region private static readonly string[] DialectKeywords = { ... } diff --git a/src/NHibernate/Hql/Ast/ANTLR/SessionFactoryHelperExtensions.cs b/src/NHibernate/Hql/Ast/ANTLR/SessionFactoryHelperExtensions.cs index d2dc73c2934..142c8a0c4ab 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/SessionFactoryHelperExtensions.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/SessionFactoryHelperExtensions.cs @@ -77,7 +77,7 @@ public IType FindFunctionReturnType(String functionName, IASTNode first) if (first != null) { - if (functionName == "cast") + if (sqlFunction is CastFunction) { argumentType = TypeFactory.HeuristicType(first.NextSibling.Text); } diff --git a/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs b/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs index bbe3517c776..e49cac5a5b3 100755 --- a/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs +++ b/src/NHibernate/Hql/Ast/HqlTreeBuilder.cs @@ -301,6 +301,17 @@ public HqlCast Cast(HqlExpression expression, System.Type type) return new HqlCast(_factory, expression, type); } + /// + /// Generate a cast node intended solely to hint HQL at the resulting type, without issuing an actual SQL cast. + /// + /// The expression to cast. + /// The resulting type. + /// A node. + public HqlTransparentCast TransparentCast(HqlExpression expression, System.Type type) + { + return new HqlTransparentCast(_factory, expression, type); + } + public HqlBitwiseNot BitwiseNot() { return new HqlBitwiseNot(_factory); diff --git a/src/NHibernate/Hql/Ast/HqlTreeNode.cs b/src/NHibernate/Hql/Ast/HqlTreeNode.cs index b44efbe4c84..fba59d196dd 100755 --- a/src/NHibernate/Hql/Ast/HqlTreeNode.cs +++ b/src/NHibernate/Hql/Ast/HqlTreeNode.cs @@ -701,6 +701,19 @@ public HqlCast(IASTFactory factory, HqlExpression expression, System.Type type) } } + /// + /// Cast node intended solely to hint HQL at the resulting type, without issuing an actual SQL cast. + /// + public class HqlTransparentCast : HqlExpression + { + public HqlTransparentCast(IASTFactory factory, HqlExpression expression, System.Type type) + : base(HqlSqlWalker.METHOD_CALL, "method", factory) + { + AddChild(new HqlIdent(factory, "transparentcast")); + AddChild(new HqlExpressionList(factory, expression, new HqlIdent(factory, type))); + } + } + public class HqlCoalesce : HqlExpression { public HqlCoalesce(IASTFactory factory, HqlExpression lhs, HqlExpression rhs) diff --git a/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionVisitor.cs b/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionVisitor.cs index 0b707fb52db..598c2828bde 100644 --- a/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionVisitor.cs +++ b/src/NHibernate/Linq/Visitors/HqlGeneratorExpressionVisitor.cs @@ -537,9 +537,12 @@ protected HqlTreeNode VisitConditionalExpression(ConditionalExpression expressio HqlExpression @case = _hqlTreeBuilder.Case(new[] {_hqlTreeBuilder.When(test, ifTrue)}, ifFalse); - return (expression.Type == typeof (bool) || expression.Type == (typeof (bool?))) - ? @case - : _hqlTreeBuilder.Cast(@case, expression.Type); + // If both operands are parameters, HQL will not be able to determine the resulting type before + // parameters binding. But it has to compute result set columns type before parameters are bound, + // so an artificial cast is introduced to hint HQL at the resulting type. + return expression.Type == typeof(bool) || expression.Type == typeof(bool?) + ? @case + : _hqlTreeBuilder.TransparentCast(@case, expression.Type); } protected HqlTreeNode VisitSubQueryExpression(SubQueryExpression expression) From bf7e34d55b5606ba91c269cdedae537a049cd165 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Thu, 7 Dec 2017 20:35:12 +0100 Subject: [PATCH 16/32] Document expiration constraint on UpdateTimestampsCache region. --- doc/reference/modules/performance.xml | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/doc/reference/modules/performance.xml b/doc/reference/modules/performance.xml index 533b179a038..4a629f0d5d9 100644 --- a/doc/reference/modules/performance.xml +++ b/doc/reference/modules/performance.xml @@ -943,11 +943,20 @@ sessionFactory.EvictCollection("Eg.Cat.Kittens");]]> This setting causes the creation of two new cache regions - one holding cached query result sets (NHibernate.Cache.StandardQueryCache), the other - holding timestamps of the most recent updates to queryable tables - (NHibernate.Cache.UpdateTimestampsCache). Note that the query - cache does not cache the state of any entities in the result set; it caches - only identifier values and results of value type. So the query cache should always be - used in conjunction with the second-level cache. + holding timestamps of the most recent updates to queryable tables + (UpdateTimestampsCache). Those region names will be prefixed by the + cache region prefix if cache.region_prefix setting is configured. + + + If you use a cache provider handling an expiration for cached entries, you should set + the UpdateTimestampsCache region expiration to a value greater than + the expiration of query cache regions. (Or disable its expiration.) Otherwise the query + cache may yield stale data. + + + Note that the query cache does not cache the state of any entities in the result set; + it caches only identifier values and results of value type. So the query cache should + always be used in conjunction with the second-level cache. From 73797df2ef79ecbd018dd2f416ea68849f8655c9 Mon Sep 17 00:00:00 2001 From: Gunnar Liljas Date: Fri, 8 Dec 2017 05:51:41 +0100 Subject: [PATCH 17/32] Reduce the number of calls to UpdateTimestampsCache (#1467) - Make methods of UpdateTimestampsCache virtual - Mark some methods UpdateTimestampsCache obsolete --- src/AsyncGenerator.yml | 10 +- .../SecondLevelCacheTest/InvalidationTests.cs | 115 ++++++++++++ .../SecondLevelCacheTest/InvalidationTests.cs | 102 +++++++++++ .../Async/Cache/UpdateTimestampsCache.cs | 60 +++++-- src/NHibernate/Async/Engine/ActionQueue.cs | 147 +++++++++------- .../Async/Engine/Query/NativeSQLQueryPlan.cs | 2 +- .../ANTLR/Exec/AbstractStatementExecutor.cs | 2 +- src/NHibernate/Cache/UpdateTimestampsCache.cs | 39 +++-- src/NHibernate/Engine/ActionQueue.cs | 165 +++++++++++------- 9 files changed, 484 insertions(+), 158 deletions(-) create mode 100644 src/NHibernate.Test/Async/SecondLevelCacheTest/InvalidationTests.cs create mode 100644 src/NHibernate.Test/SecondLevelCacheTest/InvalidationTests.cs diff --git a/src/AsyncGenerator.yml b/src/AsyncGenerator.yml index accaaeabe72..7022d322eb6 100644 --- a/src/AsyncGenerator.yml +++ b/src/AsyncGenerator.yml @@ -4,8 +4,6 @@ applyChanges: true analyzation: methodConversion: - - conversion: Ignore - hasAttributeName: ObsoleteAttribute - conversion: Ignore name: PostProcessInsert containingTypeName: HqlSqlWalker @@ -96,6 +94,9 @@ - conversion: Ignore name: Exists containingTypeName: AbstractCollectionPersister + - conversion: Ignore + name: QuoteTableAndColumns + containingTypeName: SchemaMetadataUpdater - conversion: ToAsync name: ExecuteReader containingTypeName: IBatcher @@ -119,6 +120,8 @@ - name: GetFieldValue - name: IsDBNull - name: WriteLine + ignoreAsyncCounterparts: + - rule: Obsolete callForwarding: true cancellationTokens: guards: true @@ -259,6 +262,9 @@ methodRules: - containingType: NHibernate.Tool.hbm2ddl.SchemaValidator - containingType: NHibernate.Tool.hbm2ddl.SchemaExport name: PubliclyExposedType +- filters: + - hasAttributeName: ObsoleteAttribute + name: Obsolete typeRules: - filters: - containingAssemblyName: NHibernate diff --git a/src/NHibernate.Test/Async/SecondLevelCacheTest/InvalidationTests.cs b/src/NHibernate.Test/Async/SecondLevelCacheTest/InvalidationTests.cs new file mode 100644 index 00000000000..76e5b040cbb --- /dev/null +++ b/src/NHibernate.Test/Async/SecondLevelCacheTest/InvalidationTests.cs @@ -0,0 +1,115 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by AsyncGenerator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using NHibernate.Cache; +using NHibernate.Cfg; +using NHibernate.Engine; +using NHibernate.Impl; +using NHibernate.Test.SecondLevelCacheTests; +using NSubstitute; +using NUnit.Framework; + +namespace NHibernate.Test.SecondLevelCacheTest +{ + using System.Threading.Tasks; + using System.Threading; + [TestFixture] + public class InvalidationTestsAsync : TestCase + { + protected override string MappingsAssembly => "NHibernate.Test"; + + protected override IList Mappings => new[] { "SecondLevelCacheTest.Item.hbm.xml" }; + + protected override void Configure(Configuration configuration) + { + configuration.SetProperty(Environment.CacheProvider, typeof(HashtableCacheProvider).AssemblyQualifiedName); + configuration.SetProperty(Environment.UseQueryCache, "true"); + } + + [Test] + public async Task InvalidatesEntitiesAsync() + { + var debugSessionFactory = (DebugSessionFactory) Sfi; + + var cache = Substitute.For(Sfi.Settings, new Dictionary()); + + var updateTimestampsCacheField = typeof(SessionFactoryImpl).GetField( + "updateTimestampsCache", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + + updateTimestampsCacheField.SetValue(debugSessionFactory.ActualFactory, cache); + + //"Received" assertions can not be used since the collection is reused and cleared between calls. + //The received args are cloned and stored + var preInvalidations = new List>(); + var invalidations = new List>(); + + await (cache.PreInvalidateAsync(Arg.Do>(x => preInvalidations.Add(x.ToList())), CancellationToken.None)); + await (cache.InvalidateAsync(Arg.Do>(x => invalidations.Add(x.ToList())), CancellationToken.None)); + + using (var session = OpenSession()) + { + using (var tx = session.BeginTransaction()) + { + foreach (var i in Enumerable.Range(1, 10)) + { + var item = new Item {Id = i}; + await (session.SaveAsync(item)); + } + + await (tx.CommitAsync()); + } + + using (var tx = session.BeginTransaction()) + { + foreach (var i in Enumerable.Range(1, 10)) + { + var item = await (session.GetAsync(i)); + item.Name = item.Id.ToString(); + } + + await (tx.CommitAsync()); + } + + using (var tx = session.BeginTransaction()) + { + foreach (var i in Enumerable.Range(1, 10)) + { + var item = await (session.GetAsync(i)); + await (session.DeleteAsync(item)); + } + + await (tx.CommitAsync()); + } + } + + //Should receive one preinvalidation and one invalidation per commit + Assert.That(preInvalidations, Has.Count.EqualTo(3)); + Assert.That(preInvalidations, Has.All.Count.EqualTo(1).And.Contains("Item")); + + Assert.That(invalidations, Has.Count.EqualTo(3)); + Assert.That(invalidations, Has.All.Count.EqualTo(1).And.Contains("Item")); + } + + protected override void OnTearDown() + { + using (var s = OpenSession()) + using (var tx = s.BeginTransaction()) + { + s.Delete("from Item"); + tx.Commit(); + } + } + } +} diff --git a/src/NHibernate.Test/SecondLevelCacheTest/InvalidationTests.cs b/src/NHibernate.Test/SecondLevelCacheTest/InvalidationTests.cs new file mode 100644 index 00000000000..050a488bc1e --- /dev/null +++ b/src/NHibernate.Test/SecondLevelCacheTest/InvalidationTests.cs @@ -0,0 +1,102 @@ +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using NHibernate.Cache; +using NHibernate.Cfg; +using NHibernate.Impl; +using NHibernate.Test.SecondLevelCacheTests; +using NSubstitute; +using NUnit.Framework; + +namespace NHibernate.Test.SecondLevelCacheTest +{ + [TestFixture] + public class InvalidationTests : TestCase + { + protected override string MappingsAssembly => "NHibernate.Test"; + + protected override IList Mappings => new[] { "SecondLevelCacheTest.Item.hbm.xml" }; + + protected override void Configure(Configuration configuration) + { + configuration.SetProperty(Environment.CacheProvider, typeof(HashtableCacheProvider).AssemblyQualifiedName); + configuration.SetProperty(Environment.UseQueryCache, "true"); + } + + [Test] + public void InvalidatesEntities() + { + var debugSessionFactory = (DebugSessionFactory) Sfi; + + var cache = Substitute.For(Sfi.Settings, new Dictionary()); + + var updateTimestampsCacheField = typeof(SessionFactoryImpl).GetField( + "updateTimestampsCache", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + + updateTimestampsCacheField.SetValue(debugSessionFactory.ActualFactory, cache); + + //"Received" assertions can not be used since the collection is reused and cleared between calls. + //The received args are cloned and stored + var preInvalidations = new List>(); + var invalidations = new List>(); + + cache.PreInvalidate(Arg.Do>(x => preInvalidations.Add(x.ToList()))); + cache.Invalidate(Arg.Do>(x => invalidations.Add(x.ToList()))); + + using (var session = OpenSession()) + { + using (var tx = session.BeginTransaction()) + { + foreach (var i in Enumerable.Range(1, 10)) + { + var item = new Item {Id = i}; + session.Save(item); + } + + tx.Commit(); + } + + using (var tx = session.BeginTransaction()) + { + foreach (var i in Enumerable.Range(1, 10)) + { + var item = session.Get(i); + item.Name = item.Id.ToString(); + } + + tx.Commit(); + } + + using (var tx = session.BeginTransaction()) + { + foreach (var i in Enumerable.Range(1, 10)) + { + var item = session.Get(i); + session.Delete(item); + } + + tx.Commit(); + } + } + + //Should receive one preinvalidation and one invalidation per commit + Assert.That(preInvalidations, Has.Count.EqualTo(3)); + Assert.That(preInvalidations, Has.All.Count.EqualTo(1).And.Contains("Item")); + + Assert.That(invalidations, Has.Count.EqualTo(3)); + Assert.That(invalidations, Has.All.Count.EqualTo(1).And.Contains("Item")); + } + + protected override void OnTearDown() + { + using (var s = OpenSession()) + using (var tx = s.BeginTransaction()) + { + s.Delete("from Item"); + tx.Commit(); + } + } + } +} diff --git a/src/NHibernate/Async/Cache/UpdateTimestampsCache.cs b/src/NHibernate/Async/Cache/UpdateTimestampsCache.cs index 5a1867189fd..9a086f16333 100644 --- a/src/NHibernate/Async/Cache/UpdateTimestampsCache.cs +++ b/src/NHibernate/Async/Cache/UpdateTimestampsCache.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Runtime.CompilerServices; using NHibernate.Cfg; @@ -24,7 +25,7 @@ public partial class UpdateTimestampsCache private readonly NHibernate.Util.AsyncLock _invalidate = new NHibernate.Util.AsyncLock(); private readonly NHibernate.Util.AsyncLock _isUpToDate = new NHibernate.Util.AsyncLock(); - public Task ClearAsync(CancellationToken cancellationToken) + public virtual Task ClearAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { @@ -33,26 +34,65 @@ public Task ClearAsync(CancellationToken cancellationToken) return updateTimestamps.ClearAsync(cancellationToken); } + //Since v5.1 + [Obsolete("Please use PreInvalidate(IReadOnlyCollection) instead.")] + public Task PreInvalidateAsync(object[] spaces, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + try + { + //Only for backwards compatibility. + return PreInvalidateAsync(spaces.OfType().ToList(), cancellationToken); + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + [MethodImpl()] - public async Task PreInvalidateAsync(object[] spaces, CancellationToken cancellationToken) + public virtual async Task PreInvalidateAsync(IReadOnlyCollection spaces, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (await _preInvalidate.LockAsync()) { //TODO: to handle concurrent writes correctly, this should return a Lock to the client long ts = updateTimestamps.NextTimestamp() + updateTimestamps.Timeout; - for (int i = 0; i < spaces.Length; i++) + foreach (var space in spaces) { - await (updateTimestamps.PutAsync(spaces[i], ts, cancellationToken)).ConfigureAwait(false); + await (updateTimestamps.PutAsync(space, ts, cancellationToken)).ConfigureAwait(false); } + //TODO: return new Lock(ts); } + //TODO: return new Lock(ts); } - /// + //Since v5.1 + [Obsolete("Please use PreInvalidate(IReadOnlyCollection) instead.")] + public Task InvalidateAsync(object[] spaces, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + try + { + //Only for backwards compatibility. + return InvalidateAsync(spaces.OfType().ToList(), cancellationToken); + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + [MethodImpl()] - public async Task InvalidateAsync(object[] spaces, CancellationToken cancellationToken) + public virtual async Task InvalidateAsync(IReadOnlyCollection spaces, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (await _invalidate.LockAsync()) @@ -60,16 +100,16 @@ public async Task InvalidateAsync(object[] spaces, CancellationToken cancellatio //TODO: to handle concurrent writes correctly, the client should pass in a Lock long ts = updateTimestamps.NextTimestamp(); //TODO: if lock.getTimestamp().equals(ts) - for (int i = 0; i < spaces.Length; i++) + foreach (var space in spaces) { - log.Debug("Invalidating space [{0}]", spaces[i]); - await (updateTimestamps.PutAsync(spaces[i], ts, cancellationToken)).ConfigureAwait(false); + log.Debug("Invalidating space [{0}]", space); + await (updateTimestamps.PutAsync(space, ts, cancellationToken)).ConfigureAwait(false); } } } [MethodImpl()] - public async Task IsUpToDateAsync(ISet spaces, long timestamp /* H2.1 has Long here */, CancellationToken cancellationToken) + public virtual async Task IsUpToDateAsync(ISet spaces, long timestamp /* H2.1 has Long here */, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); using (await _isUpToDate.LockAsync()) diff --git a/src/NHibernate/Async/Engine/ActionQueue.cs b/src/NHibernate/Async/Engine/ActionQueue.cs index 26d53443fb2..15a5951dbdd 100644 --- a/src/NHibernate/Async/Engine/ActionQueue.cs +++ b/src/NHibernate/Async/Engine/ActionQueue.cs @@ -13,26 +13,16 @@ using System.Collections.Generic; using System.Linq; using System.Text; - +using System.Threading; +using System.Threading.Tasks; using NHibernate.Action; using NHibernate.Cache; using NHibernate.Type; namespace NHibernate.Engine { - using System.Threading.Tasks; - using System.Threading; public partial class ActionQueue { - - public Task AddActionAsync(BulkOperationCleanupAction cleanupAction, CancellationToken cancellationToken) - { - if (cancellationToken.IsCancellationRequested) - { - return Task.FromCanceled(cancellationToken); - } - return RegisterCleanupActionsAsync(cleanupAction, cancellationToken); - } private async Task ExecuteActionsAsync(IList list, CancellationToken cancellationToken) { @@ -41,50 +31,80 @@ private async Task ExecuteActionsAsync(IList list, CancellationToken cancellatio // It will then fail here due to list being modified. (Some previous code was dodging the // trouble with a for loop which was not failing provided the list was not getting smaller. // But then it was clearing it without having executed added actions (if any), ...) + foreach (IExecutable executable in list) - await (ExecuteAsync(executable, cancellationToken)).ConfigureAwait(false); - + { + await (InnerExecuteAsync(executable, cancellationToken)).ConfigureAwait(false); + } list.Clear(); await (session.Batcher.ExecuteBatchAsync(cancellationToken)).ConfigureAwait(false); } + private Task PreInvalidateCachesAsync(CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + try + { + if (session.Factory.Settings.IsQueryCacheEnabled) + { + return session.Factory.UpdateTimestampsCache.PreInvalidateAsync(executedSpaces, cancellationToken); + } + return Task.CompletedTask; + } + catch (Exception ex) + { + return Task.FromException(ex); + } + } + public async Task ExecuteAsync(IExecutable executable, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { - await (executable.ExecuteAsync(cancellationToken)).ConfigureAwait(false); + await (InnerExecuteAsync(executable, cancellationToken)).ConfigureAwait(false); } finally { - await (RegisterCleanupActionsAsync(executable, cancellationToken)).ConfigureAwait(false); + await (PreInvalidateCachesAsync(cancellationToken)).ConfigureAwait(false); } } - - private async Task RegisterCleanupActionsAsync(IExecutable executable, CancellationToken cancellationToken) + + private async Task InnerExecuteAsync(IExecutable executable, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - beforeTransactionProcesses.Register(executable.BeforeTransactionCompletionProcess); - if (session.Factory.Settings.IsQueryCacheEnabled) + try { - string[] spaces = executable.PropertySpaces; - afterTransactionProcesses.AddSpacesToInvalidate(spaces); - await (session.Factory.UpdateTimestampsCache.PreInvalidateAsync(spaces, cancellationToken)).ConfigureAwait(false); + await (executable.ExecuteAsync(cancellationToken)).ConfigureAwait(false); + } + finally + { + if (executable.PropertySpaces != null) + { + executedSpaces.UnionWith(executable.PropertySpaces); + } + RegisterCleanupActions(executable); } - afterTransactionProcesses.Register(executable.AfterTransactionCompletionProcess); } /// /// Perform all currently queued entity-insertion actions. /// /// A cancellation token that can be used to cancel the work - public Task ExecuteInsertsAsync(CancellationToken cancellationToken) + public async Task ExecuteInsertsAsync(CancellationToken cancellationToken) { - if (cancellationToken.IsCancellationRequested) + cancellationToken.ThrowIfCancellationRequested(); + try { - return Task.FromCanceled(cancellationToken); + await (ExecuteActionsAsync(insertions, cancellationToken)).ConfigureAwait(false); + } + finally + { + await (PreInvalidateCachesAsync(cancellationToken)).ConfigureAwait(false); } - return ExecuteActionsAsync(insertions, cancellationToken); } /// @@ -94,15 +114,22 @@ public Task ExecuteInsertsAsync(CancellationToken cancellationToken) public async Task ExecuteActionsAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - await (ExecuteActionsAsync(insertions, cancellationToken)).ConfigureAwait(false); - await (ExecuteActionsAsync(updates, cancellationToken)).ConfigureAwait(false); - await (ExecuteActionsAsync(collectionRemovals, cancellationToken)).ConfigureAwait(false); - await (ExecuteActionsAsync(collectionUpdates, cancellationToken)).ConfigureAwait(false); - await (ExecuteActionsAsync(collectionCreations, cancellationToken)).ConfigureAwait(false); - await (ExecuteActionsAsync(deletions, cancellationToken)).ConfigureAwait(false); + try + { + await (ExecuteActionsAsync(insertions, cancellationToken)).ConfigureAwait(false); + await (ExecuteActionsAsync(updates, cancellationToken)).ConfigureAwait(false); + await (ExecuteActionsAsync(collectionRemovals, cancellationToken)).ConfigureAwait(false); + await (ExecuteActionsAsync(collectionUpdates, cancellationToken)).ConfigureAwait(false); + await (ExecuteActionsAsync(collectionCreations, cancellationToken)).ConfigureAwait(false); + await (ExecuteActionsAsync(deletions, cancellationToken)).ConfigureAwait(false); + } + finally + { + await (PreInvalidateCachesAsync(cancellationToken)).ConfigureAwait(false); + } } - private async Task PrepareActionsAsync(IList queue, CancellationToken cancellationToken) + private static async Task PrepareActionsAsync(IList queue, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); foreach (IExecutable executable in queue) @@ -120,7 +147,7 @@ public async Task PrepareActionsAsync(CancellationToken cancellationToken) await (PrepareActionsAsync(collectionUpdates, cancellationToken)).ConfigureAwait(false); await (PrepareActionsAsync(collectionCreations, cancellationToken)).ConfigureAwait(false); } - + /// /// Performs cleanup of any held cache softlocks. /// @@ -132,41 +159,27 @@ public Task AfterTransactionCompletionAsync(bool success, CancellationToken canc { return Task.FromCanceled(cancellationToken); } - return afterTransactionProcesses.AfterTransactionCompletionAsync(success, cancellationToken); + try + { + afterTransactionProcesses.AfterTransactionCompletion(success); + + return InvalidateCachesAsync(cancellationToken); + } + catch (Exception ex) + { + return Task.FromException(ex); + } } - private partial class AfterTransactionCompletionProcessQueue + + private async Task InvalidateCachesAsync(CancellationToken cancellationToken) { - - public async Task AfterTransactionCompletionAsync(bool success, CancellationToken cancellationToken) + cancellationToken.ThrowIfCancellationRequested(); + if (session.Factory.Settings.IsQueryCacheEnabled) { - cancellationToken.ThrowIfCancellationRequested(); - int size = processes.Count; - - for (int i = 0; i < size; i++) - { - try - { - AfterTransactionCompletionProcessDelegate process = processes[i]; - process(success); - } - catch (CacheException e) - { - log.Error(e, "could not release a cache lock"); - // continue loop - } - catch (Exception e) - { - throw new AssertionFailure("Unable to perform AfterTransactionCompletion callback", e); - } - } - processes.Clear(); - - if (session.Factory.Settings.IsQueryCacheEnabled) - { - await (session.Factory.UpdateTimestampsCache.InvalidateAsync(querySpacesToInvalidate.ToArray(), cancellationToken)).ConfigureAwait(false); - } - querySpacesToInvalidate.Clear(); + await (session.Factory.UpdateTimestampsCache.InvalidateAsync(executedSpaces, cancellationToken)).ConfigureAwait(false); } + + executedSpaces.Clear(); } } } diff --git a/src/NHibernate/Async/Engine/Query/NativeSQLQueryPlan.cs b/src/NHibernate/Async/Engine/Query/NativeSQLQueryPlan.cs index 690fdc8af01..8e0aa8630a6 100644 --- a/src/NHibernate/Async/Engine/Query/NativeSQLQueryPlan.cs +++ b/src/NHibernate/Async/Engine/Query/NativeSQLQueryPlan.cs @@ -43,7 +43,7 @@ private async Task CoordinateSharedCacheCleanupAsync(ISessionImplementor session if (session.IsEventSource) { - await (((IEventSource)session).ActionQueue.AddActionAsync(action, cancellationToken)).ConfigureAwait(false); + ((IEventSource)session).ActionQueue.AddAction(action); } } diff --git a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs index 1016b79807b..b52b21c19de 100644 --- a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs +++ b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs @@ -43,7 +43,7 @@ protected virtual async Task CoordinateSharedCacheCleanupAsync(ISessionImplement if (session.IsEventSource) { - await (((IEventSource)session).ActionQueue.AddActionAsync(action, cancellationToken)).ConfigureAwait(false); + ((IEventSource)session).ActionQueue.AddAction(action); } } diff --git a/src/NHibernate/Cache/UpdateTimestampsCache.cs b/src/NHibernate/Cache/UpdateTimestampsCache.cs index 5af4365299c..450ea3ce469 100644 --- a/src/NHibernate/Cache/UpdateTimestampsCache.cs +++ b/src/NHibernate/Cache/UpdateTimestampsCache.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Runtime.CompilerServices; using NHibernate.Cfg; @@ -20,7 +21,7 @@ public partial class UpdateTimestampsCache private readonly string regionName = typeof(UpdateTimestampsCache).Name; - public void Clear() + public virtual void Clear() { updateTimestamps.Clear(); } @@ -33,34 +34,50 @@ public UpdateTimestampsCache(Settings settings, IDictionary prop updateTimestamps = settings.CacheProvider.BuildCache(regionName, props); } - [MethodImpl(MethodImplOptions.Synchronized)] + //Since v5.1 + [Obsolete("Please use PreInvalidate(IReadOnlyCollection) instead.")] public void PreInvalidate(object[] spaces) + { + //Only for backwards compatibility. + PreInvalidate(spaces.OfType().ToList()); + } + + [MethodImpl(MethodImplOptions.Synchronized)] + public virtual void PreInvalidate(IReadOnlyCollection spaces) { //TODO: to handle concurrent writes correctly, this should return a Lock to the client long ts = updateTimestamps.NextTimestamp() + updateTimestamps.Timeout; - for (int i = 0; i < spaces.Length; i++) + foreach (var space in spaces) { - updateTimestamps.Put(spaces[i], ts); + updateTimestamps.Put(space, ts); } + //TODO: return new Lock(ts); } - /// - [MethodImpl(MethodImplOptions.Synchronized)] + //Since v5.1 + [Obsolete("Please use PreInvalidate(IReadOnlyCollection) instead.")] public void Invalidate(object[] spaces) + { + //Only for backwards compatibility. + Invalidate(spaces.OfType().ToList()); + } + + [MethodImpl(MethodImplOptions.Synchronized)] + public virtual void Invalidate(IReadOnlyCollection spaces) { //TODO: to handle concurrent writes correctly, the client should pass in a Lock long ts = updateTimestamps.NextTimestamp(); //TODO: if lock.getTimestamp().equals(ts) - for (int i = 0; i < spaces.Length; i++) + foreach (var space in spaces) { - log.Debug("Invalidating space [{0}]", spaces[i]); - updateTimestamps.Put(spaces[i], ts); + log.Debug("Invalidating space [{0}]", space); + updateTimestamps.Put(space, ts); } } [MethodImpl(MethodImplOptions.Synchronized)] - public bool IsUpToDate(ISet spaces, long timestamp /* H2.1 has Long here */) + public virtual bool IsUpToDate(ISet spaces, long timestamp /* H2.1 has Long here */) { foreach (string space in spaces) { @@ -95,7 +112,7 @@ public bool IsUpToDate(ISet spaces, long timestamp /* H2.1 has Long here return true; } - public void Destroy() + public virtual void Destroy() { try { diff --git a/src/NHibernate/Engine/ActionQueue.cs b/src/NHibernate/Engine/ActionQueue.cs index 24bce5c7dda..d4d8344000a 100644 --- a/src/NHibernate/Engine/ActionQueue.cs +++ b/src/NHibernate/Engine/ActionQueue.cs @@ -3,7 +3,8 @@ using System.Collections.Generic; using System.Linq; using System.Text; - +using System.Threading; +using System.Threading.Tasks; using NHibernate.Action; using NHibernate.Cache; using NHibernate.Type; @@ -42,6 +43,7 @@ public partial class ActionQueue private readonly AfterTransactionCompletionProcessQueue afterTransactionProcesses; private readonly BeforeTransactionCompletionProcessQueue beforeTransactionProcesses; + private readonly HashSet executedSpaces; public ActionQueue(ISessionImplementor session) { @@ -54,8 +56,10 @@ public ActionQueue(ISessionImplementor session) collectionUpdates = new List(InitQueueListSize); collectionRemovals = new List(InitQueueListSize); - afterTransactionProcesses = new AfterTransactionCompletionProcessQueue(session); - beforeTransactionProcesses = new BeforeTransactionCompletionProcessQueue(session); + afterTransactionProcesses = new AfterTransactionCompletionProcessQueue(); + beforeTransactionProcesses = new BeforeTransactionCompletionProcessQueue(); + + executedSpaces = new HashSet(); } public virtual void Clear() @@ -108,7 +112,26 @@ public void AddAction(BulkOperationCleanupAction cleanupAction) { RegisterCleanupActions(cleanupAction); } - + + //Since v5.1 + [Obsolete("This method is no longer executed asynchronously and will be removed in a next major version.")] + public Task AddActionAsync(BulkOperationCleanupAction cleanupAction, CancellationToken cancellationToken=default(CancellationToken)) + { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + try + { + AddAction(cleanupAction); + return Task.CompletedTask; + } + catch (Exception e) + { + return Task.FromException(e); + } + } + public void RegisterProcess(AfterTransactionCompletionProcessDelegate process) { afterTransactionProcesses.Register(process); @@ -125,14 +148,36 @@ private void ExecuteActions(IList list) // It will then fail here due to list being modified. (Some previous code was dodging the // trouble with a for loop which was not failing provided the list was not getting smaller. // But then it was clearing it without having executed added actions (if any), ...) + foreach (IExecutable executable in list) - Execute(executable); - + { + InnerExecute(executable); + } list.Clear(); session.Batcher.ExecuteBatch(); } + private void PreInvalidateCaches() + { + if (session.Factory.Settings.IsQueryCacheEnabled) + { + session.Factory.UpdateTimestampsCache.PreInvalidate(executedSpaces); + } + } + public void Execute(IExecutable executable) + { + try + { + InnerExecute(executable); + } + finally + { + PreInvalidateCaches(); + } + } + + private void InnerExecute(IExecutable executable) { try { @@ -140,19 +185,17 @@ public void Execute(IExecutable executable) } finally { + if (executable.PropertySpaces != null) + { + executedSpaces.UnionWith(executable.PropertySpaces); + } RegisterCleanupActions(executable); } } - + private void RegisterCleanupActions(IExecutable executable) { beforeTransactionProcesses.Register(executable.BeforeTransactionCompletionProcess); - if (session.Factory.Settings.IsQueryCacheEnabled) - { - string[] spaces = executable.PropertySpaces; - afterTransactionProcesses.AddSpacesToInvalidate(spaces); - session.Factory.UpdateTimestampsCache.PreInvalidate(spaces); - } afterTransactionProcesses.Register(executable.AfterTransactionCompletionProcess); } @@ -161,7 +204,14 @@ private void RegisterCleanupActions(IExecutable executable) /// public void ExecuteInserts() { - ExecuteActions(insertions); + try + { + ExecuteActions(insertions); + } + finally + { + PreInvalidateCaches(); + } } /// @@ -169,15 +219,22 @@ public void ExecuteInserts() /// public void ExecuteActions() { - ExecuteActions(insertions); - ExecuteActions(updates); - ExecuteActions(collectionRemovals); - ExecuteActions(collectionUpdates); - ExecuteActions(collectionCreations); - ExecuteActions(deletions); + try + { + ExecuteActions(insertions); + ExecuteActions(updates); + ExecuteActions(collectionRemovals); + ExecuteActions(collectionUpdates); + ExecuteActions(collectionCreations); + ExecuteActions(deletions); + } + finally + { + PreInvalidateCaches(); + } } - private void PrepareActions(IList queue) + private static void PrepareActions(IList queue) { foreach (IExecutable executable in queue) executable.BeforeExecutions(); @@ -200,7 +257,7 @@ public void BeforeTransactionCompletion() { beforeTransactionProcesses.BeforeTransactionCompletion(); } - + /// /// Performs cleanup of any held cache softlocks. /// @@ -208,8 +265,20 @@ public void BeforeTransactionCompletion() public void AfterTransactionCompletion(bool success) { afterTransactionProcesses.AfterTransactionCompletion(success); + + InvalidateCaches(); } - + + private void InvalidateCaches() + { + if (session.Factory.Settings.IsQueryCacheEnabled) + { + session.Factory.UpdateTimestampsCache.Invalidate(executedSpaces); + } + + executedSpaces.Clear(); + } + /// /// Check whether the given tables/query-spaces are to be executed against /// given the currently queued actions. @@ -319,7 +388,7 @@ public void SortActions() private void SortInsertActions() { new InsertActionSorter(this).Sort(); - } + } public IList CloneDeletions() { @@ -385,19 +454,13 @@ public override string ToString() [Serializable] private class BeforeTransactionCompletionProcessQueue { - private ISessionImplementor session; - private IList processes = new List(); + private List processes = new List(); public bool HasActions { get { return processes.Count > 0; } } - public BeforeTransactionCompletionProcessQueue(ISessionImplementor session) - { - this.session = session; - } - public void Register(BeforeTransactionCompletionProcessDelegate process) { if (process == null) @@ -417,9 +480,9 @@ public void BeforeTransactionCompletion() BeforeTransactionCompletionProcessDelegate process = processes[i]; process(); } - catch (HibernateException e) + catch (HibernateException) { - throw e; + throw; } catch (Exception e) { @@ -431,39 +494,15 @@ public void BeforeTransactionCompletion() } [Serializable] - private partial class AfterTransactionCompletionProcessQueue + private class AfterTransactionCompletionProcessQueue { - private ISessionImplementor session; - private HashSet querySpacesToInvalidate = new HashSet(); - private IList processes = new List(InitQueueListSize * 3); + private List processes = new List(InitQueueListSize * 3); public bool HasActions { get { return processes.Count > 0; } } - - public AfterTransactionCompletionProcessQueue(ISessionImplementor session) - { - this.session = session; - } - - public void AddSpacesToInvalidate(string[] spaces) - { - if (spaces == null) - { - return; - } - for (int i = 0, max = spaces.Length; i < max; i++) - { - this.AddSpaceToInvalidate(spaces[i]); - } - } - - public void AddSpaceToInvalidate(string space) - { - querySpacesToInvalidate.Add(space); - } - + public void Register(AfterTransactionCompletionProcessDelegate process) { if (process == null) @@ -495,12 +534,6 @@ public void AfterTransactionCompletion(bool success) } } processes.Clear(); - - if (session.Factory.Settings.IsQueryCacheEnabled) - { - session.Factory.UpdateTimestampsCache.Invalidate(querySpacesToInvalidate.ToArray()); - } - querySpacesToInvalidate.Clear(); } } From c4eb6f4c40f5748f18ba10aee418d17508579980 Mon Sep 17 00:00:00 2001 From: Roman Artiukhin Date: Sun, 10 Dec 2017 17:01:41 +0530 Subject: [PATCH 18/32] Reuse the same generic EmptyMapClass instance across the project (#1477) --- src/NHibernate.Test/Async/Hql/Ast/HqlFixture.cs | 2 +- .../BulkManipulation/BaseFixture.cs | 2 +- src/NHibernate.Test/Hql/Ast/BaseFixture.cs | 2 +- src/NHibernate.Test/Hql/Ast/HqlFixture.cs | 2 +- .../NHSpecificTest/NH1849/Fixture.cs | 2 +- .../NH2031/HqlModFuctionForMsSqlTest.cs | 2 +- .../Cfg/MappingSchema/AbstractDecoratable.cs | 2 +- src/NHibernate/Cfg/XmlHbmBinding/Binder.cs | 2 +- .../Cfg/XmlHbmBinding/ResultSetMappingBinder.cs | 2 +- src/NHibernate/Engine/JoinSequence.cs | 2 +- src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs | 2 +- src/NHibernate/Impl/SessionFactoryImpl.cs | 6 +++--- src/NHibernate/Impl/SqlQueryImpl.cs | 4 ++-- src/NHibernate/Impl/StatelessSessionImpl.cs | 2 +- .../Loader/AbstractEntityJoinWalker.cs | 2 +- .../Loader/Collection/OneToManyJoinWalker.cs | 2 +- src/NHibernate/Loader/DefaultEntityAliases.cs | 4 ++-- .../Loader/Entity/CascadeEntityJoinWalker.cs | 4 ++-- .../Loader/Entity/CascadeEntityLoader.cs | 2 +- src/NHibernate/Loader/Entity/EntityJoinWalker.cs | 2 +- .../Loader/GeneratedCollectionAliases.cs | 2 +- .../Collection/AbstractCollectionPersister.cs | 2 +- .../Persister/Entity/AbstractEntityPersister.cs | 4 ++-- src/NHibernate/Util/CollectionHelper.cs | 16 ++++++++++++++++ 24 files changed, 45 insertions(+), 29 deletions(-) diff --git a/src/NHibernate.Test/Async/Hql/Ast/HqlFixture.cs b/src/NHibernate.Test/Async/Hql/Ast/HqlFixture.cs index d1075716ed2..3a0c9a92244 100644 --- a/src/NHibernate.Test/Async/Hql/Ast/HqlFixture.cs +++ b/src/NHibernate.Test/Async/Hql/Ast/HqlFixture.cs @@ -33,7 +33,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected HQLQueryPlan CreateQueryPlan(string hql, bool scalar) { - return new QueryExpressionPlan(new StringQueryExpression(hql), scalar, new CollectionHelper.EmptyMapClass(), Sfi); + return new QueryExpressionPlan(new StringQueryExpression(hql), scalar, CollectionHelper.EmptyDictionary(), Sfi); } protected HQLQueryPlan CreateQueryPlan(string hql) diff --git a/src/NHibernate.Test/BulkManipulation/BaseFixture.cs b/src/NHibernate.Test/BulkManipulation/BaseFixture.cs index f72930fec06..2817e549991 100644 --- a/src/NHibernate.Test/BulkManipulation/BaseFixture.cs +++ b/src/NHibernate.Test/BulkManipulation/BaseFixture.cs @@ -7,7 +7,7 @@ namespace NHibernate.Test.BulkManipulation { public class BaseFixture: TestCase { - private readonly IDictionary emptyfilters = new CollectionHelper.EmptyMapClass(); + private readonly IDictionary emptyfilters = CollectionHelper.EmptyDictionary(); #region Overrides of TestCase diff --git a/src/NHibernate.Test/Hql/Ast/BaseFixture.cs b/src/NHibernate.Test/Hql/Ast/BaseFixture.cs index bcdcae76106..1f2d0d6b18c 100644 --- a/src/NHibernate.Test/Hql/Ast/BaseFixture.cs +++ b/src/NHibernate.Test/Hql/Ast/BaseFixture.cs @@ -7,7 +7,7 @@ namespace NHibernate.Test.Hql.Ast { public class BaseFixture: TestCase { - private readonly IDictionary emptyfilters = new CollectionHelper.EmptyMapClass(); + private readonly IDictionary emptyfilters = CollectionHelper.EmptyDictionary(); #region Overrides of TestCase diff --git a/src/NHibernate.Test/Hql/Ast/HqlFixture.cs b/src/NHibernate.Test/Hql/Ast/HqlFixture.cs index 900c7d9d3f7..fea98840262 100644 --- a/src/NHibernate.Test/Hql/Ast/HqlFixture.cs +++ b/src/NHibernate.Test/Hql/Ast/HqlFixture.cs @@ -22,7 +22,7 @@ protected override bool AppliesTo(Dialect.Dialect dialect) protected HQLQueryPlan CreateQueryPlan(string hql, bool scalar) { - return new QueryExpressionPlan(new StringQueryExpression(hql), scalar, new CollectionHelper.EmptyMapClass(), Sfi); + return new QueryExpressionPlan(new StringQueryExpression(hql), scalar, CollectionHelper.EmptyDictionary(), Sfi); } protected HQLQueryPlan CreateQueryPlan(string hql) diff --git a/src/NHibernate.Test/NHSpecificTest/NH1849/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1849/Fixture.cs index 6feb4958736..88eac03b442 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1849/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1849/Fixture.cs @@ -46,7 +46,7 @@ public void ExecutesCustomSqlFunctionContains() { string hql = @"from Customer c where contains(c.Name, :smth)"; - HQLQueryPlan plan = new QueryExpressionPlan(new StringQueryExpression(hql), false, new CollectionHelper.EmptyMapClass(), Sfi); + HQLQueryPlan plan = new QueryExpressionPlan(new StringQueryExpression(hql), false, CollectionHelper.EmptyDictionary(), Sfi); Assert.AreEqual(1, plan.ParameterMetadata.NamedParameterNames.Count); Assert.AreEqual(1, plan.QuerySpaces.Count); diff --git a/src/NHibernate.Test/NHSpecificTest/NH2031/HqlModFuctionForMsSqlTest.cs b/src/NHibernate.Test/NHSpecificTest/NH2031/HqlModFuctionForMsSqlTest.cs index 93e8c46a582..6fb2ab5f0cb 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2031/HqlModFuctionForMsSqlTest.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2031/HqlModFuctionForMsSqlTest.cs @@ -28,7 +28,7 @@ public void TheModuleOperationShouldAddParenthesisToAvoidWrongSentence() public string GetSql(string query) { - var qt = new QueryTranslatorImpl(null, new HqlParseEngine(query, false, Sfi).Parse(), new CollectionHelper.EmptyMapClass(), Sfi); + var qt = new QueryTranslatorImpl(null, new HqlParseEngine(query, false, Sfi).Parse(), CollectionHelper.EmptyDictionary(), Sfi); qt.Compile(null, false); return qt.SQLString; } diff --git a/src/NHibernate/Cfg/MappingSchema/AbstractDecoratable.cs b/src/NHibernate/Cfg/MappingSchema/AbstractDecoratable.cs index 7fef721560d..cc9897ce37f 100644 --- a/src/NHibernate/Cfg/MappingSchema/AbstractDecoratable.cs +++ b/src/NHibernate/Cfg/MappingSchema/AbstractDecoratable.cs @@ -9,7 +9,7 @@ namespace NHibernate.Cfg.MappingSchema [Serializable] public abstract class AbstractDecoratable : IDecoratable { - private static readonly IDictionary EmptyMetaData = new CollectionHelper.EmptyMapClass(); + private static readonly IDictionary EmptyMetaData = CollectionHelper.EmptyDictionary(); [NonSerialized] [XmlIgnore] diff --git a/src/NHibernate/Cfg/XmlHbmBinding/Binder.cs b/src/NHibernate/Cfg/XmlHbmBinding/Binder.cs index 424c2b4b65f..c51b815cd8b 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/Binder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/Binder.cs @@ -13,7 +13,7 @@ public abstract class Binder protected static readonly INHibernateLogger log = NHibernateLogger.For(typeof (Binder)); protected static readonly IDictionary EmptyMeta = - new CollectionHelper.EmptyMapClass(); + CollectionHelper.EmptyDictionary(); protected readonly Mappings mappings; diff --git a/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs index 7a54042464e..f85fd971216 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs @@ -309,7 +309,7 @@ private IDictionary BindPropertyResults(string alias, HbmRetur { newPropertyResults[entry.Key] = entry.Value; } - return newPropertyResults.Count == 0 ? (IDictionary)new CollectionHelper.EmptyMapClass() : newPropertyResults; + return newPropertyResults.Count == 0 ? (IDictionary)CollectionHelper.EmptyDictionary() : newPropertyResults; } private static List GetResultColumns(HbmReturnProperty returnPropertySchema) diff --git a/src/NHibernate/Engine/JoinSequence.cs b/src/NHibernate/Engine/JoinSequence.cs index 1b9c28a2960..5036b97ea48 100644 --- a/src/NHibernate/Engine/JoinSequence.cs +++ b/src/NHibernate/Engine/JoinSequence.cs @@ -128,7 +128,7 @@ public JoinSequence AddJoin(IAssociationType associationType, string alias, Join public JoinFragment ToJoinFragment() { - return ToJoinFragment(new CollectionHelper.EmptyMapClass(), true); + return ToJoinFragment(CollectionHelper.EmptyDictionary(), true); } public JoinFragment ToJoinFragment(IDictionary enabledFilters, bool includeExtraJoins) diff --git a/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs b/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs index e61542b62ee..b3084afcb21 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.cs @@ -393,7 +393,7 @@ private void PostProcessDML(IRestrictableStatement statement) if (persister.DiscriminatorType != null) { new SyntheticAndFactory(this) - .AddDiscriminatorWhereFragment(statement, persister, new CollectionHelper.EmptyMapClass(), fromElement.TableAlias); + .AddDiscriminatorWhereFragment(statement, persister, CollectionHelper.EmptyDictionary(), fromElement.TableAlias); } } diff --git a/src/NHibernate/Impl/SessionFactoryImpl.cs b/src/NHibernate/Impl/SessionFactoryImpl.cs index bea503c6817..9673f0de23a 100644 --- a/src/NHibernate/Impl/SessionFactoryImpl.cs +++ b/src/NHibernate/Impl/SessionFactoryImpl.cs @@ -616,7 +616,7 @@ public string GetIdentifierPropertyName(string className) public IType[] GetReturnTypes(String queryString) { return - queryPlanCache.GetHQLQueryPlan(queryString.ToQueryExpression(), false, new CollectionHelper.EmptyMapClass()). + queryPlanCache.GetHQLQueryPlan(queryString.ToQueryExpression(), false, CollectionHelper.EmptyDictionary()). ReturnMetadata.ReturnTypes; } @@ -624,7 +624,7 @@ public IType[] GetReturnTypes(String queryString) public string[] GetReturnAliases(string queryString) { return - queryPlanCache.GetHQLQueryPlan(queryString.ToQueryExpression(), false, new CollectionHelper.EmptyMapClass()). + queryPlanCache.GetHQLQueryPlan(queryString.ToQueryExpression(), false, CollectionHelper.EmptyDictionary()). ReturnMetadata.ReturnAliases; } @@ -1163,7 +1163,7 @@ private IDictionary CheckNamedQueries() { log.Debug("Checking named query: {0}", queryName); //TODO: BUG! this currently fails for named queries for non-POJO entities - queryPlanCache.GetHQLQueryPlan(qd.QueryString.ToQueryExpression(), false, new CollectionHelper.EmptyMapClass()); + queryPlanCache.GetHQLQueryPlan(qd.QueryString.ToQueryExpression(), false, CollectionHelper.EmptyDictionary()); } catch (QueryException e) { diff --git a/src/NHibernate/Impl/SqlQueryImpl.cs b/src/NHibernate/Impl/SqlQueryImpl.cs index bccccd52688..43bb2544500 100644 --- a/src/NHibernate/Impl/SqlQueryImpl.cs +++ b/src/NHibernate/Impl/SqlQueryImpl.cs @@ -93,7 +93,7 @@ protected internal override IDictionary LockModes get { //we never need to apply locks to the SQL - return new CollectionHelper.EmptyMapClass(); + return CollectionHelper.EmptyDictionary(); } } @@ -236,7 +236,7 @@ public ISQLQuery AddJoin(string alias, string path, LockMode lockMode) string ownerAlias = path.Substring(0, loc); string role = path.Substring(loc + 1); queryReturns.Add( - new NativeSQLQueryJoinReturn(alias, ownerAlias, role, new CollectionHelper.EmptyMapClass(), lockMode)); + new NativeSQLQueryJoinReturn(alias, ownerAlias, role, CollectionHelper.EmptyDictionary(), lockMode)); return this; } diff --git a/src/NHibernate/Impl/StatelessSessionImpl.cs b/src/NHibernate/Impl/StatelessSessionImpl.cs index 3f3d9326639..7127f8f786f 100644 --- a/src/NHibernate/Impl/StatelessSessionImpl.cs +++ b/src/NHibernate/Impl/StatelessSessionImpl.cs @@ -288,7 +288,7 @@ public override IType GetFilterParameterType(string filterParameterName) public override IDictionary EnabledFilters { - get { return new CollectionHelper.EmptyMapClass(); } + get { return CollectionHelper.EmptyDictionary(); } } public override IQueryTranslator[] GetQueries(IQueryExpression query, bool scalar) diff --git a/src/NHibernate/Loader/AbstractEntityJoinWalker.cs b/src/NHibernate/Loader/AbstractEntityJoinWalker.cs index 7e192cf27aa..96123b59e40 100644 --- a/src/NHibernate/Loader/AbstractEntityJoinWalker.cs +++ b/src/NHibernate/Loader/AbstractEntityJoinWalker.cs @@ -33,7 +33,7 @@ protected virtual void InitAll(SqlString whereString, SqlString orderByString, L IList allAssociations = new List(associations); allAssociations.Add( new OuterJoinableAssociation(persister.EntityType, null, null, alias, JoinType.LeftOuterJoin, null, Factory, - new CollectionHelper.EmptyMapClass())); + CollectionHelper.EmptyDictionary())); InitPersisters(allAssociations, lockMode); InitStatementString(whereString, orderByString, lockMode); diff --git a/src/NHibernate/Loader/Collection/OneToManyJoinWalker.cs b/src/NHibernate/Loader/Collection/OneToManyJoinWalker.cs index c37b9063f89..ffdd220f1f1 100644 --- a/src/NHibernate/Loader/Collection/OneToManyJoinWalker.cs +++ b/src/NHibernate/Loader/Collection/OneToManyJoinWalker.cs @@ -38,7 +38,7 @@ public OneToManyJoinWalker(IQueryableCollection oneToManyPersister, int batchSiz IList allAssociations = new List(associations); allAssociations.Add( new OuterJoinableAssociation(oneToManyPersister.CollectionType, null, null, alias, JoinType.LeftOuterJoin, null, Factory, - new CollectionHelper.EmptyMapClass())); + CollectionHelper.EmptyDictionary())); InitPersisters(allAssociations, LockMode.None); InitStatementString(elementPersister, alias, batchSize, subquery); diff --git a/src/NHibernate/Loader/DefaultEntityAliases.cs b/src/NHibernate/Loader/DefaultEntityAliases.cs index f8b6ae402da..a2c38dd8f5e 100644 --- a/src/NHibernate/Loader/DefaultEntityAliases.cs +++ b/src/NHibernate/Loader/DefaultEntityAliases.cs @@ -19,7 +19,7 @@ public class DefaultEntityAliases : IEntityAliases private readonly IDictionary userProvidedAliases; public DefaultEntityAliases(ILoadable persister, string suffix) - : this(new CollectionHelper.EmptyMapClass(), persister, suffix) {} + : this(CollectionHelper.EmptyDictionary(), persister, suffix) {} /// /// Calculate and cache select-clause suffixes. @@ -147,4 +147,4 @@ private static void Intern(string[] strings) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Loader/Entity/CascadeEntityJoinWalker.cs b/src/NHibernate/Loader/Entity/CascadeEntityJoinWalker.cs index 51d6fbb5043..27c60a156e7 100644 --- a/src/NHibernate/Loader/Entity/CascadeEntityJoinWalker.cs +++ b/src/NHibernate/Loader/Entity/CascadeEntityJoinWalker.cs @@ -12,12 +12,12 @@ public class CascadeEntityJoinWalker : AbstractEntityJoinWalker public CascadeEntityJoinWalker(IOuterJoinLoadable persister, CascadingAction action, ISessionFactoryImplementor factory) - : base(persister, factory, new CollectionHelper.EmptyMapClass()) + : base(persister, factory, CollectionHelper.EmptyDictionary()) { cascadeAction = action; SqlStringBuilder whereCondition = WhereString(Alias, persister.IdentifierColumnNames, 1) //include the discriminator and class-level where, but not filters - .Add(persister.FilterFragment(Alias, new CollectionHelper.EmptyMapClass())); + .Add(persister.FilterFragment(Alias, CollectionHelper.EmptyDictionary())); InitAll(whereCondition.ToSqlString(), SqlString.Empty, LockMode.Read); } diff --git a/src/NHibernate/Loader/Entity/CascadeEntityLoader.cs b/src/NHibernate/Loader/Entity/CascadeEntityLoader.cs index d9ee4581c6f..a30bf394100 100644 --- a/src/NHibernate/Loader/Entity/CascadeEntityLoader.cs +++ b/src/NHibernate/Loader/Entity/CascadeEntityLoader.cs @@ -7,7 +7,7 @@ namespace NHibernate.Loader.Entity public class CascadeEntityLoader : AbstractEntityLoader { public CascadeEntityLoader(IOuterJoinLoadable persister, CascadingAction action, ISessionFactoryImplementor factory) - : base(persister, persister.IdentifierType, factory, new CollectionHelper.EmptyMapClass()) + : base(persister, persister.IdentifierType, factory, CollectionHelper.EmptyDictionary()) { JoinWalker walker = new CascadeEntityJoinWalker(persister, action, factory); InitFromWalker(walker); diff --git a/src/NHibernate/Loader/Entity/EntityJoinWalker.cs b/src/NHibernate/Loader/Entity/EntityJoinWalker.cs index cb77598376a..9f8ea3b983e 100644 --- a/src/NHibernate/Loader/Entity/EntityJoinWalker.cs +++ b/src/NHibernate/Loader/Entity/EntityJoinWalker.cs @@ -23,7 +23,7 @@ public EntityJoinWalker(IOuterJoinLoadable persister, string[] uniqueKey, int ba SqlStringBuilder whereCondition = WhereString(Alias, uniqueKey, batchSize) //include the discriminator and class-level where, but not filters - .Add(persister.FilterFragment(Alias, new CollectionHelper.EmptyMapClass())); + .Add(persister.FilterFragment(Alias, CollectionHelper.EmptyDictionary())); InitAll(whereCondition.ToSqlString(), SqlString.Empty, lockMode); } diff --git a/src/NHibernate/Loader/GeneratedCollectionAliases.cs b/src/NHibernate/Loader/GeneratedCollectionAliases.cs index 2252f8efdda..e42f631c070 100644 --- a/src/NHibernate/Loader/GeneratedCollectionAliases.cs +++ b/src/NHibernate/Loader/GeneratedCollectionAliases.cs @@ -37,7 +37,7 @@ public GeneratedCollectionAliases(IDictionary userProvidedAlia } public GeneratedCollectionAliases(ICollectionPersister persister, string str) - : this(new CollectionHelper.EmptyMapClass(), persister, str) {} + : this(CollectionHelper.EmptyDictionary(), persister, str) {} private string[] GetUserProvidedCompositeElementAliases(string[] defaultAliases) { diff --git a/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs b/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs index 1c3d000de8c..27da5e4bc11 100644 --- a/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs +++ b/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs @@ -559,7 +559,7 @@ public AbstractCollectionPersister(Mapping.Collection collection, ICacheConcurre public void PostInstantiate() { initializer = queryLoaderName == null - ? CreateCollectionInitializer(new CollectionHelper.EmptyMapClass()) + ? CreateCollectionInitializer(CollectionHelper.EmptyDictionary()) : new NamedQueryCollectionInitializer(queryLoaderName, this); } diff --git a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs index 922137b6745..2bdbc345cd2 100644 --- a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs +++ b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs @@ -2118,7 +2118,7 @@ protected void CreateUniqueKeyLoaders() //don't need filters for the static loaders uniqueKeyLoaders[propertyNames[i]] = CreateUniqueKeyLoader(propertyTypes[i], GetPropertyColumnNames(i), - new CollectionHelper.EmptyMapClass()); + CollectionHelper.EmptyDictionary()); } } } @@ -2197,7 +2197,7 @@ protected IUniqueEntityLoader CreateEntityLoader(LockMode lockMode, IDictionary< protected IUniqueEntityLoader CreateEntityLoader(LockMode lockMode) { - return CreateEntityLoader(lockMode, new CollectionHelper.EmptyMapClass()); + return CreateEntityLoader(lockMode, CollectionHelper.EmptyDictionary()); } protected bool Check(int rows, object id, int tableNumber, IExpectation expectation, DbCommand statement) diff --git a/src/NHibernate/Util/CollectionHelper.cs b/src/NHibernate/Util/CollectionHelper.cs index 261fa89fe1b..c8075f02dca 100644 --- a/src/NHibernate/Util/CollectionHelper.cs +++ b/src/NHibernate/Util/CollectionHelper.cs @@ -214,6 +214,12 @@ public IEnumerator GetEnumerator() public static readonly IEnumerable EmptyEnumerable = new EmptyEnumerableClass(); public static readonly IDictionary EmptyMap = new EmptyMapClass(); + + public static IDictionary EmptyDictionary() + { + return EmptyMapClass.Instance; + } + public static readonly ICollection EmptyCollection = EmptyMap; // Since v5 [Obsolete("It has no more usages in NHibernate and will be removed in a future version.")] @@ -463,8 +469,18 @@ public object Current [Serializable] public class EmptyMapClass : IDictionary { +#pragma warning disable 618 // Constructor is obsolete, to be switched to non-obsolete but private. + internal static readonly IDictionary Instance = new EmptyMapClass(); +#pragma warning restore 618 + private static readonly EmptyEnumerator emptyEnumerator = new EmptyEnumerator(); + // Since v5.1. To be switched to private. + [Obsolete("Please use CollectionHelper.EmptyDictionary() instead.")] + public EmptyMapClass() + { + } + #region IDictionary Members public bool ContainsKey(TKey key) From f6db50019fb87813edc6c298c0930b542c420820 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Mon, 11 Dec 2017 13:00:16 +0100 Subject: [PATCH 19/32] Reformated test case, to be squashed. --- .../NHSpecificTest/GH1226/Fixture.cs | 167 ++++++++++-------- .../NHSpecificTest/GH1226/Mappings.hbm.xml | 8 +- .../NHSpecificTest/GH1226/Model.cs | 24 +-- 3 files changed, 107 insertions(+), 92 deletions(-) diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs index 132e702676a..c944410a08c 100644 --- a/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs @@ -1,79 +1,92 @@ -namespace NHibernate.Test.NHSpecificTest.GH1226 +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.GH1226 { - using System; - using System.Collections.Generic; - using System.Linq; - using NUnit.Framework; - - [TestFixture] - public class Fixture : BugTestCase { - protected override void OnSetUp() { - base.OnSetUp(); - - using (var session = OpenSession()) { - using (var tx = session.BeginTransaction()) { - Bank bank = new Bank(); - bank.Id = Guid.NewGuid(); - bank.Code = "01234"; - session.Save(bank); - - Account account = new Account(); - account.Id = Guid.NewGuid(); - account.Bank = bank; - session.Save(account); - - Account account2 = new Account(); - account2.Bank = bank; - session.Save(account2); - - tx.Commit(); - } - } - } - - [Test] - public void BankShouldBeJoinFetched() { - using (var session = OpenSession()) { - bool wasStatisticsEnabled = session.SessionFactory.Statistics.IsStatisticsEnabled; - session.SessionFactory.Statistics.IsStatisticsEnabled = true; - - long statementCount; - - using (var tx = session.BeginTransaction()) { - // Bug only occurs if the Banks are already in the session cache. - IList preloadedBanks = session.CreateQuery("from Bank").List(); - - long countBeforeQuery = session.SessionFactory.Statistics.PrepareStatementCount; - - Console.WriteLine("Query: -------------------------------------------------------"); - - IList accounts = session.CreateQuery("from Account a left join fetch a.Bank").List(); - IList associatedBanks = accounts.Select(x => x.Bank).ToList(); - - long countAfterQuery = session.SessionFactory.Statistics.PrepareStatementCount; - statementCount = countAfterQuery - countBeforeQuery; - - Console.WriteLine("End ----------------------------------------------------------"); - - tx.Commit(); - } - - session.SessionFactory.Statistics.IsStatisticsEnabled = wasStatisticsEnabled; - - Assert.AreEqual(1, statementCount); - } - } - - protected override void OnTearDown() { - base.OnTearDown(); - - using (var session = OpenSession()) { - using (var tx = session.BeginTransaction()) { - session.Delete("from Account"); - session.Delete("from Bank"); - tx.Commit(); - } - } - } - } + [TestFixture] + public class Fixture : BugTestCase + { + protected override void OnSetUp() + { + base.OnSetUp(); + + using (var session = OpenSession()) + { + using (var tx = session.BeginTransaction()) + { + var bank = new Bank + { + Id = Guid.NewGuid(), + Code = "01234" + }; + session.Save(bank); + + var account = new Account + { + Id = Guid.NewGuid(), + Bank = bank + }; + session.Save(account); + + var account2 = new Account { Bank = bank }; + session.Save(account2); + + tx.Commit(); + } + } + } + + [Test] + public void BankShouldBeJoinFetched() + { + using (var session = OpenSession()) + { + var wasStatisticsEnabled = session.SessionFactory.Statistics.IsStatisticsEnabled; + session.SessionFactory.Statistics.IsStatisticsEnabled = true; + + long statementCount; + + using (var tx = session.BeginTransaction()) + { + // Bug only occurs if the Banks are already in the session cache. + var preloadedBanks = session.CreateQuery("from Bank").List(); + + var countBeforeQuery = session.SessionFactory.Statistics.PrepareStatementCount; + + Console.WriteLine("Query: -------------------------------------------------------"); + + var accounts = session.CreateQuery("from Account a left join fetch a.Bank").List(); + IList associatedBanks = accounts.Select(x => x.Bank).ToList(); + + var countAfterQuery = session.SessionFactory.Statistics.PrepareStatementCount; + statementCount = countAfterQuery - countBeforeQuery; + + Console.WriteLine("End ----------------------------------------------------------"); + + tx.Commit(); + } + + session.SessionFactory.Statistics.IsStatisticsEnabled = wasStatisticsEnabled; + + Assert.That(statementCount, Is.EqualTo(1)); + } + } + + protected override void OnTearDown() + { + base.OnTearDown(); + + using (var session = OpenSession()) + { + using (var tx = session.BeginTransaction()) + { + session.Delete("from Account"); + session.Delete("from Bank"); + tx.Commit(); + } + } + } + } } diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml b/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml index 412bf8a135f..04d537158c2 100644 --- a/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml @@ -4,15 +4,15 @@ namespace="NHibernate.Test.NHSpecificTest.GH1226"> - + - + - + - + diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs b/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs index 1bcae5da2c9..9b527a7d51d 100644 --- a/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs @@ -1,14 +1,16 @@ -namespace NHibernate.Test.NHSpecificTest.GH1226 -{ - using System; +using System; - public class Account { - public virtual Guid Id { get; set; } - public virtual Bank Bank { get; set; } - } +namespace NHibernate.Test.NHSpecificTest.GH1226 +{ + public class Account + { + public virtual Guid Id { get; set; } + public virtual Bank Bank { get; set; } + } - public class Bank { - public virtual Guid Id { get; set; } - public virtual string Code { get; set; } - } + public class Bank + { + public virtual Guid Id { get; set; } + public virtual string Code { get; set; } + } } From bcad8ba6d965f1b8f351761233703907cdbd2f9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Mon, 11 Dec 2017 14:16:20 +0100 Subject: [PATCH 20/32] Removed unneeded id assignation. --- src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs index c944410a08c..5d169497ada 100644 --- a/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs @@ -16,18 +16,10 @@ protected override void OnSetUp() { using (var tx = session.BeginTransaction()) { - var bank = new Bank - { - Id = Guid.NewGuid(), - Code = "01234" - }; + var bank = new Bank { Code = "01234" }; session.Save(bank); - var account = new Account - { - Id = Guid.NewGuid(), - Bank = bank - }; + var account = new Account { Bank = bank }; session.Save(account); var account2 = new Account { Bank = bank }; From f61fa8bd748d84dae3f9dd497e81c35e39fdd3a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Mon, 11 Dec 2017 14:45:32 +0100 Subject: [PATCH 21/32] Cache the unique key from entity property when the entity comes from cache. --- src/NHibernate/Loader/Loader.cs | 37 +++++++++------------------------ 1 file changed, 10 insertions(+), 27 deletions(-) diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index 3bc24fd745c..46aa4164740 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -973,33 +973,16 @@ private void InstanceAlreadyLoaded(DbDataReader rs, int i, IEntityPersister pers } } - //save object to EntityUnique cache - //see LoadFromResultSet func - IAssociationType[] ownerAssociationTypes = OwnerAssociationTypes; - if (ownerAssociationTypes != null && ownerAssociationTypes[i] != null) - { - string ukName = ownerAssociationTypes[i].RHSUniqueKeyPropertyName; - if (ukName != null) - { - int index = ((IUniqueKeyLoadable) persister).GetPropertyIndex(ukName); - IType type = persister.PropertyTypes[index]; - - object id = key.Identifier; - bool eagerPropertyFetch = IsEagerPropertyFetchEnabled(i); - ILoadable entityPersister = (ILoadable) persister; - string[][] cols = EntityAliases[i].SuffixedPropertyAliases; - - object[] values = entityPersister.Hydrate(rs, id, obj, entityPersister, cols, eagerPropertyFetch, session); - - // polymorphism not really handled completely correctly, - // perhaps...well, actually its ok, assuming that the - // entity name used in the lookup is the same as the - // the one used here, which it will be - - EntityUniqueKey euk = - new EntityUniqueKey(entityPersister.EntityName, ukName, type.SemiResolve(values[index], session, obj), type, session.Factory); - session.PersistenceContext.AddEntity(euk, obj); - } + // If it can be loaded from an association with a property ref, make + // sure it is also cached by its unique key. + var ukName = OwnerAssociationTypes?[i]?.RHSUniqueKeyPropertyName; + if (ukName != null) + { + var index = ((IUniqueKeyLoadable) persister).GetPropertyIndex(ukName); + var ukValue = persister.GetPropertyValue(obj, index); + var type = persister.PropertyTypes[index]; + var euk = new EntityUniqueKey(persister.EntityName, ukName, ukValue, type, session.Factory); + session.PersistenceContext.AddEntity(euk, obj); } } From 3921f6c58c7ff7d32105c6c73ca27326513b29cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Mon, 11 Dec 2017 19:28:53 +0100 Subject: [PATCH 22/32] Support entity not yet fully loaded and un-associated. --- src/NHibernate/Loader/Loader.cs | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index 46aa4164740..3ab15d6769b 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -973,17 +973,28 @@ private void InstanceAlreadyLoaded(DbDataReader rs, int i, IEntityPersister pers } } - // If it can be loaded from an association with a property ref, make + // #1226: If it is already loaded and can be loaded from an association with a property ref, make // sure it is also cached by its unique key. var ukName = OwnerAssociationTypes?[i]?.RHSUniqueKeyPropertyName; - if (ukName != null) - { - var index = ((IUniqueKeyLoadable) persister).GetPropertyIndex(ukName); - var ukValue = persister.GetPropertyValue(obj, index); - var type = persister.PropertyTypes[index]; - var euk = new EntityUniqueKey(persister.EntityName, ukName, ukValue, type, session.Factory); - session.PersistenceContext.AddEntity(euk, obj); - } + if (ukName == null) + return; + var index = ((IUniqueKeyLoadable) persister).GetPropertyIndex(ukName); + var ukValue = persister.GetPropertyValue(obj, index); + // ukValue can be null for two reasons: + // - Entity currently loading and not yet fully hydrated. In such case, it has already been handled by + // InstanceNotYetLoaded on a previous row, there is nothing more to do. This case could also be + // detected with "session.PersistenceContext.GetEntry(obj).Status == Status.Loading", but since there + // is a second case, just test for ukValue null. + // - Entity association is unset in session but not yet persisted, autoflush disabled: ignore. We are + // already in an error case: querying entities changed in session without flushing them before querying. + // So here it gets loaded as if it were still associated, but we do not have the key anymore in session: + // we cannot cache it, so long for the additionnal round-trip this will cause. (Do not fallback on + // reading the key in rs, this is stale data in regard to the session state.) + if (ukValue == null) + return; + var type = persister.PropertyTypes[index]; + var euk = new EntityUniqueKey(persister.EntityName, ukName, ukValue, type, session.Factory); + session.PersistenceContext.AddEntity(euk, obj); } /// From bc30eb4e63085952136277c923aecd9c88d81cd5 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Wed, 13 Dec 2017 13:04:29 +1300 Subject: [PATCH 23/32] Implement new StaticProxyFactoryFactory (#1451) - The factory generates high-efficient static proxies (no interceptor) --- .../Lightweight/BytecodeProviderFixture.cs | 2 +- .../Bytecode/AbstractBytecodeProvider.cs | 5 +- .../Bytecode/StaticProxyFactoryFactory.cs | 17 + .../DynamicProxy/DefaultProxyMethodBuilder.cs | 2 +- .../Proxy/DynamicProxy/ProxyFactory.cs | 2 +- src/NHibernate/Proxy/LiteLazyInitializer.cs | 17 + .../Proxy/NHibernateProxyBuilder.cs | 386 ++++++++++++++++++ .../Proxy/NHibernateProxyFactoryInfo.cs | 58 +++ .../Proxy/NHibernateProxyObjectReference.cs | 38 ++ src/NHibernate/Proxy/StaticProxyFactory.cs | 51 +++ 10 files changed, 573 insertions(+), 5 deletions(-) create mode 100644 src/NHibernate/Bytecode/StaticProxyFactoryFactory.cs create mode 100644 src/NHibernate/Proxy/LiteLazyInitializer.cs create mode 100644 src/NHibernate/Proxy/NHibernateProxyBuilder.cs create mode 100644 src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs create mode 100644 src/NHibernate/Proxy/NHibernateProxyObjectReference.cs create mode 100644 src/NHibernate/Proxy/StaticProxyFactory.cs diff --git a/src/NHibernate.Test/Bytecode/Lightweight/BytecodeProviderFixture.cs b/src/NHibernate.Test/Bytecode/Lightweight/BytecodeProviderFixture.cs index a721fc6f2e6..31d4ca7432e 100644 --- a/src/NHibernate.Test/Bytecode/Lightweight/BytecodeProviderFixture.cs +++ b/src/NHibernate.Test/Bytecode/Lightweight/BytecodeProviderFixture.cs @@ -14,7 +14,7 @@ public void NotConfiguredProxyFactoryFactory() { var bcp = new BytecodeProviderImpl(); IProxyFactoryFactory p = bcp.ProxyFactoryFactory; - Assert.That(p, Is.InstanceOf()); + Assert.That(p, Is.InstanceOf()); } [Test] diff --git a/src/NHibernate/Bytecode/AbstractBytecodeProvider.cs b/src/NHibernate/Bytecode/AbstractBytecodeProvider.cs index 16c7fcd6468..8c6f19a7da2 100644 --- a/src/NHibernate/Bytecode/AbstractBytecodeProvider.cs +++ b/src/NHibernate/Bytecode/AbstractBytecodeProvider.cs @@ -28,7 +28,8 @@ public virtual IProxyFactoryFactory ProxyFactoryFactory throw new HibernateByteCodeException("Failed to create an instance of '" + proxyFactoryFactory.FullName + "'!", e); } } - return new DefaultProxyFactoryFactory(); + + return StaticProxyFactoryFactory.Instance; } } @@ -116,4 +117,4 @@ public void SetCollectionTypeFactoryClass(System.Type type) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Bytecode/StaticProxyFactoryFactory.cs b/src/NHibernate/Bytecode/StaticProxyFactoryFactory.cs new file mode 100644 index 00000000000..d3d9a912f15 --- /dev/null +++ b/src/NHibernate/Bytecode/StaticProxyFactoryFactory.cs @@ -0,0 +1,17 @@ +using NHibernate.Proxy; + +namespace NHibernate.Bytecode +{ + public class StaticProxyFactoryFactory : IProxyFactoryFactory + { + internal static StaticProxyFactoryFactory Instance = new StaticProxyFactoryFactory(); + + public IProxyFactory BuildProxyFactory() => new StaticProxyFactory(); + + public IProxyValidator ProxyValidator => new DynProxyTypeValidator(); + + public bool IsInstrumented(System.Type entityClass) => true; + + public bool IsProxy(object entity) => entity is INHibernateProxy; + } +} diff --git a/src/NHibernate/Proxy/DynamicProxy/DefaultProxyMethodBuilder.cs b/src/NHibernate/Proxy/DynamicProxy/DefaultProxyMethodBuilder.cs index c999aa10086..0e8249d2466 100644 --- a/src/NHibernate/Proxy/DynamicProxy/DefaultProxyMethodBuilder.cs +++ b/src/NHibernate/Proxy/DynamicProxy/DefaultProxyMethodBuilder.cs @@ -30,7 +30,7 @@ public DefaultyProxyMethodBuilder(IMethodBodyEmitter emitter) public IMethodBodyEmitter MethodBodyEmitter { get; private set; } - private static MethodBuilder GenerateMethodSignature(string name, MethodInfo method, TypeBuilder typeBuilder) + internal static MethodBuilder GenerateMethodSignature(string name, MethodInfo method, TypeBuilder typeBuilder) { //TODO: Should we use attributes of base method? var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual; diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs index 4f35eb0d35a..a40adbb80bc 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs @@ -129,7 +129,7 @@ private TypeInfo CreateUncachedProxyType(System.Type baseType, IReadOnlyCollecti return proxyType; } - private IEnumerable GetProxiableMethods(System.Type type, IEnumerable interfaces) + internal static IEnumerable GetProxiableMethods(System.Type type, IEnumerable interfaces) { const BindingFlags candidateMethodsBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; return diff --git a/src/NHibernate/Proxy/LiteLazyInitializer.cs b/src/NHibernate/Proxy/LiteLazyInitializer.cs new file mode 100644 index 00000000000..9684bbed5f7 --- /dev/null +++ b/src/NHibernate/Proxy/LiteLazyInitializer.cs @@ -0,0 +1,17 @@ +using System; +using NHibernate.Engine; + +namespace NHibernate.Proxy +{ + [Serializable] + internal sealed class LiteLazyInitializer : AbstractLazyInitializer + { + internal LiteLazyInitializer(string entityName, object id, ISessionImplementor session, System.Type persistentClass) + : base(entityName, id, session) + { + PersistentClass = persistentClass; + } + + public override System.Type PersistentClass { get; } + } +} diff --git a/src/NHibernate/Proxy/NHibernateProxyBuilder.cs b/src/NHibernate/Proxy/NHibernateProxyBuilder.cs new file mode 100644 index 00000000000..bd3613c725a --- /dev/null +++ b/src/NHibernate/Proxy/NHibernateProxyBuilder.cs @@ -0,0 +1,386 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.Serialization; +using System.Security; +using NHibernate.Proxy.DynamicProxy; +using NHibernate.Type; +using NHibernate.Util; + +namespace NHibernate.Proxy +{ + internal class NHibernateProxyBuilder + { + private const MethodAttributes constructorAttributes = + MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName; + + private static readonly ConstructorInfo ObjectConstructor = typeof(object).GetConstructor(System.Type.EmptyTypes); + + private static readonly System.Type NHibernateProxyType = typeof(INHibernateProxy); + private static readonly PropertyInfo NHibernateProxyTypeLazyInitializerProperty = NHibernateProxyType.GetProperty(nameof(INHibernateProxy.HibernateLazyInitializer)); + private static readonly System.Type LazyInitializerType = typeof(ILazyInitializer); + private static readonly PropertyInfo LazyInitializerIdentifierProperty = LazyInitializerType.GetProperty(nameof(ILazyInitializer.Identifier)); + private static readonly MethodInfo LazyInitializerInitializeMethod = LazyInitializerType.GetMethod(nameof(ILazyInitializer.Initialize)); + private static readonly MethodInfo LazyInitializerGetImplementationMethod = LazyInitializerType.GetMethod(nameof(ILazyInitializer.GetImplementation), System.Type.EmptyTypes); + private static readonly IProxyAssemblyBuilder ProxyAssemblyBuilder = new DefaultProxyAssemblyBuilder(); + + private static readonly ConstructorInfo SecurityCriticalAttributeConstructor = typeof(SecurityCriticalAttribute).GetConstructor(System.Type.EmptyTypes); + private static readonly MethodInfo SerializableGetObjectDataMethod = typeof(ISerializable).GetMethod(nameof(ISerializable.GetObjectData)); + private static readonly MethodInfo SerializationInfoSetTypeMethod = ReflectHelper.GetMethod(si => si.SetType(null)); + + private readonly MethodInfo _getIdentifierMethod; + private readonly MethodInfo _setIdentifierMethod; + private readonly IAbstractComponentType _componentIdType; + private readonly bool _overridesEquals; + + public NHibernateProxyBuilder(MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod, IAbstractComponentType componentIdType, bool overridesEquals) + { + _getIdentifierMethod = getIdentifierMethod; + _setIdentifierMethod = setIdentifierMethod; + _componentIdType = componentIdType; + _overridesEquals = overridesEquals; + } + + public TypeInfo CreateProxyType(System.Type baseType, IReadOnlyCollection baseInterfaces) + { + var typeName = $"{baseType.Name}Proxy"; + var assemblyName = $"{typeName}Assembly"; + var moduleName = $"{typeName}Module"; + + var name = new AssemblyName(assemblyName); + + var assemblyBuilder = ProxyAssemblyBuilder.DefineDynamicAssembly(AppDomain.CurrentDomain, name); + var moduleBuilder = ProxyAssemblyBuilder.DefineDynamicModule(assemblyBuilder, moduleName); + + const TypeAttributes typeAttributes = TypeAttributes.AutoClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.BeforeFieldInit; + + var interfaces = new HashSet + { + // Add the ISerializable interface so that it can be implemented + typeof(ISerializable) + }; + interfaces.UnionWith(baseInterfaces); + interfaces.UnionWith(baseInterfaces.SelectMany(i => i.GetInterfaces())); + interfaces.UnionWith(baseType.GetInterfaces()); + + // Use the object as the base type + // since we're not inheriting from any class type + var parentType = baseType; + if (baseType.IsInterface) + { + parentType = typeof(object); + interfaces.Add(baseType); + } + + var typeBuilder = moduleBuilder.DefineType(typeName, typeAttributes, parentType, interfaces.ToArray()); + + var lazyInitializerField = typeBuilder.DefineField("__lazyInitializer", LazyInitializerType, FieldAttributes.Private); + var proxyInfoField = typeBuilder.DefineField("__proxyInfo", typeof(NHibernateProxyFactoryInfo), FieldAttributes.Private); + + ImplementConstructor(typeBuilder, parentType, lazyInitializerField, proxyInfoField); + + // Provide a custom implementation of ISerializable + // instead of redirecting it back to the interceptor + foreach (var method in ProxyFactory.GetProxiableMethods(baseType, interfaces.Except(new[] {typeof(ISerializable)}))) + { + CreateProxiedMethod(typeBuilder, method, lazyInitializerField); + } + + // Make the proxy serializable + var serializableConstructor = typeof(SerializableAttribute).GetConstructor(System.Type.EmptyTypes); + var customAttributeBuilder = new CustomAttributeBuilder(serializableConstructor, new object[0]); + typeBuilder.SetCustomAttribute(customAttributeBuilder); + + ImplementDeserializationConstructor(typeBuilder); + ImplementGetObjectData(typeBuilder, proxyInfoField, lazyInitializerField); + + var proxyType = typeBuilder.CreateTypeInfo(); + + ProxyAssemblyBuilder.Save(assemblyBuilder); + + return proxyType; + } + + private void CreateProxiedMethod(TypeBuilder typeBuilder, MethodInfo method, FieldInfo lazyInitializerField) + { + if (method == NHibernateProxyTypeLazyInitializerProperty.GetMethod) + { + ImplementGetLazyInitializer(typeBuilder, method, lazyInitializerField); + } + else if (method == _getIdentifierMethod) + { + ImplementGetIdentifier(typeBuilder, method, lazyInitializerField); + } + else if (method == _setIdentifierMethod) + { + ImplementSetIdentifier(typeBuilder, method, lazyInitializerField); + } + else if (!_overridesEquals && method.Name == "Equals" && method.GetBaseDefinition() == typeof(object).GetMethod("Equals", new[] {typeof(object)})) + { + //skip + } + else if (!_overridesEquals && method.Name == "GetHashCode" && method.GetBaseDefinition() == typeof(object).GetMethod("GetHashCode")) + { + //skip + } + else if (_componentIdType != null && _componentIdType.IsMethodOf(method)) + { + ImplementCallMethodOnEmbeddedComponentId(typeBuilder, method, lazyInitializerField); + } + else + { + ImplementCallMethodOnImplementation(typeBuilder, method, lazyInitializerField); + } + } + + private static void ImplementConstructor(TypeBuilder typeBuilder, System.Type parentType, FieldInfo lazyInitializerField, FieldInfo proxyInfoField) + { + var constructor = typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, new[] {LazyInitializerType, typeof(NHibernateProxyFactoryInfo)}); + + var baseConstructor = parentType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, System.Type.EmptyTypes, null); + + // if there is no default constructor, or the default constructor is private/internal, call System.Object constructor + // this works, but the generated assembly will fail PeVerify (cannot use in medium trust for example) + if (baseConstructor == null || baseConstructor.IsPrivate || baseConstructor.IsAssembly) + baseConstructor = ObjectConstructor; + + var IL = constructor.GetILGenerator(); + + constructor.SetImplementationFlags(MethodImplAttributes.IL | MethodImplAttributes.Managed); + + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Call, baseConstructor); + + // __lazyInitializer == lazyInitializer; + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldarg_1); + IL.Emit(OpCodes.Stfld, lazyInitializerField); + + // __proxyInfo == proxyInfo; + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldarg_2); + IL.Emit(OpCodes.Stfld, proxyInfoField); + + IL.Emit(OpCodes.Ret); + } + + private static void ImplementDeserializationConstructor(TypeBuilder typeBuilder) + { + var parameterTypes = new[] {typeof (SerializationInfo), typeof (StreamingContext)}; + var constructor = typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, parameterTypes); + constructor.SetImplementationFlags(MethodImplAttributes.IL | MethodImplAttributes.Managed); + + var IL = constructor.GetILGenerator(); + //Everything is done in NHibernateProxyObjectReference, so just return data. + IL.Emit(OpCodes.Ret); + } + + private static void ImplementGetObjectData(TypeBuilder typeBuilder, FieldInfo proxyInfoField, FieldInfo lazyInitializerField) + { + const MethodAttributes attributes = + MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual; + + var parameterTypes = new[] {typeof (SerializationInfo), typeof (StreamingContext)}; + + var methodBuilder = typeBuilder.DefineMethod("GetObjectData", attributes, typeof (void), parameterTypes); + methodBuilder.SetImplementationFlags(MethodImplAttributes.IL | MethodImplAttributes.Managed); + methodBuilder.SetCustomAttribute(new CustomAttributeBuilder(SecurityCriticalAttributeConstructor, Array.Empty())); + + var IL = methodBuilder.GetILGenerator(); + //LocalBuilder proxyBaseType = IL.DeclareLocal(typeof(Type)); + + // info.SetType(typeof(NHibernateProxyObjectReference)); + IL.Emit(OpCodes.Ldarg_1); + IL.Emit(OpCodes.Ldtoken, typeof (NHibernateProxyObjectReference)); + IL.Emit(OpCodes.Call, ReflectionCache.TypeMethods.GetTypeFromHandle); + IL.Emit(OpCodes.Callvirt, SerializationInfoSetTypeMethod); + + // (new NHibernateProxyObjectReference(this.__proxyInfo, this.__lazyInitializer.Identifier)).GetObjectData(info, context); + //this.__proxyInfo + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, proxyInfoField); + + //this.__lazyInitializer.Identifier + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, lazyInitializerField); + IL.Emit(OpCodes.Callvirt, LazyInitializerIdentifierProperty.GetMethod); + + var constructor = typeof(NHibernateProxyObjectReference).GetConstructor( + new[] + { + typeof(NHibernateProxyFactoryInfo), + typeof(object), + }); + IL.Emit(OpCodes.Newobj, constructor); + + IL.Emit(OpCodes.Ldarg_1); + IL.Emit(OpCodes.Ldarg_2); + IL.Emit(OpCodes.Callvirt, SerializableGetObjectDataMethod); + + IL.Emit(OpCodes.Ret); + + typeBuilder.DefineMethodOverride(methodBuilder, SerializableGetObjectDataMethod); + } + + private static void ImplementGetLazyInitializer(TypeBuilder typeBuilder, MethodInfo method, FieldInfo lazyInitializerField) + { + // get { return this.__lazyInitializer; } + + const MethodAttributes attributes = + MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.HideBySig | + MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.Virtual; + + var getMethod = typeBuilder.DefineMethod($"{NHibernateProxyType.FullName}.get_{nameof(INHibernateProxy.HibernateLazyInitializer)}", attributes, CallingConventions.HasThis, LazyInitializerType, System.Type.EmptyTypes); + getMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL); + + var IL = getMethod.GetILGenerator(); + + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, lazyInitializerField); + IL.Emit(OpCodes.Ret); + + typeBuilder.DefineMethodOverride(getMethod, method); + } + + private static void ImplementGetIdentifier(TypeBuilder typeBuilder, MethodInfo method, FieldInfo lazyInitializerField) + { + /* + get + { + if (this.__lazyInitializer == null) + return base.get_(); + return ()this.__lazyInitializer.Identifier; + } + */ + var methodOverride = DefaultyProxyMethodBuilder.GenerateMethodSignature(method.Name, method, typeBuilder); + + var IL = methodOverride.GetILGenerator(); + + EmitCallBaseIfLazyInitializerIsNull(IL, method, lazyInitializerField); + + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, lazyInitializerField); + IL.Emit(OpCodes.Callvirt, LazyInitializerIdentifierProperty.GetMethod); + IL.Emit(OpCodes.Unbox_Any, method.ReturnType); + IL.Emit(OpCodes.Ret); + + typeBuilder.DefineMethodOverride(methodOverride, method); + } + + private static void ImplementSetIdentifier(TypeBuilder typeBuilder, MethodInfo method, FieldInfo lazyInitializerField) + { + /* + set + { + if (this.__lazyInitializer == null) + return base.set_(value); + this.__lazyInitializer.Initialize(); + this.__lazyInitializer.Identifier = value; + this.__lazyInitializer.GetImplementation(). = value; + } + */ + var propertyType = method.GetParameters()[0].ParameterType; + var methodOverride = DefaultyProxyMethodBuilder.GenerateMethodSignature(method.Name, method, typeBuilder); + var IL = methodOverride.GetILGenerator(); + + EmitCallBaseIfLazyInitializerIsNull(IL, method, lazyInitializerField); + + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, lazyInitializerField); + IL.Emit(OpCodes.Callvirt, LazyInitializerInitializeMethod); + + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, lazyInitializerField); + IL.Emit(OpCodes.Ldarg_1); + if (propertyType.IsValueType) + IL.Emit(OpCodes.Box, propertyType); + IL.Emit(OpCodes.Callvirt, LazyInitializerIdentifierProperty.SetMethod); + + EmitCallImplementation(IL, method, lazyInitializerField); + + IL.Emit(OpCodes.Ret); + + typeBuilder.DefineMethodOverride(methodOverride, method); + } + + private static void ImplementCallMethodOnEmbeddedComponentId(TypeBuilder typeBuilder, MethodInfo method, FieldInfo lazyInitializerField) + { + /* + if (this.__lazyInitializer == null) + return base.(args..); + this.__lazyInitializer.Identifier.(args..); + */ + var methodOverride = DefaultyProxyMethodBuilder.GenerateMethodSignature(method.Name, method, typeBuilder); + + var IL = methodOverride.GetILGenerator(); + + EmitCallBaseIfLazyInitializerIsNull(IL, method, lazyInitializerField); + + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, lazyInitializerField); + IL.Emit(OpCodes.Callvirt, LazyInitializerIdentifierProperty.GetMethod); + IL.Emit(OpCodes.Unbox_Any, method.DeclaringType); + EmitCallMethod(IL, OpCodes.Callvirt, method); + IL.Emit(OpCodes.Ret); + + typeBuilder.DefineMethodOverride(methodOverride, method); + } + + private static void ImplementCallMethodOnImplementation(TypeBuilder typeBuilder, MethodInfo method, FieldInfo lazyInitializerField) + { + /* + if (this.__lazyInitializer == null) + return base.(args..); + return this.__lazyInitializer.GetImplementation().(args..) + */ + var methodOverride = DefaultyProxyMethodBuilder.GenerateMethodSignature(method.Name, method, typeBuilder); + + var IL = methodOverride.GetILGenerator(); + + EmitCallBaseIfLazyInitializerIsNull(IL, method, lazyInitializerField); + + EmitCallImplementation(IL, method, lazyInitializerField); + IL.Emit(OpCodes.Ret); + + typeBuilder.DefineMethodOverride(methodOverride, method); + } + + private static void EmitCallBaseIfLazyInitializerIsNull(ILGenerator IL, MethodInfo method, FieldInfo lazyInitializerField) + { + //if (this.__lazyInitializer == null) + // return base.(args..) + + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, lazyInitializerField); + var skipBaseCall = IL.DefineLabel(); + + IL.Emit(OpCodes.Ldnull); + IL.Emit(OpCodes.Bne_Un, skipBaseCall); + + IL.Emit(OpCodes.Ldarg_0); + EmitCallMethod(IL, OpCodes.Call, method); + IL.Emit(OpCodes.Ret); + + IL.MarkLabel(skipBaseCall); + } + + private static void EmitCallMethod(ILGenerator IL, OpCode opCode, MethodInfo method) + { + for (var i = 0; i < method.GetParameters().Length; i++) + IL.Emit(OpCodes.Ldarg_S, (sbyte) (1 + i)); + IL.Emit(opCode, method); + } + + private static void EmitCallImplementation(ILGenerator IL, MethodInfo method, FieldInfo lazyInitializerField) + { + //(()this.__lazyInitializer.GetImplementation()).(args..); + IL.Emit(OpCodes.Ldarg_0); + IL.Emit(OpCodes.Ldfld, lazyInitializerField); + IL.Emit(OpCodes.Callvirt, LazyInitializerGetImplementationMethod); + IL.Emit(OpCodes.Unbox_Any, method.DeclaringType); + EmitCallMethod(IL, OpCodes.Callvirt, method); + } + } +} diff --git a/src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs b/src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs new file mode 100644 index 00000000000..065c3705729 --- /dev/null +++ b/src/NHibernate/Proxy/NHibernateProxyFactoryInfo.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.Serialization; +using System.Security; +using NHibernate.Type; + +namespace NHibernate.Proxy +{ + [Serializable] + public sealed class NHibernateProxyFactoryInfo : ISerializable + { + private readonly string _entityName; + private readonly System.Type _persistentClass; + private readonly System.Type[] _interfaces; + private readonly MethodInfo _getIdentifierMethod; + private readonly MethodInfo _setIdentifierMethod; + private readonly IAbstractComponentType _componentIdType; + + internal NHibernateProxyFactoryInfo(string entityName, System.Type persistentClass, System.Type[] interfaces, MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod, IAbstractComponentType componentIdType) + { + _entityName = entityName; + _persistentClass = persistentClass; + _interfaces = interfaces; + _getIdentifierMethod = getIdentifierMethod; + _setIdentifierMethod = setIdentifierMethod; + _componentIdType = componentIdType; + } + + public IProxyFactory CreateProxyFactory() + { + var factory = new StaticProxyFactory(); + factory.PostInstantiate(_entityName, _persistentClass, new HashSet(_interfaces), _getIdentifierMethod, _setIdentifierMethod, _componentIdType); + return factory; + } + + private NHibernateProxyFactoryInfo(SerializationInfo info, StreamingContext context) + { + _entityName = (string) info.GetValue(nameof(_entityName), typeof(string)); + _persistentClass = (System.Type) info.GetValue(nameof(_persistentClass), typeof(System.Type)); + _interfaces = (System.Type[]) info.GetValue(nameof(_interfaces), typeof(System.Type[])); + _getIdentifierMethod = (MethodInfo) info.GetValue(nameof(_getIdentifierMethod), typeof(MethodInfo)); + _setIdentifierMethod = (MethodInfo) info.GetValue(nameof(_setIdentifierMethod), typeof(MethodInfo)); + _componentIdType = (IAbstractComponentType) info.GetValue(nameof(_componentIdType), typeof(IAbstractComponentType)); + } + + [SecurityCritical] + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue(nameof(_entityName), _entityName); + info.AddValue(nameof(_persistentClass), _persistentClass); + info.AddValue(nameof(_interfaces), _interfaces); + info.AddValue(nameof(_getIdentifierMethod), _getIdentifierMethod); + info.AddValue(nameof(_setIdentifierMethod), _setIdentifierMethod); + info.AddValue(nameof(_componentIdType), _componentIdType); + } + } +} diff --git a/src/NHibernate/Proxy/NHibernateProxyObjectReference.cs b/src/NHibernate/Proxy/NHibernateProxyObjectReference.cs new file mode 100644 index 00000000000..9878bc5bc21 --- /dev/null +++ b/src/NHibernate/Proxy/NHibernateProxyObjectReference.cs @@ -0,0 +1,38 @@ +using System; +using System.Runtime.Serialization; +using System.Security; + +namespace NHibernate.Proxy +{ + [Serializable] + public sealed class NHibernateProxyObjectReference : IObjectReference, ISerializable + { + private readonly NHibernateProxyFactoryInfo _proxyFactoryInfo; + private readonly object _identifier; + + public NHibernateProxyObjectReference(NHibernateProxyFactoryInfo proxyFactoryInfo, object identifier) + { + _proxyFactoryInfo = proxyFactoryInfo; + _identifier = identifier; + } + + private NHibernateProxyObjectReference(SerializationInfo info, StreamingContext context) + { + _proxyFactoryInfo = (NHibernateProxyFactoryInfo) info.GetValue(nameof(_proxyFactoryInfo), typeof(NHibernateProxyFactoryInfo)); + _identifier = info.GetValue(nameof(_identifier), typeof(object)); + } + + [SecurityCritical] + public object GetRealObject(StreamingContext context) + { + return _proxyFactoryInfo.CreateProxyFactory().GetProxy(_identifier, null); + } + + [SecurityCritical] + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + info.AddValue(nameof(_proxyFactoryInfo), _proxyFactoryInfo); + info.AddValue(nameof(_identifier), _identifier); + } + } +} diff --git a/src/NHibernate/Proxy/StaticProxyFactory.cs b/src/NHibernate/Proxy/StaticProxyFactory.cs new file mode 100644 index 00000000000..d053a93abd2 --- /dev/null +++ b/src/NHibernate/Proxy/StaticProxyFactory.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Concurrent; +using System.Linq.Expressions; +using NHibernate.Engine; +using NHibernate.Intercept; +using NHibernate.Proxy.DynamicProxy; + +namespace NHibernate.Proxy +{ + public sealed class StaticProxyFactory : AbstractProxyFactory + { + private static readonly ConcurrentDictionary> + Cache = new ConcurrentDictionary>(); + + private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(StaticProxyFactory)); + + public override INHibernateProxy GetProxy(object id, ISessionImplementor session) + { + try + { + var cacheEntry = new ProxyCacheEntry(IsClassProxy ? PersistentClass : typeof(object), Interfaces); + var proxyActivator = Cache.GetOrAdd(cacheEntry, pke => CreateProxyActivator(pke)); + return proxyActivator( + new LiteLazyInitializer(EntityName, id, session, PersistentClass), + new NHibernateProxyFactoryInfo(EntityName, PersistentClass, Interfaces, GetIdentifierMethod, SetIdentifierMethod, ComponentIdType)); + } + catch (Exception ex) + { + Log.Error(ex, "Creating a proxy instance failed"); + throw new HibernateException("Creating a proxy instance failed", ex); + } + } + + private Func CreateProxyActivator(ProxyCacheEntry pke) + { + var proxyBuilder = new NHibernateProxyBuilder(GetIdentifierMethod, SetIdentifierMethod, ComponentIdType, OverridesEquals); + var type = proxyBuilder.CreateProxyType(pke.BaseType, pke.Interfaces); + var ctor = type.GetConstructor(new[] {typeof(ILazyInitializer), typeof(NHibernateProxyFactoryInfo)}); + var li = Expression.Parameter(typeof(ILazyInitializer)); + var pf = Expression.Parameter(typeof(NHibernateProxyFactoryInfo)); + return Expression.Lambda>(Expression.New(ctor, li, pf), li, pf).Compile(); + } + + public override object GetFieldInterceptionProxy(object instanceToWrap) + { + var factory = new ProxyFactory(); + var interceptor = new DefaultDynamicLazyFieldInterceptor(); + return factory.CreateProxy(PersistentClass, interceptor, typeof(IFieldInterceptorAccessor)); + } + } +} From 906c6920ba3557791d8856eabf3237d35502673d Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Tue, 12 Dec 2017 17:05:34 -0700 Subject: [PATCH 24/32] Fix regression caused by logging refactoring (#1479) - Add tests for legacy logger - Don't split global state for logging. Fixes #1478 --- .../Logging/LoggerProviderTest.cs | 46 +++++++++++++++++-- src/NHibernate/Logging.cs | 20 +++++++- src/NHibernate/Logging.obsolete.cs | 27 ++++------- 3 files changed, 70 insertions(+), 23 deletions(-) diff --git a/src/NHibernate.Test/Logging/LoggerProviderTest.cs b/src/NHibernate.Test/Logging/LoggerProviderTest.cs index 75c01b6148d..ae3b852f9d4 100644 --- a/src/NHibernate.Test/Logging/LoggerProviderTest.cs +++ b/src/NHibernate.Test/Logging/LoggerProviderTest.cs @@ -1,3 +1,4 @@ +using System; using NUnit.Framework; namespace NHibernate.Test.Logging @@ -12,17 +13,29 @@ public void LoggerProviderCanCreateLoggers() Assert.That(NHibernateLogger.For(typeof (LoggerProviderTest)), Is.Not.Null); } + [Test, Obsolete] + public void LoggerProviderCanCreateLoggers_Obsolete() + { + Assert.That(LoggerProvider.LoggerFor("pizza"), Is.Not.Null); + Assert.That(LoggerProvider.LoggerFor(typeof (LoggerProviderTest)), Is.Not.Null); + } + [Test] public void WhenNotConfiguredAndLog4NetExistsThenUseLog4NetFactory() { -#pragma warning disable 618 - Assert.That(NHibernateLogger.For("pizza"), Is.Not.InstanceOf()); -#pragma warning restore 618 - // NoLoggingNHibernateLogger is internal Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.Not.EqualTo("NoLoggingNHibernateLogger")); } + [Test, Obsolete] + public void WhenNotConfiguredAndLog4NetExistsThenUseLog4NetFactory_Obsolete() + { + Assert.That(LoggerProvider.LoggerFor("pizza"), Is.Not.InstanceOf()); + + // works because this is the legacy provider with a legacy logger + Assert.That(LoggerProvider.LoggerFor("pizza"), Is.InstanceOf()); + } + [Test, Explicit("Changes global state.")] public void WhenConfiguredAsNullThenNoLoggingFactoryIsUsed() { @@ -31,5 +44,30 @@ public void WhenConfiguredAsNullThenNoLoggingFactoryIsUsed() // NoLoggingNHibernateLogger is internal Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.EqualTo("NoLoggingNHibernateLogger")); } + + [Test, Explicit("Changes global state."), Obsolete] + public void WhenConfiguredAsNullThenNoLoggingFactoryIsUsed_Obsolete() + { + NHibernateLogger.SetLoggersFactory(default(INHibernateLoggerFactory)); + + Assert.That(LoggerProvider.LoggerFor("pizza"), Is.InstanceOf()); + } + + [Test, Explicit("Changes global state."), Obsolete] + public void WhenNoLoggingFactoryIsUsedThenNoLoggingInternalLoggerIsReturned() + { + LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory()); + + Assert.That(LoggerProvider.LoggerFor("pizza"), Is.InstanceOf()); + } + + [Test, Explicit("Changes global state."), Obsolete] + public void WhenNoLoggingFactoryIsUsedThenNoLoggingNHibernateLoggerIsReturned() + { + LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory()); + + // NoLoggingNHibernateLogger is internal + Assert.That(NHibernateLogger.For("pizza").GetType().Name, Is.EqualTo("NoLoggingNHibernateLogger")); + } } } diff --git a/src/NHibernate/Logging.cs b/src/NHibernate/Logging.cs index 5d7cae37150..d0248bd57a3 100644 --- a/src/NHibernate/Logging.cs +++ b/src/NHibernate/Logging.cs @@ -52,6 +52,10 @@ public static class NHibernateLogger private const string nhibernateLoggerConfKey = "nhibernate-logger"; private static INHibernateLoggerFactory _loggerFactory; +#pragma warning disable 618 + internal static ILoggerFactory LegacyLoggerFactory { get; private set; } +#pragma warning restore 618 + static NHibernateLogger() { var nhibernateLoggerClass = GetNhibernateLoggerClass(); @@ -68,9 +72,21 @@ public static void SetLoggersFactory(INHibernateLoggerFactory loggerFactory) _loggerFactory = loggerFactory ?? new NoLoggingNHibernateLoggerFactory(); #pragma warning disable 618 - if (!(loggerFactory is LoggerProvider.LegacyLoggerFactoryAdaptor)) + // Also keep global state for obsolete logger + if (loggerFactory == null) + { + LegacyLoggerFactory = new NoLoggingLoggerFactory(); + } + else { - LoggerProvider.SetLoggersFactory(new LoggerProvider.ReverseLegacyLoggerFactoryAdaptor(loggerFactory)); + if (loggerFactory is LoggerProvider.LegacyLoggerFactoryAdaptor legacyAdaptor) + { + LegacyLoggerFactory = legacyAdaptor.Factory; + } + else + { + LegacyLoggerFactory = new LoggerProvider.ReverseLegacyLoggerFactoryAdaptor(loggerFactory); + } } #pragma warning restore 618 } diff --git a/src/NHibernate/Logging.obsolete.cs b/src/NHibernate/Logging.obsolete.cs index ff8f5f5be30..fa70325e399 100644 --- a/src/NHibernate/Logging.obsolete.cs +++ b/src/NHibernate/Logging.obsolete.cs @@ -82,54 +82,47 @@ public interface ILoggerFactory [Obsolete("Use NHibernateLogger instead.")] public class LoggerProvider { - private static ILoggerFactory _legacyLoggerFactory; - [Obsolete("Implement INHibernateLoggerFactory and use NHibernateLogger.SetLoggersFactory() instead")] public static void SetLoggersFactory(ILoggerFactory loggerFactory) { - _legacyLoggerFactory = loggerFactory ?? new NoLoggingLoggerFactory(); - - if (!(loggerFactory is ReverseLegacyLoggerFactoryAdaptor)) - { - var factory = loggerFactory == null || loggerFactory is NoLoggingLoggerFactory - ? null - : (INHibernateLoggerFactory) new LegacyLoggerFactoryAdaptor(loggerFactory); + var factory = (loggerFactory == null || loggerFactory is NoLoggingLoggerFactory) + ? null + : (INHibernateLoggerFactory) new LegacyLoggerFactoryAdaptor(loggerFactory); - NHibernateLogger.SetLoggersFactory(factory); - } + NHibernateLogger.SetLoggersFactory(factory); } [Obsolete("Use NHibernateLogger.For() instead.")] public static IInternalLogger LoggerFor(string keyName) { - return _legacyLoggerFactory.LoggerFor(keyName); + return NHibernateLogger.LegacyLoggerFactory.LoggerFor(keyName); } [Obsolete("Use NHibernateLogger.For() instead.")] public static IInternalLogger LoggerFor(System.Type type) { - return _legacyLoggerFactory.LoggerFor(type); + return NHibernateLogger.LegacyLoggerFactory.LoggerFor(type); } // Since 5.1 [Obsolete("Used only in Obsolete functions to thunk to INHibernateLoggerFactory")] internal class LegacyLoggerFactoryAdaptor : INHibernateLoggerFactory { - private readonly ILoggerFactory _factory; + internal ILoggerFactory Factory { get; } public LegacyLoggerFactoryAdaptor(ILoggerFactory factory) { - _factory = factory; + Factory = factory; } public INHibernateLogger LoggerFor(string keyName) { - return new NHibernateLoggerThunk(_factory.LoggerFor(keyName)); + return new NHibernateLoggerThunk(Factory.LoggerFor(keyName)); } public INHibernateLogger LoggerFor(System.Type type) { - return new NHibernateLoggerThunk(_factory.LoggerFor(type)); + return new NHibernateLoggerThunk(Factory.LoggerFor(type)); } } From c48b4fdc3008285b44ec855bdd03e00464b31012 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Wed, 13 Dec 2017 23:42:13 +1300 Subject: [PATCH 25/32] Add timeouts support to MultiCriteria Fixes #1403 --- .../Async/Impl/MultiCriteriaImpl.cs | 2 +- src/NHibernate/Async/Impl/MultiQueryImpl.cs | 2 +- src/NHibernate/IMultiCriteria.cs | 24 +++++++++++++++++++ src/NHibernate/Impl/MultiCriteriaImpl.cs | 12 +++++++++- src/NHibernate/Impl/MultiQueryImpl.cs | 6 ++--- 5 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs b/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs index 893d59a9d26..47514f9cdf0 100644 --- a/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs +++ b/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs @@ -151,7 +151,7 @@ private async Task GetResultsFromDatabaseAsync(IList results, CancellationToken try { - using (var reader = await (resultSetsCommand.GetReaderAsync(null, cancellationToken)).ConfigureAwait(false)) + using (var reader = await (resultSetsCommand.GetReaderAsync(_timeout, cancellationToken)).ConfigureAwait(false)) { var hydratedObjects = new List[loaders.Count]; List[] subselectResultKeys = new List[loaders.Count]; diff --git a/src/NHibernate/Async/Impl/MultiQueryImpl.cs b/src/NHibernate/Async/Impl/MultiQueryImpl.cs index 8a11f631a00..cd5918deae5 100644 --- a/src/NHibernate/Async/Impl/MultiQueryImpl.cs +++ b/src/NHibernate/Async/Impl/MultiQueryImpl.cs @@ -84,7 +84,7 @@ protected async Task> DoListAsync(CancellationToken cancellationTok try { - using (var reader = await (resultSetsCommand.GetReaderAsync(commandTimeout != RowSelection.NoValue ? commandTimeout : (int?)null, cancellationToken)).ConfigureAwait(false)) + using (var reader = await (resultSetsCommand.GetReaderAsync(_timeout, cancellationToken)).ConfigureAwait(false)) { if (log.IsDebugEnabled()) { diff --git a/src/NHibernate/IMultiCriteria.cs b/src/NHibernate/IMultiCriteria.cs index 42390a873ad..ba1aaa16744 100644 --- a/src/NHibernate/IMultiCriteria.cs +++ b/src/NHibernate/IMultiCriteria.cs @@ -1,5 +1,7 @@ +using System; using System.Collections; using NHibernate.Criterion; +using NHibernate.Impl; using NHibernate.Transform; namespace NHibernate @@ -154,4 +156,26 @@ public partial interface IMultiCriteria /// object GetResult(string key); } + + public static class MultiCriteriaExtensions + { + //6.0 TODO: Convert to interface method + /// + /// Set a timeout for the underlying ADO.NET query + /// + public static IMultiCriteria SetTimeout(this IMultiCriteria multiCriteria, int timeout) + { + if (multiCriteria == null) + { + throw new ArgumentNullException(nameof(multiCriteria)); + } + + if (multiCriteria is MultiCriteriaImpl impl) + { + return impl.SetTimeout(timeout); + } + + throw new NotSupportedException(multiCriteria.GetType() + " does not support SetTimeout"); + } + } } diff --git a/src/NHibernate/Impl/MultiCriteriaImpl.cs b/src/NHibernate/Impl/MultiCriteriaImpl.cs index af13d7ffeba..8fc62f5ea0c 100644 --- a/src/NHibernate/Impl/MultiCriteriaImpl.cs +++ b/src/NHibernate/Impl/MultiCriteriaImpl.cs @@ -35,6 +35,7 @@ public partial class MultiCriteriaImpl : IMultiCriteria private string cacheRegion; private IResultTransformer resultTransformer; private readonly IResultSetsCommand resultSetsCommand; + private int? _timeout; /// /// Initializes a new instance of the class. @@ -221,7 +222,7 @@ private void GetResultsFromDatabase(IList results) try { - using (var reader = resultSetsCommand.GetReader(null)) + using (var reader = resultSetsCommand.GetReader(_timeout)) { var hydratedObjects = new List[loaders.Count]; List[] subselectResultKeys = new List[loaders.Count]; @@ -474,5 +475,14 @@ private void ThrowIfKeyAlreadyExists(string key) if (criteriaResultPositions.ContainsKey(key)) throw new InvalidOperationException(String.Format("The key '{0}' already exists", key)); } + + /// + /// Set a timeout for the underlying ADO.NET query + /// + public IMultiCriteria SetTimeout(int timeout) + { + _timeout = timeout == RowSelection.NoValue ? (int?) null : timeout; + return this; + } } } diff --git a/src/NHibernate/Impl/MultiQueryImpl.cs b/src/NHibernate/Impl/MultiQueryImpl.cs index 5701c842576..9ebbaac972c 100644 --- a/src/NHibernate/Impl/MultiQueryImpl.cs +++ b/src/NHibernate/Impl/MultiQueryImpl.cs @@ -29,7 +29,7 @@ public partial class MultiQueryImpl : IMultiQuery private IList queryResults; private readonly Dictionary queryResultPositions = new Dictionary(); private string cacheRegion; - private int commandTimeout = RowSelection.NoValue; + private int? _timeout; private bool isCacheable; private readonly ISessionImplementor session; private IResultTransformer resultTransformer; @@ -64,7 +64,7 @@ public IMultiQuery SetForceCacheRefresh(bool cacheRefresh) public IMultiQuery SetTimeout(int timeout) { - commandTimeout = timeout; + _timeout = timeout == RowSelection.NoValue ? (int?) null : timeout; return this; } @@ -526,7 +526,7 @@ protected List DoList() try { - using (var reader = resultSetsCommand.GetReader(commandTimeout != RowSelection.NoValue ? commandTimeout : (int?)null)) + using (var reader = resultSetsCommand.GetReader(_timeout)) { if (log.IsDebugEnabled()) { From 6d8d5d953efd43fd722cbabff1a2d65edb9d26e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Wed, 13 Dec 2017 13:07:27 +0100 Subject: [PATCH 26/32] Fix default types (#1484) * Remove logic duplication for getting default NHibernate type for a CLR type. * Test all defaults for CLR type having many possibilities. * Clean-up. --- src/NHibernate.Test/NHibernateUtilTest.cs | 38 ++++++++++++++++------ src/NHibernate/Async/NHibernateUtil.cs | 9 ++---- src/NHibernate/NHibernateUtil.cs | 39 +++++------------------ src/NHibernate/Type/TypeFactory.cs | 9 ++++++ 4 files changed, 49 insertions(+), 46 deletions(-) diff --git a/src/NHibernate.Test/NHibernateUtilTest.cs b/src/NHibernate.Test/NHibernateUtilTest.cs index 438e9ef0e48..abb64f5db32 100644 --- a/src/NHibernate.Test/NHibernateUtilTest.cs +++ b/src/NHibernate.Test/NHibernateUtilTest.cs @@ -10,36 +10,56 @@ public class NHibernateUtilTest [Test] public void CanGuessTypeOfInt32ByValue() { - Assert.AreEqual(NHibernateUtil.Int32, NHibernateUtil.GuessType(15)); + Assert.That(NHibernateUtil.GuessType(15), Is.EqualTo(NHibernateUtil.Int32)); } [Test] public void CanGuessTypeOfInt32ByType() { - Assert.AreEqual(NHibernateUtil.Int32, - NHibernateUtil.GuessType(typeof(int))); + Assert.That(NHibernateUtil.GuessType(typeof(int)), Is.EqualTo(NHibernateUtil.Int32)); } [Test] public void CanGuessTypeOfNullableInt32ByType() { - Assert.AreEqual(NHibernateUtil.Int32, - NHibernateUtil.GuessType(typeof(int?))); + Assert.That(NHibernateUtil.GuessType(typeof(int?)), Is.EqualTo(NHibernateUtil.Int32)); } [Test] public void CanGuessTypeOfNullableInt32ByValue() { int? val = 15; - Assert.AreEqual(NHibernateUtil.Int32, - NHibernateUtil.GuessType(val)); + Assert.That(NHibernateUtil.GuessType(val), Is.EqualTo(NHibernateUtil.Int32)); } [Test] public void CanGuessTypeOfDateTime() { - Assert.AreEqual(NHibernateUtil.DateTime, - NHibernateUtil.GuessType(typeof(DateTime))); + Assert.That(NHibernateUtil.GuessType(typeof(DateTime)), Is.EqualTo(NHibernateUtil.DateTime)); + } + + [Test] + public void CanGuessTypeOfString() + { + Assert.That(NHibernateUtil.GuessType(typeof(string)), Is.EqualTo(NHibernateUtil.String)); + } + + [Test] + public void CanGuessTypeOfBoolean() + { + Assert.That(NHibernateUtil.GuessType(typeof(bool)), Is.EqualTo(NHibernateUtil.Boolean)); + } + + [Test] + public void CanGuessTypeOfDecimal() + { + Assert.That(NHibernateUtil.GuessType(typeof(decimal)), Is.EqualTo(NHibernateUtil.Decimal)); + } + + [Test] + public void CanGuessTypeOfTimeSpan() + { + Assert.That(NHibernateUtil.GuessType(typeof(TimeSpan)), Is.EqualTo(NHibernateUtil.TimeSpan)); } } } diff --git a/src/NHibernate/Async/NHibernateUtil.cs b/src/NHibernate/Async/NHibernateUtil.cs index 7b34ff511e3..84705659529 100644 --- a/src/NHibernate/Async/NHibernateUtil.cs +++ b/src/NHibernate/Async/NHibernateUtil.cs @@ -20,11 +20,8 @@ namespace NHibernate { - using System.Collections.Generic; - using System.Reflection; using System.Threading.Tasks; using System.Threading; - public static partial class NHibernateUtil { @@ -47,13 +44,13 @@ public static partial class NHibernateUtil { return Task.CompletedTask; } - else if (proxy.IsProxy()) + if (proxy.IsProxy()) { return ((INHibernateProxy)proxy).HibernateLazyInitializer.InitializeAsync(cancellationToken); } - else if (proxy is IPersistentCollection) + else if (proxy is IPersistentCollection coll) { - return ((IPersistentCollection)proxy).ForceInitializationAsync(cancellationToken); + return coll.ForceInitializationAsync(cancellationToken); } return Task.CompletedTask; } diff --git a/src/NHibernate/NHibernateUtil.cs b/src/NHibernate/NHibernateUtil.cs index 0ab72b190e1..1d51e3e7abd 100644 --- a/src/NHibernate/NHibernateUtil.cs +++ b/src/NHibernate/NHibernateUtil.cs @@ -10,9 +10,6 @@ namespace NHibernate { - using System.Collections.Generic; - using System.Reflection; - /// /// Provides access to the full range of NHibernate built-in types. /// IType instances may be used to bind values to query parameters. @@ -21,26 +18,6 @@ namespace NHibernate /// public static partial class NHibernateUtil { - static private readonly Dictionary clrTypeToNHibernateType = new Dictionary(); - - static NHibernateUtil() - { - FieldInfo[] fields = typeof(NHibernateUtil).GetFields(); - foreach (FieldInfo info in fields) - { - if (typeof(IType).IsAssignableFrom(info.FieldType) == false) - continue; - IType type = (IType)info.GetValue(null); - clrTypeToNHibernateType[type.ReturnedClass] = type; - } - - // There are multiple possibilites for boolean, strings and datetime. - // Override so that we use the most natural mapping. - clrTypeToNHibernateType[Boolean.ReturnedClass] = Boolean; - clrTypeToNHibernateType[String.ReturnedClass] = String; - clrTypeToNHibernateType[DateTime.ReturnedClass] = DateTime; - } - /// /// Guesses the IType of this object /// @@ -61,8 +38,8 @@ public static IType GuessType(System.Type type) { type = type.UnwrapIfNullable(); - IType value; - if (clrTypeToNHibernateType.TryGetValue(type, out value)) + var value = TypeFactory.GetDefaultTypeFor(type); + if (value != null) return value; if (type.IsEnum) @@ -73,7 +50,7 @@ public static IType GuessType(System.Type type) { return Custom(type); } - + return Entity(type); } @@ -401,13 +378,13 @@ public static void Initialize(object proxy) { return; } - else if (proxy.IsProxy()) + if (proxy.IsProxy()) { ((INHibernateProxy)proxy).HibernateLazyInitializer.Initialize(); } - else if (proxy is IPersistentCollection) + else if (proxy is IPersistentCollection coll) { - ((IPersistentCollection)proxy).ForceInitialization(); + coll.ForceInitialization(); } } @@ -533,7 +510,7 @@ public static void Close(IEnumerator enumerator) EnumerableImpl hibernateEnumerator = enumerator as EnumerableImpl; if (hibernateEnumerator == null) { - throw new ArgumentException("Not a NHibernate enumerator", "enumerator"); + throw new ArgumentException("Not a NHibernate enumerator", nameof(enumerator)); } hibernateEnumerator.Dispose(); } @@ -547,7 +524,7 @@ public static void Close(IEnumerable enumerable) EnumerableImpl hibernateEnumerable = enumerable as EnumerableImpl; if (hibernateEnumerable == null) { - throw new ArgumentException("Not a NHibernate enumerable", "enumerable"); + throw new ArgumentException("Not a NHibernate enumerable", nameof(enumerable)); } hibernateEnumerable.Dispose(); } diff --git a/src/NHibernate/Type/TypeFactory.cs b/src/NHibernate/Type/TypeFactory.cs index ed10f0fe3a8..f7972227640 100644 --- a/src/NHibernate/Type/TypeFactory.cs +++ b/src/NHibernate/Type/TypeFactory.cs @@ -613,6 +613,15 @@ public static IType HeuristicType(string typeName, IDictionary p return GetSerializableType(typeClass); } + /// + /// Get the current default NHibernate type for a .Net type. + /// + /// The .Net type for which to get the corresponding default NHibernate type. + /// The current default NHibernate type for a .Net type if any, otherwise . + public static IType GetDefaultTypeFor(System.Type type) + { + return typeByTypeOfName.TryGetValue(type.FullName, out var nhType) ? nhType : null; + } [MethodImpl(MethodImplOptions.Synchronized)] public static NullableType GetAnsiStringType(int length) From aada8001e6002acfab8b97896a2e85e760acb2e2 Mon Sep 17 00:00:00 2001 From: Roman Artiukhin Date: Fri, 15 Dec 2017 14:36:22 +0530 Subject: [PATCH 27/32] Refactored DefaultEntityAliases to avoid unnecessary calculations (#1482) --- src/NHibernate/Loader/DefaultEntityAliases.cs | 173 +++++++++--------- 1 file changed, 83 insertions(+), 90 deletions(-) diff --git a/src/NHibernate/Loader/DefaultEntityAliases.cs b/src/NHibernate/Loader/DefaultEntityAliases.cs index a2c38dd8f5e..8ff8a43e65f 100644 --- a/src/NHibernate/Loader/DefaultEntityAliases.cs +++ b/src/NHibernate/Loader/DefaultEntityAliases.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using NHibernate.Persister.Entity; -using NHibernate.Util; namespace NHibernate.Loader { @@ -10,48 +9,75 @@ namespace NHibernate.Loader /// public class DefaultEntityAliases : IEntityAliases { - private readonly string[] suffixedKeyColumns; - private readonly string[] suffixedVersionColumn; - private readonly string[][] suffixedPropertyColumns; - private readonly string suffixedDiscriminatorColumn; - private readonly string suffix; - private readonly string rowIdAlias; - private readonly IDictionary userProvidedAliases; + private readonly string _suffix; + private readonly IDictionary _userProvidedAliases; + private string _rowIdAlias; public DefaultEntityAliases(ILoadable persister, string suffix) - : this(CollectionHelper.EmptyDictionary(), persister, suffix) {} + : this(null, persister, suffix) + { + } /// - /// Calculate and cache select-clause suffixes. + /// Calculate and cache select-clause aliases. /// public DefaultEntityAliases(IDictionary userProvidedAliases, ILoadable persister, string suffix) { - this.suffix = suffix; - this.userProvidedAliases = userProvidedAliases; + _suffix = suffix; + _userProvidedAliases = userProvidedAliases?.Count > 0 ? userProvidedAliases : null; - string[] keyColumnsCandidates = GetUserProvidedAliases(persister.IdentifierPropertyName, null); - if (keyColumnsCandidates == null) - { - suffixedKeyColumns = GetUserProvidedAliases(EntityPersister.EntityID, GetIdentifierAliases(persister, suffix)); - } - else - { - suffixedKeyColumns = keyColumnsCandidates; - } - Intern(suffixedKeyColumns); + SuffixedKeyAliases = DetermineKeyAliases(persister); + SuffixedPropertyAliases = DeterminePropertyAliases(persister); + SuffixedDiscriminatorAlias = DetermineDiscriminatorAlias(persister); + + SuffixedVersionAliases = persister.IsVersioned ? SuffixedPropertyAliases[persister.VersionProperty] : null; + //rowIdAlias is generated on demand in property + } - suffixedPropertyColumns = GetSuffixedPropertyAliases(persister); - suffixedDiscriminatorColumn = - GetUserProvidedAlias(AbstractEntityPersister.EntityClass, GetDiscriminatorAlias(persister, suffix)); - if (persister.IsVersioned) + /// + /// Returns aliases for subclass persister + /// + public string[][] GetSuffixedPropertyAliases(ILoadable persister) + { + if (_userProvidedAliases == null) + return GetAllPropertyAliases(persister); + + var propertyNames = persister.PropertyNames; + var suffixedPropertyAliases = new string[propertyNames.Length][]; + for (var i = 0; i < propertyNames.Length; i++) { - suffixedVersionColumn = suffixedPropertyColumns[persister.VersionProperty]; + suffixedPropertyAliases[i] = + SafeGetUserProvidedAliases(propertyNames[i]) ?? + GetPropertyAliases(persister, i); } - else + + return suffixedPropertyAliases; + } + + public string[] SuffixedVersionAliases { get; } + + public string[][] SuffixedPropertyAliases { get; } + + public string SuffixedDiscriminatorAlias { get; } + + public string[] SuffixedKeyAliases { get; } + + // TODO: not visible to the user! + public string RowIdAlias => _rowIdAlias ?? (_rowIdAlias = Loadable.RowIdAlias + _suffix); + + /// + /// Returns default aliases for all the properties + /// + private string[][] GetAllPropertyAliases(ILoadable persister) + { + var propertyNames = persister.PropertyNames; + var suffixedPropertyAliases = new string[propertyNames.Length][]; + for (var i = 0; i < propertyNames.Length; i++) { - suffixedVersionColumn = null; + suffixedPropertyAliases[i] = GetPropertyAliases(persister, i); } - rowIdAlias = Loadable.RowIdAlias + suffix; // TODO: not visible to the user! + + return suffixedPropertyAliases; } protected virtual string GetDiscriminatorAlias(ILoadable persister, string suffix) @@ -66,85 +92,52 @@ protected virtual string[] GetIdentifierAliases(ILoadable persister, string suff protected virtual string[] GetPropertyAliases(ILoadable persister, int j) { - return persister.GetPropertyAliases(suffix, j); + return persister.GetPropertyAliases(_suffix, j); } - private string[] GetUserProvidedAliases(string propertyPath, string[] defaultAliases) + private string[] DetermineKeyAliases(ILoadable persister) { - string[] result = propertyPath == null ? null : GetUserProvidedAlias(propertyPath); - if (result == null) + if (_userProvidedAliases != null) { - return defaultAliases; - } - else - { - return result; + var result = SafeGetUserProvidedAliases(persister.IdentifierPropertyName) ?? + GetUserProvidedAliases(EntityPersister.EntityID); + + if (result != null) + return result; } - } - private string[] GetUserProvidedAlias(string propertyPath) - { - string[] result; - userProvidedAliases.TryGetValue(propertyPath, out result); - return result; + return GetIdentifierAliases(persister, _suffix); } - - private string GetUserProvidedAlias(string propertyPath, string defaultAlias) + + private string[][] DeterminePropertyAliases(ILoadable persister) { - string[] columns = propertyPath == null ? null : GetUserProvidedAlias(propertyPath); - if (columns == null) - { - return defaultAlias; - } - else - { - return columns[0]; - } + return GetSuffixedPropertyAliases(persister); } - - public string[][] GetSuffixedPropertyAliases(ILoadable persister) + + private string DetermineDiscriminatorAlias(ILoadable persister) { - int size = persister.PropertyNames.Length; - string[][] suffixedPropertyAliases = new string[size][]; - for (int j = 0; j < size; j++) + if (_userProvidedAliases != null) { - suffixedPropertyAliases[j] = GetUserProvidedAliases(persister.PropertyNames[j], GetPropertyAliases(persister, j)); - Intern(suffixedPropertyAliases[j]); + var columns = GetUserProvidedAliases(AbstractEntityPersister.EntityClass); + if (columns != null) + return columns[0]; } - return suffixedPropertyAliases; - } - public string[] SuffixedVersionAliases - { - get { return suffixedVersionColumn; } + return GetDiscriminatorAlias(persister, _suffix); } - - public string[][] SuffixedPropertyAliases + + private string[] SafeGetUserProvidedAliases(string propertyPath) { - get { return suffixedPropertyColumns; } - } + if (propertyPath == null) + return null; - public string SuffixedDiscriminatorAlias - { - get { return suffixedDiscriminatorColumn; } - } - - public string[] SuffixedKeyAliases - { - get { return suffixedKeyColumns; } + return GetUserProvidedAliases(propertyPath); } - public string RowIdAlias + private string[] GetUserProvidedAliases(string propertyPath) { - get { return rowIdAlias; } - } - - private static void Intern(string[] strings) - { - for (int i = 0; i < strings.Length; i++) - { - strings[i] = StringHelper.InternedIfPossible(strings[i]); - } + _userProvidedAliases.TryGetValue(propertyPath, out var result); + return result; } } } From 418d35aa18fac3d4d9b899e2bb9f4eeda0aa95d4 Mon Sep 17 00:00:00 2001 From: Alexander Zaytsev Date: Sat, 16 Dec 2017 23:07:18 +1300 Subject: [PATCH 28/32] Optimize empty arrays usages (#1490) --- .../Async/CustomPersister.cs | 1 + src/NHibernate.DomainModel/Baz.cs | 2 +- src/NHibernate.DomainModel/CustomPersister.cs | 5 +- .../Async/Component/Basic/ComponentTest.cs | 2 +- .../Async/DialectTest/DialectFixture.cs | 2 +- .../Events/PostEvents/PostUpdateFixture.cs | 11 +-- .../Async/ExceptionsTest/NullQueryTest.cs | 2 +- src/NHibernate.Test/Async/Legacy/FumTest.cs | 2 +- .../Async/LinqBulkManipulation/Fixture.cs | 6 +- .../IntegrationTests/NH2825/FixtureByCode.cs | 5 +- .../NHSpecificTest/EmptyMappingsFixture.cs | 2 +- .../Async/NHSpecificTest/NH1421/Fixture.cs | 2 +- .../Async/NHSpecificTest/NH2166/Fixture.cs | 2 +- .../NH4077/PostInsertFixture.cs | 2 +- .../NH4077/PostUpdateFixture.cs | 2 +- .../Async/NHSpecificTest/NH901/Fixture.cs | 3 +- .../SecondLevelCacheTest/InvalidationTests.cs | 1 - src/NHibernate.Test/Async/TestTestCase.cs | 2 +- .../TransactionNotificationFixture.cs | 5 +- .../Async/TypesTest/BinaryBlobTypeFixture.cs | 2 +- .../Async/TypesTest/BinaryTypeFixture.cs | 4 +- .../BulkManipulation/BaseFixture.cs | 5 +- .../DeleteOneToOneOrphansTest.cs | 5 +- .../Fk/Composite/DeleteOneToOneOrphansTest.cs | 3 +- .../DeleteOneToOneOrphansTest.cs | 3 +- .../DeleteOneToOneOrphansTest.cs | 3 +- .../DeleteOneToOneOrphansTest.cs | 3 +- .../DeleteOneToOneOrphansTest.cs | 3 +- .../Component/Basic/ComponentTest.cs | 2 +- .../Criteria/DetachedCriteriaSerializable.cs | 4 +- .../DialectTest/DialectFixture.cs | 2 +- .../Events/PostEvents/PostUpdateFixture.cs | 11 +-- .../ExceptionsTest/NullQueryTest.cs | 2 +- .../ExpressionTest/InExpressionFixture.cs | 2 +- src/NHibernate.Test/Hql/Ast/BaseFixture.cs | 5 +- src/NHibernate.Test/Legacy/FumTest.cs | 2 +- .../Linq/ParameterisedQueries.cs | 2 +- .../LinqBulkManipulation/Fixture.cs | 6 +- .../IntegrationTests/NH2825/FixtureByCode.cs | 7 +- ...ComponentWithBagOfNestedComponentsTests.cs | 2 +- .../NHSpecificTest/EmptyMappingsFixture.cs | 2 +- .../NHSpecificTest/NH1421/Fixture.cs | 4 +- .../NHSpecificTest/NH2166/Fixture.cs | 2 +- .../NHSpecificTest/NH2931/Fixture.cs | 5 +- .../NHSpecificTest/NH3954/EqualsFixture.cs | 2 +- .../NHSpecificTest/NH3956/Fixture.cs | 7 +- .../NH4077/PostInsertFixture.cs | 2 +- .../NH4077/PostUpdateFixture.cs | 2 +- .../NHSpecificTest/NH901/Fixture.cs | 3 +- .../QueryTest/DetachedQueryFixture.cs | 6 +- .../QueryTest/QueryParametersFixture.cs | 5 +- .../TransactionNotificationFixture.cs | 7 +- src/NHibernate.Test/TestCaseMappingByCode.cs | 5 +- src/NHibernate.Test/TestTestCase.cs | 2 +- .../TransactionNotificationFixture.cs | 5 +- .../ImplementationOfEqualityTests.cs | 2 +- .../TypesTest/BinaryBlobTypeFixture.cs | 2 +- .../TypesTest/BinaryTypeFixture.cs | 4 +- .../AnyExtensionTests.cs | 2 +- .../FirstExtensionTests.cs | 2 +- .../FirstOrNullExtensionTests.cs | 2 +- .../UtilityTest/ExpressionsHelperFixture.cs | 5 +- .../DefaultFlushEntityEventListener.cs | 2 +- .../ANTLR/Exec/AbstractStatementExecutor.cs | 2 +- .../ANTLR/Exec/MultiTableDeleteExecutor.cs | 2 +- src/NHibernate/Async/IMultiCriteria.cs | 2 + .../Entity/AbstractEntityPersister.cs | 2 +- .../Entry/StructuredCollectionCacheEntry.cs | 3 +- src/NHibernate/Cfg/Configuration.cs | 70 +++++++++---------- src/NHibernate/Cfg/MappingSchema/HbmAny.cs | 4 +- src/NHibernate/Cfg/MappingSchema/HbmArray.cs | 2 +- src/NHibernate/Cfg/MappingSchema/HbmBag.cs | 4 +- src/NHibernate/Cfg/MappingSchema/HbmClass.cs | 16 ++--- .../Cfg/MappingSchema/HbmComponent.cs | 4 +- .../Cfg/MappingSchema/HbmCompositeElement.cs | 4 +- .../Cfg/MappingSchema/HbmCompositeIndex.cs | 2 +- .../Cfg/MappingSchema/HbmCompositeMapKey.cs | 2 +- .../Cfg/MappingSchema/HbmDynamicComponent.cs | 4 +- .../Cfg/MappingSchema/HbmFilterDef.cs | 6 +- src/NHibernate/Cfg/MappingSchema/HbmId.cs | 2 +- src/NHibernate/Cfg/MappingSchema/HbmIdbag.cs | 4 +- .../Cfg/MappingSchema/HbmIndexManyToAny.cs | 2 +- src/NHibernate/Cfg/MappingSchema/HbmJoin.cs | 2 +- .../Cfg/MappingSchema/HbmJoinedSubclass.cs | 10 +-- .../Cfg/MappingSchema/HbmKeyManyToOne.cs | 2 +- .../Cfg/MappingSchema/HbmKeyProperty.cs | 2 +- src/NHibernate/Cfg/MappingSchema/HbmList.cs | 4 +- .../Cfg/MappingSchema/HbmManyToAny.cs | 2 +- .../Cfg/MappingSchema/HbmManyToOne.cs | 2 +- src/NHibernate/Cfg/MappingSchema/HbmMap.cs | 4 +- .../Cfg/MappingSchema/HbmMapping.cs | 27 +++---- .../Cfg/MappingSchema/HbmNaturalId.cs | 2 +- .../HbmNestedCompositeElement.cs | 7 +- .../Cfg/MappingSchema/HbmOneToOne.cs | 5 +- .../Cfg/MappingSchema/HbmPrimitiveArray.cs | 2 +- .../Cfg/MappingSchema/HbmProperties.cs | 4 +- .../Cfg/MappingSchema/HbmProperty.cs | 2 +- src/NHibernate/Cfg/MappingSchema/HbmSet.cs | 4 +- .../Cfg/MappingSchema/HbmSubclass.cs | 12 ++-- .../Cfg/MappingSchema/HbmTimestamp.cs | 2 +- .../Cfg/MappingSchema/HbmUnionSubclass.cs | 10 +-- .../Cfg/MappingSchema/HbmVersion.cs | 5 +- .../XmlHbmBinding/ClassCompositeIdBinder.cs | 4 +- .../Cfg/XmlHbmBinding/IdGeneratorBinder.cs | 4 +- .../Cfg/XmlHbmBinding/MappingRootBinder.cs | 4 +- .../Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs | 5 +- .../XmlHbmBinding/ResultSetMappingBinder.cs | 9 +-- .../Criterion/AbstractEmptinessExpression.cs | 2 +- src/NHibernate/Criterion/Expression.cs | 5 +- src/NHibernate/Criterion/GroupedProjection.cs | 2 +- src/NHibernate/Criterion/NotNullExpression.cs | 2 +- src/NHibernate/Criterion/NullExpression.cs | 2 +- src/NHibernate/Criterion/Order.cs | 2 +- .../Criterion/PropertyExpression.cs | 2 +- src/NHibernate/Criterion/SQLProjection.cs | 2 +- src/NHibernate/Criterion/SimpleProjection.cs | 2 +- src/NHibernate/Driver/FirebirdClientDriver.cs | 2 +- src/NHibernate/Engine/QueryParameters.cs | 8 +-- src/NHibernate/Engine/UnsavedValueFactory.cs | 2 +- .../DefaultFlushEntityEventListener.cs | 2 +- src/NHibernate/Event/EventListeners.cs | 30 ++++---- .../ANTLR/Exec/AbstractStatementExecutor.cs | 2 +- .../ANTLR/Exec/MultiTableDeleteExecutor.cs | 2 +- .../Ast/ANTLR/Tree/AssignmentSpecification.cs | 2 +- .../Hql/Ast/ANTLR/Tree/ConstructorNode.cs | 2 +- src/NHibernate/Impl/ExpressionProcessor.cs | 2 +- src/NHibernate/Impl/SessionImpl.cs | 4 +- src/NHibernate/Linq/Clauses/NhJoinClause.cs | 2 +- .../Loader/AbstractEntityJoinWalker.cs | 3 +- .../Mapping/ByCode/Impl/AnyMapper.cs | 4 +- .../Mapping/ByCode/Impl/ManyToAnyMapper.cs | 4 +- src/NHibernate/Mapping/ByCode/Import.cs | 2 +- .../Mapping/ByCode/TypeExtensions.cs | 4 +- src/NHibernate/Mapping/Collection.cs | 6 +- .../Entity/AbstractEntityPersister.cs | 2 +- .../Properties/BasicPropertyAccessor.cs | 4 +- .../DynamicProxy/DefaultArgumentHandler.cs | 2 +- .../Proxy/DynamicProxy/ProxyFactory.cs | 10 +-- .../Proxy/DynamicProxy/ProxyImplementor.cs | 4 +- .../Proxy/NHibernateProxyBuilder.cs | 2 +- .../SqlCommand/BackTrackCacheParameterList.cs | 5 +- src/NHibernate/SqlTypes/SqlTypeFactory.cs | 2 +- src/NHibernate/Type/CollectionType.cs | 2 +- src/NHibernate/Type/DbTimestampType.cs | 2 +- src/NHibernate/Type/OneToOneType.cs | 4 +- src/NHibernate/Type/TypeFactory.cs | 2 +- src/NHibernate/Type/TypeHelper.cs | 2 +- src/NHibernate/Util/ArrayHelper.cs | 12 +++- src/NHibernate/Util/CollectionHelper.cs | 4 +- src/NHibernate/Util/ReflectHelper.cs | 2 +- 150 files changed, 349 insertions(+), 306 deletions(-) diff --git a/src/NHibernate.DomainModel/Async/CustomPersister.cs b/src/NHibernate.DomainModel/Async/CustomPersister.cs index 889471e0441..104cc514c36 100644 --- a/src/NHibernate.DomainModel/Async/CustomPersister.cs +++ b/src/NHibernate.DomainModel/Async/CustomPersister.cs @@ -21,6 +21,7 @@ using NHibernate.Tuple.Entity; using NHibernate.Type; using NHibernate.Util; +using Array = System.Array; namespace NHibernate.DomainModel { diff --git a/src/NHibernate.DomainModel/Baz.cs b/src/NHibernate.DomainModel/Baz.cs index 2f661a17675..acb2c846dcd 100644 --- a/src/NHibernate.DomainModel/Baz.cs +++ b/src/NHibernate.DomainModel/Baz.cs @@ -396,7 +396,7 @@ public void SetDefaults() StringArray = StringSet.ToArray(); StringList = new List(StringArray); IntArray = new int[] {1, 3, 3, 7}; - FooArray = new Foo[0]; + FooArray = Array.Empty(); Customs = new List(); Customs.Add(new String[] {"foo", "bar"}); diff --git a/src/NHibernate.DomainModel/CustomPersister.cs b/src/NHibernate.DomainModel/CustomPersister.cs index 473f136b94c..04ce8d6625b 100644 --- a/src/NHibernate.DomainModel/CustomPersister.cs +++ b/src/NHibernate.DomainModel/CustomPersister.cs @@ -11,6 +11,7 @@ using NHibernate.Tuple.Entity; using NHibernate.Type; using NHibernate.Util; +using Array = System.Array; namespace NHibernate.DomainModel { @@ -130,12 +131,12 @@ public bool[] PropertyInsertability public ValueInclusion[] PropertyInsertGenerationInclusions { - get { return new ValueInclusion[0]; } + get { return Array.Empty(); } } public ValueInclusion[] PropertyUpdateGenerationInclusions { - get { return new ValueInclusion[0]; } + get { return Array.Empty(); } } public bool[] PropertyCheckability diff --git a/src/NHibernate.Test/Async/Component/Basic/ComponentTest.cs b/src/NHibernate.Test/Async/Component/Basic/ComponentTest.cs index 362bf474d27..74c9d174485 100644 --- a/src/NHibernate.Test/Async/Component/Basic/ComponentTest.cs +++ b/src/NHibernate.Test/Async/Component/Basic/ComponentTest.cs @@ -32,7 +32,7 @@ protected override string MappingsAssembly protected override System.Collections.IList Mappings { - get { return new string[] { }; } + get { return Array.Empty(); } } protected override void Configure(Configuration configuration) diff --git a/src/NHibernate.Test/Async/DialectTest/DialectFixture.cs b/src/NHibernate.Test/Async/DialectTest/DialectFixture.cs index e822ea63452..2fd3d53d33a 100644 --- a/src/NHibernate.Test/Async/DialectTest/DialectFixture.cs +++ b/src/NHibernate.Test/Async/DialectTest/DialectFixture.cs @@ -68,7 +68,7 @@ public async Task CurrentTimestampSelectionAsync() using (var connection = await (sessions.ConnectionProvider.GetConnectionAsync(CancellationToken.None))) { - var statement = driver.GenerateCommand(CommandType.Text, new SqlString(dialect.CurrentTimestampSelectString), new SqlType[0]); + var statement = driver.GenerateCommand(CommandType.Text, new SqlString(dialect.CurrentTimestampSelectString), Array.Empty()); statement.Connection = connection; using (var reader = await (statement.ExecuteReaderAsync())) { diff --git a/src/NHibernate.Test/Async/Events/PostEvents/PostUpdateFixture.cs b/src/NHibernate.Test/Async/Events/PostEvents/PostUpdateFixture.cs index aa3487708a0..bcea4c154f0 100644 --- a/src/NHibernate.Test/Async/Events/PostEvents/PostUpdateFixture.cs +++ b/src/NHibernate.Test/Async/Events/PostEvents/PostUpdateFixture.cs @@ -8,6 +8,7 @@ //------------------------------------------------------------------------------ +using System; using System.Collections; using System.Collections.Generic; using NHibernate.Event; @@ -56,7 +57,7 @@ public async Task ImplicitFlushAsync() } await (DbCleanupAsync()); - ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } [Test] @@ -85,7 +86,7 @@ public async Task ExplicitUpdateAsync() } await (DbCleanupAsync()); - ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } [Test] @@ -123,7 +124,7 @@ public async Task WithDetachedObjectAsync() } await (DbCleanupAsync()); - ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } [Test] @@ -163,7 +164,7 @@ public async Task UpdateDetachedObjectAsync() } await (DbCleanupAsync()); - ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } [Test] @@ -202,7 +203,7 @@ public async Task UpdateDetachedObjectWithLockAsync() } await (DbCleanupAsync()); - ((DebugSessionFactory)Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory)Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } private async Task DbCleanupAsync(CancellationToken cancellationToken = default(CancellationToken)) { diff --git a/src/NHibernate.Test/Async/ExceptionsTest/NullQueryTest.cs b/src/NHibernate.Test/Async/ExceptionsTest/NullQueryTest.cs index 8cd47a15452..5fa295ef6f1 100644 --- a/src/NHibernate.Test/Async/ExceptionsTest/NullQueryTest.cs +++ b/src/NHibernate.Test/Async/ExceptionsTest/NullQueryTest.cs @@ -28,7 +28,7 @@ public class NullQueryTestAsync : TestCase protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } #endregion diff --git a/src/NHibernate.Test/Async/Legacy/FumTest.cs b/src/NHibernate.Test/Async/Legacy/FumTest.cs index 9c94d2a8d81..779c374d42d 100644 --- a/src/NHibernate.Test/Async/Legacy/FumTest.cs +++ b/src/NHibernate.Test/Async/Legacy/FumTest.cs @@ -86,7 +86,7 @@ public async Task CriteriaCollectionAsync() Assert.IsTrue(b.MapComponent.Stringmap.Count == 2); int none = (await (s.CreateCriteria(typeof(Fum)) - .Add(Expression.In("FumString", new string[0])) + .Add(Expression.In("FumString", Array.Empty())) .ListAsync())).Count; Assert.AreEqual(0, none); diff --git a/src/NHibernate.Test/Async/LinqBulkManipulation/Fixture.cs b/src/NHibernate.Test/Async/LinqBulkManipulation/Fixture.cs index 37f5b248623..dd131a898f4 100644 --- a/src/NHibernate.Test/Async/LinqBulkManipulation/Fixture.cs +++ b/src/NHibernate.Test/Async/LinqBulkManipulation/Fixture.cs @@ -25,7 +25,7 @@ namespace NHibernate.Test.LinqBulkManipulation [TestFixture] public class FixtureAsync : TestCase { - protected override IList Mappings => new string[0]; + protected override IList Mappings => Array.Empty(); protected override void Configure(Cfg.Configuration configuration) { @@ -970,7 +970,7 @@ public async Task SimpleDeleteOnAnimalAsync() using (var t = s.BeginTransaction()) { // Get rid of FK which may fail the test - _doll.Friends = new Human[0]; + _doll.Friends = Array.Empty(); await (s.UpdateAsync(_doll)); await (t.CommitAsync()); } @@ -1029,7 +1029,7 @@ public async Task DeleteOnJoinedSubclassAsync() using (var t = s.BeginTransaction()) { // Get rid of FK which may fail the test - _doll.Friends = new Human[0]; + _doll.Friends = Array.Empty(); await (s.UpdateAsync(_doll)); await (t.CommitAsync()); } diff --git a/src/NHibernate.Test/Async/MappingByCode/IntegrationTests/NH2825/FixtureByCode.cs b/src/NHibernate.Test/Async/MappingByCode/IntegrationTests/NH2825/FixtureByCode.cs index 56967846d45..e4ef7e134a2 100644 --- a/src/NHibernate.Test/Async/MappingByCode/IntegrationTests/NH2825/FixtureByCode.cs +++ b/src/NHibernate.Test/Async/MappingByCode/IntegrationTests/NH2825/FixtureByCode.cs @@ -8,6 +8,7 @@ //------------------------------------------------------------------------------ +using System; using System.Collections; using NHibernate.Cfg.MappingSchema; using NHibernate.Mapping.ByCode; @@ -21,7 +22,7 @@ public class FixtureByCodeAsync : FixtureAsync { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override string MappingsAssembly @@ -63,4 +64,4 @@ private HbmMapping GetMappings() return mapper.CompileMappingForAllExplicitlyAddedEntities(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/NHSpecificTest/EmptyMappingsFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/EmptyMappingsFixture.cs index 556893083c5..97fcfe57f9f 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/EmptyMappingsFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/EmptyMappingsFixture.cs @@ -29,7 +29,7 @@ public class EmptyMappingsFixtureAsync : TestCase { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } [Test] diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH1421/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH1421/Fixture.cs index 930a266889a..5650f0bc2df 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH1421/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH1421/Fixture.cs @@ -27,7 +27,7 @@ public void WhenParameterListIsEmptyUsingQueryThenDoesNotTrowsNullReferenceExcep using (var s = OpenSession()) { var query = s.CreateQuery("from AnEntity a where a.id in (:myList)"); - Assert.That(() => query.SetParameterList("myList", new long[0]).ListAsync(), Throws.Exception.Not.InstanceOf()); + Assert.That(() => query.SetParameterList("myList", Array.Empty()).ListAsync(), Throws.Exception.Not.InstanceOf()); } } } diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH2166/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH2166/Fixture.cs index 3e923eb932c..ce2818d7c47 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH2166/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH2166/Fixture.cs @@ -21,7 +21,7 @@ public class FixtureAsync: TestCase { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } [Test] diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH4077/PostInsertFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH4077/PostInsertFixture.cs index 79f958ebd5a..b1cf11738ad 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH4077/PostInsertFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH4077/PostInsertFixture.cs @@ -74,7 +74,7 @@ protected override HbmMapping GetMappings() protected override void Configure(Configuration configuration) { base.Configure(configuration); - var existingListeners = (configuration.EventListeners.PostInsertEventListeners ?? new IPostInsertEventListener[0]).ToList(); + var existingListeners = (configuration.EventListeners.PostInsertEventListeners ?? Array.Empty()).ToList(); // this evil listener uses the session to perform a few queries and causes an auto-flush to happen existingListeners.Add(new CausesAutoflushListener()); configuration.EventListeners.PostInsertEventListeners = existingListeners.ToArray(); diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH4077/PostUpdateFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH4077/PostUpdateFixture.cs index af02dfa76a8..f2d2f9fc2ff 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH4077/PostUpdateFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH4077/PostUpdateFixture.cs @@ -68,7 +68,7 @@ protected override HbmMapping GetMappings() protected override void Configure(Configuration configuration) { base.Configure(configuration); - var existingListeners = (configuration.EventListeners.PostUpdateEventListeners ?? new IPostUpdateEventListener[0]).ToList(); + var existingListeners = (configuration.EventListeners.PostUpdateEventListeners ?? Array.Empty()).ToList(); // this evil listener uses the session to perform a few queries and causes an auto-flush to happen existingListeners.Add(new CausesAutoflushListener()); configuration.EventListeners.PostUpdateEventListeners = existingListeners.ToArray(); diff --git a/src/NHibernate.Test/Async/NHSpecificTest/NH901/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/NH901/Fixture.cs index c576dd1a910..a0356b166fb 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/NH901/Fixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/NH901/Fixture.cs @@ -8,6 +8,7 @@ //------------------------------------------------------------------------------ +using System; using System.Collections; using NHibernate.Cfg; using NHibernate.Mapping.ByCode; @@ -118,7 +119,7 @@ public class FixtureByCodeAsync : FixtureBaseAsync { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override string MappingsAssembly diff --git a/src/NHibernate.Test/Async/SecondLevelCacheTest/InvalidationTests.cs b/src/NHibernate.Test/Async/SecondLevelCacheTest/InvalidationTests.cs index 76e5b040cbb..794140f797b 100644 --- a/src/NHibernate.Test/Async/SecondLevelCacheTest/InvalidationTests.cs +++ b/src/NHibernate.Test/Async/SecondLevelCacheTest/InvalidationTests.cs @@ -14,7 +14,6 @@ using System.Reflection; using NHibernate.Cache; using NHibernate.Cfg; -using NHibernate.Engine; using NHibernate.Impl; using NHibernate.Test.SecondLevelCacheTests; using NSubstitute; diff --git a/src/NHibernate.Test/Async/TestTestCase.cs b/src/NHibernate.Test/Async/TestTestCase.cs index 9e907c57018..10f40510026 100644 --- a/src/NHibernate.Test/Async/TestTestCase.cs +++ b/src/NHibernate.Test/Async/TestTestCase.cs @@ -23,7 +23,7 @@ public class TestTestCaseAsync : TestCase { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } private bool _failOnTearDown; diff --git a/src/NHibernate.Test/Async/TransactionTest/TransactionNotificationFixture.cs b/src/NHibernate.Test/Async/TransactionTest/TransactionNotificationFixture.cs index 6b2c82e3d2a..e52a03d96ed 100644 --- a/src/NHibernate.Test/Async/TransactionTest/TransactionNotificationFixture.cs +++ b/src/NHibernate.Test/Async/TransactionTest/TransactionNotificationFixture.cs @@ -8,6 +8,7 @@ //------------------------------------------------------------------------------ +using System; using System.Collections; using System.Data.Common; using NUnit.Framework; @@ -21,7 +22,7 @@ public class TransactionNotificationFixtureAsync : TestCase { protected override IList Mappings { - get { return new string[] {}; } + get { return Array.Empty(); } } [Test] @@ -99,4 +100,4 @@ public async Task ShouldNotifyAfterTransactionWithOwnConnectionAsync(bool usePre Assert.That(interceptor.afterTransactionCompletionCalled, Is.EqualTo(1)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/TypesTest/BinaryBlobTypeFixture.cs b/src/NHibernate.Test/Async/TypesTest/BinaryBlobTypeFixture.cs index c4d28722579..9ff01e0f495 100644 --- a/src/NHibernate.Test/Async/TypesTest/BinaryBlobTypeFixture.cs +++ b/src/NHibernate.Test/Async/TypesTest/BinaryBlobTypeFixture.cs @@ -69,7 +69,7 @@ public async Task ReadWriteZeroLenAsync() using (ISession s = OpenSession()) { BinaryBlobClass b = new BinaryBlobClass(); - b.BinaryBlob = new byte[0]; + b.BinaryBlob = Array.Empty(); savedId = await (s.SaveAsync(b)); await (s.FlushAsync()); } diff --git a/src/NHibernate.Test/Async/TypesTest/BinaryTypeFixture.cs b/src/NHibernate.Test/Async/TypesTest/BinaryTypeFixture.cs index 7421dd7cbe4..d4f4cd52fc7 100644 --- a/src/NHibernate.Test/Async/TypesTest/BinaryTypeFixture.cs +++ b/src/NHibernate.Test/Async/TypesTest/BinaryTypeFixture.cs @@ -78,8 +78,8 @@ public async Task InsertZeroLengthAsync() BinaryClass bcBinary = new BinaryClass(); bcBinary.Id = 1; - bcBinary.DefaultSize = new byte[0]; - bcBinary.WithSize = new byte[0]; + bcBinary.DefaultSize = Array.Empty(); + bcBinary.WithSize = Array.Empty(); ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); diff --git a/src/NHibernate.Test/BulkManipulation/BaseFixture.cs b/src/NHibernate.Test/BulkManipulation/BaseFixture.cs index 2817e549991..7a8870cc1f6 100644 --- a/src/NHibernate.Test/BulkManipulation/BaseFixture.cs +++ b/src/NHibernate.Test/BulkManipulation/BaseFixture.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Hql.Ast.ANTLR; using System.Collections.Generic; @@ -13,7 +14,7 @@ public class BaseFixture: TestCase protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } #endregion @@ -38,4 +39,4 @@ public string GetSql(string query) return qt.SQLString; } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Bidirectional/DeleteOneToOneOrphansTest.cs b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Bidirectional/DeleteOneToOneOrphansTest.cs index b25839232d1..692ceb86ed9 100644 --- a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Bidirectional/DeleteOneToOneOrphansTest.cs +++ b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Bidirectional/DeleteOneToOneOrphansTest.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System; +using System.Collections; using NHibernate.Cfg; using NHibernate.Mapping.ByCode; using NUnit.Framework; @@ -92,7 +93,7 @@ public class DeleteOneToOneOrphansTestByCode : DeleteOneToOneOrphansTest { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override void AddMappings(Configuration configuration) diff --git a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Composite/DeleteOneToOneOrphansTest.cs b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Composite/DeleteOneToOneOrphansTest.cs index 100ec6424a5..bb61c7245f9 100644 --- a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Composite/DeleteOneToOneOrphansTest.cs +++ b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Composite/DeleteOneToOneOrphansTest.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Cfg.MappingSchema; using NHibernate.Mapping.ByCode; @@ -93,7 +94,7 @@ public class DeleteOneToOneOrphansTestByCode : DeleteOneToOneOrphansTest { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } diff --git a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Reversed/Bidirectional/DeleteOneToOneOrphansTest.cs b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Reversed/Bidirectional/DeleteOneToOneOrphansTest.cs index 960f154dcde..eec7722552f 100644 --- a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Reversed/Bidirectional/DeleteOneToOneOrphansTest.cs +++ b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Reversed/Bidirectional/DeleteOneToOneOrphansTest.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Cfg; using NHibernate.Mapping.ByCode; @@ -92,7 +93,7 @@ public class DeleteOneToOneOrphansTestByCode : DeleteOneToOneOrphansTest { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override void AddMappings(Configuration configuration) diff --git a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Reversed/Unidirectional/DeleteOneToOneOrphansTest.cs b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Reversed/Unidirectional/DeleteOneToOneOrphansTest.cs index c550f3f4f60..beccfa339af 100644 --- a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Reversed/Unidirectional/DeleteOneToOneOrphansTest.cs +++ b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Fk/Reversed/Unidirectional/DeleteOneToOneOrphansTest.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Cfg; using NHibernate.Mapping.ByCode; @@ -142,7 +143,7 @@ public class DeleteOneToOneOrphansTestByCode : DeleteOneToOneOrphansTest { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override void AddMappings(Configuration configuration) diff --git a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Pk/Bidirectional/DeleteOneToOneOrphansTest.cs b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Pk/Bidirectional/DeleteOneToOneOrphansTest.cs index 26c1db69632..cf7e549628b 100644 --- a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Pk/Bidirectional/DeleteOneToOneOrphansTest.cs +++ b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Pk/Bidirectional/DeleteOneToOneOrphansTest.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Cfg; using NHibernate.Mapping.ByCode; @@ -95,7 +96,7 @@ public class DeleteOneToOneOrphansTestByCode : DeleteOneToOneOrphansTest { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override void AddMappings(Configuration configuration) diff --git a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Pk/Unidirectional/DeleteOneToOneOrphansTest.cs b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Pk/Unidirectional/DeleteOneToOneOrphansTest.cs index 0a263003e1e..34776c2b8d2 100644 --- a/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Pk/Unidirectional/DeleteOneToOneOrphansTest.cs +++ b/src/NHibernate.Test/Cascade/OneToOneCascadeDelete/Pk/Unidirectional/DeleteOneToOneOrphansTest.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Cfg.MappingSchema; using NHibernate.Mapping.ByCode; @@ -107,7 +108,7 @@ public class DeleteOneToOneOrphansTestByCode : DeleteOneToOneOrphansTest { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override void AddMappings(Cfg.Configuration configuration) diff --git a/src/NHibernate.Test/Component/Basic/ComponentTest.cs b/src/NHibernate.Test/Component/Basic/ComponentTest.cs index 744b9986171..d22a7708a97 100644 --- a/src/NHibernate.Test/Component/Basic/ComponentTest.cs +++ b/src/NHibernate.Test/Component/Basic/ComponentTest.cs @@ -21,7 +21,7 @@ protected override string MappingsAssembly protected override System.Collections.IList Mappings { - get { return new string[] { }; } + get { return Array.Empty(); } } protected override void Configure(Configuration configuration) diff --git a/src/NHibernate.Test/Criteria/DetachedCriteriaSerializable.cs b/src/NHibernate.Test/Criteria/DetachedCriteriaSerializable.cs index 5dd24384c69..9dff8ab8bbd 100644 --- a/src/NHibernate.Test/Criteria/DetachedCriteriaSerializable.cs +++ b/src/NHibernate.Test/Criteria/DetachedCriteriaSerializable.cs @@ -286,7 +286,7 @@ public void ResultTransformes() IResultTransformer rt = new RootEntityResultTransformer(); NHAssert.IsSerializable(rt); - rt = new AliasToBeanConstructorResultTransformer(typeof(StudentDTO).GetConstructor(new System.Type[] { })); + rt = new AliasToBeanConstructorResultTransformer(typeof(StudentDTO).GetConstructor(System.Type.EmptyTypes)); NHAssert.IsSerializable(rt); rt = new AliasToBeanResultTransformer(typeof(StudentDTO)); @@ -424,4 +424,4 @@ public void ExecutableCriteria() SerializeAndList(dc); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/DialectTest/DialectFixture.cs b/src/NHibernate.Test/DialectTest/DialectFixture.cs index 17899c1e88f..952e3e6c154 100644 --- a/src/NHibernate.Test/DialectTest/DialectFixture.cs +++ b/src/NHibernate.Test/DialectTest/DialectFixture.cs @@ -161,7 +161,7 @@ public void CurrentTimestampSelection() using (var connection = sessions.ConnectionProvider.GetConnection()) { - var statement = driver.GenerateCommand(CommandType.Text, new SqlString(dialect.CurrentTimestampSelectString), new SqlType[0]); + var statement = driver.GenerateCommand(CommandType.Text, new SqlString(dialect.CurrentTimestampSelectString), Array.Empty()); statement.Connection = connection; using (var reader = statement.ExecuteReader()) { diff --git a/src/NHibernate.Test/Events/PostEvents/PostUpdateFixture.cs b/src/NHibernate.Test/Events/PostEvents/PostUpdateFixture.cs index f09852303d8..cf607e3ba49 100644 --- a/src/NHibernate.Test/Events/PostEvents/PostUpdateFixture.cs +++ b/src/NHibernate.Test/Events/PostEvents/PostUpdateFixture.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Collections.Generic; using NHibernate.Event; @@ -44,7 +45,7 @@ public void ImplicitFlush() } DbCleanup(); - ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } [Test] @@ -73,7 +74,7 @@ public void ExplicitUpdate() } DbCleanup(); - ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } [Test] @@ -111,7 +112,7 @@ public void WithDetachedObject() } DbCleanup(); - ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } [Test] @@ -151,7 +152,7 @@ public void UpdateDetachedObject() } DbCleanup(); - ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory) Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } [Test] @@ -190,7 +191,7 @@ public void UpdateDetachedObjectWithLock() } DbCleanup(); - ((DebugSessionFactory)Sfi).EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[0]; + ((DebugSessionFactory)Sfi).EventListeners.PostUpdateEventListeners = Array.Empty(); } private void DbCleanup() { diff --git a/src/NHibernate.Test/ExceptionsTest/NullQueryTest.cs b/src/NHibernate.Test/ExceptionsTest/NullQueryTest.cs index 5af17f0a647..177bdf560aa 100644 --- a/src/NHibernate.Test/ExceptionsTest/NullQueryTest.cs +++ b/src/NHibernate.Test/ExceptionsTest/NullQueryTest.cs @@ -17,7 +17,7 @@ public class NullQueryTest : TestCase protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } #endregion diff --git a/src/NHibernate.Test/ExpressionTest/InExpressionFixture.cs b/src/NHibernate.Test/ExpressionTest/InExpressionFixture.cs index 3c4ad489661..16ed8746020 100644 --- a/src/NHibernate.Test/ExpressionTest/InExpressionFixture.cs +++ b/src/NHibernate.Test/ExpressionTest/InExpressionFixture.cs @@ -34,7 +34,7 @@ public void InSqlStringTest() public void InEmptyList() { ISession session = factory.OpenSession(); - InExpression expression = new InExpression("Count", new object[0]); + InExpression expression = new InExpression("Count", Array.Empty()); CreateObjects(typeof(Simple), session); SqlString sql = expression.ToSqlString(criteria, criteriaQuery); Assert.AreEqual("1=0", sql.ToString()); diff --git a/src/NHibernate.Test/Hql/Ast/BaseFixture.cs b/src/NHibernate.Test/Hql/Ast/BaseFixture.cs index 1f2d0d6b18c..22a8c2e0d73 100644 --- a/src/NHibernate.Test/Hql/Ast/BaseFixture.cs +++ b/src/NHibernate.Test/Hql/Ast/BaseFixture.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Collections.Generic; using NHibernate.Hql.Ast.ANTLR; @@ -13,7 +14,7 @@ public class BaseFixture: TestCase protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } #endregion @@ -43,4 +44,4 @@ public string GetSql(string query, IDictionary replacements) return qt.SQLString; } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Legacy/FumTest.cs b/src/NHibernate.Test/Legacy/FumTest.cs index d7aec5d6231..ab43bed1595 100644 --- a/src/NHibernate.Test/Legacy/FumTest.cs +++ b/src/NHibernate.Test/Legacy/FumTest.cs @@ -75,7 +75,7 @@ public void CriteriaCollection() Assert.IsTrue(b.MapComponent.Stringmap.Count == 2); int none = s.CreateCriteria(typeof(Fum)) - .Add(Expression.In("FumString", new string[0])) + .Add(Expression.In("FumString", Array.Empty())) .List().Count; Assert.AreEqual(0, none); diff --git a/src/NHibernate.Test/Linq/ParameterisedQueries.cs b/src/NHibernate.Test/Linq/ParameterisedQueries.cs index 6456ba0963b..76e3bc0d505 100644 --- a/src/NHibernate.Test/Linq/ParameterisedQueries.cs +++ b/src/NHibernate.Test/Linq/ParameterisedQueries.cs @@ -236,7 +236,7 @@ public void Different_Null_Returns_Different_Keys() protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } } } \ No newline at end of file diff --git a/src/NHibernate.Test/LinqBulkManipulation/Fixture.cs b/src/NHibernate.Test/LinqBulkManipulation/Fixture.cs index c376163051d..82fa9956909 100644 --- a/src/NHibernate.Test/LinqBulkManipulation/Fixture.cs +++ b/src/NHibernate.Test/LinqBulkManipulation/Fixture.cs @@ -14,7 +14,7 @@ namespace NHibernate.Test.LinqBulkManipulation [TestFixture] public class Fixture : TestCase { - protected override IList Mappings => new string[0]; + protected override IList Mappings => Array.Empty(); protected override void Configure(Cfg.Configuration configuration) { @@ -998,7 +998,7 @@ public void SimpleDeleteOnAnimal() using (var t = s.BeginTransaction()) { // Get rid of FK which may fail the test - _doll.Friends = new Human[0]; + _doll.Friends = Array.Empty(); s.Update(_doll); t.Commit(); } @@ -1057,7 +1057,7 @@ public void DeleteOnJoinedSubclass() using (var t = s.BeginTransaction()) { // Get rid of FK which may fail the test - _doll.Friends = new Human[0]; + _doll.Friends = Array.Empty(); s.Update(_doll); t.Commit(); } diff --git a/src/NHibernate.Test/MappingByCode/IntegrationTests/NH2825/FixtureByCode.cs b/src/NHibernate.Test/MappingByCode/IntegrationTests/NH2825/FixtureByCode.cs index 4f5e9728e1a..34dadd7b590 100644 --- a/src/NHibernate.Test/MappingByCode/IntegrationTests/NH2825/FixtureByCode.cs +++ b/src/NHibernate.Test/MappingByCode/IntegrationTests/NH2825/FixtureByCode.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System; +using System.Collections; using NHibernate.Cfg.MappingSchema; using NHibernate.Mapping.ByCode; using NUnit.Framework; @@ -10,7 +11,7 @@ public class FixtureByCode : Fixture { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override string MappingsAssembly @@ -52,4 +53,4 @@ private HbmMapping GetMappings() return mapper.CompileMappingForAllExplicitlyAddedEntities(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/MappingByCode/MappersTests/ComponentWithBagOfNestedComponentsTests.cs b/src/NHibernate.Test/MappingByCode/MappersTests/ComponentWithBagOfNestedComponentsTests.cs index 9206ecc3e18..fe7a0e0780f 100644 --- a/src/NHibernate.Test/MappingByCode/MappersTests/ComponentWithBagOfNestedComponentsTests.cs +++ b/src/NHibernate.Test/MappingByCode/MappersTests/ComponentWithBagOfNestedComponentsTests.cs @@ -58,7 +58,7 @@ protected override IList Mappings { // We can perform these tests without // creating a data schema - return new string[0]; + return Array.Empty(); } } diff --git a/src/NHibernate.Test/NHSpecificTest/EmptyMappingsFixture.cs b/src/NHibernate.Test/NHSpecificTest/EmptyMappingsFixture.cs index 6704e5877be..0f6761999d6 100644 --- a/src/NHibernate.Test/NHSpecificTest/EmptyMappingsFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/EmptyMappingsFixture.cs @@ -17,7 +17,7 @@ public class EmptyMappingsFixture : TestCase { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } [Test] diff --git a/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs index 2d622b2b2f5..8f2e002ca4b 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH1421/Fixture.cs @@ -15,7 +15,7 @@ public void WhenParameterListIsEmptyArrayUsingQueryThenDoesNotTrowsNullReference using (var s = OpenSession()) { var query = s.CreateQuery("from AnEntity a where a.id in (:myList)"); - Assert.That(() => query.SetParameterList("myList", new long[0]), Throws.Exception.Not.InstanceOf()); + Assert.That(() => query.SetParameterList("myList", Array.Empty()), Throws.Exception.Not.InstanceOf()); } } @@ -57,7 +57,7 @@ public void WhenParameterListIsEmptyUsingQueryThenDoesNotTrowsNullReferenceExcep using (var s = OpenSession()) { var query = s.CreateQuery("from AnEntity a where a.id in (:myList)"); - Assert.That(() => query.SetParameterList("myList", new long[0]).List(), Throws.Exception.Not.InstanceOf()); + Assert.That(() => query.SetParameterList("myList", Array.Empty()).List(), Throws.Exception.Not.InstanceOf()); } } } diff --git a/src/NHibernate.Test/NHSpecificTest/NH2166/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2166/Fixture.cs index 341fc5143fd..539a58eec4a 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2166/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2166/Fixture.cs @@ -10,7 +10,7 @@ public class Fixture: TestCase { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } [Test] diff --git a/src/NHibernate.Test/NHSpecificTest/NH2931/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH2931/Fixture.cs index 6140f5e0ab2..2bdc5b02066 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH2931/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH2931/Fixture.cs @@ -1,4 +1,5 @@ -using NHibernate.Mapping.ByCode; +using System; +using NHibernate.Mapping.ByCode; using NUnit.Framework; using System.Collections.Generic; using System.Linq; @@ -11,7 +12,7 @@ public class MappingByCodeTest : BugTestCase //no xml mappings here, since we use MappingByCode protected override System.Collections.IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } [Test] diff --git a/src/NHibernate.Test/NHSpecificTest/NH3954/EqualsFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3954/EqualsFixture.cs index 5b1c896da1d..5d55e7c0a1f 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3954/EqualsFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3954/EqualsFixture.cs @@ -30,7 +30,7 @@ private void TweakEntry(ProxyCacheEntry entryToTweak, int hashcode) public void TypeEquality() { var entry1 = new ProxyCacheEntry(typeof(Entity1), null); - var entry2 = new ProxyCacheEntry(typeof(Entity1), new System.Type[0]); + var entry2 = new ProxyCacheEntry(typeof(Entity1), System.Type.EmptyTypes); Assert.IsTrue(entry1.Equals(entry2)); Assert.IsTrue(entry2.Equals(entry1)); } diff --git a/src/NHibernate.Test/NHSpecificTest/NH3956/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH3956/Fixture.cs index adf8c31e4b2..92d4de9943c 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH3956/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH3956/Fixture.cs @@ -1,4 +1,5 @@ -using System.Reflection; +using System; +using System.Reflection; using NHibernate.Engine.Query.Sql; using NUnit.Framework; @@ -26,7 +27,7 @@ public void NativeSQLQuerySpecificationEqualityOnQuery() { var spec1 = new NativeSQLQuerySpecification("select blah", null, null); // Empty spaces array should be equivalent to null. Maybe results too but current implementation does not handle this. - var spec2 = new NativeSQLQuerySpecification("select blah", null, new string[0]); + var spec2 = new NativeSQLQuerySpecification("select blah", null, Array.Empty()); Assert.IsTrue(spec1.Equals(spec2)); Assert.IsTrue(spec2.Equals(spec1)); @@ -65,7 +66,7 @@ public void NativeSQLQuerySpecificationEqualityOnReturns() new NativeSQLQueryScalarReturn("alias2", NHibernateUtil.Decimal) }, // Empty spaces array should be equivalent to null. - new string[0]); + Array.Empty()); Assert.IsTrue(spec1.Equals(spec2)); Assert.IsTrue(spec2.Equals(spec1)); diff --git a/src/NHibernate.Test/NHSpecificTest/NH4077/PostInsertFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH4077/PostInsertFixture.cs index 9e02d22dba4..9cb011fc9b0 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH4077/PostInsertFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH4077/PostInsertFixture.cs @@ -62,7 +62,7 @@ protected override HbmMapping GetMappings() protected override void Configure(Configuration configuration) { base.Configure(configuration); - var existingListeners = (configuration.EventListeners.PostInsertEventListeners ?? new IPostInsertEventListener[0]).ToList(); + var existingListeners = (configuration.EventListeners.PostInsertEventListeners ?? Array.Empty()).ToList(); // this evil listener uses the session to perform a few queries and causes an auto-flush to happen existingListeners.Add(new CausesAutoflushListener()); configuration.EventListeners.PostInsertEventListeners = existingListeners.ToArray(); diff --git a/src/NHibernate.Test/NHSpecificTest/NH4077/PostUpdateFixture.cs b/src/NHibernate.Test/NHSpecificTest/NH4077/PostUpdateFixture.cs index 8e9d9932b83..ba2b9beb351 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH4077/PostUpdateFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH4077/PostUpdateFixture.cs @@ -56,7 +56,7 @@ protected override HbmMapping GetMappings() protected override void Configure(Configuration configuration) { base.Configure(configuration); - var existingListeners = (configuration.EventListeners.PostUpdateEventListeners ?? new IPostUpdateEventListener[0]).ToList(); + var existingListeners = (configuration.EventListeners.PostUpdateEventListeners ?? Array.Empty()).ToList(); // this evil listener uses the session to perform a few queries and causes an auto-flush to happen existingListeners.Add(new CausesAutoflushListener()); configuration.EventListeners.PostUpdateEventListeners = existingListeners.ToArray(); diff --git a/src/NHibernate.Test/NHSpecificTest/NH901/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/NH901/Fixture.cs index c7b06e82a42..69fcc445147 100644 --- a/src/NHibernate.Test/NHSpecificTest/NH901/Fixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/NH901/Fixture.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Cfg; using NHibernate.Mapping.ByCode; @@ -107,7 +108,7 @@ public class FixtureByCode : FixtureBase { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override string MappingsAssembly diff --git a/src/NHibernate.Test/QueryTest/DetachedQueryFixture.cs b/src/NHibernate.Test/QueryTest/DetachedQueryFixture.cs index 32ab71aa270..b137f1d0145 100644 --- a/src/NHibernate.Test/QueryTest/DetachedQueryFixture.cs +++ b/src/NHibernate.Test/QueryTest/DetachedQueryFixture.cs @@ -82,7 +82,7 @@ public void PropertiesSet() Assert.IsTrue(tdq.OptionalUntypeParams[1].Equals(new Foo("Fulano", "De Tal"))); tdq.SetAnsiString(1, ""); - tdq.SetBinary(2, new byte[] { }); + tdq.SetBinary(2, Array.Empty()); tdq.SetBoolean(3, false); tdq.SetByte(4, 255); tdq.SetCharacter(5, 'A'); @@ -119,7 +119,7 @@ public void PropertiesSet() Assert.IsTrue(tdq.PosParams[18].Type.Equals(NHibernateUtil.Guid)); tdq.SetAnsiString("1", ""); - tdq.SetBinary("2", new byte[] { }); + tdq.SetBinary("2", Array.Empty()); tdq.SetBoolean("3", false); tdq.SetByte("4", 255); tdq.SetCharacter("5", 'A'); @@ -181,7 +181,7 @@ public void CopyToTest() origin.SetLockMode("LM1", LockMode.Upgrade); origin.SetProperties(new Foo("Pallino", "Pinco")); origin.SetInt64(1, 1); - origin.SetBinary(2, new byte[] { }); + origin.SetBinary(2, Array.Empty()); origin.SetBoolean(3, false); origin.SetDateTime(6, DateTime.MaxValue); origin.SetCharacter("5", 'A'); diff --git a/src/NHibernate.Test/QueryTest/QueryParametersFixture.cs b/src/NHibernate.Test/QueryTest/QueryParametersFixture.cs index 29a74aaf84a..678c10beb91 100644 --- a/src/NHibernate.Test/QueryTest/QueryParametersFixture.cs +++ b/src/NHibernate.Test/QueryTest/QueryParametersFixture.cs @@ -1,3 +1,4 @@ +using System; using NHibernate.Engine; using NHibernate.Type; using NUnit.Framework; @@ -29,9 +30,9 @@ public void ValidateFailureDifferentLengths() { QueryParameters qp = new QueryParameters( new IType[] {NHibernateUtil.String}, - new object[] {}); + Array.Empty()); Assert.Throws(() => qp.ValidateParameters()); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/SystemTransactions/TransactionNotificationFixture.cs b/src/NHibernate.Test/SystemTransactions/TransactionNotificationFixture.cs index d37e897681a..416fe5b8637 100644 --- a/src/NHibernate.Test/SystemTransactions/TransactionNotificationFixture.cs +++ b/src/NHibernate.Test/SystemTransactions/TransactionNotificationFixture.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Transactions; using NHibernate.Cfg; @@ -8,14 +9,14 @@ namespace NHibernate.Test.SystemTransactions public class TransactionNotificationFixture : TestCase { protected override IList Mappings - => new string[] { }; + => Array.Empty(); protected virtual bool UseConnectionOnSystemTransactionPrepare => true; protected override void Configure(Configuration configuration) { configuration.SetProperty( - Environment.UseConnectionOnSystemTransactionPrepare, + Cfg.Environment.UseConnectionOnSystemTransactionPrepare, UseConnectionOnSystemTransactionPrepare.ToString()); } @@ -207,4 +208,4 @@ public class TransactionWithoutConnectionFromPrepareNotificationFixture : Transa { protected override bool UseConnectionOnSystemTransactionPrepare => false; } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/TestCaseMappingByCode.cs b/src/NHibernate.Test/TestCaseMappingByCode.cs index 1b9eb7a416a..97bb4bb4ec4 100644 --- a/src/NHibernate.Test/TestCaseMappingByCode.cs +++ b/src/NHibernate.Test/TestCaseMappingByCode.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using NHibernate.Cfg.MappingSchema; @@ -7,7 +8,7 @@ public abstract class TestCaseMappingByCode:TestCase { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } protected override string MappingsAssembly @@ -22,4 +23,4 @@ protected override void AddMappings(Cfg.Configuration configuration) protected abstract HbmMapping GetMappings(); } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/TestTestCase.cs b/src/NHibernate.Test/TestTestCase.cs index e4e8efe46e8..caa865228e4 100644 --- a/src/NHibernate.Test/TestTestCase.cs +++ b/src/NHibernate.Test/TestTestCase.cs @@ -12,7 +12,7 @@ public class TestTestCase : TestCase { protected override IList Mappings { - get { return new string[0]; } + get { return Array.Empty(); } } private bool _failOnTearDown; diff --git a/src/NHibernate.Test/TransactionTest/TransactionNotificationFixture.cs b/src/NHibernate.Test/TransactionTest/TransactionNotificationFixture.cs index 7d7a64fb960..d524ef91f77 100644 --- a/src/NHibernate.Test/TransactionTest/TransactionNotificationFixture.cs +++ b/src/NHibernate.Test/TransactionTest/TransactionNotificationFixture.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Data.Common; using NUnit.Framework; @@ -9,7 +10,7 @@ public class TransactionNotificationFixture : TestCase { protected override IList Mappings { - get { return new string[] {}; } + get { return Array.Empty(); } } @@ -113,4 +114,4 @@ public void ShouldNotifyAfterTransactionWithOwnConnection(bool usePrematureClose Assert.That(interceptor.afterTransactionCompletionCalled, Is.EqualTo(1)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/TransformTests/ImplementationOfEqualityTests.cs b/src/NHibernate.Test/TransformTests/ImplementationOfEqualityTests.cs index 863430ac06d..149f1e05aea 100644 --- a/src/NHibernate.Test/TransformTests/ImplementationOfEqualityTests.cs +++ b/src/NHibernate.Test/TransformTests/ImplementationOfEqualityTests.cs @@ -66,7 +66,7 @@ public void AliasToBeanResultTransformer_ShouldHaveEqualityBasedOnCtorParameter( [Test] public void AliasToBeanConstructorResultTransformer_ShouldHaveEqualityBasedOnCtorParameter() { - var emptyCtor = new System.Type[0]; + var emptyCtor = System.Type.EmptyTypes; var transformer1 = new AliasToBeanConstructorResultTransformer(typeof(object).GetConstructor(emptyCtor)); var transformer2 = new AliasToBeanConstructorResultTransformer(typeof(object).GetConstructor(emptyCtor)); Assert.That(transformer1, Is.EqualTo(transformer2)); diff --git a/src/NHibernate.Test/TypesTest/BinaryBlobTypeFixture.cs b/src/NHibernate.Test/TypesTest/BinaryBlobTypeFixture.cs index f7afa0b1155..81ce6e5a499 100644 --- a/src/NHibernate.Test/TypesTest/BinaryBlobTypeFixture.cs +++ b/src/NHibernate.Test/TypesTest/BinaryBlobTypeFixture.cs @@ -58,7 +58,7 @@ public void ReadWriteZeroLen() using (ISession s = OpenSession()) { BinaryBlobClass b = new BinaryBlobClass(); - b.BinaryBlob = new byte[0]; + b.BinaryBlob = Array.Empty(); savedId = s.Save(b); s.Flush(); } diff --git a/src/NHibernate.Test/TypesTest/BinaryTypeFixture.cs b/src/NHibernate.Test/TypesTest/BinaryTypeFixture.cs index e0ec802bee1..d9be9a01579 100644 --- a/src/NHibernate.Test/TypesTest/BinaryTypeFixture.cs +++ b/src/NHibernate.Test/TypesTest/BinaryTypeFixture.cs @@ -84,8 +84,8 @@ public void InsertZeroLength() BinaryClass bcBinary = new BinaryClass(); bcBinary.Id = 1; - bcBinary.DefaultSize = new byte[0]; - bcBinary.WithSize = new byte[0]; + bcBinary.DefaultSize = Array.Empty(); + bcBinary.WithSize = Array.Empty(); ISession s = OpenSession(); ITransaction t = s.BeginTransaction(); diff --git a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/AnyExtensionTests.cs b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/AnyExtensionTests.cs index 8fce55fa569..2074c125972 100644 --- a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/AnyExtensionTests.cs +++ b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/AnyExtensionTests.cs @@ -13,7 +13,7 @@ public class AnyExtensionTests [Test] public void WhenEmptyListThenReturnFalse() { - Assert.That((new object[0]).Any(), Is.False); + Assert.That((Array.Empty()).Any(), Is.False); } [Test] diff --git a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstExtensionTests.cs b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstExtensionTests.cs index 25aec547ca4..fb1412d8d02 100644 --- a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstExtensionTests.cs +++ b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstExtensionTests.cs @@ -25,7 +25,7 @@ public void WhenHasElementsThenReturnFirst() [Test] public void WhenEmptyThenThrowsInvalidOperation() { - Assert.That(() => (new object[0]).First(), Throws.TypeOf()); + Assert.That(() => (Array.Empty()).First(), Throws.TypeOf()); } } } diff --git a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstOrNullExtensionTests.cs b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstOrNullExtensionTests.cs index 3e308db71ec..7cdfbf55a9f 100644 --- a/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstOrNullExtensionTests.cs +++ b/src/NHibernate.Test/UtilityTest/EnumerableExtensionsTests/FirstOrNullExtensionTests.cs @@ -25,7 +25,7 @@ public void WhenHasElementsThenReturnFirst() [Test] public void WhenEmptyThenReturnNull() { - Assert.That((new object[0]).FirstOrNull(), Is.Null); + Assert.That((Array.Empty()).FirstOrNull(), Is.Null); } } } diff --git a/src/NHibernate.Test/UtilityTest/ExpressionsHelperFixture.cs b/src/NHibernate.Test/UtilityTest/ExpressionsHelperFixture.cs index 8a499ed1ff1..8de97b28988 100644 --- a/src/NHibernate.Test/UtilityTest/ExpressionsHelperFixture.cs +++ b/src/NHibernate.Test/UtilityTest/ExpressionsHelperFixture.cs @@ -1,3 +1,4 @@ +using System; using NHibernate.Util; using NUnit.Framework; using System.Collections.Generic; @@ -18,7 +19,7 @@ public bool BoolProp public IEnumerable CollectionProp { - get { return new string[0]; } + get { return Array.Empty(); } } } @@ -36,4 +37,4 @@ public void DecodeMemberAccessExpression() Is.EqualTo(typeof(TestingClass).GetMember("CollectionProp")[0])); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Event/Default/DefaultFlushEntityEventListener.cs b/src/NHibernate/Async/Event/Default/DefaultFlushEntityEventListener.cs index 17780c6411e..9bf172e0043 100644 --- a/src/NHibernate/Async/Event/Default/DefaultFlushEntityEventListener.cs +++ b/src/NHibernate/Async/Event/Default/DefaultFlushEntityEventListener.cs @@ -241,7 +241,7 @@ private async Task ScheduleUpdateAsync(FlushEntityEvent @event, Cancellati { throw new AssertionFailure("dirty, but no dirty properties"); } - dirtyProperties = ArrayHelper.EmptyIntArray; + dirtyProperties = Array.Empty(); } // check nullability but do not perform command execute diff --git a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs index b52b21c19de..2df56664ab1 100644 --- a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs +++ b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs @@ -111,7 +111,7 @@ protected virtual async Task DropTemporaryTableIfNecessaryAsync(IQueryable persi try { var commandText = new SqlString("delete from " + persister.TemporaryIdTableName); - ps = await (session.Batcher.PrepareCommandAsync(CommandType.Text, commandText, new SqlType[0], cancellationToken)).ConfigureAwait(false); + ps = await (session.Batcher.PrepareCommandAsync(CommandType.Text, commandText, Array.Empty(), cancellationToken)).ConfigureAwait(false); await (session.Batcher.ExecuteNonQueryAsync(ps, cancellationToken)).ConfigureAwait(false); } catch (Exception t) diff --git a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs index 3d3b269fbd4..27146fd0f95 100644 --- a/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs +++ b/src/NHibernate/Async/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs @@ -76,7 +76,7 @@ public override async Task ExecuteAsync(QueryParameters parameters, ISessio { try { - ps = await (session.Batcher.PrepareCommandAsync(CommandType.Text, deletes[i], new SqlType[0], cancellationToken)).ConfigureAwait(false); + ps = await (session.Batcher.PrepareCommandAsync(CommandType.Text, deletes[i], Array.Empty(), cancellationToken)).ConfigureAwait(false); await (session.Batcher.ExecuteNonQueryAsync(ps, cancellationToken)).ConfigureAwait(false); } finally diff --git a/src/NHibernate/Async/IMultiCriteria.cs b/src/NHibernate/Async/IMultiCriteria.cs index e0574d6e7b1..31b45dddd42 100644 --- a/src/NHibernate/Async/IMultiCriteria.cs +++ b/src/NHibernate/Async/IMultiCriteria.cs @@ -8,8 +8,10 @@ //------------------------------------------------------------------------------ +using System; using System.Collections; using NHibernate.Criterion; +using NHibernate.Impl; using NHibernate.Transform; namespace NHibernate diff --git a/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs b/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs index 788554e9d56..913844ddc20 100644 --- a/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs +++ b/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs @@ -858,7 +858,7 @@ public async Task UpdateAsync(object id, object[] fields, int[] dirtyFields, boo // to be updated; an empty array for the dirty fields needs to be passed to // getPropertiesToUpdate() instead of null. propsToUpdate = this.GetPropertiesToUpdate( - (dirtyFields == null ? ArrayHelper.EmptyIntArray : dirtyFields), hasDirtyCollection); + (dirtyFields == null ? Array.Empty() : dirtyFields), hasDirtyCollection); // don't need to check laziness (dirty checking algorithm handles that) updateStrings = new SqlCommandInfo[span]; diff --git a/src/NHibernate/Cache/Entry/StructuredCollectionCacheEntry.cs b/src/NHibernate/Cache/Entry/StructuredCollectionCacheEntry.cs index 63b6fd9ea82..e85c6828694 100644 --- a/src/NHibernate/Cache/Entry/StructuredCollectionCacheEntry.cs +++ b/src/NHibernate/Cache/Entry/StructuredCollectionCacheEntry.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Collections.Generic; using System.Linq; @@ -18,7 +19,7 @@ public virtual object Destructure(object item, ISessionFactoryImplementor factor var collection = item as IEnumerable; var objects = collection != null ? collection.Cast().ToArray() - : new object[0]; + : Array.Empty(); return new CollectionCacheEntry(objects); } } diff --git a/src/NHibernate/Cfg/Configuration.cs b/src/NHibernate/Cfg/Configuration.cs index 1ecdca22e22..a701dd4d757 100644 --- a/src/NHibernate/Cfg/Configuration.cs +++ b/src/NHibernate/Cfg/Configuration.cs @@ -1961,106 +1961,106 @@ private void ClearListeners(ListenerType type) switch (type) { case ListenerType.Autoflush: - eventListeners.AutoFlushEventListeners = new IAutoFlushEventListener[] { }; + eventListeners.AutoFlushEventListeners = Array.Empty(); break; case ListenerType.Merge: - eventListeners.MergeEventListeners = new IMergeEventListener[] { }; + eventListeners.MergeEventListeners = Array.Empty(); break; case ListenerType.Create: - eventListeners.PersistEventListeners = new IPersistEventListener[] { }; + eventListeners.PersistEventListeners = Array.Empty(); break; case ListenerType.CreateOnFlush: - eventListeners.PersistOnFlushEventListeners = new IPersistEventListener[] { }; + eventListeners.PersistOnFlushEventListeners = Array.Empty(); break; case ListenerType.Delete: - eventListeners.DeleteEventListeners = new IDeleteEventListener[] { }; + eventListeners.DeleteEventListeners = Array.Empty(); break; case ListenerType.DirtyCheck: - eventListeners.DirtyCheckEventListeners = new IDirtyCheckEventListener[] { }; + eventListeners.DirtyCheckEventListeners = Array.Empty(); break; case ListenerType.Evict: - eventListeners.EvictEventListeners = new IEvictEventListener[] { }; + eventListeners.EvictEventListeners = Array.Empty(); break; case ListenerType.Flush: - eventListeners.FlushEventListeners = new IFlushEventListener[] { }; + eventListeners.FlushEventListeners = Array.Empty(); break; case ListenerType.FlushEntity: - eventListeners.FlushEntityEventListeners = new IFlushEntityEventListener[] { }; + eventListeners.FlushEntityEventListeners = Array.Empty(); break; case ListenerType.Load: - eventListeners.LoadEventListeners = new ILoadEventListener[] { }; + eventListeners.LoadEventListeners = Array.Empty(); break; case ListenerType.LoadCollection: - eventListeners.InitializeCollectionEventListeners = new IInitializeCollectionEventListener[] { }; + eventListeners.InitializeCollectionEventListeners = Array.Empty(); break; case ListenerType.Lock: - eventListeners.LockEventListeners = new ILockEventListener[] { }; + eventListeners.LockEventListeners = Array.Empty(); break; case ListenerType.Refresh: - eventListeners.RefreshEventListeners = new IRefreshEventListener[] { }; + eventListeners.RefreshEventListeners = Array.Empty(); break; case ListenerType.Replicate: - eventListeners.ReplicateEventListeners = new IReplicateEventListener[] { }; + eventListeners.ReplicateEventListeners = Array.Empty(); break; case ListenerType.SaveUpdate: - eventListeners.SaveOrUpdateEventListeners = new ISaveOrUpdateEventListener[] { }; + eventListeners.SaveOrUpdateEventListeners = Array.Empty(); break; case ListenerType.Save: - eventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[] { }; + eventListeners.SaveEventListeners = Array.Empty(); break; case ListenerType.PreUpdate: - eventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { }; + eventListeners.PreUpdateEventListeners = Array.Empty(); break; case ListenerType.Update: - eventListeners.UpdateEventListeners = new ISaveOrUpdateEventListener[] { }; + eventListeners.UpdateEventListeners = Array.Empty(); break; case ListenerType.PreLoad: - eventListeners.PreLoadEventListeners = new IPreLoadEventListener[] { }; + eventListeners.PreLoadEventListeners = Array.Empty(); break; case ListenerType.PreDelete: - eventListeners.PreDeleteEventListeners = new IPreDeleteEventListener[] { }; + eventListeners.PreDeleteEventListeners = Array.Empty(); break; case ListenerType.PreInsert: - eventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { }; + eventListeners.PreInsertEventListeners = Array.Empty(); break; case ListenerType.PostLoad: - eventListeners.PostLoadEventListeners = new IPostLoadEventListener[] { }; + eventListeners.PostLoadEventListeners = Array.Empty(); break; case ListenerType.PostInsert: - eventListeners.PostInsertEventListeners = new IPostInsertEventListener[] { }; + eventListeners.PostInsertEventListeners = Array.Empty(); break; case ListenerType.PostUpdate: - eventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[] { }; + eventListeners.PostUpdateEventListeners = Array.Empty(); break; case ListenerType.PostDelete: - eventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[] { }; + eventListeners.PostDeleteEventListeners = Array.Empty(); break; case ListenerType.PostCommitUpdate: - eventListeners.PostCommitUpdateEventListeners = new IPostUpdateEventListener[] { }; + eventListeners.PostCommitUpdateEventListeners = Array.Empty(); break; case ListenerType.PostCommitInsert: - eventListeners.PostCommitInsertEventListeners = new IPostInsertEventListener[] { }; + eventListeners.PostCommitInsertEventListeners = Array.Empty(); break; case ListenerType.PostCommitDelete: - eventListeners.PostCommitDeleteEventListeners = new IPostDeleteEventListener[] { }; + eventListeners.PostCommitDeleteEventListeners = Array.Empty(); break; case ListenerType.PreCollectionRecreate: - eventListeners.PreCollectionRecreateEventListeners = new IPreCollectionRecreateEventListener[] { }; + eventListeners.PreCollectionRecreateEventListeners = Array.Empty(); break; case ListenerType.PreCollectionRemove: - eventListeners.PreCollectionRemoveEventListeners = new IPreCollectionRemoveEventListener[] { }; + eventListeners.PreCollectionRemoveEventListeners = Array.Empty(); break; case ListenerType.PreCollectionUpdate: - eventListeners.PreCollectionUpdateEventListeners = new IPreCollectionUpdateEventListener[] { }; + eventListeners.PreCollectionUpdateEventListeners = Array.Empty(); break; case ListenerType.PostCollectionRecreate: - eventListeners.PostCollectionRecreateEventListeners = new IPostCollectionRecreateEventListener[] { }; + eventListeners.PostCollectionRecreateEventListeners = Array.Empty(); break; case ListenerType.PostCollectionRemove: - eventListeners.PostCollectionRemoveEventListeners = new IPostCollectionRemoveEventListener[] { }; + eventListeners.PostCollectionRemoveEventListeners = Array.Empty(); break; case ListenerType.PostCollectionUpdate: - eventListeners.PostCollectionUpdateEventListeners = new IPostCollectionUpdateEventListener[] { }; + eventListeners.PostCollectionUpdateEventListeners = Array.Empty(); break; default: log.Warn("Unrecognized listener type [{0}]", type); @@ -2310,7 +2310,7 @@ public void AppendListeners(ListenerType type, object[] listeners) private static T[] AppendListeners(T[] existing, T[] listenersToAdd) { - var list = new List(existing ?? new T[0]); + var list = new List(existing ?? Array.Empty()); list.AddRange(listenersToAdd); return list.ToArray(); } diff --git a/src/NHibernate/Cfg/MappingSchema/HbmAny.cs b/src/NHibernate/Cfg/MappingSchema/HbmAny.cs index 5c5f76edc1f..f22d61bf05d 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmAny.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmAny.cs @@ -34,7 +34,7 @@ public bool IsLazyProperty protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -76,7 +76,7 @@ public ICollection MetaValues { get { - return metavalue ?? new HbmMetaValue[0]; + return metavalue ?? Array.Empty(); } } diff --git a/src/NHibernate/Cfg/MappingSchema/HbmArray.cs b/src/NHibernate/Cfg/MappingSchema/HbmArray.cs index aceda97b908..45637cbbd28 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmArray.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmArray.cs @@ -43,7 +43,7 @@ public string Cascade protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmBag.cs b/src/NHibernate/Cfg/MappingSchema/HbmBag.cs index 563df804245..9fac439a9cf 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmBag.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmBag.cs @@ -43,7 +43,7 @@ public string Cascade protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -175,7 +175,7 @@ public bool? Generic [XmlIgnore] public IEnumerable Filters { - get { return filter ?? new HbmFilter[0]; } + get { return filter ?? Array.Empty(); } } public HbmKey Key diff --git a/src/NHibernate/Cfg/MappingSchema/HbmClass.cs b/src/NHibernate/Cfg/MappingSchema/HbmClass.cs index 4189fc4aee4..efe9cc228bd 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmClass.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmClass.cs @@ -30,32 +30,32 @@ public HbmTimestamp Timestamp [XmlIgnore] public IEnumerable Joins { - get { return Items1 != null ? Items1.OfType(): new HbmJoin[0]; } + get { return Items1 != null ? Items1.OfType(): Array.Empty(); } } [XmlIgnore] public IEnumerable Subclasses { - get { return Items1 != null ? Items1.OfType() : new HbmSubclass[0]; } + get { return Items1 != null ? Items1.OfType() : Array.Empty(); } } [XmlIgnore] public IEnumerable JoinedSubclasses { - get { return Items1 != null ? Items1.OfType() : new HbmJoinedSubclass[0]; } + get { return Items1 != null ? Items1.OfType() : Array.Empty(); } } [XmlIgnore] public IEnumerable UnionSubclasses { - get { return Items1 != null ? Items1.OfType() : new HbmUnionSubclass[0]; } + get { return Items1 != null ? Items1.OfType() : Array.Empty(); } } #region Implementation of IEntityMapping protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } public string EntityName @@ -85,7 +85,7 @@ public bool? UseLazy public HbmTuplizer[] Tuplizers { - get { return tuplizer ?? new HbmTuplizer[0]; } + get { return tuplizer ?? Array.Empty(); } } public bool DynamicUpdate @@ -120,7 +120,7 @@ public bool? IsAbstract public HbmSynchronize[] Synchronize { - get { return synchronize ?? new HbmSynchronize[0]; } + get { return synchronize ?? Array.Empty(); } } #endregion @@ -171,7 +171,7 @@ public string Subselect [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast(): new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast(): Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmComponent.cs b/src/NHibernate/Cfg/MappingSchema/HbmComponent.cs index 4431bd27cd9..44acc41d84e 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmComponent.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmComponent.cs @@ -51,7 +51,7 @@ public bool OptimisticLock [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion @@ -60,7 +60,7 @@ public IEnumerable Properties protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmCompositeElement.cs b/src/NHibernate/Cfg/MappingSchema/HbmCompositeElement.cs index 1695e3fc8fc..aac2748a7c8 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmCompositeElement.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmCompositeElement.cs @@ -35,7 +35,7 @@ public string Name protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -45,7 +45,7 @@ protected override HbmMeta[] Metadatas [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmCompositeIndex.cs b/src/NHibernate/Cfg/MappingSchema/HbmCompositeIndex.cs index 096c5e27ad9..b510ec7bf42 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmCompositeIndex.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmCompositeIndex.cs @@ -12,7 +12,7 @@ public partial class HbmCompositeIndex: IComponentMapping [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmCompositeMapKey.cs b/src/NHibernate/Cfg/MappingSchema/HbmCompositeMapKey.cs index 8c6bbe852d5..1c8af1d7a6e 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmCompositeMapKey.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmCompositeMapKey.cs @@ -12,7 +12,7 @@ public partial class HbmCompositeMapKey: IComponentMapping [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmDynamicComponent.cs b/src/NHibernate/Cfg/MappingSchema/HbmDynamicComponent.cs index 1c0d921a58e..238a755f985 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmDynamicComponent.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmDynamicComponent.cs @@ -51,7 +51,7 @@ public bool OptimisticLock [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion @@ -60,7 +60,7 @@ public IEnumerable Properties protected override HbmMeta[] Metadatas { - get { return new HbmMeta[0]; } + get { return Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmFilterDef.cs b/src/NHibernate/Cfg/MappingSchema/HbmFilterDef.cs index 61c74ca9b8b..b87a7f34c31 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmFilterDef.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmFilterDef.cs @@ -1,3 +1,5 @@ +using System; + namespace NHibernate.Cfg.MappingSchema { partial class HbmFilterDef : HbmBase @@ -9,7 +11,7 @@ public string GetDefaultCondition() public HbmFilterParam[] ListParameters() { - return Items ?? new HbmFilterParam[0]; + return Items ?? Array.Empty(); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/MappingSchema/HbmId.cs b/src/NHibernate/Cfg/MappingSchema/HbmId.cs index c7ef2dbbc37..cb4a7476311 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmId.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmId.cs @@ -36,7 +36,7 @@ private IEnumerable AsColumns() protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmIdbag.cs b/src/NHibernate/Cfg/MappingSchema/HbmIdbag.cs index a888c8846a8..e4916d44220 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmIdbag.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmIdbag.cs @@ -43,7 +43,7 @@ public string Cascade protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -175,7 +175,7 @@ public bool? Generic [XmlIgnore] public IEnumerable Filters { - get { return filter ?? new HbmFilter[0]; } + get { return filter ?? Array.Empty(); } } public HbmKey Key diff --git a/src/NHibernate/Cfg/MappingSchema/HbmIndexManyToAny.cs b/src/NHibernate/Cfg/MappingSchema/HbmIndexManyToAny.cs index 52113fc66f2..bc39194e682 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmIndexManyToAny.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmIndexManyToAny.cs @@ -40,7 +40,7 @@ public string MetaType public ICollection MetaValues { - get { return new HbmMetaValue[0]; } + get { return Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmJoin.cs b/src/NHibernate/Cfg/MappingSchema/HbmJoin.cs index ff20e521dc6..0c640ac61f2 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmJoin.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmJoin.cs @@ -44,7 +44,7 @@ public string Subselect [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmJoinedSubclass.cs b/src/NHibernate/Cfg/MappingSchema/HbmJoinedSubclass.cs index ba7c4759adf..09f0d563699 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmJoinedSubclass.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmJoinedSubclass.cs @@ -10,14 +10,14 @@ public partial class HbmJoinedSubclass : AbstractDecoratable, IEntityMapping [XmlIgnore] public IEnumerable JoinedSubclasses { - get { return joinedsubclass1 ?? new HbmJoinedSubclass[0]; } + get { return joinedsubclass1 ?? Array.Empty(); } } #region Overrides of AbstractDecoratable protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -51,7 +51,7 @@ public bool? UseLazy public HbmTuplizer[] Tuplizers { - get { return tuplizer ?? new HbmTuplizer[0]; } + get { return tuplizer ?? Array.Empty(); } } public bool DynamicUpdate { @@ -85,7 +85,7 @@ public bool? IsAbstract public HbmSynchronize[] Synchronize { - get { return synchronize ?? new HbmSynchronize[0]; } + get { return synchronize ?? Array.Empty(); } } #endregion @@ -127,7 +127,7 @@ public string Subselect [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmKeyManyToOne.cs b/src/NHibernate/Cfg/MappingSchema/HbmKeyManyToOne.cs index d50fe45fde4..f5d68ff7282 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmKeyManyToOne.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmKeyManyToOne.cs @@ -36,7 +36,7 @@ private IEnumerable AsColumns() protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmKeyProperty.cs b/src/NHibernate/Cfg/MappingSchema/HbmKeyProperty.cs index 45bf3c05e02..d6bd5217f4d 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmKeyProperty.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmKeyProperty.cs @@ -46,7 +46,7 @@ public HbmType Type protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmList.cs b/src/NHibernate/Cfg/MappingSchema/HbmList.cs index e470455fb22..7cc199772e6 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmList.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmList.cs @@ -43,7 +43,7 @@ public string Cascade protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -189,7 +189,7 @@ public bool? Generic [XmlIgnore] public IEnumerable Filters { - get { return filter ?? new HbmFilter[0]; } + get { return filter ?? Array.Empty(); } } public HbmKey Key diff --git a/src/NHibernate/Cfg/MappingSchema/HbmManyToAny.cs b/src/NHibernate/Cfg/MappingSchema/HbmManyToAny.cs index c6ce9630e69..bad08a8ee94 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmManyToAny.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmManyToAny.cs @@ -43,7 +43,7 @@ public ICollection MetaValues { get { - return metavalue ?? new HbmMetaValue[0]; + return metavalue ?? Array.Empty(); } } diff --git a/src/NHibernate/Cfg/MappingSchema/HbmManyToOne.cs b/src/NHibernate/Cfg/MappingSchema/HbmManyToOne.cs index fd4e69d021c..d63ab705da1 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmManyToOne.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmManyToOne.cs @@ -35,7 +35,7 @@ public bool OptimisticLock protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmMap.cs b/src/NHibernate/Cfg/MappingSchema/HbmMap.cs index 76c06e7f279..1a291ec309a 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmMap.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmMap.cs @@ -43,7 +43,7 @@ public string Cascade protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -175,7 +175,7 @@ public bool? Generic [XmlIgnore] public IEnumerable Filters { - get { return filter ?? new HbmFilter[0]; } + get { return filter ?? Array.Empty(); } } public HbmKey Key diff --git a/src/NHibernate/Cfg/MappingSchema/HbmMapping.cs b/src/NHibernate/Cfg/MappingSchema/HbmMapping.cs index 77be384f319..3cf5b72f465 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmMapping.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmMapping.cs @@ -1,3 +1,4 @@ +using System; using System.Linq; namespace NHibernate.Cfg.MappingSchema @@ -6,62 +7,62 @@ partial class HbmMapping : AbstractDecoratable { public HbmDatabaseObject[] DatabaseObjects { - get { return databaseobject ?? new HbmDatabaseObject[0]; } + get { return databaseobject ?? Array.Empty(); } } public HbmFilterDef[] FilterDefinitions { - get { return filterdef ?? new HbmFilterDef[0]; } + get { return filterdef ?? Array.Empty(); } } public HbmResultSet[] ResultSets { - get { return resultset ?? new HbmResultSet[0]; } + get { return resultset ?? Array.Empty(); } } public HbmTypedef[] TypeDefinitions { - get { return typedef ?? new HbmTypedef[0]; } + get { return typedef ?? Array.Empty(); } } public HbmImport[] Imports { - get { return import ?? new HbmImport[0]; } + get { return import ?? Array.Empty(); } } protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } public HbmClass[] RootClasses { - get { return Items != null ? Items.OfType().ToArray():new HbmClass[0]; } + get { return Items != null ? Items.OfType().ToArray():Array.Empty(); } } public HbmSubclass[] SubClasses { - get { return Items != null ? Items.OfType().ToArray(): new HbmSubclass[0]; } + get { return Items != null ? Items.OfType().ToArray(): Array.Empty(); } } public HbmJoinedSubclass[] JoinedSubclasses { - get { return Items != null ? Items.OfType().ToArray(): new HbmJoinedSubclass[0]; } + get { return Items != null ? Items.OfType().ToArray(): Array.Empty(); } } public HbmUnionSubclass[] UnionSubclasses { - get { return Items != null ? Items.OfType().ToArray(): new HbmUnionSubclass[0]; } + get { return Items != null ? Items.OfType().ToArray(): Array.Empty(); } } public HbmQuery[] HqlQueries { - get { return Items1 != null ? Items1.OfType().ToArray() : new HbmQuery[0]; } + get { return Items1 != null ? Items1.OfType().ToArray() : Array.Empty(); } } public HbmSqlQuery[] SqlQueries { - get { return Items1 != null ? Items1.OfType().ToArray() : new HbmSqlQuery[0]; } + get { return Items1 != null ? Items1.OfType().ToArray() : Array.Empty(); } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/MappingSchema/HbmNaturalId.cs b/src/NHibernate/Cfg/MappingSchema/HbmNaturalId.cs index ae07b940a49..b2023f8982b 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmNaturalId.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmNaturalId.cs @@ -12,7 +12,7 @@ public partial class HbmNaturalId: IPropertiesContainerMapping [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmNestedCompositeElement.cs b/src/NHibernate/Cfg/MappingSchema/HbmNestedCompositeElement.cs index b229b51d6eb..a941789f592 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmNestedCompositeElement.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmNestedCompositeElement.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; @@ -11,7 +12,7 @@ public partial class HbmNestedCompositeElement : AbstractDecoratable, IEntityPro [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion @@ -54,7 +55,7 @@ public bool OptimisticLock protected override HbmMeta[] Metadatas { - get { return new HbmMeta[0];} + get { return Array.Empty();} } #endregion @@ -64,4 +65,4 @@ public bool IsLazyProperty get { return false; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/MappingSchema/HbmOneToOne.cs b/src/NHibernate/Cfg/MappingSchema/HbmOneToOne.cs index b9bdb7dac99..c06fa7ea43c 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmOneToOne.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmOneToOne.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Xml.Serialization; @@ -28,7 +29,7 @@ public bool OptimisticLock protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -84,4 +85,4 @@ public bool IsLazyProperty get { return Lazy == HbmLaziness.Proxy; } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/MappingSchema/HbmPrimitiveArray.cs b/src/NHibernate/Cfg/MappingSchema/HbmPrimitiveArray.cs index 92b964003c1..63cde7dbada 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmPrimitiveArray.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmPrimitiveArray.cs @@ -43,7 +43,7 @@ public string Cascade protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmProperties.cs b/src/NHibernate/Cfg/MappingSchema/HbmProperties.cs index c6a2fb2d86e..3f686b99f1c 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmProperties.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmProperties.cs @@ -51,7 +51,7 @@ public bool OptimisticLock [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion @@ -60,7 +60,7 @@ public IEnumerable Properties protected override HbmMeta[] Metadatas { - get { return new HbmMeta[0]; } + get { return Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmProperty.cs b/src/NHibernate/Cfg/MappingSchema/HbmProperty.cs index 000d04daacd..3a0efaf8f02 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmProperty.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmProperty.cs @@ -35,7 +35,7 @@ public bool OptimisticLock protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmSet.cs b/src/NHibernate/Cfg/MappingSchema/HbmSet.cs index 041f2793b7c..530b8d0f537 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmSet.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmSet.cs @@ -43,7 +43,7 @@ public string Cascade protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -175,7 +175,7 @@ public bool? Generic [XmlIgnore] public IEnumerable Filters { - get { return filter ?? new HbmFilter[0]; } + get { return filter ?? Array.Empty(); } } public HbmKey Key diff --git a/src/NHibernate/Cfg/MappingSchema/HbmSubclass.cs b/src/NHibernate/Cfg/MappingSchema/HbmSubclass.cs index e82a66f80a2..9de2df4990a 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmSubclass.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmSubclass.cs @@ -10,20 +10,20 @@ public partial class HbmSubclass : AbstractDecoratable, IEntityMapping, IEntityD [XmlIgnore] public IEnumerable Joins { - get { return join ?? new HbmJoin[0]; } + get { return join ?? Array.Empty(); } } [XmlIgnore] public IEnumerable Subclasses { - get { return subclass1 ?? new HbmSubclass[0]; } + get { return subclass1 ?? Array.Empty(); } } #region Overrides of AbstractDecoratable protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -57,7 +57,7 @@ public bool? UseLazy public HbmTuplizer[] Tuplizers { - get { return tuplizer ?? new HbmTuplizer[0]; } + get { return tuplizer ?? Array.Empty(); } } public bool DynamicUpdate @@ -92,7 +92,7 @@ public bool? IsAbstract public HbmSynchronize[] Synchronize { - get { return synchronize ?? new HbmSynchronize[0]; } + get { return synchronize ?? Array.Empty(); } } #endregion @@ -140,7 +140,7 @@ public string Subselect [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmTimestamp.cs b/src/NHibernate/Cfg/MappingSchema/HbmTimestamp.cs index ea0b2585d31..feb0a3923ec 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmTimestamp.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmTimestamp.cs @@ -8,7 +8,7 @@ partial class HbmTimestamp : AbstractDecoratable, IColumnsMapping { protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #region Implementation of IColumnsMapping diff --git a/src/NHibernate/Cfg/MappingSchema/HbmUnionSubclass.cs b/src/NHibernate/Cfg/MappingSchema/HbmUnionSubclass.cs index b5142cf074e..c05d39ff156 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmUnionSubclass.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmUnionSubclass.cs @@ -10,14 +10,14 @@ public partial class HbmUnionSubclass : AbstractDecoratable, IEntityMapping [XmlIgnore] public IEnumerable UnionSubclasses { - get { return unionsubclass1 ?? new HbmUnionSubclass[0]; } + get { return unionsubclass1 ?? Array.Empty(); } } #region Overrides of AbstractDecoratable protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #endregion @@ -51,7 +51,7 @@ public bool? UseLazy public HbmTuplizer[] Tuplizers { - get { return tuplizer ?? new HbmTuplizer[0]; } + get { return tuplizer ?? Array.Empty(); } } public bool DynamicUpdate @@ -86,7 +86,7 @@ public bool? IsAbstract public HbmSynchronize[] Synchronize { - get { return synchronize ?? new HbmSynchronize[0]; } + get { return synchronize ?? Array.Empty(); } } #endregion @@ -128,7 +128,7 @@ public string Subselect [XmlIgnore] public IEnumerable Properties { - get { return Items != null ? Items.Cast() : new IEntityPropertyMapping[0]; } + get { return Items != null ? Items.Cast() : Array.Empty(); } } #endregion diff --git a/src/NHibernate/Cfg/MappingSchema/HbmVersion.cs b/src/NHibernate/Cfg/MappingSchema/HbmVersion.cs index 1b5495103ce..0013af1ccc6 100644 --- a/src/NHibernate/Cfg/MappingSchema/HbmVersion.cs +++ b/src/NHibernate/Cfg/MappingSchema/HbmVersion.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Xml.Serialization; @@ -7,7 +8,7 @@ partial class HbmVersion : AbstractDecoratable, IColumnsMapping { protected override HbmMeta[] Metadatas { - get { return meta ?? new HbmMeta[0]; } + get { return meta ?? Array.Empty(); } } #region Implementation of IColumnsMapping @@ -35,4 +36,4 @@ private IEnumerable AsColumns() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/XmlHbmBinding/ClassCompositeIdBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/ClassCompositeIdBinder.cs index 60b51387610..b5d71ed5456 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/ClassCompositeIdBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/ClassCompositeIdBinder.cs @@ -90,7 +90,7 @@ private void BindComponent(System.Type reflectedClass, string path, HbmComposite } } - foreach (object item in idSchema.Items ?? new object[0]) + foreach (object item in idSchema.Items ?? System.Array.Empty()) { var keyManyToOneSchema = item as HbmKeyManyToOne; var keyPropertySchema = item as HbmKeyProperty; @@ -281,4 +281,4 @@ private void BindProperty(HbmKeyProperty keyPropertySchema, Property property) property.LogMapped(log); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/XmlHbmBinding/IdGeneratorBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/IdGeneratorBinder.cs index 24fce320385..96529f99a21 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/IdGeneratorBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/IdGeneratorBinder.cs @@ -52,10 +52,10 @@ private IDictionary GetGeneratorProperties(HbmGenerator generato if (mappings.PreferPooledValuesLo != null) results[Environment.PreferPooledValuesLo] = mappings.PreferPooledValuesLo; - foreach (HbmParam paramSchema in generatorMapping.param ?? new HbmParam[0]) + foreach (HbmParam paramSchema in generatorMapping.param ?? System.Array.Empty()) results[paramSchema.name] = paramSchema.GetText(); return results; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs index 7dcd61b7c73..0a255455ba5 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/MappingRootBinder.cs @@ -136,7 +136,7 @@ public void AddTypeDefs(HbmMapping mappingSchema) { string typeClass = FullQualifiedClassName(typedef.@class, mappings); string typeName = typedef.name; - IEnumerable paramIter = typedef.param ?? new HbmParam[0]; + IEnumerable paramIter = typedef.param ?? System.Array.Empty(); var parameters = new Dictionary(5); foreach (HbmParam param in paramIter) { @@ -172,4 +172,4 @@ private void AddResultSetMappingDefinitions(HbmMapping mappingSchema) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs index db6f6e06b37..9779af07b0b 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/NamedSQLQueryBinder.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using NHibernate.Cfg.MappingSchema; using NHibernate.Engine; @@ -61,7 +62,7 @@ private static IList GetSynchronizedTables(HbmSqlQuery querySchema) { IList synchronizedTables = new List(); - foreach (object item in querySchema.Items ?? new object[0]) + foreach (object item in querySchema.Items ?? Array.Empty()) { HbmSynchronize synchronizeSchema = item as HbmSynchronize; @@ -72,4 +73,4 @@ private static IList GetSynchronizedTables(HbmSqlQuery querySchema) return synchronizedTables; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs b/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs index f85fd971216..f168868b621 100644 --- a/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs +++ b/src/NHibernate/Cfg/XmlHbmBinding/ResultSetMappingBinder.cs @@ -7,6 +7,7 @@ using NHibernate.Mapping; using NHibernate.Type; using NHibernate.Util; +using Array = System.Array; namespace NHibernate.Cfg.XmlHbmBinding { @@ -32,7 +33,7 @@ private ResultSetMappingDefinition Create(string name, object[] items) ResultSetMappingDefinition definition = new ResultSetMappingDefinition(name); int count = 0; - foreach (object item in items ?? new object[0]) + foreach (object item in items ?? System.Array.Empty()) { count += 1; INativeSQLQueryReturn queryReturn = CreateQueryReturn(item, count); @@ -166,7 +167,7 @@ private IDictionary BindPropertyResults(string alias, HbmRetur List properties = new List(); List propertyNames = new List(); - foreach (HbmReturnProperty returnPropertySchema in returnProperties ?? new HbmReturnProperty[0]) + foreach (HbmReturnProperty returnPropertySchema in returnProperties ?? Array.Empty()) { string name = returnPropertySchema.name; if (pc == null || name.IndexOf('.') == -1) @@ -320,7 +321,7 @@ private static List GetResultColumns(HbmReturnProperty returnPropertySch if (column != null) allResultColumns.Add(column); - foreach (HbmReturnColumn returnColumnSchema in returnPropertySchema.returncolumn ?? new HbmReturnColumn[0]) + foreach (HbmReturnColumn returnColumnSchema in returnPropertySchema.returncolumn ?? Array.Empty()) allResultColumns.Add(Unquote(returnColumnSchema.name)); return allResultColumns; @@ -382,4 +383,4 @@ private string GetClassNameWithoutAssembly(string unqualifiedName) return TypeNameParser.Parse(unqualifiedName, mappings.DefaultNamespace, mappings.DefaultAssembly).Type; } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Criterion/AbstractEmptinessExpression.cs b/src/NHibernate/Criterion/AbstractEmptinessExpression.cs index d8d978ed662..bd0f5ed45fd 100644 --- a/src/NHibernate/Criterion/AbstractEmptinessExpression.cs +++ b/src/NHibernate/Criterion/AbstractEmptinessExpression.cs @@ -11,7 +11,7 @@ namespace NHibernate.Criterion [Serializable] public abstract class AbstractEmptinessExpression : AbstractCriterion { - private readonly TypedValue[] NO_VALUES = new TypedValue[0]; + private readonly TypedValue[] NO_VALUES = Array.Empty(); private readonly string propertyName; protected abstract bool ExcludeEmpty { get; } diff --git a/src/NHibernate/Criterion/Expression.cs b/src/NHibernate/Criterion/Expression.cs index 21f4ef6e070..2233f631313 100644 --- a/src/NHibernate/Criterion/Expression.cs +++ b/src/NHibernate/Criterion/Expression.cs @@ -1,3 +1,4 @@ +using System; using NHibernate.SqlCommand; using NHibernate.Type; using NHibernate.Util; @@ -59,7 +60,7 @@ public static AbstractCriterion Sql(string sql, object[] values, IType[] types) /// public static AbstractCriterion Sql(SqlString sql) { - return Sql(sql, ArrayHelper.EmptyObjectArray, TypeHelper.EmptyTypeArray); + return Sql(sql, Array.Empty(), TypeHelper.EmptyTypeArray); } /// @@ -69,7 +70,7 @@ public static AbstractCriterion Sql(SqlString sql) /// public static AbstractCriterion Sql(string sql) { - return Sql(sql, ArrayHelper.EmptyObjectArray, TypeHelper.EmptyTypeArray); + return Sql(sql, Array.Empty(), TypeHelper.EmptyTypeArray); } } } diff --git a/src/NHibernate/Criterion/GroupedProjection.cs b/src/NHibernate/Criterion/GroupedProjection.cs index 6cf9c24c8a2..f037160f32e 100644 --- a/src/NHibernate/Criterion/GroupedProjection.cs +++ b/src/NHibernate/Criterion/GroupedProjection.cs @@ -49,7 +49,7 @@ public string[] GetColumnAliases(string alias, int position, ICriteria criteria, public virtual string[] Aliases { - get { return new string[] {}; } + get { return Array.Empty(); } } public virtual bool IsGrouped diff --git a/src/NHibernate/Criterion/NotNullExpression.cs b/src/NHibernate/Criterion/NotNullExpression.cs index 38bea97346d..f08fc7bdd30 100644 --- a/src/NHibernate/Criterion/NotNullExpression.cs +++ b/src/NHibernate/Criterion/NotNullExpression.cs @@ -22,7 +22,7 @@ public NotNullExpression(IProjection projection) _projection = projection; } - private static readonly TypedValue[] NoValues = new TypedValue[0]; + private static readonly TypedValue[] NoValues = Array.Empty(); /// /// Initialize a new instance of the class for a named diff --git a/src/NHibernate/Criterion/NullExpression.cs b/src/NHibernate/Criterion/NullExpression.cs index 1c073f49694..cbd0a955575 100644 --- a/src/NHibernate/Criterion/NullExpression.cs +++ b/src/NHibernate/Criterion/NullExpression.cs @@ -12,7 +12,7 @@ public class NullExpression : AbstractCriterion { private readonly string _propertyName; private readonly IProjection _projection; - private static readonly TypedValue[] NoValues = new TypedValue[0]; + private static readonly TypedValue[] NoValues = Array.Empty(); /// /// Initializes a new instance of the class. diff --git a/src/NHibernate/Criterion/Order.cs b/src/NHibernate/Criterion/Order.cs index 83ac468d375..6f1e466a0e7 100644 --- a/src/NHibernate/Criterion/Order.cs +++ b/src/NHibernate/Criterion/Order.cs @@ -130,7 +130,7 @@ public TypedValue[] GetTypedValues(ICriteria criteria, ICriteriaQuery criteriaQu if (projection != null) return projection.GetTypedValues(criteria, criteriaQuery); - return new TypedValue[0]; // not using parameters for ORDER BY columns + return Array.Empty(); // not using parameters for ORDER BY columns } public Order IgnoreCase() diff --git a/src/NHibernate/Criterion/PropertyExpression.cs b/src/NHibernate/Criterion/PropertyExpression.cs index d7db44e7ee7..5453b982c75 100644 --- a/src/NHibernate/Criterion/PropertyExpression.cs +++ b/src/NHibernate/Criterion/PropertyExpression.cs @@ -13,7 +13,7 @@ namespace NHibernate.Criterion [Serializable] public abstract class PropertyExpression : AbstractCriterion { - private static readonly TypedValue[] NoTypedValues = new TypedValue[0]; + private static readonly TypedValue[] NoTypedValues = Array.Empty(); private readonly string _lhsPropertyName; private readonly string _rhsPropertyName; private readonly IProjection _lhsProjection; diff --git a/src/NHibernate/Criterion/SQLProjection.cs b/src/NHibernate/Criterion/SQLProjection.cs index bb257490dc5..72359e00a83 100644 --- a/src/NHibernate/Criterion/SQLProjection.cs +++ b/src/NHibernate/Criterion/SQLProjection.cs @@ -81,7 +81,7 @@ public bool IsAggregate /// public TypedValue[] GetTypedValues(ICriteria criteria, ICriteriaQuery criteriaQuery) { - return new TypedValue[0]; + return Array.Empty(); } public IType[] GetTypes(string alias, ICriteria crit, ICriteriaQuery criteriaQuery) diff --git a/src/NHibernate/Criterion/SimpleProjection.cs b/src/NHibernate/Criterion/SimpleProjection.cs index 3521d5b7476..9304c4c4222 100644 --- a/src/NHibernate/Criterion/SimpleProjection.cs +++ b/src/NHibernate/Criterion/SimpleProjection.cs @@ -67,7 +67,7 @@ public virtual string[] Aliases /// public virtual TypedValue[] GetTypedValues(ICriteria criteria, ICriteriaQuery criteriaQuery) { - return new TypedValue[0]; + return Array.Empty(); } public abstract SqlString ToSqlString(ICriteria criteria, int position, ICriteriaQuery criteriaQuery); diff --git a/src/NHibernate/Driver/FirebirdClientDriver.cs b/src/NHibernate/Driver/FirebirdClientDriver.cs index 751dbd1630c..81eb9c241ee 100644 --- a/src/NHibernate/Driver/FirebirdClientDriver.cs +++ b/src/NHibernate/Driver/FirebirdClientDriver.cs @@ -160,7 +160,7 @@ public void ClearPool(string connectionString) return; } - _clearAllPools.Invoke(null, new object[0]); + _clearAllPools.Invoke(null, Array.Empty()); } /// diff --git a/src/NHibernate/Engine/QueryParameters.cs b/src/NHibernate/Engine/QueryParameters.cs index 6af67a3d685..9417b0b2346 100644 --- a/src/NHibernate/Engine/QueryParameters.cs +++ b/src/NHibernate/Engine/QueryParameters.cs @@ -21,7 +21,7 @@ public sealed class QueryParameters private bool readOnly; - public QueryParameters() : this(TypeHelper.EmptyTypeArray, ArrayHelper.EmptyObjectArray) {} + public QueryParameters() : this(TypeHelper.EmptyTypeArray, Array.Empty()) {} public QueryParameters(IType[] positionalParameterTypes, object[] postionalParameterValues, object optionalObject, string optionalEntityName, object optionalObjectId) : this(positionalParameterTypes, postionalParameterValues) @@ -50,7 +50,7 @@ public QueryParameters(IType[] positionalParameterTypes, object[] positionalPara public QueryParameters(IDictionary namedParameters, IDictionary lockModes, RowSelection rowSelection, bool isReadOnlyInitialized, bool readOnly, bool cacheable, string cacheRegion, string comment, bool isLookupByNaturalKey, IResultTransformer transformer) : this( - TypeHelper.EmptyTypeArray, ArrayHelper.EmptyObjectArray, namedParameters, lockModes, rowSelection, isReadOnlyInitialized, readOnly, cacheable, cacheRegion, comment, null, + TypeHelper.EmptyTypeArray, Array.Empty(), namedParameters, lockModes, rowSelection, isReadOnlyInitialized, readOnly, cacheable, cacheRegion, comment, null, transformer) { // used by CriteriaTranslator @@ -61,8 +61,8 @@ public QueryParameters(IType[] positionalParameterTypes, object[] positionalPara IDictionary lockModes, RowSelection rowSelection, bool isReadOnlyInitialized, bool readOnly, bool cacheable, string cacheRegion, string comment, object[] collectionKeys, IResultTransformer transformer) { - PositionalParameterTypes = positionalParameterTypes ?? new IType[0]; - PositionalParameterValues = positionalParameterValues ?? new object[0]; + PositionalParameterTypes = positionalParameterTypes ?? Array.Empty(); + PositionalParameterValues = positionalParameterValues ?? Array.Empty(); NamedParameters = namedParameters ?? new Dictionary(1); LockModes = lockModes; RowSelection = rowSelection; diff --git a/src/NHibernate/Engine/UnsavedValueFactory.cs b/src/NHibernate/Engine/UnsavedValueFactory.cs index 1f9b3cfed4c..38735c85dc4 100644 --- a/src/NHibernate/Engine/UnsavedValueFactory.cs +++ b/src/NHibernate/Engine/UnsavedValueFactory.cs @@ -7,7 +7,7 @@ namespace NHibernate.Engine { public static class UnsavedValueFactory { - private static readonly object[] NoParameters = new object[0]; + private static readonly object[] NoParameters = Array.Empty(); private static object Instantiate(ConstructorInfo constructor) { diff --git a/src/NHibernate/Event/Default/DefaultFlushEntityEventListener.cs b/src/NHibernate/Event/Default/DefaultFlushEntityEventListener.cs index 43ad4f10064..28b4654ebbf 100644 --- a/src/NHibernate/Event/Default/DefaultFlushEntityEventListener.cs +++ b/src/NHibernate/Event/Default/DefaultFlushEntityEventListener.cs @@ -258,7 +258,7 @@ private bool ScheduleUpdate(FlushEntityEvent @event) { throw new AssertionFailure("dirty, but no dirty properties"); } - dirtyProperties = ArrayHelper.EmptyIntArray; + dirtyProperties = Array.Empty(); } // check nullability but do not perform command execute diff --git a/src/NHibernate/Event/EventListeners.cs b/src/NHibernate/Event/EventListeners.cs index 8081c031512..594df45e515 100644 --- a/src/NHibernate/Event/EventListeners.cs +++ b/src/NHibernate/Event/EventListeners.cs @@ -99,33 +99,33 @@ static EventListeners() private IPreLoadEventListener[] preLoadEventListeners = new IPreLoadEventListener[] {new DefaultPreLoadEventListener()}; - private IPreDeleteEventListener[] preDeleteEventListeners = new IPreDeleteEventListener[] {}; - private IPreUpdateEventListener[] preUpdateEventListeners = new IPreUpdateEventListener[] {}; - private IPreInsertEventListener[] preInsertEventListeners = new IPreInsertEventListener[] {}; - private IPostDeleteEventListener[] postDeleteEventListeners = new IPostDeleteEventListener[] {}; - private IPostUpdateEventListener[] postUpdateEventListeners = new IPostUpdateEventListener[] {}; - private IPostInsertEventListener[] postInsertEventListeners = new IPostInsertEventListener[] {}; - private IPostDeleteEventListener[] postCommitDeleteEventListeners = new IPostDeleteEventListener[] {}; - private IPostUpdateEventListener[] postCommitUpdateEventListeners = new IPostUpdateEventListener[] {}; - private IPostInsertEventListener[] postCommitInsertEventListeners = new IPostInsertEventListener[] {}; + private IPreDeleteEventListener[] preDeleteEventListeners = Array.Empty(); + private IPreUpdateEventListener[] preUpdateEventListeners = Array.Empty(); + private IPreInsertEventListener[] preInsertEventListeners = Array.Empty(); + private IPostDeleteEventListener[] postDeleteEventListeners = Array.Empty(); + private IPostUpdateEventListener[] postUpdateEventListeners = Array.Empty(); + private IPostInsertEventListener[] postInsertEventListeners = Array.Empty(); + private IPostDeleteEventListener[] postCommitDeleteEventListeners = Array.Empty(); + private IPostUpdateEventListener[] postCommitUpdateEventListeners = Array.Empty(); + private IPostInsertEventListener[] postCommitInsertEventListeners = Array.Empty(); private IPreCollectionRecreateEventListener[] preCollectionRecreateEventListeners = - new IPreCollectionRecreateEventListener[] {}; + Array.Empty(); private IPostCollectionRecreateEventListener[] postCollectionRecreateEventListeners = - new IPostCollectionRecreateEventListener[] {}; + Array.Empty(); private IPreCollectionRemoveEventListener[] preCollectionRemoveEventListeners = - new IPreCollectionRemoveEventListener[] {}; + Array.Empty(); private IPostCollectionRemoveEventListener[] postCollectionRemoveEventListeners = - new IPostCollectionRemoveEventListener[] {}; + Array.Empty(); private IPreCollectionUpdateEventListener[] preCollectionUpdateEventListeners = - new IPreCollectionUpdateEventListener[] {}; + Array.Empty(); private IPostCollectionUpdateEventListener[] postCollectionUpdateEventListeners = - new IPostCollectionUpdateEventListener[] {}; + Array.Empty(); private ISaveOrUpdateEventListener[] saveEventListeners = new ISaveOrUpdateEventListener[] {new DefaultSaveEventListener()}; diff --git a/src/NHibernate/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs b/src/NHibernate/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs index 10954da9925..a45819d7c6c 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Exec/AbstractStatementExecutor.cs @@ -197,7 +197,7 @@ protected virtual void DropTemporaryTableIfNecessary(IQueryable persister, ISess try { var commandText = new SqlString("delete from " + persister.TemporaryIdTableName); - ps = session.Batcher.PrepareCommand(CommandType.Text, commandText, new SqlType[0]); + ps = session.Batcher.PrepareCommand(CommandType.Text, commandText, Array.Empty()); session.Batcher.ExecuteNonQuery(ps); } catch (Exception t) diff --git a/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs b/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs index 35c5390d856..50c3cb3c93e 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Exec/MultiTableDeleteExecutor.cs @@ -113,7 +113,7 @@ public override int Execute(QueryParameters parameters, ISessionImplementor sess { try { - ps = session.Batcher.PrepareCommand(CommandType.Text, deletes[i], new SqlType[0]); + ps = session.Batcher.PrepareCommand(CommandType.Text, deletes[i], Array.Empty()); session.Batcher.ExecuteNonQuery(ps); } finally diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/AssignmentSpecification.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/AssignmentSpecification.cs index a56beb0a545..932d95aaaaf 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/AssignmentSpecification.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/AssignmentSpecification.cs @@ -67,7 +67,7 @@ public AssignmentSpecification(IASTNode eq, IQueryable persister) if (rhs == null) { - _hqlParameters = new IParameterSpecification[0]; + _hqlParameters = Array.Empty(); } else if (IsParam(rhs)) { diff --git a/src/NHibernate/Hql/Ast/ANTLR/Tree/ConstructorNode.cs b/src/NHibernate/Hql/Ast/ANTLR/Tree/ConstructorNode.cs index 2fe7baaca61..0759c83ad7c 100644 --- a/src/NHibernate/Hql/Ast/ANTLR/Tree/ConstructorNode.cs +++ b/src/NHibernate/Hql/Ast/ANTLR/Tree/ConstructorNode.cs @@ -137,7 +137,7 @@ private IType[] ResolveConstructorArgumentTypes() if ( argumentExpressions == null ) { // return an empty Type array - return new IType[]{}; + return Array.Empty(); } IType[] types = new IType[argumentExpressions.Length]; diff --git a/src/NHibernate/Impl/ExpressionProcessor.cs b/src/NHibernate/Impl/ExpressionProcessor.cs index f55ea8222c9..8fdb12af7a3 100644 --- a/src/NHibernate/Impl/ExpressionProcessor.cs +++ b/src/NHibernate/Impl/ExpressionProcessor.cs @@ -153,7 +153,7 @@ static ExpressionProcessor() RegisterCustomMethodCall(() => RestrictionExtensions.IsLike("", "", null, null), RestrictionExtensions.ProcessIsLikeMatchModeEscapeChar); RegisterCustomMethodCall(() => RestrictionExtensions.IsInsensitiveLike("", ""), RestrictionExtensions.ProcessIsInsensitiveLike); RegisterCustomMethodCall(() => RestrictionExtensions.IsInsensitiveLike("", "", null), RestrictionExtensions.ProcessIsInsensitiveLikeMatchMode); - RegisterCustomMethodCall(() => RestrictionExtensions.IsIn(null, new object[0]), RestrictionExtensions.ProcessIsInArray); + RegisterCustomMethodCall(() => RestrictionExtensions.IsIn(null, Array.Empty()), RestrictionExtensions.ProcessIsInArray); RegisterCustomMethodCall(() => RestrictionExtensions.IsIn(null, new List()), RestrictionExtensions.ProcessIsInCollection); RegisterCustomMethodCall(() => RestrictionExtensions.IsBetween(null, null).And(null), RestrictionExtensions.ProcessIsBetween); diff --git a/src/NHibernate/Impl/SessionImpl.cs b/src/NHibernate/Impl/SessionImpl.cs index f417e192012..5fe1c1c718a 100644 --- a/src/NHibernate/Impl/SessionImpl.cs +++ b/src/NHibernate/Impl/SessionImpl.cs @@ -515,8 +515,8 @@ public void Update(object obj, object id) } } - private static readonly object[] NoArgs = new object[0]; - private static readonly IType[] NoTypes = new IType[0]; + private static readonly object[] NoArgs = Array.Empty(); + private static readonly IType[] NoTypes = Array.Empty(); IList Find(string query, object[] values, IType[] types) { diff --git a/src/NHibernate/Linq/Clauses/NhJoinClause.cs b/src/NHibernate/Linq/Clauses/NhJoinClause.cs index 9257c15e2a2..d68926f88b3 100644 --- a/src/NHibernate/Linq/Clauses/NhJoinClause.cs +++ b/src/NHibernate/Linq/Clauses/NhJoinClause.cs @@ -22,7 +22,7 @@ public class NhJoinClause : NhClauseBase, IFromClause, IBodyClause System.Type _itemType; public NhJoinClause(string itemName, System.Type itemType, Expression fromExpression) - : this(itemName, itemType, fromExpression, new NhWithClause[0]) + : this(itemName, itemType, fromExpression, Array.Empty()) { } diff --git a/src/NHibernate/Loader/AbstractEntityJoinWalker.cs b/src/NHibernate/Loader/AbstractEntityJoinWalker.cs index 96123b59e40..1ad5ce5cc19 100644 --- a/src/NHibernate/Loader/AbstractEntityJoinWalker.cs +++ b/src/NHibernate/Loader/AbstractEntityJoinWalker.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using NHibernate.Engine; using NHibernate.Loader.Criteria; @@ -42,7 +43,7 @@ protected virtual void InitAll(SqlString whereString, SqlString orderByString, L protected void InitProjection(SqlString projectionString, SqlString whereString, SqlString orderByString, SqlString groupByString, SqlString havingString, IDictionary enabledFilters, LockMode lockMode) { WalkEntityTree(persister, Alias); - Persisters = new ILoadable[0]; + Persisters = Array.Empty(); InitStatementString(projectionString, whereString, orderByString, groupByString, havingString, lockMode); } diff --git a/src/NHibernate/Mapping/ByCode/Impl/AnyMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/AnyMapper.cs index e09865baa61..233d92f3928 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/AnyMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/AnyMapper.cs @@ -144,7 +144,7 @@ public void MetaValue(object value, System.Type entityType) System.Type metavalueType = value.GetType(); if (any.metavalue == null) { - any.metavalue = new HbmMetaValue[0]; + any.metavalue = System.Array.Empty(); } Dictionary values = any.metavalue.ToDictionary(mv => mv.value, mv => mv.@class); MetaType(metavalueType); @@ -205,4 +205,4 @@ private void CheckIdTypeImmutability(string nhTypeName) #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Impl/ManyToAnyMapper.cs b/src/NHibernate/Mapping/ByCode/Impl/ManyToAnyMapper.cs index 486c502f057..8fad148094e 100644 --- a/src/NHibernate/Mapping/ByCode/Impl/ManyToAnyMapper.cs +++ b/src/NHibernate/Mapping/ByCode/Impl/ManyToAnyMapper.cs @@ -119,7 +119,7 @@ public void MetaValue(object value, System.Type entityType) System.Type metavalueType = value.GetType(); if (manyToAny.metavalue == null) { - manyToAny.metavalue = new HbmMetaValue[0]; + manyToAny.metavalue = System.Array.Empty(); } Dictionary values = manyToAny.metavalue.ToDictionary(mv => mv.value, mv => mv.@class); MetaType(metavalueType); @@ -153,4 +153,4 @@ private void CheckIdTypeImmutability(string nhTypeName) } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/ByCode/Import.cs b/src/NHibernate/Mapping/ByCode/Import.cs index 2e336dfa962..48a2b9935a1 100644 --- a/src/NHibernate/Mapping/ByCode/Import.cs +++ b/src/NHibernate/Mapping/ByCode/Import.cs @@ -25,7 +25,7 @@ public void AddToMapping(HbmMapping hbmMapping) rename = this.rename }; - var existingImports = hbmMapping.import ?? new HbmImport[0]; + var existingImports = hbmMapping.import ?? System.Array.Empty(); hbmMapping.import = existingImports.Concat(new [] { hbmImport }).ToArray(); } diff --git a/src/NHibernate/Mapping/ByCode/TypeExtensions.cs b/src/NHibernate/Mapping/ByCode/TypeExtensions.cs index 89dd4a6a29d..1ae4317af22 100644 --- a/src/NHibernate/Mapping/ByCode/TypeExtensions.cs +++ b/src/NHibernate/Mapping/ByCode/TypeExtensions.cs @@ -103,7 +103,7 @@ public static MemberInfo DecodeMemberAccessExpressionOf(Expr var propertyInfo = memberOfDeclaringType as PropertyInfo; if (propertyInfo != null) { - return typeof (TEntity).GetProperty(propertyInfo.Name, PropertiesOfClassHierarchy, null, propertyInfo.PropertyType, new System.Type[0], null); + return typeof (TEntity).GetProperty(propertyInfo.Name, PropertiesOfClassHierarchy, null, propertyInfo.PropertyType, System.Type.EmptyTypes, null); } if (memberOfDeclaringType is FieldInfo) { @@ -553,4 +553,4 @@ private static IEnumerable GetUserDeclaredFields(System.Type type) return type.GetFields(PropertiesOrFieldOfClass).Where(x => !x.Name.StartsWith("<")); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Mapping/Collection.cs b/src/NHibernate/Mapping/Collection.cs index c6bc98f7e3f..49677325626 100644 --- a/src/NHibernate/Mapping/Collection.cs +++ b/src/NHibernate/Mapping/Collection.cs @@ -19,7 +19,7 @@ namespace NHibernate.Mapping [Serializable] public abstract class Collection : IFetchable, IValue, IFilterable { - private static readonly IEnumerable EmptyColumns = new ISelectable[0]; + private static readonly IEnumerable EmptyColumns = System.Array.Empty(); public const string DefaultElementColumnName = "elt"; public const string DefaultKeyColumnName = "id"; @@ -398,12 +398,12 @@ public virtual void Validate(IMapping mapping) public bool[] ColumnInsertability { - get { return ArrayHelper.EmptyBoolArray; } + get { return System.Array.Empty(); } } public bool[] ColumnUpdateability { - get { return ArrayHelper.EmptyBoolArray; } + get { return System.Array.Empty(); } } public string TypeName diff --git a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs index 2bdbc345cd2..d33555c5b93 100644 --- a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs +++ b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs @@ -3031,7 +3031,7 @@ public void Update(object id, object[] fields, int[] dirtyFields, bool hasDirtyC // to be updated; an empty array for the dirty fields needs to be passed to // getPropertiesToUpdate() instead of null. propsToUpdate = this.GetPropertiesToUpdate( - (dirtyFields == null ? ArrayHelper.EmptyIntArray : dirtyFields), hasDirtyCollection); + (dirtyFields == null ? Array.Empty() : dirtyFields), hasDirtyCollection); // don't need to check laziness (dirty checking algorithm handles that) updateStrings = new SqlCommandInfo[span]; diff --git a/src/NHibernate/Properties/BasicPropertyAccessor.cs b/src/NHibernate/Properties/BasicPropertyAccessor.cs index 8086675c81b..18399171f31 100644 --- a/src/NHibernate/Properties/BasicPropertyAccessor.cs +++ b/src/NHibernate/Properties/BasicPropertyAccessor.cs @@ -196,7 +196,7 @@ public object Get(object target) { try { - return property.GetValue(target, new object[0]); + return property.GetValue(target, Array.Empty()); } catch (Exception e) { @@ -293,7 +293,7 @@ public void Set(object target, object value) { try { - property.SetValue(target, value, new object[0]); + property.SetValue(target, value, Array.Empty()); } catch (ArgumentException ae) { diff --git a/src/NHibernate/Proxy/DynamicProxy/DefaultArgumentHandler.cs b/src/NHibernate/Proxy/DynamicProxy/DefaultArgumentHandler.cs index 363fa31eaac..40a7f9e3b00 100644 --- a/src/NHibernate/Proxy/DynamicProxy/DefaultArgumentHandler.cs +++ b/src/NHibernate/Proxy/DynamicProxy/DefaultArgumentHandler.cs @@ -18,7 +18,7 @@ internal class DefaultArgumentHandler : IArgumentHandler public void PushArguments(ParameterInfo[] methodParameters, ILGenerator IL, bool isStatic) { - ParameterInfo[] parameters = methodParameters ?? new ParameterInfo[0]; + ParameterInfo[] parameters = methodParameters ?? Array.Empty(); int parameterCount = parameters.Length; // object[] args = new object[size]; diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs index a40adbb80bc..1865190f182 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyFactory.cs @@ -21,7 +21,7 @@ public sealed class ProxyFactory { internal static readonly ConcurrentDictionary _cache = new ConcurrentDictionary(); - private static readonly ConstructorInfo defaultBaseConstructor = typeof(object).GetConstructor(new System.Type[0]); + private static readonly ConstructorInfo defaultBaseConstructor = typeof(object).GetConstructor(System.Type.EmptyTypes); private static readonly MethodInfo getValue = ReflectHelper.GetMethod( si => si.GetValue(null, null)); @@ -146,9 +146,9 @@ private static ConstructorBuilder DefineConstructor(TypeBuilder typeBuilder, Sys MethodAttributes.RTSpecialName; ConstructorBuilder constructor = - typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, new System.Type[0]); + typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, System.Type.EmptyTypes); - var baseConstructor = parentType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new System.Type[0], null); + var baseConstructor = parentType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, System.Type.EmptyTypes, null); // if there is no default constructor, or the default constructor is private/internal, call System.Object constructor // this works, but the generated assembly will fail PeVerify (cannot use in medium trust for example) @@ -256,8 +256,8 @@ private static void DefineSerializationConstructor(TypeBuilder typeBuilder, Fiel private static void AddSerializationSupport(System.Type baseType, IReadOnlyCollection baseInterfaces, TypeBuilder typeBuilder, FieldInfo interceptorField, ConstructorBuilder defaultConstructor) { - ConstructorInfo serializableConstructor = typeof(SerializableAttribute).GetConstructor(new System.Type[0]); - var customAttributeBuilder = new CustomAttributeBuilder(serializableConstructor, new object[0]); + ConstructorInfo serializableConstructor = typeof(SerializableAttribute).GetConstructor(System.Type.EmptyTypes); + var customAttributeBuilder = new CustomAttributeBuilder(serializableConstructor, Array.Empty()); typeBuilder.SetCustomAttribute(customAttributeBuilder); DefineSerializationConstructor(typeBuilder, interceptorField, defaultConstructor); diff --git a/src/NHibernate/Proxy/DynamicProxy/ProxyImplementor.cs b/src/NHibernate/Proxy/DynamicProxy/ProxyImplementor.cs index e97f2426354..bc486aee83d 100644 --- a/src/NHibernate/Proxy/DynamicProxy/ProxyImplementor.cs +++ b/src/NHibernate/Proxy/DynamicProxy/ProxyImplementor.cs @@ -36,7 +36,7 @@ public void ImplementProxy(TypeBuilder typeBuilder) field = typeBuilder.DefineField("__interceptor", typeof (IInterceptor), FieldAttributes.Private); // Implement the getter - MethodBuilder getterMethod = typeBuilder.DefineMethod("get_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof(IInterceptor), new System.Type[0]); + MethodBuilder getterMethod = typeBuilder.DefineMethod("get_Interceptor", InterceptorMethodsAttributes, CallingConventions.HasThis, typeof(IInterceptor), System.Type.EmptyTypes); getterMethod.SetImplementationFlags(MethodImplAttributes.Managed | MethodImplAttributes.IL); ILGenerator IL = getterMethod.GetILGenerator(); @@ -61,4 +61,4 @@ public void ImplementProxy(TypeBuilder typeBuilder) typeBuilder.DefineMethodOverride(getterMethod, OriginalGetter); } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Proxy/NHibernateProxyBuilder.cs b/src/NHibernate/Proxy/NHibernateProxyBuilder.cs index bd3613c725a..8502d950b33 100644 --- a/src/NHibernate/Proxy/NHibernateProxyBuilder.cs +++ b/src/NHibernate/Proxy/NHibernateProxyBuilder.cs @@ -90,7 +90,7 @@ public TypeInfo CreateProxyType(System.Type baseType, IReadOnlyCollection()); typeBuilder.SetCustomAttribute(customAttributeBuilder); ImplementDeserializationConstructor(typeBuilder); diff --git a/src/NHibernate/SqlCommand/BackTrackCacheParameterList.cs b/src/NHibernate/SqlCommand/BackTrackCacheParameterList.cs index 7a2f0451f41..595123e452f 100644 --- a/src/NHibernate/SqlCommand/BackTrackCacheParameterList.cs +++ b/src/NHibernate/SqlCommand/BackTrackCacheParameterList.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Collections.ObjectModel; using NHibernate.Util; @@ -98,7 +99,7 @@ public IEnumerable GetEffectiveParameterLocations(string backTrace) if (_indexesByBackTrace.TryGetValue(backTrace, out indexes)) return indexes; } - return ArrayHelper.EmptyIntArray; + return Array.Empty(); } } } \ No newline at end of file diff --git a/src/NHibernate/SqlTypes/SqlTypeFactory.cs b/src/NHibernate/SqlTypes/SqlTypeFactory.cs index 20e9ed75270..23983c57a53 100644 --- a/src/NHibernate/SqlTypes/SqlTypeFactory.cs +++ b/src/NHibernate/SqlTypes/SqlTypeFactory.cs @@ -36,7 +36,7 @@ public static class SqlTypeFactory public static readonly SqlType UInt32 = new SqlType(DbType.UInt32); public static readonly SqlType UInt64 = new SqlType(DbType.UInt64); - public static readonly SqlType[] NoTypes = new SqlType[0]; + public static readonly SqlType[] NoTypes = Array.Empty(); private delegate T TypeWithLenOrScaleCreateDelegate(TDim lengthOrScale); // Func diff --git a/src/NHibernate/Type/CollectionType.cs b/src/NHibernate/Type/CollectionType.cs index 3d8285532a3..29ce74db6d9 100644 --- a/src/NHibernate/Type/CollectionType.cs +++ b/src/NHibernate/Type/CollectionType.cs @@ -537,7 +537,7 @@ public string GetOnCondition(string alias, ISessionFactoryImplementor factory, I public override bool[] ToColumnNullness(object value, IMapping mapping) { - return ArrayHelper.EmptyBoolArray; + return Array.Empty(); } public override int Compare(object x, object y) diff --git a/src/NHibernate/Type/DbTimestampType.cs b/src/NHibernate/Type/DbTimestampType.cs index 0fe280fed1c..3fc4e112bae 100644 --- a/src/NHibernate/Type/DbTimestampType.cs +++ b/src/NHibernate/Type/DbTimestampType.cs @@ -17,7 +17,7 @@ namespace NHibernate.Type public partial class DbTimestampType : AbstractDateTimeType { private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DbTimestampType)); - private static readonly SqlType[] EmptyParams = new SqlType[0]; + private static readonly SqlType[] EmptyParams = Array.Empty(); /// public override string Name => "DbTimestamp"; diff --git a/src/NHibernate/Type/OneToOneType.cs b/src/NHibernate/Type/OneToOneType.cs index c903be941fe..1575629351b 100644 --- a/src/NHibernate/Type/OneToOneType.cs +++ b/src/NHibernate/Type/OneToOneType.cs @@ -13,7 +13,7 @@ namespace NHibernate.Type [Serializable] public partial class OneToOneType : EntityType, IAssociationType { - private static readonly SqlType[] NoSqlTypes = new SqlType[0]; + private static readonly SqlType[] NoSqlTypes = Array.Empty(); private readonly ForeignKeyDirection foreignKeyDirection; private readonly string propertyName; @@ -151,7 +151,7 @@ public override string PropertyName public override bool[] ToColumnNullness(object value, IMapping mapping) { - return ArrayHelper.EmptyBoolArray; + return Array.Empty(); } } } diff --git a/src/NHibernate/Type/TypeFactory.cs b/src/NHibernate/Type/TypeFactory.cs index f7972227640..da1166f8dd2 100644 --- a/src/NHibernate/Type/TypeFactory.cs +++ b/src/NHibernate/Type/TypeFactory.cs @@ -34,7 +34,7 @@ private enum TypeClassification } private static readonly INHibernateLogger _log = NHibernateLogger.For(typeof(TypeFactory)); - private static readonly string[] EmptyAliases= new string[0]; + private static readonly string[] EmptyAliases= System.Array.Empty(); private static readonly char[] PrecisionScaleSplit = new[] { '(', ')', ',' }; private static readonly char[] LengthSplit = new[] { '(', ')' }; private static readonly TypeFactory Instance; diff --git a/src/NHibernate/Type/TypeHelper.cs b/src/NHibernate/Type/TypeHelper.cs index 3e11b6f6e7d..dfb5c38d2ca 100644 --- a/src/NHibernate/Type/TypeHelper.cs +++ b/src/NHibernate/Type/TypeHelper.cs @@ -12,7 +12,7 @@ namespace NHibernate.Type /// public static partial class TypeHelper { - public static readonly IType[] EmptyTypeArray = new IType[0]; + public static readonly IType[] EmptyTypeArray = Array.Empty(); /// Deep copy a series of values from one array to another /// The values to copy (the source) diff --git a/src/NHibernate/Util/ArrayHelper.cs b/src/NHibernate/Util/ArrayHelper.cs index 8bab75868bd..531dd33a599 100644 --- a/src/NHibernate/Util/ArrayHelper.cs +++ b/src/NHibernate/Util/ArrayHelper.cs @@ -13,9 +13,15 @@ namespace NHibernate.Util /// public static class ArrayHelper { - public static readonly object[] EmptyObjectArray = new object[0]; - public static readonly int[] EmptyIntArray = new int[0]; - public static readonly bool[] EmptyBoolArray = new bool[0]; + //Since v5.1 + [Obsolete("Please use System.Array.Empty() instead")] + public static object[] EmptyObjectArray => Array.Empty(); + //Since v5.1 + [Obsolete("Please use System.Array.Empty() instead")] + public static int[] EmptyIntArray => Array.Empty(); + //Since v5.1 + [Obsolete("Please use System.Array.Empty() instead")] + public static bool[] EmptyBoolArray => Array.Empty(); public static readonly bool[] True = new bool[] { true }; public static readonly bool[] False = new bool[] { false }; diff --git a/src/NHibernate/Util/CollectionHelper.cs b/src/NHibernate/Util/CollectionHelper.cs index c8075f02dca..17684ae21b2 100644 --- a/src/NHibernate/Util/CollectionHelper.cs +++ b/src/NHibernate/Util/CollectionHelper.cs @@ -512,12 +512,12 @@ public TValue this[TKey key] public ICollection Keys { - get { return new List(); } + get { return Array.Empty(); } } public ICollection Values { - get { return new List(); } + get { return Array.Empty(); } } #endregion diff --git a/src/NHibernate/Util/ReflectHelper.cs b/src/NHibernate/Util/ReflectHelper.cs index 263764f1117..e821e966c24 100644 --- a/src/NHibernate/Util/ReflectHelper.cs +++ b/src/NHibernate/Util/ReflectHelper.cs @@ -598,7 +598,7 @@ public static bool IsFinalClass(System.Type type) /// The unwrapped exception. public static Exception UnwrapTargetInvocationException(TargetInvocationException ex) { - Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, new Object[] { }); + Exception_InternalPreserveStackTrace.Invoke(ex.InnerException, Array.Empty()); return ex.InnerException; } From 7e440bfa247b6ef905056886306d365ed1774b83 Mon Sep 17 00:00:00 2001 From: Misha Urubkov Date: Sat, 16 Dec 2017 02:10:47 -0800 Subject: [PATCH 29/32] Fix IsModified so that null equates empty components MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * And fix ComponentType.IsModified(…) method throws exception when used with a component as "old" parameter. * Fix #1486 --- .../NHSpecificTest/GH1486/Entities.cs | 82 ++++++++++ .../NHSpecificTest/GH1486/Fixture.cs | 145 ++++++++++++++++++ .../NHSpecificTest/GH1486/Mappings.hbm.xml | 15 ++ .../GH1486/OnFlushDirtyInterceptor.cs | 20 +++ .../Component/AbstractComponentTuplizer.cs | 3 +- src/NHibernate/Type/ComponentType.cs | 10 +- 6 files changed, 267 insertions(+), 8 deletions(-) create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1486/Entities.cs create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1486/Fixture.cs create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1486/Mappings.hbm.xml create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1486/OnFlushDirtyInterceptor.cs diff --git a/src/NHibernate.Test/NHSpecificTest/GH1486/Entities.cs b/src/NHibernate.Test/NHSpecificTest/GH1486/Entities.cs new file mode 100644 index 00000000000..efe49cfd6cd --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1486/Entities.cs @@ -0,0 +1,82 @@ +using System; + + +namespace NHibernate.Test.NHSpecificTest.GH1486 +{ + public class Person + { + public virtual int Id { get; set; } + + public virtual string Name { get; set; } + + public virtual Address Address { get; set; } + + public virtual int Version { get; set; } + + public Person() + { + } + + public Person(int id, string name, Address address) + { + Id = id; + Name = name; + Address = address; + } + } + + public class Address : IEquatable
+ { + public virtual string PostalCode { get; set; } + + public virtual string State { get; set; } + + public virtual string Street { get; set; } + + public Address() + { } + + public Address(string postalCode, string state, string street) + { + PostalCode = postalCode; + State = state; + Street = street; + } + + public bool Equals(Address other) + { + if (ReferenceEquals(null, other)) return false; + if (ReferenceEquals(this, other)) return true; + return string.Equals(Street, other.Street) && string.Equals(State, other.State) && string.Equals(PostalCode, other.PostalCode); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != GetType()) return false; + return Equals((Address) obj); + } + + public override int GetHashCode() + { + unchecked + { + var hashCode = (PostalCode != null ? PostalCode.GetHashCode() : 0); + hashCode = (hashCode * 397) ^ (State != null ? State.GetHashCode() : 0); + hashCode = (hashCode * 397) ^ (Street != null ? Street.GetHashCode() : 0); + return hashCode; + } + } + + public static bool operator ==(Address left, Address right) + { + return Equals(left, right); + } + + public static bool operator !=(Address left, Address right) + { + return !Equals(left, right); + } + } +} diff --git a/src/NHibernate.Test/NHSpecificTest/GH1486/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/GH1486/Fixture.cs new file mode 100644 index 00000000000..85a727f1ec6 --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1486/Fixture.cs @@ -0,0 +1,145 @@ +using System.Linq; +using NUnit.Framework; +using NHibernate.Cfg; +using NHibernate.Type; + +namespace NHibernate.Test.NHSpecificTest.GH1486 +{ + [TestFixture] + public class Fixture : BugTestCase + { + private readonly OnFlushDirtyInterceptor _interceptor = new OnFlushDirtyInterceptor(); + + protected override void Configure(Configuration configuration) + { + base.Configure(configuration); + configuration.SetInterceptor(_interceptor); + } + + protected override void OnSetUp() + { + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + var john = new Person(1, "John", new Address()); + session.Save(john); + + var mary = new Person(2, "Mary", null); + session.Save(mary); + + var bob = new Person(3, "Bob", new Address("1", "A", "B")); + session.Save(bob); + + session.Flush(); + transaction.Commit(); + } + } + } + + protected override void OnTearDown() + { + using (var session = OpenSession()) + using (var transaction = session.BeginTransaction()) + { + session.Delete("from System.Object"); + session.Flush(); + transaction.Commit(); + } + } + + /// + /// The test case was imported from Hibernate HHH-11237 and adjusted for NHibernate. + /// + [Test] + public void TestSelectBeforeUpdate() + { + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + var john = session.Get(1); + _interceptor.Reset(); + john.Address = null; + session.Flush(); + Assert.That(_interceptor.CallCount, Is.EqualTo(0), "unexpected flush dirty count for John"); + + _interceptor.Reset(); + var mary = session.Get(2); + mary.Address = new Address(); + session.Flush(); + Assert.That(_interceptor.CallCount, Is.EqualTo(0), "unexpected flush dirty count for Mary"); + transaction.Commit(); + } + } + + Person johnObj; + Person maryObj; + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + johnObj = session.Get(1); + } + } + + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + maryObj = session.Get(2); + } + } + + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + _interceptor.Reset(); + johnObj.Address = null; + session.Update(johnObj); + session.Flush(); + Assert.That(_interceptor.CallCount, Is.EqualTo(0), "unexpected flush dirty count for John update"); + + _interceptor.Reset(); + maryObj.Address = new Address(); + session.Update(maryObj); + session.Flush(); + Assert.That(_interceptor.CallCount, Is.EqualTo(0), "unexpected flush dirty count for Mary update"); + transaction.Commit(); + } + } + } + + [Test] + public void TestDirectCallToIsModified() + { + using (var session = OpenSession()) + using (var transaction = session.BeginTransaction()) + { + var person = session.Load(3); + Assert.That(person, Is.Not.Null, "Bob is not found."); + Assert.That(person.Address, Is.Not.Null, "Bob's address is missing."); + var sessionImplementor = session.GetSessionImplementation(); + + var metaData = session.SessionFactory.GetClassMetadata(typeof(Person)); + foreach (var propertyType in metaData.PropertyTypes) + { + if (!(propertyType is ComponentType componentType) || componentType.ReturnedClass.Name != "Address") + continue; + + var checkable = new [] { true, true, true }; + Assert.That( + () => componentType.IsModified(new object[] { "", "", "" }, person.Address, checkable, sessionImplementor), + Throws.Nothing, + "Checking component against an array snapshot failed"); + var isModified = componentType.IsModified(person.Address, person.Address, checkable, sessionImplementor); + Assert.That(isModified, Is.False, "Checking same component failed"); + isModified = componentType.IsModified(new Address("1", "A", "B"), person.Address, checkable, sessionImplementor); + Assert.That(isModified, Is.False, "Checking equal component failed"); + } + transaction.Rollback(); + } + } + } +} diff --git a/src/NHibernate.Test/NHSpecificTest/GH1486/Mappings.hbm.xml b/src/NHibernate.Test/NHSpecificTest/GH1486/Mappings.hbm.xml new file mode 100644 index 00000000000..a1f5f1c846c --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1486/Mappings.hbm.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/src/NHibernate.Test/NHSpecificTest/GH1486/OnFlushDirtyInterceptor.cs b/src/NHibernate.Test/NHSpecificTest/GH1486/OnFlushDirtyInterceptor.cs new file mode 100644 index 00000000000..39391a7aa97 --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1486/OnFlushDirtyInterceptor.cs @@ -0,0 +1,20 @@ +using NHibernate.Type; + +namespace NHibernate.Test.NHSpecificTest.GH1486 +{ + public class OnFlushDirtyInterceptor : EmptyInterceptor + { + public int CallCount = 0; + + public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, IType[] types) + { + CallCount++; + return false; + } + + public void Reset() + { + CallCount = 0; + } + } +} diff --git a/src/NHibernate/Tuple/Component/AbstractComponentTuplizer.cs b/src/NHibernate/Tuple/Component/AbstractComponentTuplizer.cs index 6e16b03a45c..8152da34511 100644 --- a/src/NHibernate/Tuple/Component/AbstractComponentTuplizer.cs +++ b/src/NHibernate/Tuple/Component/AbstractComponentTuplizer.cs @@ -101,7 +101,8 @@ public virtual void SetPropertyValues(object component, object[] values) public virtual object GetPropertyValue(object component, int i) { - return getters[i].Get(component); + // NH Different behavior : for NH-1101 + return component == null ? null : getters[i].Get(component); } /// This method does not populate the component parent diff --git a/src/NHibernate/Type/ComponentType.cs b/src/NHibernate/Type/ComponentType.cs index 05b8a24381e..fadf9414412 100644 --- a/src/NHibernate/Type/ComponentType.cs +++ b/src/NHibernate/Type/ComponentType.cs @@ -525,16 +525,12 @@ public override object SemiResolve(object value, ISessionImplementor session, ob public override bool IsModified(object old, object current, bool[] checkable, ISessionImplementor session) { - if (current == null) + if (old == current) { - return old != null; - } - if (old == null) - { - return current != null; + return false; } object[] currentValues = GetPropertyValues(current, session); - object[] oldValues = (Object[]) old; + var oldValues = old is object[] objects ? objects : GetPropertyValues(old, session); int loc = 0; for (int i = 0; i < currentValues.Length; i++) { From 8ffa874c70d8993ebb1313fb4d44b01296b22ef0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Sat, 16 Dec 2017 11:29:11 +0100 Subject: [PATCH 30/32] Forgotten async generation for #1487 --- .../Criteria/DetachedCriteriaSerializable.cs | 2 +- .../Async/NHSpecificTest/GH1486/Fixture.cs | 157 ++++++++++++++++++ src/NHibernate/Async/Type/ComponentType.cs | 10 +- 3 files changed, 161 insertions(+), 8 deletions(-) create mode 100644 src/NHibernate.Test/Async/NHSpecificTest/GH1486/Fixture.cs diff --git a/src/NHibernate.Test/Async/Criteria/DetachedCriteriaSerializable.cs b/src/NHibernate.Test/Async/Criteria/DetachedCriteriaSerializable.cs index 10f9217e586..927b4d39192 100644 --- a/src/NHibernate.Test/Async/Criteria/DetachedCriteriaSerializable.cs +++ b/src/NHibernate.Test/Async/Criteria/DetachedCriteriaSerializable.cs @@ -185,4 +185,4 @@ public async Task ExecutableCriteriaAsync() await (SerializeAndListAsync(dc)); } } -} \ No newline at end of file +} diff --git a/src/NHibernate.Test/Async/NHSpecificTest/GH1486/Fixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/GH1486/Fixture.cs new file mode 100644 index 00000000000..69b6e469b6a --- /dev/null +++ b/src/NHibernate.Test/Async/NHSpecificTest/GH1486/Fixture.cs @@ -0,0 +1,157 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by AsyncGenerator. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +using System.Linq; +using NUnit.Framework; +using NHibernate.Cfg; +using NHibernate.Type; + +namespace NHibernate.Test.NHSpecificTest.GH1486 +{ + using System.Threading.Tasks; + using System.Threading; + [TestFixture] + public class FixtureAsync : BugTestCase + { + private readonly OnFlushDirtyInterceptor _interceptor = new OnFlushDirtyInterceptor(); + + protected override void Configure(Configuration configuration) + { + base.Configure(configuration); + configuration.SetInterceptor(_interceptor); + } + + protected override void OnSetUp() + { + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + var john = new Person(1, "John", new Address()); + session.Save(john); + + var mary = new Person(2, "Mary", null); + session.Save(mary); + + var bob = new Person(3, "Bob", new Address("1", "A", "B")); + session.Save(bob); + + session.Flush(); + transaction.Commit(); + } + } + } + + protected override void OnTearDown() + { + using (var session = OpenSession()) + using (var transaction = session.BeginTransaction()) + { + session.Delete("from System.Object"); + session.Flush(); + transaction.Commit(); + } + } + + /// + /// The test case was imported from Hibernate HHH-11237 and adjusted for NHibernate. + /// + [Test] + public async Task TestSelectBeforeUpdateAsync() + { + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + var john = await (session.GetAsync(1)); + _interceptor.Reset(); + john.Address = null; + await (session.FlushAsync()); + Assert.That(_interceptor.CallCount, Is.EqualTo(0), "unexpected flush dirty count for John"); + + _interceptor.Reset(); + var mary = await (session.GetAsync(2)); + mary.Address = new Address(); + await (session.FlushAsync()); + Assert.That(_interceptor.CallCount, Is.EqualTo(0), "unexpected flush dirty count for Mary"); + await (transaction.CommitAsync()); + } + } + + Person johnObj; + Person maryObj; + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + johnObj = await (session.GetAsync(1)); + } + } + + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + maryObj = await (session.GetAsync(2)); + } + } + + using (var session = OpenSession()) + { + using (var transaction = session.BeginTransaction()) + { + _interceptor.Reset(); + johnObj.Address = null; + await (session.UpdateAsync(johnObj)); + await (session.FlushAsync()); + Assert.That(_interceptor.CallCount, Is.EqualTo(0), "unexpected flush dirty count for John update"); + + _interceptor.Reset(); + maryObj.Address = new Address(); + await (session.UpdateAsync(maryObj)); + await (session.FlushAsync()); + Assert.That(_interceptor.CallCount, Is.EqualTo(0), "unexpected flush dirty count for Mary update"); + await (transaction.CommitAsync()); + } + } + } + + [Test] + public async Task TestDirectCallToIsModifiedAsync() + { + using (var session = OpenSession()) + using (var transaction = session.BeginTransaction()) + { + var person = await (session.LoadAsync(3)); + Assert.That(person, Is.Not.Null, "Bob is not found."); + Assert.That(person.Address, Is.Not.Null, "Bob's address is missing."); + var sessionImplementor = session.GetSessionImplementation(); + + var metaData = session.SessionFactory.GetClassMetadata(typeof(Person)); + foreach (var propertyType in metaData.PropertyTypes) + { + if (!(propertyType is ComponentType componentType) || componentType.ReturnedClass.Name != "Address") + continue; + + var checkable = new [] { true, true, true }; + Assert.That( + () => componentType.IsModifiedAsync(new object[] { "", "", "" }, person.Address, checkable, sessionImplementor, CancellationToken.None), + Throws.Nothing, + "Checking component against an array snapshot failed"); + var isModified = await (componentType.IsModifiedAsync(person.Address, person.Address, checkable, sessionImplementor, CancellationToken.None)); + Assert.That(isModified, Is.False, "Checking same component failed"); + isModified = await (componentType.IsModifiedAsync(new Address("1", "A", "B"), person.Address, checkable, sessionImplementor, CancellationToken.None)); + Assert.That(isModified, Is.False, "Checking equal component failed"); + } + await (transaction.RollbackAsync()); + } + } + } +} diff --git a/src/NHibernate/Async/Type/ComponentType.cs b/src/NHibernate/Async/Type/ComponentType.cs index 7df3df3b71b..999852e447b 100644 --- a/src/NHibernate/Async/Type/ComponentType.cs +++ b/src/NHibernate/Async/Type/ComponentType.cs @@ -332,16 +332,12 @@ public override Task SemiResolveAsync(object value, ISessionImplementor public override async Task IsModifiedAsync(object old, object current, bool[] checkable, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - if (current == null) + if (old == current) { - return old != null; - } - if (old == null) - { - return current != null; + return false; } object[] currentValues = await (GetPropertyValuesAsync(current, session, cancellationToken)).ConfigureAwait(false); - object[] oldValues = (Object[]) old; + var oldValues = old is object[] objects ? objects : await (GetPropertyValuesAsync(old, session, cancellationToken)).ConfigureAwait(false); int loc = 0; for (int i = 0; i < currentValues.Length; i++) { From 92bae88bf367c53c5841b0fec6e35402a53e4de3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Delaporte?= Date: Sat, 16 Dec 2017 12:50:24 +0100 Subject: [PATCH 31/32] Adjustment for Join-fetching with property-ref results in n+1 select --- src/NHibernate/Loader/Loader.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index 3ab15d6769b..44738d09d5f 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -973,12 +973,17 @@ private void InstanceAlreadyLoaded(DbDataReader rs, int i, IEntityPersister pers } } + CacheByUniqueKey(i, persister, obj, session); + } + + private void CacheByUniqueKey(int i, IEntityPersister persister, object obj, ISessionImplementor session) + { // #1226: If it is already loaded and can be loaded from an association with a property ref, make // sure it is also cached by its unique key. var ukName = OwnerAssociationTypes?[i]?.RHSUniqueKeyPropertyName; if (ukName == null) return; - var index = ((IUniqueKeyLoadable) persister).GetPropertyIndex(ukName); + var index = ((IUniqueKeyLoadable)persister).GetPropertyIndex(ukName); var ukValue = persister.GetPropertyValue(obj, index); // ukValue can be null for two reasons: // - Entity currently loading and not yet fully hydrated. In such case, it has already been handled by From a9e369813d93a623340984ddb68401f8799a7257 Mon Sep 17 00:00:00 2001 From: Konstantin Fedorchenko Date: Wed, 29 Nov 2017 11:19:28 +0200 Subject: [PATCH 32/32] NH-2534 - Join-fetching a many-to-one with property-ref results in select n+1 problem (#1226) fixed #1226 --- .../NHSpecificTest/GH1226/Fixture.cs | 84 +++++++++++++++++++ .../NHSpecificTest/GH1226/Mappings.hbm.xml | 18 ++++ .../NHSpecificTest/GH1226/Model.cs | 16 ++++ src/NHibernate.Test/NHibernate.Test.csproj | 2 +- src/NHibernate/Loader/Loader.cs | 28 +++++++ 5 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml create mode 100644 src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs b/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs new file mode 100644 index 00000000000..5d169497ada --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Fixture.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; + +namespace NHibernate.Test.NHSpecificTest.GH1226 +{ + [TestFixture] + public class Fixture : BugTestCase + { + protected override void OnSetUp() + { + base.OnSetUp(); + + using (var session = OpenSession()) + { + using (var tx = session.BeginTransaction()) + { + var bank = new Bank { Code = "01234" }; + session.Save(bank); + + var account = new Account { Bank = bank }; + session.Save(account); + + var account2 = new Account { Bank = bank }; + session.Save(account2); + + tx.Commit(); + } + } + } + + [Test] + public void BankShouldBeJoinFetched() + { + using (var session = OpenSession()) + { + var wasStatisticsEnabled = session.SessionFactory.Statistics.IsStatisticsEnabled; + session.SessionFactory.Statistics.IsStatisticsEnabled = true; + + long statementCount; + + using (var tx = session.BeginTransaction()) + { + // Bug only occurs if the Banks are already in the session cache. + var preloadedBanks = session.CreateQuery("from Bank").List(); + + var countBeforeQuery = session.SessionFactory.Statistics.PrepareStatementCount; + + Console.WriteLine("Query: -------------------------------------------------------"); + + var accounts = session.CreateQuery("from Account a left join fetch a.Bank").List(); + IList associatedBanks = accounts.Select(x => x.Bank).ToList(); + + var countAfterQuery = session.SessionFactory.Statistics.PrepareStatementCount; + statementCount = countAfterQuery - countBeforeQuery; + + Console.WriteLine("End ----------------------------------------------------------"); + + tx.Commit(); + } + + session.SessionFactory.Statistics.IsStatisticsEnabled = wasStatisticsEnabled; + + Assert.That(statementCount, Is.EqualTo(1)); + } + } + + protected override void OnTearDown() + { + base.OnTearDown(); + + using (var session = OpenSession()) + { + using (var tx = session.BeginTransaction()) + { + session.Delete("from Account"); + session.Delete("from Bank"); + tx.Commit(); + } + } + } + } +} diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml b/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml new file mode 100644 index 00000000000..04d537158c2 --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Mappings.hbm.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + diff --git a/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs b/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs new file mode 100644 index 00000000000..9b527a7d51d --- /dev/null +++ b/src/NHibernate.Test/NHSpecificTest/GH1226/Model.cs @@ -0,0 +1,16 @@ +using System; + +namespace NHibernate.Test.NHSpecificTest.GH1226 +{ + public class Account + { + public virtual Guid Id { get; set; } + public virtual Bank Bank { get; set; } + } + + public class Bank + { + public virtual Guid Id { get; set; } + public virtual string Code { get; set; } + } +} diff --git a/src/NHibernate.Test/NHibernate.Test.csproj b/src/NHibernate.Test/NHibernate.Test.csproj index 6ad305596f3..7e25190bf16 100644 --- a/src/NHibernate.Test/NHibernate.Test.csproj +++ b/src/NHibernate.Test/NHibernate.Test.csproj @@ -67,4 +67,4 @@ - + \ No newline at end of file diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index 89c8271202d..86106055794 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -972,6 +972,34 @@ private void InstanceAlreadyLoaded(DbDataReader rs, int i, IEntityPersister pers entry.LockMode = lockMode; } } + + CacheByUniqueKey(i, persister, obj, session); + } + + private void CacheByUniqueKey(int i, IEntityPersister persister, object obj, ISessionImplementor session) + { + // #1226: If it is already loaded and can be loaded from an association with a property ref, make + // sure it is also cached by its unique key. + var ukName = OwnerAssociationTypes?[i]?.RHSUniqueKeyPropertyName; + if (ukName == null) + return; + var index = ((IUniqueKeyLoadable)persister).GetPropertyIndex(ukName); + var ukValue = persister.GetPropertyValue(obj, index); + // ukValue can be null for two reasons: + // - Entity currently loading and not yet fully hydrated. In such case, it has already been handled by + // InstanceNotYetLoaded on a previous row, there is nothing more to do. This case could also be + // detected with "session.PersistenceContext.GetEntry(obj).Status == Status.Loading", but since there + // is a second case, just test for ukValue null. + // - Entity association is unset in session but not yet persisted, autoflush disabled: ignore. We are + // already in an error case: querying entities changed in session without flushing them before querying. + // So here it gets loaded as if it were still associated, but we do not have the key anymore in session: + // we cannot cache it, so long for the additionnal round-trip this will cause. (Do not fallback on + // reading the key in rs, this is stale data in regard to the session state.) + if (ukValue == null) + return; + var type = persister.PropertyTypes[index]; + var euk = new EntityUniqueKey(persister.EntityName, ukName, ukValue, type, session.Factory); + session.PersistenceContext.AddEntity(euk, obj); } ///