コード例 #1
0
ファイル: SeedRunner.cs プロジェクト: PatrickRatzow/Skrabbl
        internal async Task Start()
        {
            await Connect();

            DbTransaction trx = null;

            try
            {
                trx = await _connection.BeginTransactionAsync();

                foreach (var seed in _seeds)
                {
                    seed.Connection  = _connection;
                    seed.Transaction = trx;
                    await seed.Up();
                }

                await trx.CommitAsync();
            }
            catch (Exception e)
            {
                await trx !.RollbackAsync();

                throw new SeedingException($"Failed to seed! Rolling back", e);
            }
        }
コード例 #2
0
 private async Task WritingAction(CancellationToken forceStopToken)
 {
     using (ConnectionWrapper connectionWrapper = await manager.GetConnectionAsync(forceStopToken))
     {
         DbCommand command = writerCore.CreateMainCommand(connectionWrapper.Connection);
         while (!forceStopToken.IsCancellationRequested && !DataQueue.IsEmpty)
         {
             using (DbTransaction transaction = await connectionWrapper.Connection.BeginTransactionAsync(forceStopToken))
             {
                 try
                 {
                     for (int i = 0; i < settings.TrasactionSize && !forceStopToken.IsCancellationRequested && !DataQueue.IsEmpty; i++)
                     {
                         if (DataQueue.TryDequeue(out T message))
                         {
                             await writerCore.ExecuteWriting(command, message, forceStopToken);
                         }
                     }
                     await transaction.CommitAsync(forceStopToken);
                 }
                 catch (Exception ex)
                 {
                     logger.Error(ex, "Error while writing messages!");
                     await transaction.RollbackAsync();
                 }
             }
             await Task.Delay(100);
         }
     }
 }
コード例 #3
0
ファイル: UnitOfWork.cs プロジェクト: YCSiTong/SiTong.Core
        /// <summary>
        /// 提交事务
        /// </summary>
        /// <returns></returns>
        public virtual async Task CommitAsync()
        {
            if (_DbConnection == null || !_IsCommit)
            {
                return;
            }

            try
            {
                await _DbTransaction.CommitAsync();
            }
            catch (Exception ex)
            {
                if (_DbTransaction?.Connection != null)
                {
                    await _DbTransaction.RollbackAsync();
                }
                throw ex;
            }
            finally
            {
                if (_Db.Database.CurrentTransaction != null)
                {
                    await _Db.Database.CurrentTransaction.DisposeAsync();
                }
                _IsCommit = false;
            }
        }
コード例 #4
0
ファイル: Transaction.cs プロジェクト: mingyaaaa/Brochure
 /// <summary>
 /// Commits the.
 /// </summary>
 public async Task CommitAsync()
 {
     if (dbTransaction != null)
     {
         await dbTransaction.CommitAsync();
     }
     Dispose();
 }
コード例 #5
0
        /// <summary>
        /// imports unimported poem data from a locally accessible ganjoor SqlLite database
        /// </summary>
        /// <returns></returns>
        public async Task <RServiceResult <bool> > ImportLocalSQLiteDb()
        {
            try
            {
                SqliteConnectionStringBuilder connectionStringBuilder = new SqliteConnectionStringBuilder();
                connectionStringBuilder.DataSource = Configuration.GetSection("LocalSqliteImport")["FilePath"];
                using (SqliteConnection sqliteConnection = new SqliteConnection(connectionStringBuilder.ToString()))
                {
                    await sqliteConnection.OpenAsync();

                    IDbConnection dapper = sqliteConnection;
                    using (var sqlConnection = _context.Database.GetDbConnection())
                    {
                        await sqlConnection.OpenAsync();

                        foreach (var poet in await dapper.QueryAsync("SELECT * FROM poet ORDER BY id"))
                        {
                            int poetId = (int)poet.id;
                            if ((await _context.GanjoorPoets.Where(p => p.Id == poetId).FirstOrDefaultAsync()) != null)
                            {
                                continue;
                            }

                            DbTransaction transaction = await sqlConnection.BeginTransactionAsync();

                            try
                            {
                                using (var command = sqlConnection.CreateCommand())
                                {
                                    command.Transaction = transaction;
                                    command.CommandText =
                                        $"INSERT INTO GanjoorPoets (Id, Name, Description) VALUES (${poet.id}, N'{poet.name}', N'{poet.description}')";
                                    await command.ExecuteNonQueryAsync();
                                    await _ImportSQLiteCatChildren(command, dapper, poetId, 0, "", "");

                                    await transaction.CommitAsync();
                                }
                            }
                            catch (Exception exp2)
                            {
                                await transaction.RollbackAsync();

                                return(new RServiceResult <bool>(false, exp2.ToString()));
                            }
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                return(new RServiceResult <bool>(false, exp.ToString()));
            }
            return(new RServiceResult <bool>(true));
        }
コード例 #6
0
        public async Task CommitTransactionAsync(DbTransaction transaction)
        {
            DbConnection connection = transaction.Connection;
            await transaction.CommitAsync();

            await connection.CloseAsync();

            await transaction.DisposeAsync();

            await connection.DisposeAsync();
        }
コード例 #7
0
        public async Task <T> Run <T>(Func <Task <T> > action, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
        {
            var connection = connectionProvider.GetOpenedConnection();

            await using DbTransaction transaction = await connection.BeginTransactionAsync(isolationLevel);

            var result = await action();

            await transaction.CommitAsync();

            return(result);
        }
コード例 #8
0
ファイル: UnitOfWork.cs プロジェクト: xiaodelea/Sukt.Core
        /// <summary>
        /// 提交异步事务
        /// </summary>
        /// <returns></returns>
        public async Task CommitAsync()
        {
            if (HasCommitted || _dbTransaction == null)
            {
                return;
            }
            await _dbTransaction.CommitAsync();

            await _dbContext.Database.CurrentTransaction.DisposeAsync();

            HasCommitted = true;
        }
コード例 #9
0
        public async Task ExecuteAsync(IRequest command, CancellationToken cancellationToken)
        {
            await using (DbTransaction dbTransaction = (await _dbContext.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken: cancellationToken)).GetDbTransaction())
            {
                _messageStorageClient.UseTransaction(dbTransaction);
                await _mediator.Send(command, cancellationToken);

                await _dbContext.SaveChangesAsync(cancellationToken);

                await dbTransaction.CommitAsync(cancellationToken);
            }
        }
コード例 #10
0
        public virtual async Task <int> ExecuteNonQueryAsync(string rawSql)
        {
            Console.WriteLine(rawSql);
            DbCommand     cmd         = Connection.CreateCommand();
            DbTransaction transaction = await Connection.BeginTransactionAsync();

            cmd.CommandText = rawSql;
            var affectedRows = await cmd.ExecuteNonQueryAsync();

            await transaction.CommitAsync();

            return(affectedRows);
        }
コード例 #11
0
        public async Task <int> ChangeAnimalAsync()
        {
            using var con = new SqlConnection("Data Source=db-mssql;Initial Catalog=s18378;Integrated Security=True");
            using var com = new SqlCommand("select * from animal", con);

            await con.OpenAsync();

            DbTransaction tran = await con.BeginTransactionAsync();

            com.Transaction = (SqlTransaction)tran;

            try
            {
                var list = new List <Animal>();
                using (var dr = await com.ExecuteReaderAsync())
                {
                    while (await dr.ReadAsync())
                    {
                        list.Add(new Animal
                        {
                            Name        = dr["Name"].ToString(),
                            Description = dr["Description"].ToString()
                        });
                    }
                }

                com.Parameters.Clear();
                com.CommandText = "Update Animal Set Name= Name+ 'a' Where Name= @Name";
                com.Parameters.AddWithValue("@Name", list[0].Name);
                await com.ExecuteNonQueryAsync();

                throw new Exception("Error");

                com.Parameters.Clear();
                com.Parameters.AddWithValue("@Name", list[1].Name);
                await com.ExecuteNonQueryAsync();

                await tran.CommitAsync();
            }
            catch (SqlException exc)
            {
                await tran.RollbackAsync();
            }
            catch (Exception exc)
            {
                await tran.RollbackAsync();
            }
            return(1);
        }
コード例 #12
0
        public async Task <int> ExecuteTransactionAsync(Dictionary <string, object> sqlAndParameters, bool disposeConnection = true)
        {
            DbTransaction dbTransaction = null;

            try
            {
                await this.OpenDBConnectionAsync();

                dbTransaction = await base._dbConnection.BeginTransactionAsync();

                int affectedCollumnsNum = 0;

                foreach (KeyValuePair <string, object> sqlAndParameter in sqlAndParameters)
                {
                    affectedCollumnsNum += await base._dbConnection.ExecuteAsync(sqlAndParameter.Key, sqlAndParameter.Value, dbTransaction);
                }

                await dbTransaction.CommitAsync();

                return(affectedCollumnsNum);
            }
            catch (DbException e)
            {
                await dbTransaction?.RollbackAsync();

                disposeConnection = true;
                throw e;
            }
            catch (Exception e)
            {
                await dbTransaction?.RollbackAsync();

                disposeConnection = true;
                // TODO: Create a Transaction exception.
                throw e;
            }
            finally
            {
                _ = dbTransaction.DisposeAsync();

                if (disposeConnection)
                {
                    _ = base._dbConnection.DisposeAsync();
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task CreateAsync(CreateGroupDto inputDto)
        {
            bool exist = await _groupRepository.Select.AnyAsync(r => r.Name == inputDto.Name);

            if (exist)
            {
                throw new LinCmsException("分组已存在,不可创建同名分组", ErrorCode.RepeatField);
            }

            LinGroup linGroup = Mapper.Map <LinGroup>(inputDto);

            using var conn = _freeSql.Ado.MasterPool.Get();
            await using DbTransaction transaction = await conn.Value.BeginTransactionAsync();

            try
            {
                long groupId = await _freeSql.Insert(linGroup).WithTransaction(transaction).ExecuteIdentityAsync();

                List <LinPermission> allPermissions = await _freeSql.Select <LinPermission>().WithTransaction(transaction).ToListAsync();

                List <LinGroupPermission> linPermissions = new List <LinGroupPermission>();
                inputDto.PermissionIds.ForEach(r =>
                {
                    LinPermission pdDto = allPermissions.FirstOrDefault(u => u.Id == r);
                    if (pdDto == null)
                    {
                        throw new LinCmsException($"不存在此权限:{r}", ErrorCode.NotFound);
                    }
                    linPermissions.Add(new LinGroupPermission(groupId, pdDto.Id));
                });

                await _freeSql.Insert <LinGroupPermission>()
                .WithTransaction(transaction)
                .AppendData(linPermissions)
                .ExecuteAffrowsAsync();

                await transaction.CommitAsync();
            }
            catch
            {
                await transaction.RollbackAsync();

                throw;
            }
        }
コード例 #14
0
ファイル: Session.cs プロジェクト: Skrypt/yessql
 private async Task CommitOrRollbackTransactionAsync()
 {
     try
     {
         if (!_cancel)
         {
             if (_transaction != null)
             {
                 await _transaction.CommitAsync();
             }
         }
         else
         {
             if (_transaction != null)
             {
                 await _transaction.RollbackAsync();
             }
         }
     }
     finally
     {
         await ReleaseConnectionAsync();
     }
 }
コード例 #15
0
        public async Task CommitAsync(CancellationToken cancellationToken)
        {
            ThrowIfTransactionNull();

            try
            {
                await transaction.CommitAsync(cancellationToken);
            }
            finally
            {
                try
                {
                    transaction.Dispose();
                }
#pragma warning disable S2486 // Generic exceptions should not be ignored
                catch (Exception)
                {
                    // todo log
                }
#pragma warning restore S2486 // Generic exceptions should not be ignored

                transaction = null;
            }
        }
コード例 #16
0
ファイル: UnitOfWork.cs プロジェクト: xiangzi-lucky/OSharp
        /// <summary>
        /// 异步提交当前上下文的事务更改
        /// </summary>
        /// <returns></returns>
        public async Task CommitAsync()
        {
            if (HasCommitted || _dbContexts.Count == 0 || _transaction == null)
            {
                return;
            }

            await _transaction.CommitAsync();

            _logger.LogDebug($"提交事务,事务标识:{_transaction.GetHashCode()}");
            foreach (DbContextBase context in _dbContexts)
            {
                if (context.IsRelationalTransaction())
                {
                    context.Database.CurrentTransaction.Dispose();
                    //关系型数据库共享事务
                    continue;
                }

                await context.Database.CommitTransactionAsync();
            }

            HasCommitted = true;
        }
コード例 #17
0
        /// <summary>
        /// 异步提交事务
        /// </summary>
        /// <returns></returns>
        public async Task CommitAsync()
        {
            if (!Enabled)
            {
                return;
            }

            if (HasCommitted || _transaction == null)
            {
                return;
            }
            await _transaction.CommitAsync();

            if (_dbContext.IsRelationalTransaction())
            {
                await _dbContext.Database.CurrentTransaction.DisposeAsync();
            }
            else
            {
                _dbContext.Database.CommitTransaction();
            }

            HasCommitted = true;
        }
コード例 #18
0
        /// <summary>
        /// SQL事务处理封装
        /// </summary>
        /// <param name="isOnlyRead">是否是只读</param>
        /// <param name="isInnerTranaction">当不在事务环境中时,是否需要开启事务</param>
        /// <param name="strConn">连接字符串</param>
        /// <param name="callBack">处理回调函数</param>
        public static async Task SqlTransactionWorkAsync(string dbType, bool isOnlyRead, bool isInnerTranaction, string strConn, Func <DbConnection, DbTransaction, Task> callBack, System.Transactions.IsolationLevel innerTransactionIsolationLevel = System.Transactions.IsolationLevel.ReadCommitted)
        {
            if (!_dbConnGenerates.TryGetValue(dbType, out IDBConnGenerate dbConnGenerate))
            {
                throw new Exception($"not found {dbType} in DBTransactionHelper.DBConnGenerates");
            }

            DbConnection  conn        = null;
            DbTransaction transaction = null;

            //如果当前处于事务环境中
            if (DBTransactionScope.InScope())
            {
                //检查是否已经在事务中创建过连接
                if (DBTransactionScope.CurrentConnections.ContainsKey(strConn.ToLower()) && (DBTransactionScope.CurrentConnections[strConn.ToLower()].Connection.State == ConnectionState.Connecting || DBTransactionScope.CurrentConnections[strConn.ToLower()].Connection.State == ConnectionState.Open))
                {
                    conn        = DBTransactionScope.CurrentConnections[strConn.ToLower()].Connection;
                    transaction = await DBTransactionScope.CurrentConnections[strConn.ToLower()].CreateTransactionAsync(async(connection, options) =>
                    {
                        return(await CreateTransactionAsync(dbConnGenerate, connection, options));
                    });

                    await callBack(conn, transaction);
                }
                else
                {
                    //只读连接在事务中的时候需要做隔离,防止提升到分布式事务
                    if (isOnlyRead)
                    {
                        //using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress, TransactionScopeAsyncFlowOption.Enabled))
                        //{
                        await using (conn = dbConnGenerate.Generate(strConn))
                        {
                            await conn.OpenAsync();

                            //判断IsolationLevel是否是ReadUncommitted,如果是,则需要单独创建事务
                            if (DBTransactionScope.CurrentTransactionInfo.TransactionOptions.IsolationLevel == System.Transactions.IsolationLevel.ReadUncommitted)
                            {
                                transaction = await dbConnGenerate.GenerateTransactionAsync(conn, ConvertIsolationLevel(DBTransactionScope.CurrentTransactionInfo.TransactionOptions.IsolationLevel));
                            }
                            else
                            {
                                transaction = null;
                            }
                            await callBack(conn, transaction);

                            if (transaction != null)
                            {
                                await transaction.CommitAsync();
                            }
                            await conn.CloseAsync();
                        }

                        //    transactionScope.Complete();
                        //}
                    }
                    else
                    {
                        //如果是写连接,需要加入到事务连接列表中
                        conn = dbConnGenerate.Generate(strConn);
                        await conn.OpenAsync();

                        DBTransactionScope.CurrentConnections[strConn.ToLower()] = new DBTransactionScope.DBConnectionContainer()
                        {
                            Connection = conn, Error = true
                        };
                        transaction = await DBTransactionScope.CurrentConnections[strConn.ToLower()].CreateTransactionAsync(async(connection, options) =>
                        {
                            return(await CreateTransactionAsync(dbConnGenerate, connection, options));
                        });

                        await callBack(conn, transaction);
                    }
                }
            }
            else
            {
                //不在事务中,需要创建连接,由isInnerTranaction确定是否需要创建事务
                if (isInnerTranaction)
                {
                    //using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
                    //{
                    await using (conn = dbConnGenerate.Generate(strConn))
                    {
                        await conn.OpenAsync();

                        transaction = await dbConnGenerate.GenerateTransactionAsync(conn, ConvertIsolationLevel(innerTransactionIsolationLevel));
                        await callBack(conn, transaction);

                        await transaction.CommitAsync();

                        await conn.CloseAsync();
                    }

                    //    transactionScope.Complete();
                    //}
                }
                else
                {
                    await using (conn = dbConnGenerate.Generate(strConn))
                    {
                        await conn.OpenAsync();
                        await callBack(conn, null);

                        await conn.CloseAsync();
                    }
                }
            }
        }
コード例 #19
0
        public async Task CommitAsync(CancellationToken cancellationToken = default)
        {
            await _dbContextTransaction?.CommitAsync(cancellationToken);

            await _dbTransaction?.CommitAsync(cancellationToken);
        }
コード例 #20
0
 public Task CommitAsync(CancellationToken cancellationToken = default)
 {
     return(_transaction.CommitAsync(cancellationToken));
 }
コード例 #21
0
 public async Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     await _transaction.CommitAsync(cancellationToken);
 }
コード例 #22
0
        /// <summary>
        /// Closes the database connection
        /// </summary>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public async Task DisconnectAsync()
        {
            await _dbTransaction.CommitAsync();

            await _dbConnection.CloseAsync();
        }