Friday, December 31, 2010

Friday December 31st 2010

Last day of 2010.


Index.html
<html>
<head>
<title>Submit() method example</title>
<script language="JavaScript">
function submitForm(){
alert("Going to submit form");
document.frm.submit();
}
</script>
</head>

<body>
<div style="background:#ff9900; width:'90%';" align=center>
<font color="#0000ff" size="12pt">
<b>Submit() Example</b>
</font>
</div>
<center>
<form name="frm" action="SuccessPage.html">
<P>Click on the following link to submit form</P>
<a href="javascript: submitForm();">Submit Form</a>
</form>
</center>
</body>
</html>


SuccesPage.html


<html>
<head>
<title>Submission success page</title>
</head>
<body>
<div stlye="background:#ff9900; width: '100%';" align="center">
<font color:#0000ff" size="12pt">
<b>Success Page</b>
</font>
</div>
</center>
<P>Great! You have submitted the form successfully</P>
<center>
<a href="javascript:history.go(-1);">Go Back</a>
</center>
</body>
</html>

Tuesday, December 28, 2010

Tuesday December 28 2010


<html>
<head>
<title>Validator</title>

// This is from the book JavaScript Bible (5th Edition) by Danny Goodman and Michael morrison

<script type="text/javascript">
function checkForm(form) {
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].value =="") {
alert("Fill out ALL fields.");
return false;
}
}
return true;
}
</script>
</head>

<body>
<form onsubmit="return checkForm(this)">
Please enter all requested information:<br>
First Name:<input type="text" name="firstName"><br>
Last Name:<input type="text" name="lastName"><br>
Rank:<input type="text" name="rank"><br>
serial Number:<input type="text" name="serialNumber"><br>

<input type="submit">
</form>
</body>
</html>



Here is another tutorial. In this tutorial, in the <body> the first script runs as the page loads, setting a global variable (today) to the current date and time.


<html>
<head>
<title>Date Calculation</title>
<script type="text/javascript">
function nextWeek() {
var todayInMs = today.getTime();
var nextWeekInMs = todayInMs + (60 * 60 * 24 * 7 * 1000);
return new Date(nextWeekInMs);
}
</script>
</head>

<body>

<script type="text/javascript">
var today = new Date();
document.write(today);
</script>
<br>
Next week will be:
<script type="text/javascript">
document.write(nextWeek());
</script>
</body>
</html>


This is from Chapter 1-20 Of Visual Basic 2008 Recipes by Todd Herman, Allen Jones, Matthew MacDonald, and Rakesh Rajan


Public Class Person
Private m_FirstName As String
Private m_LastName As String

Public Sub New()
m_FirstName = String.Empty
m_LastName = String.Empty
End Sub

Public Property FirstName() As String
Get
Return m_FirstName
End Get
Set(ByVal value As String)
m_FirstName = value
End Set
End Property

Public Property LastName() As String
Get
Return m_LastName
End Get
Set(ByVal value As String)
m_LastName = value
End Set
End Property
End Class

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim people = New Person() {
New Person With {.FirstName = "Todd", _
.LastName = "Herman"}, _
New Person With {.FirstName = "Amy", _
.LastName = "Herman"}, _
New Person With {.FirstName = "Alaina", _
.LastName = "Herman"}, _
New Person With {.FirstName = "Aidan", _
.LastName = "Herman"}}


MessageBox.Show(people(2).FirstName)
End Sub
End Class

Monday, December 27, 2010

Monday December 27 2010


<html>
<head>
<title>JS Cook 1.4</title>
<script type="text/javascript">
function inquiry() {
var testValue = "This is the cookbook's test string";
var subsValue = prompt("Enter the value you wish to search for", "");
var iValue = testValue.indexOf(subsValue);

if (iValue != -1) {
alert("We found it!");
} else {
alert("We didn't find it!");
}
}
</script>
<body onload="inquiry()">
</body>


Here is another tutorial from The JavaScript Cookbook by Shelley Powers


<html>
<head>
<title>JS Cookbook 1.5</title>
<script type="text/javascript">
function substringTest() {
var sentence = "This is one sentence. This is a sentence wih a list of items:
cherries, oranges, bananas, apples.";
alert(sentence);
var start = sentence.indexOf(":");
var end = sentence.indexOf(".", start+1);

var list = sentence.substring(start+1, end);
alert(list);
}
</script>
<body onload="substringTest()">
</body>


Here is a JavaScript tutorial from The JavaScript Bible by Danny Goodman

To bring a select object to life, use the onchange event handler.


<html>
<head>
<title>Select Navigation</title>
<script type="text/JavaScript">
function goThere() {
var list = document.forms[0].urlList;
location.href = list.options[list.selectedIndex].value;
}
</script>
</head>

<body>

<form>
Choose a place to go:
<select name="urlList" onchange="goThere()">
<option selected value = "http://www.laservault.com/">Home Page</option>
<option value = "http://www.laservault.com/Home/ContactUs/tabid/92/Default.aspx">Contact Us</option>
<option value = "http://www.laservault.com/Support/FlashTutorials/tabid/110/Default.aspx">Flash Tutorials
<option value = "httP://www.google.com/">Search the Web</option>
</select>
</form>
</body>
</html>


Last tutorial for today, tutorial 9-5 from the JavaScript Bible


<html>
<head>
<title>Beatle Picker</title>
<script type ="text/javascript">
function processData(form) {
for (var i = 0; i < form.Beatles.length; i++) {
if (form.Beatles[i].checked) {
break;
}
}
//assign values to variables for convenience
var beatle = form.Beatles[i].value;
var song = form.song.value;
alert("Checking whether " + song + " features " + beatle + "...");
}

function verifySong(entry) {
var song = entry.value;
alert("Checking whether " + song + " is a Beatles tune...");
}
</script>
</head>
<body>
<form onsubmit = "return false">
<p>Choose your favorite Beatle:
<input type="radio" name="Beatles" value="John Lennon" checked>John
<input type="radio" name="Beatles" value="Paul McCartney">Paul
<input type="radio" name="Beatles" value="George Harrison">George
<input type="radio" name="Beatles" value="Ringo Starr">Ringo



<P>Enter the name of your favorite Beatles song:<br>
<input type="text" name="song" value="Eleanor Rigby" onchange="verifySong(this)">
<Input type="button" name="process" value="Process Request..." onclick="processData(this.form)"


</form>
</body>
<html>

Sunday, December 26, 2010

Sunday, December 26 2010

This code is adapted from the JavaScript Cookbook by Shelley Powers.

It was edited with the help of http://www.jslint.com/




<htmL>
<head>
<title>JavaScript 1.2</title>
<script type = "text/javascript">
var numValue = 23.45;
var total = "And the total is " + numValue;
function writeData() {
alert(total);
}
</script>
<body onload="writeData()">
</body>



<html>
<head>
<title>JS Cook 1.3</title>
<script type="text/javascript">
function inquiry() {
var strName = prompt("What's your name?", "");
if(strName.toUpperCase() == "SHELLEY") {
alert("Your name is Shelley! Good for you!");
} else {
alert("Your name isn't Shelley! Too bad.");
}
}
</script>
<body onload="inquiry()">
</body>

Thursday, December 23, 2010

Thursday 12/23/10

Working on a tutorial by Evangelos Petroutsos.

With this code be sure and set the forms KeyPreview property to true.


Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Enter Then
If Me.ActiveControl.GetType Is GetType(TextBox) Then
e.SuppressKeyPress = True
If e.Shift Then
Me.ProcessTabKey(False)
Else
Me.ProcessTabKey(True)
End If
End If
End If
End Sub


Canceling the closing of a form


Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Dim reply As MsgBoxResult
reply = MsgBox("Document has been edited. " & _
"OK to terminate application, Cancel to " & _
"return to your document.", MsgBoxStyle.OkCancel)
If reply = MsgBoxResult.Cancel Then
e.Cancel = True
End If
End Sub


Here I am working on The Tim Patrick tutorial - still building the module for the library ap



Public Function LeftAndRightText(ByVal origLeft As String, _
ByVal origRight As String, _
ByVal textWidth As Integer) As String
' Build a string of the indicated width that has both left-justified and right-justified text

Dim leftText As String
Dim rightText As String

leftText = Trim(origLeft)
rightText = Trim(origRight)
If (Len(leftText & rightText) >= textWidth) Then
Return Trim(Left(leftText & rightText, textWidth))
Else
Return leftText & Space(textWidth - Len(leftText & rightText)) & rightText
End If

End Function


Here is a function from the module by Tim Patrick dealing with InStr functions


Public Function CountSubStr(ByVal mainText As String, ByVal subText As String) As Integer
'--- Return a count of the number of times
' that a subText occurs in a string (mainText)
Dim totalTimes As Integer
Dim startPos As Integer
Dim foundPos As Integer

totalTimes = 0
startPos = 1

'keep searching until we don't find any more
Do
'---search for the subText
foundPos = InStr(startPos, mainText, subText)
If (foundPos = 0) Then Exit Do
totalTimes += 1
'--- move to just after the occurrence
startPos = foundPos + Len(subText)
Loop

'---Return the count
Return totalTimes

End Function

Wednesday, December 22, 2010

Wednesday, 12/22/10

Another tutorial out of the JavaScript Bible, which is really thorough.


<html>
<head>
<title>Writing to the Same Doc</title>
<script type="text/javascript">
function reWrite(){
// assemble content for new window
var newContent = "<html><head><title>A New Doc</title></head>";
newContent += "<body bgcolor='acqua'><h1>This document is brand new.</h1>";
newContent += "

Click the back button to see the original document.</P>";
newContent += "</body></html>";
//write HTML to new Window document
document.write(newContent);
document.close(); //close layout stream
}
</script>
</head>
<body>
<form>
<<input type="button" value="Replace Content" onclick="reWrite()">
</form>
</body>
</html>



Here is another tutorial from the JavaScript bible



<html>
<head>
<title>Writing to Subwindow</title>
<script type="text/javascript">

function makeNewWindow() {
newWindow = window.open("","new window","height=200,width=300");
define()
}

function define(){
var newContent="<html><head><title>The New document</title></head>";
newContent +="<body bgcolor='coral'; padding=25px><h1>This document is brand new.</h1>";
newContent +="</body></html>"
newWindow.document.write(newContent)
newWindow.document.close(); // close layout stream
}
</script>

</head>
<body>
<input type="button" value="Write to Subwindow" onclick="makeNewWindow()">

</body>

</html>


Here is another tutorial working with textboxes


<html>
<head>
<title>Checkbox Inspector</title>
<script type="text/javascript">
function inspectBox() {
if (document.forms[0].checkThis.checked) {
alert("The box is checked.");
} else {
alert("The box is not checked at the moment.");
}
}
</script>

</head>
<body>
<form>
<input type="checkbox" name="checkThis">Check here

<input type="button" value="Inspect Box" onclick="inspectBox()">

</form>
</body>
</html>


And this tutorial deals with a group of radio objects


<html>
<head>
<title>Extracting Highlighted Radio Button</title>
<script type="text/javascript">
function fullName() {
var form = document.forms[0];
for (var i = 0; i < form.stooges.length; i++) {
if (form.stooges[i].checked) {
break;
}
}
//the break statement bails out of the FOR loop, leaving the value of the i loop counter at the number where the loop broke ranks
alert("You chose " + form.stooges[i].value + ".");
}
</script>
</head>

<body>
<form>
<P>Select your favorite Stooge:
<input type="radio" name="stooges" value="Moe Howard" checked>Moe
<input type="radio" name="stooges" value="Larry Fine">Larry
<input type="radio" name="stooges" value="Curly Howard">Curly<br>
<input type="button" name="viewer" value="View Full Name..."
onclick="fullName()">


//The onclick event handler invokes the fullName() function
<


</form>
</body>

</html>


Switching back to Visual Basic, here is a tutorial on dynamically adding items to a combo box.


Private Sub Label4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label4.Click

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim itm As String
itm = InputBox("Enter new item", "New Item")
If itm.Trim <> " " Then AddElement(itm)
End Sub

Sub AddElement(ByVal newItem As String)
Dim idx As Integer
If ComboBox1.FindString(newItem) > 0 Then
idx = ComboBox1.FindString(newItem)
Else
idx = ComboBox1.Items.Add(newItem)
End If
ComboBox1.SelectedIndex = idx
End Sub

Private Sub ComboBox_LostFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.LostFocus
Dim newItem As String = ComboBox1.Text
AddElement(newItem)
End Sub


Here is part of a large project by Tim Patrick, it is the first module I have ever worked with


Friend Module General
Public Const ProgramTitle As String = "The Library Project"
Public Const NotAuthorizedMessage As String = _
"You are not authorized to perform this task."
Public Const UseDBVersion As Integer = 1

' --- Constants for the MatchingImages image list
Public Const MatchPresent As Integer = 0
Public Const MatchNone As Integer = 1
Public Enum LookupMethods As Integer
ByTitle = 1
ByAuthor = 2
BySubject = 3
ByKeywordAny = 4
ByKeywordAll = 5
ByPublisher = 6
BySeries = 7
BySeriesID = 8
ByBarcode = 9
ByDatabaseID = 10
ByAuthorID = 11
BySubjectID = 12
ByPublisherID = 13
End Enum

Public Enum LibrarySecurity As Integer
ManageAuthors = 1
ManageAuthorTypes = 2
ManageCopyStatus = 3
ManageMediaTypes = 4
ManageSeries = 5
ManageGroups = 6
ManageItems = 7
ManagePatrons = 8
ManagePublishers = 9
ManageValues = 10
ManageUsers = 11
ProcessFees = 12
ManageLocations = 13
CheckOutItems = 14
CheckInItems = 15
AdminFeatures = 16
DailyProcessing = 17
BunReports = 18
PatronOverride = 19
ManageBarcodeTemplates = 20
ManageHolidays = 21
ManagePatronGroups = 22
ViewAdminPatronMessages = 23
End Enum

Public Const MaxLibrarySecurity As LibrarySecurity = LibrarySecurity.ViewAdminPatronMessages

Tuesday, December 21, 2010

Wednesday 12/21/10

Here is a tutorial on stacks by Wei-Ming Lee

Module Module1

Sub Main()
Dim stack1 As New System.Collections.Stack

'push the items onto the stack
stack1.Push("What ")
stack1.Push("is ")
stack1.Push("the ")
stack1.Push("point ")
stack1.Push("of ")
stack1.Push("using ")
stack1.Push("stacks? ")


'get the item count in the stack

Dim itemCount As Integer = stack1.Count
Console.WriteLine("The stack has {0} items in it", itemCount)

'pop the items out from the stack
For i As Integer = 0 To stack1.Count - 1
MsgBox(stack1.Pop()) 'strings are printed in the reverse order
Next

Console.ReadLine()
End Sub

End Module


Here is a tutorial by Michael Halvorson


Imports System.Drawing.Printing
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
'Print using an error handler to catch problems
Try
AddHandler printdocument1.printpage, AddressOf Me.printgraphic
Catch ex As Exception
MessageBox.Show("Sorry, there was a problem printing", _
ex.ToString())

End Try
End Sub

'Sub for printing graphic
Private Sub PrintGraphic(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
'create the graphic using DrawImage
ev.Graphics.DrawImage(Image.FromFile(TextBox1.Text), _
ev.Graphics.VisibleClipBounds)
'specify that this is the last page to print
ev.HasMorePages = False

End Sub

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

End Sub
End Class


and here are some tentative things I am doing with event handlers


Public Class MainClass
Private Event firstEvent()

Private Sub MainClass_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RaiseEvent firstEvent()
End Sub


Sub TestEvents() Handles Me.firstEvent
MsgBox("First Event Raised")
Me.Name = "MainForm"
MsgBox("The form's name is now " & Me.Name.ToString)
btn = New Button
btn.Location = New Point(80, 70)
btn.Text = "Click me"
Me.Controls.Add(btn)
AddHandler btn.Click, AddressOf btn_click


End Sub


Private WithEvents btn As Button


Private Sub btn_click(ByVal sender As Object, ByVal e As EventArgs)
Dim textbox1 As New tTextbox(Me)
Me.Width = 400
Me.Height = 400
Me.Text = "Enter Text"
End Sub

End Class

Class buttons

End Class
Class tTextbox
Dim tbox As TextBox

Sub New(ByRef form1 As Form)
tBox = New TextBox
tBox.Size = New System.Drawing.Size(300, 300)
tBox.Location = New System.Drawing.Point(20, 20)
form1.Controls.Add(tBox)

End Sub



End Class

Monday, December 20, 2010

Tuesday 12/20/2010


Option Strict On
Imports System
Namespace InterfaceDemo
'define the interface
Interface IStorable
Sub Read()
Sub Write(ByVal obj As Object)
Property Status() As Integer
End Interface

'create a class that implements the IStorable interface

Public Class document
Implements IStorable
'oh cool it just added a bunch of things on its own

Private myStatus As Integer = 0

Public Sub New(ByVal s As String)
Console.WriteLine("Creaing document with: {0}", s)
End Sub 'new

Public Sub Read() Implements IStorable.Read
Console.WriteLine("Implementing the Read Method for IStorable")
End Sub 'read

Public Property Status As Integer Implements IStorable.Status
Get
Return myStatus
End Get
Set(ByVal value As Integer)
myStatus = value
End Set
End Property

Public Sub Write(ByVal obj As Object) Implements IStorable.Write
Console.WriteLine("Implementing the write method for IStorable.")
End Sub 'write
End Class

Class tester
Public Sub run()
Console.writeline("Implementing Tester.Run")


Dim doc As New document("Test Document")
doc.status = -1
doc.read()
console.writeline("Document status: {0} ", doc.status)
End Sub
End Class

End Namespace

Module Module1

Sub Main()
Dim t As New InterfaceDemo.tester()
t.run()
Console.WriteLine("Ran an instance of InterfaceDemo.tester()")
Console.ReadLine()
End Sub

End Module


Classes can implement any number of interfaces.


Option Strict On
Imports System
Namespace InterfaceDemo
Interface IStorable
Sub Read()
Sub Write(ByVal obj As Object)
Property status() As Integer
End Interface 'IStorable

Interface ICompressible
Sub Compress()
Sub Decompress()
End Interface 'ICompressible

'document implements both interfaces

Public Class Document
Implements ICompressible, IStorable

'hold the value for IStorable's Status property
Private myStatus As Integer = 0

'the document constructor
Public Sub New(ByVal s As String)
Console.WriteLine("Creating document with {0} ", s)
End Sub 'New



Public Sub Compress() Implements ICompressible.Compress
Console.WriteLine("Implementing Compress")
End Sub

Public Sub Decompress() Implements ICompressible.Decompress
Console.WriteLine("Implementing Decompress")
End Sub

Public Sub Read() Implements IStorable.Read
Console.WriteLine("Implementing the read method for IStorable")
End Sub 'Read

Public Property status As Integer Implements IStorable.status
Get
Return myStatus
End Get
Set(ByVal value As Integer)
myStatus = value
End Set
End Property

Public Sub Write(ByVal obj As Object) Implements IStorable.Write
Console.WriteLine("Implementing the Write Method for IStorable")
End Sub 'Write
End Class


End Namespace


And here is a variation I wrote:


Class Tester
Public Sub Run(ByVal textValue As String)
Dim doc As New Document(textValue)
doc.status = -1
doc.Read()
doc.Compress()
Console.WriteLine("Document Status: {0}", doc.status)
End Sub 'Run
End Class

End Namespace

Module Module1
Sub Main()
Dim textVal As String = ""
For i = 1 To 5
textVal = "Document #" & i.ToString
Dim t As New InterfaceDemo.Tester()
t.Run(textVal)
Next

Console.ReadLine()

End Sub 'main
End Module

Sunday, December 19, 2010

Sunday 12/19/2010


Public Class Form1
'This is a tutorial written by Michael Halvorston towards the end of his book, "Microsoft Visual Basic 2005 Step By Step
'The book has been a big help
'I originally tried to get this to work by using several classes and writing it all out in code - but it was a bit too much making my own event handlers
'Getting there, though
'I would really like to have Mr. Halvorston's book finished by Christmas but fat chance


'Variables
Dim GoingUp As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
PictureBox1.Image = New System.Drawing.Bitmap("C:\Users\Alfred\Documents\VBPractice\dog.JPG")
Timer1.Enabled = False
Timer1.Interval = 500
Button1.Text = "Going Up"
Button2.Text = "Going Down"
'note this is not how the original tutorial goes, in the original tutorial Michael Halvorston has us change the properties using the Visual Studio editor

End Sub

Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click

End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If GoingUp = True Then
'move picture box toward the top
If PictureBox1.Top > 10 Then
PictureBox1.Location = New Point _
(PictureBox1.Location.X - 10, _
PictureBox1.Location.Y - 10)
'didn't realize this when I typed it but this makes the picture move diagonally.
End If
Else
'move picture box toward the bottom
If PictureBox1.Top < (Me.Size.Height - 75) Then
PictureBox1.Location = New Point _
(PictureBox1.Location.X + 10, _
PictureBox1.Location.Y + 10)
End If
End If
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
GoingUp = True
Timer1.Enabled = True
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
GoingUp = False
Timer1.Enabled = True
End Sub
End Class


Here is another tutorial from Michael Halvorston


Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Employee As New Person
Dim DOB As Date

Employee.FirstName = TextBox1.Text
Employee.LastName = TextBox2.Text
DOB = DateTimePicker1.Value.Date

MsgBox(Employee.FirstName & " " & Employee.LastName _
& " Is " & Employee.age(DOB) & " years old.")

End Sub
End Class

Public Class Person
Private Name1 As String
Private Name2 As String

Public Property FirstName() As String
Get
Return (Name1)
End Get
Set(ByVal value As String)
Name1 = value
End Set
End Property

Public Property LastName() As String
Get
Return Name2
End Get
Set(ByVal value As String)
Name2 = value
End Set
End Property

'Create a method
Public Function age(ByVal Birthday As Date) As Integer
Return Int(Now.Subtract(Birthday).Days / 365.25)
End Function
End Class

Friday, December 17, 2010

Friday December 17 2010

Almost time for Christmas

Here is a variation I did, starting from a tutorial by Michael Halvorson


Public Class buttonClass
Dim buttonScheme As Button
Dim baseForm As Form

Sub New()
buttonScheme = New Button
With buttonScheme
.Size = New Size(200, 30)
.Enabled = True
.visible = True
.forecolor = Color.Blue
End With
End Sub

Sub buttonUp()
buttonScheme.text = "Go Up"
buttonScheme.Location = New System.Drawing.Point(600, 100)
buttonScheme.Name = "buttonUp"
End Sub

Sub add(ByRef form1 As Form)
baseForm = form1
baseForm.Controls.Add(buttonScheme)
End Sub

End Class

Public Class basicAnimation
Dim picturebox As New PictureBox
Dim buttonUp As buttonClass
Dim buttonDown As Object


Private Sub basicAnimation_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


With picturebox
.Image = New System.Drawing.Bitmap("C:\Users\Alfred\Documents\VBPractice\maoMao.jpg")
.Location = New System.Drawing.Point(90, 30)
.Visible = True
.Size = New System.Drawing.Size(300, 300)
.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
End With


buttonUp = New buttonClass
buttonUp.buttonUp()
buttonUp.add(Me)



Me.ClientSize = New System.Drawing.Size(1200, 900)
Me.Controls.Add(picturebox)

End Sub

Private Sub buttonUp_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles buttonUp.click



End Sub

End Class

Thursday, December 16, 2010

Thursday 12/16/2010


Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim newform As New formBuilder.formAssembler(Me)
End Sub
End Class

Namespace formBuilder
Public Class formAssembler
Private form1 As Form

Private textboxMain As New formTextBox
Private textboxEntry As New formTextBox



Sub New(ByRef formA As Form)
form1 = formA

'define the form itself
form1.ClientSize = New System.Drawing.Size(700, 700)

'Main textbox
textboxMain = New formTextBox()
textboxMain.mainTextBox()
textboxMain.addtextbox(form1)

'entry textbox
textboxEntry = New formTextBox()
textboxEntry.secondaryTextBox()
textboxEntry.addtextbox(form1)


End Sub

End Class

Public Class formTextBox
Private textBoxBuilder As TextBox

Sub New()
textBoxBuilder = New TextBox
End Sub

Sub secondaryTextBox()
textBoxBuilder.Name = "secondaryTextBox"
textBoxBuilder.Multiline = True
textBoxBuilder.Location = New System.Drawing.Point(150, 320)
End Sub

Sub mainTextBox()
textBoxBuilder.Name = "textboxMain"
textBoxBuilder.Multiline = True
textBoxBuilder.Location = New System.Drawing.Point(150, 100)
textBoxBuilder.Size = New System.Drawing.Size(200, 200)
End Sub

Sub addtextbox(ByRef formA As Form)
formA.Controls.Add(textBoxBuilder)
End Sub


End Class
End Namespace

Wednesday, December 15, 2010

Wednesday 12/15/10

I have started using a book written by Tim Patrick. Here is a tutorial by him. A list of his books are available at http://www.timaki.com/books.htm



Public Class Form1
Private WithEvents helloDecoder As HelloStuff.SayHello
' What does withEvents mean?
' "The withEvents keyword included in the statement is what lets the control know that someone wants to monitor event notifications.

Private Sub button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles button1.Click
'show the message
helloDecoder = New HelloStuff.SayHello("!iqwtB ,tqqjM", True)
helloDecoder.DecodeMessage(-5)
helloDecoder.ReportMessage()
End Sub

Private Sub HelloDecoder_MessageDecoded(ByVal decodedMessage As String) _
Handles helloDecoder.MessageDecoded
'show the decoded message
MsgBox(decodedMessage)
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load

End Sub


End Class

Namespace HelloStuff
Friend Class SayHello
Private secretMessage As String
Private reverseFlag As Boolean
Private decoded As Boolean

Public Event MessageDecoded(ByVal decodedMessage As String)

'The New constructor allows the user to create a new instance of SayHello
'with an initial message text, and a flag which tells
' the program whether the text should be reversed before display.


Public Sub New(ByVal codedMessage As String, ByVal reverseIt As Boolean)
'save the secret message. It will be decoded later.
secretMessage = codedMessage
reverseFlag = reverseIt
decoded = False
End Sub

'The decodeMessage method converts each letter of the
'encoded message by shifting each letter a number of spaces
'determined by the rotationFactor


Public Sub DecodeMessage(ByVal rotationFactor As Integer)
'The original message was coded. Rotate each character through the alphabet by the specified number
'of times to get the true value
Dim result As String
Dim oneChar As Char
Dim counter As Integer
Dim charValue As Integer

'Don't decode twice
If (decoded = True) Then Return

'Process each character
result = ""
For counter = 1 To Len(secretMessage)
oneChar = CChar(Mid(secretMessage, counter, 1))
If (Char.IsLower(oneChar) = True) Then
'rotate the character. convert it to an integer,
'rotate it, then convert it back
charValue = Asc(oneChar) - Asc("a"c)
charValue = (charValue + rotationFactor + 26) Mod 26
oneChar = Chr(charValue + Asc("a"c))
result &= oneChar
ElseIf (Char.IsUpper(oneChar) = True) Then
'rotate the character. convert it to an integer, rotate it, then convert it back.
charValue = Asc(oneChar) - Asc("A"c)
charValue = (charValue + rotationFactor + 26) Mod 26
oneChar = Chr(charValue + Asc("A"c))
result &= oneChar
Else
'no special translation on this character.
result &= oneChar
End If
Next counter

'store the converted value
secretMessage = result
decoded = True
End Sub

Public Sub ReportMessage()
'fire event for the caller
If (reverseFlag = True) Then
RaiseEvent MessageDecoded(StrReverse(secretMessage))
Else
RaiseEvent MessageDecoded(secretMessage)
End If
End Sub


End Class
End Namespace

Tuesday, December 14, 2010

Tuesday, December 14th

This is my first hello world program using javascript:



document.writeln('Hello, world!');



Here is another program, I can tell that working with JavaScript and posting it on this blog might be a problem, we may have to end up switching to Google Documents





The alert() method displays a simple alert dialog box whose content is whatever text is passed as a parameter to the method.



<html>
<head>
<title>My First Script</title>
<style type="text/css">
.highlight {font-weight:bold}
</style>
</head>

<body>
<h1>Let's Script</h1>
<hr>
<script type="text/javascript">
document.write("This browser is version " + navigator.appVersion);
document.write(" of " + navigator.appName + ".");
</script>
</body>
</html>


Here is another JavaScript tutorial using deferred scripts In this tutorial, a javaScript function is called upon to loan right after the page loads.




<html>

<head>
<title>An onload script</title>

<script type="text/javascript">
function done() {
alert("The page has finished loading.");
}
</script>

</head>

<body onload="done()">
Here is some body text.
</body>

</html>



Here is another tutorial on running a script from User Action



<html>
<head>
<title>An onclick script</title>
<script type="text/javascript">
function alertUser() {
alert("Ouch!");
}
</script>
</head>

<body>
Here is some body text
<form>
<Input type="text" name="entry">
<input type="button" name="oneButton" value="Press Me!" onclick="alertUser()">
</form>
</body>
</html>



OK this is going to be my last JavaScript Tutorial for today, and for now I am going to go back to working on vb.net



<html>
<head>
<title>Window Opener and Closer</title>
<script type="text/javascript">
var newWindow
function makeNewWindow() {
newWindow = window.open("","","height=300,width=300");
}
function closeNewWindow() {
if (newWindow) {
newWindow.close();
newWindow = null;
}
}
</script>
</head>

<body>
<form>
<input type="button" value="Create New Window" onclick="makeNewWindow()">
<input type="button" value="Close the Window" onclick="closeNewWindow()">
</form>
</body>
</html>



Here is a tutorial on using parameter arrays




Module Module1

Sub Main()
AnyNumberArgument()
AnyNumberArgument(3, 4)
AnyNumberArgument(8, 2, 3, 7, 10)
Console.ReadLine()
End Sub

'use paramArray to create a variable-length parameter list
Sub AnyNumberArgument(ByVal ParamArray array1 As Integer())
Dim i, total As Integer
total = 0

If array1.Length = 0 Then
Console.WriteLine("Received 0 arguments.")
Else
Console.Write("The total of ")
For i = 0 To array1.GetUpperBound(0)
Console.Write(array1(i) & " ")
total += array1(i)
Next
Console.WriteLine("is {0}.", total)

End If
End Sub
End Module


Here is another tutorial on Parameter Arrays



Sub displayVals(ByVal ParamArray intVals() As Integer)
Dim i As Integer
For Each i In intVals
Console.WriteLine("Display Vals {0} ", i)
Next i

End Sub

Sub main()
Dim a As Integer = 5
Dim b As Integer = 7
Dim c As Integer = 9
Console.WriteLine("Calling with three Integers")
displayVals(a, b, c)

Console.WriteLine("Calling with four integers")
displayVals(5, 6, 7, 8)

Console.WriteLine("Calling with an array of four integers")
Dim explicitArray() As Integer = {5, 6, 7, 8}
displayVals(explicitArray)

Console.ReadLine()

End Sub

Monday, December 13, 2010

Monday December 13th 2010

The following code is from a tutorial by Evangelo Petroutsos, but I didn't seem to get it working all that well.



Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Dim srchWord As String = TextBox1.Text.Trim
If srchWord.Length = 0 Then Exit Sub
Dim wordIndex As Integer
wordIndex = ListBox1.FindStringExact(srchWord)
If wordIndex >= 0 Then
ListBox1.TopIndex = wordIndex
ListBox1.SelectedIndex = wordIndex
Else
wordIndex = ListBox1.FindString(srchWord)
If wordIndex >= 0 Then
ListBox1.TopIndex = wordIndex
ListBox1.SelectedIndex = wordIndex
Else

End If
End If
End Sub
End Class


Here is another tutorial by Jesse Liberty


'Object is the base class for all other classes.

Dim myIntegerVariable As Integer = 123

Sub Main()
'Boxing
Dim myObjectVariable As Object = myIntegerVariable
Console.WriteLine("myObjectVariable: {0} ", myObjectVariable.ToString)

'unboxing
Dim anotherIntegerVariable As Integer = _
DirectCast(myObjectVariable, Integer)
Console.WriteLine("anotherIntegerVariable {0}", anotherIntegerVariable)

Console.ReadLine()

End Sub


Here is the next Jesse Liberty Tutorial, from "Learning Visual Basic .NET"



'from a tutorial by Jesse Liberty. Some modifications by myself.
Imports System
'This set of notes are from Srinivasa Sivkumar:
'Namespaces are the basic builidng block for the .net framework
'System is the basic namespace of every .net code
Namespace StructureDemonstration

'declare a structure named Location
Public Structure Location
'the structure has private data
Private myXVal As Integer
Private myYVal As Integer

'constructor

Public Sub New( _
ByVal xCoordinate As Integer, ByVal yCoordinate As Integer)
myXVal = xCoordinate
myYVal = yCoordinate
End Sub 'new

'Property
Public Property XVal() As Integer
Get
Return myXVal
End Get
Set(ByVal Value As Integer)
myXVal = Value
End Set
End Property

Public Property YVal() As Integer
Get
Return myYVal
End Get
Set(ByVal value As Integer)
myYVal = value
End Set
End Property

'Display the structure as a string
Public Overrides Function ToString() As String
Return [String].Format("{0}, {1}", XVal, YVal)
End Function 'toString
End Structure 'Location

Class tester
Public Sub Run()
'create an instance of the structure
Dim locl As New Location(200, 300)

'display the values in the structure
Console.WriteLine("Locl location: {0}", locl)

'invoke the default constructor
Dim loc2 As New Location()
Console.WriteLine("Loc2 location: {0}", loc2)

'pass the structure to a method
myFunc(locl)

'redisplay the value in the structure
Console.WriteLine("Locl location:{0} ", locl)
End Sub 'run

'method takes a structure as a parameter
Public Sub myFunc(ByVal loc As Location)
'modift the values through the properties
loc.XVal = 50
loc.YVal = 100
Console.WriteLine("Locl location: {0}", loc)

End Sub 'myFunc

End Class
End Namespace

Namespace circleDemonstration
'this is my own variation note that I got circumference and diameter confused
Public Structure cCircle
Private rRadius As Integer
Private cColor As String
Private dDiameter As Double

Public Sub New(ByVal inputRadius As Integer, ByVal inputColor As String)
rRadius = inputRadius
cColor = inputColor
End Sub

Public Sub getCircumference()
dDiameter = (rRadius ^ 2) * 3.14
End Sub

Public Overrides Function toString() As String
Return [String].Format("The circumference is {0} ", dDiameter)
End Function

Public Property myRadius() As Integer
Get
Return rRadius
End Get
Set(ByVal value As Integer)
rRadius = value
End Set
End Property

End Structure

Class newCircle

Public Sub run()
Dim circ As New cCircle
Console.WriteLine("Please enter the radius of the circle")
circ.myRadius = Console.ReadLine()
circ.getCircumference()
Console.WriteLine(circ.toString())

End Sub

End Class

End Namespace
Module module1
Sub main()
Dim t As New StructureDemonstration.tester

t.Run()
Console.ReadLine()

Dim c As New circleDemonstration.newCircle

c.run()
Console.ReadLine()

End Sub
End Module


Here is a tutorial by Michael Halverson on drawing



Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
'prepare GraphicsFun Variable for graphics calls
Dim GraphicsFun As System.Drawing.Graphics
GraphicsFun = Me.CreateGraphics

'use a red pen color to draw a line and an ellipse
Dim PenColor As New System.Drawing.Pen(System.Drawing.Color.Red)
GraphicsFun.DrawLine(PenColor, 20, 30, 100, 80)
GraphicsFun.DrawEllipse(PenColor, 10, 120, 200, 160)

'use a green brush color to create a filled rectangle
Dim BrushColor As New SolidBrush(Color.Green)
GraphicsFun.FillRectangle(BrushColor, 150, 10, 250, 100)

'Create a blue cardinal spline curve with four points
Dim Points() As Point = {New Point(358, 280), _
New Point(300, 320), New Point(275, 155), New Point(350, 180)}
For tension As Single = 0 To 2.5 Step 0.5
GraphicsFun.DrawCurve(Pens.DodgerBlue, Points, tension)
Next
End Sub
End Class

Friday, December 10, 2010

Friday December 10 2010


Private Sub Form1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp

If e.KeyCode = Keys.Enter And Not (e.Alt Or e.Control) Then
If Me.ActiveControl.GetType Is GetType(TextBox) Or _
Me.ActiveControl.GetType Is GetType(CheckBox) Or _
Me.ActiveControl.GetType Is GetType(DateTimePicker) Then
If e.Shift Then
Me.ProcessTabKey(False)
Else
Me.ProcessTabKey(True)
End If
End If
End If

End Sub


Here is a program I made myself


Dim masterArray() As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim fileGrab As New Connection(OpenFileDialog1)
fileGrab.Connect()
fileGrab.buildArray()

masterArray = fileGrab.returnStringArray

Dim sString As String
For Each sString In masterArray
ListBox1.Items.Add(sString)
Next

Dim indexIn As Integer = masterArray.Length - 1

MessageBox.Show(indexIn)

End Sub

Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk

End Sub


Public Class Connection
Dim stringFileName As String = ""
Dim holdingString As String = ""
Dim stringArray() As String

Function returnStringArray()

Return stringArray
End Function

Sub buildArray()
Dim index As Integer = 0
Dim holdingArray() = holdingString.Split(vbCrLf)
stringArray = holdingArray

End Sub

Sub Connect()
MessageBox.Show(stringFileName)
Dim fileReader As New System.IO.StreamReader(stringFileName)
holdingString = fileReader.ReadToEnd
fileReader.Close()
End Sub



Sub New(ByVal OpenFileDialog1)

OpenFileDialog1.Title = "Select a text file"
OpenFileDialog1.Filter = "Text files (*.txt) | *.txt"
OpenFileDialog1.InitialDirectory = "C:\Users\Alfred\Documents\VBPractice"
OpenFileDialog1.ShowDialog()
MessageBox.Show(OpenFileDialog1.FileName)
stringFileName = OpenFileDialog1.FileName

End Sub
End Class

Thursday, December 9, 2010

Thursday, Decemeber 12 2010

Here is the code from a tutorial by Evangelos Petroutsos that I have been working on:




Public Class frmTextPad

Private Sub CopyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyToolStripMenuItem.Click
If TextBox1.SelectionLength > 0 Then
Clipboard.SetText(TextBox1.SelectedText)
End If
End Sub

Private Sub CutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CutToolStripMenuItem.Click
Clipboard.SetText(TextBox1.SelectedText)
TextBox1.SelectedText = ""
End Sub

Private Sub PasteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PasteToolStripMenuItem.Click
If Clipboard.ContainsText Then
TextBox1.SelectedText = Clipboard.GetText
End If
End Sub

Private Sub NumberLinesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumberLinesToolStripMenuItem.Click
Dim iLine As Integer
'notice the use of StringBuilder
Dim newText As New System.Text.StringBuilder()
For iLine = 0 To TextBox1.Lines.Length - 1
'adds a number before each line, then tabs and then the text for that line
newText.Append((iLine + 1).ToString & vbTab & TextBox1.Lines(iLine) & vbCrLf)
Next
TextBox1.SelectAll()
Clipboard.SetText(newText.ToString)
TextBox1.Paste()
End Sub

Private Sub FindReplaceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindReplaceToolStripMenuItem.Click
findReplace.ShowDialog()
End Sub

Private Sub UndoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UndoToolStripMenuItem.Click
If UndoToolStripMenuItem.Text = "Undo" Then
If TextBox1.CanUndo Then
TextBox1.Undo()
UndoToolStripMenuItem.Text = "Redo"
End If
Else
If TextBox1.CanUndo Then
TextBox1.Undo()
EditToolStripMenuItem.Text = "Undo"
End If
End If
End Sub
End Class


Here is another tutorial by Jesse Liberty



Imports System
Public Class window
'constructor takes two integers to fix location on the console
Public Sub New(ByVal top As Integer, ByVal left As Integer)
Me.top = top
Me.left = left
End Sub

'simulates drawing the window
Public Overridable Sub drawWindow()
Console.WriteLine("Window: drawing window at {0}, {1}", top, Left)
End Sub

'these members are protected and thus invisible to derived class methods
'we'll examine this later in the chapter

Protected top As Integer
Protected left As Integer
End Class


'ListBox derives from Window
Public Class listBox
Inherits window

'the keyword MyBase indentifies the base class for the current object
'constructor adds a parameter
Public Sub New(ByVal top As Integer, ByVal left As Integer, ByVal contents As String)
MyBase.New(top, left) 'call base constructor
listBoxContents = contents
End Sub

'an overrident version(note keyword) because in the derived method we change the behavior
Public Overrides Sub drawWindow()
MyBase.drawWindow() 'nvokes the base method
Console.WriteLine( _
"Writing string to the listbox: {0} ", listBoxContents)
End Sub 'DrawWindow

Private listBoxContents As String 'new member variable

End Class 'listbox

Public Class Button
Inherits window

Public Sub New(ByVal top As Integer, ByVal left As Integer)
MyBase.New(top, left)
End Sub 'new

'an overridden version (again, note keyword) because in the derived method we change the behavior

Public Overrides Sub drawWindow()
Console.WriteLine("Drawing a button at {0}, {1}" & ControlChars.Lf, top, left)
End Sub 'drawWindow

End Class 'button

Module Module1
'The following tutorial is by Jesse Liberty.
'It deal with polymorphism and overriding
'It's important to note that VB.net differs from Java or C++ in that an "overridable function is always considered to the be the root of dispatch"
'This tutorial also looks at object arrays

Sub Main()
Dim win As New window(1, 2)
Dim lb As New listBox(3, 4, "Stand Alone list box")
Dim b As New Button(5, 6)
win.drawWindow()
lb.drawWindow()
b.drawWindow()
Dim winArray(3) As window
winArray(0) = New window(1, 2)
winArray(1) = New listBox(3, 4, "List box in array")
winArray(2) = New Button(5, 6)

Dim i As Integer
For i = 0 To 2
winArray(i).drawWindow()
Next i

Console.ReadLine()
End Sub 'Main

End Module


Here is a little mini form builder class I have been working on





Public Class formBuilder

Dim formNew As Form

Dim buttonButton(10) As Button
Dim buttonIndex As Integer = 0
Dim buttonArray() As Button


Sub New()
formNew = New Form
MessageBox.Show("We created a new form")
End Sub

Sub showForm()
formNew.Show()
End Sub

Sub addButton(ByVal x, ByVal y)

If buttonIndex <= 10 Then
buttonButton(buttonIndex) = New Button
buttonButton(buttonIndex).Top = y
10: buttonButton(buttonIndex).Left = x
buttonButton(buttonIndex).Name = "NewButton" & buttonIndex
MessageBox.Show("We created a new button named " & buttonIndex)
buttonButton(buttonIndex).Text = "Button" & buttonIndex

formNew.Controls.Add(buttonButton(buttonIndex))
buttonIndex = buttonIndex + 1
Else
MessageBox.Show("You created enough buttons already")
Exit Sub
End If
End Sub

Sub bringForward()
formNew.TopMost = True
End Sub
End Class

Public Class Form1
Dim formRoll As formBuilder
Dim x As Integer = 0
Dim y As Integer = 0


Private Sub btnCreateForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateForm.Click
formRoll = New formBuilder
btnShowForm.Enabled = True
btnBringFormForward.Enabled = True
btnAddButton.Enabled = True
btnCreateForm.Enabled = False
End Sub

Private Sub btnShowForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowForm.Click
formRoll.showForm()
End Sub

Private Sub btnAddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddButton.Click

y = InputBox("Enter the top coordinate")
x = InputBox("enter the left coordinate")
formRoll.addButton(x, y)

End Sub

Private Sub btnBringFormForward_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBringFormForward.Click
formRoll.bringForward()

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
btnShowForm.Enabled = False
btnBringFormForward.Enabled = False
btnAddButton.Enabled = False
End Sub
End Class

Monday, December 6, 2010

Monday, December 6th 2010

Here is a tutorial by Jesse Liberty on inheritance


Imports System
Public Class Window
'constructor takes to integers to fix location
'on the console

Public Sub New(ByVal top As Integer, ByVal left As Integer)
Me.top = top
Me.left = left

End Sub 'new

'simulaes drawing the window
Public Sub DrawWindow()
Console.WriteLine("Drawing window at {0}, {1}", top, Left)
End Sub 'draw window

'these members are private and thus invisible to
'derived class methods

Private top As Integer
Private left As Integer

End Class 'window


'Liar boz sweicwa deom Qinsoq
Public Class ListBox
Inherits Window

'constructor adds a parameter
Public Sub New(ByVal top As Integer, ByVal left As Integer, ByVal theContents As String)
MyBase.new(top, left) 'call base constructor
mListBoxContents = theContents
End Sub 'new

Public Shadows Sub DrawWindow()
MyBase.DrawWindow()
Console.WriteLine("Writing string to the ListBox: {0}", mListBoxContents)
End Sub 'DrawWindow

Private mListBoxContents As String 'new member variable

End Class 'listbox


Module module1
Sub main()
'create a base instance
Dim w As New Window(5, 10)
w.DrawWindow()

'create a derived instance
Dim lb As New ListBox(20, 30, "Hello World")
lb.DrawWindow()

Console.ReadLine()

End Sub
End Module


Here is something that I wrote about reading comma dilemeted text files.



Imports System
Imports System.IO


Public Class getFile


Dim fileAddress As String
Dim parsedArray(1, 30) As String

Dim stringLoad As String

Public Sub New()
Dim parentDirectory As String = "C:\Users\Alfred\Documents\VBPractice"
For Each fn In My.Computer.FileSystem.GetFiles(parentDirectory)
Dim fi As FileInfo = New FileInfo(fn)
Console.WriteLine("{0}: {1}", fi.Name, fi.Attributes.ToString())
Next


Console.WriteLine("Please enter the address of the file")
fileAddress = parentDirectory & "\" & Console.ReadLine()
Console.WriteLine("You have entered the address: " & fileAddress)
End Sub

Public Sub retrieve()
Console.WriteLine(fileAddress)

Dim objReader As New System.IO.StreamReader(fileAddress)
Console.WriteLine()

stringLoad = objReader.ReadToEnd
objReader.Close()
End Sub

Public Sub parse()

Dim strArray() As String = stringLoad.Split(",")

For i = 0 To strArray.GetUpperBound(0)
Console.WriteLine(strArray(i))
Next

Console.WriteLine(strArray(0))
Console.ReadLine()

parsedArray(0, 0) = strArray(0)
parsedArray(1, 0) = strArray(1)
Console.WriteLine(parsedArray(0, 0) & " " & parsedArray(1, 0))

Console.ReadLine()

For i = 0 To strArray.GetUpperBound(0) - 1
If (i + 1) Mod 2 = 0 Then
parsedArray(1, i) = strArray(i)
Else
parsedArray(0, i) = strArray(i)
End If
Next
End Sub

Public Sub print()
Dim stringHolder As String
For x = 0 To parsedArray.GetUpperBound(0)
Console.WriteLine("X = " & x)
Next

Console.ReadLine()

For y = 0 To parsedArray.GetUpperBound(1)
Console.WriteLine("Y = " & y)

Next

Console.ReadLine()

For x = 0 To parsedArray.GetUpperBound(0)
Console.WriteLine(parsedArray(x, 0))
Next
Console.ReadLine()

For y = 0 To parsedArray.GetUpperBound(1)

Console.WriteLine(parsedArray(0, y) & " " & parsedArray(1, y))

Next


End Sub

End Class


Module module1
Sub main()

Console.WriteLine("Getting file address...")
Dim fileRead As New getFile
continueContinue()

Console.WriteLine("Loading file...")
fileRead.retrieve()
continueContinue()

Console.WriteLine("Parsing file...")
fileRead.parse()
continueContinue()

Console.WriteLine("Displaying file...")
fileRead.print()
continueContinue()




End Sub

Sub continueContinue()
Console.WriteLine("Hit enter to continue")
Console.ReadLine()
End Sub


The final tutorial for today is one on returning an array from a procedure.


Imports System
Module module1

Sub main()
Dim numEntry As Integer
Dim rates() As Decimal = RateArray(9)
Dim indexInteger As Integer = 5
Do While indexInteger > 0
numEntry = Console.ReadLine()
Console.WriteLine(rates(numEntry))
indexInteger -= 1
Loop


End Sub


Private Function RateArray(ByVal elementCount As Integer) As Decimal()
Dim rates(elementCount - 1) As Decimal
For i As Integer = 0 To rates.Length - 1
rates(i) = (i + 1) / 100D
Next
Return rates
End Function
End Module


Pretty soon I am going to start studying JavaScript, among other things it would be good to take my mind off of VB for a while.

Friday, December 3, 2010

Friday 12/3/2010

Here is a tutorial by Evangelos Peroutsos


Public Class Form1

'FYI this tutorial was written by Evangelos Petroutsos, the notations in it are mostly made by myself, but are quoted from his book.
'Anyone interested should take a look at his book "Mastering Microsoft Visual Basic 2008" it is pretty good

Dim clearDisplay As Boolean
Dim Operand1 As Double
Dim Operand2 As Double
Dim theOperator As String


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub


Private Sub DigitClick(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnZero.Click, btnOne.Click, btnTwo.Click, btnThree.Click, btnFour.Click, btnFive.Click, btnSix.Click, btnSeven.Click, btnEight.Click, btnNine.Click

If clearDisplay = True Then
lblDisplay.Text = ""
clearDisplay = False
End If
' take a look at the expression sender.text
lblDisplay.Text = lblDisplay.Text + sender.text
End Sub

Private Sub bttnClear_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnClear.Click
lblDisplay.Text = ""
End Sub



Private Sub btnPeriod_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPeriod.Click
'indexOf is a method that can be applied to any string...if this number is zero or positive, the number enetered contains a period already, and another can't be entered
If lblDisplay.Text.IndexOf(".") >= 0 Then
Exit Sub
Else
lblDisplay.Text = lblDisplay.Text & "."
End If
End Sub

'coding the math operations - the math operations will involve two operands and an operator (+,-,/,*, etc)
'As Petroutsos states, when the user clicks one of the math symbols, the value on the display is then set to be operand1, the math symbol pressed becomes the operator, then
'whatever numbers are entered next become the second number in the operation, aka operand2

'Petroutsos wants us to remember as well here that the variables are local in the subroutines in which they are declared.

'The plus button
Private Sub btnPlus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPlus.Click
Operand1 = Convert.ToDouble(lblDisplay.Text)
theOperator = "+"
clearDisplay = True
End Sub

Private Sub btnMultiply_Click(ByVal send As System.Object, ByVal e As System.EventArgs) Handles btnMultiply.Click
Operand1 = Convert.ToDouble(lblDisplay.Text)
theOperator = "*"
clearDisplay = True
End Sub

'The equals button
Private Sub btnEquals_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEquals.Click
Dim result As Double
Operand2 = Convert.ToDouble(lblDisplay.Text)
Select Case theOperator
Case "+"
result = Operand1 + Operand2
Case "-"
result = Operand1 - Operand2
Case "*"
result = Operand1 * Operand2
Case "/"
result = Operand1 / Operand2
End Select
lblDisplay.Text = result.ToString
clearDisplay = True
End Sub

Private Sub btnDivide_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDivide.Click
Operand1 = Convert.ToDouble(lblDisplay.Text)
theOperator = "*"
clearDisplay = True
End Sub
End Class


Next, I am going to do my first WPF tutorial. Honestly, the more I learn about vb.net, the more I realize I don't know.


What is XAML? I am going to look on wikipedia, as this is the most obscure and incomprehensible source that I can think of off the top of my head.

Nevermind, I am going to finish the first Jesse Liberty book instead


Here is one of his tutorials on passing by value between classes etc.


Option Strict On
Imports System
Public Class Cat
Private mWeight As Integer

Public Sub New(ByVal weight As Integer)
mWeight = weight
End Sub

Public Property Weight() As Integer
Get
Return mWeight
End Get
Set(ByVal value As Integer)
mWeight = value
End Set
End Property

Public Overrides Function ToString() As String
Return mWeight.ToString()
End Function



End Class


Public Class tester
Public Sub run()
'declare a cat and initialize to 5
Dim theVariable As New Cat(5)

'display its value
Console.WriteLine("In run. theVariable: {0}", theVariable)
'call a method & pass the variable
Doubler(theVariable)


End Sub

Public Sub doubler(ByVal param As Cat)
'display the value that was passed in
Console.writeLine("In method1. received param: {0}", param)

'double the value
param.Weight = param.Weight * 2

'display the doubled value before returning
Console.WriteLine("Updated param. returning new value: {0}", param)
End Sub


End Class ' tester

Module Module1
Sub Main()
Dim t As New tester()
t.run()
Console.ReadLine()
End Sub
End Module


Here is a tutorial on FileStreams


Imports System.IO
Imports System.Text

Public Class Tester
Public Sub Run()
Dim mySourceFileStream As FileStream
Dim myDestFileStream As FileStream
Dim bteRead() As Byte
Dim intByte As Integer
Dim bteMessage(128) As Byte
Dim strCopyMessage As String = ""

Try
myDestFileStream = New FileStream("C:\Users\Alfred\Documents\dest.txt", FileMode.OpenOrCreate, FileAccess.Write)

bteMessage = Encoding.ASCII.GetBytes(strCopyMessage)
myDestFileStream.Write(bteMessage, 0, bteMessage.Length)

mySourceFileStream = New FileStream("C:\Users\Alfred\Documents\texttime.text", FileMode.OpenOrCreate, FileAccess.Read)
intByte = mySourceFileStream.Length
ReDim bteRead(intByte)
mySourceFileStream.Read(bteRead, 0, intByte)
myDestFileStream.Write(bteRead, 0, intByte)

myDestFileStream.Close()
mySourceFileStream.Close()

Catch ex As Exception
Console.WriteLine("oh oh")

End Try


End Sub
End Class

Module module1
Sub main()
Dim testerTime As New Tester

testerTime.Run()

End Sub
End Module



Here is a little something I wrote myself on arrays and classes.


Public Class stock

Dim ticker As String
Dim stockName As String
Dim purchaseValue As Double
Dim todaysValue As Double

Public Sub New(ByVal subTicker As String, ByVal subStockName As String, ByVal subPurchaseValue As Double, ByVal subTodaysValue As Double)
ticker = subTicker
stockName = subStockName
purchaseValue = subPurchaseValue
todaysValue = subTodaysValue
End Sub

Public Sub verify()
Console.WriteLine("The information for stock " & ticker & " has been entered")

End Sub

End Class

Module module1
Sub main()
Dim stock1 As New stock("BMS", "Bank of Montreal", 24.37, 32.75)
stock1.verify()

Console.ReadLine()

Dim stockArray(9) As stock

stockArray(0) = New stock("FTE", "France Telecom", 25.21, 21.35)

stockArray(0).verify()

Console.ReadLine()

End Sub
End Module

Thursday, December 2, 2010

Thursday, 12/2/2010


Imports System
Public Class time
'public member variables
Private mYear As Integer
Private mMonth As Integer
Private mDate As Integer
Private mHour As Integer
Private mMinute As Integer
Private mSecond As Integer

'this is my first time to use properties
Property Hour() As Integer
Get
Return mHour
End Get
Set(ByVal value As Integer)
mHour = value
End Set
End Property

'public accessor methods

Public Sub DisplayCurrentTime()
Console.WriteLine( _
"{0}/{1}/{2} {3}:{4}:{5}", _
mMonth, mDate, mYear, mHour, mMinute, mSecond)
End Sub 'DisplayCurrentTime

'constructors
Public Sub New(ByVal dt As System.DateTime)
mYear = dt.Year
mMonth = dt.Month
mDate = dt.Date
mHour = dt.Hour
mMinute = dt.Minute
mSecond = dt.Second
End Sub 'new

Public Sub New( _
ByVal mYear As Integer, _
ByVal mMonth As Integer, _
ByVal mDate As Integer, _
ByVal mHour As Integer, _
ByVal mMinute As Integer, _
ByVal mSecond As Integer)
Me.mYear = mYear
Me.mMonth = mMonth
Me.mDate = mDate
Me.mHour = mHour
Me.mHour = mMinute
Me.mSecond = mSecond
End Sub 'new

End Class 'Time

Module Module1

Sub main()
Dim currentTime As System.DateTime = System.DateTime.Now
Dim time1 As New time(currentTime)
time1.DisplayCurrentTime()

'extract the hour to a local variable
Dim theHour As Integer = time1.Hour

'display the local variable
Console.WriteLine("Retrieved the hour: {0}", theHour)

'add one to the local variable
theHour += 1
'write teh time back to the object
time1.Hour = theHour

'dispaly the result
Console.WriteLine("Update the hour: {0} ", _
time1.Hour)

Console.ReadLine()
End Sub
End Module

Wednesday, December 1, 2010

Tuesday 12/1/10

Here is another tutorial by Jesse Liberty


Imports System
'Fields hold the state of the object, and methods define the object's behavior.

Class cat
Private Shared instances As Integer = 0
Private weight As Integer
Private name As String

Public Sub New(ByVal name As String, ByVal weight As Integer)
instances += 1
Me.name = name
Me.weight = weight
End Sub

Public Shared Sub HowManyCats()
Console.WriteLine("{0} cats adopted ", instances)
End Sub

Public Sub TellWeight()
Console.WriteLine("{0} is {1} pounds", name, weight)
End Sub

End Class 'cat




Module Module1

Sub Main()
cat.HowManyCats()
Dim frisky As New cat("Frisky", 5)
frisky.tellWeight()
cat.HowManyCats()
Dim whiskers As New cat("Whiskers", 7)
whiskers.TellWeight()
whiskers.HowManyCats()

cat.HowManyCats()


Console.ReadLine()
End Sub

End Module


Here is another tutorial I worked on myself


Imports System

Public Class Employee
Private empID As Integer
Public Sub New(ByVal empID As Integer)
Me.empID = empID
End Sub
Public Overrides Function ToString() As String
Return empID.ToString()
End Function
End Class




Module Module1

Sub Main()
Dim empArray(5) As Employee
Dim counter As Integer = 0
Dim idNumber As Integer

While counter < 6
idNumber = Console.ReadLine()
empArray(counter) = New Employee(idNumber)
counter += 1
End While


Dim employeeInstance As Employee
For Each employeeInstance In empArray
Console.WriteLine("Employee ID# " & employeeInstance.ToString)
Next

Console.ReadLine()

End Sub

End Module


Here is another tutorial from the book by Jesse Liberty


Imports System

'The signature of a method is composed of its name and its parameter list

Public Class Time
'private member variables
Private yearYear As Integer
Private monthMonth As Integer
Private dateDate As Integer
Private hourHour As Integer
Private minuteMinute As Integer
Private secondSecond As Integer

'public accessor methods
Public Sub DisplayCurrentTime()
System.Console.WriteLine( _
"{0}/{1}/{2} {3}:{4}:{5}", _
monthMonth, dateDate, yearYear, hourHour, minuteMinute, secondSecond)
End Sub 'displayCurrentTime

'constructors
Public Sub New(ByVal dt As System.DateTime)
yearYear = dt.Year
monthMonth = dt.Month
dateDate = dt.Day
hourHour = dt.Hour
minuteMinute = dt.Minute
secondSecond = dt.Second
End Sub ' new

Public Sub New( _
ByVal aYear As Integer, _
ByVal aMonth As Integer, _
ByVal aDate As Integer, _
ByVal anHour As Integer, _
ByVal aMinute As Integer, _
ByVal aSecond As Integer)
Me.yearYear = aYear
Me.monthMonth = aMonth
Me.dateDate = aDate
Me.hourHour = anHour
Me.minuteMinute = aMinute
Me.secondSecond = aSecond
End Sub 'new
End Class 'time

Module Module1
Sub Main()
Dim currentTime As System.DateTime = System.DateTime.Now
Dim time1 As New Time(currentTime)
time1.DisplayCurrentTime()
Dim time2 As New Time(2005, 11, 18, 11, 3, 30)
time2.DisplayCurrentTime()
Console.ReadLine()
End Sub
End Module


Here is a tutorial about passing values on to subs using classes



Imports System
Public Class Tester
Public Sub run()
'declare a variable and initialize to 5
Dim theVariable As Integer = 5

'dipslay its value
Console.WriteLine("In Run. theVariable: {0}", theVariable)

'call a mthod & pass in the variable
Doubler(theVariable)

'return & display the value again
Console.WriteLine("Back in Run, theVariable: {0}", _
theVariable)
End Sub

Public Sub Doubler(ByVal param As Integer)
'display the value that was passed in
Console.WriteLine("In method1. received param: {0}", _
param)
'dobule the value
param *= 2

'display the dobuled value before returning
Console.WriteLine("Updated param. Returning new value: {0}", param)

End Sub
End Class 'tester

Module Module1
Sub Main()
Dim t As New Tester()
t.run()
Console.ReadLine()
End Sub

End Module

Tuesday, November 30, 2010

Tuesday 11/30/2010


Dim numbers(,) As Integer = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}
Dim numberOfRows As Integer = numbers.GetLength(0)
Dim numberOfColumns As Integer = numbers.GetLength(1)
Dim sumOfFirstRow As Integer = numbers(0, 0) + numbers(0, 1)

Dim numbersString As String = " "
For i As Integer = 0 To numbers.GetLength(0) - 1
For j As Integer = 0 To numbers.GetLength(1) - 1
numbersString &= numbers(i, j) & " "
Next
numbersString &= vbCrLf
Next
MessageBox.Show(numbersString, "Numbers Test")


Here is a tutorial dealing with ticks


Dim ticksBefore As Long
Dim ticksAfter As Long
Dim tickSeconds As Double

Do
ticksBefore = Now.Ticks
Console.WriteLine("Press enter to see elapsed time")
Console.ReadLine()
ticksAfter = Now.Ticks
tickSeconds = (ticksAfter - ticksBefore) / 10000000.0
Console.WriteLine("Elapsed time: " & tickSeconds.ToString)
Console.WriteLine()
Loop


Here is a tutorial I wrote on a rectangular array containing strings


Dim recArray(4, 4) As String
Dim wholeString As String = ""

recArray(0, 0) = "Mary"
recArray(0, 1) = "Thompson"
recArray(1, 0) = "John"
recArray(1, 1) = "Martin"
recArray(2, 0) = "Kirstin"
recArray(2, 1) = "Newbury"

For y = 0 To recArray.GetUpperBound(0)
For x = 0 To recArray.GetUpperBound(1)
wholeString = recArray(y, 0) & " " & recArray(y, 1)
Next
Console.WriteLine(wholeString)
Next

Console.ReadLine()

Sunday, November 28, 2010

Sunday 11/28/10

Continuing with the Jesse Liberty Console Tutorials


Option Strict On
Imports System

Public Class Time
'Private variables
Private AYear As Integer
Private AMonth As Integer
Private ADate As Integer
Private AHour As Integer
Private AMinute As Integer
Private ASecond As Integer

'public methods
Public Sub displayCurrentTime()
System.Console.WriteLine("{0} / {1} / {2} " & vbTab & "{3} : {4} : {5}", AMonth, ADate, AYear, AHour, AMinute, ASecond)
End Sub ' display current time

Public Sub New( _
ByVal theYear As Integer, _
ByVal theMonth As Integer, _
ByVal theDate As Integer, _
ByVal theHour As Integer, _
ByVal theMinute As Integer, _
ByVal theSecond As Integer)

AYear = theYear
AMonth = theMonth
ADate = theDate
AHour = theHour
AMinute = theMinute
ASecond = theSecond

End Sub
End Class 'Time

Module Module1

Sub Main()
Dim timeObject As New Time(2005, 3, 25, 9, 35, 20)
timeObject.displayCurrentTime()
Console.ReadLine()
End Sub
End Module


Here is a tutorial I wrote for getting the current time in seconds


Sub Main()
Dim second1 As Integer
Dim second2 As Integer

Dim keepGoing As Boolean = True


While keepGoing = True
Call printSeconds(second1, second2)
keepGoing = stopOrNot()
End While

End Sub

Sub printSeconds(ByRef second1, ByRef second2)

Call getSeconds(second1, second2)
Console.WriteLine("second1 is: " & second1 & " and second2 is: " & second2)
End Sub

Function stopOrNot()
Dim inputString As String = ""
inputString = Console.ReadLine
If inputString.ToUpper = "STOP" Then
Return False
Else
Return True
End If
End Function

Sub getSeconds(ByRef second1, ByRef second2)
Dim d1 As DateTime = DateTime.Now
Dim d2 As String = d1.ToString
second1 = (Val(d2.Chars(16)))
second2 = (Val(d2.Chars(17)))
End Sub


Here is another variant of the tutorial by Jesse Liberty


Imports System
Public Class Time
'private variables
Private aYear As Integer
Private aMonth As Integer
Private aDate As Integer
Private anHour As Integer
Private aMinute As Integer
Private aSecond As Integer = 30

'Public methods
Public Sub DisplayCurrentTime()
System.Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}", _
aMonth, aDate, aYear, anHour, aMinute, aSecond)

End Sub

Public Sub New(ByVal theYear As Integer, _
ByVal theMonth As Integer, _
ByVal theDate As Integer, _
ByVal theHour As Integer, _
ByVal theMinute As Integer, _
ByVal theSecond As Integer)

aYear = theYear
aMonth = theMonth
aDate = theDate
anHour = theHour
aMinute = theMinute
aSecond = theSecond
End Sub

Public Sub New(ByVal existingObject As Time)
aYear = existingObject.aYear
aMonth = existingObject.aMonth
aDate = existingObject.aDate
anHour = existingObject.anHour
aMinute = existingObject.aMinute
aSecond = existingObject.aSecond
End Sub
End Class 'Time





Module Module1
Sub Main()
Dim timeObject As New Time(2008, 3, 25, 10, 25, 11)
Dim t2 As New Time(timeObject)
timeObject.DisplayCurrentTime()
t2.DisplayCurrentTime()
Console.ReadLine()
End Sub



End Module


Here is another tutorial



Dim fileName As String = "C:\Users\Alfred\My Documents\VBPractice\newStocks.txt"

Console.WriteLine("Created: " & _
System.IO.File.GetCreationTime(fileName))
Console.WriteLine("Last Modified: " & _
System.IO.File.GetLastWriteTime(fileName))
Console.WriteLine("Last accessed: " & _
System.IO.File.GetLastAccessTime(fileName))
Console.ReadLine()

Friday, November 26, 2010

Friday, 11/26/10


Public Sub main()
Dim testObject As New Tester()
testObject.run()
Console.ReadLine()
End Sub

Public Class dog
Public weight As Integer
Public color As String
End Class

Public Class Tester


Public Sub run()
'create an integer
Dim firstInt As Integer = 5

'create a second integer
Dim secondInt As Integer = firstInt

'display the two integers
Console.WriteLine("fistInt: {0}, secondInt: {1}", firstInt, secondInt)

'modify the second integer
secondInt = 8

'display the two integers
Console.WriteLine("firstInt: {0}, secondInt {1}", firstInt, secondInt)

'create a dog
Dim milo As New dog()

'assign a value to weight
milo.weight = 5
milo.color = "brown"

'create a second reference to the dog

Dim fido As dog = milo

'display their values
Console.WriteLine("Milo:{0}, {1}; Fido: {2}, {3}", milo.weight, milo.color, fido.weight, fido.color)
'assign a new weight to the second reference
fido.weight = 9
fido.color = "white"

'display the two values
Console.WriteLine("Milo:{0}, {1}; Fido:{2}, {3}", milo.weight, milo.color, fido.weight, fido.color)
End Sub


Here is another tutorial by Jesse Liberty


Option Strict On
Imports System
Public Class TestClass

Sub SomeMethod(ByVal firstParam As Integer, ByVal secondParam As Single)
Console.WriteLine("Here are the parameters recieved: {0}, {1}", _
firstParam, secondParam)
End Sub
End Class

Module Module1
Sub main()
Dim howManyPeople As Integer = 5
Dim pi As Single = 3.14

Dim tc As New TestClass()
tc.SomeMethod(howManyPeople, pi)
Console.ReadLine()
End Sub
End Module



I get the impression that when you code using vb.net you need to have an understanding of Common Intermediate Language going on in the back of your mind.

Here is the final tutorial of the day


Module Module1

Sub main()
Dim array As Integer() = New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 35}

Dim total As Integer = 0, i As Integer = 0

For i = 0 To array.GetUpperBound(0)
total += array(i)
Next

Console.WriteLine("Total of array elements: " & total)
Console.ReadLine()

End Sub

End Module