diff --git a/src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs b/src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs index 0f660e1994e..1a9cdefceac 100644 --- a/src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs +++ b/src/NHibernate.Test/Async/NHSpecificTest/Logs/LogsFixture.cs @@ -9,10 +9,16 @@ using System.Collections; - +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using NHibernate.Cfg; using NHibernate.Impl; - +using NHibernate.SqlCommand; +using NHibernate.Type; using NUnit.Framework; +using NHibernate.Linq; namespace NHibernate.Test.NHSpecificTest.Logs { @@ -24,7 +30,6 @@ namespace NHibernate.Test.NHSpecificTest.Logs using log4net.Core; using log4net.Layout; using log4net.Repository.Hierarchy; - using System.Threading.Tasks; [TestFixture] public class LogsFixtureAsync : TestCase @@ -39,6 +44,33 @@ protected override string MappingsAssembly get { return "NHibernate.Test"; } } + protected override void Configure(Configuration configuration) + { + base.Configure(configuration); + configuration.SetProperty(Cfg.Environment.UseSecondLevelCache, "false"); + } + + protected override void OnSetUp() + { + using (var s = Sfi.OpenSession()) + using (var t = s.BeginTransaction()) + { + s.Save(new Person()); + s.Save(new Person()); + t.Commit(); + } + } + + protected override void OnTearDown() + { + using (var s = Sfi.OpenSession()) + using (var t = s.BeginTransaction()) + { + s.CreateQuery("delete from Person").ExecuteUpdate(); + t.Commit(); + } + } + [Test] public async Task WillGetSessionIdFromSessionLogsAsync() { @@ -47,15 +79,128 @@ public async Task WillGetSessionIdFromSessionLogsAsync() using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}")) using (var s = Sfi.OpenSession()) { - var sessionId = ((SessionImpl)s).SessionId; + var sessionId = ((SessionImpl) s).SessionId; - await (s.GetAsync(1));//will execute some sql + await (s.GetAsync(1)); //will execute some sql var loggingEvent = spy.GetWholeLog(); Assert.That(loggingEvent.Contains(sessionId.ToString()), Is.True); } } + [Test] + public async Task WillGetSessionIdFromConsecutiveSessionsLogsAsync() + { + GlobalContext.Properties["sessionId"] = new SessionIdCapturer(); + + using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}")) + { + var sessions = Enumerable.Range(1, 10).Select(i => Sfi.OpenSession()).ToArray(); + try + { + for (var i = 0; i < 10; i++) + for (var j = 0; j < 10; j++) + { + var s = sessions[j]; + await (s.GetAsync(i * 10 + j)); //will execute some sql + } + } + finally + { + foreach (var s in sessions) + { + s.Dispose(); + } + } + + var loggingEvent = spy.GetWholeLog(); + for (var i = 0; i < 10; i++) + for (var j = 0; j < 10; j++) + { + var sessionId = sessions[j].GetSessionImplementation().SessionId; + Assert.That(loggingEvent, Does.Contain($"p0 = {i * 10 + j} [Type: Int32 (0:0:0)] | SessionId: {sessionId}")); + } + } + } + + [Test] + public async Task WillGetSessionIdFromInterlacedSessionsLogsAsync() + { + GlobalContext.Properties["sessionId"] = new SessionIdCapturer(); + var interceptor = new InterlacedSessionInterceptor(Sfi); + using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}")) + using (var s = Sfi.WithOptions().Interceptor(interceptor).OpenSession()) + { + // Trigger an operation which will fire many interceptor events, before and after s own logging. + var persons = await (s.Query().ToListAsync()); + + var loggingEvent = spy.GetWholeLog(); + for (var i = 0; i < interceptor.SessionIds.Count; i++) + { + var sessionId = interceptor.SessionIds[i]; + Assert.That(loggingEvent, Does.Contain($"p0 = {i + 1} [Type: Int32 (0:0:0)] | SessionId: {sessionId}")); + } + Assert.That(loggingEvent, Does.Contain($"Person person0_ | SessionId: {s.GetSessionImplementation().SessionId}")); + } + } + + [Test] + public async Task WillGetSessionIdFromSessionLogsConcurrentAsync() + { + GlobalContext.Properties["sessionId"] = new SessionIdCapturer(); + + // Do not use a ManualResetEventSlim, it does not support async and exhausts the task thread pool in the + // async counterparts of this test. SemaphoreSlim has the async support and release the thread when waiting. + var semaphore = new SemaphoreSlim(0); + var failures = new ConcurrentBag(); + 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 => + { + if (i > 10) + { + // Give some time to threads for reaching the wait, having all of them ready to do most of their job concurrently. + await (Task.Delay(100)); + semaphore.Release(10); + return; + } + try + { + using (var s = Sfi.OpenSession()) + { + sessionIds.AddOrUpdate( + i, + s.GetSessionImplementation().SessionId, + (ti, old) => throw new InvalidOperationException( + $"Thread number {ti} has already session id {old}, while attempting to set it to" + + $" {s.GetSessionImplementation().SessionId}")); + await (semaphore.WaitAsync()); + + for (int j = 0; j < 10; j++) + { + await (s.GetAsync(i * 10 + j)); //will execute some sql + } + } + } + catch (Exception e) + { + failures.Add(e); + } + }))); + + Assert.That(failures, Is.Empty, $"{failures.Count} task(s) failed."); + + var loggingEvent = spy.GetWholeLog(); + for (var i = 1; i < 11; i++) + for (var j = 0; j < 10; j++) + { + var sessionId = sessionIds[i]; + Assert.That(loggingEvent, Does.Contain($"p0 = {i * 10 + j} [Type: Int32 (0:0:0)] | SessionId: {sessionId}")); + } + } + } + // IFixingRequired interface ensures the value is evaluated at log time rather than at log buffer flush time. public class SessionIdCapturer : IFixingRequired { @@ -83,7 +228,7 @@ public TextLogSpy(string loggerName, string pattern) Threshold = Level.All, Writer = new StringWriter(stringBuilder) }; - loggerImpl = (Logger)LogManager.GetLogger(typeof(LogsFixtureAsync).Assembly, loggerName).Logger; + loggerImpl = (Logger) LogManager.GetLogger(typeof(LogsFixtureAsync).Assembly, loggerName).Logger; loggerImpl.AddAppender(appender); previousLevel = loggerImpl.Level; loggerImpl.Level = Level.All; @@ -100,7 +245,37 @@ public void Dispose() loggerImpl.Level = previousLevel; } } - } + public class InterlacedSessionInterceptor : EmptyInterceptor + { + private readonly ISessionFactory _sfi; + + public System.Collections.Generic.List SessionIds { get; } = new System.Collections.Generic.List(); + public InterlacedSessionInterceptor(ISessionFactory sfi) + { + _sfi = sfi; + } + + public override SqlString OnPrepareStatement(SqlString sql) + { + using (var s = _sfi.OpenSession()) + { + SessionIds.Add(s.GetSessionImplementation().SessionId); + s.Get(SessionIds.Count); //will execute some sql + } + return base.OnPrepareStatement(sql); + } + + public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types) + { + using (var s = _sfi.OpenSession()) + { + SessionIds.Add(s.GetSessionImplementation().SessionId); + s.Get(SessionIds.Count); //will execute some sql + } + return base.OnLoad(entity, id, state, propertyNames, types); + } + } + } } diff --git a/src/NHibernate.Test/NHSpecificTest/Logs/LogsFixture.cs b/src/NHibernate.Test/NHSpecificTest/Logs/LogsFixture.cs index a64c0093345..b69bee02597 100644 --- a/src/NHibernate.Test/NHSpecificTest/Logs/LogsFixture.cs +++ b/src/NHibernate.Test/NHSpecificTest/Logs/LogsFixture.cs @@ -1,7 +1,12 @@ using System.Collections; - +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using NHibernate.Cfg; using NHibernate.Impl; - +using NHibernate.SqlCommand; +using NHibernate.Type; using NUnit.Framework; namespace NHibernate.Test.NHSpecificTest.Logs @@ -28,6 +33,33 @@ protected override string MappingsAssembly get { return "NHibernate.Test"; } } + protected override void Configure(Configuration configuration) + { + base.Configure(configuration); + configuration.SetProperty(Cfg.Environment.UseSecondLevelCache, "false"); + } + + protected override void OnSetUp() + { + using (var s = Sfi.OpenSession()) + using (var t = s.BeginTransaction()) + { + s.Save(new Person()); + s.Save(new Person()); + t.Commit(); + } + } + + protected override void OnTearDown() + { + using (var s = Sfi.OpenSession()) + using (var t = s.BeginTransaction()) + { + s.CreateQuery("delete from Person").ExecuteUpdate(); + t.Commit(); + } + } + [Test] public void WillGetSessionIdFromSessionLogs() { @@ -36,15 +68,130 @@ public void WillGetSessionIdFromSessionLogs() using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}")) using (var s = Sfi.OpenSession()) { - var sessionId = ((SessionImpl)s).SessionId; + var sessionId = ((SessionImpl) s).SessionId; - s.Get(1);//will execute some sql + s.Get(1); //will execute some sql var loggingEvent = spy.GetWholeLog(); Assert.That(loggingEvent.Contains(sessionId.ToString()), Is.True); } } + [Test] + public void WillGetSessionIdFromConsecutiveSessionsLogs() + { + GlobalContext.Properties["sessionId"] = new SessionIdCapturer(); + + using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}")) + { + var sessions = Enumerable.Range(1, 10).Select(i => Sfi.OpenSession()).ToArray(); + try + { + for (var i = 0; i < 10; i++) + for (var j = 0; j < 10; j++) + { + var s = sessions[j]; + s.Get(i * 10 + j); //will execute some sql + } + } + finally + { + foreach (var s in sessions) + { + s.Dispose(); + } + } + + var loggingEvent = spy.GetWholeLog(); + for (var i = 0; i < 10; i++) + for (var j = 0; j < 10; j++) + { + var sessionId = sessions[j].GetSessionImplementation().SessionId; + Assert.That(loggingEvent, Does.Contain($"p0 = {i * 10 + j} [Type: Int32 (0:0:0)] | SessionId: {sessionId}")); + } + } + } + + [Test] + public void WillGetSessionIdFromInterlacedSessionsLogs() + { + GlobalContext.Properties["sessionId"] = new SessionIdCapturer(); + var interceptor = new InterlacedSessionInterceptor(Sfi); + using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}")) + using (var s = Sfi.WithOptions().Interceptor(interceptor).OpenSession()) + { + // Trigger an operation which will fire many interceptor events, before and after s own logging. + var persons = s.Query().ToList(); + + var loggingEvent = spy.GetWholeLog(); + for (var i = 0; i < interceptor.SessionIds.Count; i++) + { + var sessionId = interceptor.SessionIds[i]; + Assert.That(loggingEvent, Does.Contain($"p0 = {i + 1} [Type: Int32 (0:0:0)] | SessionId: {sessionId}")); + } + Assert.That(loggingEvent, Does.Contain($"Person person0_ | SessionId: {s.GetSessionImplementation().SessionId}")); + } + } + + [Test] + public void WillGetSessionIdFromSessionLogsConcurrent() + { + GlobalContext.Properties["sessionId"] = new SessionIdCapturer(); + + // Do not use a ManualResetEventSlim, it does not support async and exhausts the task thread pool in the + // async counterparts of this test. SemaphoreSlim has the async support and release the thread when waiting. + var semaphore = new SemaphoreSlim(0); + var failures = new ConcurrentBag(); + var sessionIds = new ConcurrentDictionary(); + using (var spy = new TextLogSpy("NHibernate.SQL", "%message | SessionId: %property{sessionId}")) + { + Parallel.For( + 1, 12, + i => + { + if (i > 10) + { + // Give some time to threads for reaching the wait, having all of them ready to do most of their job concurrently. + Thread.Sleep(100); + semaphore.Release(10); + return; + } + try + { + using (var s = Sfi.OpenSession()) + { + sessionIds.AddOrUpdate( + i, + s.GetSessionImplementation().SessionId, + (ti, old) => throw new InvalidOperationException( + $"Thread number {ti} has already session id {old}, while attempting to set it to" + + $" {s.GetSessionImplementation().SessionId}")); + semaphore.Wait(); + + for (int j = 0; j < 10; j++) + { + s.Get(i * 10 + j); //will execute some sql + } + } + } + catch (Exception e) + { + failures.Add(e); + } + }); + + Assert.That(failures, Is.Empty, $"{failures.Count} task(s) failed."); + + var loggingEvent = spy.GetWholeLog(); + for (var i = 1; i < 11; i++) + for (var j = 0; j < 10; j++) + { + var sessionId = sessionIds[i]; + Assert.That(loggingEvent, Does.Contain($"p0 = {i * 10 + j} [Type: Int32 (0:0:0)] | SessionId: {sessionId}")); + } + } + } + // IFixingRequired interface ensures the value is evaluated at log time rather than at log buffer flush time. public class SessionIdCapturer : IFixingRequired { @@ -72,7 +219,7 @@ public TextLogSpy(string loggerName, string pattern) Threshold = Level.All, Writer = new StringWriter(stringBuilder) }; - loggerImpl = (Logger)LogManager.GetLogger(typeof(LogsFixture).Assembly, loggerName).Logger; + loggerImpl = (Logger) LogManager.GetLogger(typeof(LogsFixture).Assembly, loggerName).Logger; loggerImpl.AddAppender(appender); previousLevel = loggerImpl.Level; loggerImpl.Level = Level.All; @@ -89,7 +236,37 @@ public void Dispose() loggerImpl.Level = previousLevel; } } - } + public class InterlacedSessionInterceptor : EmptyInterceptor + { + private readonly ISessionFactory _sfi; + + public System.Collections.Generic.List SessionIds { get; } = new System.Collections.Generic.List(); + public InterlacedSessionInterceptor(ISessionFactory sfi) + { + _sfi = sfi; + } + + public override SqlString OnPrepareStatement(SqlString sql) + { + using (var s = _sfi.OpenSession()) + { + SessionIds.Add(s.GetSessionImplementation().SessionId); + s.Get(SessionIds.Count); //will execute some sql + } + return base.OnPrepareStatement(sql); + } + + public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, IType[] types) + { + using (var s = _sfi.OpenSession()) + { + SessionIds.Add(s.GetSessionImplementation().SessionId); + s.Get(SessionIds.Count); //will execute some sql + } + return base.OnLoad(entity, id, state, propertyNames, types); + } + } + } } diff --git a/src/NHibernate/Async/Engine/ISessionImplementor.cs b/src/NHibernate/Async/Engine/ISessionImplementor.cs index dc638d67676..ee08870c55d 100644 --- a/src/NHibernate/Async/Engine/ISessionImplementor.cs +++ b/src/NHibernate/Async/Engine/ISessionImplementor.cs @@ -28,6 +28,7 @@ namespace NHibernate.Engine { using System.Threading.Tasks; using System.Threading; + public partial interface ISessionImplementor { diff --git a/src/NHibernate/Async/Event/IEventSource.cs b/src/NHibernate/Async/Event/IEventSource.cs index 19021969bea..12d5b1f0c19 100644 --- a/src/NHibernate/Async/Event/IEventSource.cs +++ b/src/NHibernate/Async/Event/IEventSource.cs @@ -35,7 +35,7 @@ public partial interface IEventSource : ISessionImplementor, ISession /// Cascade refresh an entity instance Task RefreshAsync(object obj, IDictionary refreshedAlready, CancellationToken cancellationToken); - + /// Cascade delete an entity instance Task DeleteAsync(string entityName, object child, bool isCascadeDeleteEnabled, ISet transientEntities, CancellationToken cancellationToken); } diff --git a/src/NHibernate/Async/Id/Insert/AbstractSelectingDelegate.cs b/src/NHibernate/Async/Id/Insert/AbstractSelectingDelegate.cs index a3069bb05bb..fab195e7602 100644 --- a/src/NHibernate/Async/Id/Insert/AbstractSelectingDelegate.cs +++ b/src/NHibernate/Async/Id/Insert/AbstractSelectingDelegate.cs @@ -54,7 +54,7 @@ public async Task PerformInsertAsync(SqlCommandInfo insertSql, ISessionI } var selectSql = SelectSQL; - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { try { @@ -124,4 +124,4 @@ protected internal virtual Task BindParametersAsync(ISessionImplementor session, } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Impl/AbstractSessionImpl.cs b/src/NHibernate/Async/Impl/AbstractSessionImpl.cs index ea7333f8439..72a5433f7f0 100644 --- a/src/NHibernate/Async/Impl/AbstractSessionImpl.cs +++ b/src/NHibernate/Async/Impl/AbstractSessionImpl.cs @@ -58,7 +58,7 @@ public virtual async Task ListAsync(IQueryExpression queryExpression, Que public virtual async Task> ListAsync(IQueryExpression query, QueryParameters parameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); await (ListAsync(query, parameters, results, cancellationToken)).ConfigureAwait(false); @@ -69,7 +69,7 @@ public virtual async Task> ListAsync(IQueryExpression query, QueryPa public virtual async Task> ListAsync(CriteriaImpl criteria, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); await (ListAsync(criteria, results, cancellationToken)).ConfigureAwait(false); @@ -82,7 +82,7 @@ public virtual async Task> ListAsync(CriteriaImpl criteria, Cancella public virtual async Task ListAsync(CriteriaImpl criteria, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); await (ListAsync(criteria, results, cancellationToken)).ConfigureAwait(false); @@ -113,7 +113,7 @@ public async Task ListFilterAsync(object collection, IQueryExpression que public virtual async Task ListAsync(NativeSQLQuerySpecification spec, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); await (ListAsync(spec, queryParameters, results, cancellationToken)).ConfigureAwait(false); @@ -124,7 +124,7 @@ public virtual async Task ListAsync(NativeSQLQuerySpecification spec, Que public virtual async Task ListAsync(NativeSQLQuerySpecification spec, QueryParameters queryParameters, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var query = new SQLCustomQuery( spec.SqlQueryReturns, @@ -138,7 +138,7 @@ public virtual async Task ListAsync(NativeSQLQuerySpecification spec, QueryParam public virtual async Task> ListAsync(NativeSQLQuerySpecification spec, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); await (ListAsync(spec, queryParameters, results, cancellationToken)).ConfigureAwait(false); @@ -151,7 +151,7 @@ public virtual async Task> ListAsync(NativeSQLQuerySpecification spe public virtual async Task> ListCustomQueryAsync(ICustomQuery customQuery, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); await (ListCustomQueryAsync(customQuery, queryParameters, results, cancellationToken)).ConfigureAwait(false); @@ -170,7 +170,7 @@ public virtual async Task> ListCustomQueryAsync(ICustomQuery customQ protected async Task AfterOperationAsync(bool success, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { if (!ConnectionManager.IsInActiveTransaction) { diff --git a/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs b/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs index cf29b30d2a9..7fa5ea1175f 100644 --- a/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs +++ b/src/NHibernate/Async/Impl/MultiCriteriaImpl.cs @@ -33,7 +33,7 @@ public partial class MultiCriteriaImpl : IMultiCriteria public async Task ListAsync(CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { bool cacheable = session.Factory.Settings.IsQueryCacheEnabled && isCacheable; diff --git a/src/NHibernate/Async/Impl/MultiQueryImpl.cs b/src/NHibernate/Async/Impl/MultiQueryImpl.cs index d6d69984a5b..06281206c97 100644 --- a/src/NHibernate/Async/Impl/MultiQueryImpl.cs +++ b/src/NHibernate/Async/Impl/MultiQueryImpl.cs @@ -39,7 +39,7 @@ public partial class MultiQueryImpl : IMultiQuery public async Task ListAsync(CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { bool cacheable = session.Factory.Settings.IsQueryCacheEnabled && isCacheable; combinedParameters = CreateCombinedQueryParameters(); diff --git a/src/NHibernate/Async/Impl/SessionImpl.cs b/src/NHibernate/Async/Impl/SessionImpl.cs index 0f027fa0484..68cc9b4d6f1 100644 --- a/src/NHibernate/Async/Impl/SessionImpl.cs +++ b/src/NHibernate/Async/Impl/SessionImpl.cs @@ -49,7 +49,7 @@ public sealed partial class SessionImpl : AbstractSessionImpl, IEventSource, ISe public override async Task AfterTransactionCompletionAsync(bool success, ITransaction tx, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { log.Debug("transaction completion"); @@ -90,7 +90,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task SaveAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return await (FireSaveAsync(new SaveOrUpdateEvent(null, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -99,7 +99,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task SaveAsync(string entityName, object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return await (FireSaveAsync(new SaveOrUpdateEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -108,7 +108,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task SaveAsync(string entityName, object obj, object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireSaveAsync(new SaveOrUpdateEvent(entityName, obj, id, this), cancellationToken)).ConfigureAwait(false); } @@ -123,7 +123,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task SaveAsync(object obj, object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireSaveAsync(new SaveOrUpdateEvent(null, obj, id, this), cancellationToken)).ConfigureAwait(false); } @@ -137,7 +137,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task DeleteAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireDeleteAsync(new DeleteEvent(obj, this), cancellationToken)).ConfigureAwait(false); } @@ -147,7 +147,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task DeleteAsync(string entityName, object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireDeleteAsync(new DeleteEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -156,7 +156,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task UpdateAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireUpdateAsync(new SaveOrUpdateEvent(null, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -165,7 +165,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task UpdateAsync(string entityName, object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireUpdateAsync(new SaveOrUpdateEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -174,7 +174,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task UpdateAsync(string entityName, object obj, object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireUpdateAsync(new SaveOrUpdateEvent(entityName, obj, id, this), cancellationToken)).ConfigureAwait(false); } @@ -183,7 +183,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task SaveOrUpdateAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireSaveOrUpdateAsync(new SaveOrUpdateEvent(null, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -192,7 +192,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task SaveOrUpdateAsync(string entityName, object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireSaveOrUpdateAsync(new SaveOrUpdateEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -201,7 +201,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task SaveOrUpdateAsync(string entityName, object obj, object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireSaveOrUpdateAsync(new SaveOrUpdateEvent(entityName, obj, id, this), cancellationToken)).ConfigureAwait(false); } @@ -210,7 +210,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa public async Task UpdateAsync(object obj, object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireUpdateAsync(new SaveOrUpdateEvent(null, obj, id, this), cancellationToken)).ConfigureAwait(false); } @@ -219,7 +219,7 @@ public override async Task AfterTransactionCompletionAsync(bool success, ITransa async Task FindAsync(string query, object[] values, IType[] types, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return await (ListAsync(query.ToQueryExpression(), new QueryParameters(types, values), cancellationToken)).ConfigureAwait(false); } @@ -248,9 +248,8 @@ protected override Task ListFilterAsync(object collection, IQueryExpression quer private async Task ListAsync(IQueryExpression queryExpression, QueryParameters queryParameters, IList results, object filterConnection, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var isFilter = filterConnection != null; @@ -290,7 +289,7 @@ private async Task ListAsync(IQueryExpression queryExpression, QueryParameters q public override async Task GetQueriesAsync(IQueryExpression query, bool scalar, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var plan = Factory.QueryPlanCache.GetHQLQueryPlan(query, scalar, enabledFilters); await (AutoFlushIfRequiredAsync(plan.QuerySpaces, cancellationToken)).ConfigureAwait(false); @@ -301,9 +300,8 @@ public override async Task GetQueriesAsync(IQueryExpression public override async Task> EnumerableAsync(IQueryExpression queryExpression, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, true); await (AutoFlushIfRequiredAsync(plan.QuerySpaces, cancellationToken)).ConfigureAwait(false); @@ -318,9 +316,8 @@ public override async Task> EnumerableAsync(IQueryExpression q public override async Task EnumerableAsync(IQueryExpression queryExpression, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, true); await (AutoFlushIfRequiredAsync(plan.QuerySpaces, cancellationToken)).ConfigureAwait(false); @@ -334,36 +331,34 @@ public override async Task EnumerableAsync(IQueryExpression queryEx // TODO: Scroll(string query, QueryParameters queryParameters) - public async Task DeleteAsync(string query, CancellationToken cancellationToken = default(CancellationToken)) + public Task DeleteAsync(string query, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - return await (DeleteAsync(query, NoArgs, NoTypes, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return DeleteAsync(query, NoArgs, NoTypes, cancellationToken); } - public async Task DeleteAsync(string query, object value, IType type, CancellationToken cancellationToken = default(CancellationToken)) + public Task DeleteAsync(string query, object value, IType type, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - return await (DeleteAsync(query, new[] { value }, new[] { type }, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return DeleteAsync(query, new[] { value }, new[] { type }, cancellationToken); } public async Task DeleteAsync(string query, object[] values, IType[] types, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (string.IsNullOrEmpty(query)) { throw new ArgumentNullException("query", "attempt to perform delete-by-query with null query"); } - CheckAndUpdateSessionStatus(); - if (log.IsDebugEnabled) { log.Debug("delete: " + query); @@ -386,7 +381,7 @@ public override async Task EnumerableAsync(IQueryExpression queryEx public async Task LockAsync(object obj, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireLockAsync(new LockEvent(obj, lockMode, this), cancellationToken)).ConfigureAwait(false); } @@ -395,7 +390,7 @@ public override async Task EnumerableAsync(IQueryExpression queryEx public async Task LockAsync(string entityName, object obj, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireLockAsync(new LockEvent(entityName, obj, lockMode, this), cancellationToken)).ConfigureAwait(false); } @@ -404,10 +399,8 @@ public override async Task EnumerableAsync(IQueryExpression queryEx public async Task CreateFilterAsync(object collection, string queryString, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - var plan = await (GetFilterQueryPlanAsync(collection, queryString, null, false, cancellationToken)).ConfigureAwait(false); var filter = new CollectionFilterImpl(queryString, collection, this, plan.ParameterMetadata); //filter.SetComment(queryString); @@ -418,10 +411,8 @@ public override async Task EnumerableAsync(IQueryExpression queryEx public override async Task CreateFilterAsync(object collection, IQueryExpression queryExpression, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - var plan = await (GetFilterQueryPlanAsync(collection, queryExpression, null, false, cancellationToken)).ConfigureAwait(false); var filter = new ExpressionFilterImpl(plan.QueryExpression, collection, this, plan.ParameterMetadata); return filter; @@ -446,18 +437,22 @@ private Task GetFilterQueryPlanAsync(object collection, st return GetFilterQueryPlanAsync(collection, parameters, shallow, filter, null, cancellationToken); } - private async Task GetFilterQueryPlanAsync(object collection, QueryParameters parameters, bool shallow, + private Task GetFilterQueryPlanAsync(object collection, QueryParameters parameters, bool shallow, string filter, IQueryExpression queryExpression, CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (collection == null) + throw new ArgumentNullException(nameof(collection), "null collection passed to filter"); + if (filter != null && queryExpression != null) + throw new ArgumentException($"Either {nameof(filter)} or {nameof(queryExpression)} must be specified, not both."); + if (filter == null && queryExpression == null) + throw new ArgumentException($"{nameof(filter)} and {nameof(queryExpression)} were both null."); + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + return InternalGetFilterQueryPlanAsync(); + async Task InternalGetFilterQueryPlanAsync() { - if (collection == null) - throw new ArgumentNullException(nameof(collection), "null collection passed to filter"); - if (filter != null && queryExpression != null) - throw new ArgumentException($"Either {nameof(filter)} or {nameof(queryExpression)} must be specified, not both."); - if (filter == null && queryExpression == null) - throw new ArgumentException($"{nameof(filter)} and {nameof(queryExpression)} were both null."); var entry = persistenceContext.GetCollectionEntryOrNull(collection); var roleBeforeFlush = entry?.LoadedPersister; @@ -513,9 +508,8 @@ private async Task GetFilterQueryPlanAsync(object collecti public async Task ForceFlushAsync(EntityEntry entityEntry, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); if (log.IsDebugEnabled) { log.Debug("flushing to force deletion of re-saved object: " + @@ -538,7 +532,7 @@ public async Task ForceFlushAsync(EntityEntry entityEntry, CancellationToken can public async Task MergeAsync(string entityName, object obj, IDictionary copiedAlready, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireMergeAsync(copiedAlready, new MergeEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -548,7 +542,7 @@ public async Task MergeAsync(string entityName, object obj, IDictionary copiedAl public async Task PersistAsync(string entityName, object obj, IDictionary createdAlready, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FirePersistAsync(createdAlready, new PersistEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -558,7 +552,7 @@ public async Task PersistAsync(string entityName, object obj, IDictionary create public async Task PersistOnFlushAsync(string entityName, object obj, IDictionary copiedAlready, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FirePersistOnFlushAsync(copiedAlready, new PersistEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -568,7 +562,7 @@ public async Task PersistOnFlushAsync(string entityName, object obj, IDictionary public async Task RefreshAsync(object obj, IDictionary refreshedAlready, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireRefreshAsync(refreshedAlready, new RefreshEvent(obj, this), cancellationToken)).ConfigureAwait(false); } @@ -578,7 +572,7 @@ public async Task RefreshAsync(object obj, IDictionary refreshedAlready, Cancell public async Task DeleteAsync(string entityName, object child, bool isCascadeDeleteEnabled, ISet transientEntities, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireDeleteAsync(new DeleteEvent(entityName, child, isCascadeDeleteEnabled, this), transientEntities, cancellationToken)).ConfigureAwait(false); } @@ -589,7 +583,7 @@ public async Task DeleteAsync(string entityName, object child, bool isCascadeDel public async Task MergeAsync(string entityName, object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return await (FireMergeAsync(new MergeEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } @@ -607,57 +601,56 @@ public async Task DeleteAsync(string entityName, object child, bool isCascadeDel return (T)await (MergeAsync(entityName, (object)entity, cancellationToken)).ConfigureAwait(false); } - public async Task MergeAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) + public Task MergeAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - return await (MergeAsync(null, obj, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return MergeAsync(null, obj, cancellationToken); } public async Task PersistAsync(string entityName, object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FirePersistAsync(new PersistEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } } - public async Task PersistAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) + public Task PersistAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - await (PersistAsync(null, obj, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return PersistAsync(null, obj, cancellationToken); } public async Task PersistOnFlushAsync(string entityName, object obj, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FirePersistOnFlushAsync(new PersistEvent(entityName, obj, this), cancellationToken)).ConfigureAwait(false); } } - public async Task PersistOnFlushAsync(object obj, CancellationToken cancellationToken) + public Task PersistOnFlushAsync(object obj, CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - await (PersistAsync(null, obj, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return PersistAsync(null, obj, cancellationToken); } public override async Task GetEntityUsingInterceptorAsync(EntityKey key, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); // todo : should this get moved to PersistentContext? // logically, is PersistentContext the "thing" to which an interceptor gets attached? object result = persistenceContext.GetEntity(key); @@ -688,9 +681,8 @@ public override async Task GetEntityUsingInterceptorAsync(EntityKey key, private async Task AutoFlushIfRequiredAsync(ISet querySpaces, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); if (!ConnectionManager.IsInActiveTransaction) { // do not auto-flush while outside a transaction @@ -711,7 +703,7 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public async Task LoadAsync(object obj, object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { LoadEvent loadEvent = new LoadEvent(id, obj, this); await (FireLoadAsync(loadEvent, LoadEventListener.Reload, cancellationToken)).ConfigureAwait(false); @@ -721,7 +713,7 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public async Task LoadAsync(object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)await (LoadAsync(typeof(T), id, cancellationToken)).ConfigureAwait(false); } @@ -730,7 +722,7 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public async Task LoadAsync(object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)await (LoadAsync(typeof(T), id, lockMode, cancellationToken)).ConfigureAwait(false); } @@ -751,19 +743,19 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc /// /// Thrown when the object with the specified id does not exist in the database. /// - public async Task LoadAsync(System.Type entityClass, object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) + public Task LoadAsync(System.Type entityClass, object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - return await (LoadAsync(entityClass.FullName, id, lockMode, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return LoadAsync(entityClass.FullName, id, lockMode, cancellationToken); } public async Task LoadAsync(string entityName, object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (id == null) { @@ -792,7 +784,7 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public async Task LoadAsync(string entityName, object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var @event = new LoadEvent(id, entityName, lockMode, this); await (FireLoadAsync(@event, LoadEventListener.Load, cancellationToken)).ConfigureAwait(false); @@ -800,19 +792,19 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc } } - public async Task LoadAsync(System.Type entityClass, object id, CancellationToken cancellationToken = default(CancellationToken)) + public Task LoadAsync(System.Type entityClass, object id, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - return await (LoadAsync(entityClass.FullName, id, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return LoadAsync(entityClass.FullName, id, cancellationToken); } public async Task GetAsync(object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)await (GetAsync(typeof(T), id, cancellationToken)).ConfigureAwait(false); } @@ -821,19 +813,19 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public async Task GetAsync(object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)await (GetAsync(typeof(T), id, lockMode, cancellationToken)).ConfigureAwait(false); } } - public async Task GetAsync(System.Type entityClass, object id, CancellationToken cancellationToken = default(CancellationToken)) + public Task GetAsync(System.Type entityClass, object id, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - return await (GetAsync(entityClass.FullName, id, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return GetAsync(entityClass.FullName, id, cancellationToken); } /// @@ -851,7 +843,7 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public async Task GetAsync(System.Type clazz, object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { LoadEvent loadEvent = new LoadEvent(id, clazz.FullName, lockMode, this); await (FireLoadAsync(loadEvent, LoadEventListener.Get, cancellationToken)).ConfigureAwait(false); @@ -862,10 +854,8 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public async Task GetEntityNameAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - if (obj.IsProxy()) { var proxy = obj as INHibernateProxy; @@ -893,7 +883,7 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public async Task GetAsync(string entityName, object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { LoadEvent loadEvent = new LoadEvent(id, entityName, false, this); bool success = false; @@ -918,7 +908,7 @@ private async Task AutoFlushIfRequiredAsync(ISet querySpaces, Canc public override async Task ImmediateLoadAsync(string entityName, object id, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (log.IsDebugEnabled) { @@ -940,7 +930,7 @@ public override async Task ImmediateLoadAsync(string entityName, object public override async Task InternalLoadAsync(string entityName, object id, bool eager, bool isNullable, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { // todo : remove LoadType type = isNullable @@ -961,7 +951,7 @@ public override async Task InternalLoadAsync(string entityName, object i public async Task RefreshAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireRefreshAsync(new RefreshEvent(obj, this), cancellationToken)).ConfigureAwait(false); } @@ -970,7 +960,7 @@ public override async Task InternalLoadAsync(string entityName, object i public async Task RefreshAsync(object obj, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireRefreshAsync(new RefreshEvent(obj, lockMode, this), cancellationToken)).ConfigureAwait(false); } @@ -1001,9 +991,8 @@ public override async Task InternalLoadAsync(string entityName, object i public override async Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); if (persistenceContext.CascadeLevel > 0) { throw new HibernateException("Flush during cascade is dangerous"); @@ -1022,10 +1011,8 @@ public override async Task InternalLoadAsync(string entityName, object i public async Task IsDirtyAsync(CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - log.Debug("checking session dirtiness"); if (actionQueue.AreInsertionsOrDeletionsQueued) { @@ -1054,9 +1041,8 @@ public override async Task InternalLoadAsync(string entityName, object i public override async Task InitializeCollectionAsync(IPersistentCollection collection, bool writing, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IInitializeCollectionEventListener[] listener = listeners.InitializeCollectionEventListeners; for (int i = 0; i < listener.Length; i++) { @@ -1068,9 +1054,8 @@ public override async Task InitializeCollectionAsync(IPersistentCollection colle private async Task FilterAsync(object collection, string filter, QueryParameters queryParameters, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var plan = await (GetFilterQueryPlanAsync(collection, filter, queryParameters, false, cancellationToken)).ConfigureAwait(false); bool success = false; @@ -1101,31 +1086,24 @@ private async Task FilterAsync(object collection, string filter, QueryParameters public override async Task ListFilterAsync(object collection, string filter, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) - { - var results = new List(); - await (FilterAsync(collection, filter, queryParameters, results, cancellationToken)).ConfigureAwait(false); - return results; - } + var results = new List(); + await (FilterAsync(collection, filter, queryParameters, results, cancellationToken)).ConfigureAwait(false); + return results; } public override async Task> ListFilterAsync(object collection, string filter, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) - { - List results = new List(); - await (FilterAsync(collection, filter, queryParameters, results, cancellationToken)).ConfigureAwait(false); - return results; - } + List results = new List(); + await (FilterAsync(collection, filter, queryParameters, results, cancellationToken)).ConfigureAwait(false); + return results; } public override async Task EnumerableFilterAsync(object collection, string filter, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var plan = await (GetFilterQueryPlanAsync(collection, filter, queryParameters, true, cancellationToken)).ConfigureAwait(false); return await (plan.PerformIterateAsync(queryParameters, this, cancellationToken)).ConfigureAwait(false); } @@ -1134,9 +1112,8 @@ public override async Task EnumerableFilterAsync(object collection, public override async Task> EnumerableFilterAsync(object collection, string filter, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var plan = await (GetFilterQueryPlanAsync(collection, filter, queryParameters, true, cancellationToken)).ConfigureAwait(false); return await (plan.PerformIterateAsync(queryParameters, this, cancellationToken)).ConfigureAwait(false); } @@ -1145,10 +1122,8 @@ public override async Task> EnumerableFilterAsync(object colle public override async Task ListAsync(CriteriaImpl criteria, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - string[] implementors = Factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; @@ -1207,7 +1182,7 @@ public override async Task ListAsync(CriteriaImpl criteria, IList results, Cance public async Task EvictAsync(object obj, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireEvictAsync(new EvictEvent(obj, this), cancellationToken)).ConfigureAwait(false); } @@ -1216,10 +1191,8 @@ public override async Task ListAsync(CriteriaImpl criteria, IList results, Cance public override async Task ListCustomQueryAsync(ICustomQuery customQuery, QueryParameters queryParameters, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - CustomLoader loader = new CustomLoader(customQuery, Factory); await (AutoFlushIfRequiredAsync(loader.QuerySpaces, cancellationToken)).ConfigureAwait(false); @@ -1242,7 +1215,7 @@ public override async Task ListCustomQueryAsync(ICustomQuery customQuery, QueryP public async Task ReplicateAsync(object obj, ReplicationMode replicationMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireReplicateAsync(new ReplicateEvent(obj, replicationMode, this), cancellationToken)).ConfigureAwait(false); } @@ -1251,7 +1224,7 @@ public override async Task ListCustomQueryAsync(ICustomQuery customQuery, QueryP public async Task ReplicateAsync(string entityName, object obj, ReplicationMode replicationMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (FireReplicateAsync(new ReplicateEvent(entityName, obj, replicationMode, this), cancellationToken)).ConfigureAwait(false); } @@ -1260,7 +1233,7 @@ public override async Task ListCustomQueryAsync(ICustomQuery customQuery, QueryP public override async Task BeforeTransactionCompletionAsync(ITransaction tx, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { log.Debug("before transaction completion"); var context = TransactionContext; @@ -1283,22 +1256,29 @@ public override async Task BeforeTransactionCompletionAsync(ITransaction tx, Can } } - public override async Task FlushBeforeTransactionCompletionAsync(CancellationToken cancellationToken) + public override Task FlushBeforeTransactionCompletionAsync(CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + try { if (FlushMode != FlushMode.Manual) - await (FlushAsync(cancellationToken)).ConfigureAwait(false); + return FlushAsync(cancellationToken); + return Task.CompletedTask; + } + catch (Exception ex) + { + return Task.FromException(ex); } } private async Task FireDeleteAsync(DeleteEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IDeleteEventListener[] deleteEventListener = listeners.DeleteEventListeners; for (int i = 0; i < deleteEventListener.Length; i++) { @@ -1310,9 +1290,8 @@ private async Task FireDeleteAsync(DeleteEvent @event, CancellationToken cancell private async Task FireDeleteAsync(DeleteEvent @event, ISet transientEntities, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IDeleteEventListener[] deleteEventListener = listeners.DeleteEventListeners; for (int i = 0; i < deleteEventListener.Length; i++) { @@ -1324,9 +1303,8 @@ private async Task FireDeleteAsync(DeleteEvent @event, ISet transientEnt private async Task FireEvictAsync(EvictEvent evictEvent, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEvictEventListener[] evictEventListener = listeners.EvictEventListeners; for (int i = 0; i < evictEventListener.Length; i++) { @@ -1338,9 +1316,8 @@ private async Task FireEvictAsync(EvictEvent evictEvent, CancellationToken cance private async Task FireLoadAsync(LoadEvent @event, LoadType loadType, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ILoadEventListener[] loadEventListener = listeners.LoadEventListeners; for (int i = 0; i < loadEventListener.Length; i++) { @@ -1352,9 +1329,8 @@ private async Task FireLoadAsync(LoadEvent @event, LoadType loadType, Cancellati private async Task FireLockAsync(LockEvent lockEvent, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ILockEventListener[] lockEventListener = listeners.LockEventListeners; for (int i = 0; i < lockEventListener.Length; i++) { @@ -1366,9 +1342,8 @@ private async Task FireLockAsync(LockEvent lockEvent, CancellationToken cancella private async Task FireMergeAsync(MergeEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IMergeEventListener[] mergeEventListener = listeners.MergeEventListeners; for (int i = 0; i < mergeEventListener.Length; i++) { @@ -1381,9 +1356,8 @@ private async Task FireMergeAsync(MergeEvent @event, CancellationToken c private async Task FireMergeAsync(IDictionary copiedAlready, MergeEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IMergeEventListener[] mergeEventListener = listeners.MergeEventListeners; for (int i = 0; i < mergeEventListener.Length; i++) { @@ -1395,9 +1369,8 @@ private async Task FireMergeAsync(IDictionary copiedAlready, MergeEvent @event, private async Task FirePersistAsync(IDictionary copiedAlready, PersistEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IPersistEventListener[] persistEventListener = listeners.PersistEventListeners; for (int i = 0; i < persistEventListener.Length; i++) { @@ -1409,9 +1382,8 @@ private async Task FirePersistAsync(IDictionary copiedAlready, PersistEvent @eve private async Task FirePersistAsync(PersistEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IPersistEventListener[] createEventListener = listeners.PersistEventListeners; for (int i = 0; i < createEventListener.Length; i++) { @@ -1423,9 +1395,8 @@ private async Task FirePersistAsync(PersistEvent @event, CancellationToken cance private async Task FirePersistOnFlushAsync(IDictionary copiedAlready, PersistEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IPersistEventListener[] persistEventListener = listeners.PersistOnFlushEventListeners; for (int i = 0; i < persistEventListener.Length; i++) { @@ -1437,9 +1408,8 @@ private async Task FirePersistOnFlushAsync(IDictionary copiedAlready, PersistEve private async Task FirePersistOnFlushAsync(PersistEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IPersistEventListener[] createEventListener = listeners.PersistOnFlushEventListeners; for (int i = 0; i < createEventListener.Length; i++) { @@ -1451,9 +1421,8 @@ private async Task FirePersistOnFlushAsync(PersistEvent @event, CancellationToke private async Task FireRefreshAsync(RefreshEvent refreshEvent, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IRefreshEventListener[] refreshEventListener = listeners.RefreshEventListeners; for (int i = 0; i < refreshEventListener.Length; i++) { @@ -1465,9 +1434,8 @@ private async Task FireRefreshAsync(RefreshEvent refreshEvent, CancellationToken private async Task FireRefreshAsync(IDictionary refreshedAlready, RefreshEvent refreshEvent, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IRefreshEventListener[] refreshEventListener = listeners.RefreshEventListeners; for (int i = 0; i < refreshEventListener.Length; i++) { @@ -1479,9 +1447,8 @@ private async Task FireRefreshAsync(IDictionary refreshedAlready, RefreshEvent r private async Task FireReplicateAsync(ReplicateEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IReplicateEventListener[] replicateEventListener = listeners.ReplicateEventListeners; for (int i = 0; i < replicateEventListener.Length; i++) { @@ -1493,9 +1460,8 @@ private async Task FireReplicateAsync(ReplicateEvent @event, CancellationToken c private async Task FireSaveAsync(SaveOrUpdateEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ISaveOrUpdateEventListener[] saveEventListener = listeners.SaveEventListeners; for (int i = 0; i < saveEventListener.Length; i++) { @@ -1508,9 +1474,8 @@ private async Task FireSaveAsync(SaveOrUpdateEvent @event, CancellationT private async Task FireSaveOrUpdateAsync(SaveOrUpdateEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ISaveOrUpdateEventListener[] saveOrUpdateEventListener = listeners.SaveOrUpdateEventListeners; for (int i = 0; i < saveOrUpdateEventListener.Length; i++) { @@ -1522,9 +1487,8 @@ private async Task FireSaveOrUpdateAsync(SaveOrUpdateEvent @event, CancellationT private async Task FireUpdateAsync(SaveOrUpdateEvent @event, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ISaveOrUpdateEventListener[] updateEventListener = listeners.UpdateEventListeners; for (int i = 0; i < updateEventListener.Length; i++) { @@ -1536,9 +1500,8 @@ private async Task FireUpdateAsync(SaveOrUpdateEvent @event, CancellationToken c public override async Task ExecuteNativeUpdateAsync(NativeSQLQuerySpecification nativeQuerySpecification, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); NativeSQLQueryPlan plan = GetNativeSQLQueryPlan(nativeQuerySpecification); @@ -1562,9 +1525,8 @@ public override async Task ExecuteNativeUpdateAsync(NativeSQLQuerySpecifica public override async Task ExecuteUpdateAsync(IQueryExpression queryExpression, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, false); await (AutoFlushIfRequiredAsync(plan.QuerySpaces, cancellationToken)).ConfigureAwait(false); diff --git a/src/NHibernate/Async/Impl/StatelessSessionImpl.cs b/src/NHibernate/Async/Impl/StatelessSessionImpl.cs index 3f3a097c272..03b8bb20832 100644 --- a/src/NHibernate/Async/Impl/StatelessSessionImpl.cs +++ b/src/NHibernate/Async/Impl/StatelessSessionImpl.cs @@ -66,9 +66,8 @@ public override Task InitializeCollectionAsync(IPersistentCollection collection, public override async Task InternalLoadAsync(string entityName, object id, bool eager, bool isNullable, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEntityPersister persister = Factory.GetEntityPersister(entityName); object loaded = temporaryPersistenceContext.GetEntity(GenerateEntityKey(id, persister)); if (loaded != null) @@ -97,9 +96,8 @@ public override Task CreateFilterAsync(object collection, IQueryExpressi public override async Task ListAsync(IQueryExpression queryExpression, QueryParameters queryParameters, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, false); @@ -129,9 +127,8 @@ public override async Task ListAsync(IQueryExpression queryExpression, QueryPara public override async Task ListAsync(CriteriaImpl criteria, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); string[] implementors = Factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; @@ -225,13 +222,21 @@ public override Task BeforeTransactionCompletionAsync(ITransaction tx, Cancellat } } - public override async Task FlushBeforeTransactionCompletionAsync(CancellationToken cancellationToken) + public override Task FlushBeforeTransactionCompletionAsync(CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + try { if (FlushMode != FlushMode.Manual) - await (FlushAsync(cancellationToken)).ConfigureAwait(false); + return FlushAsync(cancellationToken); + return Task.CompletedTask; + } + catch (Exception ex) + { + return Task.FromException(ex); } } @@ -255,10 +260,8 @@ public override Task AfterTransactionCompletionAsync(bool successful, ITransacti public override async Task ListCustomQueryAsync(ICustomQuery customQuery, QueryParameters queryParameters, IList results, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - var loader = new CustomLoader(customQuery, Factory); var success = false; @@ -307,21 +310,20 @@ public override Task GetEntityUsingInterceptorAsync(EntityKey key, Cance } } - public override async Task FlushAsync(CancellationToken cancellationToken) + public override Task FlushAsync(CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - await (ManagedFlushAsync(cancellationToken)).ConfigureAwait(false); // NH Different behavior since ADOContext.Context is not implemented + return Task.FromCanceled(cancellationToken); } + return ManagedFlushAsync(cancellationToken); // NH Different behavior since ADOContext.Context is not implemented } public async Task ManagedFlushAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); await (Batcher.ExecuteBatchAsync(cancellationToken)).ConfigureAwait(false); } } @@ -332,14 +334,13 @@ public async Task ManagedFlushAsync(CancellationToken cancellationToken) /// A new transient instance /// A cancellation token that can be used to cancel the work /// the identifier of the instance - public async Task InsertAsync(object entity, CancellationToken cancellationToken = default(CancellationToken)) + public Task InsertAsync(object entity, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - CheckAndUpdateSessionStatus(); - return await (InsertAsync(null, entity, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return InsertAsync(null, entity, cancellationToken); } /// Insert a row. @@ -350,9 +351,8 @@ public async Task ManagedFlushAsync(CancellationToken cancellationToken) public async Task InsertAsync(string entityName, object entity, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEntityPersister persister = GetEntityPersister(entityName, entity); object id = await (persister.IdentifierGenerator.GenerateAsync(this, entity, cancellationToken)).ConfigureAwait(false); object[] state = persister.GetPropertyValues(entity); @@ -382,14 +382,13 @@ public async Task ManagedFlushAsync(CancellationToken cancellationToken) /// Update a entity. /// a detached entity instance /// A cancellation token that can be used to cancel the work - public async Task UpdateAsync(object entity, CancellationToken cancellationToken = default(CancellationToken)) + public Task UpdateAsync(object entity, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - CheckAndUpdateSessionStatus(); - await (UpdateAsync(null, entity, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return UpdateAsync(null, entity, cancellationToken); } /// Update a entity. @@ -399,9 +398,8 @@ public async Task ManagedFlushAsync(CancellationToken cancellationToken) public async Task UpdateAsync(string entityName, object entity, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.GetIdentifier(entity); object[] state = persister.GetPropertyValues(entity); @@ -424,14 +422,13 @@ public async Task ManagedFlushAsync(CancellationToken cancellationToken) /// Delete a entity. /// a detached entity instance /// A cancellation token that can be used to cancel the work - public async Task DeleteAsync(object entity, CancellationToken cancellationToken = default(CancellationToken)) + public Task DeleteAsync(object entity, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - CheckAndUpdateSessionStatus(); - await (DeleteAsync(null, entity, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return DeleteAsync(null, entity, cancellationToken); } /// Delete a entity. @@ -441,9 +438,8 @@ public async Task ManagedFlushAsync(CancellationToken cancellationToken) public async Task DeleteAsync(string entityName, object entity, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.GetIdentifier(entity); object version = persister.GetVersion(entity); @@ -453,13 +449,13 @@ public async Task ManagedFlushAsync(CancellationToken cancellationToken) /// Retrieve a entity. /// a detached entity instance - public async Task GetAsync(string entityName, object id, CancellationToken cancellationToken = default(CancellationToken)) + public Task GetAsync(string entityName, object id, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - return await (GetAsync(entityName, id, LockMode.None, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return GetAsync(entityName, id, LockMode.None, cancellationToken); } /// Retrieve a entity. @@ -470,19 +466,19 @@ public async Task ManagedFlushAsync(CancellationToken cancellationToken) public async Task GetAsync(object id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)await (GetAsync(typeof(T), id, cancellationToken)).ConfigureAwait(false); } } - private async Task GetAsync(System.Type persistentClass, object id, CancellationToken cancellationToken) + private Task GetAsync(System.Type persistentClass, object id, CancellationToken cancellationToken) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - return await (GetAsync(persistentClass.FullName, id, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return GetAsync(persistentClass.FullName, id, cancellationToken); } /// @@ -492,9 +488,8 @@ private async Task GetAsync(System.Type persistentClass, object id, Canc public async Task GetAsync(string entityName, object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); object result = await (Factory.GetEntityPersister(entityName).LoadAsync(id, null, lockMode, this, cancellationToken)).ConfigureAwait(false); if (temporaryPersistenceContext.IsLoadFinished) { @@ -511,7 +506,7 @@ private async Task GetAsync(System.Type persistentClass, object id, Canc public async Task GetAsync(object id, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)await (GetAsync(typeof(T).FullName, id, lockMode, cancellationToken)).ConfigureAwait(false); } @@ -525,7 +520,7 @@ private async Task GetAsync(System.Type persistentClass, object id, Canc public async Task RefreshAsync(object entity, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (RefreshAsync(BestGuessEntityName(entity), entity, LockMode.None, cancellationToken)).ConfigureAwait(false); } @@ -537,13 +532,13 @@ private async Task GetAsync(System.Type persistentClass, object id, Canc /// The entityName for the entity to be refreshed. /// The entity to be refreshed. /// A cancellation token that can be used to cancel the work - public async Task RefreshAsync(string entityName, object entity, CancellationToken cancellationToken = default(CancellationToken)) + public Task RefreshAsync(string entityName, object entity, CancellationToken cancellationToken = default(CancellationToken)) { - cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + if (cancellationToken.IsCancellationRequested) { - await (RefreshAsync(entityName, entity, LockMode.None, cancellationToken)).ConfigureAwait(false); + return Task.FromCanceled(cancellationToken); } + return RefreshAsync(entityName, entity, LockMode.None, cancellationToken); } /// @@ -555,7 +550,7 @@ private async Task GetAsync(System.Type persistentClass, object id, Canc public async Task RefreshAsync(object entity, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { await (RefreshAsync(BestGuessEntityName(entity), entity, lockMode, cancellationToken)).ConfigureAwait(false); } @@ -571,7 +566,7 @@ private async Task GetAsync(System.Type persistentClass, object id, Canc public async Task RefreshAsync(string entityName, object entity, LockMode lockMode, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.GetIdentifier(entity); @@ -615,9 +610,8 @@ private async Task GetAsync(System.Type persistentClass, object id, Canc public override async Task ExecuteNativeUpdateAsync(NativeSQLQuerySpecification nativeSQLQuerySpecification, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); NativeSQLQueryPlan plan = GetNativeSQLQueryPlan(nativeSQLQuerySpecification); @@ -640,9 +634,8 @@ public override async Task ExecuteNativeUpdateAsync(NativeSQLQuerySpecifica public override async Task ExecuteUpdateAsync(IQueryExpression queryExpression, QueryParameters queryParameters, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, false); bool success = false; diff --git a/src/NHibernate/Async/Loader/Loader.cs b/src/NHibernate/Async/Loader/Loader.cs index c3e9db3e1b6..f8a85bfebd0 100644 --- a/src/NHibernate/Async/Loader/Loader.cs +++ b/src/NHibernate/Async/Loader/Loader.cs @@ -239,7 +239,7 @@ private async Task ReadCollectionElementsAsync(object[] row, DbDataReader result private async Task DoQueryAsync(ISessionImplementor session, QueryParameters queryParameters, bool returnProxies, IResultTransformer forcedResultTransformer, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { RowSelection selection = queryParameters.RowSelection; int maxRows = HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; diff --git a/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs b/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs index bd0d77a2e22..87772eff5b5 100644 --- a/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs +++ b/src/NHibernate/Async/Persister/Entity/AbstractEntityPersister.cs @@ -67,7 +67,7 @@ public async Task GetDatabaseSnapshotAsync(object id, ISessionImplemen log.Debug("Getting current persistent state for: " + MessageHelper.InfoString(this, id, Factory)); } - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { var st = await (session.Batcher.PrepareCommandAsync(CommandType.Text, SQLSnapshotSelectString, IdentifierType.SqlTypes(factory), cancellationToken)).ConfigureAwait(false); @@ -187,7 +187,7 @@ public async Task GetCurrentVersionAsync(object id, ISessionImplementor { log.Debug("Getting version: " + MessageHelper.InfoString(this, id, Factory)); } - using(new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { var st = session.Batcher.PrepareQueryCommand(CommandType.Text, VersionSelectString, IdentifierType.SqlTypes(Factory)); @@ -331,7 +331,7 @@ public async Task HydrateAsync(DbDataReader rs, object id, object obj, DbCommand sequentialSelect = null; DbDataReader sequentialResultSet = null; bool sequentialSelectEmpty = false; - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { if (hasDeferred) @@ -1160,7 +1160,7 @@ private async Task ProcessGeneratedPropertiesWithGeneratedSqlAsync(object id, ob ISessionImplementor session, SqlString selectionSQL, ValueInclusion[] generationInclusions, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { var cmd = session.Batcher.PrepareQueryCommand(CommandType.Text, selectionSQL, IdentifierType.SqlTypes(Factory)); @@ -1280,7 +1280,7 @@ async Task InternalGetNaturalIdentifierSnapshotAsync() /////////////////////////////////////////////////////////////////////// object[] snapshot = new object[naturalIdPropertyCount]; - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { var ps = await (session.Batcher.PrepareCommandAsync(CommandType.Text, sql, IdentifierType.SqlTypes(factory), cancellationToken)).ConfigureAwait(false); diff --git a/src/NHibernate/Async/Transaction/AdoNetTransactionFactory.cs b/src/NHibernate/Async/Transaction/AdoNetTransactionFactory.cs index d035e912c58..add13d2a768 100644 --- a/src/NHibernate/Async/Transaction/AdoNetTransactionFactory.cs +++ b/src/NHibernate/Async/Transaction/AdoNetTransactionFactory.cs @@ -73,7 +73,7 @@ async Task InternalExecuteWorkInIsolationAsync() } catch (Exception t) { - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginContext()) { try { @@ -132,4 +132,4 @@ async Task InternalExecuteWorkInIsolationAsync() } } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Async/Transaction/AdoTransaction.cs b/src/NHibernate/Async/Transaction/AdoTransaction.cs index 94ed4912ab6..77156a210b6 100644 --- a/src/NHibernate/Async/Transaction/AdoTransaction.cs +++ b/src/NHibernate/Async/Transaction/AdoTransaction.cs @@ -26,17 +26,14 @@ public partial class AdoTransaction : ITransaction private async Task AfterTransactionCompletionAsync(bool successful, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(sessionId)) - { - session.ConnectionManager.AfterTransaction(); - await (session.AfterTransactionCompletionAsync(successful, this, cancellationToken)).ConfigureAwait(false); - NotifyLocalSynchsAfterTransactionCompletion(successful); - foreach (var dependentSession in session.ConnectionManager.DependentSessions) - await (dependentSession.AfterTransactionCompletionAsync(successful, this, cancellationToken)).ConfigureAwait(false); - - session = null; - begun = false; - } + session.ConnectionManager.AfterTransaction(); + await (session.AfterTransactionCompletionAsync(successful, this, cancellationToken)).ConfigureAwait(false); + NotifyLocalSynchsAfterTransactionCompletion(successful); + foreach (var dependentSession in session.ConnectionManager.DependentSessions) + await (dependentSession.AfterTransactionCompletionAsync(successful, this, cancellationToken)).ConfigureAwait(false); + + session = null; + begun = false; } /// @@ -51,7 +48,7 @@ private async Task AfterTransactionCompletionAsync(bool successful, Cancellation public async Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); - using (new SessionIdLoggingContext(sessionId)) + using (session.BeginProcess()) { CheckNotDisposed(); CheckBegun(); diff --git a/src/NHibernate/Async/Type/DbTimestampType.cs b/src/NHibernate/Async/Type/DbTimestampType.cs index e5d4cef61bb..74609fb18a3 100644 --- a/src/NHibernate/Async/Type/DbTimestampType.cs +++ b/src/NHibernate/Async/Type/DbTimestampType.cs @@ -58,7 +58,7 @@ protected virtual async Task UsePreparedStatementAsync(string timestam var tsSelect = new SqlString(timestampSelectString); DbCommand ps = null; DbDataReader rs = null; - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { try { diff --git a/src/NHibernate/Engine/ISessionImplementor.cs b/src/NHibernate/Engine/ISessionImplementor.cs index 934e8669d20..43f6dde729b 100644 --- a/src/NHibernate/Engine/ISessionImplementor.cs +++ b/src/NHibernate/Engine/ISessionImplementor.cs @@ -16,12 +16,34 @@ namespace NHibernate.Engine { + // 6.0 TODO: Convert to interface methods + internal static class SessionImplementorExtensions + { + internal static IDisposable BeginContext(this ISessionImplementor session) + { + if (session == null) + return null; + return (session as AbstractSessionImpl)?.BeginContext() ?? new SessionIdLoggingContext(session.SessionId); + } + + internal static IDisposable BeginProcess(this ISessionImplementor session) + { + if (session == null) + return null; + return (session as AbstractSessionImpl)?.BeginProcess() ?? + // This method has only replaced bare call to setting the id, so this fallback is enough for avoiding a + // breaking change in case in custom session implementation is used. + new SessionIdLoggingContext(session.SessionId); + } + } + /// /// Defines the internal contract between the Session and other parts of NHibernate /// such as implementors of Type or ClassPersister /// public partial interface ISessionImplementor { + // 5.1 TODO: obsolete Initialize, it has no more usages. /// /// Initialize the session after its construction was complete /// diff --git a/src/NHibernate/Event/IEventSource.cs b/src/NHibernate/Event/IEventSource.cs index 55150a18181..423415d9f1a 100644 --- a/src/NHibernate/Event/IEventSource.cs +++ b/src/NHibernate/Event/IEventSource.cs @@ -36,10 +36,11 @@ public partial interface IEventSource : ISessionImplementor, ISession /// Cascade refresh an entity instance void Refresh(object obj, IDictionary refreshedAlready); - + /// Cascade delete an entity instance void Delete(string entityName, object child, bool isCascadeDeleteEnabled, ISet transientEntities); + // 6.0 TODO: yield null if already suspended. /// /// Suspend auto-flushing, yielding a disposable to dispose when auto flush should be restored. Supports /// being called multiple times. diff --git a/src/NHibernate/Id/Insert/AbstractSelectingDelegate.cs b/src/NHibernate/Id/Insert/AbstractSelectingDelegate.cs index 39d117525a6..2fbd95e1262 100644 --- a/src/NHibernate/Id/Insert/AbstractSelectingDelegate.cs +++ b/src/NHibernate/Id/Insert/AbstractSelectingDelegate.cs @@ -54,7 +54,7 @@ public object PerformInsert(SqlCommandInfo insertSql, ISessionImplementor sessio } var selectSql = SelectSQL; - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { try { @@ -123,4 +123,4 @@ protected internal virtual SqlType[] ParametersTypes #endregion } -} \ No newline at end of file +} diff --git a/src/NHibernate/Impl/AbstractSessionImpl.cs b/src/NHibernate/Impl/AbstractSessionImpl.cs index 217f77df90f..6f013a8a994 100644 --- a/src/NHibernate/Impl/AbstractSessionImpl.cs +++ b/src/NHibernate/Impl/AbstractSessionImpl.cs @@ -56,10 +56,7 @@ protected internal AbstractSessionImpl(ISessionFactoryImplementor factory, ISess public void Initialize() { - using (new SessionIdLoggingContext(SessionId)) - { - CheckAndUpdateSessionStatus(); - } + BeginProcess()?.Dispose(); } public abstract void InitializeCollection(IPersistentCollection collection, bool writing); @@ -99,7 +96,7 @@ public virtual IList List(IQueryExpression queryExpression, QueryParameters para public virtual IList List(IQueryExpression query, QueryParameters parameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); List(query, parameters, results); @@ -109,7 +106,7 @@ public virtual IList List(IQueryExpression query, QueryParameters paramete public virtual IList List(CriteriaImpl criteria) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); List(criteria, results); @@ -121,7 +118,7 @@ public virtual IList List(CriteriaImpl criteria) public virtual IList List(CriteriaImpl criteria) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); List(criteria, results); @@ -154,7 +151,7 @@ public IList ListFilter(object collection, IQueryExpression queryExpression, Que public virtual IList List(NativeSQLQuerySpecification spec, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); List(spec, queryParameters, results); @@ -164,7 +161,7 @@ public virtual IList List(NativeSQLQuerySpecification spec, QueryParameters quer public virtual void List(NativeSQLQuerySpecification spec, QueryParameters queryParameters, IList results) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var query = new SQLCustomQuery( spec.SqlQueryReturns, @@ -177,7 +174,7 @@ public virtual void List(NativeSQLQuerySpecification spec, QueryParameters query public virtual IList List(NativeSQLQuerySpecification spec, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); List(spec, queryParameters, results); @@ -189,7 +186,7 @@ public virtual IList List(NativeSQLQuerySpecification spec, QueryParameter public virtual IList ListCustomQuery(ICustomQuery customQuery, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var results = new List(); ListCustomQuery(customQuery, queryParameters, results); @@ -203,9 +200,8 @@ public virtual IList ListCustomQuery(ICustomQuery customQuery, QueryParame public virtual IQuery GetNamedSQLQuery(string name) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var nsqlqd = _factory.GetNamedSQLQuery(name); if (nsqlqd == null) { @@ -246,9 +242,8 @@ public virtual FlushMode FlushMode public virtual IQuery GetNamedQuery(string queryName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var nqd = _factory.GetNamedQuery(queryName); IQuery query; if (nqd != null) @@ -281,8 +276,63 @@ public bool IsClosed get { return closed; } } + /// + /// If not nested in another call to BeginProcess on this session, check and update the + /// session status and set its session id in context. + /// + /// + /// If not already processing, an object to dispose for signaling the end of the process. + /// Otherwise, . + /// + public IDisposable BeginProcess() + { + return _processing ? null : new ProcessHelper(this); + } + + /// + /// If not nested in a call to BeginProcess on this session, set its session id in context. + /// + /// + /// If not already processing, an object to dispose for restoring the previous session id. + /// Otherwise, . + /// + public IDisposable BeginContext() + { + return _processing ? null : new SessionIdLoggingContext(SessionId); + } + + [NonSerialized] + private bool _processing; + + private sealed class ProcessHelper : IDisposable + { + private AbstractSessionImpl _session; + private SessionIdLoggingContext _context; + + public ProcessHelper(AbstractSessionImpl session) + { + _session = session; + _context = new SessionIdLoggingContext(session.SessionId); + session.CheckAndUpdateSessionStatus(); + _session._processing = true; + } + + public void Dispose() + { + if (_session == null) + throw new ObjectDisposedException("The session process helper has been disposed already"); + _session._processing = false; + _context.Dispose(); + _context = null; + _session = null; + } + } + protected internal virtual void CheckAndUpdateSessionStatus() { + if (_processing) + return; + ErrorIfClosed(); // Ensure the session does not run on a thread supposed to be blocked, waiting @@ -292,7 +342,7 @@ protected internal virtual void CheckAndUpdateSessionStatus() EnlistInAmbientTransactionIfNeeded(); } - protected internal virtual void ErrorIfClosed() + protected virtual void ErrorIfClosed() { if (IsClosed || IsAlreadyDisposed) { @@ -319,35 +369,31 @@ protected internal void SetClosed() private void InitQuery(IQuery query, NamedQueryDefinition nqd) { - using (new SessionIdLoggingContext(SessionId)) + query.SetCacheable(nqd.IsCacheable); + query.SetCacheRegion(nqd.CacheRegion); + if (nqd.Timeout != -1) { - query.SetCacheable(nqd.IsCacheable); - query.SetCacheRegion(nqd.CacheRegion); - if (nqd.Timeout != -1) - { - query.SetTimeout(nqd.Timeout); - } - if (nqd.FetchSize != -1) - { - query.SetFetchSize(nqd.FetchSize); - } - if (nqd.CacheMode.HasValue) - query.SetCacheMode(nqd.CacheMode.Value); + query.SetTimeout(nqd.Timeout); + } + if (nqd.FetchSize != -1) + { + query.SetFetchSize(nqd.FetchSize); + } + if (nqd.CacheMode.HasValue) + query.SetCacheMode(nqd.CacheMode.Value); - query.SetReadOnly(nqd.IsReadOnly); - if (nqd.Comment != null) - { - query.SetComment(nqd.Comment); - } - query.SetFlushMode(nqd.FlushMode); + query.SetReadOnly(nqd.IsReadOnly); + if (nqd.Comment != null) + { + query.SetComment(nqd.Comment); } + query.SetFlushMode(nqd.FlushMode); } public virtual IQuery CreateQuery(IQueryExpression queryExpression) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var queryPlan = GetHQLQueryPlan(queryExpression, false); var query = new ExpressionQueryImpl(queryPlan.QueryExpression, this, queryPlan.ParameterMetadata); query.SetComment("[expression]"); @@ -357,9 +403,8 @@ public virtual IQuery CreateQuery(IQueryExpression queryExpression) public virtual IQuery CreateQuery(string queryString) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var queryPlan = GetHQLQueryPlan(queryString.ToQueryExpression(), false); var query = new QueryImpl(queryString, this, queryPlan.ParameterMetadata); query.SetComment(queryString); @@ -369,9 +414,8 @@ public virtual IQuery CreateQuery(string queryString) public virtual ISQLQuery CreateSQLQuery(string sql) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var query = new SqlQueryImpl(sql, this, _factory.QueryPlanCache.GetSQLParameterMetadata(sql)); query.SetComment("dynamic native SQL query"); return query; @@ -380,7 +424,7 @@ public virtual ISQLQuery CreateSQLQuery(string sql) protected internal virtual IQueryExpressionPlan GetHQLQueryPlan(IQueryExpression queryExpression, bool shallow) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return _factory.QueryPlanCache.GetHQLQueryPlan(queryExpression, shallow, EnabledFilters); } @@ -388,7 +432,7 @@ protected internal virtual IQueryExpressionPlan GetHQLQueryPlan(IQueryExpression protected internal virtual NativeSQLQueryPlan GetNativeSQLQueryPlan(NativeSQLQuerySpecification spec) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { return _factory.QueryPlanCache.GetNativeSQLQueryPlan(spec); } @@ -396,7 +440,7 @@ protected internal virtual NativeSQLQueryPlan GetNativeSQLQueryPlan(NativeSQLQue protected Exception Convert(Exception sqlException, string message) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { return ADOExceptionHelper.Convert(_factory.SQLExceptionConverter, sqlException, message); } @@ -404,7 +448,7 @@ protected Exception Convert(Exception sqlException, string message) protected void AfterOperation(bool success) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { if (!ConnectionManager.IsInActiveTransaction) { @@ -422,15 +466,15 @@ protected void EnlistInAmbientTransactionIfNeeded() public void JoinTransaction() { - CheckAndUpdateSessionStatus(); - _factory.TransactionFactory.ExplicitJoinSystemTransaction(this); + using (BeginProcess()) + _factory.TransactionFactory.ExplicitJoinSystemTransaction(this); } public abstract IQuery CreateFilter(object collection, IQueryExpression queryExpression); internal IOuterJoinLoadable GetOuterJoinLoadable(string entityName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { var persister = Factory.GetEntityPersister(entityName) as IOuterJoinLoadable; if (persister == null) diff --git a/src/NHibernate/Impl/MultiCriteriaImpl.cs b/src/NHibernate/Impl/MultiCriteriaImpl.cs index cf0055afc7b..e4b4480907a 100644 --- a/src/NHibernate/Impl/MultiCriteriaImpl.cs +++ b/src/NHibernate/Impl/MultiCriteriaImpl.cs @@ -60,7 +60,7 @@ public SqlString SqlString public IList List() { - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { bool cacheable = session.Factory.Settings.IsQueryCacheEnabled && isCacheable; diff --git a/src/NHibernate/Impl/MultiQueryImpl.cs b/src/NHibernate/Impl/MultiQueryImpl.cs index 597bfda3716..14d1cbbb18e 100644 --- a/src/NHibernate/Impl/MultiQueryImpl.cs +++ b/src/NHibernate/Impl/MultiQueryImpl.cs @@ -406,7 +406,7 @@ public IMultiQuery SetCacheRegion(string region) /// public IList List() { - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { bool cacheable = session.Factory.Settings.IsQueryCacheEnabled && isCacheable; combinedParameters = CreateCombinedQueryParameters(); diff --git a/src/NHibernate/Impl/SessionImpl.cs b/src/NHibernate/Impl/SessionImpl.cs index 8ac98f96ffe..ab767f46acd 100644 --- a/src/NHibernate/Impl/SessionImpl.cs +++ b/src/NHibernate/Impl/SessionImpl.cs @@ -184,7 +184,7 @@ void IDeserializationCallback.OnDeserialization(object sender) internal SessionImpl(SessionFactoryImpl factory, ISessionCreationOptions options) : base(factory, options) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { actionQueue = new ActionQueue(this); persistenceContext = new StatefulPersistenceContext(this); @@ -283,7 +283,7 @@ public bool ShouldAutoClose /// public DbConnection Close() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { log.Debug("closing session"); if (IsClosed) @@ -318,7 +318,7 @@ public DbConnection Close() /// public override void AfterTransactionCompletion(bool success, ITransaction tx) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { log.Debug("transaction completion"); @@ -352,21 +352,16 @@ public override void AfterTransactionCompletion(bool success, ITransaction tx) private void Cleanup() { - using (new SessionIdLoggingContext(SessionId)) - { - // Let the after tran clear that if we are still in an active system transaction. - if (TransactionContext?.IsInActiveTransaction == true) - return; - persistenceContext.Clear(); - } + // Let the after tran clear that if we are still in an active system transaction. + if (TransactionContext?.IsInActiveTransaction == true) + return; + persistenceContext.Clear(); } public LockMode GetCurrentLockMode(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - if (obj == null) { throw new ArgumentNullException("obj", "null object passed to GetCurrentLockMode"); @@ -408,7 +403,7 @@ public override bool IsOpen /// public object Save(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return FireSave(new SaveOrUpdateEvent(null, obj, this)); } @@ -416,7 +411,7 @@ public object Save(object obj) public object Save(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return FireSave(new SaveOrUpdateEvent(entityName, obj, this)); } @@ -424,7 +419,7 @@ public object Save(string entityName, object obj) public void Save(string entityName, object obj, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireSave(new SaveOrUpdateEvent(entityName, obj, id, this)); } @@ -437,7 +432,7 @@ public void Save(string entityName, object obj, object id) /// public void Save(object obj, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireSave(new SaveOrUpdateEvent(null, obj, id, this)); } @@ -449,7 +444,7 @@ public void Save(object obj, object id) /// public void Delete(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireDelete(new DeleteEvent(obj, this)); } @@ -458,7 +453,7 @@ public void Delete(object obj) /// Delete a persistent object (by explicit entity name) public void Delete(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireDelete(new DeleteEvent(entityName, obj, this)); } @@ -466,7 +461,7 @@ public void Delete(string entityName, object obj) public void Update(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireUpdate(new SaveOrUpdateEvent(null, obj, this)); } @@ -474,7 +469,7 @@ public void Update(object obj) public void Update(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireUpdate(new SaveOrUpdateEvent(entityName, obj, this)); } @@ -482,7 +477,7 @@ public void Update(string entityName, object obj) public void Update(string entityName, object obj, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireUpdate(new SaveOrUpdateEvent(entityName, obj, id, this)); } @@ -490,7 +485,7 @@ public void Update(string entityName, object obj, object id) public void SaveOrUpdate(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireSaveOrUpdate(new SaveOrUpdateEvent(null, obj, this)); } @@ -498,7 +493,7 @@ public void SaveOrUpdate(object obj) public void SaveOrUpdate(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireSaveOrUpdate(new SaveOrUpdateEvent(entityName, obj, this)); } @@ -506,7 +501,7 @@ public void SaveOrUpdate(string entityName, object obj) public void SaveOrUpdate(string entityName, object obj, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireSaveOrUpdate(new SaveOrUpdateEvent(entityName, obj, id, this)); } @@ -514,7 +509,7 @@ public void SaveOrUpdate(string entityName, object obj, object id) public void Update(object obj, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireUpdate(new SaveOrUpdateEvent(null, obj, id, this)); } @@ -525,7 +520,7 @@ public void Update(object obj, object id) IList Find(string query, object[] values, IType[] types) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return List(query.ToQueryExpression(), new QueryParameters(types, values)); } @@ -538,9 +533,8 @@ public override void CloseSessionFromSystemTransaction() public override IQuery CreateQuery(IQueryExpression queryExpression) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var plan = GetHQLQueryPlan(queryExpression, false); var query = new ExpressionQueryImpl(plan.QueryExpression, this, plan.ParameterMetadata); query.SetComment("[expression]"); @@ -562,9 +556,8 @@ protected override void ListFilter(object collection, IQueryExpression queryExpr private void List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results, object filterConnection) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var isFilter = filterConnection != null; @@ -603,7 +596,7 @@ private void List(IQueryExpression queryExpression, QueryParameters queryParamet public override IQueryTranslator[] GetQueries(IQueryExpression query, bool scalar) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var plan = Factory.QueryPlanCache.GetHQLQueryPlan(query, scalar, enabledFilters); AutoFlushIfRequired(plan.QuerySpaces); @@ -613,9 +606,8 @@ public override IQueryTranslator[] GetQueries(IQueryExpression query, bool scala public override IEnumerable Enumerable(IQueryExpression queryExpression, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, true); AutoFlushIfRequired(plan.QuerySpaces); @@ -629,9 +621,8 @@ public override IEnumerable Enumerable(IQueryExpression queryExpression, Q public override IEnumerable Enumerable(IQueryExpression queryExpression, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, true); AutoFlushIfRequired(plan.QuerySpaces); @@ -647,31 +638,23 @@ public override IEnumerable Enumerable(IQueryExpression queryExpression, QueryPa public int Delete(string query) { - using (new SessionIdLoggingContext(SessionId)) - { - return Delete(query, NoArgs, NoTypes); - } + return Delete(query, NoArgs, NoTypes); } public int Delete(string query, object value, IType type) { - using (new SessionIdLoggingContext(SessionId)) - { - return Delete(query, new[] { value }, new[] { type }); - } + return Delete(query, new[] { value }, new[] { type }); } public int Delete(string query, object[] values, IType[] types) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (string.IsNullOrEmpty(query)) { throw new ArgumentNullException("query", "attempt to perform delete-by-query with null query"); } - CheckAndUpdateSessionStatus(); - if (log.IsDebugEnabled) { log.Debug("delete: " + query); @@ -693,7 +676,7 @@ public int Delete(string query, object[] values, IType[] types) public void Lock(object obj, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireLock(new LockEvent(obj, lockMode, this)); } @@ -701,7 +684,7 @@ public void Lock(object obj, LockMode lockMode) public void Lock(string entityName, object obj, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireLock(new LockEvent(entityName, obj, lockMode, this)); } @@ -709,10 +692,8 @@ public void Lock(string entityName, object obj, LockMode lockMode) public IQuery CreateFilter(object collection, string queryString) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - var plan = GetFilterQueryPlan(collection, queryString, null, false); var filter = new CollectionFilterImpl(queryString, collection, this, plan.ParameterMetadata); //filter.SetComment(queryString); @@ -722,10 +703,8 @@ public IQuery CreateFilter(object collection, string queryString) public override IQuery CreateFilter(object collection, IQueryExpression queryExpression) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - var plan = GetFilterQueryPlan(collection, queryExpression, null, false); var filter = new ExpressionFilterImpl(plan.QueryExpression, collection, this, plan.ParameterMetadata); return filter; @@ -745,62 +724,59 @@ private IQueryExpressionPlan GetFilterQueryPlan(object collection, string filter private IQueryExpressionPlan GetFilterQueryPlan(object collection, QueryParameters parameters, bool shallow, string filter, IQueryExpression queryExpression) { - using (new SessionIdLoggingContext(SessionId)) - { - if (collection == null) - throw new ArgumentNullException(nameof(collection), "null collection passed to filter"); - if (filter != null && queryExpression != null) - throw new ArgumentException($"Either {nameof(filter)} or {nameof(queryExpression)} must be specified, not both."); - if (filter == null && queryExpression == null) - throw new ArgumentException($"{nameof(filter)} and {nameof(queryExpression)} were both null."); + if (collection == null) + throw new ArgumentNullException(nameof(collection), "null collection passed to filter"); + if (filter != null && queryExpression != null) + throw new ArgumentException($"Either {nameof(filter)} or {nameof(queryExpression)} must be specified, not both."); + if (filter == null && queryExpression == null) + throw new ArgumentException($"{nameof(filter)} and {nameof(queryExpression)} were both null."); - var entry = persistenceContext.GetCollectionEntryOrNull(collection); - var roleBeforeFlush = entry?.LoadedPersister; + var entry = persistenceContext.GetCollectionEntryOrNull(collection); + var roleBeforeFlush = entry?.LoadedPersister; - IQueryExpressionPlan plan; - if (roleBeforeFlush == null) + IQueryExpressionPlan plan; + if (roleBeforeFlush == null) + { + // if it was previously unreferenced, we need to flush in order to + // get its state into the database in order to execute query + Flush(); + entry = persistenceContext.GetCollectionEntryOrNull(collection); + var roleAfterFlush = entry?.LoadedPersister; + if (roleAfterFlush == null) { - // if it was previously unreferenced, we need to flush in order to - // get its state into the database in order to execute query - Flush(); - entry = persistenceContext.GetCollectionEntryOrNull(collection); - var roleAfterFlush = entry?.LoadedPersister; - if (roleAfterFlush == null) - { - throw new QueryException("The collection was unreferenced"); - } - plan = GetFilterQueryPlan(roleAfterFlush.Role, shallow, filter, queryExpression); + throw new QueryException("The collection was unreferenced"); } - else + plan = GetFilterQueryPlan(roleAfterFlush.Role, shallow, filter, queryExpression); + } + else + { + // otherwise, we only need to flush if there are in-memory changes + // to the queried tables + plan = GetFilterQueryPlan(roleBeforeFlush.Role, shallow, filter, queryExpression); + if (AutoFlushIfRequired(plan.QuerySpaces)) { - // otherwise, we only need to flush if there are in-memory changes - // to the queried tables - plan = GetFilterQueryPlan(roleBeforeFlush.Role, shallow, filter, queryExpression); - if (AutoFlushIfRequired(plan.QuerySpaces)) + // might need to run a different filter entirely after the flush + // because the collection role may have changed + entry = persistenceContext.GetCollectionEntryOrNull(collection); + var roleAfterFlush = entry?.LoadedPersister; + if (roleBeforeFlush != roleAfterFlush) { - // might need to run a different filter entirely after the flush - // because the collection role may have changed - entry = persistenceContext.GetCollectionEntryOrNull(collection); - var roleAfterFlush = entry?.LoadedPersister; - if (roleBeforeFlush != roleAfterFlush) + if (roleAfterFlush == null) { - if (roleAfterFlush == null) - { - throw new QueryException("The collection was dereferenced"); - } - plan = GetFilterQueryPlan(roleAfterFlush.Role, shallow, filter, queryExpression); + throw new QueryException("The collection was dereferenced"); } + plan = GetFilterQueryPlan(roleAfterFlush.Role, shallow, filter, queryExpression); } } + } - if (parameters != null) - { - parameters.PositionalParameterValues[0] = entry.LoadedKey; - parameters.PositionalParameterTypes[0] = entry.LoadedPersister.KeyType; - } - - return plan; + if (parameters != null) + { + parameters.PositionalParameterValues[0] = entry.LoadedKey; + parameters.PositionalParameterTypes[0] = entry.LoadedPersister.KeyType; } + + return plan; } private IQueryExpressionPlan GetFilterQueryPlan(string role, bool shallow, string filter, IQueryExpression queryExpression) @@ -812,7 +788,7 @@ private IQueryExpressionPlan GetFilterQueryPlan(string role, bool shallow, strin public override object Instantiate(string clazz, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return Instantiate(Factory.GetEntityPersister(clazz), id); } @@ -836,9 +812,8 @@ public ActionQueue ActionQueue /// public object Instantiate(IEntityPersister persister, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - ErrorIfClosed(); object result = Interceptor.Instantiate(persister.EntityName, id); if (result == null) { @@ -852,9 +827,8 @@ public object Instantiate(IEntityPersister persister, object id) /// Force an immediate flush public void ForceFlush(EntityEntry entityEntry) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); if (log.IsDebugEnabled) { log.Debug("flushing to force deletion of re-saved object: " + @@ -876,7 +850,7 @@ public void ForceFlush(EntityEntry entityEntry) /// Cascade merge an entity instance public void Merge(string entityName, object obj, IDictionary copiedAlready) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireMerge(copiedAlready, new MergeEvent(entityName, obj, this)); } @@ -885,7 +859,7 @@ public void Merge(string entityName, object obj, IDictionary copiedAlready) /// Cascade persist an entity instance public void Persist(string entityName, object obj, IDictionary createdAlready) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FirePersist(createdAlready, new PersistEvent(entityName, obj, this)); } @@ -894,7 +868,7 @@ public void Persist(string entityName, object obj, IDictionary createdAlready) /// Cascade persist an entity instance during the flush process public void PersistOnFlush(string entityName, object obj, IDictionary copiedAlready) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FirePersistOnFlush(copiedAlready, new PersistEvent(entityName, obj, this)); } @@ -903,7 +877,7 @@ public void PersistOnFlush(string entityName, object obj, IDictionary copiedAlre /// Cascade refresh an entity instance public void Refresh(object obj, IDictionary refreshedAlready) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireRefresh(refreshedAlready, new RefreshEvent(obj, this)); } @@ -912,7 +886,7 @@ public void Refresh(object obj, IDictionary refreshedAlready) /// Cascade delete an entity instance public void Delete(string entityName, object child, bool isCascadeDeleteEnabled, ISet transientEntities) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireDelete(new DeleteEvent(entityName, child, isCascadeDeleteEnabled, this), transientEntities); } @@ -950,7 +924,7 @@ public void Dispose() public object Merge(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return FireMerge(new MergeEvent(entityName, obj, this)); } @@ -968,15 +942,12 @@ public T Merge(string entityName, T entity) where T : class public object Merge(object obj) { - using (new SessionIdLoggingContext(SessionId)) - { - return Merge(null, obj); - } + return Merge(null, obj); } public void Persist(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FirePersist(new PersistEvent(entityName, obj, this)); } @@ -984,15 +955,12 @@ public void Persist(string entityName, object obj) public void Persist(object obj) { - using (new SessionIdLoggingContext(SessionId)) - { - Persist(null, obj); - } + Persist(null, obj); } public void PersistOnFlush(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FirePersistOnFlush(new PersistEvent(entityName, obj, this)); } @@ -1000,10 +968,7 @@ public void PersistOnFlush(string entityName, object obj) public void PersistOnFlush(object obj) { - using (new SessionIdLoggingContext(SessionId)) - { - Persist(null, obj); - } + Persist(null, obj); } // Obsolete in v5, and was already having no usages previously. @@ -1012,7 +977,7 @@ public void PersistOnFlush(object obj) public override string BestGuessEntityName(object entity) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { if (entity.IsProxy()) { @@ -1047,7 +1012,7 @@ public override string BestGuessEntityName(object entity) public override string GuessEntityName(object entity) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { string entityName = Interceptor.GetEntityName(entity); if (entityName == null) @@ -1069,9 +1034,8 @@ public override bool IsEventSource public override object GetEntityUsingInterceptor(EntityKey key) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); // todo : should this get moved to PersistentContext? // logically, is PersistentContext the "thing" to which an interceptor gets attached? object result = persistenceContext.GetEntity(key); @@ -1109,9 +1073,8 @@ public override IPersistenceContext PersistenceContext /// private bool AutoFlushIfRequired(ISet querySpaces) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); if (!ConnectionManager.IsInActiveTransaction) { // do not auto-flush while outside a transaction @@ -1131,7 +1094,7 @@ private bool AutoFlushIfRequired(ISet querySpaces) public void Load(object obj, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { LoadEvent loadEvent = new LoadEvent(id, obj, this); FireLoad(loadEvent, LoadEventListener.Reload); @@ -1140,7 +1103,7 @@ public void Load(object obj, object id) public T Load(object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)Load(typeof(T), id); } @@ -1148,7 +1111,7 @@ public T Load(object id) public T Load(object id, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)Load(typeof(T), id, lockMode); } @@ -1170,15 +1133,12 @@ public T Load(object id, LockMode lockMode) /// public object Load(System.Type entityClass, object id, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) - { - return Load(entityClass.FullName, id, lockMode); - } + return Load(entityClass.FullName, id, lockMode); } public object Load(string entityName, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (id == null) { @@ -1206,7 +1166,7 @@ public object Load(string entityName, object id) public object Load(string entityName, object id, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { var @event = new LoadEvent(id, entityName, lockMode, this); FireLoad(@event, LoadEventListener.Load); @@ -1216,15 +1176,12 @@ public object Load(string entityName, object id, LockMode lockMode) public object Load(System.Type entityClass, object id) { - using (new SessionIdLoggingContext(SessionId)) - { - return Load(entityClass.FullName, id); - } + return Load(entityClass.FullName, id); } public T Get(object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)Get(typeof(T), id); } @@ -1232,7 +1189,7 @@ public T Get(object id) public T Get(object id, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)Get(typeof(T), id, lockMode); } @@ -1240,10 +1197,7 @@ public T Get(object id, LockMode lockMode) public object Get(System.Type entityClass, object id) { - using (new SessionIdLoggingContext(SessionId)) - { - return Get(entityClass.FullName, id); - } + return Get(entityClass.FullName, id); } /// @@ -1259,7 +1213,7 @@ public object Get(System.Type entityClass, object id) /// public object Get(System.Type clazz, object id, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { LoadEvent loadEvent = new LoadEvent(id, clazz.FullName, lockMode, this); FireLoad(loadEvent, LoadEventListener.Get); @@ -1269,10 +1223,8 @@ public object Get(System.Type clazz, object id, LockMode lockMode) public string GetEntityName(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - if (obj.IsProxy()) { var proxy = obj as INHibernateProxy; @@ -1299,7 +1251,7 @@ public string GetEntityName(object obj) public object Get(string entityName, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { LoadEvent loadEvent = new LoadEvent(id, entityName, false, this); bool success = false; @@ -1323,7 +1275,7 @@ public object Get(string entityName, object id) /// public override object ImmediateLoad(string entityName, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (log.IsDebugEnabled) { @@ -1344,7 +1296,7 @@ public override object ImmediateLoad(string entityName, object id) /// public override object InternalLoad(string entityName, object id, bool eager, bool isNullable) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { // todo : remove LoadType type = isNullable @@ -1364,7 +1316,7 @@ public override object InternalLoad(string entityName, object id, bool eager, bo public void Refresh(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireRefresh(new RefreshEvent(obj, this)); } @@ -1372,7 +1324,7 @@ public void Refresh(object obj) public void Refresh(object obj, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireRefresh(new RefreshEvent(obj, lockMode, this)); } @@ -1380,7 +1332,7 @@ public void Refresh(object obj, LockMode lockMode) public ITransaction BeginTransaction(IsolationLevel isolationLevel) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (_transactionCoordinatorShared) { @@ -1389,14 +1341,13 @@ public ITransaction BeginTransaction(IsolationLevel isolationLevel) log.Warn("Transaction started on non-root session"); } - CheckAndUpdateSessionStatus(); return connectionManager.BeginTransaction(isolationLevel); } } public ITransaction BeginTransaction() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (_transactionCoordinatorShared) { @@ -1405,7 +1356,6 @@ public ITransaction BeginTransaction() log.Warn("Transaction started on non-root session"); } - CheckAndUpdateSessionStatus(); return connectionManager.BeginTransaction(); } } @@ -1438,9 +1388,8 @@ public ITransaction Transaction /// public override void Flush() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); if (persistenceContext.CascadeLevel > 0) { throw new HibernateException("Flush during cascade is dangerous"); @@ -1463,10 +1412,8 @@ public override bool TransactionInProgress public bool IsDirty() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - log.Debug("checking session dirtiness"); if (actionQueue.AreInsertionsOrDeletionsQueued) { @@ -1493,9 +1440,8 @@ public bool IsDirty() /// public object GetIdentifier(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); // Actually the case for proxies will probably work even with // the session closed, but do the check here anyway, so that // the behavior is uniform. @@ -1529,7 +1475,7 @@ public object GetIdentifier(object obj) /// public override object GetContextEntityIdentifier(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { if (obj.IsProxy()) { @@ -1547,7 +1493,7 @@ public override object GetContextEntityIdentifier(object obj) internal ICollectionPersister GetCollectionPersister(string role) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { return Factory.GetCollectionPersister(role); } @@ -1560,9 +1506,8 @@ internal ICollectionPersister GetCollectionPersister(string role) /// public override void InitializeCollection(IPersistentCollection collection, bool writing) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IInitializeCollectionEventListener[] listener = listeners.InitializeCollectionEventListeners; for (int i = 0; i < listener.Length; i++) { @@ -1595,9 +1540,8 @@ public override bool IsConnected /// public DbConnection Disconnect() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); log.Debug("disconnecting session"); return connectionManager.Disconnect(); } @@ -1605,9 +1549,8 @@ public DbConnection Disconnect() public void Reconnect() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); log.Debug("reconnecting session"); connectionManager.Reconnect(); } @@ -1615,9 +1558,8 @@ public void Reconnect() public void Reconnect(DbConnection conn) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); log.Debug("reconnecting session"); connectionManager.Reconnect(conn); } @@ -1640,7 +1582,7 @@ public void Reconnect(DbConnection conn) /// public void Dispose() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { log.DebugFormat("[session-id={0}] running ISession.Dispose()", SessionId); // Ensure we are not disposing concurrently to transaction completion, which would @@ -1671,7 +1613,7 @@ public void Dispose() /// private void Dispose(bool isDisposing) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { if (IsAlreadyDisposed) { @@ -1701,9 +1643,8 @@ private void Dispose(bool isDisposing) private void Filter(object collection, string filter, QueryParameters queryParameters, IList results) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var plan = GetFilterQueryPlan(collection, filter, queryParameters, false); bool success = false; @@ -1733,29 +1674,22 @@ private void Filter(object collection, string filter, QueryParameters queryParam public override IList ListFilter(object collection, string filter, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) - { - var results = new List(); - Filter(collection, filter, queryParameters, results); - return results; - } + var results = new List(); + Filter(collection, filter, queryParameters, results); + return results; } public override IList ListFilter(object collection, string filter, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) - { - List results = new List(); - Filter(collection, filter, queryParameters, results); - return results; - } + List results = new List(); + Filter(collection, filter, queryParameters, results); + return results; } public override IEnumerable EnumerableFilter(object collection, string filter, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var plan = GetFilterQueryPlan(collection, filter, queryParameters, true); return plan.PerformIterate(queryParameters, this); } @@ -1763,9 +1697,8 @@ public override IEnumerable EnumerableFilter(object collection, string filter, Q public override IEnumerable EnumerableFilter(object collection, string filter, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); var plan = GetFilterQueryPlan(collection, filter, queryParameters, true); return plan.PerformIterate(queryParameters, this); } @@ -1773,72 +1706,58 @@ public override IEnumerable EnumerableFilter(object collection, string fil public ICriteria CreateCriteria() where T : class { - using (new SessionIdLoggingContext(SessionId)) - { - return CreateCriteria(typeof(T)); - } + return CreateCriteria(typeof(T)); } public ICriteria CreateCriteria(System.Type persistentClass) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - return new CriteriaImpl(persistentClass, this); } } public ICriteria CreateCriteria(string alias) where T : class { - using (new SessionIdLoggingContext(SessionId)) - { - return CreateCriteria(typeof(T), alias); - } + return CreateCriteria(typeof(T), alias); } public ICriteria CreateCriteria(System.Type persistentClass, string alias) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - return new CriteriaImpl(persistentClass, alias, this); } } public ICriteria CreateCriteria(string entityName, string alias) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new CriteriaImpl(entityName, alias, this); } } public ICriteria CreateCriteria(string entityName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new CriteriaImpl(entityName, this); } } public IQueryOver QueryOver() where T : class { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new QueryOver(new CriteriaImpl(typeof(T), this)); } } public IQueryOver QueryOver(Expression> alias) where T : class { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); string aliasPath = ExpressionProcessor.FindMemberExpression(alias.Body); return new QueryOver(new CriteriaImpl(typeof(T), aliasPath, this)); } @@ -1846,18 +1765,16 @@ public IQueryOver QueryOver(Expression> alias) where T : class public IQueryOver QueryOver(string entityName) where T : class { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new QueryOver(new CriteriaImpl(entityName, this)); } } public IQueryOver QueryOver(string entityName, Expression> alias) where T : class { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); string aliasPath = ExpressionProcessor.FindMemberExpression(alias.Body); return new QueryOver(new CriteriaImpl(entityName, aliasPath, this)); } @@ -1865,10 +1782,8 @@ public IQueryOver QueryOver(string entityName, Expression> alia public override void List(CriteriaImpl criteria, IList results) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - string[] implementors = Factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; @@ -1920,10 +1835,8 @@ public override void List(CriteriaImpl criteria, IList results) public bool Contains(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - if (obj.IsProxy()) { var proxy = obj as INHibernateProxy; @@ -1963,27 +1876,16 @@ public bool Contains(object obj) /// public void Evict(object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireEvict(new EvictEvent(obj, this)); } } - public override ISQLQuery CreateSQLQuery(string sql) - { - using (new SessionIdLoggingContext(SessionId)) - { - CheckAndUpdateSessionStatus(); - return base.CreateSQLQuery(sql); - } - } - public override void ListCustomQuery(ICustomQuery customQuery, QueryParameters queryParameters, IList results) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - CustomLoader loader = new CustomLoader(customQuery, Factory); AutoFlushIfRequired(loader.QuerySpaces); @@ -2010,9 +1912,8 @@ public ISharedSessionBuilder SessionWithOptions() public void Clear() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); actionQueue.Clear(); persistenceContext.Clear(); } @@ -2020,7 +1921,7 @@ public void Clear() public void Replicate(object obj, ReplicationMode replicationMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireReplicate(new ReplicateEvent(obj, replicationMode, this)); } @@ -2028,7 +1929,7 @@ public void Replicate(object obj, ReplicationMode replicationMode) public void Replicate(string entityName, object obj, ReplicationMode replicationMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { FireReplicate(new ReplicateEvent(entityName, obj, replicationMode, this)); } @@ -2041,19 +1942,16 @@ public ISessionFactory SessionFactory public void CancelQuery() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - Batcher.CancelLastQuery(); } } public IFilter GetEnabledFilter(string filterName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IFilter result; enabledFilters.TryGetValue(filterName, out result); return result; @@ -2062,9 +1960,8 @@ public IFilter GetEnabledFilter(string filterName) public IFilter EnableFilter(string filterName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); FilterImpl filter = new FilterImpl(Factory.GetFilterDefinition(filterName)); enabledFilters[filterName] = filter; if (!enabledFilterNames.Contains(filterName)) @@ -2077,9 +1974,8 @@ public IFilter EnableFilter(string filterName) public void DisableFilter(string filterName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); enabledFilters.Remove(filterName); enabledFilterNames.Remove(filterName); } @@ -2087,9 +1983,8 @@ public void DisableFilter(string filterName) public override Object GetFilterParameterValue(string filterParameterName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); string[] parsed = ParseFilterParameterName(filterParameterName); IFilter ifilter; enabledFilters.TryGetValue(parsed[0], out ifilter); @@ -2104,9 +1999,8 @@ public override Object GetFilterParameterValue(string filterParameterName) public override IType GetFilterParameterType(string filterParameterName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); string[] parsed = ParseFilterParameterName(filterParameterName); FilterDefinition filterDef = Factory.GetFilterDefinition(parsed[0]); if (filterDef == null) @@ -2140,17 +2034,14 @@ public override IDictionary EnabledFilters private string[] ParseFilterParameterName(string filterParameterName) { - using (new SessionIdLoggingContext(SessionId)) + int dot = filterParameterName.IndexOf("."); + if (dot <= 0) { - int dot = filterParameterName.IndexOf("."); - if (dot <= 0) - { - throw new ArgumentException("Invalid filter-parameter name format", "filterParameterName"); - } - string filterName = filterParameterName.Substring(0, dot); - string parameterName = filterParameterName.Substring(dot + 1); - return new[] { filterName, parameterName }; + throw new ArgumentException("Invalid filter-parameter name format", "filterParameterName"); } + string filterName = filterParameterName.Substring(0, dot); + string parameterName = filterParameterName.Substring(dot + 1); + return new[] { filterName, parameterName }; } public override ConnectionManager ConnectionManager @@ -2160,7 +2051,7 @@ public override ConnectionManager ConnectionManager public IMultiQuery CreateMultiQuery() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return new MultiQueryImpl(this); } @@ -2168,7 +2059,7 @@ public IMultiQuery CreateMultiQuery() public IMultiCriteria CreateMultiCriteria() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return new MultiCriteriaImpl(this, Factory); } @@ -2185,16 +2076,15 @@ public ISessionStatistics Statistics public override void AfterTransactionBegin(ITransaction tx) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); Interceptor.AfterTransactionBegin(tx); } } public override void BeforeTransactionCompletion(ITransaction tx) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { log.Debug("before transaction completion"); var context = TransactionContext; @@ -2219,11 +2109,8 @@ public override void BeforeTransactionCompletion(ITransaction tx) public override void FlushBeforeTransactionCompletion() { - using (new SessionIdLoggingContext(SessionId)) - { - if (FlushMode != FlushMode.Manual) - Flush(); - } + if (FlushMode != FlushMode.Manual) + Flush(); } public ISession SetBatchSize(int batchSize) @@ -2282,9 +2169,8 @@ public override string FetchProfile /// public void SetReadOnly(object entityOrProxy, bool readOnly) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); persistenceContext.SetReadOnly(entityOrProxy, readOnly); } } @@ -2300,15 +2186,13 @@ public bool DefaultReadOnly public bool IsReadOnly(object entityOrProxy) { ErrorIfClosed(); - // CheckTransactionSynchStatus(); return persistenceContext.IsReadOnly(entityOrProxy); } private void FireDelete(DeleteEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IDeleteEventListener[] deleteEventListener = listeners.DeleteEventListeners; for (int i = 0; i < deleteEventListener.Length; i++) { @@ -2319,9 +2203,8 @@ private void FireDelete(DeleteEvent @event) private void FireDelete(DeleteEvent @event, ISet transientEntities) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IDeleteEventListener[] deleteEventListener = listeners.DeleteEventListeners; for (int i = 0; i < deleteEventListener.Length; i++) { @@ -2332,9 +2215,8 @@ private void FireDelete(DeleteEvent @event, ISet transientEntities) private void FireEvict(EvictEvent evictEvent) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEvictEventListener[] evictEventListener = listeners.EvictEventListeners; for (int i = 0; i < evictEventListener.Length; i++) { @@ -2345,9 +2227,8 @@ private void FireEvict(EvictEvent evictEvent) private void FireLoad(LoadEvent @event, LoadType loadType) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ILoadEventListener[] loadEventListener = listeners.LoadEventListeners; for (int i = 0; i < loadEventListener.Length; i++) { @@ -2358,9 +2239,8 @@ private void FireLoad(LoadEvent @event, LoadType loadType) private void FireLock(LockEvent lockEvent) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ILockEventListener[] lockEventListener = listeners.LockEventListeners; for (int i = 0; i < lockEventListener.Length; i++) { @@ -2371,9 +2251,8 @@ private void FireLock(LockEvent lockEvent) private object FireMerge(MergeEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IMergeEventListener[] mergeEventListener = listeners.MergeEventListeners; for (int i = 0; i < mergeEventListener.Length; i++) { @@ -2385,9 +2264,8 @@ private object FireMerge(MergeEvent @event) private void FireMerge(IDictionary copiedAlready, MergeEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IMergeEventListener[] mergeEventListener = listeners.MergeEventListeners; for (int i = 0; i < mergeEventListener.Length; i++) { @@ -2398,9 +2276,8 @@ private void FireMerge(IDictionary copiedAlready, MergeEvent @event) private void FirePersist(IDictionary copiedAlready, PersistEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IPersistEventListener[] persistEventListener = listeners.PersistEventListeners; for (int i = 0; i < persistEventListener.Length; i++) { @@ -2411,9 +2288,8 @@ private void FirePersist(IDictionary copiedAlready, PersistEvent @event) private void FirePersist(PersistEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IPersistEventListener[] createEventListener = listeners.PersistEventListeners; for (int i = 0; i < createEventListener.Length; i++) { @@ -2424,9 +2300,8 @@ private void FirePersist(PersistEvent @event) private void FirePersistOnFlush(IDictionary copiedAlready, PersistEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IPersistEventListener[] persistEventListener = listeners.PersistOnFlushEventListeners; for (int i = 0; i < persistEventListener.Length; i++) { @@ -2437,9 +2312,8 @@ private void FirePersistOnFlush(IDictionary copiedAlready, PersistEvent @event) private void FirePersistOnFlush(PersistEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IPersistEventListener[] createEventListener = listeners.PersistOnFlushEventListeners; for (int i = 0; i < createEventListener.Length; i++) { @@ -2450,9 +2324,8 @@ private void FirePersistOnFlush(PersistEvent @event) private void FireRefresh(RefreshEvent refreshEvent) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IRefreshEventListener[] refreshEventListener = listeners.RefreshEventListeners; for (int i = 0; i < refreshEventListener.Length; i++) { @@ -2463,9 +2336,8 @@ private void FireRefresh(RefreshEvent refreshEvent) private void FireRefresh(IDictionary refreshedAlready, RefreshEvent refreshEvent) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IRefreshEventListener[] refreshEventListener = listeners.RefreshEventListeners; for (int i = 0; i < refreshEventListener.Length; i++) { @@ -2476,9 +2348,8 @@ private void FireRefresh(IDictionary refreshedAlready, RefreshEvent refreshEvent private void FireReplicate(ReplicateEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IReplicateEventListener[] replicateEventListener = listeners.ReplicateEventListeners; for (int i = 0; i < replicateEventListener.Length; i++) { @@ -2489,9 +2360,8 @@ private void FireReplicate(ReplicateEvent @event) private object FireSave(SaveOrUpdateEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ISaveOrUpdateEventListener[] saveEventListener = listeners.SaveEventListeners; for (int i = 0; i < saveEventListener.Length; i++) { @@ -2503,9 +2373,8 @@ private object FireSave(SaveOrUpdateEvent @event) private void FireSaveOrUpdate(SaveOrUpdateEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ISaveOrUpdateEventListener[] saveOrUpdateEventListener = listeners.SaveOrUpdateEventListeners; for (int i = 0; i < saveOrUpdateEventListener.Length; i++) { @@ -2516,9 +2385,8 @@ private void FireSaveOrUpdate(SaveOrUpdateEvent @event) private void FireUpdate(SaveOrUpdateEvent @event) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); ISaveOrUpdateEventListener[] updateEventListener = listeners.UpdateEventListeners; for (int i = 0; i < updateEventListener.Length; i++) { @@ -2529,9 +2397,8 @@ private void FireUpdate(SaveOrUpdateEvent @event) public override int ExecuteNativeUpdate(NativeSQLQuerySpecification nativeQuerySpecification, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); NativeSQLQueryPlan plan = GetNativeSQLQueryPlan(nativeQuerySpecification); @@ -2554,9 +2421,8 @@ public override int ExecuteNativeUpdate(NativeSQLQuerySpecification nativeQueryS public override int ExecuteUpdate(IQueryExpression queryExpression, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, false); AutoFlushIfRequired(plan.QuerySpaces); @@ -2578,9 +2444,8 @@ public override int ExecuteUpdate(IQueryExpression queryExpression, QueryParamet public override IEntityPersister GetEntityPersister(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); if (entityName == null) { return Factory.GetEntityPersister(GuessEntityName(obj)); diff --git a/src/NHibernate/Impl/StatelessSessionImpl.cs b/src/NHibernate/Impl/StatelessSessionImpl.cs index bc0f9aced09..44f96bc933a 100644 --- a/src/NHibernate/Impl/StatelessSessionImpl.cs +++ b/src/NHibernate/Impl/StatelessSessionImpl.cs @@ -37,7 +37,7 @@ public partial class StatelessSessionImpl : AbstractSessionImpl, IStatelessSessi internal StatelessSessionImpl(SessionFactoryImpl factory, ISessionCreationOptions options) : base(factory, options) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { temporaryPersistenceContext = new StatefulPersistenceContext(this); connectionManager = new ConnectionManager(this, options.UserSuppliedConnection, ConnectionReleaseMode.AfterTransaction, @@ -68,9 +68,8 @@ public override void InitializeCollection(IPersistentCollection collection, bool public override object InternalLoad(string entityName, object id, bool eager, bool isNullable) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEntityPersister persister = Factory.GetEntityPersister(entityName); object loaded = temporaryPersistenceContext.GetEntity(GenerateEntityKey(id, persister)); if (loaded != null) @@ -117,9 +116,8 @@ public override IQuery CreateFilter(object collection, IQueryExpression queryExp public override void List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, false); @@ -148,9 +146,8 @@ public override void List(IQueryExpression queryExpression, QueryParameters quer public override void List(CriteriaImpl criteria, IList results) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); string[] implementors = Factory.GetImplementors(criteria.EntityOrClassName); int size = implementors.Length; @@ -238,11 +235,8 @@ public override void BeforeTransactionCompletion(ITransaction tx) public override void FlushBeforeTransactionCompletion() { - using (new SessionIdLoggingContext(SessionId)) - { - if (FlushMode != FlushMode.Manual) - Flush(); - } + if (FlushMode != FlushMode.Manual) + Flush(); } public override void AfterTransactionCompletion(bool successful, ITransaction tx) @@ -251,25 +245,21 @@ public override void AfterTransactionCompletion(bool successful, ITransaction tx public override object GetContextEntityIdentifier(object obj) { - CheckAndUpdateSessionStatus(); return null; } public override object Instantiate(string clazz, object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return Factory.GetEntityPersister(clazz).Instantiate(id); } } public override void ListCustomQuery(ICustomQuery customQuery, QueryParameters queryParameters, IList results) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); - var loader = new CustomLoader(customQuery, Factory); var success = false; @@ -303,7 +293,7 @@ public override IDictionary EnabledFilters public override IQueryTranslator[] GetQueries(IQueryExpression query, bool scalar) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { // take the union of the query spaces (ie the queried tables) var plan = Factory.QueryPlanCache.GetHQLQueryPlan(query, scalar, EnabledFilters); @@ -333,14 +323,16 @@ public override bool IsEventSource public override object GetEntityUsingInterceptor(EntityKey key) { - CheckAndUpdateSessionStatus(); - // while a pending Query we should use existing temporary entities so a join fetch does not create multiple instances - // of the same parent item (NH-3015, NH-3705). - object obj; - if (temporaryPersistenceContext.EntitiesByKey.TryGetValue(key, out obj)) - return obj; + using (BeginProcess()) + { + // while a pending Query we should use existing temporary entities so a join fetch does not create multiple instances + // of the same parent item (NH-3015, NH-3705). + object obj; + if (temporaryPersistenceContext.EntitiesByKey.TryGetValue(key, out obj)) + return obj; - return null; + return null; + } } public override IPersistenceContext PersistenceContext @@ -366,7 +358,7 @@ public override FlushMode FlushMode public override string BestGuessEntityName(object entity) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { if (entity.IsProxy()) { @@ -379,8 +371,10 @@ public override string BestGuessEntityName(object entity) public override string GuessEntityName(object entity) { - CheckAndUpdateSessionStatus(); - return entity.GetType().FullName; + using (BeginContext()) + { + return entity.GetType().FullName; + } } public override DbConnection Connection @@ -396,17 +390,13 @@ public IStatelessSession SetBatchSize(int batchSize) public override void Flush() { - using (new SessionIdLoggingContext(SessionId)) - { - ManagedFlush(); // NH Different behavior since ADOContext.Context is not implemented - } + ManagedFlush(); // NH Different behavior since ADOContext.Context is not implemented } public void ManagedFlush() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); Batcher.ExecuteBatch(); } } @@ -454,15 +444,12 @@ public ISessionImplementor GetSessionImplementation() /// Close the stateless session and release the ADO.NET connection. public void Close() { - using (new SessionIdLoggingContext(SessionId)) - { - ManagedClose(); - } + ManagedClose(); } public void ManagedClose() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { if (IsClosed) { @@ -478,11 +465,7 @@ public void ManagedClose() /// the identifier of the instance public object Insert(object entity) { - using (new SessionIdLoggingContext(SessionId)) - { - CheckAndUpdateSessionStatus(); - return Insert(null, entity); - } + return Insert(null, entity); } /// Insert a row. @@ -491,9 +474,8 @@ public object Insert(object entity) /// the identifier of the instance public object Insert(string entityName, object entity) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.IdentifierGenerator.Generate(this, entity); object[] state = persister.GetPropertyValues(entity); @@ -524,11 +506,7 @@ public object Insert(string entityName, object entity) /// a detached entity instance public void Update(object entity) { - using (new SessionIdLoggingContext(SessionId)) - { - CheckAndUpdateSessionStatus(); - Update(null, entity); - } + Update(null, entity); } /// Update a entity. @@ -536,9 +514,8 @@ public void Update(object entity) /// a detached entity instance public void Update(string entityName, object entity) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.GetIdentifier(entity); object[] state = persister.GetPropertyValues(entity); @@ -562,11 +539,7 @@ public void Update(string entityName, object entity) /// a detached entity instance public void Delete(object entity) { - using (new SessionIdLoggingContext(SessionId)) - { - CheckAndUpdateSessionStatus(); - Delete(null, entity); - } + Delete(null, entity); } /// Delete a entity. @@ -574,9 +547,8 @@ public void Delete(object entity) /// a detached entity instance public void Delete(string entityName, object entity) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.GetIdentifier(entity); object version = persister.GetVersion(entity); @@ -588,10 +560,7 @@ public void Delete(string entityName, object entity) /// a detached entity instance public object Get(string entityName, object id) { - using (new SessionIdLoggingContext(SessionId)) - { - return Get(entityName, id, LockMode.None); - } + return Get(entityName, id, LockMode.None); } /// Retrieve a entity. @@ -601,7 +570,7 @@ public object Get(string entityName, object id) /// public T Get(object id) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)Get(typeof(T), id); } @@ -609,10 +578,7 @@ public T Get(object id) private object Get(System.Type persistentClass, object id) { - using (new SessionIdLoggingContext(SessionId)) - { - return Get(persistentClass.FullName, id); - } + return Get(persistentClass.FullName, id); } /// @@ -621,9 +587,8 @@ private object Get(System.Type persistentClass, object id) /// a detached entity instance public object Get(string entityName, object id, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); object result = Factory.GetEntityPersister(entityName).Load(id, null, lockMode, this); if (temporaryPersistenceContext.IsLoadFinished) { @@ -639,7 +604,7 @@ public object Get(string entityName, object id, LockMode lockMode) /// a detached entity instance public T Get(object id, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { return (T)Get(typeof(T).FullName, id, lockMode); } @@ -651,7 +616,7 @@ public T Get(object id, LockMode lockMode) /// The entity to be refreshed. public void Refresh(object entity) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { Refresh(BestGuessEntityName(entity), entity, LockMode.None); } @@ -664,10 +629,7 @@ public void Refresh(object entity) /// The entity to be refreshed. public void Refresh(string entityName, object entity) { - using (new SessionIdLoggingContext(SessionId)) - { - Refresh(entityName, entity, LockMode.None); - } + Refresh(entityName, entity, LockMode.None); } /// @@ -677,7 +639,7 @@ public void Refresh(string entityName, object entity) /// The LockMode to be applied. public void Refresh(object entity, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { Refresh(BestGuessEntityName(entity), entity, lockMode); } @@ -691,7 +653,7 @@ public void Refresh(object entity, LockMode lockMode) /// The LockMode to be applied. public void Refresh(string entityName, object entity, LockMode lockMode) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { IEntityPersister persister = GetEntityPersister(entityName, entity); object id = persister.GetIdentifier(entity); @@ -739,10 +701,7 @@ public void Refresh(string entityName, object entity, LockMode lockMode) /// Entities returned by the query are detached. public ICriteria CreateCriteria() where T : class { - using (new SessionIdLoggingContext(SessionId)) - { - return CreateCriteria(typeof(T)); - } + return CreateCriteria(typeof(T)); } /// @@ -755,26 +714,21 @@ public ICriteria CreateCriteria() where T : class /// Entities returned by the query are detached. public ICriteria CreateCriteria(string alias) where T : class { - using (new SessionIdLoggingContext(SessionId)) - { - return CreateCriteria(typeof(T), alias); - } + return CreateCriteria(typeof(T), alias); } public ICriteria CreateCriteria(System.Type entityType) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new CriteriaImpl(entityType, this); } } public ICriteria CreateCriteria(System.Type entityType, string alias) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new CriteriaImpl(entityType, alias, this); } } @@ -787,9 +741,8 @@ public ICriteria CreateCriteria(System.Type entityType, string alias) /// Entities returned by the query are detached. public ICriteria CreateCriteria(string entityName) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new CriteriaImpl(entityName, this); } } @@ -804,27 +757,24 @@ public ICriteria CreateCriteria(string entityName) /// Entities returned by the query are detached. public ICriteria CreateCriteria(string entityName, string alias) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new CriteriaImpl(entityName, alias, this); } } public IQueryOver QueryOver() where T : class { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return new QueryOver(new CriteriaImpl(typeof(T), this)); } } public IQueryOver QueryOver(Expression> alias) where T : class { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); string aliasPath = ExpressionProcessor.FindMemberExpression(alias.Body); return new QueryOver(new CriteriaImpl(typeof(T), aliasPath, this)); } @@ -846,9 +796,8 @@ public ITransaction BeginTransaction() /// A NHibernate transaction public ITransaction BeginTransaction(IsolationLevel isolationLevel) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); return connectionManager.BeginTransaction(isolationLevel); } } @@ -873,7 +822,7 @@ public ITransaction BeginTransaction(IsolationLevel isolationLevel) ///2 public void Dispose() { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { log.Debug("running IStatelessSession.Dispose()"); // Ensure we are not disposing concurrently to transaction completion, which would @@ -895,7 +844,7 @@ public void Dispose() protected void Dispose(bool isDisposing) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginContext()) { if (_isAlreadyDisposed) { @@ -922,9 +871,8 @@ protected void Dispose(bool isDisposing) public override int ExecuteNativeUpdate(NativeSQLQuerySpecification nativeSQLQuerySpecification, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); NativeSQLQueryPlan plan = GetNativeSQLQueryPlan(nativeSQLQuerySpecification); @@ -946,9 +894,8 @@ public override int ExecuteNativeUpdate(NativeSQLQuerySpecification nativeSQLQue public override int ExecuteUpdate(IQueryExpression queryExpression, QueryParameters queryParameters) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); queryParameters.ValidateParameters(); var plan = GetHQLQueryPlan(queryExpression, false); bool success = false; @@ -981,9 +928,8 @@ public override FutureQueryBatch FutureQueryBatch public override IEntityPersister GetEntityPersister(string entityName, object obj) { - using (new SessionIdLoggingContext(SessionId)) + using (BeginProcess()) { - CheckAndUpdateSessionStatus(); if (entityName == null) { return Factory.GetEntityPersister(GuessEntityName(obj)); diff --git a/src/NHibernate/Loader/Loader.cs b/src/NHibernate/Loader/Loader.cs index 1fa0fc79960..17c7d5dfb24 100644 --- a/src/NHibernate/Loader/Loader.cs +++ b/src/NHibernate/Loader/Loader.cs @@ -423,7 +423,7 @@ private void ReadCollectionElements(object[] row, DbDataReader resultSet, ISessi private IList DoQuery(ISessionImplementor session, QueryParameters queryParameters, bool returnProxies, IResultTransformer forcedResultTransformer) { - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { RowSelection selection = queryParameters.RowSelection; int maxRows = HasMaxRows(selection) ? selection.MaxRows : int.MaxValue; diff --git a/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs b/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs index 42611366c74..af430968a1d 100644 --- a/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs +++ b/src/NHibernate/Persister/Collection/AbstractCollectionPersister.cs @@ -1512,12 +1512,12 @@ private static void CalcPropertyColumnSpan(IType propertyType, ref int count) public int GetSize(object key, ISessionImplementor session) { - using(new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { if(session.EnabledFilters.Count > 0) { - + // The above call validates the filters } var st = session.Batcher.PrepareCommand(CommandType.Text, GenerateSelectSizeString(session), KeyType.SqlTypes(factory)); @@ -1554,7 +1554,7 @@ public bool ElementExists(object key, object element, ISessionImplementor sessio private bool Exists(object key, object indexOrElement, IType indexOrElementType, SqlString sql, ISessionImplementor session) { - using(new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { List sqlTl = new List(KeyType.SqlTypes(factory)); @@ -1594,7 +1594,7 @@ private bool Exists(object key, object indexOrElement, IType indexOrElementType, public virtual object GetElementByIndex(object key, object index, ISessionImplementor session, object owner) { - using(new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { List sqlTl = new List(KeyType.SqlTypes(factory)); diff --git a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs index 5fdecff5df3..a51ef2c52c3 100644 --- a/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs +++ b/src/NHibernate/Persister/Entity/AbstractEntityPersister.cs @@ -1270,7 +1270,7 @@ private object InitializeLazyPropertiesFromDatastore(string fieldName, object en log.Debug("initializing lazy properties from datastore"); - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { object result = null; @@ -1447,7 +1447,7 @@ public object[] GetDatabaseSnapshot(object id, ISessionImplementor session) log.Debug("Getting current persistent state for: " + MessageHelper.InfoString(this, id, Factory)); } - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { var st = session.Batcher.PrepareCommand(CommandType.Text, SQLSnapshotSelectString, IdentifierType.SqlTypes(factory)); @@ -1702,7 +1702,7 @@ public object GetCurrentVersion(object id, ISessionImplementor session) { log.Debug("Getting version: " + MessageHelper.InfoString(this, id, Factory)); } - using(new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { var st = session.Batcher.PrepareQueryCommand(CommandType.Text, VersionSelectString, IdentifierType.SqlTypes(Factory)); @@ -2489,7 +2489,7 @@ public object[] Hydrate(DbDataReader rs, object id, object obj, ILoadable rootLo DbCommand sequentialSelect = null; DbDataReader sequentialResultSet = null; bool sequentialSelectEmpty = false; - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { if (hasDeferred) @@ -4103,7 +4103,7 @@ public void ProcessUpdateGeneratedProperties(object id, object entity, object[] private void ProcessGeneratedPropertiesWithGeneratedSql(object id, object entity, object[] state, ISessionImplementor session, SqlString selectionSQL, ValueInclusion[] generationInclusions) { - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { var cmd = session.Batcher.PrepareQueryCommand(CommandType.Text, selectionSQL, IdentifierType.SqlTypes(Factory)); @@ -4210,7 +4210,7 @@ public virtual object[] GetNaturalIdentifierSnapshot(object id, ISessionImplemen /////////////////////////////////////////////////////////////////////// object[] snapshot = new object[naturalIdPropertyCount]; - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) try { var ps = session.Batcher.PrepareCommand(CommandType.Text, sql, IdentifierType.SqlTypes(factory)); diff --git a/src/NHibernate/Transaction/AdoNetTransactionFactory.cs b/src/NHibernate/Transaction/AdoNetTransactionFactory.cs index 57515c6e6d9..0e3f093d98a 100644 --- a/src/NHibernate/Transaction/AdoNetTransactionFactory.cs +++ b/src/NHibernate/Transaction/AdoNetTransactionFactory.cs @@ -83,7 +83,7 @@ public virtual void ExecuteWorkInIsolation(ISessionImplementor session, IIsolate } catch (Exception t) { - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginContext()) { try { @@ -146,4 +146,4 @@ public virtual void Configure(IDictionary props) { } } -} \ No newline at end of file +} diff --git a/src/NHibernate/Transaction/AdoNetWithSystemTransactionFactory.cs b/src/NHibernate/Transaction/AdoNetWithSystemTransactionFactory.cs index 65dc8cc3e55..9205521dd8d 100644 --- a/src/NHibernate/Transaction/AdoNetWithSystemTransactionFactory.cs +++ b/src/NHibernate/Transaction/AdoNetWithSystemTransactionFactory.cs @@ -309,7 +309,7 @@ protected virtual void Unlock() /// The object for notifying the prepare phase outcome. public virtual void Prepare(PreparingEnlistment preparingEnlistment) { - using (new SessionIdLoggingContext(_session.SessionId)) + using (_session.BeginContext()) { try { @@ -378,7 +378,7 @@ void IEnlistmentNotification.InDoubt(Enlistment enlistment) /// callback, if this is an in-doubt callback. protected virtual void ProcessSecondPhase(Enlistment enlistment, bool? success) { - using (new SessionIdLoggingContext(_session.SessionId)) + using (_session.BeginContext()) { _logger.Debug( success.HasValue @@ -414,7 +414,7 @@ protected virtual void CompleteTransaction(bool isCommitted) { // Allow transaction completed actions to run while others stay blocked. _bypassLock.Value = true; - using (new SessionIdLoggingContext(_session.SessionId)) + using (_session.BeginContext()) { // Flag active as false before running actions, otherwise the session may not cleanup as much // as possible. diff --git a/src/NHibernate/Transaction/AdoTransaction.cs b/src/NHibernate/Transaction/AdoTransaction.cs index ce01705d0b8..ecea5213492 100644 --- a/src/NHibernate/Transaction/AdoTransaction.cs +++ b/src/NHibernate/Transaction/AdoTransaction.cs @@ -108,7 +108,7 @@ public void Begin() /// public void Begin(IsolationLevel isolationLevel) { - using (new SessionIdLoggingContext(sessionId)) + using (session.BeginProcess()) { if (begun) { @@ -161,17 +161,14 @@ public void Begin(IsolationLevel isolationLevel) private void AfterTransactionCompletion(bool successful) { - using (new SessionIdLoggingContext(sessionId)) - { - session.ConnectionManager.AfterTransaction(); - session.AfterTransactionCompletion(successful, this); - NotifyLocalSynchsAfterTransactionCompletion(successful); - foreach (var dependentSession in session.ConnectionManager.DependentSessions) - dependentSession.AfterTransactionCompletion(successful, this); - - session = null; - begun = false; - } + session.ConnectionManager.AfterTransaction(); + session.AfterTransactionCompletion(successful, this); + NotifyLocalSynchsAfterTransactionCompletion(successful); + foreach (var dependentSession in session.ConnectionManager.DependentSessions) + dependentSession.AfterTransactionCompletion(successful, this); + + session = null; + begun = false; } /// @@ -184,7 +181,7 @@ private void AfterTransactionCompletion(bool successful) /// public void Commit() { - using (new SessionIdLoggingContext(sessionId)) + using (session.BeginProcess()) { CheckNotDisposed(); CheckBegun(); diff --git a/src/NHibernate/Transaction/ITransactionContext.cs b/src/NHibernate/Transaction/ITransactionContext.cs index 1a96d3fea8a..fee820c35d0 100644 --- a/src/NHibernate/Transaction/ITransactionContext.cs +++ b/src/NHibernate/Transaction/ITransactionContext.cs @@ -25,7 +25,8 @@ public interface ITransactionContext : IDisposable /// /// With some transaction factory, synchronization of session may be required. This method should be called /// by session before each of its usage where a concurrent transaction completion action could cause a thread - /// safety issue. This method is already called by . + /// safety issue. This method is already called by + /// and . /// /// /// @@ -66,4 +67,4 @@ public interface ITransactionContext : IDisposable /// void Wait(); } -} \ No newline at end of file +} diff --git a/src/NHibernate/Type/DbTimestampType.cs b/src/NHibernate/Type/DbTimestampType.cs index 4eb9118c810..c205572823d 100644 --- a/src/NHibernate/Type/DbTimestampType.cs +++ b/src/NHibernate/Type/DbTimestampType.cs @@ -53,7 +53,7 @@ protected virtual DateTime UsePreparedStatement(string timestampSelectString, IS var tsSelect = new SqlString(timestampSelectString); DbCommand ps = null; DbDataReader rs = null; - using (new SessionIdLoggingContext(session.SessionId)) + using (session.BeginProcess()) { try {