public IDataReader ExecuteDataReader(string procedure, params QueryParameter[] parameters) { var connection = this.GetConnection(); var command = this.GetConnection().CreateStoredProcedureCommand(procedure); command.CommandTimeout = commandTimeout ?? command.CommandTimeout; SetIncomingParameterValues(command, parameters); StateChangeEventHandler stateChangedHandler = null; stateChangedHandler = (_s, _e) => { if (_e.CurrentState == ConnectionState.Closed) { SetOutputParameterValues(command, parameters); connection.StateChange -= stateChangedHandler; } }; connection.StateChange += stateChangedHandler; return(command.OpenConnectionAndExecute(CommandBehavior.CloseConnection)); }
/// <inheritdoc /> public async Task <ApplicationContext> Init() { if (dbContext == null) { dbContext = new ApplicationContext(new DbContextOptions <ApplicationContext>()); } StateChangeEventHandler handler = (sender, e) => { if (e.CurrentState != ConnectionState.Open) { return; } var connection = (SqliteConnection)sender; sqlite3_extended_result_codes(connection.Handle, 0); }; dbContext.Database.GetDbConnection().StateChange += handler; dbContext.Database.OpenConnection(); await dbContext.Database.MigrateAsync(); dbContext.Database.GetDbConnection().StateChange -= handler; return(dbContext); }
public void Dispose_closes_connection() { var connection = new SQLiteConnection("Filename=:memory:"); connection.Open(); var raised = false; StateChangeEventHandler handler = (sender, e) => { raised = true; Assert.Equal(connection, sender); Assert.Equal(ConnectionState.Open, e.OriginalState); Assert.Equal(ConnectionState.Closed, e.CurrentState); }; connection.StateChange += handler; try { connection.Dispose(); Assert.True(raised); Assert.Equal(ConnectionState.Closed, connection.State); } finally { connection.StateChange -= handler; } }
//----------------- public MyAeSubscription(MyAeSession parentSession) : base(parentSession) { PerformStateTransitionCompleted += new PerformStateTransitionEventHandler(HandlePerformObjectStateTransitionCompleted); StateChangeCompleted += new StateChangeEventHandler(HandleStateChangeCompleted); AeEventsReceived += new AeEventsReceivedEventHandler(HandleEventsReceived); AeConditionsChanged += new AeConditionsChangedEventHandler(HandleConditionsChanged); }
/// <summary> /// Initializes a new instance of the <see cref="DbConnectionWrapper"/> class. /// </summary> /// <param name="connection">The connection.</param> public DbConnectionWrapper( DbConnection connection ) { onWrappedStateChange = ( s, e ) => { this.OnStateChange( e ); }; this.WrappedConnection = connection; this.WrappedConnection.StateChange += onWrappedStateChange; }
public void Close_works() { using (var connection = new SqliteConnection("Data Source=:memory:")) { connection.Open(); var raised = false; StateChangeEventHandler handler = (sender, e) => { raised = true; Assert.Equal(connection, sender); Assert.Equal(ConnectionState.Open, e.OriginalState); Assert.Equal(ConnectionState.Closed, e.CurrentState); }; connection.StateChange += handler; try { connection.Close(); Assert.True(raised); Assert.Equal(ConnectionState.Closed, connection.State); } finally { connection.StateChange -= handler; } } }
private SqlConnectionLifetimeTracker(SqlConnection sqlConnection) { this.con = sqlConnection; stateChangeListener = new System.Data.StateChangeEventHandler(con_StateChange); sqlConnection.StateChange += stateChangeListener; responsibleStack = new StackTrace(2); }
//----------------- public MyAeSession(string url) : base(url) { StateChangeCompleted += new StateChangeEventHandler(HandleStateChangeCompleted); PerformStateTransitionCompleted += new PerformStateTransitionEventHandler(HandlePerformObjectStateTransitionCompleted); ShutdownRequest += new ShutdownEventHandler(HandleShutdown); GetServerStatusCompleted += new GetStatusEventHandler(HandleGetStatusCompleted); }
public void AddStateChangeListener(ProcessState targetState, long timeoutInterval, StateChangeEventHandler handler) { lock (SyncRoot) { if (m_currentState >= targetState) { handler(this, new XComputeProcessStateChangeEventArgs(m_id, m_currentState, false)); } else { if (m_stateChangeListeners.ContainsKey(targetState)) { m_stateChangeListeners[targetState] += handler; } else { m_stateChangeListeners.Add(targetState, handler); } if (timeoutInterval != long.MaxValue) { m_stateChangeTimers[handler] = new Timer(this.Timeout, handler, timeoutInterval, 0); } } } }
//----------------- public MyDaSubscription(uint updateRate, MyDaSession parentSession) : base(updateRate, parentSession) { DataChanged += new DataChangedEventHandler(HandleDataChanged); StateChangeCompleted += new StateChangeEventHandler(HandleStateChanged); ReadCompleted += new SubscriptionReadEventHandler(HandleSubscriptionReadCompleted); WriteCompleted += new SubscriptionWriteEventHandler(HandleSubscriptionWriteCompleted); PerformStateTransitionCompleted += new PerformStateTransitionEventHandler(HandlePerformStateTransition); }
/// <summary> /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed. /// <example> /// statechangeeventhandler.BeginInvoke(sender, e, callback); /// </example> /// </summary> public static IAsyncResult BeginInvoke(this StateChangeEventHandler statechangeeventhandler, Object sender, StateChangeEventArgs e, AsyncCallback callback) { if (statechangeeventhandler == null) { throw new ArgumentNullException("statechangeeventhandler"); } return(statechangeeventhandler.BeginInvoke(sender, e, callback, null)); }
//----------------- public MyDaSession(string url) : base(url) { StateChangeCompleted += new StateChangeEventHandler(HandleStateChanged); PerformStateTransitionCompleted += new PerformStateTransitionEventHandler(HandlePerformStateTransition); ShutdownRequest += new ShutdownEventHandler(HandleServerShutdown); ReadCompleted += new SessionReadEventHandler(HandleSessionReadCompleted); WriteCompleted += new SessionWriteEventHandler(HandleSessionWriteCompleted); GetStatusCompleted += new GetStatusEventHandler(HandleGetServerStatus); }
/// <summary> /// Creates a PostgreSQL connection using the 'Npgsql' .NET Data Provider. /// This works on Windows and on Linux. /// </summary> /// <param name="AServer">Database Server.</param> /// <param name="APort">Port that the DB server is running on.</param> /// <param name="ADatabaseName">Name of the database that we want to connect to.</param> /// <param name="AUsername">Username for opening the PostgreSQL connection.</param> /// <param name="APassword">Password for opening the PostgreSQL connection.</param> /// <param name="AConnectionString">Connection string; if it is not empty, it will /// overrule the previous parameters.</param> /// <param name="AStateChangeEventHandler">Event Handler for connection state changes /// (NOTE: This doesn't work yet with the Npgsql driver - see code comments in this Methods' /// source code)!</param> /// <returns> /// Instantiated NpgsqlConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { ArrayList ExceptionList; NpgsqlConnection TheConnection = null; #if EXTREME_DEBUGGING NpgsqlEventLog.Level = LogLevel.Debug; NpgsqlEventLog.LogName = "NpgsqlTests.LogFile"; NpgsqlEventLog.EchoMessages = false; #endif if (String.IsNullOrEmpty(AConnectionString)) { if (String.IsNullOrEmpty(AUsername)) { throw new ArgumentException("AUsername", "AUsername must not be null or an empty string!"); } if (String.IsNullOrEmpty(APassword)) { throw new ArgumentException("APassword", "APassword must not be null or an empty string!"); } AConnectionString = String.Format( "Server={0};Port={1};User Id={2};Database={3};Timeout={4};ConnectionIdleLifeTime={5};CommandTimeout={6}" + ";Password="******"Server.DBConnectionTimeout", 10), TAppSettingsManager.GetInt32("Server.DBConnectionLifeTime", 300), TAppSettingsManager.GetInt32("Server.DBCommandTimeout", 3600)); // Note: We must use TAppSettingsManager above and not TSrvSetting because if we would be using the latter // somehow some NUnit Tests fail with extremely weird timeouts... } try { // TLogging.Log('Full ConnectionString (with Password!): ''' + ConnectionString + ''''); // TLogging.Log('Full ConnectionString (with Password!): ''' + ConnectionString + ''''); // TLogging.Log('ConnectionStringBuilder.ToString (with Password!): ''' + ConnectionStringBuilder.ToString + ''''); // Now try to connect to the DB TheConnection = new NpgsqlConnection(); TheConnection.ConnectionString = AConnectionString + APassword + ";"; } catch (Exception exp) { ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } return(TheConnection); }
protected void OnStateChange(StateChangeEventArgs stateChange) { StateChangeEventHandler handler = StateChange; if (handler != null) { handler(this, stateChange); } }
protected virtual void OnStateChange(StateChangeEventArgs stateChange) { StateChangeEventHandler handler = _stateChangeEventHandler; if (null != handler) { handler(this, stateChange); } }
public ConnectionState EcouterConnexion(StateChangeEventHandler handler) { if (Connexion != null) { Connexion.StateChange += handler; } return(Connexion.State); }
protected virtual void OnStateChange(StateChangeEventArgs stateChange) { StateChangeEventHandler handler = this._stateChangeEventHandler; if (handler != null) { handler(this, stateChange); } }
private void OnStateChange(StateChangeEventArgs stateChangeEvent) { StateChangeEventHandler handler = (StateChangeEventHandler)Events[EventStateChange]; if (null != handler) { handler(this, stateChangeEvent); } }
protected override void OnStateChange(StateChangeEventArgs stateChange) { StateChangeEventHandler stateChangeEventHandler = this._stateChangeEventHandler; if (stateChangeEventHandler != null) { stateChangeEventHandler(this, stateChange); } }
//======================================================================================== // Execute() // This is the thread worker routine. //======================================================================================== private void Execute(object chassisObj) { Chassis chassis = (Chassis)chassisObj; if (UserOptions.RunStatistics) { chassis.queries.Statistics = new Statistics(dbase); chassis.queries.Statistics.Initialize(); } var infoHandler = new OracleInfoMessageEventHandler(CaptureInfoMessage); var stateHandler = new StateChangeEventHandler(CaptureStateChange); OracleConnection con = dbase.OraConnection; con.InfoMessage += infoHandler; con.StateChange += stateHandler; try { QueryCollection.Enumerator qe; while ((chassis.repeat-- > 0) && !isCancelled) { qe = chassis.queries.GetEnumerator(); while (qe.MoveNext() && !isCancelled) { ExecuteQuery(query = qe.Current); if (query.AffectedRecords > 0) { chassis.queries.TotalRecords += query.AffectedRecords; } chassis.queries.TotalTicks += query.Ticks; } } if (UserOptions.RunStatistics) { chassis.queries.Statistics.Summarize(); } } finally { this.isExecuting = false; if (QueriesCompleted != null) { QueriesCompleted(new QueriesCompletedEventArgs(chassis.queries)); } con.InfoMessage -= infoHandler; con.StateChange -= stateHandler; } }
public void Timeout(object state) { StateChangeEventHandler handler = state as StateChangeEventHandler; handler(this, new XComputeProcessStateChangeEventArgs(m_id, m_currentState, true)); lock (SyncRoot) { m_stateChangeTimers.Remove(handler); } }
private void FireStateChange(ConnectionState oldState, ConnectionState newState) { // retrieve the delegate from the Components.Events property StateChangeEventHandler stateChangeEventHandler = (StateChangeEventHandler)Events[objEventStateChange]; if (stateChangeEventHandler != null) { stateChangeEventHandler( this, new StateChangeEventArgs(oldState, newState)); } }
internal bool _supressStateChangeForReconnection = false; // Do not use for anything else ! Value will be overwritten by CR process protected virtual void OnStateChange(StateChangeEventArgs stateChange) { if (_supressStateChangeForReconnection) { return; } StateChangeEventHandler handler = _stateChangeEventHandler; if (null != handler) { handler(this, stateChange); } }
/// <summary> /// Raises the state change event when the state of the connection changes /// </summary> /// <param name="newState">The new state. If it is different from the previous state, an event is raised.</param> internal void OnStateChange(ConnectionState newState) { ConnectionState oldState = _connectionState; _connectionState = newState; StateChangeEventHandler handler = StateChange; if (handler != null && oldState != newState) { handler(this, new StateChangeEventArgs(oldState, newState)); } }
/// <summary> /// Opens a connection to the specified database /// </summary> /// <param name="ADataBaseRDBMS">the database functions for the selected type of database</param> /// <param name="AServer">The Database Server</param> /// <param name="APort">the port that the db server is running on</param> /// <param name="ADatabaseName">the database to connect to</param> /// <param name="AUsername">The username for opening the connection</param> /// <param name="APassword">The password for opening the connection</param> /// <param name="AConnectionString">The connection string; if it is not empty, it will overrule the previous parameters</param> /// <param name="AStateChangeEventHandler">for connection state changes</param> /// <returns>Opened Connection (null if connection could not be established). /// </returns> public static DbConnection GetConnection(IDataBaseRDBMS ADataBaseRDBMS, String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { return(ADataBaseRDBMS.GetConnection(AServer, APort, ADatabaseName, AUsername, ref APassword, ref AConnectionString, AStateChangeEventHandler)); }
private void OnStateChange(ConnectionState original, ConnectionState state) { StateChangeEventHandler stateChangeEventHandler = (StateChangeEventHandler)base.Events[ADP.EventStateChange]; if (stateChangeEventHandler != null) { try { stateChangeEventHandler(this, new StateChangeEventArgs(original, state)); } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } } } }
/// <summary> /// Creates an ODBC connection using the standard ADO.NET Data Provider ODBC. /// </summary> /// <param name="ADSN">The DSN defining the connection to the database server</param> /// <param name="APort">not in use</param> /// <param name="ADatabaseName">not in use</param> /// <param name="AUsername">odbc user name</param> /// <param name="APassword">The password for opening the database</param> /// <param name="AConnectionString">not in use</param> /// <param name="AStateChangeEventHandler">for connection state changes</param> /// <returns>Instantiated OdbcConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String ADSN, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { ArrayList ExceptionList; OdbcConnection TheConnection = null; if (AConnectionString == "") { AConnectionString = "DSN=" + ADSN + ";UID=" + AUsername + ";PWD="; } try { // Now try to connect to the DB TheConnection = new OdbcConnection(); TheConnection.ConnectionString = AConnectionString + APassword; } catch (Exception exp) { ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { ((OdbcConnection)TheConnection).StateChange += AStateChangeEventHandler; } FDBEncoding = System.Text.Encoding.Default; try { Int16 sqlClientCodePage = Convert.ToInt16(System.Environment.GetEnvironmentVariable("SQL_CLIENT_CHARSET")); FDBEncoding = System.Text.Encoding.GetEncoding(sqlClientCodePage); } catch (Exception) { } return(TheConnection); }
/// <summary> /// Creates an ODBC connection using the standard ADO.NET Data Provider ODBC. /// </summary> /// <param name="ADSN">The DSN defining the connection to the database server</param> /// <param name="APort">not in use</param> /// <param name="ADatabaseName">not in use</param> /// <param name="AUsername">odbc user name</param> /// <param name="APassword">The password for opening the database</param> /// <param name="AConnectionString">not in use</param> /// <param name="AStateChangeEventHandler">for connection state changes</param> /// <returns>Instantiated OdbcConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String ADSN, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { ArrayList ExceptionList; OdbcConnection TheConnection = null; if (AConnectionString == "") { AConnectionString = "DSN=" + ADSN + ";UID=" + AUsername + ";PWD="; } try { // Now try to connect to the DB TheConnection = new OdbcConnection(); TheConnection.ConnectionString = AConnectionString + APassword; } catch (Exception exp) { ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { ((OdbcConnection)TheConnection).StateChange += AStateChangeEventHandler; } FDBEncoding = System.Text.Encoding.Default; try { Int16 sqlClientCodePage = Convert.ToInt16(System.Environment.GetEnvironmentVariable("SQL_CLIENT_CHARSET")); FDBEncoding = System.Text.Encoding.GetEncoding(sqlClientCodePage); } catch (Exception) { } return TheConnection; }
/// <summary> /// Creates a MySqlConnection connection using the 'MySQL AB ADO.Net Driver for MySQL' .NET Data Provider. /// </summary> /// <param name="AServer">Database Server.</param> /// <param name="APort">Port that the DB server is running on.</param> /// <param name="ADatabaseName">Name of the database that we want to connect to.</param> /// <param name="AUsername">Username for opening the MySQL connection.</param> /// <param name="APassword">Password for opening the MySQL connection.</param> /// <param name="AConnectionString">Connection string; if it is not empty, it will /// overrule the previous parameters.</param> /// <param name="AStateChangeEventHandler">Event Handler for connection state changes.</param> /// <returns> /// Instantiated MySqlConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { MySqlConnection TheConnection = null; if (String.IsNullOrEmpty(AConnectionString)) { if (AUsername == "") { throw new ArgumentException("AUsername", "AUsername must not be null or an empty string!"); } if (APassword == "") { throw new ArgumentException("APassword", "APassword must not be null or an empty string!"); } AConnectionString = "SERVER=" + AServer + ";" + "DATABASE=" + ADatabaseName + ";" + "UID=" + AUsername + ";" + "PASSWORD="******";"); } catch (Exception exp) { ArrayList ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { // TODO: need to test this TheConnection.StateChange += AStateChangeEventHandler; } return TheConnection; }
/// <summary> /// Creates a MySqlConnection connection using the 'MySQL AB ADO.Net Driver for MySQL' .NET Data Provider. /// </summary> /// <param name="AServer">Database Server.</param> /// <param name="APort">Port that the DB server is running on.</param> /// <param name="ADatabaseName">Name of the database that we want to connect to.</param> /// <param name="AUsername">Username for opening the MySQL connection.</param> /// <param name="APassword">Password for opening the MySQL connection.</param> /// <param name="AConnectionString">Connection string; if it is not empty, it will /// overrule the previous parameters.</param> /// <param name="AStateChangeEventHandler">Event Handler for connection state changes.</param> /// <returns> /// Instantiated MySqlConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { MySqlConnection TheConnection = null; if (String.IsNullOrEmpty(AConnectionString)) { if (AUsername == "") { throw new ArgumentException("AUsername", "AUsername must not be null or an empty string!"); } if (APassword == "") { throw new ArgumentException("APassword", "APassword must not be null or an empty string!"); } AConnectionString = "SERVER=" + AServer + ";" + "DATABASE=" + ADatabaseName + ";" + "UID=" + AUsername + ";" + "PASSWORD="******";"); } catch (Exception exp) { ArrayList ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { // TODO: need to test this TheConnection.StateChange += AStateChangeEventHandler; } return(TheConnection); }
/// <summary> /// Opens a connection to the specified database /// </summary> /// <param name="ADataBaseRDBMS">the database functions for the selected type of database</param> /// <param name="AServer">The Database Server</param> /// <param name="APort">the port that the db server is running on</param> /// <param name="ADatabaseName">the database to connect to</param> /// <param name="AUsername">The username for opening the connection</param> /// <param name="APassword">The password for opening the connection</param> /// <param name="AConnectionString">The connection string; if it is not empty, it will overrule the previous parameters</param> /// <param name="AStateChangeEventHandler">for connection state changes</param> /// <returns>Opened Connection (null if connection could not be established). /// </returns> public DbConnection GetConnection(IDataBaseRDBMS ADataBaseRDBMS, String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { FConnectionString = AConnectionString; return ADataBaseRDBMS.GetConnection(AServer, APort, ADatabaseName, AUsername, ref APassword, ref FConnectionString, AStateChangeEventHandler); }
/// <summary> /// Creates a SQLite connection using the 'Mono.Data.Sqlite' .NET Data Provider. /// This works on Windows (with the sqlite3.dll) and on Linux. /// </summary> /// <param name="AServer">Database file.</param> /// <param name="APort">Port that the db server is running on.</param> /// <param name="ADatabaseName">Not in use with SQLite.</param> /// <param name="AUsername">Not in use with SQLite.</param> /// <param name="APassword">Password for opening the database.</param> /// <param name="AConnectionString">Not in use with SQLite.</param> /// <param name="AStateChangeEventHandler">Event Handler for connection state changes.</param> /// <returns>Instantiated SqliteConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { ArrayList ExceptionList; SqliteConnection TheConnection = null; if (!File.Exists(AServer)) { // on Windows, we cannot store the database in userappdata during installation, because // the setup has to be run as administrator. // therefore the first time the user starts Petra, we need to prepare his environment // see also http://www.vincenzo.net/isxkb/index.php?title=Vista_considerations#Best_Practices // copy the base database string baseDatabase = TAppSettingsManager.GetValue("Server.SQLiteBaseFile"); if (!Directory.Exists(Path.GetDirectoryName(AServer))) { Directory.CreateDirectory(Path.GetDirectoryName(AServer)); } File.Copy(baseDatabase, AServer); } if (String.IsNullOrEmpty(AConnectionString)) { AConnectionString = "Data Source=" + Path.GetFullPath(AServer); // sqlite on Windows does not support encryption with a password // System.EntryPointNotFoundException: sqlite3_key APassword = string.Empty; if (APassword.Length > 0) { AConnectionString += ";Password="******"3.7.11")) < 0) { // for insert statements with multiple rows. see http://www.sqlite.org/releaselog/3_7_11.html TLogging.Log("OpenPetra requires SQLite >= 3.7.11, but current version is " + SqliteConnection.SQLiteVersion); return(null); } try { // Now try to connect to the DB TheConnection = new SqliteConnection(AConnectionString + APassword); } catch (Exception exp) { ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { TheConnection.StateChange += AStateChangeEventHandler; } return(TheConnection); }
/// <summary> /// Creates a PostgreSQL connection using the 'Npgsql' .NET Data Provider. /// This works on Windows and on Linux. /// </summary> /// <param name="AServer">Database Server.</param> /// <param name="APort">Port that the DB server is running on.</param> /// <param name="ADatabaseName">Name of the database that we want to connect to.</param> /// <param name="AUsername">Username for opening the PostgreSQL connection.</param> /// <param name="APassword">Password for opening the PostgreSQL connection.</param> /// <param name="AConnectionString">Connection string; if it is not empty, it will /// overrule the previous parameters.</param> /// <param name="AStateChangeEventHandler">Event Handler for connection state changes /// (NOTE: This doesn't work yet with the Npgsql driver - see code comments in this Methods' /// source code)!</param> /// <returns> /// Instantiated NpgsqlConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { ArrayList ExceptionList; NpgsqlConnection TheConnection = null; #if EXTREME_DEBUGGING NpgsqlEventLog.Level = LogLevel.Debug; NpgsqlEventLog.LogName = "NpgsqlTests.LogFile"; NpgsqlEventLog.EchoMessages = false; #endif if (String.IsNullOrEmpty(AConnectionString)) { if (String.IsNullOrEmpty(AUsername)) { throw new ArgumentException("AUsername", "AUsername must not be null or an empty string!"); } if (String.IsNullOrEmpty(APassword)) { throw new ArgumentException("APassword", "APassword must not be null or an empty string!"); } AConnectionString = String.Format( "Server={0};Port={1};User Id={2};Database={3};Timeout={4};ConnectionLifeTime={5};CommandTimeout={6}" + ";Password="******"Server.DBConnectionTimeout", 10), TAppSettingsManager.GetInt32("Server.DBConnectionLifeTime", 60), TAppSettingsManager.GetInt32("Server.DBCommandTimeout", 3600)); // Note: We must use TAppSettingsManager above and not TSrvSetting because if we would be using the latter // somehow some NUnit Tests fail with extremely weird timeouts... } try { // TLogging.Log('Full ConnectionString (with Password!): ''' + ConnectionString + ''''); // TLogging.Log('Full ConnectionString (with Password!): ''' + ConnectionString + ''''); // TLogging.Log('ConnectionStringBuilder.ToString (with Password!): ''' + ConnectionStringBuilder.ToString + ''''); // Now try to connect to the DB TheConnection = new NpgsqlConnection(); TheConnection.ConnectionString = AConnectionString + APassword + ";"; } catch (Exception exp) { ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { // Somehow the StateChange Event is never fired for an NpgsqlConnection, although it is documented. // As a result of that we cannot rely on the FConnectionReady variable to contain valid values for // NpgsqlConnection. Therefore I (ChristianK) wrote a wrapper routine, ConnectionReady, which // handles this difference. FConnectionReady must therefore never be inquired directly, but only // through calling ConnectionReady()! // (As of Npgsql 2.0.11.92 the Event still isn't raised) // TODO: need to test this again ((NpgsqlConnection)TheConnection).StateChange += AStateChangeEventHandler; } return(TheConnection); }
/// <summary> /// Creates a PostgreSQL connection using the 'Npgsql' .NET Data Provider. /// This works on Windows and on Linux. /// </summary> /// <param name="AServer">Database Server.</param> /// <param name="APort">Port that the DB server is running on.</param> /// <param name="ADatabaseName">Name of the database that we want to connect to.</param> /// <param name="AUsername">Username for opening the PostgreSQL connection.</param> /// <param name="APassword">Password for opening the PostgreSQL connection.</param> /// <param name="AConnectionString">Connection string; if it is not empty, it will /// overrule the previous parameters.</param> /// <param name="AStateChangeEventHandler">Event Handler for connection state changes /// (NOTE: This doesn't work yet with the Npgsql driver - see code comments in this Methods' /// source code)!</param> /// <returns> /// Instantiated NpgsqlConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { ArrayList ExceptionList; NpgsqlConnection TheConnection = null; #if EXTREME_DEBUGGING NpgsqlEventLog.Level = LogLevel.Debug; NpgsqlEventLog.LogName = "NpgsqlTests.LogFile"; NpgsqlEventLog.EchoMessages = false; #endif if (String.IsNullOrEmpty(AConnectionString)) { if (String.IsNullOrEmpty(AUsername)) { throw new ArgumentException("AUsername", "AUsername must not be null or an empty string!"); } if (String.IsNullOrEmpty(APassword)) { throw new ArgumentException("APassword", "APassword must not be null or an empty string!"); } // TODO: Make 'ConnectionLifeTime' and 'CommandTimeout' configurable somehow. That would allow // us to cater better for server environments where the server is quite busy and the RDBMS could // therefore be slow to respond! See https://tracker.openpetra.org/view.php?id=2330. AConnectionString = "Server=" + AServer + ";Port=" + APort + ";User Id=" + AUsername + ";Database=" + ADatabaseName + ";ConnectionLifeTime=60;CommandTimeout=3600;Password="******";"; } catch (Exception exp) { ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { // Somehow the StateChange Event is never fired for an NpgsqlConnection, although it is documented. // As a result of that we cannot rely on the FConnectionReady variable to contain valid values for // NpgsqlConnection. Therefore I (ChristianK) wrote a wrapper routine, ConnectionReady, which // handles this difference. FConnectionReady must therefore never be inquired directly, but only // through calling ConnectionReady()! // (As of Npgsql 2.0.11.92 the Event still isn't raised) // TODO: need to test this again ((NpgsqlConnection)TheConnection).StateChange += AStateChangeEventHandler; } return TheConnection; }
public void NotifyStateChange(int processId, long timeoutInterval, ProcessState targetState, StateChangeEventHandler handler) { this.processTable[processId].AddStateChangeListener(targetState, timeoutInterval, handler); }
//----------------- public MyDaItem(string itemId, MyDaSubscription parentSubscription) : base(itemId, parentSubscription) { StateChangeCompleted += new StateChangeEventHandler(HandleStateChanged); PerformStateTransitionCompleted += new PerformStateTransitionEventHandler(HandlePerformStateTransition); }
/// <summary> /// Creates a SQLite connection using the 'Mono.Data.Sqlite' .NET Data Provider. /// This works on Windows (with the sqlite3.dll) and on Linux. /// </summary> /// <param name="AServer">Database file.</param> /// <param name="APort">Port that the db server is running on.</param> /// <param name="ADatabaseName">Not in use with SQLite.</param> /// <param name="AUsername">Not in use with SQLite.</param> /// <param name="APassword">Password for opening the database.</param> /// <param name="AConnectionString">Not in use with SQLite.</param> /// <param name="AStateChangeEventHandler">Event Handler for connection state changes.</param> /// <returns>Instantiated SqliteConnection, but not opened yet (null if connection could not be established). /// </returns> public DbConnection GetConnection(String AServer, String APort, String ADatabaseName, String AUsername, ref String APassword, ref String AConnectionString, StateChangeEventHandler AStateChangeEventHandler) { ArrayList ExceptionList; SqliteConnection TheConnection = null; if (!File.Exists(AServer)) { // on Windows, we cannot store the database in userappdata during installation, because // the setup has to be run as administrator. // therefore the first time the user starts Petra, we need to prepare his environment // see also http://www.vincenzo.net/isxkb/index.php?title=Vista_considerations#Best_Practices // copy the base database string baseDatabase = TAppSettingsManager.GetValue("Server.SQLiteBaseFile"); if (!Directory.Exists(Path.GetDirectoryName(AServer))) { Directory.CreateDirectory(Path.GetDirectoryName(AServer)); } File.Copy(baseDatabase, AServer); } if (String.IsNullOrEmpty(AConnectionString)) { AConnectionString = "Data Source=" + Path.GetFullPath(AServer); // sqlite on Windows does not support encryption with a password // System.EntryPointNotFoundException: sqlite3_key APassword = string.Empty; if (APassword.Length > 0) { AConnectionString += ";Password="******"3.7.11")) < 0) { // for insert statements with multiple rows. see http://www.sqlite.org/releaselog/3_7_11.html TLogging.Log("OpenPetra requires SQLite >= 3.7.11, but current version is " + SqliteConnection.SQLiteVersion); return null; } try { // Now try to connect to the DB TheConnection = new SqliteConnection(AConnectionString + APassword + ";StoreDateTimeAsTicks=true"); } catch (Exception exp) { ExceptionList = new ArrayList(); ExceptionList.Add((("Error establishing a DB connection to: " + AConnectionString) + Environment.NewLine)); ExceptionList.Add((("Exception thrown :- " + exp.ToString()) + Environment.NewLine)); TLogging.Log(ExceptionList, true); } if (TheConnection != null) { TheConnection.StateChange += AStateChangeEventHandler; } return TheConnection; }