/// <summary> /// Executes the HTTP POST method. /// </summary> public async Task <HttpResponseMessage> Post(SessionResource resource) { // Make sure the resource is valid. bool resourceIsNull = resource == null; bool resourceIsInvalid = this.ModelState.IsValid == false; if (resourceIsNull || resourceIsInvalid) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); HttpResponseException httpResponseException = new HttpResponseException(httpResponseMessage); throw httpResponseException; } // Open a database connection and begin a database transaction. using (IDatabaseConnection databaseConnection = await this.databaseConnectionProvider.OpenDatabaseConnection()) using (IDatabaseTransaction databaseTransaction = databaseConnection.BeginDatabaseTransaction()) { // Invoke the NewSession business operation. NewSessionBusinessResponse newSessionBusinessResponse = await this.InvokeNewSession(databaseConnection, resource); // Update the Session resource element. if (resource.Session != null) { resource.Session.SessionCode = newSessionBusinessResponse.Session.SessionCode; } // Commit the database transaction. databaseTransaction.Commit(); // Build an HTTP response message. HttpResponseMessage httpResponseMessage = this.Request.CreateResponse(HttpStatusCode.Created, resource); return(httpResponseMessage); } }
public async Task <bool> Run() { using IDatabaseService databaseService = Resolve <IDatabaseService>(); IDbConnection connection = await databaseService.Connection; connection.CreateTableIfNotExists <Migration>(); using IDatabaseTransaction transaction = await databaseService.Transaction(); try { foreach (IMigrationModule module in _modules) { if (!await MigrateModule(connection, module)) { return(false); } } transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } return(true); }
public void Dispose() { if (!_disposed) { _disposed = true; TransactionState state = GetTransactionState(_workContext); if (!_completed) { System.Threading.Interlocked.Increment(ref state.RollbackCount); } if ((state.RollbackCount + state.CommiteCount) == state.ChainCount) { if (state.RollbackCount > 0) { _dbTransaction?.Rollback(); } state.ChainCount = 0; state.CommiteCount = 0; state.RollbackCount = 0; } _dbTransaction?.Dispose(); _dbTransaction = null; _workContext = null; } }
public BaseService(IDatabaseTransaction databaseTransaction, IBaseService childBL = null) : this(childBL) { DatabaseTransaction = databaseTransaction; if (ChildBL != null) { ChildBL.IsChild = true; ChildBL.IsCommitingChanges = false; // Default value when BL is child var bl = ChildBL as BaseService; if (bl != null) { bl.DatabaseTransaction = DatabaseTransaction; } BaseService temp = this; while (temp.ChildBL != null) { temp = temp.ChildBL as BaseService; if (temp != null) { temp.IsChild = true; temp.IsCommitingChanges = false; temp.DatabaseTransaction = DatabaseTransaction; } } } }
/// <summary> /// Handles the situation in which the database is locked and the statement cannot be executed because of race conditions. /// </summary> private void HandleDeadlock() { // if there is an open transaction on the connection if (this.Statement.Connection.IsUnderTransaction) { // roll it back - rolling back a nested transaction forces all previous transactions to be reverted using (IDatabaseTransaction transaction = this.Statement.Connection.BeginTransaction()) { transaction.Rollback(); } } try { this.Statement.SqliteStatement.Reset(); } catch (SQLiteException) { // sqlite.PCL hides result code from Reset() and throws exception instead // when BUSY is returned by sqlite, Reset() will also return Busy for the first call // ignore first time exception so no BUSY exception is returned when disposing this statement } throw new DatabaseException( DatabaseErrorCode.Deadlock, "This statement has been aborted and the transaction (if any) rolled back to avoid a deadlock. Please try executing your operation again."); }
private void ResetInterfaceOnRelations(ItInterface affectedInterface, IDatabaseTransaction transaction) { var systemRelations = affectedInterface.AssociatedSystemRelations.ToList(); if (systemRelations.Any()) { foreach (var systemRelation in systemRelations) { var fromSystemUsage = systemRelation.FromSystemUsage; var result = fromSystemUsage.ModifyUsageRelation( relationId: systemRelation.Id, toSystemUsage: systemRelation.ToSystemUsage, changedDescription: systemRelation.Description, changedReference: systemRelation.Reference, relationInterface: Maybe <ItInterface> .None, //Remove the interface binding toContract: systemRelation.AssociatedContract, toFrequency: systemRelation.UsageFrequency); if (result.Failed) { throw new InvalidOperationException($"Failed to modify system relation. Error: {result.Error}"); } } _systemUsageRepository.Save(); transaction.Commit(); } }
/// <summary> /// Executes the HTTP GET method. /// </summary> public async Task <HttpResponseMessage> Get() { // Open a database connection and begin a database transaction. using (IDatabaseConnection databaseConnection = await this.databaseConnectionProvider.OpenDatabaseConnection()) using (IDatabaseTransaction databaseTransaction = databaseConnection.BeginDatabaseTransaction()) { // Invoke the GetSessions business operation. GetSessionsBusinessResponse getSessionsBusinessResponse = await this.InvokeGetSessions(databaseConnection); // Build the Session resources. List <SessionResource> sessionResources = new List <SessionResource>(); foreach (GetSessionsBusinessResponse.SessionBusinessResponseElement sessionBusinessResponseElement in getSessionsBusinessResponse.Sessions) { // Build the Session resource. SessionResource sessionResource = new SessionResource(); sessionResources.Add(sessionResource); // Build the Session resource element. SessionResource.SessionResourceElement sessionResourceElement = new SessionResource.SessionResourceElement(); sessionResourceElement.SessionCode = sessionBusinessResponseElement.SessionCode; sessionResourceElement.Name = sessionBusinessResponseElement.Name; sessionResourceElement.StartDate = sessionBusinessResponseElement.StartDate; sessionResource.Session = sessionResourceElement; } // Commit the database transaction. databaseTransaction.Commit(); // Return an HTTP response message. HttpResponseMessage httpResponseMessage = this.Request.CreateResponse(HttpStatusCode.OK, sessionResources.ToArray()); return(httpResponseMessage); } }
private void RemoveTransaction(IDatabaseTransaction workItem) { _rwLock.EnterWriteLock(); _workItems.Remove(workItem); _rwLock.ExitWriteLock(); }
private int CompleteUpdate(int updatesExecuted, List <PendingReadModelUpdate> updates, PendingReadModelUpdate userUpdate, IDatabaseTransaction transaction) { updates.ForEach(update => _updateRepository.Add(update)); _updateRepository.Delete(userUpdate); transaction.Commit(); updatesExecuted++; return(updatesExecuted); }
public ServiceBase(IDatabaseTransaction databaseTransaction, ServiceBase parent) : this(databaseTransaction) { DatabaseTransaction = databaseTransaction; if (parent != null) { DatabaseTransaction = parent.DatabaseTransaction; IsCommitingChanges = false; // When BL is child IsChild = true; } }
/// <summary> /// 构造函数 /// </summary> /// <param name="isolationLevel">事务级别</param> /// <param name="connectionName">连接配置名</param> public DbTransactionScope(IsolationLevel isolationLevel = IsolationLevel.ReadUncommitted, string connectionName = null) { TransactionState state = GetTransactionState(); int count = Interlocked.Increment(ref state.ChainCount); if (count == 1) { var context = WorkContext.Current.RequestServices.GetRequiredService <IDatabaseContext>(); var dbTransaction = context.BeginTransaction(isolationLevel, connectionName); Transaction = dbTransaction; } }
/// <summary> /// Populates the temporary table in the database with the records presents in the <see cref="Table"/>. /// </summary> private void ExecutePopulateTable() { const string InsertTable = "INSERT INTO {0} ({1}) VALUES ({2});"; // for multiple row insertion, begining a transaction improves performance, because sqlite doesn't need to start // a new transaction for every single insert. using (var provider = new SqliteDatabaseProvider()) using (IDatabaseTransaction transaction = this.connection.BeginTransaction()) { this.Table.ExecuteNonQuery(this.connection, provider, InsertTable); transaction.Commit(); } }
public DbTransactionScope(WorkContext workContext, IsolationLevel isolationLevel = IsolationLevel.ReadUncommitted, string connectionName = null) { _workContext = workContext ?? throw new InvalidOperationException("当前环境缺少工作上下文 WorkContext, 请尝试使用其他重载的构造函数。"); TransactionState state = GetTransactionState(workContext); int count = System.Threading.Interlocked.Increment(ref state.ChainCount); if (count == 1) { var context = workContext.ResolveRequired <IDatabaseContext>(); var dbTransaction = context.BeginTransaction(isolationLevel, connectionName); _dbTransaction = dbTransaction; } }
public DetailService( IGenericRepository <Detail> details, IGenericRepository <Category> categories, IGenericRepository <Brand> brands, IGenericRepository <Country> countries, IDatabaseTransaction transaction, IGenericRepository <Log> logs) { this.details = details; this.categories = categories; this.brands = brands; this.countries = countries; this.transaction = transaction; this.logs = logs; }
/// <summary> /// 进入一个事务上下文 /// </summary> /// <param name="transaction">要进入的事务</param> /// <returns>事务上下文</returns> public static IDatabaseTransaction EnterTransaction(IDatabaseTransaction transaction) { if (transaction == null) { throw new ArgumentNullException(nameof(transaction)); } var context = DbContext.EnterContext(transaction); transaction.RegisterDispose(context); transaction.BeginTransaction(); return(transaction); }
private int PerformUpdate( int updatesExecuted, HashSet <int> alreadyScheduledIds, IEnumerable <int> idsOfAffectedUsages, PendingReadModelUpdate sourceUpdate, IDatabaseTransaction transaction) { var updates = idsOfAffectedUsages .Where(id => alreadyScheduledIds.Contains(id) == false) .ToList() .Select(id => PendingReadModelUpdate.Create(id, PendingReadModelUpdateSourceCategory.ItSystemUsage)) .ToList(); updatesExecuted = CompleteUpdate(updatesExecuted, updates, sourceUpdate, transaction); updates.ForEach(completedUpdate => alreadyScheduledIds.Add(completedUpdate.SourceId)); return(updatesExecuted); }
public TransactionalCommand(string commandText, bool createTransaction, DataContext dataContext) { // TODO: check if all this stuff is necessary // the OpenConnection() checks that the connection is already open // TODO: see if we can move this here (in theory the final DataContext shouldn't use) _connection = dataContext.DatabaseContext.OpenConnection(); // the transaction is optional if (createTransaction) { _transaction = dataContext.DatabaseContext.Transaction(); } _command = dataContext.DatabaseContext.CreateCommand(); Command.CommandText = commandText; if (createTransaction) { Command.Transaction = _transaction.Transaction; } }
private void TransactionalFlush(IsolationLevel isolationLevel) { IDatabaseTransaction transaction = BeginTransaction(isolationLevel); try { transaction.Commit(); } catch (Exception e) { transaction.Rollback(); throw new ArgumentException("Exception_FailedToFlush"); } finally { transaction.Dispose(); } }
/// <summary> /// 回收 /// </summary> public void Dispose() { if (!_disposed) { TransactionState state = GetTransactionState(); if (!_completed) { Interlocked.Increment(ref state.RollbackCount); } if (state.RollbackCount + state.CommitCount == state.ChainCount) { if (state.RollbackCount > 0) { Transaction?.Rollback(); } state.ChainCount = 0; state.CommitCount = 0; state.RollbackCount = 0; } Transaction?.Dispose(); Transaction = null; } _disposed = true; }
protected override void Initialize() { base.Initialize(); if (this.Verbose) { this.LoggingService.WriteLine("\nOpening Destination Database Connection..."); } this.DestinationDatabase = ConnectorFactory.Create(this.Configuration.DestinationDatabase.DatabaseType); this.DestinationDatabase.Initialize(this.Configuration.DestinationDatabase.ConnectionString); if (!this.DestinationDatabase.IsOpen()) { this.DestinationDatabase.Open(); } this.Transaction = this.DestinationDatabase.CreateTransaction(); if (this.Verbose) { this.LoggingService.WriteLine("Destination Database Connection openend."); } }
private static void OnTransactionException(IDatabaseTransaction transaction, Exception e) { try { if (transaction.Status == TransactionStatus.Running) { transaction.Rollback(); } } catch (Exception ex) { var exception = new TransactionCompleteException("exception in auto rollback database transaction.", ex); if (e is RollbackImmediatelyException) { throw exception; } else { throw new AggregateException(exception, e); } } }
/// <summary> /// 异步进入一个事务上下文 /// </summary> /// <param name="transaction">要进入的事务,若事务是异步事务,则会异步开启,否则将同步开启</param> /// <returns>事务上下文</returns> public static async ValueTask <IDatabaseTransaction> EnterTransactionAsync(IDatabaseTransaction transaction) { if (transaction == null) { throw new ArgumentNullException(nameof(transaction)); } var context = DbContext.EnterContext(transaction); transaction.RegisterDispose(context); if (transaction is IAsyncDatabaseTransaction async) { await async.BeginTransactionAsync(); } else { transaction.BeginTransaction(); } return(transaction); }
public Lease CreateLease(OrderQuote responseOrderQuote, StoreBookingFlowContext flowContext, IStateContext stateContext, IDatabaseTransaction dbTransaction) { return(CreateLease(responseOrderQuote, flowContext, (TStateContext)stateContext, (TDatabaseTransaction)dbTransaction)); }
public ValueTask ProposeOrderItems(List <IOrderItemContext> orderItemContexts, StoreBookingFlowContext flowContext, IStateContext stateContext, IDatabaseTransaction databaseTransactionContext) { return(ProposeOrderItems(ConvertToSpecificComponents(orderItemContexts), flowContext, (TStateContext)stateContext, (TDatabaseTransaction)databaseTransactionContext)); }
public AsyncDbTransactionContextWrapper(IDatabaseTransaction context) { _context = context; }
public TransactionalCommand(string commandText, bool createTransaction, DataContext dataContext) { // TODO: check if all this stuff is necessary // the OpenConnection() checks that the connection is already open // TODO: see if we can move this here (in theory the final DataContext shouldn't use) _connection = dataContext.DatabaseContext.OpenConnection(); _command = dataContext.DatabaseContext.CreateCommand(); haveHigherTransaction = dataContext.Transaction != null; // the transaction is optional if (createTransaction && !haveHigherTransaction) { _transaction = dataContext.DatabaseContext.Transaction(); _command.Transaction = _transaction.Transaction; } else _command.Transaction = dataContext.Transaction; Command.CommandText = commandText; }
public TransactionService(IDatabaseTransaction databaseTransaction) { this.databaseTransaction = databaseTransaction; }
public BaseService(IDatabaseTransaction databaseTransaction) : this() { DatabaseTransaction = databaseTransaction; }
public void BookOrderItems(List <IOrderItemContext> orderItemContexts, StoreBookingFlowContext flowContext, IStateContext stateContext, IDatabaseTransaction databaseTransactionContext) { // TODO: Include validation on the OrderItem created, to ensure it includes all the required fields BookOrderItem(ConvertToSpecificComponents(orderItemContexts), flowContext, (TStateContext)stateContext, (TDatabaseTransaction)databaseTransactionContext); }
public TransactionScope(DatabaseContext context, IDatabaseTransaction parentScope) { _context = context; _parentScope = parentScope; _context._transactions.Push(this); }
public void UpdateOrder(Order responseOrder, StoreBookingFlowContext flowContext, IStateContext stateContext, IDatabaseTransaction dbTransaction) { UpdateOrder(responseOrder, flowContext, (TStateContext)stateContext, (TDatabaseTransaction)dbTransaction); }