Making a back up of A SQL Server Compact Edition Corrupts the database - vb.net

On close of an application written in VB, I need to copy the .sdf file, this is the local SQL Server CE database that syncs with the server. Each time we close the app we require a backup to be made.
I am using the file.copy method. First I close the connection to the database then copy the file to a specific location.
Dim conn As SqlCeConnection = New SqlCeConnection(My.Settings.MyClientConnectionString)
conn.Open()
conn.Close()
Dim tpath As String = My.Settings.CertPath
Dim path As String = tpath.Replace("db\", "MyDatabase.sdf")
Dim fs As FileStream = File.Create(path)
fs.Close()
File.Delete("C:\db\backup\MyDatabase.sdf")
File.Copy(path, "C:\db\backup\MyDatabase.sdf")
The problem arises on the line of code:
Dim fs As FileStream = File.Create(path)
The database becomes corrupted and has a size of 0 kb.
Has anyone seen this before? Thanks

Are you calling Create on an existing database file? According to the docs, Create creates or overwrites a file in the specified path. In the code you show, calling Create isn't necessary anyway. Just call File.Copy.

Related

Additional information: There is already an open DataReader associated with this Command which must be closed first. vb.net

Dim cat As New Catalog()
Dim con As New OleDbConnection()
Dim cmd As New OleDbCommand
Dim ds1 As New DataSet
Dim conn As ADODB.Connection
' Open the Access database.
conn = New Connection
conn.ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" &
"Data Source=" + openExcel + "\Test" + ".mdb; Persist Security Info=False"
con.ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" &
"Data Source=" + openExcel + "\Test" + ".mdb; Persist Security Info=False"
conn.Open()
xlWorkSheet1.Columns(5).Insert
Dim cellValue As String = ""
Dim newValue As String = ""
Dim sh1 As String = ""
Dim qty As String = ""
Dim matchText As String = ""
Dim sql As String = ""
con.Open()
sh1 = LTrim$(xlWorkSheet1.Cells(i, 1).Text)
sql = "SELECT Num_ber, Q_ty FROM good WHERE Na_me LIKE 'staff%' And Ty_pe = 'ORD'"
Dim cmd As New OleDbCommand(sql, con)
Dim myReader As OleDbDataReader = cmd.ExecuteReader()
conn.Execute(sql)
myReader = cmd.ExecuteReader() ' HERE'S THE PROBLEM
xlWorkSheet1.Cells(1, 5) = myReader.GetString(0)
xlWorkSheet1.Cells(1, 11) = myReader.GetString(1)
myReader.Close()
conn.Close()
conn = Nothing
**I wanted to retrieve a specific value from mdb and then write it to excel.
Here's my code, I got this error so many times and I can't find it out. Can anybody help me? Thanks.**
[1]: https://i.stack.imgur.com/6Fuvg.png
Ok, you first have to decide when usng .net what "provider" you are going to use, AND THEN decide what kind of data objects you want to use.
You can use a oracle provider, a sql server provider, or in this case, since we using Access, then we can use EITHER oleDB, or ODBC. Either choice is fine. Most use oleDB providers for Access, but often ODBC is a good choice, especially if down the road you plane to swap out Access for say SQL server.
What the above means in plain English?
You don't want to adopt the external ADODB code and library. That code is NOT .net, and thus you REALLY but REALLY do not want to write your .net code that way. ADODB was written LONG before .net, and is what we call un-managed code (non .net). I strong, but strong suggest you do NOT add a reference to ADODB to your project, and I beyond strong recommend you avoid introduction of a non .net library for doing this!!! We certainly can adopt the oleDB provider in .net, but we will NOT have a direct reference to JET/ACE (the access database engine) in our applcation. As noted, there are some exceptions to this suggesting, but they don't apply to you and here.
Next up:
The design pattern in .net is to create the connection, get the data, and CLOSE the connection. This "pattern" will then be 100% sure that the data base is always closed, and you NEVER have to worry about if the connection is open, closed, or even if you forgot to close the connection!!! So, do this correct, and some "open" connection will never bite you, or will you have to worry about this issue.
You can in some operations keep the connection open for performance, but lets learn to walk before we run so to speak.
next up:
We certainly do NOT want to place and have connection strings all over in our code. Not only is this going to wear out your keyboard, but if you ever need to change the connection, then you going to have to hunt down all that code.
Best to let Visual Studio save that connection in ONE location, and MORE important MANAGE this for you!!!
Next up:
Do you ONLY need to work with mdb files, or do you plan/need to work with accDB files? This is a HUGE issue, and one that you cannot ignore.
next up:
Are you going to use the x32 bit version of the Access database system, or the x64 bit version?
Since your example posted code uses JET (access data engine for mdb files ONLY x32 bit version)?
Then this ALSO means you MUST (and I repeat MUST) force your .net project to run as x32 bits. You cannot use "any cpu", and you cannot use x64 bits, you MUST choose x86 bit size for your .net project. Failure to do so will result in the project not working.
Ok, with the above information?
First up, force/set/be 100% sure your project is set to run as x32 bits.
That setting is this one:
and remove the reference you have to ADO if you created one.
Ok,
next up:
Create the connection to the database.
Project ->properties.
This here:
And then:
and then
Now, you can browse, and select the access mdb file.
But, you MUST not skip the next step - you have to choose JET (older, mdb files), or choose the newer ACE (for accDB format files).
So, this:
now this:
As noted, you choose JET or ACE here.
now, we have this and you can use test connection.
BUT BE VERY careful!!!!
If you are using vs2022, then keep in mind vs2022 is the FIRST version of VS that is now x64 bits. As a result, vs can't pass the test connection!!! Your connection is in fact ok, but will fail with vs2022.
If you using a previous version of VS (before 2022), then the test connection button should work. and you see this:
Ok, now that we have a valid working conneciton setup, we can now write code, and we will NOT use ADODB!!!!
The typical code pattern to read and load a data table (like a access VBA recordset) will be like this:
Now, I became RATHER tired of writing that same using block over and over. So, in a global module, I have this code now:
Public Function MyRst(strSQL As String) As DataTable
Dim rstData As New DataTable
Using conn As New OleDbConnection(My.Settings.AccessDB)
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
Return rstData
End Function
So, now with the above handy dandy helper routine?
Your code becomes this:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim Sql As String =
"SELECT Num_ber, Q_ty FROM good WHERE Na_me LIKE 'staff%' And Ty_pe = 'ORD'"
Dim rstData As DataTable = MyRst(Sql)
Debug.Print("Na_me is " & rstData.Rows(0).Item("Na_me"))
End Sub
Or, display all return rows from that data table
Debug.Print("Na_me is " & rstData.Rows(0).Item("Na_me"))
For Each OneRow As DataRow In rstData.Rows
Debug.Print("na_me = " & OneRow("Na_me"))
Next
So, you really don't need (or want) a reader anyway. Just load the results into a nice clean, easy to use data table, and from that you can loop the table, grab rows, or do whatever you want.

Cloning a csv file to memory and using it in a datatable? (vb.net)

I have a question about the following code. in order to prevent problems caused by file locking I came across the following code.
Dim OrignalBitmap As New Bitmap(Application.StartupPath & "\IMAGES\BACKGROUND_LARGE.jpg")
Dim CloneBitmap As New Bitmap(OrignalBitmap)
OrignalBitmap.Dispose()
Which works like a charm. Now I have all the images in place and I can still access them as a file without anything locking. It works so well for what I need that I was thinking if its possible to do this for file formats other than images such as Csv files which are then used in a datagridview as a bound table?
Usually it is enough to open a File like this, so that it will not block other programs to access and open it.
Dim path1 As String = "C:\temp\temp.csv"
Using fs As FileStream = File.Open(path1, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
' Do something with filestream
End Using
this will prevent even huge files to open without blocking access
you should check https://learn.microsoft.com/de-de/dotnet/api/system.io.file.open?view=netframework-4.8

Access to .txt [VB.NET]

I've developed a multi-user application. One user saves a string to a text file, other users have to read this string in a background process.
My problem is: when some users open the file to read the string, another user that wants to save a new string can't write to the file. I would like to implement a system that checks if the file is opened or not, and in case it is, waits a few seconds and retries.
What is the function or command to look if the file is already opened?
I solved my problem using tips:
i've replaced this code:
ip_acquisito = My.Computer.FileSystem.ReadAllText(path_elenco & "\ip.txt")
with this code:
Using fs As FileStream = File.Open(path_elenco & "\ip.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While fs.Read(b, 0, b.Length) > 0
ip_acquisito = temp.GetString(b)
Loop
End Using
There are quite a few patterns you can deal with. Two I'd recommend would be:
Dealing with FileAccess, FileMode and FileShare
Sync the file access with EventWaitHandle

Can't open IIS w3c log vb.net

I have been writing an app in vb.net to copy the last few lines of an IIS W3C log file every few minusts to A file that will be used for some remote reporting.
Everything works when I test on my local PC but when I try it on the live IIS server it tells me the file is locked by another process, I take it IIS has it locked...
It does read in some of the sites log files (more than on site on the server) but not others, tells me locked/in use.
Why is it that I can always open the file in notepad but not open it in my app?
The Code:
Dim linex = ""
Dim Line = ""
'### IT ERROS OUT ON THE NEXT LINE ###
Using sr As New StreamReader("C:\inetpub\logs\LogFiles\W3SVC14\u_ex130702.log")
Do Until sr.EndOfStream
linex = sr.ReadLine()
line = line & linex & vbCrLf
Loop
End Using
You need to specify correct sharing options and open mode when creating underlying FileStream. Since there is no constructor of StreamReader that passes all necessary arguments you need to construct FileStream first using FileStream(String, FileMode, FileAccess, FileShare) and than create StreamReader on it using SrteamReader(Stream).
I think following should open IIS log file while it is being written to by IIS (if not - try other combinations of flags)
Using stream As New New FileStream( _
"Test####.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Using sr As New StreamReader(stream)

Loading Sequential Files in VB

I have written a vb program a few years ago and now as I get started with vb again i am hitting a "snag". With sequential files. I am trying to load a file in to the vb program with the file dialog box.
NOTE:I am using structures
Dim FileDialog as new openFileDialog
Dim MyStream as Stream = nothing
Dim FileLocation as string 'this is to save the file location
if( FileDialog.ShowDialog() = DialogResults.OK)Then
FS = new FileStream(FileLocation, FileMode.open, fileaccess.Read)
BF = new BinaryFromatter
While FS.Position < FS.Length
Dim temp as unit
...'Please note that this is where the file reads the structures data.It is to much code to write in.
When I run the program I can create a file and save it with the data in and I can load it with the Dialog box, The problem is when I run the program again and try to load it. It just wont run the file or load it(Remember I created the file with this program and saved)
How do I get this to work?
Make sure you have closed the file after writing and reading the data the first time, and make sure you are using the correct path (FileLocation).
Exit Visual Studio between the first and second times you run the program. If it works then, then you know you are not closing the file properly.
Set a breakpoint at the new FileStream assignment and check the value of FileLocation. Is it the same as it was when the file was written?
Check the error message, if there is one, and see if that tells you anything.