/// <summary> /// 지정된 함수를 Transaction하에서 실행한다. /// 일반적인 DB 처리 로직을 Transaction 환경하에서 실행될 수 있도록 한다. /// </summary> /// <param name="connectionStringName">Database connection string name</param> /// <param name="isolationLevel">격리 수준</param> /// <param name="actionToExecute">실행할 Action</param> public static void Transaction(string connectionStringName, IsolationLevel isolationLevel, Action <IDbCommand> actionToExecute) { connectionStringName.ShouldNotBeWhiteSpace("connectionStringName"); actionToExecute.ShouldNotBeNull("actionToExecute"); if (IsDebugEnabled) { log.Debug("Execute the specified action under transaction with dbName=[{0}], isolationLevel=[{1}]", connectionStringName, isolationLevel); } StartTransaction(connectionStringName, isolationLevel); try { using (var cmd = ActiveConnection.CreateCommand()) { cmd.Transaction = ActiveTransaction; actionToExecute(cmd); } CommitTransaction(); } catch (Exception ex) { if (log.IsErrorEnabled) { log.Error("Transaction 하에서 actionToExecute를 실행하는데 실패했습니다."); log.Error(ex); } RolebackTransaction(); throw; } finally { DisposeTransaction(); } }
/// <summary> /// called every time new data is inserted /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Root_Updated(object sender, NotificationEventArgs e) { if (_stopUpdates) { return; } if (e.ConfObject is ActiveConnection) {//filter active Connections ActiveConnection con = e.ConfObject as ActiveConnection; if (con.Status != ConnectionStatus.Connected) { return;//count only the connected connections } if (con.DN is Queue) { if (!_queueConnDict.ContainsKey(con.CallID)) { _queueConnDict[con.CallID] = con; this.BeginInvoke(new UpdateConnectDlg(UpdateCallsInQueue), new object[] { _queueConnDict.Count }); } } else if (!_activeConnDict.ContainsKey(con.CallID)) { _activeConnDict[con.CallID] = con; this.BeginInvoke(new UpdateConnectDlg(UpdateActiveConns), new object[] { _activeConnDict.Count }); } } }
/// <summary> /// Opens an AMQP link for use with producer operations. /// </summary> /// <param name="entityPath"></param> /// <param name="viaEntityPath">The entity path to route the message through. Useful when using transactions.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use with producer operations.</returns> /// public virtual async Task <SendingAmqpLink> OpenSenderLinkAsync( string entityPath, string viaEntityPath, TimeSpan timeout, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var stopWatch = Stopwatch.StartNew(); AmqpConnection connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); SendingAmqpLink link = await CreateSendingLinkAsync( entityPath, viaEntityPath, connection, timeout.CalculateRemaining(stopWatch.Elapsed), cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); await OpenAmqpObjectAsync(link, timeout.CalculateRemaining(stopWatch.Elapsed)).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); stopWatch.Stop(); return(link); }
private void StartReading() { Task.Run(async() => { var connectionId = ConnectionId; try { var reader = new StreamReader(ActiveConnection.GetStream()); while (IsOnline && connectionId == ConnectionId) { var message = await reader.ReadLineAsync(); if (message == null) { break; } Logger.Trace($">> {message}"); if (!ClientReadProxy.ProcessRequest(message).Invoked) { await ServerReceivedInvalidMessageAsync(InvalidMessage.For(message)).CastToTask(); } } } catch (Exception exception) { Logger.Warn($"[READ] Disconnected. Reason: {exception.Message}"); await OnTcpClientDisconnected(connectionId); } }); }
/// <summary> /// Disconnects the active connection when ReuseSingleConnection is enabled. /// </summary> public void Disconnect() { if (ReuseSingleConnection) { ActiveConnection.Close(); } }
public void SyncComplete(bool success) { if (success) { using (SqliteTransaction tran = ActiveConnection.BeginTransaction()) { try { CreateSchema(); foreach (string tableName in _tablesByIdx) { if (tableName.StartsWith("_Catalog_") || tableName.StartsWith("_Document_")) { Exec(string.Format("UPDATE {0} SET IsDirty = 0 WHERE IsDirty = 1", tableName), cmd => { cmd.Transaction = tran; cmd.ExecuteNonQuery(); }); } } Cache.ClearNew(); tran.Commit(); } catch { tran.Rollback(); throw; } } } UpdateDbStatus(_userId, success); }
private void StartWriting() { Task.Run(async() => { var connectionId = ConnectionId; try { var writer = new StreamWriter(ActiveConnection.GetStream()) { AutoFlush = true }; while (IsOnline && connectionId == ConnectionId) { while (!WriteQueue.IsEmpty) { string message; if (!WriteQueue.TryDequeue(out message)) { continue; } Logger.Debug($"<< {message}"); await writer.WriteLineAsync(message); } await Task.Delay(10); } } catch (Exception exception) { Logger.Warn($"[WRITE] Disconnected. Reason: {exception.Message}"); await OnTcpClientDisconnected(connectionId); } }); }
/// <summary> /// Disconnects the active connection when ReuseSingleConnection is enabled. /// </summary> public async Task DisconnectAsync() { if (ReuseSingleConnection) { await ActiveConnection.CloseAsync(); } }
/// <summary> /// Opens an AMQP link for use with management operations. /// </summary> /// <param name="entityPath">The path for the entity.</param> /// <param name="identifier">The identifier for the sender or receiver that is opening a management link.</param> /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use with management operations.</returns> /// /// <remarks> /// The authorization for this link does not require periodic /// refreshing. /// </remarks> /// public virtual async Task <RequestResponseAmqpLink> OpenManagementLinkAsync( string entityPath, string identifier, TimeSpan timeout, CancellationToken cancellationToken) { ServiceBusEventSource.Log.CreateManagementLinkStart(identifier); try { cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var stopWatch = ValueStopwatch.StartNew(); var connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var link = await CreateManagementLinkAsync( entityPath, connection, timeout.CalculateRemaining(stopWatch.GetElapsedTime()), cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); await OpenAmqpObjectAsync(link, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); ServiceBusEventSource.Log.CreateManagementLinkComplete(identifier); return(link); } catch (Exception ex) { ServiceBusEventSource.Log.CreateManagementLinkException(identifier, ex.ToString()); throw; } }
public void SaveAnchor(byte[] anchor) { using (SqliteTransaction tran = ActiveConnection.BeginTransaction()) { try { Exec(string.Format("DELETE FROM {0}", AnchorTable), cmd => { cmd.Transaction = tran; cmd.ExecuteNonQuery(); if (anchor != null) { string data = Convert.ToBase64String(anchor); cmd.CommandText = String.Format("INSERT INTO {0}([Data]) VALUES(@Data)", AnchorTable); cmd.Parameters.AddWithValue("@Data", data); cmd.ExecuteNonQuery(); } }); tran.Commit(); } catch { tran.Rollback(); throw; } } }
/// <summary> /// Opens an AMQP link for use with management operations. /// </summary> /// <param name="entityPath"></param> /// /// <param name="timeout">The timeout to apply when creating the link.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>A link for use with management operations.</returns> /// /// <remarks> /// The authorization for this link does not require periodic /// refreshing. /// </remarks> /// public virtual async Task <RequestResponseAmqpLink> OpenManagementLinkAsync( string entityPath, TimeSpan timeout, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var stopWatch = ValueStopwatch.StartNew(); var connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var link = await CreateManagementLinkAsync( entityPath, connection, timeout.CalculateRemaining(stopWatch.GetElapsedTime()), cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); await OpenAmqpObjectAsync(link, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); return(link); }
public void Run(params string[] args) { //in sample, we take first available connection of the specified extension. ActiveConnection ac = PhoneSystem.Root.GetDNByNumber(args[2]).GetActiveConnections()[0]; PhoneSystem.Root.BargeinCall(args[1], ac, PBXConnection.BargeInMode.BargeIn); }
/// <summary> /// Disconnects this instance. /// </summary> public void Disconnect( ) { lock ( _syncRoot ) { if (ActiveConnection != null) { string host = null; if (ActiveConnection.Configuration != null) { ConfigurationOptions configurationOptions = ConfigurationOptions.Parse(ActiveConnection.Configuration); if (configurationOptions.EndPoints != null && configurationOptions.EndPoints.Count > 0) { host = GetEndPointHost(configurationOptions.EndPoints[0]); } } ActiveConnection.Close( ); ActiveConnection.Dispose( ); ActiveConnection = null; EventLog.Application.WriteInformation("Connection to Redis server{0} closed.", string.IsNullOrEmpty(host) ? string.Empty : string.Format(" ('{0}')", host)); } } }
private async Task <Controller> CreateControllerAsync(TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout, true); AmqpConnection connection = await ActiveConnection.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; AmqpSession amqpSession = null; Controller controller; try { amqpSession = connection.CreateSession(sessionSettings); await amqpSession.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); controller = new Controller(amqpSession, timeoutHelper.RemainingTime()); await controller.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } catch (Exception exception) { if (amqpSession != null) { await amqpSession.CloseAsync(timeout).ConfigureAwait(false); } MessagingEventSource.Log.AmqpCreateControllerException(ActiveConnection.ToString(), exception); throw; } return(controller); }
private void CreateSchema() { if (_idxByTable == null) { System.Data.DataTable tbl = ActiveConnection.GetSchema(SqliteMetaDataCollectionNames.Tables); if (tbl.Rows.Count == 0) { return; } _tablesByIdx = new string[tbl.Rows.Count]; int idx = 0; foreach (System.Data.DataRow row in tbl.Rows) { _tablesByIdx[idx] = row[2].ToString(); idx++; } Array.Sort(_tablesByIdx); _idxByTable = new Dictionary <string, int>(); idx = 0; foreach (String s in _tablesByIdx) { _idxByTable.Add(s, idx); idx++; } } }
private async Task <Controller> CreateControllerAsync(TimeSpan timeout) { var stopWatch = ValueStopwatch.StartNew(); AmqpConnection connection = await ActiveConnection.GetOrCreateAsync(timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false); var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; AmqpSession amqpSession = null; Controller controller; try { amqpSession = connection.CreateSession(sessionSettings); await amqpSession.OpenAsync(timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false); controller = new Controller(amqpSession, timeout.CalculateRemaining(stopWatch.GetElapsedTime())); await controller.OpenAsync(timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false); } catch (Exception exception) { if (amqpSession != null) { await amqpSession.CloseAsync(timeout).ConfigureAwait(false); } ServiceBusEventSource.Log.CreateControllerException(ActiveConnection.ToString(), exception.ToString()); throw; } return(controller); }
public void CommitTransaction() { var lst = new List <string>(); using (var cmd = new SqliteCommand(String.Format("SELECT DISTINCT [TableName] FROM {0}", TranStatusTable), ActiveConnection)) { using (SqliteDataReader r = cmd.ExecuteReader()) { while (r.Read()) { lst.Add(r.GetString(0)); } } } SqliteTransaction tran = ActiveConnection.BeginTransaction(); try { foreach (String tableName in lst) { using (var cmd = new SqliteCommand(String.Format("DELETE FROM __{0}", tableName), tran.Connection, tran)) cmd.ExecuteNonQuery(); } using (var cmd = new SqliteCommand(String.Format("DELETE FROM {0}", TranStatusTable), tran.Connection, tran)) cmd.ExecuteNonQuery(); tran.Commit(); } catch { tran.Rollback(); throw; } }
public virtual void Connect() { Close(); ActiveConnection = (DbConnection)Activator.CreateInstance(this.getDatabaseType()); ActiveConnection.ConnectionString = this.getConnectionString(); ActiveConnection.Open(); }
private static void DisposeTransaction() { if (TransactionCounter <= 0) { ActiveConnection.Dispose(); ActiveConnection = null; } }
public void Run(params string[] args) { PBXConnection pbx = Utilities.CreatePbxConn(); //in sample, we take first available connection of the specified extension and then whisper to it. ActiveConnection ac = PhoneSystem.Root.GetDNByNumber(args[2]).GetActiveConnections()[0]; pbx.BargeinCall(args[1], ac, PBXConnection.BargeInMode.Whisper); }
public virtual void Close() { if (ActiveConnection != null && ActiveConnection.State == System.Data.ConnectionState.Open) { ActiveConnection.Close(); } }
public bool Equals(ActiveConnection that) { return(this.Protocol == that.Protocol && this.LocalAddress == that.LocalAddress && this.LocalPort == that.LocalPort && this.ForeignAddress == that.ForeignAddress && this.ForeignPort == that.ForeignPort && this.State == that.State); }
private void Send(Request request) { /* * byte[] encodeable = Encoding.ASCII.GetBytes(request.ToString()); * * ActiveConnection.Send(Encoder.Encode(encodeable, encodeable.Length)); */ ActiveConnection.Send(Encoding.ASCII.GetBytes(request.ToString())); }
/// <summary> /// Disposes of this instance, closing the session with the Target. /// </summary> public void Dispose() { if (ActiveConnection != null) { ActiveConnection.Close(LogoutReason.CloseSession); } ActiveConnection = null; }
/// <summary> /// Starts the transaction. /// </summary> /// <param name="name">The name.</param> /// <param name="isolation">The isolation.</param> private static void StartTransaction(string name, IsolationLevel isolation) { if (TransactionCounter <= 0) { TransactionCounter = 0; ActiveConnection = Connection(name); ActiveTransaction = ActiveConnection.BeginTransaction(isolation); } TransactionCounter++; }
public override bool Equals(object obj) { ActiveConnection ac = obj as ActiveConnection; if (null == ac) { return(false); } return(Equals(ac)); }
protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { ActiveConnection?.Dispose(); } } _disposed = true; }
private void pollStatusReport() { if (statusQueryTimeout.Expired(statusQueryInterval) && pendingStatusQueryRequest == null) { GrblRequest request = GrblRequest.CreateStatusQueryRequest(); if (ActiveConnection.Send(request)) { statusQueryTimeout.Reset(); pendingStatusQueryRequest = request; } } }
/// <summary> /// Send to DB query to compute. /// </summary> /// <param name="expression">The query to compute</param> /// <returns>The value computed</returns> protected object ComputeValue(string expression) { object result; using (DbCommand cmd = ActiveConnection.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select " + expression; cmd.Transaction = TransactionManager.GetTransaction(ActiveConnection); result = cmd.ExecuteScalar(); } return(result); }
/// <summary> /// Performs the task needed to clean up resources used by the <see cref="AmqpConnectionScope" />, /// including ensuring that the client itself has been closed. /// </summary> /// public override void Dispose() { if (IsDisposed) { return; } ActiveConnection?.Dispose(); OperationCancellationSource.Cancel(); OperationCancellationSource.Dispose(); IsDisposed = true; }
public SendMessage(ActiveConnection.Base.ISelect selectActiveConnection) { this._selectActiveConnection = selectActiveConnection; this._hub = GlobalHost.ConnectionManager.GetHubContext<BusinessLogic.AppServices.Hubs.ArmedCards>(); }
public bool Equals(ActiveConnection that) { return this.Protocol == that.Protocol && this.LocalAddress == that.LocalAddress && this.LocalPort == that.LocalPort && this.ForeignAddress == that.ForeignAddress && this.ForeignPort == that.ForeignPort && this.State == that.State; }
public static ActiveConnection[] GetActiveConnections() { List<ActiveConnection> results = new List<ActiveConnection>(); string[] lines = Exec.Shell("netstat -n").Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); char[] sp = new char[] { ' ', '\t' }; bool StartedActiveConnections = false; bool StartedProtoHeader = false; foreach (string line in lines) { if (!StartedActiveConnections) { if (line.StartsWith("Active Connections")) { StartedActiveConnections = true; } } else if (!StartedProtoHeader) { string tline = line.Trim(); if (tline.StartsWith("Proto")) { StartedProtoHeader = true; } } else { if (0 == line.Length || (' ' != line[0] && '\t' != line[0])) { break; } string[] parts = line.Split(sp, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 4) { break; } ActiveConnection ac = new ActiveConnection(); ac.Protocol = parts[0]; GetAddressParts(parts[1], out ac.LocalAddress, out ac.LocalPort); GetAddressParts(parts[2], out ac.ForeignAddress, out ac.ForeignPort); ac.State = parts[3]; results.Add(ac); } } return results.ToArray(); }