Releasing an .MDF File in VB.NET - sql

I have an application that checks to see if it's the most recent version. If not, it updates itself by using File.Copy to replace the DB attached to the application with a fresh one (that may or may not have had changes made to it). In an attempt to keep the data from being deleted, I created a backup system that writes all the data to an XML file before the database is deleted and restores the data once the database has been copied.
I am having a problem with the File.Copy method, however, in that an error pops up telling me the .MDF is being used by another process.
I was told that stopping SQL Server would work, but it hasn't. I've also been told I can use SMO, but also have not been able to make that work. With this seeming so close to complete, SMO also seems like it won't be necessary.
My code is this:
'This is the backup. I make sure to close the SQL Connection when the process is complete.
Dim db As String = "C:\ACE DB\localACETest.mdf"
Dim dbLog As String = "C:\ACE DB\localACETest_log.ldf"
If File.Exists(db) = True Then
'Backup process
'...
End If
'"Data/localACETest.mdf" referenced below is the file located inside of my application that is used to overwrite the other MDF; it is NOT the .MDF I'm looking to replace.
Directory.CreateDirectory("C:\Random Directory\")
File.Copy("Data/localACETest.mdf", db, True) 'This is the line where I get the error
File.Copy("Data/localACETest_log.ldf", dbLog, True)
success = False
...
EDITS:
I have narrowed the issue down to the method that backs up my data. I'm using the following connection string:
Private Const _sqlDB As String = "Data Source=(localdb)\v11.0;Initial Catalog=localACETest;Integrated Security=True; _
AttachDbFileName=C:\ACE DB\localACETest.mdf"
I open SQL, run a command, and then close it:
Using connection = New SqlConnection(_sqlDB)
connection.Open()
...
connection.close()
Why does this not release the MDF from the process? (When I don't run it, I have no problems)

You are better off sending a command to SQL server telling it to make a backup for you. This SO article has a great (command line) script that you can copy/paste:
SQL Server command line backup statement
Put that into a batch and launch it like this.
System.Diagnostics.Process.Start("C:\Ace Db\MakeADBBackup.bat")
If you would prefer to make your program wait till the backup finishes, read about launching processes: http://support.microsoft.com/kb/305368
If you are REALLY insistent on making a copy of the .mdf (which is not a good idea), then you need to ask the server to stop the SQL service before you make a copy. You could run a batch that says
NET STOP MSSQLSERVER
Assuming that your SQL Server is running under the name "MSSQLSERVER". To check the names of running services, open a command prompt and type-in "NET START". It will give a list of services that are running. One of them will be the "process name" of your SQL Server's running service.
Better still, here is an article (for VB.NET) that shows the source code for starting/stopping SQL Server. http://msdn.microsoft.com/en-us/library/ms162139(v=SQL.90).aspx
I strongly recommend that you try the first approach that I suggested.

Related

Access 2007 compact DB

Sorry for my English, I write from Italy.
I use the Access 2007 DB in a business data management procedure in VB Net.
As is known, Access DBs expand during use and consequently I need to compact them when the program is closed.
I perform the compaction in this way
Dim MioEngine As New Microsoft.Office.Interop.Access.Dao.DBEngine
MioEngine.CompactDatabase(myAccesDB, newAccessDB,)
Application.DoEvents()
but often and not on all PCs on the network, the compaction does not finish and gives me the following error message:
The process cannot access the 'C:\myAccesDB.accdb' file because it is being used by another process
Analyzing in depth what happens, I see that when the error occurs, the .laccdb file is not closed at the time of compacting.
Is there any way other than the one I used to do the compacting safely?
I specify that all the PCs in our network are Windows 10 pro and all updated; when Windows 10 was in its infancy, I didn't get this error.
Since my comment was not enough, here's an answer:
The idea is to try to opetn .laccdb file before you try to compact the database. You can do something like this:
Dim file as System.IO.FileInfo = New System.IO.FileInfo("c:\myAccesDB.laccdb")
Dim stream As FileStream = Nothing
Try
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
stream.Close()
'if stream is successfully closed, file is not in use and database can be compacted
MioEngine.CompactDatabase(myAccesDB, newAccessDB,)
Catch ex As Exception
'show some message to user that file is in use so it can try again
End Try
I worked with VB and Access ages ago, so this is only a direction that you should take.
Thanks, I'll try.
I also had a look to this:
https://support.microsoft.com/en-us/topic/office-error-accdb-remains-locked-after-oledb-connection-is-closed-37d42348-9edf-4493-a5f4-35c685af3160?ui=en-us&rs=en-us&ad=us
Where I find:
This issue is now fixed. If you launch Access, click 'File', then 'Account', then 'Update Options', and 'Update Now', this will ensure that you have the latest version, and all versions should have the fix available.
But I'm not able to find 'File' opening Access,....

calling a uid and pwd file into an access db for a system dsn

I have 5 different MS Access 2013 db files which connect to system dsn files(Linked Server)
The machine/system dsn's are Oracle based but the issue I am running into is 1 my password isn't encryped and has to be changed every 90 days and
2 I have to open each file and save my password multiple times when its changed.
I want to have a secure location which has the credentials stored and pass this into access so that they are not visible to other users and
not having to save my password on each access file and relink it.
I have googled for over 2 days but can't find anything other than looking at connection strings which still doesn't solve the problem. What do I need to look at to solve this?
Sorry I dont have code as I just use the linked tables wizard inside of ms access.
#Albert D I couldn't get your code to work but I have done the following which fixes the issue on the tables but not the Pass Through queries
Created a File DSN and linked some tables to the access database.
Created an Excel File to store my UserName And Passwords but my credentials in the pass-through query still show which I am stuck on?
Option Compare Database
Function Connections()
On Error Resume Next
'delete query if exists
DoCmd.DeleteObject acQuery, "PTQ"
Err.Clear
On Error GoTo 0 '"on error" statement here
'GET EXCEL LOGIN DETAILS
Set xlsApp = CreateObject("Excel.Application")
Dim WkBk As Excel.WorkBook
Set WkBk = xlsApp.WorkBooks.Open(FileName:="C:\folderlocation\filename.xlsx")
Dim USERLIST As String
Dim PWDLIST As String
USERLIST = WkBk.Sheets(1).Range("A2").Value
PWDLIST = WkBk.Sheets(1).Range("B2").Value
If Not (xlsApp Is Nothing) Then xlsApp.Quit
'end excel stuff
Dim db As DAO.Database
Dim qdExtData As QueryDef
Dim strSQL As String
Set db = CurrentDb
'passthrough query statement
strSQL = "SELECT * FROM table"
Set qdExtData = db.CreateQueryDef("PTQ")
ServerName = "Server1"
qdExtData.Connect = "ODBC;DRIVER={Oracle in OraClient11g_home1};Server=" & ServerName & ";DBQ=Server1;UID=" & USERLIST & ";Pwd=" & PWDLIST & ""
qdExtData.SQL = strSQL
qdExtData.Close
db.Close
Set db = Nothing
End Function
I then Set up a runcode macro called AutoExec
Ok, first up?
I would avoid (not use) a system, or a user DSN. The reasons are MANY, but these types of DSN's require not only a external reference, but also often require elevated registry rights. And worse yet, your password will be in plain view.
The best solution is to use what is called a DSN-less connection. And you can create these connections even without code!
And even better? If the server + database name is NOT changed, but ONLY the password? You can change the userID + password WITHOUT having to re-link the tables (ideal for you with a changing password, but NOT the server + database being changed).
Even better better? If you adopt a wee bit of "log on" code, then you don't have to store the password in the table links! What this means if someone decides to fire up access, and say import your linked tables? Well, for one, they will not be able to open the tables, and EVEN better yet the uid/password is NOT part of, nor is it stored in the connection string for each linked table. As noted, because of this, you can change the UID, and not have to re-link the tables.
The first step:
First up, ALWAYS (but ALWAYS!) when you link the tables, use a FILE dsn. this is imporant since when using a FILE dsn in access, they are automatic converted to DSN-less connections for you.
In other words, if you link your tables with a FILE dsn, then once the tables are re-linked, then you can even delete or toss out the DSN. And this means you can deploy the linked database (front end) to any workstation. You will not have to setup a DSN on that workstation, and in fact don't have to setup anything at all. (you will as before of course require the oracle database driver).
What the above means is when a password is updated/changed, you could then simply roll out a new front end. In fact, you likely have some auto updating ability for your application. (and if you don't', then you could (should) cobble together a bit of code to do this for you). So, you should have some means to roll out a new version of your software. After all, you REALLY have to install your "application" on each workstation LIKE you do with all other software, right???
So, there are two parts here:
Adopting a FILE dsn for the table links. As noted, once you do this, then you don't need the DSN anymore. This is great for distribution to each workstation.
Also MAKE SURE when you do link, you do NOT check the box to save the password. This is to ensure that uid/password is NOT saved in the connection strings.
So, if tables don't have uid/password, then how will they work?
Well, what you do is execute a "logon" to the database in your startup code. Once you execute this logon, then all linked tables will work! It is this "small" bit of code that can read the uid/password you place in an external file. Where you place this uid/password is up to you. It could be embedder in the code, or even some external text file that you read on startup. And it could even be a local table in the front end. (this idea would work well if you have some kind of automatic update system for when you roll out the next great version of your software.
So, with the ability to execute a logon, and not having to re-link the tables, then we have a EASY means to change the password.
So, you have to:
go dsn-less. Thankfully, access does this by default, but ONLY if you use a FILE dsn.
Get/grab the code to execute a logon to the database. In fact, you likly have to delete all your table links. Exit Access, then re-start Access. Now, run your logon code, and THEN re-link your tables (using a FILE dsn you make).
The code to execute a logon is this:
Function TestLogin(strCon As String) As Boolean
On Error GoTo TestError
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb()
Set qdf = dbs.CreateQueryDef("")
qdf.connect = strCon
qdf.ReturnsRecords = False
'Any VALID SQL statement that runs on server will work below.
qdf.sql = "SELECT 1 "
qdf.Execute
TestLogin = True
Exit Function
TestError:
TestLogin = False
Exit Function
End Function
The above of course requires a correctly formed conneciton string.
So, to make ALL of this work, you can adopt the FILE dsn, and use above. You will likly cobbile together some code to build you a connection string. Then add to your code some code to read an external ext file, or have the UID/password in some table. This logon code as per above has to run BEFORE any form or linked table is used or touched.
The whole process is simple, but only if you break down this into the correct steps.
How this logon trick, and example code works is not complex, but a full article explaining this approach is outlined here
Power Tip: Improve the security of database connections
https://www.microsoft.com/en-us/microsoft-365/blog/2011/04/08/power-tip-improve-the-security-of-database-connections/

using environment variables in excel

So I am using this code in excel to read environment parameters on startup:
Dim ExcelArgs As String
Dim arg As String
ExcelArgs = Environ("ExcelArgs")
MsgBox ExcelArgs
If InStr(UCase(ExcelArgs), "CREO") >= 0 Then
Application.DisplayAlerts = False
If Len(ExcelArgs) > Len("CREO") Then
arg = Split(ExcelArgs, ",")(1)
Call Creo.addNewPartToPartslist(arg)
End If
Application.DisplayAlerts = True
End If
and this line in my batch script:
echo "Launch excel"
Set "ExcelArgs=CREO,DXFWITHOUTDRW
"C:\Program Files (x86)\Microsoft Office\OFFICE16\Excel.exe" /r "%APPDATA%\Microsoft\Excel\XLSTART\PERSONAL.XLSB"
exit 0
The problem is that if i run the batch file once, keep excel open change the excelargs to CREO,wqhatever in batch file and rerun batch file the excelargs, dos not get updated!!!
So my theory is that excel either caches out the environment variable or that if it is being used by one instance the batch script can not set it
link with some info about passing arguments to excel:
https://superuser.com/questions/640359/bat-file-to-open-excel-with-parameters-spaces
Usually excel sees if there is a previous instance running and let this instance handle the file opening.
Is this important? Yes, in your case both requests to open the file are handled by the same excel process.
How does it make a difference? Environment variables are not shared. Each process has it own environment block that is initialized when the process is created (can be a customized block or a copy of the environment of the parent process) and once the environment is created for a process, only this process can change its environment.
In your case, when you start excel the new process gets a copy of the environment block of the cmd process. Later, when you change the cmd environment, the already running excel instance sees no changes in environment and, as the new request to open excel is converted to a request to the previous process, there is not a new process with a new copy of the cmd environment with the changes.
The only way I see to make it work is to force excel to start a new process (that will inherit the changes in the cmd instance) instead of reusing the previous one.
But this depends on the excel version. As far as I know, the 2013 version includes an /x switch to force separate process usage. For previous versions, maybe this question, or this one could help you.
Excel is open
Then i start the batch script:
The it does not open it as read only by default, but prompt me instead, not a big issue but a bit annoying, and it also make it impossible to loop through to run the batch several times for different input parameters.
A bit unsure how I should post this, couldnt paste images in comments, and to edit the the original question, which was how to start excel with enviroment variable in new instance (/x did the trick), but now /r does not work, Should I post as new question and refer to this one or can I leave it as an answer?

SQL error unable to copy file

I'v built a program, and I used SQL. It worked fine but suddenly, without changing the code, I got the error message:
Error 3 Unable to copy file "C:\Users\user\documents\visual studio
2010\Projects\Programm\Programm\App_Data\DataBase_log.ldf" to
"bin\Debug\App_Data\DataBase_log.ldf". The process cannot access the
file 'C:\Users\user\documents\visual studio
2010\Projects\Programm\Programm\App_Data\DataBase_log.ldf' because it
is being used by another process.
This is my connection string:
private string ConnectionString()
{
return #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\DataBase.mdf;Initial Catalog=DataBase.mdf;Integrated Security=True;User Instance=True";
}
I'm using SQL server 2008 and Visual studio 2010.
I can't figure out what the problem is and I'd appreciate anyone who helps.
1) Sometimes the vslshost.exe gets stuck from prior run and you can't build again as it has files open. Sometime another build works, other times you have to close VS and reopen. Other times you have go delete the process.
2) If DB will be on end user machine, then ".\SqlExpress" should work

Intermittent error when attempting to control another database

I have the following code:
Dim obj As New Access.Application
obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")
obj.Run "Routine"
obj.CloseCurrentDatabase
Set obj = Nothing
The problem I'm experimenting is a pop-up that tells me Access can't set the focus on the other database. As you can see from the code, I want to run a Subroutine in another mdb. Any other way to achieve this will be appreciated.
I'm working with MS Access 2003.
This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.
I suspect this may occur when someone is working with this or the other database.
The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.
Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If
I'll make another subroutine without the MsgBox.
I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user.
This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.
I suspect this may occur when someone is working with this or the other database.
The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.
Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If
I'll make another subroutine without the MsgBox.
I've tried this in our development database and it works. This doesn't mean anything as the other code also workes fine in development.
I guess this error message is linked to the state of one of your databases. You are using here Jet connections and Access objects, and you might not be able, for multiple reasons (multi-user environment, unability to delete LDB Lock file, etc), to properly close your active database and open another one. So, according to me, the solution is to forget the Jet engine and to use another connexion to update the data in the "other" database.
When you say "The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database", I assume that the role of your "Routine" is to update some data, either via SQL instructions or equivalent recordset updates.
Why don't you try to make the corresponding updates by opening a connexion to your other database and (1) send the corresponding SQL instructions or (2) opening recordset and making requested updates?
One idea would be for example:
Dim cn as ADODB.connexion,
qr as string,
rs as ADODB.recordset
'qr can be "Update Table_Blablabla Set ... Where ...
'rs can be "SELECT * From Table_Blablabla INNER JOIN Table_Blobloblo
set cn = New ADODB.connexion
cn.open
You can here send any SQL instruction (with command object and execute method)
or open and update any recordset linked to your other database, then
cn.close
This can also be done via an ODBC connexion (and DAO.recordsets), so you can choose your favorite objects.
If you would like another means of running the function, try the following:
Dim obj As New Access.Application
obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")
obj.DoCmd.RunMacro "MyMacro"
obj.CloseCurrentDatabase
Set obj = Nothing
Where 'MyMacro' has an action of 'RunCode' with the Function name you would prefer to execute in Working.mdb
I've been able to reproduce the error in 'development'.
"This action cannot be completed because the other application is busy. Choose 'Switch To' to activate ...."
I really can't see the rest of the message, as it is blinking very fast. I guess this error is due to 'switching' between the two databases. I hope that, by educating the user, this will stop.
Philippe, your answer is, of course, correct. I'd have chosen that path if I hadn't developed the 'routine' beforehand.
"I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user." As it is impossible to prevent the user to switch application in Windows, I'd like to close the subject.