how can i see output of Console.Error.WriteLine? - vb.net

in vb.net i have some code that looks like this:
Imports System
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Public Class Form1
Public Sub New1()
Directory.SetCurrentDirectory("C:\Users\alexluvsdanielle\Desktop\") '"
Console.WriteLine("Chapter 10 example 10: nested PdfPTables")
Dim doc As Document = New Document(PageSize.A4, 50, 50, 50, 50)
Try
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("Chap1010.pdf", FileMode.Create))
doc.Open()
Dim table As PdfPTable = New PdfPTable(4)
Dim nested1 As PdfPTable = New PdfPTable(2)
nested1.AddCell("1.1")
nested1.AddCell("1.2")
Dim nested2 As PdfPTable = New PdfPTable(1)
nested2.AddCell("2.1")
nested2.AddCell("2.2")
Dim k As Integer = 0
While k < 24
If k = 1 Then
table.AddCell(nested1)
Else
If k = 20 Then
table.AddCell(nested2)
Else
table.AddCell("cell " + k)
End If
End If
System.Threading.Interlocked.Increment(k)
End While
table.TotalWidth = 300
table.WriteSelectedRows(0, -1, 100, 600, writer.DirectContent)
doc.Close()
Catch de As Exception
Console.Error.WriteLine(de.Message)
Console.Error.WriteLine(de.StackTrace)
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
New1()
End
End Sub
End Class
i would like to see what the console is writing. how do i do this?

An alternative is to use the System.Diagnostics.Trace class for these messages. Then they will show up in your Visual Studio output window, and you can optionally attach other "listeners", like a ConsoleTraceListener (for the console, when it's available) or the TextWriterTraceListener (for log files). You can even implement your own (like a DatabaseLogTraceListener or MessageBoxTraceListener — be careful with that last one, though).

I have piped the output of a WinForms application by starting it from the command line:
myapp.exe > debugfile.txt
I've done that before to redirect the output to a file that I can then read.

Why not use Debug.Print ? it will show up in the output window while developing and is much cleaner then a bunch of Message boxes everywhere...

There is no Console in a Winforms application.
You will need to use a MessageBox to display your message.
MessageBox.Show(de.Message)

I have my own solution:
I created a form with a multiline textbox docked to fill the window size. I created a function to append some text to the textbox. My function looks like this:
Friend Sub ConsoleBox(ByVal message As String)
If frmConsole.Visible = False Then
frmConsole.Show()
End If
frmConsole.txtConsole.AppendText(message & vbNewLine)
End Sub
Then, instead of using MsgBox("error message") i call my function this way:
ConsoleBox("My error message")
This has worked so far, and replaces all the annoying message boxes whose Accept buttons you must clik every time something goes wrong.
Hope this helps.

Related

Vb.Net Control Variable Names

I am trying to create bunch of WebBrowsers with Variable Names; I started with the following code, but seems it has something wrong that I cannot figure our;
The error is in the FIRST PORTION OF THE CODE;
Any help/comment appreciated:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim NumberOfBrowsers As Integer = 12
For Pro As Integer = 1 To NumberOfBrowsers
Dim frmNew As New Form
'------------------------- FIRST PORTION:
Dim MekdamBrowser As New WebBrowser
MekdamBrowser = "WebBrowser" & Pro
frmNew.Controls.Add(MekdamBrowser)
'-------------------------
MekdamBrowser.Location = New System.Drawing.Point(10, 10)
MekdamBrowser.Size = New System.Drawing.Size(300, 300)
MekdamBrowser.Show()
'-------------------------
Next
End Sub
End Class
Thanks
It seems that you want the first portion to be as follow instead :
'------------------------- FIRST PORTION:
Dim MekdamBrowser As New WebBrowser
MekdamBrowser.Name = "WebBrowser" & Pro
frmNew.Controls.Add(MekdamBrowser)
'-------------------------
The difference between this and the original code you tried is, above code assigns name for WebBrowser control, where corresponding line of code in question tried to "replace" WebBrowser control it self with a name (it tried to assign string data to variable of type WebBrowser which is not a valid operation).

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.

NO WAY to get the text from a panel control of another application

I'm trying to get information from a windows form of another application.
I can read data from textbox or label of this application but not from a PANEL,because this panel doesnt contain controls.
I need your suggestions.
Thanks in advance.
Here the code that i'm using :
For Each top As windowsAPIoutils.ApiWindow In enumerator.GetTopLevelWindows()
For Each child As windowsAPIoutils.ApiWindow In enumerator.GetChildWindows(top.hWnd)
If top.MainWindowTitle.StartsWith("TITLE_Of_APPLICATION") Then
'The class name of the control
If child.ClassName = "TEdit" Then
textbox1.Text = child.MainWindowTitle
End If
End If
Next child
Next top
The only way that you can use the Win32 API to do this is if the item whose text you want to grab is a Win32 control, backed by an actual window.
That's why it works fine if the other item is a textbox or a label, because those are both implemented using Win32 EDIT and STATIC controls, respectively.
I don't know exactly what you mean by a "panel", but my guess is that it has been custom drawn by the other application. You'll therefore need to ask that application for the text it contains. Windows cannot give it to you because it is not a standard Windows control. If you cannot ask the other application, for whatever reason, you will need to research alternative methods, like UI automation.
If by "panel", you mean a group box, well then that is just a standard Windows button control and it has a caption (displayed at the top). You can retrieve that in the same way you'd retrieve the caption of a label control. In Win32 terms, that means sending a WM_GETTEXT message to the control.
Here is a solution that i used:
Tesseract an open source OCR engine and here the link to get it : https://code.google.com/p/tesseract-ocr/
how to use it :
Imports System.IO
Imports System.Threading
Imports System.Collections.Specialized
Public class myClass
Private ProcessList As New Hashtable
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button.Click
Dim croppedFile as String = "C:\image.tif"
Dim OCRProcess As Process = New Process()
OCRProcess.StartInfo.FileName = "C:\tesseract\tesseract.exe"
OCRProcess.StartInfo.Arguments = croppedFile & " " & croppedFile & " -l eng"
OCRProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
OCRProcess.StartInfo.CreateNoWindow = True
OCRProcess.EnableRaisingEvents = True
AddHandler OCRProcess.Exited, AddressOf Me.ProcessExited
OCRProcess.Start()
ProcessList.Add(OCRProcess.Id.ToString, croppedFile & ".txt")
Do While Not OCRProcess.HasExited
Application.DoEvents()
Loop
End Sub
Friend Sub ProcessExited(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Proc As DictionaryEntry
Dim oRead As StreamReader
Dim EntireFile As String = ""
For Each Proc In ProcessList
If (sender.id.ToString = Proc.Key) Then
oRead = File.OpenText(Proc.Value)
EntireFile = oRead.ReadToEnd()
End If
Next
MsgBox(EntireFile)
End Sub
End Class
Hope it will help someone

Populating a combo box with the first word of a textfile

So I feel like im pretty close, but I also have a feeling I am mixing up StreamReader and ReadAllLines
....................................................................................
Option Strict On
Imports System.IO
Public Class Form4
Dim file As System.IO.StreamWriter
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
file = My.Computer.FileSystem.OpenTextFileWriter("c:\devices.bat", False)
file.WriteLine("#echo off")
file.WriteLine("cd " & Form1.TextBox2.Text)
file.WriteLine("adb devices > C:\devices.txt")
file.Close()
Shell("C:\devices.bat", AppWinStyle.Hide, True, 500)
Dim output() = System.IO.File.ReadAllLines("C:\deviceinfo2.txt")
Dim Devices As String = ""
Dim line() As String = {}
For X = 1 To output.Count = -1
line = output(X).Split(New Char() {(" ")})
Devices = line(0)
ComboBox1.Items.Add(Devices)
Next
output.Close()
output.Dispose()
End Sub
End Class
........................................................................
What I am trying to have it do is to start reading on line two of devices.txt and then read the first word from each line until the text file is done.
It seems simple enough, but like I said, I think I am mixing streamreader with readalllines
Any help is appreciated
Class Test
Public Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As New StreamReader("TestFile.txt")
Dim line, firstWord As String
Dim i as Integer = 0
' Read and display lines from the file until the end of
' the file is reached.
Do
line = sr.ReadLine()
If Not (line Is Nothing) AndAlso i > 0 Then
firstWord = line.Split(" ")(i)
'do your logic
End If
i += 1
Loop Until line Is Nothing
End Using
Catch e As Exception
' Let the user know what went wrong.
End Try
End Sub
End Class
Grabbed this from MSDN and modified it. It should compile, but I didn't test it. This will loop through the lines, 1 by 1, skip the first line and grab each line's first word after. Hope this helps.

persisting textbox text in visual basic

I am pretty new to VB and am compiling a program which contains several forms, each of which is populated with text boxes. The purpose of the program is for text to be dragged between boxes to move assets around. I've managed the drag and drop functionality but need to persist the text in the text boxes once the program is shut down so that when reopened, the last location of all moved text is still present.
Can anyone make any suggestions/supply sample code please?
I've tried the easiest to understand suggestion to get me started but when I build and publish the program it says that I do not have access to the file to save the values!! Can anyone help? Code below
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim txtpersist As IO.TextWriter = New IO.StreamWriter("C:\Users\HP\Documents\namestore")
txtpersist.WriteLine(TextBox1.Text)
txtpersist.WriteLine(TextBox2.Text)
txtpersist.WriteLine(TextBox3.Text)
txtpersist.Close()
Dim yourfile As IO.TextReader = New IO.StreamReader("C:\Users\HP\Documents\namestore")
TextBox1.Text = yourfile.ReadLine()
TextBox2.Text = yourfile.ReadLine()
TextBox3.Text = yourfile.ReadLine()
yourfile.Close()
End Sub
End Class
You can use the built in PropertyBinding to link your TextBox.Text to a Property. It will put it into your App.Config File which will allow you to edit it through MySettings as long as it is per user. If the settings are application level you would be better of using one of the other answers. You can also look at this article for some more information.
You should write the location of the textboxes to a persistent store on program exit, such as a file, a database, or the registry. On program load, you can retrieve the saved values and set the locations accordingly.
You could save each textbox's text inside of a file and re-open it at runtime.
Dim yourfile As TextWriter = New StreamWriter("pathtofile")
Say you had 3 textBoxes called textBox1, textBox2 and textBox3. You would save each one's status by simply writing each textbox's text property inside the file. Like so:
yourfile.WriteLine(textBox1.Text)
yourfile.WriteLine(textBox2.Text)
yourfile.WriteLine(textBox3.Text)
At the end, you just close the file.
yourfile.Close()
Loading the data back is just as simple.
Dim yourfile As TextReader = New StreamReader("pathtofile")
textBox1.Text = yourfile.ReadLine()
textBox2.Text = yourfile.ReadLine()
textBox3.Text = yourfile.ReadLine()
yourfile.Close()
Let me know if you have any questions or require further assistance. Be sure to import the System.IO namespace, to get access to the IO classes used here.
The most common method of persisting data is to store it in a database. Of course that adds more work to your project since you now have to create, update, and maintain a database. An easier solution is to use a file.
We'll create a new class in order to read & write data from the file. This way if you switch to a database later on, you only need to change the class. And since I'm sure at some point you'll want a database we'll make the class use datatables to minimize the changes needed to it. Here's our class:
Public Class TextBoxes
Private tbl As DataTable
Private filename As String
'Use constants for our column names to reduce errors
Private Const ctrlName As String = "CtrlName"
Private Const text As String = "Text"
Public Sub New(ByVal file As String)
'Create the definition of our table
tbl = New DataTable("TextBox")
tbl.Columns.Add(ctrlName, Type.GetType("System.String"))
tbl.Columns.Add(text, Type.GetType("System.String"))
'Save the filename to store the data in
Me.filename = file
End Sub
Public Sub Save(ByVal frm As Form)
Dim row As DataRow
'Loop through the controls on the form
For Each ctrl As Control In frm.Controls
'If the control is a textbox, store its name & text in the datatable
If TypeOf (ctrl) Is TextBox Then
row = tbl.NewRow
row.Item(ctrlName) = ctrl.Name
row.Item(text) = ctrl.Text
tbl.Rows.Add(row)
End If
Next
'Save the additions to the dataset and write it out as an XML file
tbl.AcceptChanges()
tbl.WriteXml(filename)
End Sub
Public Sub Load(ByVal frm As Form)
'Don't load data if we can't find the file
If Not IO.File.Exists(filename) Then Return
tbl.ReadXml(filename)
For Each row As DataRow In tbl.Rows
'If this control is on the form, set its text property
If frm.Controls.ContainsKey(row.Item(ctrlName)) Then
CType(frm.Controls(row.Item(ctrlName)), TextBox).Text = row.Item(text).ToString
End If
Next
End Sub
End Class
Next you'll want to use this fine class to read & write your data. The code for doing this is nice and simple:
Dim clsTextBoxes As New TextBoxes("C:\Txt.xml")
'Save the textboxes on this form
clsTextBoxes.Save(Me)
'Load the textboxes on this form
clsTextBoxes.Load(Me)
I would do it using either the Application settings as Mark Hall pointed out or like this...
Public Class MyTextBoxValueHolder
Public Property Value1 As String
Public Property Value2 As String
Public Property Value3 As String
Public Sub Save(Path As String)
Dim serializer As New XmlSerializer(GetType(MyTextBoxValueHolder))
Using streamWriter As New StreamWriter(Path)
serializer.Serialize(streamWriter, Me)
End Using
End Sub
Public Shared Function Load(Path As String) As MyTextBoxValueHolder
Dim serializer As New XmlSerializer(GetType(MyTextBoxValueHolder))
Using streamReader As New StreamReader(Path)
Return DirectCast(serializer.Deserialize(streamReader), MyTextBoxValueHolder)
End Using
End Function
End Class
So what you can then do is...
Dim myValues As MyTextBoxValueHolder = MyTextBoxValueHolder.Load("SomeFilePath.xml")
myTextBox1.Text = myValues.Value1
myTextBox2.Text = myValues.Value2
'And so on....
2 Save
Dim myValues As New MyTextBoxValueHolder
myValues.Value1 = myTextBox1.Text
myValues.Value2 = myTextBox2.Text
myValues.Save("SomeFilePath.xml")
'All saved
to maintain the values ​​you can use stored user settings, see the following links.
http://msdn.microsoft.com/en-us/library/ms379611(v=vs.80).aspx
http://www.codeproject.com/KB/vb/appsettings2005.aspx
Regards.