Monday, August 30, 2010

Monday, August 30th 2010

I'm going to redo and expand upon a tutorial from an O'Reilly book.

first things first, drag and drop the ToolStripContainer control onto the form.

Seriously, what is the point of the ToolStrpContainer?

Setting up the pubs database was quite hard, the tutorial wanted me to use visual studio, but I ended up just doing it with SQL server



Dim result As DialogResult = Dialog1.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
End
End If


A weird thing from the tutorial



Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Dim result As DialogResult = Dialog1.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
End
Else
e.Cancel = True
End If
End Sub


Why did this have to be set up separately? I am not really what is going on here but I am just going to do it and hope that it makes sense one day.

Apparently, VB.net has several templates, including an about-box template, and an explorer form. which has a built-in tree view. Cool beans.

Thursday, August 26, 2010

Thursday, August 26 2010

Finally got something to work


Dim conServer As SqlConnection = New SqlConnection("data source =ALFRED-PC\SQLExpress; initial catalog=database_Alfred; User ID=sa; password=china")
conServer.Open()

If conServer.State = ConnectionState.Open Then
lblConnection.Text = "SQLConnection is Open"

ElseIf conServer.State = ConnectionState.Closed Then
lblConnection.Text = "SQLConnection is closed"
End If


I'm going to full around with making my own projects, although I realized that I dutifully need to go back to tutorials as well.

I have a couple of projects that I want to work on:

1.) calculating salary, the percentage taken out by federal tax, the percentage taken out by state tax
-THEN- the cost of an item, the additional sales tax, and the percentage of your net income that it would take out

2.) calculating compound growth

I added a lblConnection.ForeColor = Color.Blue to the code above, which was nifty.

I modified my SQL DB with the following Transact-SQL code



USE database_Alfred
GO
CREATE TABLE investments
(
CompanyNumber int NOT NULL,
Ticker char(7) NOT NULL,
Name char(70) NOT NULL,
PurchasePrice int NOT NULL,
)


This was the first time for me to add a reference.

Wednesday, August 25, 2010

Wednesday, August 25 2010

I am trying to develop my own small app as a way of learning VB.

Right now I am focused on using ADO.NET to create a new record in a SQL Server DB using information taking from a VB windows application.



Imports System.Data.SQLClient


System.Data.SqlClient is a namespace.

I have to remember to right click and run visual studio as an administrator. Thank you Windows 7

Monday, August 23, 2010

Monday, August 23 2010

I wrote my first mini console application today. It was nothing impressive.

I took a look at the WebBrowser Control which is very cool.

I also reviewed some rudiments of Visual Basic using LearnVisualStudio.Net which is an alright site.

Friday, August 20, 2010

Friday, August 20 2010

The simplified syntax of the SELECT statement



SELECT select_list
FROM table_source
[WHERE search_condition]
[ORDER BY order_by_list]

Thursday, August 19, 2010

Thursday, August 19th, 2010

Today I am going to take a look at SQL server (hopefully) using yet another tutorial using Murach - (). They do make excellent books, although I felt (feel) that the VB book "jumps" a bit.

Client/Server System - has three parts, a client which I would call the user terminal (?) that is basically a PC in most cases, the Database server and the Network itself, cables, routers, etc.

(LAN) and (WAN) - one is a local area network, the other is a wide area network.

SQL stands for Structured Query Language and apparently you can pronounce it "S-Q-L" if you wish.

Back-end processing versus front-end processing - back-end processing is done by the database management system, whereas front-end processing is done by the application software.

Columns are vertical (like columns in a building) and rows are horizontal.

A foreign key is one (or more) column in one table that refers to a column in another table.

The most common data manipulation language (DML) SQL statements are SELECT,INSERT,UPDATE, and DELETE.

The most common data definition language(DDL) SQL statements are CREATE DATABASE, CREATE TABLE, CREATE INDEX, ALTER TABLE, DROP DATABASE, DROP TABLE, DROP INDEX

Wednesday, August 18, 2010

Wednesday, August 18 2010


Private Function IsValidData() As Boolean
If Not IsPresent(txtMonthlyInvestment, "Monthly Investment") Then
Return False
End If
If Not IsDecimal(txtMonthlyInvestment, "Monthly Investment") Then
Return False
End If
If Not IsDecimal(txtMonthlyInvestment, "Monthly Investment") Then
Return Faslse
End If
If Not IsWithinRange(txtMonthlyInvestment, "MonthlyInvestment", 1, 1000) Then
Return False
End If


One of the things Anne Boehm shows us in her tutorials is how to use compound conditions in a single return statement, rather than use a series of simple if statements.

I've also been watching a series of videos that MIT provides for free online - right now I am watching Prof. Eric Grimson and Prof. John Guttag talk about computational thinking.

A big problem with all this I can tell is that I am ignorant of SQL server and terrified of databases, so I am going to try educating myself on SQL server.

Monday, August 16, 2010

Monday, August 16th 2010

Looking at Anne Boehms tutorials, we're going to take a look back at sub procedures. Sub procedures have four parts, the access modifier, the sub keyword, the name of the procedure, and the parameter list.

The access modifier states whether the procedure can be called from other classes. You can set the access modifier to be either public or private.


Private Function FutureValue(ByVal monthlyInvestment As Decimal, _
ByVal monthlyInterestRate As Decimal, ByVal months As Integer) _
As Decimal
For i As Integer = 1 To months
FutureValue = (FutureValue + monthlyInvestment) _
* (1 + monthlyInterestRate)
Next
Return FutureValue
End Function


Ms. Boehm reminds us that every function procedure should return a value.

The next tutorial is about data validation, meaning making sure that the end user is entering the correct type of data. One way to do this is by using the IsNumeric function. The example Ms. Boehm uses is



If not IsNumeric(txtSubtotal.text) Then
MessageBox.Show( _
"Please enter a valid number for the Subtotal field.", _
"Entry Error")
Exit Sub
End If


What sub procedure would we be exiting in this case? It doesn't seem quite clear to me.

Here is an example for a dialog box in response to a program error:



MessageBox.Show( _
"An exception has occurred. " & ControlChars.NewLine _
& "The program will be canceled." _
"Program Error")


Since checking text boxes for valid data is a regular occurrence, it makes sense to create sub procedures and functions to handle them so that you don't have to keep reinventing the wheel.

For instance:



Private Function IsPresent(ByVal textBox as TextBox, ByVal name as String) _
As Boolean
If textBox.Text = "" Then
MessageBox.Show(Name & " Is a required field.", "Entry Error")
textBox.Select()
Return False
Else
Return True
End If
End Function


This function returns a Boolean value that indicates whether the data was valid or invalid via Return true and Return false

Friday, August 13, 2010

Friday, August 13th 2010

Alright, I am going to start with a tutorial by Michael Halvorson, looking at basic math operators.

What is the point of the Group box in Visual Basic? The tutorial uses a group box and I am not sure why, other than it looks cool.

The tutorial uses radio buttons which is cool


If rbtnAddition.Checked = True Then
TextBox1.Text = FirstNum + SecondNum
End If


I find it confusing - all the different variable types that are available


Dim FirstNum, SecondNum As Double


Next, I will do another tutorial by Mr. Halvorson on using Decision structures.

One of the neat features of this tutorial is the chance to use MaskedTextBox, in this case I will use one for Social Security numbers.

I changed the PIN from five digits to four, since that is more common in the States (?)


If MaskedTextBox1.Text = "340-92-7267" _
And mtxtPin.Text = "1234" Then
MsgBox("Welcome to the system!")
Else
MsgBox("I don't recognize this number!")
End If


Halvorson also introduces the AndAlso and the ElseIf - with AndAlso it basically means that if the first condition isn't true then the program does not even bother to test the second condition, reducing the chance of run time errors as well as speeding up the program - Dan Mabbutt writes, If you place the expression that is most likely to be false in the leftmost position when using AndAlso, you can prevent execution cycles from being used to evaluate the rightmost expression. Cool beans!

Halvorson also takes a look at Select Case Decision Structures

I changed his tutorial around a little, for one, I replaced Germany with France in the Form Load event procedure.


lstCountryBox.Items.Add("England")
lstCountryBox.Items.Add("France")
lstCountryBox.Items.Add("Mexico")
lstCountryBox.Items.Add("Italy")


I also changed the code for the SelectedIndexChanged even procedure for the list box


Select Case lstCountryBox.SelectedIndex
Case 0
lblGreeting.Text = "Hello, programmer."
lblGreeting.Font = New System.Drawing.Font("Times New Roman", 15)

Case 1
lblGreeting.Text = "Bonjour, programmeur."
lblGreeting.Font = New System.Drawing.Font("Algerian", 15)
Case 2
lblGreeting.Text = "Hola, programador."
lblGreeting.Font = New System.Drawing.Font("Garamond", 15, FontStyle.Italic)
Case 3
lblGreeting.Text = "Ciao, programmatore."
lblGreeting.Font = New System.Drawing.Font("Futura", 15, FontStyle.Bold)
End Select

Monday, August 9, 2010

Monday, August 9 2010

Still working on the Toolbar tutorial written by Michael Halvorson


label1.Text = TimeString


and


label1.Text = DateString


I left the name of the label as the default label1 since that is how it is written in the tutorial. Both of these are what I think of as "onClick" events since that is how they are defined in html / CSS which is what I am most familiar with. With VB, they are called click event procedure I believe (?) For both of these click events the label1.text's Text property is changed to whatever the Time and Date are converted to strings.

There are a number of System Clock Properties and Functions which are important and useful to know. Particularly intriguing is the Now property which returns "an encoded value representing the current date and time." This property is used when making arguments for other system clock functions - comparing now to some other time, making if/then statements, etc.

As well as having a MenuStrip control VB has a ToolStrip control which is just what you would think it would be - it adds a tool bar to your program that the user can use.

Jumping ahead, I took a looking at the tutorial dealing with statements. The tutorial Mr. Halvorson has written.

The tutorial emphasizes that a variable holds its value or scope only within the event procedure being used, for instance:


Dim LastName As String

LastName = "Jensen"
Label1.text = LastName

LastName = "Zimbardo"
Label1.text = LastName


Label1.text = LastName shows us one of the most important uses for a variable - transferring data to a property.

It's worth noting that you can declare two or more variables in one line as long as they are the same type, for instance


Dim FirstName, LastName as String


InputBox is a function. A function usually uses an argument, and can even have more than one argument separated by commas. For instance:


MsgBox(First Name, Last Name)


I wrote my own variation of the tutorial as


Dim PromptFirstName, PromptLastName, FirstName, LastName As String
PromptFirstName = "Please enter your first name."
PromptLastName = "Please enter your last name."

FirstName = InputBox(PromptFirstName)
LastName = InputBox(PromptLastName)
MsgBox(FirstName & " " & LastName, , "Input Results")


I then rewrote this variation as a nifty little username generator


Dim PromptFirstName, PromptLastName, FirstName, LastName, UserName As String
Dim UserNameNumber As Integer
PromptFirstName = "Please enter your first name."
PromptLastName = "Please enter your last name."

UserNameNumber = Int(Rnd() * 100) Note:This doesn't actually generate a random number, like I was hoping, it just generates .7055 each time!

FirstName = InputBox(PromptFirstName)
LastName = InputBox(PromptLastName)

UserName = FirstName & LastName & UserNameNumber
MsgBox("Your user name is, " & "" & UserName, , "Input Results")


If you wanted to generate a random number 1-9, you could write


Dim MyValue As Integer
MyValue = CInt(Int((9 * Rnd()) + 1))
Why would you use CInt instead of Int?


I'm not going to worry too much about random number generation at the moment.



Const Pi As Double = 3.14159265


or



Public Const Pi As Double = 3.14159265

Friday, August 6, 2010

Friday, August 6th 2010

Today I am going to take a look at a tutorial by Michael Halvorson, it's a game based on generating random numbers like a slot machine.


PictureBox1.Visible = False


This hides the image (in this case a picture of golden coins I downloaded from the Interweb.

There is also a code for generating the random number which is quite interesting - Rnd generates a random number between 0 and 1 then multiplies it by ten, then uses the Int function to deliver a whole number. The whole thing looks like


txtSlotOne.Text = CStr(Int(Rnd() * 10))


So far Mr. Halvorson's tutorials seem to be a bit more fun than the others. The next tutorial is one that uses the DateTimePicker control. Apparently, I was born on a Tuesday.

The only other thing worth mentioning from that tutorial is the use of & as a string concatention operator.

The next tutorial features to PictureBoxes, one with a calculator in it and one with a printer. I searched for retro 80s images to put use for the fun of it.

Both PictureBoxes have their visibility set to false. By clicking on one (or both) of the two Checkboxes you can toggle the visibility on or off.

An interesting modification would be to allow the user to set the default to both the calculator and the printer to always be on, or to set it so that one is on and one is off, and to have the program remember that the next time it starts. I don't know how to tell the program to save something, though.


If CheckBox1.CheckState = 1 Then
pctCalculator.Visible = True
Else
pctCalculator.Visible = False
End If


The next short tutorial shows us how to use the LinkLabel control.

The LinkLabel control just seems to draw a label, only the text is blue and underlined. Thanks guys, big help.

The code that has to be written seems pretty easy


LinkLabel1.LinkVisited = True
System.Diagnostics.Process.Start _
("http://www.somethingawful.com/")


Unfortunately I goofed and put the code under the FormLoad procedure so it automatically loaded up the web page when I ran the program. Although, that could be useful, too.

Next, I'm gonna work with the MenuStrip control, which is pretty darn cool if you ask me.

Michael Halvorson points out, as does Anne Boehm, the importance of providing access key support, and the ease with which a programmer can do so. All you have to do is type an ampersand (&) before the appropriate letter in the name.

Wednesday, August 4, 2010

Wednesday, August 4th 2010

Hi! Today I am going to begin by looking back at looping - going off of a tutorial written by Anne Boehm.



Dim sum As Integer
Dim i as Integer
For i = 0 to 10
sum += i
Next


This loop will add the numbers 0-10, which is extremely important as we are all forgetting how to count.

It's important to note that on the Next clause above I did not add the counter i. It is not necessary to add the counter name, although it helps to add the counter name as it adds clarity, especially when you are nesting loops

Anne Boehm also directs our attention to Do loops, which, since they seem to do the same thing as For loops I want to skip over. Do loops have one thing that is really worth mentioning here, which is that the condition can be tested either before or after the series of statements is executed. As I understand it, For loops always tests the condition before the series of statements is executed (again, as I understand it).

Generally speaking, a For loop is a count-controlled loop and a Do loop is a condition-controlled loop...

As part of an expansion of the Invoice Total application I wrote the following code:


ElseIf txtCustomerType.Text = "T" Then
If subtotal < discountpercent =" 0.4" discountpercent =" 0.5"


I also changed the text entry box for selecting the customer type to a combo type (doesn't this make more sense?) If the customer type selected is "other" or if nothing is selected than the program uses the default discount amount.

I decided to expand the Invoice Total tutorial with code from a previous tutorial.

I added the following variable definitions to the load form event (where else was I supposed to put them?) This didn't work, by the way, I had to move this code to above the click event for the "Calculate" button


Dim numberOfInvoices As Integer
Dim totalOfInvoices As Decimal
Dim invoiceAverage As Decimal


There are now two subtotal text boxes - txtSubtotal.text and txtEnterSubtotal.text. txtSubtotal.text is set to read only, and txtEnterSubtotal.text is of course where you actually enter the amount.

There is also a counter to count how many of each kind of invoice is issued - C type, T type, etc.
I wrote the following If statement


If cmbCustomerType.Text = "R" Then
RInvoices += 1
ElseIf cmbCustomerType.Text = "C" Then
CInvoices += 1
ElseIf cmbCustomerType.Text = "T" Then
TInvoices += 1
Else : OtherInvoices += 1
End If


For actually producing the information on screen, I wrote:


txtCinvoicesTotal.Text = CInvoices
txtRinvoicesTotal.Text = RInvoices
txtTinvoicesTotal.Text = TInvoices
txtOtherInvoicesTotal.Text = OtherInvoices



Is it not necessary to add ToString the end of the variables? In one of the tutorials Anne Boehm writes:


txtNumberOfInvoices.Text = numberOfInvoices.ToString


Next I am going to look and coding procedures and event handlers. I have already coded some sub procedures for Jesse Liberty tutorial, which I hope to be getting back to soon.

When writing a Sub procedure you can declare the the parameters that are required by the procedure in the parameter list that follows in parenthesis the parameter name.


ByRef allows you to change the value of the variable itself, whereas ByVal does not.

Tuesday, August 3, 2010

Tuesday, August 3rd

Using the tutorial written by Jesse Liberty, I have had some trouble getting the Search Criteria Builder to work.

I am going to take a break from the Jesse Liberty tutorial and focus on one written by Anne Boehm. This tutorial deals with coding control structures, and I am quite happy to see that we will be learning how to write nested If statements. The example Anne Boehm gives (which is used in an expanded form in the tutorial) is:


If customerType = "R" Then
If subtotal >= 100 Then
discountPercent = .2D
Else
discountPercent = .1D
End If
Else
discountPercent = .4D
End If


I can use nested If statements to develop a personal project of mine - one that would figure exactly how much take home pay you were bringing home after federal and state taxes, and what percentage of your pay would be spent on a purchase item (including telling you what the total purchase cost of the item will be with your local sales tax). There would be three input fields - two blank text boxes for entering your yearly salary and cost of the item you wish to purchase and one combo box using a scroll down list of states.

For the tutorial we have a variable defined as discountPercent, which is defined using an If statement with two nested If statements within it, each of these nested If statements defines the discount according to the amount purchased and the customer type, if the customer type is "R" or "C" then there is a special discount amount depending on how much is purchased. All other customers get a flat rate.

Next, I took a look at For loops with a syntax of:


For counter [As datatype] = start To end [Step step]
statements
Next [counter]


Using i as the counter name is common coding practice, since counters can also be referred to as indexes