How can I Display Text Files? - vb.net

I have a program that allows the user to complete test where all the user's scores are recorded in a seperate text file for each test. How would I display each text file so that for each test the scores can be displayed?

You can do this with a Linq query:
var scores = from file in System.IO.Directory.GetFiles(#"c:\path", "*.scores")
select GetScoreFromFile(System.IO.File.ReadAllLines(file));
with GetScoreFromFile:
private int GetScoreFromFile(string[] scoreLines)
{
// Some code to read the score from the file
}
To actually display the scores... You probably want to make something fancy (it sounds pretty game-like). If not, go with some sort of Grid control.

You can use an ini configuration file to do this. I have designed a VB class library which contains an ini File reader class which can be used to read and write to ini configuration files. Rather than save each score as a separate file, you can contain it in a single ini configuration file by separating them in sections.
You can download my class library here
Add a reference to the library in your project.
Here is an example of how to use it:
Dim ScoresReader As New Rodit.IniLib.IniParser
Public Sub ReadTestScores(ScoreFilePath As String)
ScoresReader = New Rodit.IniLib.IniParser 'Initializes new instance of class
ScoresReader.Load(ScoreFilePath) 'Loads scores file specified in subroutine args
For Each score As Rodit.IniLib.IniParser.IniSection In ScoresReader.Sections 'Each section in the ini file will represent a different user's score
'Here you can write whatever you want to do with the user's score
Next
End Sub
'Call example:
Protected Sub Form_Load(sender As Object, e As EventArgs) Handles Me.Load
ReadTestScores("C:\scores.ini")
End Sub
Ini file stucture:
[INIFILETEST] <-- Section
Name=Rodit
^ ^
| |
Key Value
By understanding this, it would be easy to read and write your scores using this method...
Hope this helped...
Rodit

Related

Extract file using SevenZip

I'm trying to add a file unzipper to my application, so I googled a little and stumbled on the sevenzipsharp library that is able to extract the most common archive formats.
So I for testing I created a simple application with a windows form.
So the entered data is the file location C:\Users\jeee\Desktop\CriticalSubPrintout.rar and the extract location C:\Users\jeee\Desktop\Test Extract
I added some code, without any documentation.. not my strong side apparently..
Imports SevenZip
Public Class Archiver
Private Sub btnExtractArchive_Click(sender As Object, e As EventArgs) Handles btnExtractArchive.Click
Dim Extractor As New SevenZipExtractor(tbExtractFile.Text)
Extractor.ExtractArchive(tbExtractPath.Text)
End Sub
End Class
This causes an error when I try and run the code
Can anyone provide a sample code, or a link to a good example how-to-use SevenZipSharp? Because I searched and can't find any VB.NET samples.
Or maybe just help me figure out what I need to do.
Thanks.
You need to call SevenZipBase.SetLibraryPath with the path to 7z.dll, and make sure that you are using the correct version for your application (32- or 64-bit). e.g.
SevenZipBase.SetLibraryPath("C:\Dev\7z.dll")
Dim Extractor As New SevenZipExtractor(tbExtractFile.Text)
Extractor.ExtractArchive(tbExtractPath.Text)

VB.NET batch pdf printer tool

I'm looking for a tool, but I can't find it. So I thought, maybe I can make one. Seems like a good idea, a program that fits my needs at last! Just one problem.. I don't know how!
Intro
At my work we create production drawings in .dwg format. Once this is done they are exported as .pdf sent to the client for approval. If approved they are issued for production, so they need to be plotted.
So my current workflow is:
Set my default printer preferences (number of copies, paper size, ..)
Go to the folder that has the .pdf files
Select 15 files
Right click print.
The problem here is
The files are printed in the order the printer receives them and not the order in the folder. So I would need to sort them out ( this x number times the number of copies sometimes this goes up to 6 times. )
I can only do 15 at a time (large projects are +100 documents)
I have to reset my preferences each time the sizes change.
Our file numbering system has some "intelligence" into it. Its build like this:
A1-12345-001 rev1
A1 = page size
12345 = document number, the same within a project. Other project means other number. (mostly irrelevant as I only print a project at a time)
001 = sequence number, next drawing will be 003,004,005,007,... you get the drift.
rev1 = revision number. Normally only the highest revision should be located in the folder, but it could be used to check for documents with a lower revision.
Now, I would like to automate my happy printing task, as this makes my week very bad if a large projects needs to go into production or, there are revisions mid-production and we need to re-issue them for production.
So far the situation sketch
Program sketch
So I've started to make a sketch of what the program should do.
User should be able to add .pdf files into a list. file browser object for starters, can be drag and drop later (the drawings are in one folder so there is no real need for drag and drop).
The list should contain 4 columns. paper size, document number, sequence, revision. Could be a data-grid view.
The list should be sorted by the drawing sequence. This how I would like to pass the drawing so, no sorting is required anymore! You can look at the sequence as page numbers.
Select the desired printer to do the job. (usually the same but other departments also have a printer so that would be a nice option.)
Set the number of copies. When printed, it shouldn't be 5x -001 then 5x -002 .. it should print them still in order of the sequence number and the re-loop the process x times.
Print the documents.
Adding PDF files
I started out with creating a dialog.. easy enough I guess.(please keep in mind that I'm a very low level programmer and nothing seems easy to me..) I added an open file dialog to my windows-form set multiple select true. Also made a filter to have only .pdf files
added a button with this code:
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim file As String
For Each file In FileDialog.FileNames
Debug.Print(file)
Next
End If
End Sub
So this should give me all the info I need from the file. I will edit this later, I know how to access it now!
The document object
I guess it would be wise to use some o.o.p. for this. As each file is a document and have the same required properties to make this work.
So I made a Public class for the document called PDF_Document
Public Class PDF_Document
Public FullFilePath As String
Public Property Size As String
Public Property DocNumber As String
Public Property Sequence As String
Public Property Revision As String
Public Sub New(ByVal oFilePath As String)
' Set the FullFilePath
FullFilePath = oFilePath
' Get the filename only without path.
Dim oFileName As String
oFileName = Path.GetFileName(oFilePath)
' Get the document size from the file name
Size = oFileName.Substring(0, 2)
' Get the document number from the file name
DocNumber = oFileName.Substring(3, 5)
' Get the sequence from the file name
Sequence = oFileName.Substring(9, 3)
' Chop of the .pdf from the name to get access the revision
Revision = oFileName.Substring(oFileName.Length - 5, 1)
End Sub
End Class
Well this should result into the info I need from the document..
creating a list(of t)
Wow, it seems to be getting somewhere.. Now to hold the list I'll have this collection I think don't know whats best for this? Public oPrintList As New List(Of PDF_Document)
So I think I should populate my list like this?
Public oPrintList As New List(Of PDF_Document)
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim oFile As String
For Each oFile In FileDialog.FileNames
Dim oPDF As New PDF_Document(oFile)
oPrintList.Add(oPDF)
Next
End If
End Sub
Making things visual for the user
Hmm okay, were getting somewhere, I got a list of all the files I need! But I want to see them in a viewer. I'm gonna use a data-grid view maybe? It should show my properties and it looks good I think.
So I made a binding that binds my List(of T) and added this binding as data-source for the data-grid view. I also change the ADD_FILES_Click a little, the PDF_Document is now added into the binding and not in the List(of T).
Public Class Form1
Public oPrintList As New List(Of PDF_Document)
Public oBinding As BindingSource
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim oFile As String
For Each oFile In FileDialog.FileNames
Dim oPDF As New PDF_Document(oFile)
oBinding.Add(oPDF)
Next
End If
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
oBinding = New BindingSource(oPrintList, Nothing)
DataGridView1.DataSource = oBinding
End Sub
End Class
Printing the list
Well I managed to do quite some things now. But.. the main essence still isn't reached! I now got a form with a bunch of buttons that don't work yet, a list of select documents in queue for printing and .. thats it :)
Now I'm trying to create a method that prints a .pdf file.. easier sad than done. I need some help with this.. I search the net, but I can find samples that don't work, or I don't understand. All users PC's are equiped with acrobat reader.
Also feel free to comment me on the other parts of the program. ( yes I know there is no sorting function yet etc. ) but getting a page from the printer is more important now.
Sorry for the long post!
If your users have Adobe Acrobat Reader installed, the following code should do the trick. I recommend Acrobat Reader 11 or lower version. With Acrobat DC the window from Acrobat does not close anymore, that is a "design" decision by Adobe.
Dim pr As New Process()
pr.StartInfo.FileName = "c:\myfile.pdf"
pr.StartInfo.UseShellExecute = True
pr.StartInfo.Verb = "print"
pr.Start()
pr.WaitForExit()
I work with DWG and PDF files for 20+ years. If you are interested in a solution that fully automates all steps you explained in your "wishlist" software and does a ton more feel free to contact me at pdfmagick at gmail dot com
Another way to print PDF files with the Print Drivers dialog is as follows:
Dim starter As ProcessStartInfo
starter = New ProcessStartInfo(<pathToAdobeAcrobatExecutable>, String.Format(" /s /N /P ""{0}""", Filename))
Dim Process As New Process()
Process.StartInfo = starter
Process.Start()
Process.WaitForExit()
Process = Nothing
starter = Nothing
More command line switches are explained here
Adobe Reader Command Line Reference
Regards

How to save a changed label when you exit

In my program I have a preview, and edit side.
When you edit using the text boxes on the edit side(right side) and click "save", It should change the label on the right side (preview side). Although when you exit the program and re-open, all the data you entered has disappeared!,
I have tried the below code and had no luck as my result.
Public Class Form1
Private Shared NameBasic As Integer
Public Sub New()
InitializeComponent()
lblNameBasic.Text = Convert.ToString(NameBasic)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
NameBasic = txtFirstBasic.Text
lblNameBasic.Text = Convert.ToString(NameBasic)
End Sub
End Class
Also my goal is to have it be able to take it on a flashdrive onto any computer and have that data still saved within the exe. Is this even manageable? (I am more of a web based programmer so I am a bit new to this)
You need to write values to a text file at the same location of the exe. and read it. you will need both exe and the textfile.
OR
You will need to write a dll on run-time and write some values while closing the application. this will be more secure then the text file. here you will need both exe and dll to be copied into flash drive
OR
the application setting as spoken by others..

How to check if a dictionary word is a part of a user input in vb?

I've coded a password analyser for a school project. I want it to be able to test if their password contains a dictionary word in any place. For example, kdghdcheesegjgjd would still be flagged because it contains cheese. Would I need to find a file containing a list of all dictionary words, or is their such a built-in function?
Thanks.
Most languages don't have any (human language) dictionaries built into them. You will need to find/make your own and have the program read from that file.
A personal tip is to make your own very short one for testing purposes (say 5 words) to see that the program reads and interprets the file properly.
As stated by #Jonas Olsson, there is no built-in dictionary in VB. You need to create them on your own. And making it is fairly easy, but I'll show easier way to solve your problem. First make a text file containing all the words you want your program to check if it contains that word. Then save it somewhere else, for the sake of my example, I'll create a text file containing the word "cheese". So:
Dim myFile As String = "D:\test.txt" //Location of my txt file
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim item() As String = File.ReadAllLines(myFile) //Reads whatever your txt file contains
//compares every line in your to text file to the password field
For Each line As String In item
If txtPassword.Text.Contains(line) Then
MessageBox.Show("Invalid password!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Next
End Sub
Hope that helps! Or atleast it gave you an idea :))
You will have to find your own dictionary somewhere. I've used the The Gutenberg Webster's Unabridged Dictionary in the past myself because it's public domain. However, it is in a pretty raw form, and you'll likely have to do a lot of processing on it to get it in a shape that is usable to you.
There are likely other public domain or "open sourced" wordlists somewhere that you can use. I suggest a google search for "public domain english word list" or "free english word list" or similar searches. Then it's just a matter of reading in the file and doing your processing against it.

Copy File on Modification FIleSystemWatcher, Visual Basic (VS 2012 V11)

After looking through many sites and some tutorial videos, I'm still stumped on this one. I'm finishing up a program and I need to add one last bit of functionality.
The program works this way. The user specifies a file in textbox1 and then specifies a directory in textbox2. The user sets how often they want the file to by copied in textbox3. The user hits run and the program copies the file to the new location, adding a number to the file name each time it is copied (to avoid overwrites). That all works fine, but I want the user to have the choice to either copy the file by time or when the file is modified.
How can I use the FileSystemWatcher to look for modification in the directory (given in textbox1) and then call the statement that copies the specified directory to the target destination (specified in textbox 2)?
Additional Note:
In one tutorial the FileSystemWatcher path was set up by doing this
Dim watched As String = System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Pictures")
Dim fsw As New FileSystemWatcher(watched)
The path that the code directs to is "C:\Users[User Name]\Pictures" .
I can't find a resource online that shows what variables ".GetEnvironmentVariable" accepts or even what the variables mean. This is one of many reasons why I am having trouble with this last bit code.
GetEnvironmentVariable returns the value for the specified environment for the current process.
In the case of your example, USERPROFILE is the path to the folder for the current user. For example, on my laptop USERPROFILE is C:\Users\Tim.
The output of System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Pictures") would be the USERPROFILE path plus "Pictures" - to continue with my example, it would be C:\Users\Tim\Pictures - which is the physical path to the My Pictures folder for my user account.
To get a list of all your environment variables, if you're curious, go to the DOS prompt and type in SET and hit return.
To answer your original question, you need to handle the FileSystemWatcher.Changed Event.
For example:
Private Shared Sub OnChanged(source As Object, e As RenamedEventArgs)
' Do your copy here
End Sub
You can hook the event handler up to your FileWatcher like this:
AddHandler fsw.Changed, AddressOf OnChanged
However, pay attention to this warning from the MSDN docs.
Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.
This is the code I used it does what I want it to.
Option Explicit On
Option Strict On
Imports System.IO
Imports Microsoft.VisualBasic ' I don't know this one, but the code worked without this.
Imports System.Security.Permissions ' I don't know the exactly what this does but the
' http://msdn.microsoft.com/ site did this, I assume it'f to allow for permission to
' watch files? The code still worked for me without this
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
Dim directoryPath As String = Path.GetDirectoryName(TextBox1.Text)
Dim varFileSystemWatcher As New FileSystemWatcher()
varFileSystemWatcher.Path = directoryPath
varFileSystemWatcher.NotifyFilter = (NotifyFilters.LastWrite)
varFileSystemWatcher.Filter = Path.GetFileName(TextBox1.Text) ' I know this
' limits what's being watched to one file, but right now this is
' what I want the program to do.
AddHandler varFileSystemWatcher.Changed, AddressOf OnChanged
varFileSystemWatcher.EnableRaisingEvents = True
End Sub
Private Sub OnChanged(source As Object, ByVal e As FileSystemEventArgs)
My.Computer.FileSystem.CopyFile(e.FullPath, TextBox2.Text & "\" & e.Name, True)
End Sub