C# backup of datatier database works fine in debug environment, but exceptions occur after release - sql-server

I now have the following code to backup the database
public class SqlServerBacpac
{
public static void Startup(ServerConfigOption option)
{
var connectionString = SqlClientHelper.BuildSqlConnectionString(option);
var fileName = option.Database + "_" + DateTime.Now.ToString(option.Format) + ".bacpac";
var filePath = Path.Combine(option.Folder, fileName);
var ds = new DacServices(connectionString);
ds.ExportBacpac(filePath, option.Database);
}
}
use nuget package
Microsoft.SqlServer.Dac
In debug environment, everything works fine
Posting a configuration file
However, the following problem occurred after the release
Unhandled exception. System.ArgumentException: The path is empty. (Parameter 'path')
at System.IO.Path.GetFullPath(String path)
at System.Diagnostics.FileVersionInfo.GetVersionInfo(String fileName)
at Microsoft.Data.Tools.Schema.Sql.Dac.DacOrigin.Operation.SetOperatingAssembly(Assembly assembly)
at Microsoft.Data.Tools.Schema.Sql.Dac.DacOrigin.Operation..ctor(Assembly executingAssembly)
at Microsoft.Data.Tools.Schema.Sql.Dac.DacOrigin..ctor(Assembly executingAssembly)
at Microsoft.SqlServer.Dac.DacServices.<>c__DisplayClass77_1.<CreateExportOperation>b__1()
at Microsoft.Data.Tools.Schema.Sql.Dac.OperationLogger.Capture(Action action)
at Microsoft.SqlServer.Dac.DacServices.<>c__DisplayClass77_0.<CreateExportOperation>b__0(Object operation, CancellationToken token)
at Microsoft.SqlServer.Dac.Operation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.OperationExtension.CompositeOperation.Microsoft.SqlServer.Dac.IOperation.Run(OperationContext context)
at Microsoft.SqlServer.Dac.OperationExtension.Execute(IOperation operation, DacLoggingContext loggingContext, CancellationToken cancellationToken)
at Microsoft.SqlServer.Dac.DacServices.ExportBacpac(Func`1 streamGetter, String databaseName, DacExportOptions exportOptions, IEnumerable`1 tables, CancellationToken cancellationToken)
at Microsoft.SqlServer.Dac.DacServices.ExportBacpac(String packageFileName, String databaseName, DacExportOptions options, IEnumerable`1 tables, Nullable`1 cancellationToken)
at Microsoft.SqlServer.Dac.DacServices.ExportBacpac(String packageFileName, String databaseName, DacSchemaModelStorageType modelStorageType, IEnumerable`1 tables, Nullable`1 cancellationToken)
at Microsoft.SqlServer.Dac.DacServices.ExportBacpac(String packageFileName, String databaseName, IEnumerable`1 tables, Nullable`1 cancellationToken)
at SqlServerBackup.SqlServerBacpac.Startup(ServerConfigOption option)
at Program.<<Main>$>g__RunOptions|0_1(ServerConfigOption opts)
at CommandLine.ParserResultExtensions.WithParsed[T](ParserResult`1 result, Action`1 action)
at Program.<Main>$(String[] args)
I want the release to be usable in any environment, not just an error

Related

Exception while reading from stream ---> System.IO.IOException

I use Postgresql-13 in my ASP MVC NET 6 project, occasionally, I face this issue below:
Npgsql.NpgsqlException (0x80004005): Exception while reading from stream ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.. ---> System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host. at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count) --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count) at Npgsql.Internal.NpgsqlReadBuffer.g__EnsureLong|41_0(NpgsqlReadBuffer buffer, Int32 count, Boolean async, Boolean readingNotifications) at Npgsql.Internal.NpgsqlReadBuffer.g__EnsureLong|41_0(NpgsqlReadBuffer buffer, Int32 count, Boolean async, Boolean readingNotifications) at Npgsql.Internal.NpgsqlConnector.RawOpen(SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt) at Npgsql.Internal.NpgsqlConnector.g__OpenCore|191_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt) at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) at Npgsql.ConnectorPool.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) at Npgsql.ConnectorPool.g__RentAsync|28_0(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlConnection.g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken) at Npgsql.NpgsqlConnection.Open() at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, CommandDefinition& command, Action2 paramReader) in /_/Dapper/SqlMapper.cs:line 2847 at Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition& command) in /_/Dapper/SqlMapper.cs:line 581 at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable1 commandTimeout, Nullable`1 commandType) in /_/Dapper/SqlMapper.cs:line 452
my ConnectionString to Postgresql-13 was:
"Server=xxx.xxx.xxx.xxx;Database=mydb;User ID=myuserid;Password=mypassword;Keepalive=30; Connection Idle Lifetime=300; Tcp Keepalive=true";
my postgresql.conf
shared_buffers = 256MB
and my sysctl.conf
kernel.shmmax=100663296
why did it happen?, what should I check?
Potential causes are:
Session had hit an inactivity timeout and was terminated. ==> You can try adding/changing CommandTimeout parameter to more than default of 30 seconds.
Connection used an authentication token, which had expired.
Database connection listener service had been restarted, possibly due to patching or automated code deployment. ==> You could add code to reconnect and run a simple "heartbeat" query like SELECT CURRENT_DATE;

"An unhandled exception occurred while processing the request" with ABP asp.net core 3.1

I have just set up the ABP code in the machine and when I run the web project, I am getting this issue.
An unhandled exception occurred while processing the request.
SocketException: No connection could be made because the target machine actively refused it.
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)
HttpRequestException: No connection could be made because the target machine actively refused it.
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)
Stack Query Cookies Headers Routing
SocketException: No connection could be made because the target machine actively refused it.
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)
Show raw exception details
HttpRequestException: No connection could be made because the target machine actively refused it.
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>+ConfiguredValueTaskAwaiter.GetResult()
System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, bool allowHttp2, CancellationToken cancellationToken)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>+ConfiguredValueTaskAwaiter.GetResult()
System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>+ConfiguredValueTaskAwaiter.GetResult()
System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>+ConfiguredValueTaskAwaiter.GetResult()
System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Polly.Retry.AsyncRetryEngine.ImplementationAsync<TResult>(Func<Context, CancellationToken, Task<TResult>> action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates<TResult> shouldRetryResultPredicates, Func<DelegateResult<TResult>, TimeSpan, int, Context, Task> onRetryAsync, int permittedRetryCount, IEnumerable<TimeSpan> sleepDurationsEnumerable, Func<int, DelegateResult<TResult>, Context, TimeSpan> sleepDurationProvider, bool continueOnCapturedContext)
Polly.AsyncPolicy<TResult>.ExecuteAsync(Func<Context, CancellationToken, Task<TResult>> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext)
Microsoft.Extensions.Http.PolicyHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
Volo.Abp.Http.Client.DynamicProxying.ApiDescriptionFinder.GetApiDescriptionFromServerAsync(HttpClient client, string baseUrl)
Volo.Abp.Http.Client.DynamicProxying.ApiDescriptionCache.GetAsync(string baseUrl, Func<Task<ApplicationApiDescriptionModel>> factory)
Volo.Abp.Http.Client.DynamicProxying.ApiDescriptionFinder.GetApiDescriptionAsync(HttpClient client, string baseUrl)
Volo.Abp.Http.Client.DynamicProxying.ApiDescriptionFinder.FindActionAsync(HttpClient client, string baseUrl, Type serviceType, MethodInfo method)
Volo.Abp.Http.Client.DynamicProxying.DynamicHttpProxyInterceptor<TService>.MakeRequestAsync(IAbpMethodInvocation invocation)
Volo.Abp.Http.Client.DynamicProxying.DynamicHttpProxyInterceptor<TService>.MakeRequestAndGetResultAsync<T>(IAbpMethodInvocation invocation)
Volo.Abp.Http.Client.DynamicProxying.DynamicHttpProxyInterceptor<TService>.GetResultAsync(Task task, Type resultType)
Volo.Abp.Http.Client.DynamicProxying.DynamicHttpProxyInterceptor<TService>.InterceptAsync(IAbpMethodInvocation invocation)
Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter<TInterceptor>.InterceptAsync<TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func<IInvocation, IInvocationProceedInfo, Task<TResult>> proceed)
Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous<TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo)
Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue<TResult>.ProceedAsync()
Volo.Abp.Validation.ValidationInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter<TInterceptor>.InterceptAsync<TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func<IInvocation, IInvocationProceedInfo, Task<TResult>> proceed)
Volo.Abp.AspNetCore.Mvc.Client.CachedApplicationConfigurationClient.<GetAsync>b__13_0()
Volo.Abp.Caching.DistributedCache<TCacheItem, TCacheKey>.GetOrAddAsync(TCacheKey key, Func<Task<TCacheItem>> factory, Func<DistributedCacheEntryOptions> optionsFactory, Nullable<bool> hideErrors, CancellationToken token)
Volo.Abp.AspNetCore.Mvc.Client.CachedApplicationConfigurationClient.GetAsync()
Volo.Abp.AspNetCore.Mvc.Client.RemoteLanguageProvider.GetLanguagesAsync()
Microsoft.AspNetCore.RequestLocalization.DefaultAbpRequestLocalizationOptionsProvider.GetLocalizationOptionsAsync()
Microsoft.AspNetCore.RequestLocalization.AbpRequestLocalizationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass5_1+<<UseMiddlewareInterface>b__1>d.MoveNext()
Volo.Abp.AspNetCore.MultiTenancy.MultiTenancyMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass5_1+<<UseMiddlewareInterface>b__1>d.MoveNext()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Volo.Abp.AspNetCore.Tracing.AbpCorrelationIdMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass5_1+<<UseMiddlewareInterface>b__1>d.MoveNext()
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Run projects in this order: *.IdentiyServer project, *.HttpApi.Host project and then *.Web project.

SQL Server Management Studio raises error when running a script

I try to seed database with data via script
I run it via SSMS
But when I start to execute it, I have this error
Here is Memory properties
How I can fix it?
Here is last data in Log
> <entry>
<record>177</record>
<time>2017/09/08 08:42:14.686</time>
<type>Error</type>
<source>Editor or Editor Extension</source>
<description>System.OutOfMemoryException: Exception of type &apos;System.OutOfMemoryException&apos; was thrown.
at System.String.CtorCharArray(Char[] value)
at Microsoft.VisualStudio.Text.Implementation.BinaryStringRebuilder.GetText(Span span)
at Microsoft.VisualStudio.Text.Implementation.TextSnapshot.GetText(Span span)
at Microsoft.VisualStudio.Text.SnapshotSpan.GetText()
at Microsoft.VisualStudio.Editor.Implementation.TextDocData.GetLineText(Int32 iStartLine, Int32 iStartIndex, Int32 iEndLine, Int32 iEndIndex, String& pbstrBuf)
at Microsoft.VisualStudio.Package.Source.GetText()
at Microsoft.VisualStudio.Package.Source.BeginParse(Int32 line, Int32 idx, TokenInfo info, ParseReason reason, IVsTextView view, ParseResultHandler callback)
at Microsoft.VisualStudio.Package.ViewFilter.GetDataTipText(TextSpan[] aspan, String& textValue)
at Microsoft.VisualStudio.Editor.Implementation.ShimQuickInfoSource.TryGetQuickInfoFromFilter(IQuickInfoSession session, TextSpan[] dataBufferTextSpan, String& tipText)
at Microsoft.VisualStudio.Editor.Implementation.ShimQuickInfoSource.AugmentQuickInfoSession(IQuickInfoSession session, IList`1 qiContent, ITrackingSpan& applicableToSpan)
at Microsoft.VisualStudio.Language.Intellisense.Implementation.QuickInfoSession.Recalculate()
at Microsoft.VisualStudio.Language.Intellisense.Implementation.QuickInfoSession.Start()
at Microsoft.VisualStudio.Language.Intellisense.Implementation.DefaultQuickInfoController.OnTextView_MouseHover(Object sender, MouseHoverEventArgs e)
at Microsoft.VisualStudio.Text.Editor.Implementation.WpfTextView.RaiseHoverEvents()</description>
</entry>

new SqlConnection throws argument exception "format of the initialisation string does not conform"

Trying my hand at aspnet5 with a console application using the full framework. The application is going to use Dapper to make a SQL query but when instantiating the SqlConnection object I get the following error:
System.ArgumentException: Format of the initialization string does not conform to specification starting at index 13.
at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)
at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)
at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)
at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key)
at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString, SqlCredential credential)
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at Program.Main(String[] args) in C:\Users\me\Source\ASPNET5\SysAid SLA Alarm\program.cs:line 10
If I remove the \ from the server attribute then it executes fine but clearly fails because of the incorrect name and reports sql instance not found. The offending line of code looks like this:
using(IDbConnection db = new SqlConnection("Server=server\instance;Database=db;Trusted_Connection=True"))
And to be complete this is my project.json:
{
"version": "1.0.0-*",
"dependencies": {
},
"commands": {
"ConsoleApp": "ConsoleApp"
},
"frameworks" : {
"dnx451": {
"dependencies": {
"System.Data.Common": "4.0.1-beta-*",
"Dapper": "1.50.0-beta5"
}
}
}
}
My next line of attack was to get the source for System.Data and see what's going on. Anyone spot a mistake I'm making in the above?
Give this a shot - just using \ as a literal with #
using(IDbConnection db = new SqlConnection(#"Server=server\instance;Database=db;Trusted_Connection=True"))

SMO Restore Failed/Cannot Open Backup Device Error

I got an error while I'm trying to restore a SQL Server 2008 R2 database:
Restore failed for Server 'KIMO-PC'.
Code used:
Server myServer = new Server("KIMO-PC");
Database myDatabase = new Database(myServer, "POS");
Restore restoreDB = new Restore();
restoreDB.Database = myDatabase.Name;
restoreDB.Action = RestoreActionType.Database;
restoreDB.Devices.AddDevice(FileName, DeviceType.File);
restoreDB.ReplaceDatabase = false;
restoreDB.NoRecovery = true;
restoreDB.PercentComplete += CompletionStatusInPercent;
restoreDB.Complete += Restore_Completed;
restoreDB.SqlRestore(myServer);
and here is the exception details
Microsoft.SqlServer.Management.Smo.FailedOperationException was unhandled HelpLink=http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600.1+((KJ_RTM).100402-1540+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476 Message=Restore failed for Server 'KIMO-PC'.
Source=Microsoft.SqlServer.SmoExtended Operation=Restore
StackTrace: at Microsoft.SqlServer.Management.Smo.Restore.SqlRestore(Server srv) at ICS.Forms.frmRestore.Restoredb(String FileName)
in D:\POS\POS\POS\Database\RestoreDB.cs:line 56 at ICS.Forms.frmRestore.btnBackup_Click(Object sender, EventArgs e)
in D:\POS\POS\POS\Database\RestoreDB.cs:line 35 at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.PerformClick()
at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm) at POS.Program.Main() in D:\POS\POS\POS\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()
InnerException: Microsoft.SqlServer.Management.Smo.SmoException HelpLink=http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600.1+((KJ_RTM).100402-1540+)&LinkId=20476
Message=System.Data.SqlClient.SqlError: Cannot open backup device 'C:\Users\kimo\Desktop\POS.bak'. Operating system error 5(failed to retrieve text for this error. Reason: 15100).
Source=Microsoft.SqlServer.Smo StackTrace:
at Microsoft.SqlServer.Management.Smo.ExecutionManager.ExecuteNonQueryWithMessage(StringCollection queries, ServerMessageEventHandler dbccMessageHandler, Boolean errorsAsMessages)
at Microsoft.SqlServer.Management.Smo.BackupRestoreBase.ExecuteSql(Server server, StringCollection queries)
at Microsoft.SqlServer.Management.Smo.Restore.SqlRestore(Server srv) InnerException
Take a look at the stack trace inner exception:
Cannot open backup device 'C:\Users\kimo\Desktop\POS.bak'. Operating
system error 5
Most likely, the SQL Server does not have rights to view files in kimo\Desktop. Move the backup to a different folder like c:\temp and try it again.
Try this:
Database currentDb = srvsql.Databases["dbname"];// get the current database
if (currentDb != null)
{
Connection.ChangeDatabase("dbname");
//Stop all processes running on the DataBase database
server.KillAllProcesses("dbname ");
}

Resources