I'm trying to do a XML export of the database with VistaDB.
Unfortuanently, I'm lost.
Here's my code so far:
Dim instance As IVistaDBDatabase
Dim value As System.Int64
SaveFileDialog2.InitialDirectory = "C:\"
Select Case SaveFileDialog2.ShowDialog()
Case Windows.Forms.DialogResult.OK
Try
instance.ExportXml(SaveFileDialog2.FileName, VistaDBXmlWriteMode.All)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Select
All I get is object not set to instance of an object (or something like that).
Can anyone provide so guidance?
I was able to figure it out with help from an old code package.
Here is the proper code:
Dim vdbDatabase As IVistaDBDatabase = Nothing
Dim filenameDB As String = SaveFileDialog2.FileName
Dim filenameXML As String = SaveFileDialog2.FileName
Select Case SaveFileDialog2.ShowDialog()
Case System.Windows.Forms.DialogResult.OK
Try
' Call the method that will open the connection to the database and return an open IVistaDBDatabase object for the database to us
vdbDatabase = DDA.VistaDBEngine.Connections.OpenDDA.OpenDatabase("C:\Ledger.vdb5", VistaDBDatabaseOpenMode.NonexclusiveReadOnly, Nothing)
' Clear the XML Transfer List - this is the list used by the Import/Export methods
vdbDatabase.ClearXmlTransferList()
' Loop through the tables in the database and add them to the XmlTransferList
For Each tableName As String In vdbDatabase.GetTableNames()
vdbDatabase.AddToXmlTransferList(tableName)
Next
' Call the ExportXML method with the name of the XML file and the WriteMode value indicating what to Export
vdbDatabase.ExportXml(filenameXML, VistaDBXmlWriteMode.All)
' If the database is open - close it
If Not vdbDatabase.IsClosed Then
vdbDatabase.Close()
End If
MsgBox("Database Export complete.", MsgBoxStyle.Information)
Catch ex As Exception
WriteErrorEvent("Error exporting Database in addin", ex)
MsgBox("An error occured attempting to export the Database. Error Message:" & vbCrLf & vbCrLf & ex.ToString, MsgBoxStyle.Exclamation)
Finally
' If we have a vdbDatabase object
If Not (vdbDatabase Is Nothing) Then
' If it is open, close it
If Not vdbDatabase.IsClosed Then
vdbDatabase.Close()
End If
' Dispose of the object
vdbDatabase.Dispose()
End If
End Try
End Select
A Little late but i've made a small change to your code, so you can see the exact time of your backup.
Dim vdbDatabase As IVistaDBDatabase = Nothing
Dim filenamedb As String = vdbDatabase
Dim filenameXML As String = "MyDataBaseName_" + Now.ToString("dd-MM-yyyy_hh-mm-ss") + ".Xml"
Dim path As String
path = System.IO.Path.GetFullPath(filenameXML)
Try
vdbDatabase = DDA.VistaDBEngine.Connections.OpenDDA.OpenDatabase("DataDirectory|MyDataBase.vdb5", VistaDBDatabaseOpenMode.NonexclusiveReadOnly, Nothing)
vdbDatabase.ClearXmlTransferList()
For Each tableName As String In vdbDatabase.GetTableNames()
vdbDatabase.AddToXmlTransferList(tableName)
Next
vdbDatabase.ExportXml(filenameXML, VistaDBXmlWriteMode.All)
If Not vdbDatabase.IsClosed Then
vdbDatabase.Close()
End If
MsgBox("Backup is in " + path, MsgBoxStyle.Information)
Catch ex As Exception
MsgBox("An error occured attempting to export the Database. Error Message:" & vbCrLf & vbCrLf & ex.ToString, MsgBoxStyle.Exclamation)
Finally
If Not (vdbDatabase Is Nothing) Then
If Not vdbDatabase.IsClosed Then
vdbDatabase.Close()
End If
vdbDatabase.Dispose()
End If
End Try
Related
I have an asynchronous method that creates a PDF file from XML retrieved from a database. Everything works great, but occasionally I get an IOException because when I try to cleanup the temporary .fo file after creating the PDF, the file is still in use.
Public Sub FormatObjectToPdf(ByVal intRxNo As Integer, ByVal strSourceFileName As String)
Dim startInfo As New ProcessStartInfo
Dim strPdfFile As String = g_strRootPath & "Paperwork\" & intRxNo & "M.pdf"
' if the PDF file already exists, no need to re-create it
If Not File.Exists(strPdfFile) Then
Try
startInfo.Arguments = "-fo """ & strSourceFileName & """ -pdf """ & strPdfFile & """"
startInfo.FileName = g_strAppPath & "FO.NET\fonet.exe"
startInfo.UseShellExecute = True
startInfo.WindowStyle = ProcessWindowStyle.Hidden
Using proc As Process = Process.Start(startInfo)
proc.WaitForExit()
If proc.HasExited Then
proc.Dispose()
End If
End Using
Catch ex As Exception
Call InsertLog("ErrorLog", "FormatObjectToPdf: " & ex.Message, ex)
MessageBox.Show(ex.Message, "Create PDF", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End If
' wait 3 seconds to allow file to be released
System.Threading.Thread.Sleep(3000)
' delete the source FO file when processing is complete
If File.Exists(strSourceFileName) Then
Try
File.Delete(strSourceFileName)
Catch iEx As IOException
Call InsertLog("ErrorLog", "Could not delete file '" & strSourceFileName & "': " & iEx.Message, iEx)
Catch ex As Exception
Call InsertLog("ErrorLog", "Error deleting file '" & strSourceFileName & "': " & ex.Message, ex)
End Try
End If
End Sub
The FormatObjectToPdf method is called from another method, AsyncXmlToPdf, which is actually where the IOException is thrown. I had initially thought that the exception was in FormatObjectToPdf since that is where I am deleting the .fo file, so I had added a Sleep(3000) to see if giving it a few seconds would help.
Here is the AsyncXmlToPdf:
Public Sub AsyncXmlToPdf(ByVal state As Object)
Dim intRxNo = state(0)
Dim flgPrintResult As Boolean = state(1)
Dim strFileName As String = g_strAppPath & intRxNo & ".fo"
Dim strOutput As String
Dim strPdfFile As String = g_strRootPath & "Paperwork\" & intRxNo & "M.pdf"
Try
If File.Exists(strPdfFile) Then
File.Delete(strPdfFile)
End If
If Not File.Exists(strPdfFile) AndAlso Not File.Exists(strFileName) Then
strOutput = XmlToFormatObject(intRxNo, g_strAppPath & "FO.NET\immfo.xsl")
Using writer As StreamWriter = New StreamWriter(strFileName)
writer.Write(strOutput)
End Using
Call FormatObjectToPdf(intRxNo, strFileName)
End If
Catch ex As Exception
Call InsertLog("ErrorLog", "AsyncXmlToPdf: " & ex.Message, ex)
End Try
End Sub
The only part of either method other than the declaration of strFileName that even does anything with the .fo file is in FormatObjectToPdf and that method has a Catch block for IOException. Why is the exception being caught in AsyncXmlToPdf?? Here is the actual error message:
3/25/2015 11:15 AM: [IOException] AsyncXmlToPdf: The process cannot access the file 'C:\Users\<username>\AppData\Local\Apps\2.0\1M2D4TCB.REJ\3LH3JZY2.TQC\<clickonce app>\561964.fo' because it is being used by another process.
Everything works as expected, other than the occasional orphaned .fo file when this exception occurs. Anyone have any suggestions on how I might be able to find out where the problem is?
The only part of either method ... that even does anything with the .fo file is in FormatObjectToPdf It appears that AsyncXmlToPdf will also try to open a streamwriter on it.
If there is a chance that some other BackGroundWorker, Thread or Task could also be working on the same set of files, it would be possible for the same file to be in use in AsyncXmlToPdf and FormatObjectToPdf. MSDN warns of this in the File.Exists entry:
Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete.
In your case it looks like it might be a a coin flip which method the Exception will happen in.
If an accidental double click could start the same process twice, it is possible that the same file could be in use in both methods at the same time. You could add another test to see if you can open the file for ReadWrite. Given that the file was not supposed to exist yet, you could at least be somewhat certain as to the reason.
Some sort of flag to prevent more than one set of jobs from starting might be the final solution.
I have a vb.net program that runs a Try Catch. What i'd like to have happen, if there is an exception is have it log that exception to a text file. I have:
Catch ex As Exception
MsgBox(ex.Message)
My.Application.Log.WriteException(ex, TraceEventType.Error, "Exception " & "with argument " & "C:\Log.txt" & ".")
End Try
But it's not sending the exception to the logfile. What am I missing?
Adding a timestamp in the log file
Catch ex As Exception
IO.File.AppendAllText("C:\Log.txt", String.Format("{0}[{1}]{2}", Environment.NewLine, DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss"), ex.ToString()))
End Try
I think the example here: http://msdn.microsoft.com/en-us/library/dsxzceby(v=vs.90).aspx might have mislead you a bit. I find it a bit odd.
I think this is probably better:
Public Sub SomeMethodWhichMightGenerateException(byval someArg as String)
Try
' Code that might generate an exception goes here.
' For example:
' Dim x As Object
' MsgBox(x.ToString)
Catch ex As Exception
My.Application.Log.WriteException(ex, _
TraceEventType.Error, _
"Exception with argument " & someArg & ".")
End Try
End Sub
fileName is just a random variable in the msdn example and nothing to to do with where the Exception is logged...
Look here http://msdn.microsoft.com/en-us/library/7fx0fexe(v=vs.90).aspx to see where My.Application.Log.WriteException writes data to.
Alternatively you could do something like this:
Catch ex As Exception
IO.File.AppendAllText("C:\Log.txt", String.Format("{0}{1}", Environment.NewLine, ex.ToString()))
End Try
As others have said, however, you're probably better off using an existing error logging framework.
Public Function logerrors(ByVal [error] As String)
Dim filename As String = "Log_" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt"
Dim filepath As String = HttpContext.Current.Server.MapPath(Convert.ToString("~/ErrorLog/") & filename)
If File.Exists(filepath) Then
Using stwriter As New StreamWriter(filepath, True)
stwriter.WriteLine("-------------------START-------------" + DateTime.Now)
stwriter.WriteLine(Convert.ToString("Page :"))
stwriter.WriteLine([error])
stwriter.WriteLine("-------------------END-------------" + DateTime.Now)
End Using
Else
Dim stwriter As StreamWriter = File.CreateText(filepath)
stwriter.WriteLine("-------------------START-------------" + DateTime.Now)
stwriter.WriteLine(Convert.ToString("Page :"))
stwriter.WriteLine([error])
stwriter.WriteLine("-------------------END-------------" + DateTime.Now)
stwriter.Close()
End If
Return [error]
End Function
this is my very first project on vb.net and i am now struggling to migrate a vba working add in to a vb.net COM Add-in. I think i'm sort of getting the hang, but error handling has me stymied.
This is a test i've been using to understand the try-catch and how to pass exception to caller
Public Sub test()
Dim ActWkSh As Excel.Worksheet
Dim ActRng As Excel.Range
Dim ActCll As Excel.Range
Dim sVar01 As String
Dim iVar01 As Integer
Dim sVar02 As String
Dim iVar02 As Integer
Dim objVar01 As Object
ActWkSh = Me.Application.ActiveSheet
ActRng = Me.Application.Selection
ActCll = Me.Application.ActiveCell
iVar01 = iVar02 = 1
sVar01 = CStr(ActCll.Value)
sVar02 = CStr(ActCll.Offset(1, 0).Value)
Try
objVar01 = GetValuesV(sVar01, sVar02)
'DO SOMETHING HERE
Catch ex As Exception
MsgBox("ERROR: " + ex.Message)
'LOG ERROR SOMEWHERE
Finally
MsgBox("DONE!")
End Try
End Sub
Private Function GetValuesV(ByVal QryStr As Object, ByVal qryConn As String) As Object
Dim cnn As Object
Dim rs As Object
Try
cnn = CreateObject("ADODB.Connection")
cnn.Open(qryConn)
rs = CreateObject("ADODB.recordset")
rs = cnn.Execute(QryStr)
If rs.EOF = False Then
GetValuesV = rs.GetRows
Else
Throw New System.Exception("Query Return Empty Set")
End If
Catch ex As Exception
Throw ex
Finally
rs.Close()
cnn.Close()
End Try
End Function
i'd like to have the error message up to test, but
MsgBox("ERRORE: " + ex.Message)
pops out something unexpected (Object variable or With block variable not set)
What am i doing wrong here??
Thanks
D
It may be because you're doing a
Throw ex
Try using
Throw
instead. This maintains the error stack, instead of generating a new one each time.
Based on your comments, I think the specific problem you're getting is in your Finally block. You're trying to close the recordset and the connection, but if you got an error when you instantiated them, they will not exist; therefore, you get the Object variable or with block error.
(I would put the connection is a using statement anyway).
Error : "Detach database failed for Server 'MONO-PC\SQLEXPRESS'."
Public Sub bk()
Try
Dim strDatabasePath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC.mdf")
Dim strdbLogPath As String = My.Computer.FileSystem.CombinePath(My.Application.Info.DirectoryPath, "LIC_log.ldf")
' DB.Connection can be any valid SQLConnection which you might already be using in your application
Dim con As New SqlClient.SqlConnection(LIC.My.Settings.LICConnectionString)
Dim srvCon As New ServerConnection(con)
Dim srv As Server = New Server(srvCon)
If srv.Databases.Contains(strDatabasePath) Then
If Not con.State = ConnectionState.Closed Then
con.Close()
End If
srv.DetachDatabase(strDatabasePath, True)
My.Computer.FileSystem.CopyFile(strDatabasePath, "c:\backup\LIC.mdf", True)
My.Computer.FileSystem.CopyFile(strdbLogPath, "c:\backup\LIC_log.ldf", True)
MessageBox.Show("Backup taken successfully")
End If
srvCon.Disconnect()
con.Open()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
Why does it fail??Any Help Appreciated.
You should not use the path for the database name and you should extract the file names from the database object. Here is a rewrite that will work for any database:
Public Sub bk()
Try
Using con As New SqlClient.SqlConnection(LIC.My.Settings.LICConnectionString)
Dim sDatabaseName As String
con.Open()
sDatabaseName = con.Database
con.Close()
Dim srvCon As New ServerConnection(con)
Dim srv As Server = New Server(srvCon)
If srv.Databases.Contains(sDatabaseName) Then
Dim oDatabase As Database
Dim cFiles As New List(Of String)
' Get a local reference to the database
oDatabase = srv.Databases(sDatabaseName)
' Collect the list of database files associated with this database
For Each oFileGroup As FileGroup In oDatabase.FileGroups
For Each oFile As DataFile In oFileGroup.Files
cFiles.Add(oFile.FileName)
Next
Next
' And collect the list of log files associated with this database
For Each oFile As LogFile In oDatabase.LogFiles
cFiles.Add(oFile.FileName)
Next
' Ensure nothing is using the database
srv.KillAllProcesses(sDatabaseName)
' Detach the database
srv.DetachDatabase(sDatabaseName, False)
' And finally, copy all of the files identified above to the backup directory
For Each sFileName As String In cFiles
System.IO.File.Copy(sFileName, System.IO.Path.Combine("c:\backup\", System.IO.Path.GetFileName(sFileName)), True)
Next
MessageBox.Show("Backup taken successfully")
End If
srvCon.Disconnect()
End Using
Catch ex As Exception
MessageBox.Show("Error Occured : " & ex.Message)
End Try
End Sub
Using VB.NET, I am trying to create a text file if it doesn't exist or append text to it if exists.
For some reason, though it is creating the text file I am getting an error saying process cannot access file.
And when I run the program it is writing text, but how can I make it write on a new line?
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Dim fs As FileStream = Nothing
If (Not File.Exists(strFile)) Then
Try
fs = File.Create(strFile)
sw = File.AppendText(strFile)
sw.WriteLine("Start Error Log for today")
Catch ex As Exception
MsgBox("Error Creating Log File")
End Try
Else
sw = File.AppendText(strFile)
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)
sw.Close()
End If
Try this:
Dim strFile As String = "yourfile.txt"
Dim fileExists As Boolean = File.Exists(strFile)
Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw.WriteLine( _
IIf(fileExists, _
"Error Message in Occured at-- " & DateTime.Now, _
"Start Error Log for today"))
End Using
Don't check File.Exists() like that. In fact, the whole thing is over-complicated. This should do what you need:
Dim strFile As String = $#"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt"
File.AppendAllText(strFile, $"Error Message in Occured at-- {DateTime.Now}{Environment.NewLine}")
Got it all down to two lines of code :)
This should work for you without changing program logic (by not outputting "Start error" on the top of each file) like the other answers do :)
Remember to add exception handling code.
Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Dim fileExists As Boolean = File.Exists(filePath)
Using writer As New StreamWriter(filePath, True)
If Not fileExists Then
writer.WriteLine("Start Error Log for today")
End If
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
End Using
You didn't close the file after creating it, so when you write to it, it's in use by yourself. The Create method opens the file and returns a FileStream object. You either write to the file using the FileStream or close it before writing to it. I would suggest that you use the CreateText method instead in this case, as it returns a StreamWriter.
You also forgot to close the StreamWriter in the case where the file didn't exist, so it would most likely still be locked when you would try to write to it the next time. And you forgot to write the error message to the file if it didn't exist.
Dim strFile As String = "C:\ErrorLog_" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim sw As StreamWriter
Try
If (Not File.Exists(strFile)) Then
sw = File.CreateText(strFile)
sw.WriteLine("Start Error Log for today")
Else
sw = File.AppendText(strFile)
End If
sw.WriteLine("Error Message in Occured at-- " & DateTime.Now)
sw.Close()
Catch ex As IOException
MsgBox("Error writing to log file.")
End Try
Note: When you catch exceptions, don't catch the base class Exception, catch only the ones that are releveant. In this case it would be the ones inheriting from IOException.
Why not just use the following simple call (with any exception handling added)?
File.AppendAllText(strFile, "Start Error Log for today")
EDITED ANSWER
This should answer the question fully!
If File.Exists(strFile)
File.AppendAllText(strFile, String.Format("Error Message in Occured at-- {0:dd-MMM-yyyy}{1}", Date.Today, Environment.NewLine))
Else
File.AppendAllText(strFile, "Start Error Log for today{0}Error Message in Occured at-- {1:dd-MMM-yyyy}{0}", Environment.NewLine, Date.Today)
End If
While I realize this is an older thread, I noticed the if block above is out of place with using:
Following is corrected:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath As String =
String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Using writer As New StreamWriter(filePath, True)
If File.Exists(filePath) Then
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
Else
writer.WriteLine("Start Error Log for today")
End If
End Using
End Sub
Try it this way:
Dim filePath As String =
String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
if File.Exists(filePath) then
Using writer As New StreamWriter(filePath, True)
writer.WriteLine("Error Message in Occured at-- " & DateTime.Now)
Else
writer.WriteLine("Start Error Log for today")
End Using
end if