本文整理汇总了C#中ServerConnection.Disconnect方法的典型用法代码示例。如果您正苦于以下问题:C# ServerConnection.Disconnect方法的具体用法?C# ServerConnection.Disconnect怎么用?C# ServerConnection.Disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ServerConnection
的用法示例。
在下文中一共展示了ServerConnection.Disconnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExecuteSqlScript
private static bool ExecuteSqlScript(string connectionString, string databaseName, string script)
{
bool scriptSucceeded = false;
var connection = new ServerConnection();
connection.ConnectionString = connectionString;
connection.StatementTimeout = 3600;
connection.Connect();
Server sqlServer = new Server(connection);
Database dbTarget = sqlServer.Databases[databaseName];
if (dbTarget != null)
{
connection.BeginTransaction();
try
{
dbTarget.ExecuteNonQuery(script);
connection.CommitTransaction();
scriptSucceeded = true;
}
catch (Exception ex)
{
connection.RollBackTransaction();
throw new Exception("Failed to execute script", ex);
}
finally
{
connection.Disconnect();
}
}
return scriptSucceeded;
}
示例2: RestoreDatabase
public void RestoreDatabase(SqlConnectionStringBuilder sqlConnection, String backUpFile)
{
ServerConnection serverConnection = null;
try
{
if (!FileManager.FileExists(backUpFile))
{
throw new FileNotFoundException();
}
serverConnection = new ServerConnection(sqlConnection.DataSource, sqlConnection.UserID, sqlConnection.Password);
Server sqlServer = new Server(serverConnection);
Restore restoreDatabase = new Restore()
{
Action = RestoreActionType.Database,
Database = sqlConnection.InitialCatalog,
};
BackupDeviceItem backupItem = new BackupDeviceItem(backUpFile, DeviceType.File);
restoreDatabase.Devices.Add(backupItem);
restoreDatabase.ReplaceDatabase = true;
restoreDatabase.SqlRestore(sqlServer);
}
finally
{
if (serverConnection != null && serverConnection.IsOpen)
{
serverConnection.Disconnect();
}
}
}
示例3: BackupDatabase
public static void BackupDatabase(string backUpFile)
{
ServerConnection con = new ServerConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\works\Work\.Net\Divan\Divan\bin\Debug\Database.mdf;Integrated Security=True;Connect Timeout=30");
Server server = new Server(con);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = "divan";
BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
source.Devices.Add(destination);
source.SqlBackup(server);
con.Disconnect();
}
示例4: BackupDatabase
public static void BackupDatabase(string backUpFile)
{
ServerConnection con = new ServerConnection(Constants.DatabaseServerName);
Server server = new Server(con);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = Constants.DatabaseName;
BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
source.Devices.Add(destination);
source.SqlBackup(server);
con.Disconnect();
}
示例5: BackupDatabase
public static void BackupDatabase(string backUpFile)
{
ServerConnection con = new ServerConnection(@"YasarMalik-PC\SQLEXPRESS");
Server server = new Server(con);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = "AQSMS";
BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
source.Devices.Add(destination);
source.SqlBackup(server);
con.Disconnect();
}
示例6: BackupDatabase
/// <summary>
/// Backups the Database.
/// </summary>
/// <param name="sqlConnection">
/// The SQL connection of the database to be backup.
/// </param>
/// <param name="destinationPath">
/// The backup file path.
/// </param>
public static void BackupDatabase(SqlConnection sqlConnection, string destinationPath)
{
if (sqlConnection == null)
throw new ArgumentNullException("sqlConnection", "The sql connection cannot be null.");
if (string.IsNullOrWhiteSpace(destinationPath))
throw new ArgumentException("A valid back up file name is required.");
if (Path.IsPathRooted(destinationPath))
{
string directoryName = destinationPath.Substring(0, destinationPath.LastIndexOf('\\'));
if (!Directory.Exists(directoryName))
Directory.CreateDirectory(directoryName);
}
var serverConnection = new ServerConnection(sqlConnection);
var server = new Server(serverConnection);
var backup =
new Backup
{
Action = BackupActionType.Database,
BackupSetDescription = string.Format("ArchiveDataBase: {0}", DateTime.Now.ToShortDateString()),
BackupSetName = sqlConnection.Database,
Database = sqlConnection.Database,
Initialize = true,
Checksum = true,
ContinueAfterError = true,
Incremental = false
};
var deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
backup.Devices.Add(deviceItem);
backup.SqlBackup(server);
backup.Devices.Remove(deviceItem);
serverConnection.Disconnect();
}
示例7: BackupDatabase
public void BackupDatabase(SqlConnectionStringBuilder sqlConnection, string destinationPath)
{
ServerConnection serverConnection = null;
try
{
serverConnection = new ServerConnection(sqlConnection.DataSource, sqlConnection.UserID, sqlConnection.Password);
Server sqlServer = new Server(serverConnection);
Backup backupDatabase = new Backup()
{
Action = BackupActionType.Database,
Database = sqlConnection.InitialCatalog,
};
BackupDeviceItem backupItem = new BackupDeviceItem(destinationPath, DeviceType.File);
backupDatabase.Devices.Add(backupItem);
backupDatabase.SqlBackup(sqlServer);
}
finally
{
if (serverConnection != null && serverConnection.IsOpen)
{
serverConnection.Disconnect();
}
}
}
示例8: MakeBackup
public static bool MakeBackup(ServerMessageEventHandler onComplete, Guid id, int experimentNumber,
string serverName, string dbName, string uncDir, string userName, string password)
{
bool result = false;
try
{
var sc = new ServerConnection(serverName);
try
{
sc.LoginSecure = false;
sc.Login = userName;
sc.Password = password;
var srv = new Server(sc);
var bkp = new Backup();
bkp.Action = BackupActionType.Database;
bkp.Database = dbName;
bkp.BackupSetName = id.ToString();
bkp.BackupSetDescription = string.Format("VisLab auto-backup (experiment N{0}).", experimentNumber);
bkp.Devices.AddDevice(Path.Combine(uncDir, bkp.Database + ".bak"), DeviceType.File);
bkp.Incremental = false;
if (onComplete != null) bkp.Complete += onComplete;
bkp.SqlBackup(srv);
result = true;
}
finally
{
sc.Disconnect();
}
}
catch { }
return result;
}
示例9: MakeRestore
public static bool MakeRestore(ServerMessageEventHandler onComplete, Guid id,
string serverName, string dbName, string uncDir, string userName, string password)
{
bool result = false;
try
{
var sc = new ServerConnection(serverName);
try
{
sc.LoginSecure = false;
sc.Login = userName;
sc.Password = password;
var srv = new Server(sc);
var rest = new Restore();
rest.Action = RestoreActionType.Database;
rest.Database = dbName;
rest.Devices.AddDevice(Path.Combine(uncDir, rest.Database + ".bak"), DeviceType.File);
rest.ReplaceDatabase = true;
var headers = rest.ReadBackupHeader(srv);
var query = from DataRow row in headers.Rows
where (string)row["BackupName"] == id.ToString()
select (Int16)row["Position"];
rest.FileNumber = query.First();
if (onComplete != null) rest.Complete += onComplete;
rest.SqlRestore(srv);
result = true;
}
finally
{
sc.Disconnect();
}
}
catch { }
return result;
}
示例10: CreateDatabase
public static void CreateDatabase(Identifier claimedId, string friendlyId, string databaseName) {
const string SqlFormat = @"
{0}
GO
EXEC [dbo].[AddUser] 'admin', 'admin', '{1}', '{2}'
GO
";
var removeSnippets = new string[] { @"
IF IS_SRVROLEMEMBER(N'sysadmin') = 1
BEGIN
IF EXISTS (SELECT 1
FROM [master].[dbo].[sysdatabases]
WHERE [name] = N'$(DatabaseName)')
BEGIN
EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
SET HONOR_BROKER_PRIORITY OFF
WITH ROLLBACK IMMEDIATE';
END
END
ELSE
BEGIN
PRINT N'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
END
GO" };
string databasePath = HttpContext.Current.Server.MapPath("~/App_Data/" + databaseName + ".mdf");
StringBuilder schemaSqlBuilder = new StringBuilder();
using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(DefaultNamespace + ".CreateDatabase.sql"))) {
schemaSqlBuilder.Append(sr.ReadToEnd());
}
foreach (string remove in removeSnippets) {
schemaSqlBuilder.Replace(remove, string.Empty);
}
schemaSqlBuilder.Replace("$(Path1)", HttpContext.Current.Server.MapPath("~/App_Data/"));
schemaSqlBuilder.Replace("WEBROOT", databasePath);
schemaSqlBuilder.Replace("$(DatabaseName)", databaseName);
string sql = string.Format(CultureInfo.InvariantCulture, SqlFormat, schemaSqlBuilder, claimedId, "Admin");
var serverConnection = new ServerConnection(".\\sqlexpress");
try {
serverConnection.ExecuteNonQuery(sql);
} finally {
try {
var server = new Server(serverConnection);
server.DetachDatabase(databaseName, true);
} catch (FailedOperationException) {
}
serverConnection.Disconnect();
}
}
示例11: Run
//.........这里部分代码省略.........
throw new System.ArgumentException("Specify either a partition number OR a partition range value");
}
// Construct a staging table name likely to be unique, if no name is provided
String stagingTblName = parsedArgs.StagingTable;
if (stagingTblName == null)
{
stagingTblName = partitionTblName + "_part" + partitionNumber.ToString("####", System.Globalization.CultureInfo.InvariantCulture)
+ partitionRangeValue + "_" + System.DateTime.Now.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
bool keepStaging = parsedArgs.Keep;
PartitionManager pm = null;
System.IO.StreamWriter scriptWriter = null;
if ((scriptOption == "i" || scriptOption == "o")
&& parsedArgs.ScriptFile != null)
{
try
{
scriptWriter = new System.IO.StreamWriter(parsedArgs.ScriptFile, true, Encoding.Unicode);
}
catch (System.IO.IOException ex)
{
Console.WriteLine(ex.Message, ex.Source);
Console.WriteLine("Output will be sent to console instead");
}
}
using (scriptWriter)
{
// Call appropriate Partition Manager constructor depending on whether a partition number or range value is provided
if (partitionNumber != 0)
{
pm = new PartitionManagement.PartitionManager(sc, dbName, schName, partitionTblName,
stagingTblName, partitionNumber, scriptWriter, executeCommands);
}
else
{
pm = new PartitionManagement.PartitionManager(sc, dbName, schName, partitionTblName,
stagingTblName, partitionRangeValue, scriptWriter, executeCommands);
}
pm.SetTransactionIsolationLevelReaduncommitted();
switch (command)
{
case "clearpartition":
pm.CreateStgTable();
pm.CreateStgFkeys();
pm.CreateStgChecks();
pm.CreateStgPartitionCheck();
// If staging table is being deleted, no need to create non-clustered indexes & views
pm.CreateStgIndexes(keepStaging);
pm.ClearPartition(keepStaging);
if (generateScript) pm.outputScript();
break;
case "createstagingfull":
pm.CreateStgTable();
pm.CreateStgFkeys();
pm.CreateStgChecks();
pm.CreateStgPartitionCheck();
pm.CreateStgIndexes(true);
if (generateScript) pm.outputScript();
break;
case "createstagingclusteredindex":
pm.CreateStgTable();
pm.CreateStgFkeys();
pm.CreateStgChecks();
pm.CreateStgPartitionCheck();
pm.CreateStgIndexes(false);
if (generateScript) pm.outputScript();
break;
case "createstagingnoindex":
pm.CreateStgTable();
pm.CreateStgFkeys();
pm.CreateStgChecks();
pm.CreateStgPartitionCheck();
if (generateScript) pm.outputScript();
break;
case "indexstaging":
pm.CreateStgIndexes(true);
if (generateScript) pm.outputScript();
break;
default:
throw new System.InvalidOperationException("Invalid command choice\nCommand Choices: ClearPartition | CreateStagingFull | CreateStagingClusteredIndex | CreateStagingNoindex | IndexStaging");
}
}
}
catch (Exception e)
{
sc.Disconnect();
sc = null;
Console.WriteLine(e);
throw e;
}
sc.Disconnect();
sc = null;
}
示例12: BackupDatabase
//------------------------Back up/Restore---------------------------------------------------
public void BackupDatabase(string backUpFile)
{
ServerConnection serverConnection = new ServerConnection(@"ROHAN-PC\SQLEXPRESS");
Server myServer = new Server(serverConnection);
Backup source = new Backup();
source.Action = BackupActionType.Database;
source.Database = "RecordKeeper";
BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
source.Devices.Add(destination);
source.SqlBackup(myServer);
serverConnection.Disconnect();
}
示例13: ReinitializeSubscriptionWithUpload
public void ReinitializeSubscriptionWithUpload()
{
MergeSynchronizationAgent syncAgent;
try
{
// Make the connection and get the subscription properties.
subscriberConn = new ServerConnection(subscriberServer);
subscriberConn.Connect();
}
catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
{
ExceptionMessageBox emb = new ExceptionMessageBox(
Properties.Resources.ExceptionCannotConnectLocal,
Properties.Resources.ExceptionSqlServerError,
ExceptionMessageBoxButtons.OK);
emb.InnerException = ex;
emb.Show(this);
// Shutdown the application because we can't continue.
Application.Exit();
}
mergePullSub = new MergePullSubscription();
// Set the properties needed to get the subscription.
mergePullSub.ConnectionContext = subscriberConn;
mergePullSub.PublicationName = publicationName;
mergePullSub.PublisherName = publisherServer;
mergePullSub.PublicationDBName = publicationDatabase;
mergePullSub.DatabaseName = subscriptionDatabase;
// Load the properties of the existing subscription.
if (!mergePullSub.LoadProperties())
{
throw new ApplicationException(
Properties.Resources.ExceptionProblemLocalData
+ Environment.NewLine
+ Properties.Resources.ExceptionContactTechSupport);
}
// Check to make sure that the Merge Agent isn't already running.
if (mergePullSub.LastAgentStatus
!= (ReplicationStatus.Running | ReplicationStatus.Starting))
{
// Mark the subscription for reinitialization after uploading.
mergePullSub.Reinitialize(true);
// Get the Merge Agent for synchronous execution.
syncAgent = mergePullSub.SynchronizationAgent;
// Define the event handler.
syncAgent.Status
+= new AgentCore.StatusEventHandler(Sync_Status);
syncAgent.Output = outputLogFile;
syncAgent.OutputVerboseLevel = outputLevel;
// Start the Merge Agent Job.
try
{
currentStatusTextBox.Text = statusReinitialize
+ Environment.NewLine;
syncAgent.Synchronize();
}
catch (Exception ex)
{
throw new ApplicationException(
Properties.Resources.ExceptionCouldNotReInit
+ Environment.NewLine
+ Properties.Resources.ExceptionContactTechSupport, ex);
}
finally
{
statusProgressBar.Value = 100;
closeButton.Enabled = true;
subscriberConn.Disconnect();
}
}
else
{
currentStatusTextBox.Text
= Properties.Resources.StatusSubscriptionAlreadySync;
closeButton.Enabled = true;
}
}
示例14: SynchronizeSubscriptionUploadOnly
public void SynchronizeSubscriptionUploadOnly()
{
MergeSynchronizationAgent syncAgent;
try
{
// Make the connection and get the subscription properties.
subscriberConn = new ServerConnection(subscriberServer);
subscriberConn.Connect();
}
catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
{
ExceptionMessageBox emb = new ExceptionMessageBox(
Properties.Resources.ExceptionCannotConnectLocal,
Properties.Resources.ExceptionSqlServerError,
ExceptionMessageBoxButtons.OK);
emb.InnerException = ex;
emb.Show(this);
// Shutdown the application because we can't continue.
Application.Exit();
}
mergePullSub = new MergePullSubscription();
// Set the properties needed to get the subscription.
mergePullSub.ConnectionContext = subscriberConn;
mergePullSub.PublicationName = publicationName;
mergePullSub.PublisherName = publisherServer;
mergePullSub.PublicationDBName = publicationDatabase;
mergePullSub.DatabaseName = subscriptionDatabase;
// Load the properties of the existing subscription.
if (!mergePullSub.LoadProperties())
{
throw new ApplicationException(
Properties.Resources.ExceptionProblemLocalData
+ Environment.NewLine
+ Properties.Resources.ExceptionContactTechSupport);
}
// Get the Merge Agent for synchronous execution.
syncAgent = mergePullSub.SynchronizationAgent;
// Specify an upload-only exchange type.
syncAgent.ExchangeType = MergeExchangeType.Upload;
// Generate a troubleshooting log file.
syncAgent.Output = outputLogFile;
syncAgent.OutputVerboseLevel = outputLevel;
// Define the event handler.
syncAgent.Status += new AgentCore.StatusEventHandler(Sync_Status);
// Start the Merge Agent Job.
try
{
syncAgent.Synchronize();
}
catch (Exception ex)
{
statusProgressBar.Value = 0;
throw new ApplicationException(
Properties.Resources.ExceptionMergeAgentFailedSync,
ex);
}
finally
{
closeButton.Enabled = true;
subscriberConn.Disconnect();
}
}
示例15: CreateSubscription
//.........这里部分代码省略.........
Subscriber = new ReplicationServer(subscriberConn);
insertUpdateHandler = new BusinessLogicHandler();
insertUpdateHandler.FriendlyName = handlerFriendlyName;
insertUpdateHandler.DotNetAssemblyName = "BusinessLogic.dll";
insertUpdateHandler.DotNetClassName = "Microsoft.Samples.SqlServer.CustomBusinessLogicHandler";
insertUpdateHandler.IsDotNetAssembly = true;
try
{
// Create the pull subscription.
currentStatusTextBox.Text += statusCreateSubscription
+ Environment.NewLine;
Application.DoEvents();
mergePullSub.Create();
mergePullSub.Refresh();
// Get the Merge Agent for synchronous execution.
syncAgent = mergePullSub.SynchronizationAgent;
// We have to set these because of an RMO bug.
// Remove for RTM.
syncAgent.DistributorSecurityMode = SecurityMode.Integrated;
syncAgent.PublisherSecurityMode = SecurityMode.Integrated;
syncAgent.SubscriberSecurityMode = SecurityMode.Integrated;
// Generate a troubleshooting log file.
syncAgent.OutputVerboseLevel = outputLevel;
syncAgent.Output = outputLogFile;
// Define the event handler.
syncAgent.Status
+= new AgentCore.StatusEventHandler(Sync_Status);
currentStatusTextBox.Text += statusInitialize
+ Environment.NewLine;
Application.DoEvents();
// Start the Merge Agent synchronously to apply the initial snapshot.
syncAgent.Synchronize();
// Make sure that the initialization was successful.
mergePullSub.Refresh();
if (mergePullSub.LastAgentStatus
!= ReplicationStatus.Succeeded)
{
throw new SubscriptionInitializationException(
Properties.Resources.ExceptionSubscriptionNotSync);
}
currentStatusTextBox.Text += statusSuccess.ToString()
+ Environment.NewLine;
statusProgressBar.Value = 100;
}
catch (Exception ex)
{
currentStatusTextBox.Text += statusFail.ToString()
+ Environment.NewLine;
statusProgressBar.Value = 0;
// If an exception occurs, undo subscription registration at both
// the Publisher and Subscriber and remove the handler registration.
mergePullSub.Remove();
if (isRegistered)
{
Subscriber.UnregisterBusinessLogicHandler(insertUpdateHandler);
isRegistered = false;
}
throw new SubscriptionCreationException(
Properties.Resources.ExceptionSubscriptionNotCreated,
ex);
}
finally
{
closeButton.Enabled = true;
subscriberConn.Disconnect();
//publisherConn.Disconnect();
}
}
else
{
// If we can't create the subscription, close the application.
ExceptionMessageBox emb = new ExceptionMessageBox(
Properties.Resources.ExceptionSubscriptionNotCreated);
emb.Buttons = ExceptionMessageBoxButtons.RetryCancel;
DialogResult drRetry = emb.Show(this);
if (drRetry == DialogResult.Retry)
{
this.CreateSubscription();
}
else
{
Application.Exit();
}
}
}