public bool Connect(string connectionString, CommandType commandType, string commandText) { _connection = (OdbcConnection)_factory.CreateConnection(connectionString); VerifyArgument.IsNotNull("commandText", commandText); return(ReturnConnection(commandType, commandText)); }
public ProductTypeDto CreateOrUpdateProductType(ProductTypeDto dto, int RequestUserId, string TokenKey) { try { CheckAuthentication(RequestUserId, TokenKey); #region Empty Control if (dto.Name.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Name")); } #endregion var data = GetAllCachedData <ProductTypeEntity>().ToList(); #region Field Control if (data != null) { if (data.Any(q => q.Name == dto.Name)) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.IsInUse, ExceptionMessageHelper.IsInUse("Name")); } } #endregion var entity = dto.ConvertTo <ProductTypeEntity>(); var conn = Db.CreateConnection(true); if (dto.Id > 0) { entity.UpdateUser = RequestUserId; entity.UpdateDate = DateTimeHelper.Now; conn.Update(entity, Db._DbTransaction); data.RemoveAt(data.FindIndex(q => q.Id == entity.Id)); } else { int Id = conn.Insert(entity, Db._DbTransaction).ToInt(); entity = conn.Get <ProductTypeEntity>(Id); } data.Add(entity); FillCacheData(data); return(entity.ConvertTo <ProductTypeDto>()); } catch (KnownException ex) { throw ex; } catch (Exception ex) { Logger.AddLog(LogTypeEnum.Error, "ProductManager.CreateOrUpdateProductType", RequestUserId, ex.Message, dto.ToJson(), ex); throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex); } }
public void Connect(string connectionString) { if (connectionString.Contains("Database")) { connectionString = connectionString.Replace(connectionString.Substring(connectionString.IndexOf("Database", StringComparison.Ordinal)), ""); } _connection = (OracleConnection)_factory.CreateConnection(connectionString); if (!_isTesting) { _connection.Open(); } }
public void AddConnectionIfNeeded(IConnectionInformation connection) { var fileName = _getFileNameFromConnection.GetFileName(connection.ConnectionString); if (!fileName.IsInMemory) { return; } if (_connections.ContainsKey(connection.ConnectionString)) { return; } var sqlConnection = _dbFactory.CreateConnection(connection.ConnectionString, true); try { sqlConnection.Open(); } catch (Exception) //resource leak possible on open { sqlConnection.Dispose(); throw; } if (!_connections.TryAdd(connection.ConnectionString, sqlConnection)) { //already added by another thread sqlConnection.Dispose(); } }
public DbContext(IDbFactory factory) { DbFactory = factory; Connection = DbFactory.CreateConnection(); Command = Connection.CreateCommand(); Connection.Open(); }
/// <summary> /// 创建连接 /// </summary> /// <returns></returns> private bool CreateConnection() { _dbConn = _dbFactory.CreateConnection(); _dbConn.ConnectionString = _DBConnectionString; return(true); }
/// <summary> /// Handles the specified query. /// </summary> /// <param name="query">The query.</param> /// <returns></returns> public IReceivedMessageInternal Handle(ReceiveMessageQuery <IDbConnection, IDbTransaction> query) { if (!_databaseExists.Exists(_connectionInformation.ConnectionString)) { return(null); } using (var connection = _dbFactory.CreateConnection(_connectionInformation.ConnectionString, false)) { connection.Open(); using (var transaction = _dbFactory.CreateTransaction(connection).BeginTransaction()) { using (var selectCommand = connection.CreateCommand()) { selectCommand.Transaction = transaction; CommandString commandString = GetDeQueueCommand(_tableNameHelper.MetaDataName, _tableNameHelper.QueueName, _tableNameHelper.StatusName, query.Routes); _buildDequeueCommand.BuildCommand(selectCommand, commandString, _options.Value, query.Routes); using (var reader = selectCommand.ExecuteReader()) { return(_messageDeQueue.HandleMessage(connection, transaction, reader, commandString)); } } } } }
private static ConnectionWrapper GetOpenConnection(string connString, IDbFactory factory, bool disposeInnerConnection) { DbConnection connection = TransactionScopeConnections.GetConnection(connString, factory); if (connection != null) { return(new ConnectionWrapper(connection, false)); } else { try { connection = factory.CreateConnection(connString); connection.Open(); } catch { if (connection != null) { connection.Close(); } throw; } return(new ConnectionWrapper(connection, disposeInnerConnection)); } }
/// <summary> /// Handles the specified query. /// </summary> /// <param name="query">The query.</param> /// <returns></returns> /// <exception cref="PoisonMessageException">An error has occured trying to re-assemble a message de-queued from SQLite</exception> /// <exception cref="MessageQueueId"></exception> public async Task <IReceivedMessageInternal> Handle(ReceiveMessageQueryAsync <IDbConnection, IDbTransaction> query) { if (!_databaseExists.Exists(_connectionInformation.ConnectionString)) { return(null); } using (var connection = _dbFactory.CreateConnection(_connectionInformation.ConnectionString, false)) { connection.Open(); using (var transaction = _dbFactory.CreateTransaction(connection).BeginTransaction()) { using (var selectCommand = connection.CreateCommand()) { selectCommand.Transaction = transaction; CommandString commandString = GetDeQueueCommand(_tableNameHelper.MetaDataName, _tableNameHelper.QueueName, _tableNameHelper.StatusName, query.Routes); if (commandString == null) { throw new DotNetWorkQueueException("Failed to generate command text for de-queue of messages"); } _buildDequeueCommand.BuildCommand(selectCommand, commandString, _options.Value, query.Routes); using (var reader = await _readerAsync.ExecuteReaderAsync(selectCommand).ConfigureAwait(false)) { return(_messageDeQueue.HandleMessage(connection, transaction, reader, commandString)); } } } } }
/// <summary> /// Initializes a new instance of the <see cref="DbStoreBase"/> class. /// </summary> /// <param name="factory">Factory to create the inner <see cref="IDbConnection"/> object.</param> protected DbStoreBase(IDbFactory factory) { _connection = new Lazy <IDbConnection>( () => { var db = factory.CreateConnection(); db.Open(); return(db); }, true); }
private static SqlServerProcessor CreateProcessor( IDbFactory connectionFactory, IAnnouncer announcer, IMigrationProcessorOptions options) { return(new SqlServerProcessor( connectionFactory.CreateConnection(null), new SqlServer2000Generator(), announcer, options, connectionFactory)); }
/// <summary> /// Returns a connection for the current transaction. This will be an existing <see cref="DbConnection"/> /// instance or a new one if there is a <see cref="TransactionScope"/> active. Otherwise this method /// returns null. /// </summary> /// <param name="db"></param> /// <returns>Either a <see cref="DbConnection"/> instance or null.</returns> public static DbConnection GetConnection(string connStr, IDbFactory dbFactory) { Transaction currentTransaction = Transaction.Current; if (currentTransaction == null) { return(null); } if (s_Dictionary == null) { s_Dictionary = GetTransactionConnectionDictionary(); } Dictionary <string, DbConnection> connectionList; s_Dictionary.TryGetValue(currentTransaction, out connectionList); DbConnection connection; if (connectionList != null) { connectionList.TryGetValue(connStr, out connection); if (connection != null) { return(connection); } } else { // We don't have a list for this transaction, so create a new one connectionList = new Dictionary <string, DbConnection>(); s_Dictionary.Add(currentTransaction, connectionList); } // // Next we'll see if there is already a connection. If not, we'll create a new connection and add it // to the transaction's list of connections. // if (connectionList.ContainsKey(connStr)) { connection = connectionList[connStr]; } else { connection = dbFactory.CreateConnection(connStr); connection.Open(); currentTransaction.TransactionCompleted += new TransactionCompletedEventHandler(OnTransactionCompleted); connectionList.Add(connStr, connection); } return(connection); }
/// <summary> /// Returns a connection for the current transaction. This will be an existing <see cref="DbConnection"/> /// instance or a new one if there is a <see cref="TransactionScope"/> active. Otherwise this method /// returns null. /// </summary> /// <param name="db"></param> /// <returns>Either a <see cref="DbConnection"/> instance or null.</returns> public static DbConnection GetConnection(string connectionString, IDbFactory dbFactory) { Transaction currentTransaction = Transaction.Current; if (currentTransaction == null) { return null; } Dictionary<string, DbConnection> connectionList; transactionConnections.TryGetValue(currentTransaction, out connectionList); DbConnection connection; if (connectionList != null) { connectionList.TryGetValue(connectionString, out connection); if (connection != null) { return connection; } } else { // We don't have a list for this transaction, so create a new one connectionList = new Dictionary<string, DbConnection>(); lock (transactionConnections) { transactionConnections.Add(currentTransaction, connectionList); } } // // Next we'll see if there is already a connection. If not, we'll create a new connection and add it // to the transaction's list of connections. // if (connectionList.ContainsKey(connectionString)) { connection = connectionList[connectionString]; } else { connection = dbFactory.CreateConnection(connectionString); connection.Open(); currentTransaction.TransactionCompleted += new TransactionCompletedEventHandler(OnTransactionCompleted); connectionList.Add(connectionString, connection); } return connection; }
public void CallingProcessWithPerformDBOperationExpressionWhenInPreviewOnlyModeWillNotMakeDbChanges() { var output = new StringWriter(); var connection = _dbFactory.CreateConnection(IntegrationTestOptions.SqlLite.ConnectionString); var processor = new SQLiteProcessor( connection, new SQLiteGenerator(), new TextWriterAnnouncer(output), new ProcessorOptions { PreviewOnly = true }, new SQLiteDbFactory()); bool tableExists; try { var expression = new PerformDBOperationExpression { Operation = (con, trans) => { var command = con.CreateCommand(); command.CommandText = "CREATE TABLE ProcessTestTable (test int NULL) "; command.Transaction = trans; command.ExecuteNonQuery(); } }; processor.Process(expression); tableExists = processor.TableExists("", "ProcessTestTable"); } finally { processor.RollbackTransaction(); } tableExists.ShouldBeFalse(); Assert.That(output.ToString(), Does.Contain(@"/* Performing DB Operation */")); }
private DbConnectionWrap CreateConnectionWrap(bool isNew) { DbConnectionWrap wrapConn; //在TransScope范围中共用一个数据库连接对象 if (_TransScopeConnections.Value != null && _TransScopeConnections.Value.Count > 0 && !isNew) { wrapConn = _TransScopeConnections.Value.Peek(); LogDebug("Get a exist connection from TransScope. DbConnectionWrap.Guid={0}", wrapConn.Guid); } else { var conn = _DbFactory.CreateConnection(); wrapConn = new DbConnectionWrap(conn, LoggerFactory); LogDebug("Create new connection. DbConnectionWrap.Guid={0}", wrapConn.Guid); } return(wrapConn); }
public void SetUp() { // This connection used in the tests _dbFactory = new SQLiteDbFactory(); _connection = _dbFactory.CreateConnection(IntegrationTestOptions.SqlLite.ConnectionString); _connection.Open(); _command = _connection.CreateCommand(); // SUT _processor = new SQLiteProcessor(_connection, new SQLiteGenerator(), new TextWriterAnnouncer(TestContext.Out), new ProcessorOptions(), _dbFactory); column = new Mock <ColumnDefinition>(); tableName = "NewTable"; tableNameThanMustBeEscaped = "123NewTable"; columnName = "ColumnName"; column.SetupGet(c => c.Name).Returns(columnName); column.SetupGet(c => c.IsNullable).Returns(true); column.SetupGet(c => c.Type).Returns(DbType.Int32); }
public void Handle(RollbackMessageCommand <long> rollBackCommand) { if (!_databaseExists.Exists(_connectionInformation.ConnectionString)) { return; } SetupSql(); using (var connection = _dbFactory.CreateConnection(_connectionInformation.ConnectionString, false)) { connection.Open(); using (var trans = _dbFactory.CreateTransaction(connection).BeginTransaction()) { using (var command = connection.CreateCommand()) { command.Transaction = trans; var param = command.CreateParameter(); param.ParameterName = "@QueueID"; param.DbType = DbType.Int64; param.Value = rollBackCommand.QueueId; command.Parameters.Add(param); if (_options.Value.EnableDelayedProcessing && rollBackCommand.IncreaseQueueDelay.HasValue) { if (rollBackCommand.LastHeartBeat.HasValue) { command.CommandText = GetRollbackSql(false, true); param = command.CreateParameter(); param.ParameterName = "@HeartBeat"; param.DbType = DbType.DateTime2; param.Value = rollBackCommand.LastHeartBeat.Value.Ticks; command.Parameters.Add(param); } else { command.CommandText = GetRollbackSql(true, false); } var dtUtcDate = _getUtcDateQuery.Create().GetCurrentUtcDate(); var dtUtcDateIncreased = dtUtcDate.Add(rollBackCommand.IncreaseQueueDelay.Value); param = command.CreateParameter(); param.ParameterName = "@QueueProcessTime"; param.DbType = DbType.DateTime2; param.Value = dtUtcDateIncreased.Ticks; command.Parameters.Add(param); } else { if (rollBackCommand.LastHeartBeat.HasValue) { command.CommandText = GetRollbackSql(false, true); param = command.CreateParameter(); param.ParameterName = "@HeartBeat"; param.DbType = DbType.DateTime2; param.Value = rollBackCommand.LastHeartBeat.Value.Ticks; command.Parameters.Add(param); } else { command.CommandText = GetRollbackSql(false, false); } } command.ExecuteNonQuery(); } if (_options.Value.EnableStatusTable) { using (var command = connection.CreateCommand()) { command.Transaction = trans; var param = command.CreateParameter(); param.ParameterName = "@QueueID"; param.DbType = DbType.Int64; param.Value = rollBackCommand.QueueId; command.Parameters.Add(param); param = command.CreateParameter(); param.ParameterName = "@Status"; param.DbType = DbType.Int32; param.Value = Convert.ToInt16(QueueStatuses.Waiting); command.Parameters.Add(param); command.CommandText = _commandCache.GetCommand(CommandStringTypes.UpdateStatusRecord); command.ExecuteNonQuery(); } } trans.Commit(); } } }
/// <summary> /// Creates a new connection to the database /// </summary> /// <returns></returns> public IDbConnection Create() { return(_dbFactory.CreateConnection(_connectionInformation.ConnectionString, false)); }
/// <summary> /// Handles the specified command. /// </summary> /// <param name="commandSend">The command.</param> /// <returns></returns> /// <exception cref="DotNetWorkQueueException">Failed to insert record - the ID of the new record returned by SQLite was 0</exception> public long Handle(SendMessageCommand commandSend) { if (!_databaseExists.Exists(_configurationSend.ConnectionInfo.ConnectionString)) { return(0); } if (!_messageExpirationEnabled.HasValue) { _messageExpirationEnabled = _options.Value.EnableMessageExpiration || _options.Value.QueueType == QueueTypes.RpcReceive || _options.Value.QueueType == QueueTypes.RpcSend; } using (var connection = _dbFactory.CreateConnection(_configurationSend.ConnectionInfo.ConnectionString, false)) { connection.Open(); var expiration = TimeSpan.Zero; if (_messageExpirationEnabled.Value) { expiration = MessageExpiration.GetExpiration(commandSend, _headers, data => data.GetExpiration()); } var jobName = _jobSchedulerMetaData.GetJobName(commandSend.MessageData); var scheduledTime = DateTimeOffset.MinValue; var eventTime = DateTimeOffset.MinValue; if (!string.IsNullOrWhiteSpace(jobName)) { scheduledTime = _jobSchedulerMetaData.GetScheduledTime(commandSend.MessageData); eventTime = _jobSchedulerMetaData.GetEventTime(commandSend.MessageData); } IDbCommand commandStatus = null; using (var command = SendMessage.GetMainCommand(commandSend, connection, _commandCache, _headers, _serializer)) { long id; using (var commandMeta = SendMessage.CreateMetaDataRecord(commandSend.MessageData.GetDelay(), expiration, connection, commandSend.MessageToSend, commandSend.MessageData, _tableNameHelper, _headers, _options.Value, _getTime)) { if (_options.Value.EnableStatusTable) { commandStatus = CreateStatusRecord(connection, commandSend.MessageToSend, commandSend.MessageData); } using (var trans = _dbFactory.CreateTransaction(connection).BeginTransaction()) { try { if (string.IsNullOrWhiteSpace(jobName) || _jobExistsHandler.Handle(new DoesJobExistQuery <IDbConnection, IDbTransaction>(jobName, scheduledTime, connection, trans)) == QueueStatuses.NotQueued) { command.Transaction = trans; command.ExecuteNonQuery(); var commandId = connection.CreateCommand(); commandId.Transaction = trans; commandId.CommandText = "SELECT last_insert_rowid();"; id = Convert.ToInt64(commandId.ExecuteScalar()); if (id > 0) { commandMeta.Transaction = trans; var param = commandMeta.CreateParameter(); param.ParameterName = "@QueueID"; param.DbType = DbType.Int64; param.Value = id; commandMeta.Parameters.Add(param); commandMeta.ExecuteNonQuery(); if (commandStatus != null) { commandStatus.Transaction = trans; param = commandStatus.CreateParameter(); param.ParameterName = "@QueueID"; param.DbType = DbType.Int64; param.Value = id; commandStatus.Parameters.Add(param); commandStatus.ExecuteNonQuery(); } if (!string.IsNullOrWhiteSpace(jobName)) { _sendJobStatus.Handle(new SetJobLastKnownEventCommand <IDbConnection, IDbTransaction>(jobName, eventTime, scheduledTime, connection, trans)); } trans.Commit(); } else { throw new DotNetWorkQueueException( "Failed to insert record - the ID of the new record returned by SQLite was 0"); } } else { throw new DotNetWorkQueueException( "Failed to insert record - the job has already been queued or processed"); } } finally { commandStatus?.Dispose(); } } } return(id); } } }
// Use for sql updates public int Update(string sql, CommandType commandType) { IDbConnection connection = factory.CreateConnection(); try { connection.ConnectionString = connectionString; IDbCommand command = factory.CreateCommand(); command.Connection = connection; command.CommandType = commandType; command.CommandText = sql; connection.Open(); int rowsAffected = command.ExecuteNonQuery(); return(rowsAffected); } catch (Exception ex) { log.Fatal(ex); return(0); } finally { connection.Close(); connection.Dispose(); } }
public void Connect(string connectionString) { _connection = (NpgsqlConnection)_factory.CreateConnection(connectionString); _connection.Open(); }
public bool Connect(string connectionString) { _connection = (MySqlConnection)_factory.CreateConnection(connectionString); _connection.Open(); return(true); }
private static ConnectionWrapper <DbConnection> GetOpenConnection(string connectionString, IDbFactory factory, bool disposeInnerConnection) { return(TransactionScopeConnections.GetOpenConnection(connectionString, () => factory.CreateConnection(), disposeInnerConnection)); }
public Transaction Transaction; // used to keep track of transaction participation. #endregion Fields #region Constructors // to restore lock timeout on ConnectionScope.Dispose(). public Context(IDbFactory factory, string connectionString) { this.Factory = factory; this.Connection = Factory.CreateConnection(); this.Connection.ConnectionString = connectionString; }
public SqliteServer(string connectionString) { _factory = new SqliteServerFactory(); _connection = (SQLiteConnection)_factory.CreateConnection(connectionString); _connection.Open(); }
private static ConnectionWrapper<DbConnection> GetOpenConnection(string connectionString, IDbFactory factory, bool disposeInnerConnection) { return TransactionScopeConnections.GetOpenConnection(connectionString, () => factory.CreateConnection(), disposeInnerConnection); }
public CustomerDto CreateOrUpdateCustomer(CustomerDto dto, int RequestUserId, string TokenKey) { try { CheckAuthentication(RequestUserId, TokenKey); #region Empty Control if (dto.UserName.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("User Name")); } if (dto.Password.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Password")); } if (dto.FullName.IsNullOrEmpty()) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.CannotEmptyField, ExceptionMessageHelper.CannotEmptyField("Full Name")); } #endregion var data = GetAllCachedData <CustomerDto>().ToList(); #region Field Control if (data != null) { if (data.Any(q => q.UserName == dto.UserName)) { throw new RequestWarningException(ErrorTypeEnum.WarningException, ExceptionCodeHelper.IsInUse, ExceptionMessageHelper.IsInUse("UserName")); } } #endregion var entity = dto.ConvertTo <CustomerEntity>(); var Pass = PasswordHelper.GeneratePassword(6); entity.Password = (dto.Id > 0) ? PasswordHelper.EncryptData(dto.Password) : PasswordHelper.EncryptData(Pass); var conn = Db.CreateConnection(true); if (dto.Id > 0) { entity.UpdateUser = RequestUserId; entity.UpdateDate = DateTimeHelper.Now; conn.Update(entity, Db._DbTransaction); data.RemoveAt(data.FindIndex(q => q.Id == entity.Id)); } else { int Id = conn.Insert(entity, Db._DbTransaction).ToInt(); entity = conn.Get <CustomerEntity>(Id); } var result = entity.ConvertTo <CustomerDto>(); data.Add(result); FillCacheData(data); return(result); } catch (KnownException ex) { throw ex; } catch (Exception ex) { Logger.AddLog(LogTypeEnum.Error, "CustomerManager.CreateOrUpdateCustomer", RequestUserId, ex.Message, dto.ToJson(), ex); throw new KnownException(ErrorTypeEnum.UnexpectedExeption, ex.Message, ex); } }
protected IDbConnection CreateConnection() { return(_dbFactory.CreateConnection()); }
protected IDbConnection CreateConnection() => _dbFactory.CreateConnection();