No Access to an mdb database file after copying the file - vb.net

I have the following code where I make an copy of my database that I use. the code executes 100% but the problem I have is I'm not able to access my database afterward.I get a "Cannot start your application. The workgroup information file is missing or opened exclusively by another user." and so if I restart the application it all works fine again.
I'm certain the reason is because I can only access that database using a specific account name and password which is not account I'm logged in with.
What i want to try is to default that database mdb to the point where no user is accessing it, or to reassign the the only account name that can access it to that database mdb.
Any ideas, will be enormously appreciated? I've tried playing around with file security but had no luck.
Private Sub cmdBackup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBackup.Click
BackupDialogDB.DefaultExt = ".mdb"
BackupDialogDB.InitialDirectory = "c:\"
'SaveFileDialog1.ShowDialog()
If BackupDialogDB.ShowDialog() = Windows.Forms.DialogResult.OK Then
Try
Dim sDBFile As String = Application.StartupPath + "\VFMS_DB.mdb"
Dim sBackUpFile As String = BackupDialogDB.FileName
'First check the file u want to compact exists or not
If File.Exists(sDBFile) Then
If Not File.Exists(sBackUpFile) Then
File.Copy(sDBFile, sBackUpFile)
Else
File.Delete(sBackUpFile)
File.Copy(sDBFile, sBackUpFile)
End If
MessageBox.Show("The database was successfully backedup to: " + sBackUpFile , "Database Backedup", MessageBoxButtons.OK, MessageBoxIcon.Information)
sDBFile = ""
Else
MessageBox.Show("There is no database to backup. Please restore from a backup", "Database Backup Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub

You should also copy and/or restore the workgroup information file.

Do you have write permission in the target directory? Access needs to create a .ldb file along side the .mdb.
Otherwise, you can try some of the stuff here:
http://www.xlinesoft.com/asprunnerpro/docs/error_the_microsoft_jet_database_engine_cannot%20open%20the%20file%20(unknown).htm

Was the Database open when you copied it? Access creates lock files, *.ldb in the same directory the database is in, you might want to check for that file before you copy the database.

Related

access is denied exception when using Process.Start("excel.exe",FileName) to open an excel file

We have a winforms application written in VB.Net that creates an excel file from a grid in the user's temporary folder and then opens the newly created file in Excel. This code has started to fail for one user only who gets an "access is denied" error when the application tries to open the newly created file in Excel.
If the user navigates to the temporary folder and double clicks on the newly created file it opens in Excel. The users of this application all belong to a domain and this behaviour has only recently started for one user running Windows10.
The code used is as below
Private Sub btnExportExcel_Click(sender As System.Object, e As System.EventArgs) Handles btnExportExcel.Click
If MsgBox("Export details to excel spreadsheet?", MsgBoxStyle.OkCancel + MsgBoxStyle.Question) = MsgBoxResult.Ok Then
Cursor = Windows.Forms.Cursors.WaitCursor
Dim lcFileName As String = String.Format("{0}{1}.xlsx", System.IO.Path.GetTempPath(), Guid.NewGuid())
PivotGridControl1.ExportToXlsx(lcFileName)
Process.Start("EXCEL.EXE", lcFileName)
Cursor = Windows.Forms.Cursors.Default
End If
End Sub
Tia Andy
Is the local machine properly in the domain? The users might be, but I have seen process errors when the local PC is not part of the domain, or in a different AD group. Check the machine permissions to the temporary folder - when he double-clicks on the Excel file it is definitely his process, but that is not necessarily the case here.

How do I create an Azure SQL Database copy during runtime?

I am new to VB.NET and Azure SQL services and I have spent the last 3 days searching for an answer and cannot come up with an answer I can truly understand. Here is my scenario and problem:
I have a VB.NET application where a user will log into their account and have their own set of tables under their own Azure SQL Database. I would like my program to automatically create their database for them (using their own selected name), which would be a database copy of an existing empty Database in Azure.
I can already access the data tables in my master database, but I do not know how to make a copy of it from my program during runtime. When I run my application and it debugs the following snippit of code, I get an exception error saying "You must be logged into the master database" I'm not sure how to resolve that error from popping up as I am using the master admin account in my normal SQL connection string.
Private Sub BtnActivate_Click(sender As Object, e As RoutedEventArgs)
If passwrd1.Password <> passwrd2.Password Then
MsgBox("Password doesn't match Confirm Password.", vbOKOnly)
Else
Dim commandString = "CREATE DATABASE " & dbname.Text & " AS COPY OF DBDEV;"
Using connection As New SqlConnection(My.Settings.DBDEVConnectionString)
Dim command As New SqlCommand(commandString, connection)
Try
connection.Open()
command.ExecuteNonQuery()
MsgBox("DATABASE SETUP. USE " & dbname.Text & "AS DBNAME TO CONNECT TO")
Catch ex As Exception
Throw ex
End Try
End Using
End If
End Sub
Please help, I've been moving nowhere and everything I'm searching for doesn't give me a clear answer to this simple scenario.
After many attempts, I solved the problem: in my connection string, I had the initial catalog default to my database and so I changed it to say "master" (even though I don't have a database named master) and it performed the Database copy for me. Woohoo!

OpenFileDialog locks the file when trying to get the name of a sql database that it was open before in VB.NET Windows Form

I have a sub in which I open sql databases through a OpenFileDialog. The problem arises when I try to re-open a database it was open before. Let me put an example:
I first open the database "mydatabase.mdf" -> Result OK
Then I open a second database "Seconddatabase.mdf" -> Result OK
Now, when I try to re-open "mydatabase.mdf", OpenFileDialog triggers an error and say "This file is being used. Write another name". Well, the message is not this,this is my translation into English, because in my system it is in Spanish "Este archivo está en uso. Escriba un nuevo nombre o cierre el archivo abierto en otro programa".
Well, the problem I am absolutely sure is caused by OpenFileDialog, because if I try the same process with an SaveFileDialog there is no file locking and I can open and reopen the database, but it's not a solution because the Dialog says the user to save file, not open.
I did another check by inserting a button control in which I re-open the first database hard-coded and it works, so the problem is in OpenFileDialog.
This is my code, but the code is not the problem (I think):
Private Sub AbrirBaseDados()
Dim fildia As New OpenFileDialog
If fildia.ShowDialog() Then
Try
If fildia.FileName <> vbNullString Then
pathBaseDados = (fildia.FileName)
CadenaConexion = "Data Source=(LocalDB)\v11.0;AttachDbFilename=" & pathBaseDados & ";Integrated Security=True;Connect Timeout=30"
End If
Catch ex As Exception
End Try
Desconectar()
fildia.Dispose()
End If
End Sub
The sub doesn't throw an exception, it's just OpenDialogFile telling me that the file is being used and not allowing me to get the name of the file I want to open. Because ALL I WANT TO KNOW is the name of the file of the db that the user specifies, because knowing the name I can open it without problem.
Thank you very much in advance.
Mdf is database file, not an ordinary file.
If you want to perform read write operations on database then read some tutorials first:
ADO.NET Examples
If you just want to get the names of database files from a given directory then use:
Dim filePaths As String() = Directory.GetFiles(YourFolderPath, "*.mdf")
Edit:
Use openFileDialog.ValidateNames = False:
Dim fildia As New OpenFileDialog
fildia.ValidateNames = False

Distribute database on end user machine

I have a little desktop application using a *.db3 database. When I run the application on other machine than mine, the database cannot be found: an absolute path is used.
Currently, in my App.Config file, I have
connectionStrings>
add name="MyProject.My.MySettings.MyProjectSQLiteConnectionString"
connectionString="data source="N:\Long path do my DB\MyDB.db3""
providerName="System.Data.SQLite" />
/connectionStrings>
I would like to replace the data source with something like this (unfortunately not working)
data source =|DataDirectory|\MyDB.db3
How can I enter the application directory (relative path) in my connection string?
Starting with Steve B's comment and later finding this article, I solved my problem doing the following:
On the user machine, the database is copied into the %AppData% directory.
The |DataDirectory| is dynamically changed between Debug and Release mode.
This allows not to change the connection string.
In the meantime, I opted for a MS Access *.accdb database, but here is my code anyway.
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
#If (Not Debug) Then
pathMyAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MyApp"
'"DataDirectory" is used in the Connection String
AppDomain.CurrentDomain.SetData("DataDirectory", pathMyAppData)
'The application closes if no database is found
If Not File.Exists(pathMyAppData & "\MyDB.accdb) Then
MsgBox("Database not found. Program closes.", MsgBoxStyle.Critical, "Error")
Me.Close()
End If
#End If

IDatabaseCompact.Compact() on an used IWorkspace

I am writting an ArcMap-AddIn with vb.net. I got an error when trying to compact my IWorkspace(mdb), the error is:
COMException
You tried to open a database, which was already opened by the user
'ADMIN' on Computer 'XXXXXX'. Try it again when the database is
available.
On ESRI.ArcGIS.Geodatabase.IDatabaseCompact.Compact() on
MyProject.MyClass.CompactGDB(IWorkspace pWS)
How can i compact the used workspace?
There are 8 other functions which also used my workspace.
Any suggestions?
The Code:
' CompactGDB
Public Sub CompactGDB(ByVal pWS As IWorkspace)
Dim pDatabaseCompact As IDatabaseCompact
If (TypeOf pWS Is IDatabaseCompact) Then
pDatabaseCompact = CType(pWS, IDatabaseCompact)
If (pDatabaseCompact.CanCompact) Then
Try
pDatabaseCompact.Compact()
Catch ex As Exception
MessageBox.Show(ex.type & ex.Message & ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End If
End Sub
Found the solution:
Before calling the Compact() method make sure there are not any existing locks on the database.
If it is a file geodatabase then open the gdb directory in Windows Explorer and look for LOCK type files, they end in .lock.
For personal geodatabase there will be a .ldb file in the directory with the same name as the .mdb.
If you have a layer or table from the geodatabase loaded in the map
then you will not be able to remove all locks.
If another user is
accessing the geodatabase then you will not be able to remove all
locks.
If you are using arcobjects to temporarily access the
geodatabase then you need to use good practices and close any
geodatabase resources when the calling process ends. This includes
releasing all COM objects when you are finished with them.
Use the ComReleaser Class in ESRI.ArcGIS.ADF.Connection.Local namespace