SMO Restore Failed/Cannot Open Backup Device Error - winforms

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 ");
}

Related

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

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

Error when trying to create or edit a job step in SQL Server "The system cannot find the file specified."

I am using
Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64)
Developer Edition (64-bit) on Windows Server 2016 Standard 10.0 <X64> (Build 14393: )
The recent things I have done was creating a job that restores databases dynamically from a path, ran it and disabled it.
Afterwards, when I tried to add a new step I got this error:
The system cannot find the file specified
I can't find any errors in the SQL Server logs.
I am able to create jobs with T-SQL and able to run them.
The other similar question on stack overflow are not relevant to my issue.
Why am I getting this error suddenly?
This is the error copied from management studio:
The system cannot find the file specified.
Program Location:
at Microsoft.SqlServer.Dts.Runtime.Application.get_LogProviderInfos()
at Microsoft.DataTransformationServices.DTSExecUI.Controls.LoggingCtrl..ctor(IDTSExecViewManager treePanel)
at Microsoft.SqlServer.Management.SqlManagerUI.DTSJobSubSystemDefinition.InitializeControls()
at Microsoft.SqlServer.Management.SqlManagerUI.DTSJobSubSystemDefinition..ctor(CDataContainer dataContainer, IMessageBoxProvider messageProvider)
at Microsoft.SqlServer.Management.SqlManagerUI.JobStepSubSystems.CreateJobStepSubSystemSsis(AgentSubSystem agentSubSystem, CDataContainer dataContainer, JobStepData data, IMessageBoxProvider messageProvider)
at Microsoft.SqlServer.Management.SqlManagerUI.JobStepSubSystems.CreateJobStepSubSystem(AgentSubSystem agentSubSystem, CDataContainer dataContainer, JobStepData data, IMessageBoxProvider messageProvider, IServiceProvider serviceProvider)
at Microsoft.SqlServer.Management.SqlManagerUI.JobStepSubSystems..ctor(CDataContainer dataContainer, JobStepData data, IMessageBoxProvider messageProvider, IServiceProvider serviceProvider)
at Microsoft.SqlServer.Management.SqlManagerUI.JobStepProperties.get_SubSystems()
at Microsoft.SqlServer.Management.SqlManagerUI.JobStepProperties.FilterStepCombo(DatabaseEngineEdition engineEdition)
at Microsoft.SqlServer.Management.SqlManagerUI.JobStepProperties.InitializeStepCombo()
at Microsoft.SqlServer.Management.SqlManagerUI.JobStepProperties.InitializeData()
at Microsoft.SqlServer.Management.SqlManagerUI.JobStepProperties.OnInitialization()
at Microsoft.SqlServer.Management.SqlMgmt.ViewSwitcherControlsManager.SetView(Int32 index, TreeNode node)
at Microsoft.SqlServer.Management.SqlMgmt.ViewSwitcherControlsManager.SelectCurrentNode()
at Microsoft.SqlServer.Management.SqlMgmt.ViewSwitcherControlsManager.InitializeUI(ViewSwitcherTreeView treeView, ISqlControlCollection viewsHolder, Panel rightPane)
at Microsoft.SqlServer.Management.SqlMgmt.LaunchForm.InitializeForm(XmlDocument doc, IServiceProvider provider, ISqlControlCollection control)
at Microsoft.SqlServer.Management.SqlMgmt.LaunchForm..ctor(ISqlControlCollection control, IServiceProvider provider)
at Microsoft.SqlServer.Management.SqlManagerUI.JobSteps.OnDoubleClick(Object sender, MouseButtonDoubleClickedEventArgs args)
at Microsoft.SqlServer.Management.UI.Grid.GridControl.OnMouseButtonDoubleClicked(HitTestResult htArea, Int64 nRowIndex, Int32 nColIndex, Rectangle rCellRect, MouseButtons btn, GridButtonArea headerArea)
at Microsoft.SqlServer.Management.SqlManagerUI.SqlManagerUIDlgGrid.OnMouseButtonDoubleClicked(HitTestResult htArea, Int64 rowIndex, Int32 colIndex, Rectangle cellRect, MouseButtons btn, GridButtonArea headerArea)
at Microsoft.SqlServer.Management.UI.Grid.GridControl.OnMouseDown(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at Microsoft.SqlServer.Management.UI.Grid.GridControl.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(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.RunDialog(Form form)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
at Microsoft.SqlServer.Management.SqlMgmt.RunningFormsTable.RunningFormsTableImpl.ThreadStarter.StartThread()
The system cannot find the file specified.
Program Location:
at Microsoft.SqlServer.Dts.Runtime.Wrapper.ApplicationClass.get_LogProviderInfos()
at Microsoft.SqlServer.Dts.Runtime.Application.get_LogProviderInfos()
Thanks in advance.
Turns out it was some problem with SSMS.
I only noticed it when trying to edit a job step on another server.
When opening a new instance of SSMS, everything worked fine.

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>

Cannot connect to database during umbraco install

I have a clean project, which i am trying to get started. I have also created a clean database.
Both are running locally on my pc.
I can connect to my database with linqpad, with no issues.
But when i try to "customize" and set a microsoft SQL server, it says
Could not connect to database
And in console, i get a 500 internal server error, on :
:62164/install/api/PostValidateDatabaseConnection
What can i do ?
Edit
when trying to use a custom connection string, i get this :
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Umbraco.Web.Install.Controllers.InstallApiController.ExecuteStep(InstallSetupStep step, JToken instruction)
2017-09-12 09:16:22,389 [P1996/D2/T11] INFO Umbraco.Web.Install.Controllers.InstallApiController - Step completed (took 32ms)
2017-09-12 09:16:22,390 [P1996/D2/T11] ERROR Umbraco.Web.Install.Controllers.InstallApiController - An error occurred during installation step DatabaseConfigure
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Umbraco.Core.DatabaseContext.SaveConnectionString(String connectionString, String providerName)
at Umbraco.Core.DatabaseContext.ConfigureDatabaseConnection(String connectionString)
at Umbraco.Web.Install.InstallSteps.DatabaseConfigureStep.ConfigureConnection(DatabaseModel database)
at Umbraco.Web.Install.InstallSteps.DatabaseConfigureStep.Execute(DatabaseModel database)
--- End of inner exception stack trace ---
If, even with a custom connection string, you still get a 500 error I think that you have a botched installation and you should try to reinstall Umbraco from scratch

Error when exporting data from SQL server database

I try to export data-only from SQL server using task->generate scripts menu and get this following error. what does it mean? I'm not so familiar with this SQL server, so this bunch of text really confusing for me.
Microsoft.SqlServer.Management.SqlScriptPublish.SqlScriptPublishException: An error occurred while scripting the objects. ---> Microsoft.SqlServer.Management.Smo.SmoException: Cyclic dependencies found. at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.DependencyGraphTraversal(Int32 num, Dictionary`2 dictionary, List`1 sortedList, HashSet`1 visited, HashSet`1 current) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.DependencyGraphTraversal(Int32 num, Dictionary`2 dictionary, List`1 sortedList, HashSet`1 visited, HashSet`1 current) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.DependencyGraphTraversal(Int32 num, Dictionary`2 dictionary, List`1 sortedList, HashSet`1 visited, HashSet`1 current) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.SortDictionary(Dictionary`2 dictionary) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.SortDataSet(DataSet ds) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.SortDataSet(List`1 objectList, Dictionary`2 idDictionary, DataSet ds) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.ExecuteQueryUsingTempTable(List`1 objectList, List`1 list, String query) at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.ResolveTableOnlyDependencies() at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.ResolveDependencies() at Microsoft.SqlServer.Management.Smo.SmoDependencyOrderer.Order(IEnumerable`1 urns) at Microsoft.SqlServer.Management.Smo.ScriptMaker.DiscoverOrderScript(IEnumerable`1 urns) at Microsoft.SqlServer.Management.Smo.ScriptMaker.ScriptWorker(List`1 urns, ISmoScriptWriter writer) at Microsoft.SqlServer.Management.Smo.ScriptMaker.Script(Urn[] urns, ISmoScriptWriter writer) at Microsoft.SqlServer.Management.SqlScriptPublish.SqlScriptGenerator.DoScript(ScriptOutputOptions outputOptions) --- End of inner exception stack trace --- at Microsoft.SqlServer.Management.SqlScriptPublish.GeneratePublishPage.worker_DoWork(Object sender, DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
I suggest you to install Sql Server Management 2008 R2 to connect to your SQL Server 2008 instance.
In my case this solved the problem and I generated the script in this way.

Resources