/// <summary> /// 建立 db /// </summary> /// <param name="server"></param> /// <param name="db"></param> public static void CreateDatabase(string server, string db) { ConsoleUtils.WriteInfo("Creating database {0}", db); // Retry 機制 ,並取得 Connection String using (ReliableSqlConnection conn = new ReliableSqlConnection( Configuration.GetConnectionString(server, MasterDatabaseName), SqlRetryPolicy, SqlRetryPolicy)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); // 確定我們是否連接到SQL Azure的數據庫 cmd.CommandText = "SELECT SERVERPROPERTY('EngineEdition')"; cmd.CommandTimeout = 60; int engineEdition = conn.ExecuteCommand<int>(cmd); if (engineEdition == 5) { // Azure SQL DB SqlRetryPolicy.ExecuteAction(() => { if (!DatabaseExists(server, db)) { // 開始建立 async for Standard/Premium cmd.CommandText = string.Format( "CREATE DATABASE {0} (EDITION = '{1}')", BracketEscapeName(db), Configuration.DatabaseEdition); cmd.CommandTimeout = 60; cmd.ExecuteNonQuery(); } }); // 等待操作完成 while (!DatabaseIsOnline(server, db)) { ConsoleUtils.WriteInfo("Waiting for database {0} to come online...", db); Thread.Sleep(TimeSpan.FromSeconds(5)); } ConsoleUtils.WriteInfo("Database {0} is online", db); } else { // 其他版本 SQL DB cmd.CommandText = string.Format("CREATE DATABASE {0}", BracketEscapeName(db)); conn.ExecuteCommand(cmd); } } }
public void CreateTable() { // Uses specified connection for open, default for execute String commandText = @"CREATE TABLE Writer ( Id int PRIMARY KEY NOT NULL, Name nvarchar(20) NOT NULL, CountBooks int NULL)"; using (ReliableSqlConnection connection = new ReliableSqlConnection(connectionString, connectionRetryPolicy)) { connection.Open(); using (SqlCommand sqlCommand = connection.CreateCommand()) { sqlCommand.CommandText = commandText; sqlCommand.ExecuteNonQueryWithRetry(); } } }
private bool VerifyCustomerAddress(int customerId, int addressId) { int count = 0; using (ReliableSqlConnection connection = new ReliableSqlConnection(connectionString)) { using (SqlCommand command = (SqlCommand)connection.CreateCommand()) { command.CommandText = "SELECT COUNT(*) FROM [SalesLT].[CustomerAddress] WHERE [CustomerID] = @CustomerID AND [AddressID] = @AddressID"; command.Parameters.Add("@CustomerID", SqlDbType.Int).Value = customerId; command.Parameters.Add("@AddressID", SqlDbType.Int).Value = addressId; count = (int)command.ExecuteScalarWithRetry(); } connection.Close(); } return(count > 0); }
public static bool DatabaseIsOnline(string server, string db) { using (ReliableSqlConnection conn = new ReliableSqlConnection( Configuration.GetConnectionString(server, MasterDatabaseName), SqlRetryPolicy, SqlRetryPolicy)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from sys.databases where name = @dbname and state = 0"; // online cmd.Parameters.AddWithValue("@dbname", db); cmd.CommandTimeout = 60; int count = conn.ExecuteCommand<int>(cmd); bool exists = count > 0; return exists; } }
public static bool DatabaseIsOnline(string server, string db) { using (ReliableSqlConnection conn = new ReliableSqlConnection( Configuration.GetConnectionString(server, MasterDatabaseName), SqlRetryPolicy, SqlRetryPolicy)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from sys.databases where name = @dbname and state = 0"; // online cmd.Parameters.AddWithValue("@dbname", db); cmd.CommandTimeout = 60; int count = conn.ExecuteCommand <int>(cmd); bool exists = count > 0; return(exists); } }
private IEnumerable<ActivityDetailDataContract> getActivityDetailsUsingADO() { //var connectionString = getAzureConnectionString().ConnectionString; //var connectionString = ConfigurationManager.ConnectionStrings["mediaHubActivityConnectionString"].ConnectionString; var connectionString = CloudConfigurationManager.GetSetting("mediaHubActivityConnectionString"); using (var connection = new ReliableSqlConnection(connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandText = "SELECT TOP 10000 * FROM j30t_changelog ORDER BY j30c_date DESC"; using (var reader = command.ExecuteReader()) { while (reader.Read()) yield return reader.Transform(); } } connection.Close(); } }
public static void ExecuteSqlScript(string server, string db, string schemaFile) { using (ReliableSqlConnection conn = new ReliableSqlConnection( Configuration.GetConnectionString(server, db), SqlRetryPolicy, SqlRetryPolicy)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); // Read the commands from the sql script file IEnumerable <string> commands = ReadSqlScript(schemaFile); foreach (string command in commands) { cmd.CommandText = command; cmd.CommandTimeout = 60; conn.ExecuteCommand(cmd); } } }
public static void ExecuteSqlScript(string masterDbConnectionString, string schemaFile) { //ConsoleUtils.WriteInfo("Executing script {0}", schemaFile); using (ReliableSqlConnection conn = new ReliableSqlConnection(masterDbConnectionString, SqlRetryPolicy, SqlRetryPolicy)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); // Read the commands from the sql script file IEnumerable <string> commands = ReadSqlScript(schemaFile); foreach (string command in commands) { cmd.CommandText = command; cmd.CommandTimeout = 60; conn.ExecuteCommand(cmd); } } }
/// <summary> /// Get the Middle FedKey of this member's range, or of a tables values /// </summary> /// <param name="bGetMiddleOfRange"></param> /// <returns>The new FedKey in the middle</returns> public FedKey GetMiddleFedKey(bool bGetMiddleOfRange = true) { FedKey fedkey = null; // Query the table to get the median value, if no rows return middle of the pack (yeah, right!) if (!bGetMiddleOfRange) { string command = ""; foreach (FederatedTable fedtable in Tables) { command = String.Format(MEDIAN_QUERY, fedtable.ColumnList, fedtable.Name); break; // Get First Table only } using (var cnn = new ReliableSqlConnection(Parent.Parent.ConnectionString)) { cnn.Open(); cnn.UseFederationMember(this); using (var cmd = cnn.CreateCommand()) { cmd.CommandText = command; using (var rdr = cmd.ExecuteReaderWithRetry()) { while (rdr.Read()) { fedkey = FedKey.CreateFedKey(this.FedKeyType, (object)rdr.GetValue(0)); } } } } } if (null == fedkey) { fedkey = this.Range.GetMidRange(); } return(fedkey); }
public void CreateOrder(Order order) { using (var reliableSqlConnection = new ReliableSqlConnection(connectionString, retryPolicy)) { reliableSqlConnection.Open(); var sqlCommand = reliableSqlConnection.CreateCommand(); sqlCommand.CommandText = "INSERT INTO [dbo].[Ordrar] ([Quantity], [ProductId], [Email], [Shipping], [Price]) " + "VALUES(@quantity, @productId, @email, @shipping, @price)"; sqlCommand.Parameters.AddWithValue("@quantity", order.Quantity); sqlCommand.Parameters.AddWithValue("@productId", order.ProductId); sqlCommand.Parameters.AddWithValue("@email", order.Email); sqlCommand.Parameters.AddWithValue("@shipping", order.Shipping); sqlCommand.Parameters.AddWithValue("@price", order.Price); sqlCommand.ExecuteScalarWithRetry(retryPolicy); } Thread.Sleep(TimeSpan.FromSeconds(5)); }
/// <summary> /// To execute sql script /// </summary> /// <param name="server"></param> /// <param name="db"></param> /// <param name="schemaFile"></param> public static void ExecuteSqlScript(string server, string db, string schemaFile) { ConsoleUtils.WriteInfo("Executing script {0}", schemaFile); using (ReliableSqlConnection conn = new ReliableSqlConnection( MultiShardConfiguration.GetConnectionStringForSelectedDatabase(db), SqlRetryPolicy, SqlRetryPolicy)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); // Read the commands from the sql script file IEnumerable <string> commands = ReadSqlScript(schemaFile); foreach (string command in commands) { cmd.CommandText = command; cmd.CommandTimeout = 60; conn.ExecuteCommand(cmd); } } }
private IEnumerable <FederatedTable> GetTablesAndColumns(Member member) { List <FederatedTable> tables = new List <FederatedTable>(); using (var cnn = new ReliableSqlConnection(ConnectionString)) { cnn.Open(); cnn.UseFederationMember(member); using (var cmd = cnn.CreateCommand()) { cmd.CommandText = QUERY_COLUMNS; using (var rdr = cmd.ExecuteReaderWithRetry()) { while (rdr.Read()) { FederatedTable currentTable = tables.SingleOrDefault(x => x.Name == rdr.GetString(0));; if (currentTable == null) { currentTable = new FederatedTable(); currentTable.Name = rdr.GetString(0); tables.Add(currentTable); } //currentTable.Columns.Add(new FederatedColumn() { Name = rdr.GetString(1) }); currentTable.Add(new FederatedColumn() { Name = rdr.GetString(1) }); } } } } return(tables); }
public List<KeyValuePair<string, string>> GetPairs() { try { List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>(); ReliableSQL sql = new ReliableSQL(); sql.Connection.ExecuteAction(() => { using (ReliableSqlConnection connection = new ReliableSqlConnection("Data Source=plasne-sql01.database.windows.net; Initial Catalog=plasne-db01; Authentication=Active Directory Integrated;")) { connection.Open(); using (SqlCommand cmd = connection.CreateCommand()) { cmd.CommandText = "SELECT [key], [value] FROM [pairs]"; sql.Command.ExecuteAction(() => { using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { pairs.Add(new KeyValuePair<string, string>((string)reader[0], (string)reader[1])); } } }); } } }); return pairs; } catch (Exception ex) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { ReasonPhrase = Regex.Replace(ex.Message, @"\t|\n|\r", "") }); } }
private void StopJob(Guid activityId) { var rPolicy = new RetryPolicy<SqlAzureTransientErrorDetectionStrategy> (5, TimeSpan.FromMilliseconds(150)); using (ReliableSqlConnection con = new ReliableSqlConnection(DefaultConnectionString(), rPolicy)) { con.Open(); using (var cmdStop = con.CreateCommand()) { cmdStop.CommandType = System.Data.CommandType.StoredProcedure; cmdStop.CommandText = "StopJob"; cmdStop.Parameters.AddWithValue("@ActivityId", activityId); con.ExecuteCommand(cmdStop, rPolicy); } } }
private void BuildMetaData() { using (var cnn = new ReliableSqlConnection(ConnectionString)) { cnn.Open(); cnn.UseFederationRoot(); using (var cmd = cnn.CreateCommand()) { cmd.CommandText = FederatedDatabase.METADATA_QUERY; using (var rdr = cmd.ExecuteReaderWithRetry()) { Federations = new Dictionary <string, Federation>(); while (rdr.Read()) { Federation currentFederation; if (Federations.ContainsKey(rdr.GetString(1))) { currentFederation = Federations[rdr.GetString(1)]; } else { currentFederation = new Federation(); currentFederation.ID = rdr.GetInt32(0); currentFederation.Name = rdr.GetString(1); currentFederation.Parent = this; Federations.Add(currentFederation.Name, currentFederation); } var m = new Member(); m.Parent = currentFederation; m.Id = rdr.GetInt32(2); m.DistributionName = rdr.GetString(3); switch (rdr.GetByte(4)) { case 56: System.Int32 lowInt = rdr.GetInt32(5); System.Int32 highInt = int.MaxValue;; if (!rdr.IsDBNull(6)) { highInt = rdr.GetInt32(6); } m.Range = new FedRange(lowInt, highInt); break; case 127: System.Int64 lowLong = rdr.GetInt64(5); System.Int64 highLong = long.MaxValue;; if (!rdr.IsDBNull(6)) { highLong = rdr.GetInt64(6); } m.Range = new FedRange(lowLong, highLong); break; case 36: System.Guid lowGuid = rdr.GetGuid(5); System.Guid highGuid = Guid.Parse("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"); if (!rdr.IsDBNull(6)) { highGuid = rdr.GetGuid(6); } m.Range = new FedRange(lowGuid, highGuid); break; case 165: System.Byte[] lowVarBinary = rdr.GetValue(5) as byte[];; System.Byte[] highVarBinary = null; if (!rdr.IsDBNull(6)) { highVarBinary = rdr.GetValue(6) as byte[]; } m.Range = new FedRange(lowVarBinary, highVarBinary); break; default: break; } currentFederation.Members.Add(m.Id, m); } } } LoadMemberTablesAndColumns(); } }
public void DropTable() { // Uses default for connection open and specified for command String commandText = "DROP TABLE Writer"; using (ReliableSqlConnection connection = new ReliableSqlConnection(connectionString)) { connection.Open(connectionRetryPolicy); using (SqlCommand sqlCommand = connection.CreateCommand()) { sqlCommand.CommandText = commandText; sqlCommand.ExecuteNonQueryWithRetry(commandRetryPolicy); } } }
/// <summary> /// Creates a SqlCommand that you can use for loving your database. /// </summary> SqlCommand CreateCommand(string sql, ReliableSqlConnection conn, params object[] args) { var result = conn.CreateCommand(); result.CommandText = sql; if (args.Length > 0) { result.AddParams(args); } return result; }
private bool VerifyCustomerAddress(int customerId, int addressId) { int count = 0; using (ReliableSqlConnection connection = new ReliableSqlConnection(connectionString)) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "SELECT COUNT(*) FROM [SalesLT].[CustomerAddress] WHERE [CustomerID] = @CustomerID AND [AddressID] = @AddressID"; command.Parameters.Add("@CustomerID", SqlDbType.Int).Value = customerId; command.Parameters.Add("@AddressID", SqlDbType.Int).Value = addressId; count = (int)command.ExecuteScalarWithRetry(); } connection.Close(); } return count > 0; }
/// <summary> /// Execute Stored Procedure /// </summary> /// <param name="procedureName">procedure Name</param> /// <param name="parameters">parameters dictionary</param> /// <param name="timeOutSecs">Timeout for Command in Seconds</param> /// <returns>Task of string</returns> public async Task <string> ExecuteStoredProcedureAsync(string procedureName, Dictionary <string, object> parameters, int timeOutSecs) { const int RetryCountMin = 3; const int RetryCountMax = 5; const int MinBackOffTimeMsecs = 100; const int MaxBackOffTimeMsecs = 30; RetryManager.SetDefault( new RetryManager( new List <RetryStrategy> { new ExponentialBackoff( name: Default, retryCount: RetryCountMin, minBackoff: TimeSpan.FromMilliseconds(MinBackOffTimeMsecs), maxBackoff: TimeSpan.FromSeconds(MaxBackOffTimeMsecs), deltaBackoff: TimeSpan.FromSeconds(1), firstFastRetry: true), new ExponentialBackoff( name: DefaultSQLConnection, retryCount: RetryCountMin, minBackoff: TimeSpan.FromMilliseconds(MinBackOffTimeMsecs), maxBackoff: TimeSpan.FromSeconds(MaxBackOffTimeMsecs), deltaBackoff: TimeSpan.FromSeconds(1), firstFastRetry: true), new ExponentialBackoff( name: DefaultSQLCommand, retryCount: RetryCountMin, minBackoff: TimeSpan.FromMilliseconds(MinBackOffTimeMsecs), maxBackoff: TimeSpan.FromSeconds(MaxBackOffTimeMsecs), deltaBackoff: TimeSpan.FromSeconds(1), firstFastRetry: true), new ExponentialBackoff( name: AltSQL, retryCount: RetryCountMax, minBackoff: TimeSpan.FromMilliseconds(MinBackOffTimeMsecs), maxBackoff: TimeSpan.FromSeconds(MaxBackOffTimeMsecs), deltaBackoff: TimeSpan.FromSeconds(1), firstFastRetry: true), }, Default, new Dictionary <string, string> { { RetryManagerSqlExtensions .DefaultStrategyConnectionTechnologyName, DefaultSQLConnection }, { RetryManagerSqlExtensions.DefaultStrategyCommandTechnologyName, DefaultSQLCommand } }), false); return(await Task.Run( () => { var retryConnectionPolicy = RetryManager.Instance.GetDefaultSqlConnectionRetryPolicy(); var retryCommandPolicy = RetryManager.Instance.GetDefaultSqlCommandRetryPolicy(); using ( ReliableSqlConnection conn = new ReliableSqlConnection( this.connectionString, retryConnectionPolicy, retryCommandPolicy)) { SqlParameter outResult = new SqlParameter("@result", SqlDbType.NVarChar, -1) { Direction = ParameterDirection .Output }; conn.Open(); var command = conn.CreateCommand(); command.CommandText = procedureName; command.CommandType = CommandType.StoredProcedure; if (timeOutSecs > 0) { command.CommandTimeout = (timeOutSecs > MaxTimeOut) ? MaxTimeOut : timeOutSecs; } foreach (var param in parameters) { command.Parameters.AddWithValue(param.Key, param.Value); } command.Parameters.Add(outResult); conn.ExecuteCommand(command); return outResult.Value.ToString(); } }).ConfigureAwait(false)); }
public bool HasAccess(string accessDeviceId, int accessDeviceType, int locationId) { var command = _sqlConnection.CreateCommand(); command.CommandText = string.Format(@"select Id, PoolId from AccessControlList where AccessDevice = '{0}' and AccessDeviceType = {1} and LocationId = {2}", accessDeviceId, accessDeviceType, locationId); int?aclId = null; int?poolId = null; try { _sqlConnection.Open(); var reader = command.ExecuteReader(); if (reader.Read()) { aclId = reader.GetInt32(0); if (!reader.IsDBNull(1)) { poolId = reader.GetInt32(1); } } } catch (Exception e) { //either the number of retries specified in the policy is exceeded or there is another exception? throw e; } finally { _sqlConnection.Close(); } if (aclId == null) { return(false); } if (poolId == null) { return(true); } //check pool List <Pool> poolList = new List <Pool>(); try { _sqlConnection.Open(); var poolCommand = _sqlConnection.CreateCommand(); poolCommand.CommandText = string.Format(@" select p.Id, p.MaxAllowed, p.Occupied, p.Hard from Pool p where p.Id = {0}", poolId); using (var reader = poolCommand.ExecuteReader()) { while (reader.Read()) { poolList.Add(new Pool { Id = reader.GetInt32(0), MaxAllowed = reader.GetInt32(1), Occupied = reader.GetInt32(2), Hard = reader.GetBoolean(3) }); } } } catch (Exception e) { //either the number of retries specified in the policy is exceeded or there is another exception? throw e; } finally { _sqlConnection.Close(); } if (poolList.Any()) { var pool = poolList.Single(); if (pool.Hard && pool.MaxAllowed <= pool.Occupied) { return(false); } var updatePoolCommand = _sqlConnection.CreateCommand(); updatePoolCommand.CommandText = string.Format(@"Update Pool set Occupied= {0} where Id = {1}", ++pool.Occupied, pool.Id); try { _sqlConnection.Open(); updatePoolCommand.ExecuteNonQuery(); } catch (Exception e) { //either the number of retries specified in the policy is exceeded or there is another exception? throw e; } finally { _sqlConnection.Close(); } } return(true); }
public static void DropDatabase(string server, string db) { ConsoleUtils.WriteInfo("Dropping database {0}", db); using (ReliableSqlConnection conn = new ReliableSqlConnection( Configuration.GetConnectionString(server, MasterDatabaseName), SqlRetryPolicy, SqlRetryPolicy)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); // Determine if we are connecting to Azure SQL DB cmd.CommandText = "SELECT SERVERPROPERTY('EngineEdition')"; cmd.CommandTimeout = 60; int engineEdition = conn.ExecuteCommand<int>(cmd); // Drop the database if (engineEdition == 5) { // Azure SQL DB cmd.CommandText = string.Format("DROP DATABASE {0}", BracketEscapeName(db)); cmd.ExecuteNonQuery(); } else { cmd.CommandText = string.Format( @"ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE DROP DATABASE {0}", BracketEscapeName(db)); cmd.ExecuteNonQuery(); } } }
public static void ExecuteSqlScript(string server, string db, string schemaFile) { ConsoleUtils.WriteInfo("Executing script {0}", schemaFile); using (ReliableSqlConnection conn = new ReliableSqlConnection( Configuration.GetConnectionString(server, db), SqlRetryPolicy, SqlRetryPolicy)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); // Read the commands from the sql script file IEnumerable<string> commands = ReadSqlScript(schemaFile); foreach (string command in commands) { cmd.CommandText = command; cmd.CommandTimeout = 60; conn.ExecuteCommand(cmd); } } }
public void TextExecuteSimpleCommand() { SqlCommand command = (SqlCommand)connection.CreateCommand(); command.CommandText = "SELECT 1"; command.ExecuteNonQueryWithRetry(); }
protected override DbCommand CreateDbCommand() { return(_connection.CreateCommand()); }
public String GetSessionTracingId() { // using all default policies String commandText = "SELECT CONVERT(NVARCHAR(36), CONTEXT_INFO())"; String sessionTracingId; using (ReliableSqlConnection connection = new ReliableSqlConnection(connectionString)) { connection.Open(); using (SqlCommand sqlCommand = connection.CreateCommand()) { sqlCommand.CommandText = commandText; sessionTracingId = sqlCommand.ExecuteScalarWithRetry() as String; } } return sessionTracingId; }
private int RetrieveCountofTable() { int count = 0; using (ReliableSqlConnection connection = new ReliableSqlConnection(connectionString)) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "SELECT COUNT(*) FROM [SalesLT].[CustomerAddress]"; count = (int)command.ExecuteScalarWithRetry(); } connection.Close(); } return count; }
/// <summary> /// Creates and returns a <see cref="T:System.Data.Common.DbCommand"></see> object associated with the current connection. /// </summary> /// <returns>A <see cref="T:System.Data.Common.DbCommand"></see> object.</returns> protected override DbCommand CreateDbCommand() { return(ReliableConnection.CreateCommand()); }
private void DeleteCustomerAddress(int customerId, int addressId) { using (ReliableSqlConnection connection = new ReliableSqlConnection(connectionString)) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = "DELETE FROM [SalesLT].[CustomerAddress] WHERE [CustomerID] = @CustomerID AND [AddressID] = @AddressID"; command.Parameters.Add("@CustomerID", SqlDbType.Int).Value = customerId; command.Parameters.Add("@AddressID", SqlDbType.Int).Value = addressId; command.ExecuteNonQueryWithRetry(); } connection.Close(); } }
public AzureSqlCommand(ReliableSqlConnection reliableConnection) { this.command = reliableConnection.CreateCommand(); this.Connection = reliableConnection; }