Get data into tabular format on printing in vb.net - vb.net

I have a program which takes attendee’s names and contact details and writes them to a text file. In all, there are 20 rows and 5 columns which are used in my form so that when the user clicks on the ‘Save’ button, these details are written to a text file.
The code I am using works fine, and is shown below. Please note that this code is truncated to the first attendee only.
Dim AttendeeData = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Attendee Information\" & TextBox1.Text))
Dim FileNameTXT As String = Path.Combine(AttendeeData.FullName, "Attendee Data" + ".TXT")
Dim FileTXT As New System.IO.StreamWriter(FileNameTXT)
‘Write the Attendee details to the text file
‘Attendee Number 1
FileTXT.Write(Form1.TextBox2.Text) ‘Attendee’s Name
FileTXT.WriteLine("")
FileTXT.Write(Form1.TextBox3.Text) ‘Attendee's Nationality
FileTXT.WriteLine("")
FileTXT.Write(Form1.TextBox4.Text) ‘Attendee's Position
FileTXT.WriteLine("")
FileTXT.Write(Form1.TextBox5.Text) ‘Attendee's Email
FileTXT.WriteLine("")
FileTXT.Write(Form1.TextBox6.Text) ‘Attendee's telephone No.
FileTXT.WriteLine("")
‘Attendee Number 2 ... to Attendee Number 20
'The below line of code closes the writer
FileTXT.Close()
I decided to use this method because at some point, the text file has to be read from the text file, back into the textboxes on my form.
My problem is that when it comes to reporting, printing out these details in the above format would be cumbersome, using up sheets of paper to make the report unnecessarily plentiful. So I reckoned that displaying these data in a tabular format would be much more tidy and professional.
Please how can I achieve this? I am using Visual Basic 2010 Express. Thank you in advance.
The code I am currently using in printing is shown below:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim AttendeeData = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Attendee Information\" & TextBox1.Text))
For Each AttendeeDetailsTXT As FileInfo In AttendeeData.GetFiles("*.TXT", SearchOption.TopDirectoryOnly)
For Each line As String In File.ReadAllLines(AttendeeDetailsTXT.FullName)
If Not String.IsNullOrEmpty(line) Then RichTextBox1.AppendText(line & vbCrLf & vbCrLf)
Next
Next
' Send data to printing script
End Sub

How about recording the attendee's information in a structured format such as XML?
Writing the data to XML in code is quite simple - here is a good article on the subject: http://vb.net-informations.com/xml/create-xml-vb.net.htm
Reading the data back into your application will also be much simpler as you no longer have to rely on the lines in your unstructured input file being in a particular order which could cause issues with data being out of sync if, for example, a line is missing.
Displaying the data is slightly more tricky as you would have to use something like an XSLT to display your data in a tabular form but there are plenty of resources online which could get you started with this such as the W3Schools: http://www.w3schools.com/xsl/xsl_transformation.asp

Related

VBA - Reading PDF as String - Cannot sometimes but can other times - 'Run time error 62' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
You can open PDFs in text editors to see the structure of how the PDF is written.
Using VBA I have opened a PDF as a text file and go to extract the text and save it as a string variable in VBA. I want to look through this text to find a specific element; a polyline (called sTreamTrain) and get the vertices of the polyline by using the InStr function.
When i add more vertices to the polyline I cannot seem to extract the text string of the pdf. I get the error 'Run time error 62' which I do not understand what it means or what about the PDF has changed to now have this error.
Attached (via the link) is a PDF that I can read (Document 15) and a PDF I cannot read (Document 16). I have checked in excel so see that the vertices are present in both files. Also there is a copy of my VBA script as a notepad document and also my excel file (but it is difficult to find in my excel file - the script is "Module 6" function called "CoordExtractor_TestBuild01()")
Link:
https://drive.google.com/open?id=1zOhwnFWZZfy9bTAxKiQFSl7qiQLlYIJV
Code snippet of the text extraction process below to reproduce the problem (given an applicable pdf is used):
Sub CoordExtractor_TestBuild01()
'Opening the PDF and getting the coordinates
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
'File Path of Text File
FilePath = "C:\Users\KAllan\Documents\WorkingInformation\sTreamTrain\Document16 - Original.pdf"
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
'Store file content inside a variable
Dim Temp As Long
Temp = LOF(TextFile)
FileContent = Input(LOF(TextFile), TextFile)
'Clost Text File
Close TextFile
End Sub
I would like someone to let me know what runtime error 62 is in this context and propose any workflows to get around it in future. Also, I would like to know whether there certain characters you cannot store as strings? - Perhaps these are included when I increase the number of vertices past a certain number.
Also I would prefer to keep the scrips quite simple and not use external libraries because I want to share the script when it is done so others can use it thus its simpler if it works without extra dependencies etc, however, any and all advice welcome since this is only the first half of this project.
Thank you very much.
According to the MSDN documentation, this error is caused by the file containing
...blank spaces or extra returns at the end of the file or the syntax
is not correct.
Since your code works sometimes on documents with very similar names and content to documents where it doesn't work, we can rule out syntax errors in this case.
You can clean up the file contents before processing it any further by replacing the code at the top of your macro with the one below. With this I can read and extract information from your Document16.pdf:
Sub CoordExtractor_TestBuild01()
'Purpose to link together the extracting real PDF information and outputting the results onto a spreadsheet
'########################################################################################
'Opening the PDF and getting the coordinates
Dim n As Long
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
'File Path of Text File
FilePath = "C:\TEST\Document16.pdf" ' change path
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
Dim strTextLine As String
Dim vItem As Variant
Line Input #1, strTextLine
vItem = Split(strTextLine, Chr(10))
' clean file of garbage information line by line
For n = LBound(vItem) To UBound(vItem)
' insert appropriate conditions here - in this case if the string "<<" is present
If InStr(1, vItem(n), "<<") > 0 Then
If FileContent = vbNullString Then
FileContent = vItem(n)
Else
FileContent = FileContent & Chr(10) & vItem(n)
End If
End If
Next n
'Clost Text File
Close TextFile
' insert the rest of the code here

Programmatical RDLC reporting

I'm a bit dumbfounded here. Most of the tutorials I've seen around create a report using the wizard or a built-in (or ready-made) dataset. I build my dataset using queries in runtime so I'm not too sure how to adopt the ones I've seen so far.
Usually, when I create a report, it's a one record report and fields in the RDLC file can easily be populated using parameters. The one I'm trying to do below however works similarly to making a SELECT query. So here's what I'm trying to do, I'm trying to make a report that shows up like so:
Status: Approved
PID | Name | Address
1 | Name 1 | Address 1
2 | Name 2 | Address 2
===========================
Status: Denied
PID | Name | Address
3 | Name 3 | Address 3
4 | Name 4 | Address 4
I have several questions with this:
My RDLC reports are stored in a "\Reports" folder inside the folder with the .vb/.resx files. When I refer to it's using Application.StartupPath & "\Reports\myReport.rdlc", it can't find it there (obviously). Is there a way for me to embed the report files to the program (ie: use a relative folder name, where should I place the RDLC folder/file)? I don't think I should transfer the RDLC files to the Debug folder just to make this work (hence the full directory listing).
What's a good approach to take in trying to create a report using the code above? I was thinking that if I were to loop along my dataset and pass the values from there to the RDLC file as parameters, it would populate the report (as with my one-record report before) but that doesn't seem to be the case.
Refreshing the report viewer also gives me
A data source instance has not been supplied for the data source 'Dataset1'.
I created a dummy dataset in the RDLC file just to be able to use a Tablix as was suggested in several threads I read around. I'd really prefer if I could just use the dataset I made from scratch rather than use the wizard for that.
Private Sub btnGenerateReport_Click(sender As Object, e As EventArgs) Handles btnGenerateReport.Click
Dim query As String
query = BuildQuery()
SQLControl = New SQLControl
Try
If Not query = String.Empty Then
SQLControl.QueryParams(query)
If SQLControl.SQLDS.Tables(0).Rows.Count > 0 Then
FetchData()
End If
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Report Maker")
End Try
End Sub
Private Sub FetchData()
Dim dataSource As ReportDataSource
Dim PID As Integer
Dim Name As String
Dim ApplicationStatus As String
Dim Address As String
rvPreview.Reset()
rvPreview.LocalReport.ReportPath = "C:\Users\xxx\Documents\Visual Studio 2015\Projects\My Project 1\My Project 1\Reports\myReport.rdlc"
rvPreview.LocalReport.DataSources.Clear()
dataSource = New ReportDataSource()
_rparams = New List(Of ReportParameter)
With SQLControl.SQLDS.Tables(0)
For x As Integer = 0 To .Rows.Count - 1
PID = .Rows(x).Item("PID")
Name = .Rows(x).Item("LName") & ", " & .Rows(x).Item("FName")
ApplicationStatus = .Rows(x).Item("ApplicationStatus")
Address = .Rows(x).Item("StreetAddress") & ", " & .Rows(x).Item("City")
_rparams.Add(New ReportParameter("PID", PID))
_rparams.Add(New ReportParameter("Name", Name))
_rparams.Add(New ReportParameter("ApplicationStatus", ApplicationStatus))
_rparams.Add(New ReportParameter("Address", Address))
For Each param As ReportParameter In _rparams
rvPreview.LocalReport.SetParameters(_rparams)
Next
Next x
rvPreview.RefreshReport()
End With
End Sub
At the begining I have to mention that I use RDLC reports with C#, but the solution should be very similar in vb.net.
I usualy prepare every report as separate project (so I have separate DLL for every report) and use a separate class in this project to handle everything I need to do with report. I add Every RDLC file just under the project (main report file and subreports files). In my case I can read every RDLC file like a stream just using project namespace and RDLC filename as in this sample code below
Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("[Some project namespace].[Some report filename].rdlc");
Then I use a code like this to connect that stream with report viewer (the stream in this code is the same object as above but this code is in another class which has access to report viewer object)
ReportViewerControl.LocalReport.LoadReportDefinition(new StreamReader(stream));
You can provide a DataSet for your report in very simple way. You can use object of the System.Data.DataTable class for table (I call this object as yourTableObject in code below) and System.Data.DataRow class for rows in that table. When you put all your data in the table then you can provide it to the report using code like this
//I use DataSet1 as dataset name because you use this name in your report definition
ReportDataSource rds = new ReportDataSource("DataSet1", yourTableObject);
ReportViewerControl.LocalReport.DataSources.Add(rds);
Ofcourse provided table should have the same fields like the dataset in your report definition.
You have to provide a valid DataSet to the report. Solution is above in point 2.

Issue with pdf docs not showing up

We recently wrote some code for a client using the Aspose.pdf library, on my system the pdf in question opened fine and most of the merge fields were filled in (we don't have the exact list of merge fields that they do).
They're telling me that on their system, some documents take 2-4 mins to open while others don't open at all.
What could be a possible cause of the document not opening at all?
My code is below:
' Load form
Dim doc As Aspose.Pdf.Document = New Aspose.Pdf.Document(sTemplateDir & sDocName)
'Get names of form fields
Dim fields As Aspose.Pdf.InteractiveFeatures.Forms.Field() = doc.Form.Fields
Dim sField As String
Dim field As Aspose.Pdf.InteractiveFeatures.Forms.Field
If fields.Length > 0 Then
For Each field In fields
'Get name of field
sField = field.FullName
'If the merge field isn't valid then we'll just leave it and assume its a fill-in
If nMergeCol.Contains(sField) And Not IsNothing(sField) Then
field.Value = nMergeCol.Item(sField)
End If
Next
End If
This has been resolved! As we suspected, it was a problem with the client's Javascript within the pdf file. The problem was within the calculations the absolute value was being used (name.value). Once this was switched to the relative value (this.event.value) the pdf file began behaving correctly with the AsPose code.

How to read VB formatted code from a text file?

I writing a pair of programs in visual basics that will consist of a client and receiver. The client is completed making an output text file similar to below.
Dim FileName As String = "Text.txt"
Dim message As String
Dim file As System.IO.StreamWriter
'lblmessage.text says "Call MsgBox("Hello!", 0, "Version Beta 0.3")"
lblmessage.text = message
Dim Drive As String = "C:\hello world\" & FileName
file = My.Computer.FileSystem.OpenTextFileWriter(Drive, True)
file.WriteLine(message)
file.Close()
A sister program that is designed to be a reader will read the generated file.
The program will then take the text located in the selected file and use it as code in the readers programming.
Best example I can show...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\hello world\Text.txt")
fileReader
End Sub
where "fileReader" is suppose to run the generated code from the previous program and use it as code it the Reader.
The point of this program is to create help tickets in the client and have a tool for reviewing these ticket in the same way they were submitted through the second app.
vba and vb.net is different. I'm not sure in which language your doing your stuff.
vba: use the ScriptControl.Eval command to execute a bunch of commands.
vb.net: it's a bit more code. you can use VBCodeProvider Class. s this SO Question: Load VB.net code from .txt file and execute it on fly using System.CodeDom.Compiler
UPDATE
I found a perfekt resource if you are interested in how to do it right and how it works in the background: http://www.codemag.com/article/0211081

How to search data in a txt file through Visual Basic

I have this txt file with the following information:
National_Insurence_Number;Name;Surname;Hours_Worked;Price_Per_Hour so:
eg.: aa-12-34-56-a;Peter;Smith;36;12
This data has been inputed to the txt file through a VB form which works totally fine, the problem comes when, on another form. This is what I expect it to do:
The user will input into a text box the employees NI Number.
The program will then search through the file that NI Number and, if found;
It will fill in the appropriate text boxes with its data.
(Then the program calculates tax and national insurance which i got working fine)
So basically the problem comes telling the program to search that NI number and introduce each ";" delimited field into its corresponding text box.
Thanks for all.
You just need to parse the file like a csv, you can use Microsoft.VisualBasic.FileIO.TextFieldParser to do this or you can use CSVHelper - https://github.com/JoshClose/CsvHelper
I've used csv helper in the past and it works great, it allows you to create a class with the structure of the records in your data file then imports the data into a list of these for searching.
You can look here for more info on TextFieldParser if you want to go that way -
Parse Delimited CSV in .NET
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(FileName)
Dim CurrentRecord As String() ' this array will hold each line of data
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {";"}
afile.HasFieldsEnclosedInQuotes = True
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
I'd recommend using CsvHelper though, the documentation is pretty good and working with objects is much easier opposed to the raw string data.
Once you have found the record you can then manually set the text of each text box on your form or use a bindingsource.