internal void SystemBeforeRemove(EntityRemoveReason reason) { if (Session.IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXRemovingKeyY, Session, Key); } Session.SystemEvents.NotifyEntityRemoving(this, reason); using (Session.Operations.EnableSystemOperationRegistration()) { Session.Events.NotifyEntityRemoving(this, reason); if (Session.IsSystemLogicOnly) { return; } var subscriptionInfo = GetSubscription(EntityEventBroker.RemovingEntityEventKey); if (subscriptionInfo.Second != null) { ((Action <Key>)subscriptionInfo.Second) .Invoke(subscriptionInfo.First); } OnRemoving(); } }
internal override sealed void SystemSetValueAttempt(FieldInfo field, object value) { EnsureNotRemoved(); OrmLog.Debug(Strings.LogSessionXSettingValueKeyYFieldZ, Session, Key, field); if (field.IsPrimaryKey) { throw new NotSupportedException(string.Format(Strings.ExUnableToSetKeyFieldXExplicitly, field.Name)); } if (changeVersionOnSetAttempt) { UpdateVersionInfo(this, field); } Session.SystemEvents.NotifyFieldValueSettingAttempt(this, field, value); using (Session.Operations.EnableSystemOperationRegistration()) { Session.Events.NotifyFieldValueSettingAttempt(this, field, value); if (Session.IsSystemLogicOnly) { return; } var subscriptionInfo = GetSubscription(EntityEventBroker.SettingFieldAttemptEventKey); if (subscriptionInfo.Second != null) { ((Action <Key, FieldInfo, object>)subscriptionInfo.Second).Invoke(subscriptionInfo.First, field, value); } OnSettingFieldValueAttempt(field, value); Session.ValidationContext.ValidateSetAttempt(this, field, value); } }
internal void CommitTransaction(Transaction transaction) { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXCommittingTransaction, this); } SystemEvents.NotifyTransactionPrecommitting(transaction); Events.NotifyTransactionPrecommitting(transaction); Persist(PersistReason.Commit); ValidationContext.Validate(ValidationReason.Commit); SystemEvents.NotifyTransactionCommitting(transaction); Events.NotifyTransactionCommitting(transaction); Handler.CompletingTransaction(transaction); if (transaction.IsNested) { Handler.ReleaseSavepoint(transaction); } else { Handler.CommitTransaction(transaction); } }
private async ValueTask RemapEntityKeys(KeyMapping keyMapping, bool isAsync, CancellationToken token = default) { if (keyMapping.Map.Count == 0) { return; } using (Activate()) { if (!LazyKeyGenerationIsEnabled) { await Persist(PersistReason.RemapEntityKeys, isAsync, token).ConfigureAwait(false); Invalidate(); } if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXRemappingEntityKeys, this); } foreach (var entityState in EntityChangeRegistry.GetItems(PersistenceState.New)) { var key = entityState.Key; var remappedKey = keyMapping.TryRemapKey(key); if (remappedKey != key) { entityState.RemapKey(remappedKey); } EntityStateCache.Add(entityState); } ProcessChangesOfEntitySets(entitySetState => entitySetState.RemapKeys(keyMapping)); EntityEvents.RemapKeys(keyMapping); } }
/// <inheritdoc/> public void Dispose() { lock (disposeGuard) { if (isDisposed) { return; } isDisposed = true; OrmLog.Debug(Strings.LogDomainIsDisposing); NotifyDisposing(); Services.Dispose(); if (SingleConnection == null) { return; } lock (singleConnectionGuard) { if (singleConnectionOwner == null) { var driver = Handlers.StorageDriver; driver.CloseConnection(null, SingleConnection); driver.DisposeConnection(null, SingleConnection); } else { OrmLog.Warning( Strings.LogUnableToCloseSingleAvailableConnectionItIsStillUsedBySessionX, singleConnectionOwner); } } } }
internal void Invalidate() { OrmLog.Debug(Strings.LogSessionXInvalidate, this); ClearChangeRegistry(); InvalidateCachedEntities(); }
private async ValueTask <TransactionScope> OpenTransactionScope( Transaction transaction, bool isAsync, CancellationToken token = default) { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXOpeningTransaction, this); } SystemEvents.NotifyTransactionOpening(transaction); Events.NotifyTransactionOpening(transaction); Transaction = transaction; if (isAsync) { await transaction.BeginAsync(token).ConfigureAwait(false); } else { transaction.Begin(); } IDisposable logIndentScope = null; if (IsDebugEventLoggingEnabled) { logIndentScope = OrmLog.DebugRegion(Strings.LogSessionXTransaction, this); } SystemEvents.NotifyTransactionOpened(transaction); Events.NotifyTransactionOpened(transaction); return(new TransactionScope(transaction, logIndentScope)); }
private TransactionScope OpenTransactionScope(Transaction transaction) { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXOpeningTransaction, this); } SystemEvents.NotifyTransactionOpening(transaction); Events.NotifyTransactionOpening(transaction); Transaction = transaction; transaction.Begin(); IDisposable logIndentScope = null; if (IsDebugEventLoggingEnabled) { logIndentScope = OrmLog.DebugRegion(Strings.LogSessionXTransaction, this); } SystemEvents.NotifyTransactionOpened(transaction); Events.NotifyTransactionOpened(transaction); return(new TransactionScope(transaction, logIndentScope)); }
internal void RemapEntityKeys(KeyMapping keyMapping) { if (keyMapping.Map.Count == 0) { return; } using (Activate()) { if (!LazyKeyGenerationIsEnabled) { Persist(PersistReason.RemapEntityKeys); Invalidate(); } OrmLog.Debug(Strings.LogSessionXRemappingEntityKeys, this); foreach (var entityState in EntityChangeRegistry.GetItems(PersistenceState.New)) { var key = entityState.Key; var remappedKey = keyMapping.TryRemapKey(key); if (remappedKey != key) { entityState.RemapKey(remappedKey); } EntityStateCache.Add(entityState); } ProcessChangesOfEntitySets(entitySetState => entitySetState.RemapKeys(keyMapping)); EntityEvents.RemapKeys(keyMapping); } }
internal void CompleteTransaction(Transaction transaction) { userDefinedQueryTasks.Clear(); pinner.ClearRoots(); ValidationContext.Reset(); Transaction = transaction.Outer; switch (transaction.State) { case TransactionState.Committed: if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXCommittedTransaction, this); } SystemEvents.NotifyTransactionCommitted(transaction); Events.NotifyTransactionCommitted(transaction); break; case TransactionState.RolledBack: if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXRolledBackTransaction, this); } SystemEvents.NotifyTransactionRollbacked(transaction); Events.NotifyTransactionRollbacked(transaction); break; default: throw new ArgumentOutOfRangeException("transaction.State"); } }
/// <exception cref="InvalidOperationException"> /// Attempt to associate non-null <paramref name="tuple"/> with <paramref name="key"/> of unknown type. /// </exception> internal EntityState UpdateStateInCache(Key key, Tuple tuple, bool isStale) { var result = EntityStateCache[key, true]; if (result == null) { if (!key.HasExactType && tuple != null) { throw Exceptions.InternalError( Strings.ExCannotAssociateNonEmptyEntityStateWithKeyOfUnknownType, OrmLog.Instance); } result = AddEntityStateToCache(key, tuple, isStale); SystemEvents.NotifyEntityMaterialized(result); Events.NotifyEntityMaterialized(result); } else { if (!result.Key.HasExactType && key.HasExactType) { EntityStateCache.RemoveKey(result.Key); result = AddEntityStateToCache(key, tuple, result.IsStale); } result.Update(tuple); result.IsStale = isStale; if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXUpdatingCacheY, this, result); } } return(result); }
internal void RemoveOrCreateRemovedEntity(Type type, Key key, EntityRemoveReason reason) { // Checking for deleted entity with the same key var result = EntityStateCache[key, false]; if (result != null) { if (result.PersistenceState == PersistenceState.Removed) { return; } result.Entity.RemoveLaterInternal(reason); return; } EnforceChangeRegistrySizeLimit(); // Must be done before new entity registration result = new EntityState(this, key, null) { PersistenceState = PersistenceState.Removed }; EntityStateCache.Add(result); if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXCachingY, this, result); } }
internal override sealed void SystemBeforeGetValue(FieldInfo field) { if (!Session.Configuration.Supports(SessionOptions.ReadRemovedObjects)) { EnsureNotRemoved(); } if (Session.IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXGettingValueKeyYFieldZ, Session, Key, field); } EnsureIsFetched(field); Session.CheckForSwitching(); Session.SystemEvents.NotifyFieldValueGetting(this, field); using (Session.Operations.EnableSystemOperationRegistration()) { Session.Events.NotifyFieldValueGetting(this, field); if (Session.IsSystemLogicOnly) { return; } var subscriptionInfo = GetSubscription(EntityEventBroker.GettingFieldEventKey); if (subscriptionInfo.Second != null) { ((Action <Key, FieldInfo>)subscriptionInfo.Second) .Invoke(subscriptionInfo.First, field); } OnGettingFieldValue(field); } }
internal override sealed void SystemBeforeGetValue(FieldInfo field) { if (!Session.Configuration.Supports(SessionOptions.ReadRemovedObjects)) { EnsureNotRemoved(); } // getting of field value is frequent operation and access to resources // will slow down execution significantly if (OrmLog.IsLogged(LogLevel.Debug)) { OrmLog.Debug(Strings.LogSessionXGettingValueKeyYFieldZ, Session, Key, field); } EnsureIsFetched(field); Session.SystemEvents.NotifyFieldValueGetting(this, field); using (Session.Operations.EnableSystemOperationRegistration()) { Session.Events.NotifyFieldValueGetting(this, field); if (Session.IsSystemLogicOnly) { return; } var subscriptionInfo = GetSubscription(EntityEventBroker.GettingFieldEventKey); if (subscriptionInfo.Second != null) { ((Action <Key, FieldInfo>)subscriptionInfo.Second) .Invoke(subscriptionInfo.First, field); } OnGettingFieldValue(field); } }
// Constructors internal Session(Domain domain, SessionConfiguration configuration, bool activate) : base(domain) { Guid = Guid.NewGuid(); IsDebugEventLoggingEnabled = OrmLog.IsLogged(LogLevel.Debug); // Just to cache this value // Both Domain and Configuration are valid references here; // Configuration is already locked Configuration = configuration; Name = configuration.Name; identifier = Interlocked.Increment(ref lastUsedIdentifier); CommandTimeout = configuration.DefaultCommandTimeout; allowSwitching = configuration.Supports(SessionOptions.AllowSwitching); // Handlers Handlers = domain.Handlers; Handler = CreateSessionHandler(); // Caches, registry EntityStateCache = CreateSessionCache(configuration); EntityChangeRegistry = new EntityChangeRegistry(this); EntitySetChangeRegistry = new EntitySetChangeRegistry(this); ReferenceFieldsChangesRegistry = new ReferenceFieldsChangesRegistry(this); entitySetsWithInvalidState = new HashSet <EntitySetBase>(); // Events EntityEvents = new EntityEventBroker(); Events = new SessionEventAccessor(this, false); SystemEvents = new SessionEventAccessor(this, true); // Etc. PairSyncManager = new SyncManager(this); RemovalProcessor = new RemovalProcessor(this); pinner = new Pinner(this); Operations = new OperationRegistry(this); NonPairedReferencesRegistry = new NonPairedReferenceChangesRegistry(this); CommandProcessorContextProvider = new CommandProcessorContextProvider(this); // Validation context ValidationContext = Configuration.Supports(SessionOptions.ValidateEntities) ? (ValidationContext) new RealValidationContext() : new VoidValidationContext(); // Creating Services Services = CreateServices(); disposableSet = new DisposableSet(); remapper = new KeyRemapper(this); disableAutoSaveChanges = !configuration.Supports(SessionOptions.AutoSaveChanges); // Perform activation if (activate) { ActivateInternally(); } // Query endpoint SystemQuery = Query = new QueryEndpoint(new QueryProvider(this)); }
internal void RollbackTransaction(Transaction transaction) { try { OrmLog.Debug(Strings.LogSessionXRollingBackTransaction, this); SystemEvents.NotifyTransactionRollbacking(transaction); Events.NotifyTransactionRollbacking(transaction); } finally { try { Handler.CompletingTransaction(transaction); } finally { try { if (Configuration.Supports(SessionOptions.SuppressRollbackExceptions)) { RollbackWithSuppression(transaction); } else { Rollback(transaction); } } finally { if (!persistingIsFailed || !Configuration.Supports(SessionOptions.NonTransactionalReads)) { CancelEntitySetsChanges(); ClearChangeRegistry(); NonPairedReferencesRegistry.Clear(); EntitySetChangeRegistry.Clear(); } persistingIsFailed = false; } } } }
// IDisposable implementation /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (isDisposed) { return; } try { OrmLog.Debug(Strings.LogSessionXDisposing, this); SystemEvents.NotifyDisposing(); Events.NotifyDisposing(); Services.DisposeSafely(); Handler.DisposeSafely(); CommandProcessorContextProvider.DisposeSafely(); Domain.ReleaseSingleConnection(); disposableSet.DisposeSafely(); disposableSet = null; EntityChangeRegistry.Clear(); EntitySetChangeRegistry.Clear(); EntityStateCache.Clear(); ReferenceFieldsChangesRegistry.Clear(); NonPairedReferencesRegistry.Clear(); } finally { isDisposed = true; } }
internal Session OpenSessionInternal(SessionConfiguration configuration, StorageNode storageNode, bool activate) { ArgumentValidator.EnsureArgumentNotNull(configuration, nameof(configuration)); configuration.Lock(true); if (isDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogOpeningSessionX, configuration); } Session session; if (SingleConnection != null) { // Ensure that we check shared connection availability // and acquire connection atomically. lock (singleConnectionGuard) { if (singleConnectionOwner != null) { throw new InvalidOperationException(string.Format( Strings.ExSessionXStillUsesSingleAvailableConnection, singleConnectionOwner)); } session = new Session(this, storageNode, configuration, activate); singleConnectionOwner = session; } } else { session = new Session(this, storageNode, configuration, activate); } NotifySessionOpen(session); return(session); }
private void RollbackWithSuppression(Transaction transaction) { try { Rollback(transaction); } catch (Exception e) { OrmLog.Warning(e); } }
internal void Invalidate() { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXInvalidate, this); } ClearChangeRegistry(); InvalidateCachedEntities(); }
public async ValueTask InnerDispose(bool isAsync) { lock (disposeGuard) { if (isDisposed) { return; } isDisposed = true; } if (isDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogDomainIsDisposing); } NotifyDisposing(); Services.Dispose(); if (SingleConnection == null) { return; } SqlConnection singleConnectionLocal; lock (singleConnectionGuard) { if (singleConnectionOwner != null) { OrmLog.Warning( Strings.LogUnableToCloseSingleAvailableConnectionItIsStillUsedBySessionX, singleConnectionOwner); return; } else { singleConnectionLocal = SingleConnection; SingleConnection = null; } } var driver = Handlers.StorageDriver; if (isAsync) { await driver.CloseConnectionAsync(null, singleConnectionLocal).ConfigureAwait(false); await driver.DisposeConnectionAsync(null, singleConnectionLocal).ConfigureAwait(false); } else { driver.CloseConnection(null, singleConnectionLocal); driver.DisposeConnection(null, singleConnectionLocal); } }
internal override sealed void SystemBeforeInitialize(bool materialize) { State.Entity = this; if (Session.IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXMaterializingYKeyZ, Session, GetType().GetShortName(), State.Key); } if (Session.IsSystemLogicOnly || materialize) { return; } // Not necessity to use // Session.Operations.EnableSystemOperationRegistration() // here, because there is no higher level system operation // for this one, or system op. registration is already enabled. bool hasKeyGenerator = Session.Domain.KeyGenerators[TypeInfo.Key] != null; if (hasKeyGenerator) { Session.SystemEvents.NotifyKeyGenerated(Key); Session.Events.NotifyKeyGenerated(Key); } Session.SystemEvents.NotifyEntityCreated(this); Session.Events.NotifyEntityCreated(this); var operations = Session.Operations; // Operation 1: using (var scope = operations.BeginRegistration(OperationType.System)) { if (operations.CanRegisterOperation) { operations.RegisterOperation(new KeyGenerateOperation(Key), true); } scope.Complete(); } // Operation 2: using (var scope = operations.BeginRegistration(OperationType.System)) { if (operations.CanRegisterOperation) { operations.RegisterOperation(new EntityCreateOperation(Key), true); } IdentifyAs(EntityIdentifierType.Auto); scope.Complete(); } var subscriptionInfo = GetSubscription(EntityEventBroker.InitializingPersistentEventKey); if (subscriptionInfo.Second != null) { ((Action <Key>)subscriptionInfo.Second).Invoke(subscriptionInfo.First); } }
private EntityState AddEntityStateToCache(Key key, Tuple tuple, bool isStale) { var result = new EntityState(this, key, tuple, isStale) { PersistenceState = PersistenceState.Synchronized }; EntityStateCache.Add(result); OrmLog.Debug(Strings.LogSessionXCachingY, this, result); return(result); }
internal async Task <Session> OpenSessionInternalAsync(SessionConfiguration configuration, StorageNode storageNode, SessionScope sessionScope, CancellationToken cancellationToken) { ArgumentValidator.EnsureArgumentNotNull(configuration, nameof(configuration)); configuration.Lock(true); if (isDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogOpeningSessionX, configuration); } Session session; if (SingleConnection != null) { // Ensure that we check shared connection availability // and acquire connection atomically. lock (singleConnectionGuard) { if (singleConnectionOwner != null) { throw new InvalidOperationException(string.Format( Strings.ExSessionXStillUsesSingleAvailableConnection, singleConnectionOwner)); } session = new Session(this, storageNode, configuration, false); singleConnectionOwner = session; } } else { // DO NOT make session active right from constructor. // That would make session accessible for user before // connection become opened. session = new Session(this, storageNode, configuration, false); try { await((SqlSessionHandler)session.Handler).OpenConnectionAsync(cancellationToken) .ContinueWith(t => { if (sessionScope != null) { session.AttachToScope(sessionScope); } }, TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously) .ConfigureAwait(false); } catch (OperationCanceledException) { await session.DisposeSafelyAsync().ConfigureAwait(false); throw; } } NotifySessionOpen(session); return(session); }
public void OrmLogTest() { if (File.Exists(filePath)) { File.Delete(filePath); } OrmLog.Debug("Test message", null); OrmLog.Debug("Test message with parameter {0}", new object[] { 1 }); _ = OrmLog.Debug(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 }); OrmLog.Debug("Test message", new object[] { 1 }); OrmLog.Debug("Test message {0}", null); _ = OrmLog.Debug(new Exception("Some exeption")); OrmLog.Debug(null, new object[] { 1 }); OrmLog.Info("Test message", null); OrmLog.Info("Test message with parameter {0}", new object[] { 1 }); _ = OrmLog.Info(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 }); OrmLog.Info("Test message", new object[] { 1 }); OrmLog.Info("Test message {0}", null); _ = OrmLog.Info(new Exception("Some exeption")); OrmLog.Info(null, new object[] { 1 }); OrmLog.Warning("Test message", null); OrmLog.Warning("Test message with parameter {0}", new object[] { 1 }); _ = OrmLog.Warning(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 }); OrmLog.Warning("Test message", new object[] { 1 }); OrmLog.Warning("Test message {0}", null); _ = OrmLog.Warning(new Exception("Some exeption")); OrmLog.Warning(null, new object[] { 1 }); OrmLog.Error("Test message", null); OrmLog.Error("Test message with parameter {0}", new object[] { 1 }); _ = OrmLog.Error(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 }); OrmLog.Error("Test message", new object[] { 1 }); OrmLog.Error("Test message {0}", null); _ = OrmLog.Error(new Exception("Some exeption")); OrmLog.Error(null, new object[] { 1 }); OrmLog.FatalError("Test message", null); OrmLog.FatalError("Test message with parameter {0}", new object[] { 1 }); _ = OrmLog.FatalError(new Exception("Some exception"), "Test message with parameter {0}", new object[] { 1 }); OrmLog.FatalError("Test message", new object[] { 1 }); OrmLog.FatalError("Test message {0}", null); _ = OrmLog.FatalError(new Exception("Some exeption")); OrmLog.FatalError(null, new object[] { 1 }); Assert.IsTrue(File.Exists(filePath)); Assert.AreEqual(File.ReadAllLines(filePath).Count(), 35); }
internal async ValueTask CommitTransaction(Transaction transaction, bool isAsync) { if (IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXCommittingTransaction, this); } SystemEvents.NotifyTransactionPrecommitting(transaction); Events.NotifyTransactionPrecommitting(transaction); if (isAsync) { await PersistAsync(PersistReason.Commit).ConfigureAwait(false); } else { Persist(PersistReason.Commit); } ValidationContext.Validate(ValidationReason.Commit); SystemEvents.NotifyTransactionCommitting(transaction); Events.NotifyTransactionCommitting(transaction); Handler.CompletingTransaction(transaction); if (transaction.IsNested) { if (isAsync) { await Handler.ReleaseSavepointAsync(transaction).ConfigureAwait(false); } else { Handler.ReleaseSavepoint(transaction); } } else { if (isAsync) { await Handler.CommitTransactionAsync(transaction).ConfigureAwait(false); } else { Handler.CommitTransaction(transaction); } } }
public TypeInfo ResolveTypeInfo([NotNull, InstantHandle] Session session) { ArgumentValidator.EnsureArgumentNotNull(session, "session"); if (TypeReference.Accuracy == TypeReferenceAccuracy.ExactType) { return(TypeReference.Type); } var domain = session.Domain; var keyCache = domain.KeyCache; Key cachedKey; lock (keyCache) keyCache.TryGetItem(this, true, out cachedKey); if (cachedKey != null) { TypeReference = cachedKey.TypeReference; return(TypeReference.Type); } var hierarchy = TypeReference.Type.Hierarchy; if (hierarchy != null && hierarchy.Types.Count == 1) { TypeReference = new TypeReference(hierarchy.Types[0], TypeReferenceAccuracy.ExactType); return(TypeReference.Type); } if (IsTemporary(domain)) { return(TypeReference.Type); } if (session.IsDebugEventLoggingEnabled) { OrmLog.Debug(Strings.LogSessionXResolvingKeyYExactTypeIsUnknownFetchIsRequired, session, this); } var entityState = session.Handler.FetchEntityState(this); if (entityState == null || entityState.IsNotAvailableOrMarkedAsRemoved) { throw new InvalidOperationException(string.Format(Strings.ExUnableToResolveTypeForKeyX, this)); } TypeReference = new TypeReference(entityState.Type, TypeReferenceAccuracy.ExactType); return(TypeReference.Type); }
/// <summary> /// Validates the <paramref name="version"/> /// for the specified <paramref name="key"/>. /// </summary> /// <param name="key">The key to validate version for.</param> /// <param name="version">The version to validate.</param> /// <param name="throwOnFailure">Indicates whether <see cref="InvalidOperationException"/> /// must be thrown on validation failure.</param> /// <returns> /// <see langword="True"/>, if validation passes successfully; /// otherwise, <see langword="false"/>. /// </returns> /// <exception cref="VersionConflictException">Version conflict is detected.</exception> public bool ValidateVersion(Key key, VersionInfo version, bool throwOnFailure) { var result = ValidateVersion(key, version); if (throwOnFailure && !result) { if (OrmLog.IsLogged(LogLevel.Info)) { OrmLog.Info(Strings.LogSessionXVersionValidationFailedKeyYVersionZExpected3, Session, key, version, expectedVersionProvider.Invoke(key)); } throw new VersionConflictException(string.Format( Strings.ExVersionOfEntityWithKeyXDiffersFromTheExpectedOne, key)); } return(result); }
/// <inheritdoc/> /// <exception cref="VersionConflictException">Version check failed.</exception> protected override void ExecuteSelf(OperationExecutionContext context) { var session = context.Session; var entity = session.Query.Single(Key); if (entity.VersionInfo != Version) { if (OrmLog.IsLogged(LogLevel.Info)) { OrmLog.Info(Strings.LogSessionXVersionValidationFailedKeyYVersionZExpected3, session, Key, entity.VersionInfo, Version); } throw new VersionConflictException( string.Format(Strings.ExVersionOfEntityWithKeyXDiffersFromTheExpectedOne, Key)); } }
private async ValueTask RollbackWithSuppression(Transaction transaction, bool isAsync) { try { if (isAsync) { await RollbackAsync(transaction).ConfigureAwait(false); } else { Rollback(transaction); } } catch (Exception e) { OrmLog.Warning(e); } }