A common task when creating a form based windows application is to allow a user to save their information and to also load saved information. In this short tutorial I will show you the basic steps to save a form’s information to a file and then load up the contents of the saved file.

Saving a Form’s Data to a File

The process for saving data to a file is pretty straightforward in Visual Basic. They include opening up a writer to a specified file, writing the contents, and then closing the writer when completed.

  1. Define and open your File Writer
    In this case we will utilize the StreamWriter class of the System.IO package. I will assume for these instructions that you have imported the System.IO library.
    Dim FileWriter As StreamWriter ' define the stream writer
    
    ' Open the File for writing
    FileWriter = New StreamWriter("c:\temp\sampleFile.txt", False)
  2. Write the desired data to the file
    To write data to the file you can utilize the WriteLine function. In the case of forms you may want to write different data. For a text field saving the Text is appropriate while when using a check box or radio button you will want to save the Checked property.
     ' Save Component values
    FileWriter.WriteLine(textBox.Name & "|" & textBox.Text)
    FileWriter.WriteLine(comboBox.Name & "|" & comboBox.SelectedIndex.ToString())
    FileWriter.WriteLine(radioBtn.Name & "|" & radioBtn.Checked.ToString())
  3. Close and Save your data to the File
    To complete your write you simply need to call Close on your writer. However if you want you can first call Flush to have the data written out. This step is optional however as the Close function will call Flush if needed.
     ' Save and Close File
    FileWriter.Flush() ' optional as close will flush
    FileWriter.Close()

Reading Data from a File

The process for reading information out of a File is similar to the writing process. First you want to open up the file, then you want to read a line of data, single character, or etc depending on how you are going to process the data until you reach the end. After you have read all the data you would lastly close the File.

  1. Define and open your File Reader
    In this case we will utilize the StreamReader class of the System.IO package.
     Dim FileReader As StreamReader   ' define the File Reader
    FileReader = New StreamReader("c:\temp\sampleFile.txt", False)
  2. Iterate until the End of File is reached
    Do Until FileReader.EndOfStream
        ' Processing Code goes here
    Loop
  3. Read in and Process the File’s data
    In the below example we will read in the file’s contents 1 line at a time. To see the full example of how the data is processed please view the full source code below.
    'Read the next line
    prop = FileReader.ReadLine()
  4. Close the File Reader
    After the loop close the FileReader as all the data has been read.
    FileReader.Close()

A complete sample Save and Write Class

For those that learn better by example below is a Simple Class that holds a complete example of saving data to a File from a Form in addition to loading the saved data from the form and setting the components to the correct state. The example contains basic error checking including validating that the saved file exists, however it does not validate the data in the file is of the correct format and not corrupted.

Imports System.IO
 
Public Class Form1
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        loadSavedData()
    End Sub
 
    Private Sub CloseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseButton.Click
        Close() 'Close Application
    End Sub
 
    Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadButton.Click
        loadSavedData()
    End Sub
 
    Private Sub loadSavedData()
 
        Dim FileReader As StreamReader   ' define the File Reader
        Dim prop(2) As String            ' define array of length 2

        ' Test if the Saved File exists
        If File.Exists("c:\temp\sampleFile.txt") Then
 
            'Open the File for reading
            FileReader = New StreamReader("c:\temp\sampleFile.txt", False)
 
            ' Continue until EOF reached
            Do Until FileReader.EndOfStream
 
                'Read the next line and split its value based on the | character
                prop = FileReader.ReadLine().Split("|")
 
                ' If TextBox Component set it's property
                If String.Equals(prop(0), textBox.Name) Then
 
                    textBox.Text = prop(1)
 
                    ' If ComboBox Component set it's property
                ElseIf String.Equals(prop(0), comboBox.Name) Then
 
                    comboBox.SelectedIndex = Integer.Parse(prop(1))
 
                    ' If RadioButton set if checked
                ElseIf String.Equals(prop(0), radioBtn.Name) Then
 
                    radioBtn.Checked = Boolean.Parse(prop(1))
 
                ElseIf String.Equals(prop(0), RadioButton1.Name) Then
 
                    RadioButton1.Checked = Boolean.Parse(prop(1))
 
                ElseIf String.Equals(prop(0), RadioButton2.Name) Then
 
                    RadioButton2.Checked = Boolean.Parse(prop(1))
 
                End If
 
            Loop
 
            ' close the file
            FileReader.Close()
 
        End If
 
    End Sub
 
    Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
 
        Dim FileWriter As StreamWriter ' define the stream writer

        ' Open the File for writing
        FileWriter = New StreamWriter("c:\temp\sampleFile.txt", False)
 
        ' Save Component values
        FileWriter.WriteLine(textBox.Name & "|" & textBox.Text)
        FileWriter.WriteLine(comboBox.Name & "|" & comboBox.SelectedIndex.ToString())
        FileWriter.WriteLine(radioBtn.Name & "|" & radioBtn.Checked.ToString())
        FileWriter.WriteLine(RadioButton1.Name & "|" & RadioButton1.Checked.ToString())
        FileWriter.WriteLine(RadioButton2.Name & "|" & RadioButton2.Checked.ToString())
 
        ' Save and Close File
        FileWriter.Flush() ' optional as close will flush
        FileWriter.Close()
    End Sub
End Class
, , , , , , , ,

Like most individuals I find the built int SUM function of SQL very helpful when performing computations. Recently however I found myself wondering how to compute the product of a result set grouped by some factor, and I found myself slightly at a lost as no Product function exists.

Fortunately for us we can use some basic Math to do our aggregate multiplication. As you may or may not remember we can Log and AntiLog to perform multiplication.

X * Y * Z = ANTILOG( LOG( X ) + LOG( Y ) + LOG( Z ) )

Looking closely at the above formula you can see that these functions all exist in most Database Servers and in T-SQL specifically you can rewrite the formula as :

SELECT EXP ( SUM ( LOG (myColumn) ) ) FROM myTable

If you wanted to get even fancier and get totals based on some criteria then you could add in GROUP BY and WHERE clauses to your queries. For example lets say you are doing some probability calculations and want to have the product of some percentages then you could do something like:

SELECT EXP(SUM(LOG(r.MEAN)))
FROM RESOURCES r
WHERE r.MODEL_ID = "TEMP"
GROUP BY r.GROUP_ID
ORDER BY r.GROUP_ID

Also it is worth wild to mention this only works for positive values. If you want to have the product of values that could potentially be negative you will have to keep track of the number of negative values and then set the result as necessary.

, , , , , ,

Visual Basic allows multiple methods for concatenating Strings. The simplest and most easily recognized method is using the + operator which will perform the concatenation of Strings. However if you want to concatenate two numbers together you will first have to convert them to Strings to use the + operator. To enable you to specify explicitly that you want to perform a String concatenation Visual Basic has the & operator.

The & operator

The & operator specifies that you want to perform String Concatenation of the objects. Using this operator the objects must be convertible to a String, and if the objects are null then an empty String is returned.

Dim testStr As String
testStr = "My " & "Number: " & 3214

In addition to the & operator you can use the &= operator if you want to append data to the end of a String.

Dim testStr As String
testStr = "Hello"
testStr &= " World"

String Builder

In the case that your application is performing massive String Concatenations then you might get better performance in utilizing the System.Text.StringBuilder Class. This class allows you append, prepend, replace, and in general manipulate the underlying String Data.

Dim sb As New StringBuilder()
sb.Append("Hello")
sb.Append(" World!")
sb.ToString()

String Concatenation is a basic task performed in most applications. Visual Basic enables you to utilize multiple methods for completing the task including the & operator that will force String Concatenation of Integers and Doubles.

, , , ,

Remembering the correct command prompts across different platforms can be confusing. To make things easier on myself I have compiled a short list of the commands and their options that are commonly used to create and delete files and folder in DOS. Including how to delete a folder and all its contents.

How to Delete a file

Deleting files from the DOS prompt is done by the del command. To use it you simply specify the single file you want deleted or the wild card pattern to match files against.

Deleting a Single file

del example.txt

Deleting all .jpg files

del *.jpg

In addition to deleting files in a single directory you can delete files from subfolders as well by using the /s switch. This option says to delete files matching the pattern in a ll subfolders. I highly suggest using this switch only if you know what you are doing.

Deleting all files within a folder and its subfolders

del  /s testFolder/*

The most important thing to remember is that the del command will delete files but will leave the folder structure intact.

How to delete Folders

There are two commands available to delete folders rd and rmdir. Both commands perform the same functionality so you can use which ever comes more natural to you. To delete a folder you will first have to delete its contents.

Deleting a Single Folder

rd myFolder
rmdir myFolder

To delete a folder as well as its contents including files and sub folders you will use the /s switch. If you don’t want to have the command line prompt you with are you sure you want to delete each file you can also use the /q switch. This causes the command to run in quiet mode meaning it will assume y for all the prompts.

Deleting a Folder and all its contents

rd /s /q myFolder
rmdir /s /q myFolder

Creating a new Directory or Folder

To create a folder you use the md or mkdir commands. When running the command simply type the name of the folder you want to create. If you want to create a sub folder as well simply pass in the full path and it will create the parent folders if they don’t exist.

Creating a single Folder

md myFolder
mkdir myFolder

Creating a sub Folder and its parents

md myFolder/Folder2/Folder3
mkdir myFolder/Folder2/Folder3

To be sure creating and deleting files and folders is a command that by far is done mostly through the Operation Systems User Interface. However there are times that working from the dos prompt (command line) is a necessity, in those case simply remember del, rd, and md commands.

, , , , , , ,

Often we forget that although we want our URLs to be SEO friendly and contain information about the current page. Because of this URLs can become very long and cumbersome to the user and to other applications which allow a limited amount of text like Twitter. For example the URL to this article is http://resources.mdbitz.com/2010/03/creating-user-friendly-and-twitter-friendly-links-with-tinyurl, however using a tool like TinyURL we can create a short user friendly redirect that would look something like http://tinyurl.com/y9bs9k5

This shorter URL is easier to post on both web applications and through emails without worrying about the application truncating the link or breaking it up on multiple lines. To create a TinyURL you simply need to access their website at tinyurl.com/. Once there simply paste in your long URL into the input box and generate your shorter redirect link. Also if desired you could create a vanity link that can contain information on what is being linked to.

, , ,