Debug logging VB.net - vb.net

I'm trying to create a Debug log for my application, and I'd like to document everything to the log.
%TimeStamp% - Loaded main form
%TimeStamp% - Loaded Settings
%TimeStamp% - Entered Ready state
etc.
I've got a function that creates a folder to house the debug log, and creates the debug file accordingly:
Dim DebugFile As String = String.Format(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\App\Debug_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))
Public Sub Debug_File_Check()
' Set a variable to the My Documents path.
If (Not System.IO.Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\App\")) Then
System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\App\")
End If
End Sub
And a function that opens the debug file and writes a line to it:
Public Sub Debug()
Using writer As New StreamWriter(DebugFile, True)
If File.Exists(DebugFile) Then
writer.WriteLine(%DEBUG MESSAEGE + " Occured at-- " & DateTime.Now)
Else
writer.WriteLine("Start Error Log for today")
End If
End Using
End Sub
My question is, how can I pass information from something like:
Private Sub FrmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Debug_File_Check()
Debug("The form has loaded")
End Sub
Where it, on one line, will write the debug line to my debug.txt file?
I've never dealt with debug logging before, so not even sure if I'm on the write track.

Related

Error with VB ParseFileText method

When I run this I made a dummy "Button1" to test populate the fields they will successfully fill out the texts boxes. How ever I will have it parse that file every minute, and when I do it again I get the error shown below. By adding the routine "DisplayForm_Load" to the button1_click even it would work fine.
My question is I'm pretty sure I shouldn't have to redefine this every time? I think I'm not setting the index back to 0 or something along those lines. From what I've been able to understand from MS website is its like its indexing things in the array that don't exist.
Error received:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication4.exe
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private Directory As String ' Used to hold the folder directory to push/pull data from.
Private FileParser As Microsoft.VisualBasic.FileIO.TextFieldParser
Private Sub PushButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles PushButton.Click
' Sends information to txt file.
' This bit works fine, just writes code to txt file that can be parsed below.
End Sub
Sub DefineTextFieldParse_Load() Handles MyBase.Load
' Instantiate teh TextFieldParser and the set the delimiter
Dim FileName As String = "C:\Users\Caleb\Documents\TestDoc.txt"
Try
FileParser = New FileIO.TextFieldParser(FileName) '' Selects File to Parse
FileParser.TextFieldType = FieldType.Delimited
FileParser.SetDelimiters(",")
Catch ex As Exception
' Errors
MessageBox.Show("Unable to read the file" & "," & FileName)
End Try
End Sub
Sub UpdateCheck()
' Checks share txt file for update.
Dim FileName As String = "C:\Users\<Me>\Documents\TestDoc.txt"
Dim FieldString() As String
'Read the file
If Not FileParser.EndOfData Then
FieldString = FileParser.ReadFields()
' 1st Field
NIS1TextBox.Text = FieldString(0)
' 2nd Field
NIS2TextBox.Text = FieldString(1)
' You get the idea...All Testboxes identified above in the write section
' Repeats 12 more times...
EODTextBox.Text = FieldString(14)
InfoRichTextBox.Text = FieldString.LastOrDefault()
End If
End Sub
Sub PushUpdate()
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
'DefineTextFieldParse_Load()_Load() ' When Enabled code works fine when commented out generates alert.
UpdateCheck()
End Sub
End Class
mchihinney - I did review https://msdn.microsoft.com/en-us/library/hks5e2k6.aspx
However what I found was the issue was with the formatting of the text file. The problem I found was with the text file there was a second line which was blank, so when it tried to parse nothing it through the error. Deleting the second line from the .txt file and worked as expected.

VB.net program hangs when asked to read .txt

I am attempting to read a .txt file that I successfully wrote with a separate program, but I keep getting the program stalling (aka no input/output at all, like it had an infinite loop or something). I get the message "A", but no others.
I've seen a lot of threads on sites like this one that list all sorts of creative ways to read from a file, but every guide I have found wants me to change the code between Msgbox A and Msgbox D. None of them change the result, so I'm beginning to think that the issue is actually with how I'm pointing out the file's location. There was one code (had something to do with Dim objReader As New System.IO.TextReader(FileLoc)), but when I asked for a read of the file I got the file's address instead. That's why I suspect I'm pointing to the .txt wrong. There is one issue...
I have absolutely no idea how to do this, if what I've done is wrong.
I've attached at the end the snippet of code (with every single line of extraneous data ripped out of it).
If it matters, the location of the actual program is in the "G01-Cartography" folder.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine()
MsgBox("C")
End Using
MsgBox("D")
End Sub
What does running this show you in the debugger? Can you open the Map_Cygnus.txt file in Notepad? Set a breakpoint on the first line and run the program to see what is going on.
Private BaseDirectory As String = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\"
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim WholeMap = File.ReadAllText(Path.Combine(BaseDirectory, "Map_Cygnus.txt"))
Debug.Print("Size Of Map: {0}", WholeMap.Length)
End Sub
It looks like you're using the correct methods/objects according to MSDN.
Your code runs for me in an new VB console app(.net 4.5)
A different approach then MSGBOXs would be to use Debug.WriteLine or Console.WriteLine.
If MSGBOX A shows but not B, then the problem is in constructing the stream reader.
Probably you are watching the application for output but the debugger(visual studio) has stopped the application on that line, with an exception. eg File not found, No Permission, using a http uri...
If MSGBOX C doesn't show then problem is probably that the file has problems being read.
Permissions?
Does it have a Line of Text?
Is the folder 'online'
If MSGBOX D shows, but nothing happens then you are doing nothing with WholeMap
See what is displayed if you rewite MsgBox("C") to Debug.WriteLine("Read " + WholeMap)
I have a few suggestions. Firstly, use Option Strict On, it will help you to avoid headaches down the road.
The code to open the file is correct. In addition to avoiding using MsgBox() to debug and instead setting breakpoints or using Debug.WriteLine(), wrap the subroutine in a Try...Catch exception.
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
MsgBox("A")
Using File As New StreamReader(FileLoc)
MsgBox("B")
Dim WholeMap = File.ReadLine() 'dimming a variable inside a block like this means the variable only has scope while inside the block
MsgBox("C")
End Using
MsgBox("D")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that you normally should only catch whatever exceptions you expect, but I generally catch everything while debugging things like this.
I would also like to point out that you are only reading one line out of the file into the variable WholeMap. That variable loses scope as soon as the End Using line is hit, thereby losing the line you just read from the file. I'm assuming that you have the code in this way because it seems to be giving you trouble reading from it, but thought I would point it out anyway.
Public Class GameMain
Private WholeMap As String = ""
Private Sub GameMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
LoadMap("Map_Cygnus.txt")
End Sub
Private Sub LoadMap(FileLoc As String)
Try
FileLoc = "C:\Users\Adam\Documents\Visual Studio 2013\Projects\G01-Cartography\Maps\" + FileLoc
Using File As New StreamReader(FileLoc)
WholeMap = File.ReadLine() 'dimming the variable above will give all of your subs inside class Form1 access to the contents of it (note that I've removed the Dim command here)
End Using
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

File not being written to in vb.net

I did some google searching and everyone gives me the same answer which isn't working. I hope its something simple I am missing. I am trying to test write a line to a txt file. The file was created just fine when I used similar code, and no errors are thrown, the txt just doesn't write/save to the file. I am using stream writer in VB.
Here is my code:
Imports System.IO
Public Class Form1
Private Sub btnGen2DArray_Click(sender As Object, e As EventArgs)
Handles btnGen2DArray.Click
Try
'this is the file created and where it is saved:
Dim fileLoc As String = "c:\Users\clint\save.txt"
If File.Exists(fileLoc) Then
Using sw As New StreamWriter(fileLoc)
sw.Write("Test line write")
sw.Close()
End Using
End If
MsgBox("C++ 2D array text file created in: " + fileLoc, MsgBoxStyle.OkOnly, "Successful")
Catch ex As Exception
MsgBox("error: " + e.ToString(), MsgBoxStyle.OkOnly, "Error")
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Close()
End Sub
End Class
I am using vb 2012 if this helps. Normal windows form application.
You need to close your StreamWriter when you are done. sw.Close
You must call Close to ensure that all data is correctly written out
to the underlying stream.
Better yet, use Using. The following would go inside your if:
Using sw As New StreamWriter(fileLoc)
sw.Write("Test line write")
For rowcount As Double = 1 To rows
For colcount As Double = 1 To cols
'when the file write test works I will finish the rest of the code here
Next
Next
End Using
This will automatically dispose of the StreamWriter for you.

Move file in Windows-Service

This is my first time making a windows service app. I'm trying to move files from one folder to another using a windows service app. It'll do so every 10 seconds.
This is the code I'm using. It works when I use it on a windows form app but doesn't work when I use it on a windows-service app.
The code in the Timer1_Tick works if I use it in OnStart. But doesn't work in the timer.
Protected Overrides Sub OnStart(ByVal args() As String)
Timer1.Enabled = True
End Sub
Protected Overrides Sub OnStop()
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim FileToMove As String
Dim MoveLocation As String
Dim count1 As Integer = 0
Dim files() As String = Directory.GetFiles("C:\Documents and Settings\dmmc.operation\Desktop\Q8")
Dim pdfFiles(100) As String
For i = 0 To files.Length - 1
If Path.GetExtension(files(i)) = ".pdf" Then
pdfFiles(count1) = files(i)
count1 += 1
End If
Next
For i = 0 To pdfFiles.Length - 1
If pdfFiles(i) <> "" Then
FileToMove = pdfFiles(i)
MoveLocation = "C:\Documents and Settings\dmmc.operation\Desktop\Output\" + Path.GetFileName(pdfFiles(i))
If File.Exists(FileToMove) = True Then
File.Move(FileToMove, MoveLocation)
End If
End If
Next
End Sub
Windows.Forms.Timer won't work without a Form instantiated. You should be using System.Timers.Timer instead:
Private WithEvents m_timer As System.Timers.Timer
Protected Overrides Sub OnStart(ByVal args() As String)
m_timer = New System.Timers.Timer(1000) ' 1 second
m_timer.Enabled = True
End Sub
Private Sub m_timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles m_timer.Elapsed
m_timer.Enabled = False
'Do your stuff here
m_timer.Enabled = True
End Sub
I've also build a service that moves files that are dropped into a folder but I'm using the FileSystemWatcher. The FileSystemWatcher allows me to move the file when a new one is created, create an entry in a SQL Database and send an email notification when it's all done.
This is how I have setup the FileSystemWatcher
Set a folder to watch: watcher.Path = "C:\Folder to Watch"
Set the file type to watch: watcher.Filter = "*.pdf".
The type of event to watch and the Method that gets triggered: watcher.Created += new FileSystemEventHandler(OnChanged);
Lastly, I need to enable the event: watcher.EnableRaisingEvents = true;
Unfortunately, I have instances on a daily basis where the files do not get moved successfully. I get IO exceptions for file in use. The files get copied but the file in the destination folder is 0kb.
I'm trying to troubleshoot it and I've manage to debug remotely but I still haven't figured out what I am doing wrong.
The most common error I get is: Error: System.IO.IOException: The process cannot access the file 'fileName.pdf' because it is being used by another process.
this error does not make sense as the file did not exist prior to my service trying to move it...
Any further help would be appreciated.

How to hide Windows 7 Open File Security when running certain EXE file using VB.NET?

Hello dearest community,
I am trying to build a simple AutoUpdate application using VB.NET. It was quite simple. That is, I put the newest ZIP file in my hosting site, and then download it using WebClient.DownloadFileAsync. After it get downloaded, I extract it using http://stahlforce.com/dev/unzip.exe
But each time I run the unzip.exe using Process.start, Windows 7 always show Open File Security.
Is it possible for VB.NET to bypass such security restriction?
Thanks.
Btw, this is my code of using WebClient.DownloadFileAsync, in case any one google about it and landed on this page :
Public Class AutoUpdate
Dim installationFolder As String = "C:\Program Files\xyz\abc\"
Dim updateFileNameTarget As String
Private Sub btnStartUpdte_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStartUpdte.Click
lblPercent.Text = ""
lblDownloading.Text = ""
lblDownloading.Text = ""
pbDownloadStatus.Value = 0
Dim wc As New WebClient
AddHandler wc.DownloadFileCompleted, AddressOf downloadComplete
AddHandler wc.DownloadProgressChanged, AddressOf progressChanged
Dim path As String = "http://xyz.abc.com/test.zip"
updateFileNameTarget = installationFolder & "test.zip"
Try
If File.Exists(updateFileNameTarget) Then
File.Delete(updateFileNameTarget)
End If
lblDownloading.Text = "Downloading " & path
wc.DownloadFileAsync(New Uri(path), updateFileNameTarget)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub progressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
pbDownloadStatus.Value = e.ProgressPercentage
lblPercent.Text = e.ProgressPercentage & "%"
End Sub
Private Sub downloadComplete(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
MessageBox.Show("Download complete. Now extracting")
Dim cmd As String = Application.StartupPath & "\Tools\unzip.exe"
Dim arg As String = "-o """ & updateFileNameTarget & """"
Process.Start(cmd, arg)
End Sub
End Class
If you're already process-invoking everything else (including unzip), also use Sysinternal's streams.exe. Use the -d flag to remove the NTFS alternate data streams (ADS). There should only be one - and it is the one that indicates to Windows that the file was downloaded from an "untrusted source".
Your downloaded files will currently have a stream that looks like this:
:Zone.Identifier:$DATA 26
Remove this stream from the download files after extracting but before execution, and the warning will no longer appear.
See also: What is Zone Identifier? - and Accessing alternate data streams in files for a library to work with these within .NET without needing streams.exe.