Tuesday, November 22, 2011

Tuesday 11.22.11

Module Module1

Sub Main()
ExplicitTyping()
ImplicitTypingInForEach()
Console.ReadLine()
End Sub

Public Sub ExplicitTyping()
'local variables are declared as follows
'Dim variableName as DataType = initialValue
Dim myInt As Integer = 0
Dim myBool As Boolean = True
Dim myString As String = "Time, marches on..."
End Sub

Public Sub ImplicitTypingInForEach()
Dim evenNumbers() = New Integer() {2, 4, 6, 8, 10}
'use implicit typing in a standard For Each loop
'here, 'item' is really a System.Int32
For Each item In evenNumbers
Console.WriteLine("Item value: {0}", item)
Next
End Sub

End Module


Module Module1

Sub Main()
Console.WriteLine("***** Fun with Extension Methods *****" & vbLf)

'the integer has assumed a new identity
Dim myInt As Integer = 123456789
myInt.DisplayDefiningAssembly()

'so has the DataSet!
Dim d = New System.Data.DataSet()
d.DisplayDefiningAssembly()

'and the soundplayer (show details)
Dim sp As New System.Media.SoundPlayer()
sp.DisplayDefiningAssembly(True)

'use new Integer functionality
Console.WriteLine(vbLf & "Value of myInt: {0}", myInt)
Console.WriteLine("Reversed digits of myInt: {0}", myInt.ReverseDigits())

Console.ReadLine()

End Sub

End Module

Imports System.Reflection
Imports System.Runtime.CompilerServices


Module MyExtensions

'this method allows any object to display the assembly
'it is defined in
_
Public Sub DisplayDefiningAssembly(ByVal obj As Object)
Console.WriteLine("{0} lives here: {1}", obj.GetType().Name, obj.GetType().Assembly)
End Sub

'this method allows any integer to reverse its digits
'for example, 56 would return 65
_
Public Function ReverseDigits(ByVal i As Integer) As Integer
'translate integer into a string, and then
'get all the characters
Dim digits() As Char = i.ToString().ToCharArray()

'now reverse items in teh array
Array.Reverse(digits)

'put back into string
Dim newDigits As String = New String(digits)

'finally return the modified string back as an integer
Return Integer.Parse(newDigits)

End Function

'overloading extension methods
_
Public Sub DisplayDefiningAssembly(ByVal obj As Object, ByVal showDetails As Boolean)
Console.WriteLine("Defining Assembly: {0}", obj.GetType().Assembly)
If showDetails Then
Console.WriteLine("Name of type: {0}", obj.GetType().Name)
Console.WriteLine("Parent of type: {0}", obj.GetType().BaseType)
Console.WriteLine("Is generic?: {0}", obj.GetType().IsGenericType)

End If
End Subjavascript:void(0)

End Module


Module Module1

Sub Main()
QueryOverStrings()
Console.WriteLine()
QueryOverInts()
Console.WriteLine()
ImmediateExecution()
End Sub


Sub QueryOverStrings()
'assume we have an array o fstrings
'some of whcih have more than 6 letters
Dim currentVideoGames As String() = {"Morrowind", "BioShock", "Half Life 2: Episode 1", "The Darkness", "Daxter", "System Shock 2"}

'build a LINQ query
Dim subset As IEnumerable(Of String) = From g In currentVideoGames _
Where g.Length > 6 Order By g Select g

'print out results
For Each s As String In subset
Console.WriteLine("Item: {0}", s)
Next

ReflectOverQueryResults(subset)
Console.ReadLine()
End Sub

Sub QueryOverInts()
Dim numbers() As Integer = {10, 20, 30, 40, 1, 2, 3, 8, 11}
'only print items less than 10
'note use of implicit typing
Dim subset = From i In numbers Where i < 10 Select i

'more implicit typing
For Each i In subset
Console.WriteLine("Item: {0} < 10", i)
Next

'change some data in the array
numbers(0) = 4
Console.WriteLine()

'evaluate again
For Each i In subset
Console.WriteLine("{0} < 10 ", i)
Next
ReflectOverQueryResults(subset)
Console.ReadLine()
End Sub


Sub ImmediateExecution()
Dim numbers() As Integer = {10, 20, 30, 40, 1, 2, 3, 8, 9}
'get data right now as integer()
Dim subsetAsIntArray() As Integer = (From i In numbers Where i < 10 Select i).ToArray()

'get data right now as list(of integer)
Dim subsetAsListOfInts As List(Of Integer) = (From i In numbers Where i < 10 Select i).ToList()

For Each l In subsetAsListOfInts
Console.WriteLine("[{0}]", l)
Next

Console.ReadLine()
End Sub

Sub ReflectOverQueryResults(ByVal resultSet As Object)
Console.WriteLine("*** Info about Query ***")
Console.WriteLine("resultSet is of type: {0}", resultSet.GetType().Name)
Console.WriteLine("resultset location: {0}", resultSet.GetType().Assembly)
Console.WriteLine()
End Sub
End Module


Public Class Car
Public PetName As String = String.Empty
Public Color As String = String.Empty
Public speed As Integer
Public Make As String = String.Empty
End Class

Module Module1

Sub Main()
Console.WriteLine("**** More Fun with LINQ Expressions ****")
'make a list of car objects
Dim myCars As New List(Of Car)()
myCars.Add(New Car With {.PetName = "Henry", .Color = "Silver", .speed = 100, .Make = "BMW"})
myCars.Add(New Car With {.PetName = "Daisy", .Color = "Tan", .speed = 90, .Make = "BMW"})
myCars.Add(New Car With {.PetName = "Mary", .Color = "Black", .speed = 55, .Make = "VW"})
myCars.Add(New Car With {.PetName = "Clunker", .Color = "Rust", .speed = 5, .Make = "Yugo"})
myCars.Add(New Car With {.PetName = "Melvin", .Color = "White", .speed = 43, .Make = "Ford"})
GetFastCars(myCars)
GetFastBMWs(myCars)
ExtractNumericalData()
Console.ReadLine()


End Sub

Sub ExtractNumericalData()
'extract the integers from ArrayList
Dim myStuff As New ArrayList()
myStuff.AddRange(New Object() {10, 400, 8, False, New Car(), "string data"})
Dim myInts As IEnumerable(Of Integer) = myStuff.OfType(Of Integer)()

'print out 10, 400, and 8
For Each i As Integer In myInts
Console.WriteLine("Int value: {0}", i)
Next
End Sub

Sub GetFastCars(ByVal myCars As List(Of Car))
'create a query expression
Dim fastCars = From c In myCars Where c.speed > 55 Select c

For Each Car In fastCars
Console.WriteLine("{0} is going too fast!", Car.PetName)
Next
End Sub

Sub GetFastBMWs(ByVal myCars As List(Of Car))
'find all items where speed is greater than 90
'and make is BMW
Dim fastCars = From c In myCars Where c.speed > 90 And c.Make = "BMW" Select c

For Each Car In fastCars
Console.WriteLine("{0} is going too fast!", Car.PetName)
Next
End Sub
End Module


Module Module1

Sub Main()
QueryStringArrayWithOperators()
QueryStringWithEnumerableAndLambdas()
VeryComplexQueryExpression.QueryStringsWithRawDelegates()
GetCount()
Console.ReadLine()
End Sub


Sub QueryStringArrayWithOperators()
Console.WriteLine("***** Using LINQ Query Operators *****")

Dim currentVideoGames As String() = {"Morrowind", "Bioshock", "Half Life 2: Episode 1", "The Darkness", "Daxter", "System Shock 2"}

'build a LINQ query with VB LINQ operators
Dim subset = From g In currentVideoGames Where g.Length > 6 Order By g Select g

For Each s As String In subset
Console.WriteLine("Item: {0}", s)
Next
Console.WriteLine()
End Sub

Sub QueryStringWithEnumerableAndLambdas()
Console.WriteLine("***** Using Enumerable / Lambda Expressions *****")
Dim currentVideoGames As String() = {"Morrowind", "Bioshock", "Half LIfe 2: Episode 1", "The Darkness", "Daxter", "System Shock 2"}

'build a query expression using extension methods
'granted to the array via the Enumerable type
Dim subset = currentVideoGames.Where(Function(game) game.Length > 6).OrderBy(Function(game) game).Select(Function(game) game)

'print out the results
For Each game In subset
Console.WriteLine("Item: {0}", game)
Next
Console.WriteLine()

End Sub

Sub GetCount()
Dim currentVideoGames() As String = {"Morrowind", "Bioshock", "Half Life 2: Episode 1", "The Darkness", "Daxter", "System Shock 2"}
'get count from the query
Dim num As Integer = (From g In currentVideoGames Where g.Length > 6 Order By g Select g).Count()

'numb is the value 5
Console.WriteLine("{0} items honor the LINQ query.", num)


End Sub
End Module

Monday, November 21, 2011

Monday 11/21/11

Module Module1

Sub Main()
Console.WriteLine("***** Fun with Operator Overloading *****" & vbLf)
AddSubtractMyPointsWithMethodCalls()
Console.WriteLine("Calling sub AddSubtractMyPointsWithOperators()")
AddSubtractMyPointsWithOperators()
Console.WriteLine("Calling sub testPointsForEquality()")
TestMyPointsForEquality()
Console.WriteLine("Calling sub TestMyPointsForGreaterLessThan()")
TestMyPointsForGreaterLessThan()
Console.ReadLine()
End Sub

Sub AddSubtractMyPointsWithMethodCalls()
Dim p As New MyPoint(10, 10)
Dim p2 As New MyPoint(20, 30)

'add two MyPoints using Add() method
Dim newPoint = MyPoint.Add(p, p2)
Console.WriteLine("p + p2 = {0}", newPoint)

'subtract two MyPoints using Subtract() method
Console.WriteLine("p - p2 = {0}", MyPoint.Subtract(p, p2))
End Sub

Sub AddSubtractMyPointsWithOperators()
Dim p As New MyPoint(10, 10)
Dim p2 As New MyPoint(20, 30)

'really calls: MyPoint.Operator+(p, p2)
Dim newPoint As MyPoint = p + p2
Console.WriteLine("p + p2 = {0}", newPoint)

'really calls: MyPoint.Operator -(p, p2)
Console.WriteLine("p - p2 = {0}", p - p2)
End Sub

'make use of the overloaded equality operators
Sub TestMyPointsForEquality()
Dim ptOne As New MyPoint(10, 2)
Dim ptTwo As New MyPoint(10, 44)

Console.WriteLine("ptOne = ptTwo : {0}", ptOne = ptTwo) 'false
Console.WriteLine("ptOne <> ptTwo : {0}", ptOne <> ptTwo) 'true

End Sub

Sub TestMyPointsForGreaterLessThan()
Dim ptOne As New MyPoint(5, 2)
Dim ptTwo As New MyPoint(5, 44)

Console.WriteLine("ptOne > ptTwo: {0}", ptOne > ptTwo) 'false
Console.WriteLine("ptOne < ptTwo: {0}", ptOne < ptTwo) ' false
Console.WriteLine("ptOne >= ptTwo: {0}", ptOne >= ptTwo) 'true
Console.WriteLine("ptOne <= ptTwo: {0}", ptOne <= ptTwo) 'true
End Sub
End Module

Public Structure MyPoint
Implements IComparable

Private x As Integer, y As Integer

Public Sub New(ByVal xPos As Integer, ByVal yPos As Integer)
x = xPos
y = yPos
End Sub

Public Overrides Function ToString() As String
Return String.Format("[{0}, {1}]", Me.x, Me.y)
End Function

'adding two MyPoint objects to yield a new MyPoint
Public Shared Function Add(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As MyPoint
Return New MyPoint(p1.x + p2.x, p1.y + p2.y)
End Function

'better yet, overload operator +
Public Shared Operator +(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As MyPoint
Return New MyPoint(p1.x + p2.x, p1.y + p2.y)
End Operator

'subtratcting two MyPoint objects to yield a new MyPoint
Public Shared Function Subtract(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As MyPoint
Return New MyPoint(p1.x - p2.x, p1.y - p2.y)
End Function

'better yet, overload operator -
Public Shared Operator -(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As MyPoint
Return New MyPoint(p1.x - p2.x, p1.y - p2.y)
End Operator

'overriden methods of system.Object
Public Overrides Function Equals(ByVal obj As Object) As Boolean
If TypeOf obj Is MyPoint Then
If Me.ToString() = obj.ToString() Then
Return True
End If
End If
Return False
End Function

Public Overrides Function GetHashCode() As Integer
Return Me.ToString().GetHashCode()
End Function

'now lets overload the = and <> operators
Public Shared Operator =(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return p1.Equals(p2)
End Operator
Public Shared Operator <>(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return Not p1.Equals(p2)
End Operator

Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
If TypeOf obj Is MyPoint Then
Dim p As MyPoint = CType(obj, MyPoint)
If Me.x > p.x AndAlso Me.y > p.y Then
Return 1
End If
If Me.x < p.x AndAlso Me.y < p.y Then
Return -1
Else
Return 0
End If
Else
Throw New ArgumentException()
End If
End Function

'the overloaded comparison ops
Public Shared Operator <(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return (p1.CompareTo(p2) < 0)
End Operator

Public Shared Operator >(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return (p1.CompareTo(p2) > 0)
End Operator

Public Shared Operator <=(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return (p1.CompareTo(p2) <= 0)
End Operator

Public Shared Operator >=(ByVal p1 As MyPoint, ByVal p2 As MyPoint) As Boolean
Return (p1.CompareTo(p2) >= 0)
End Operator


End Structure


Module Module1

Sub Main()
ValueTypesRefTypesAndAssignment()
End Sub

Sub ValueTypesRefTypesAndAssignment()
Console.WriteLine("***** Value Types and the Assignment Operator *****")
Console.WriteLine("-> Creating p1")
Dim p1 As New MyPoint(100, 100)

Console.WriteLine("-> Assigning p2 to p1")
Dim p2 As MyPoint = p1

'here is p1
Console.WriteLine("p1.x = {0}", p1.x)
Console.WriteLine("p1.y = {0}", p1.y)

'here is p2
Console.WriteLine("p2.x = {0}", p2.x)
Console.WriteLine("p2.y = {0}", p2.y)

'change p2.x this will NOT change p1.x
Console.WriteLine("-> Changing p2.x to 900")
p2.x = 900

'print again
Console.WriteLine("-> Here are the X values again...")
Console.WriteLine("p1.x = {0}", p1.x)
Console.WriteLine("p2.x = {0}", p2.x)
Console.ReadLine()
End Sub
End Module


Module Module1

Sub Main()
'create the first MyRectangle
Console.WriteLine("-> Creating r1")
Dim r1 As New MyRectangle("this is my first rect")

'now assign a new MyRectangle to r1
Console.WriteLine("-> Assigning r2 to r1")
Dim r2 As MyRectangle
r2 = r1

'change values of r2
Console.WriteLine("-> Changing all values of r2")
r2.rectInfo.infoString = "This is new info!"
r2.bottom = 4444

'print values
Console.WriteLine("-> Values after change:")
Console.WriteLine("-> r1.rectInfo.infoString: {0}", r1.rectInfo.infoString)
Console.WriteLine("-> r2.rectInfo.infoSTring: {0}", r2.rectInfo.infoString)
Console.WriteLine("-> r1.bottom: {0}", r1.bottom)
Console.WriteLine("-> r2.bottom: {0}", r2.bottom)
Console.ReadLine()
End Sub

End Module


Public Class Person
Public fullName As String
Public age As Integer

Public Sub New(ByVal n As String, ByVal a As Integer)
fullName = n
age = a
End Sub

Public Sub New()
End Sub

Public Overrides Function ToString() As String
Return String.Format("Name: {0}, Age: {1}", fullName, age)
End Function

End Class

Module Module1

Sub SendAPersonByValue(ByVal p As Person)
'change the age of 'p'?
p.age = 99
p = New Person("Nikki", 999)
End Sub

Sub SendAPersonByReference(ByRef p As Person)
'change some data of "p"
p.age = 555

'"p" is now point to a new object on the heap!
p = New Person("Nikki", 999)
End Sub

Sub Main()
'passing ref types by value
Console.WriteLine("***** Passing Person object by value *****" & vbLf)
Dim fred As New Person("Fred", 12)
Console.WriteLine("Before by value call, Person is:")
Console.WriteLine(fred)

SendAPersonByValue(fred)
Console.WriteLine("After by value call, Person is:")
Console.WriteLine(fred)

Console.WriteLine("***** Passing Person object by reference *****")
Dim mel As New Person("Mel", 23)
Console.WriteLine("Before by ref call, Person is:")
Console.WriteLine(mel)
SendAPersonByReference(mel)
Console.WriteLine("After by ref call, Person is:")
Console.WriteLine(mel)
Console.ReadLine()
Console.ReadLine()

End Sub
End Module


Public Class Base
End Class

Public Class Derived
Inherits Base
End Class

Module Program
Sub Main()
'implicit cast between derived to base
Dim myBaseType As Base
myBaseType = New Derived()

'must explicitly cast to store base reference
'in derived tpye
Dim myDerivedType As Derived = CType(myBaseType, Derived)
End Sub
End Module


Public Structure Rectangle
'public for ease of use
Public width As Integer, Height As Integer
Public Sub Draw()
Console.WriteLine("Drawing a rect.")
End Sub

Public Overrides Function ToString() As String
Return String.Format("[Width = {0}; Height = {1}]", width, Height)
End Function

Public Shared Widening Operator CType(ByVal s As Square) As Rectangle
Dim r As Rectangle
r.Height = s.Length
'assume the length of the new Rectangle with (Length X 2)
r.width = s.Length * 2
Return r
End Operator
End Structure

Public Structure Square
Public Length As Integer
Public Sub Draw()
Console.WriteLine("Drawing a square")
End Sub

Public Overrides Function ToString() As String
Return String.Format("[Length = {0}]", Length)
End Function

'rectangls can be explicitly converted
'into squares
Public Shared Narrowing Operator CType(ByVal r As Rectangle) As Square
Dim s As Square
s.Length = r.width
Return s
End Operator

Public Shared Narrowing Operator CType(ByVal sideLength As Integer) As Square
Dim newSq As Square
newSq.Length = sideLength
Return newSq
End Operator

Public Shared Narrowing Operator CType(ByVal s As Square) As Integer
Return s.Length
End Operator

End Structure

Module Module1
Sub DrawSquare(ByVal sq As Square)
sq.Draw()
End Sub

Sub Main()
Console.WriteLine("***** Fun with Custom Conversions *****")
Console.WriteLine()

'create a 10 * 5 rectangle
Dim rect As Rectangle
rect.width = 10
rect.Height = 5
Console.WriteLine("rect = {0}", rect)

'convert rectangle to a 10 * 10 square
Dim sq As Square = CType(rect, Square)
Console.WriteLine("sq = {0}", sq)

'this is all right, as the Square has a custom narrowing CType() implementation
DrawSquare(CType(rect, Square))

'converting an integer to a square
Dim sq2 As Square = CType(90, Square)
Console.WriteLine("sq2 = {0}", sq2)

'converting a square to an integer
Dim side As Integer = CType(sq2, Integer)
Console.WriteLine("Side length of sq2 = {0}", side)

'implicit cast ok!
Dim s3 As Square
s3.Length = 83
Dim rect2 As Rectangle = s3
Console.WriteLine("rect2 = {0}", rect2)
DrawSquare(s3)

'explicit cast syntax ok!
Dim s4 As Square
s4.Length = 3
Dim rect3 As Rectangle = CType(s4, Rectangle)
Console.WriteLine("rect3 = {0}", rect3)
Console.ReadLine()
End Sub

End Module


Imports System
Imports System.Net

Namespace Apress.VisualBasicRecipes.Chapter11
Public Class Recipe11_08
Public Shared Sub Main()
Dim args As String() = {"www.apress.com", "www.microsoft.com", "www.cracked.com"}

For Each comp As String In args
Try
'retrieve the DNS entry for the specified computer
Dim dnsEntry As IPHostEntry = dNS.GetHostEntry(comp)

'the dns entry may contain more thant one IP address iterate through
'them and display each one along with the type of address
For Each address As IPAddress In dnsEntry.AddressList
Console.WriteLine("{0} = {1} ({2})", comp, address, address.AddressFamily)
Next

Catch ex As Exception
Console.WriteLine("{0} = Error ({1})", comp, ex.Message)
End Try

Next
Console.ReadLine()
End Sub
End Class
End Namespace


Imports System
Imports System.Net.NetworkInformation

Namespace Apress.VisualBasicRecipes.Chapter11
Public Class Recipe11_09

Public Shared Sub Main()
Dim args As String() = {"www.cracked.com"}
'crate an instance of the Ping class
Using png As New Ping
Console.WriteLine("Pringing:")
For Each comp As String In args
Try
Console.Write("{0}...", comp)
'ping the specified computer with a time-out of 100ms
Dim reply As PingReply = png.Send(comp, 100)

If reply.Status = IPStatus.Success Then
Console.WriteLine("Success - IP Address:{0} " & "Time:{1}ms", reply.Address, reply.RoundtripTime)
Else
Console.WriteLine(reply.Status.ToString)
End If
Catch ex As Exception
Console.WriteLine("Error ({0})", ex.InnerException.Message)
End Try
Next
End Using
Console.ReadLine()
End Sub
End Class
End Namespace


Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sockets

Namespace Apress.VisualBasicRecipes.Chapter11



Public Class Recipe11_10Shared
Public Const AcknowledgeOK As String = "OK"
Public Const AcknowledgeCancel = "Cancel"
Public Const Disconnect As String = "Bye"
Public Const RequestConnect As String = "Hello"
End Class

Public Class Recipe11_10Server

Public Shared Sub Main()
'create a listener on port 8000
Dim listener As New TcpListener(IPAddress.Parse("127.0.0.1"), 8000)

Console.WriteLine("About to initialize port")
listener.Start()
Console.WriteLine("Listening for a connection...")

Try
'wait for a connection request and return a TcpClient initialized for communication
Using client As TcpClient = listener.AcceptTcpClient
Console.WriteLine("Connection accepted")

'retrieve the network stream
Dim stream As NetworkStream = client.GetStream()

'create a binarywriter for writing to the stream
Using w As New BinaryWriter(stream)
'create a binaryReader for reading from the stream
Using r As New BinaryReader(stream)
If r.ReadString = Recipe11_10Shared.RequestConnect Then
w.Write(Recipe11_10Shared.AcknowledgeOK)
Console.WriteLine("Connection completed.")

While Not r.ReadString = Recipe11_10Shared.Disconnect

End While
Console.WriteLine(Environment.NewLine)
Console.WriteLine("Disconnect request receieved.")
Else
Console.WriteLine("Can't complete connection.")
End If
End Using
End Using
End Using
Console.WriteLine("Connection closed.")
Catch ex As Exception
Console.WriteLine(ex.ToString)
Finally
'close the underlying socket (stop listening for new requests)
listener.Stop()
Console.WriteLine("Listener stopped.")

End Try
Console.ReadLine()
End Sub
End Class


End Namespace



Option Strict On

Imports System
Imports System.Collections

Namespace Enumeration
Public Class ListBoxTest : Implements IEnumerable
Private strings() As String
Private ctr As Integer = 0

'private nested implementation of ListBoxEnumerator
Private Class ListBoxEnumerator
Implements IEnumerator

'member fields of the nested ListBoxEnumerator class
Private currentListBox As ListBoxTest
Private index As Integer

'public within the private implementation
'thus private within ListBoxTest
Public Sub New(ByVal currentListBox As ListBoxTest)
'a particular ListBoxTest instance is passed in, hold a reference to it
'in the member variable currentListBox
Me.currentListBox = currentListBox
index = -1
End Sub

'incremement the index and make sure the value is valid
Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
index += 1
If index >= currentListBox.strings.Length Then
Return False
Else
Return True
End If
End Function

Public Sub Reset() Implements IEnumerator.Reset
index = -1
End Sub

Public ReadOnly Property Current As Object Implements System.Collections.IEnumerator.Current
Get
Return currentListBox(index)
End Get
End Property

End Class 'end nested class

'enumerable classes can return an enumerator
Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return New ListBoxEnumerator(Me)
End Function

'initialize the list box with strings
Public Sub New(ByVal ParamArray initialStrings() As String)
'allocate space for the strings
ReDim strings(7)

'copy the strings passed in to the constructor
Dim s As String
For Each s In initialStrings
strings(ctr) = s
ctr += 1
Next
End Sub

'add a single string to the end of the list box
Public Sub add(ByVal theString As String)
strings(ctr) = theString
ctr += 1
End Sub

'allow array-like access
Default Public Property Item(ByVal index As Integer) As String
Get
If index < 0 Or index >= strings.Length Then
'handle bad index
Exit Property
End If
Return strings(index)
End Get
Set(ByVal value As String)
strings(index) = value
End Set
End Property

'publish how many strings you hold
Public Function GetNumEntries() As Integer
Return ctr
End Function
End Class



Public Class Tester
Public Sub Run()
'create a new lst box and initialize
Dim currentListBox As New ListBoxTest("Hello", "World")
'add a few strings
currentListBox.add("Who")
currentListBox.add("Is")
currentListBox.add("John")
currentListBox.add("Galt")

'test the access
Dim subst As String = "Universe"
currentListBox(1) = subst

'access all the string
Dim s As String
For Each s In currentListBox
Console.WriteLine("Value: {0}", s)
Next
End Sub

Shared Sub Main()
Dim t As New Tester()
t.Run()
Console.ReadLine()
End Sub
End Class
End Namespace


Option Strict On
Imports System
Namespace ArrayListDemo
'a class to hold in the array list
Public Class Employee
Private myEmpID As Integer
Public Sub New(ByVal empID As Integer)
Me.myEmpID = empID
End Sub

Public Overrides Function ToString() As String
Return myEmpID.ToString()
End Function 'toSTring

Public Property EmpID() As Integer
Get
Return myEmpID
End Get
Set(ByVal value As Integer)
myEmpID = value
End Set
End Property
End Class 'Employee


Class Tester

Public Sub Run()
Dim empArray As New ArrayList()
Dim intArray As New ArrayList()

'populate the arraylists
Dim i As Integer
For i = 0 To 4
empArray.Add(New Employee(i + 100))
intArray.Add((i * 5))
Next i

'print each member of the array
For Each i In intArray
Console.Write("{0} ", i.ToString())
Next i

Console.WriteLine(ControlChars.Lf)
'print each employee
For Each e In empArray
Console.WriteLine("{0} ", e.ToString())
Next

Console.WriteLine(ControlChars.Lf)

Console.WriteLine("empArray.Capacity: {0}", empArray.Capacity)
End Sub 'Run

Shared Sub Main()
Dim t As New Tester()
t.Run()
Console.ReadLine()
End Sub

End Class

End Namespace

Friday, November 18, 2011

Friday 11.18.11

Public Delegate Function BinaryOp(ByVal x As Integer, ByVal y As Integer) As Integer

'this class defines the methods that will be "pointed to" by the delegate
Public Class SimpleMath
Public Shared Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
Public Shared Function Subtract(ByVal x As Integer, ByVal y As Integer) As Integer
Return x - y
End Function
End Class

Module Module1
Sub DisplayDelegateInfo(ByVal delObj As System.Delegate)
For Each d As System.Delegate In delObj.GetInvocationList()
Console.WriteLine("Method Name: {0}", d.Method)
Console.WriteLine("Type name: {0}", d.Target)
Next
End Sub

Sub Main()
Console.WriteLine("***** Simple Delegate Example *****" & vbLf)
'make a delegate object and add a method to the invocation
'liust using the AddressOf keyword
Dim b As BinaryOp = New BinaryOp(AddressOf SimpleMath.Add)

'invoke the method 'pointed to'
Console.WriteLine("10 + 10 is {0}", b(10, 10))
DisplayDelegateInfo(b)
Console.WriteLine()
End Sub

End Module


Module Module1


Sub Main()
Console.WriteLine("***** Delegates as event enablers *****")
Dim c1 As New Car("SlugBug", 10)

'pass the address of the methods that will be maintained
'by the delegate member variables of the car type
c1.OnAboutToBlow(AddressOf CarAboutToBlow)
c1.OnExploded(AddressOf CarExploded)

Console.WriteLine("***** Speeding Up *****")
For i As Integer = 0 To 5
c1.Accelerate(20)
Next
Console.ReadLine()
End Sub
Public Sub CarAboutToBlow(ByVal msg As String)
Console.WriteLine(msg)
End Sub

Public Sub CarExploded(ByVal msg As String)
Console.WriteLine(msg)
End Sub
End Module


Module Module1
'declare member variables "WithEvents" to capture the events
Private WithEvents c As New Car("NightRider", 50)

Sub Main()
Console.WriteLine("***** Fun with Events *****")
Dim i As Integer
For i = 0 To 5
c.Accelerate(10)
Next
Console.ReadLine()
End Sub

'event handlers
Public Sub MyExplodedHandler(ByVal s As String) Handles c.Exploded
Console.WriteLine(s)
End Sub

Public Sub MyAboutToDieHandler(ByVal s As String) Handles c.AboutToBlow
Console.WriteLine(s)
End Sub
End Module





Module Module1
Sub main()
Console.WriteLine("***** Fun with AddHandler/RemoveHandler *****")
'note the lack of WithEvents keyword
Dim c As New Car("NightRider", 50)

'dynamically hook into event using addhandler
AddHandler c.Exploded, AddressOf CarEventHandler
AddHandler c.AboutToBlow, AddressOf CarEventHandler

For I As Integer = 0 To 5
c.Accelerate(10)
Next

Console.ReadLine()

End Sub

Public Sub CarEventHandler(ByVal s As String)
Console.WriteLine(s)
End Sub


End Module


'this event has been customized
Public Custom Event EngineStart As System.EventHandler
AddHandler(ByVal value As System.EventHandler)
Console.WriteLine("Added connection")
arConnections.Add(value)

End AddHandler

RemoveHandler(ByVal value As System.EventHandler)

End RemoveHandler

RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs)
For Each h As EventHandler In arConnections
Console.WriteLine("Raising event")
h(sender, e)
Next
End RaiseEvent
End Event

Public Sub Start()
RaiseEvent EngineStart(Me, New EventArgs())
End Sub

Thursday, November 17, 2011

Friday 11.17.11

Partial Class TimeDisplay
Inherits System.Web.UI.UserControl

Private Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
RefreshTime()
End If
End Sub

Public Sub RefreshTime()
If strFormat = String.Empty Then
lnkTime.Text = DateTime.Now.ToLongTimeString()
Else
lnkTime.Text = DateTime.Now.ToString(Format)
End If

End Sub

Protected Sub lnkTime_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkTime.Click
RefreshTime()
End Sub

Private strFormat As String
Public Property Format() As String
Get
Return strFormat
End Get
Set(ByVal value As String)
strFormat = value
End Set
End Property
End Class


Console.WriteLine("***** Custom Generic Collection *****")
Console.WriteLine()

'make a collection of Cars
Dim myCars As New CarCollection(Of Car)()
myCars(0) = New Car("Rusty", 20)
myCars(1) = New Car("Zippy", 90)

For Each c As Car In myCars
Console.WriteLine("PetName: {0}, Speed: {1}", c.petName, c.Speed)
Next
Console.ReadLine()

Public Class CarCollection(Of T)
Implements IEnumerable(Of T)

Private myCars As New List(Of T)

'generic default property
Default Public Property Item(ByVal index As Integer) As T
Get
Return myCars(index)
End Get
Set(ByVal value As T)
myCars.Add(value)
End Set
End Property

Public Sub ClearCars()
myCars.Clear()
End Sub

Public Function CarCount() As Integer
Return myCars.Count()
End Function



Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
Return myCars.GetEnumerator()
End Function

Public Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return myCars.GetEnumerator()
End Function
End Class

Wednesday, November 16, 2011

Wednesday 11.16.11

Partial Class FileIO
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not (Directory.Exists("C:\ASPFiles")) Then
Directory.CreateDirectory("C:\ASPFiles")
End If
Dim fStream As New FileStream("C:\ASPFiles\myFile.txt", FileMode.Create)
Dim w As New StreamWriter(fStream)

w.WriteLine(Now.ToString)
w.WriteLine("ASP.NET Text File Text") 'write a string
w.WriteLine(1000)

'tidy up
w.Flush()
w.Close()
End Sub

Imports System.IO

Partial Class FileIOLoad
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim r As StreamReader = File.OpenText("C:\ASPFiles\myFile.txt")
Dim line As String
Do
line = r.ReadLine()
If line IsNot Nothing Then
Response.Write(line)
End If
Loop While line IsNot Nothing

End Sub



Protected Sub cmdUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpload.Click
Try
If Uploader.PostedFile.ContentLength > 11064 Then
'this exceeds the size limit you want to allow
'you should check the size to prevent a denial of service attack that attempt to fill up
'your web servers hard drive
'you might also want to check the amount of remaining free space
lblStatus.Text = "Too lage. This file is not allowed"
Else
'retireve the physical direcotry path for the upload subdirectory
Dim destDir As String = "C:/ASPFiles"
'Dim destDir As String = Server.MapPath("./Upload")
'extract the filename part from teh full path fo the original file
Dim fName As String = Path.GetFileName(Uploader.PostedFile.FileName)
'combine the destination directory wtih the filename
Dim destPath As String = Path.Combine(destDir, fName)
'save the file on the server
Uploader.PostedFile.SaveAs(destPath)
lblStatus.Text = "Thanks for submitting your file."
End If
Catch err As Exception
lblStatus.Text = err.Message
End Try

End Sub


Imports System.IO

Partial Class LogFile
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.IsPostBack) Then
Log("Page loaded for the first time")
Else
Log("Page posted back")
End If
End Sub

'store a user-specific log

Private Function GetFileName() As String
'crate a unique filename
Dim fileName As String = "user." & Guid.NewGuid().ToString()

'put the file in the current web applciation path
Return Path.Combine(Request.PhysicalApplicationPath, fileName)

End Function

Private Sub Log(ByVal message As String)
'check for the file
Dim mode As FileMode
Try
If ViewState("LogFile") Is Nothing Then
'first create a unique user-specific filename
ViewState("LogFile") = GetFileName()
'the log file must be greated
mode = FileMode.Create

Else
'add to the existing fle
mode = FileMode.Append
End If

'write teh message
'A Using block ensures the file is automatically closed
'even in the case of error
Dim fileName As String = CStr(ViewState("LogFile"))
Using fs As New FileStream(fileName, mode)
Dim w As New StreamWriter(fs)
w.WriteLine(DateTime.Now)
w.WriteLine(message)
w.Close()
End Using
Catch ex As Exception
Response.Write(ex.ToString())
End Try

End Sub


Protected Sub cmdReadLog_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdReadLog.Click
If ViewState("LogFile") IsNot Nothing Then
Dim fileName As String = CStr(ViewState("LogFile"))
Using fs As New FileStream(fileName, FileMode.Open)
Dim r As New StreamReader(fs)
'read line by line allows you to add line breaks to the web page
Dim line As String
Do
line = r.ReadLine()
If line IsNot Nothing Then
lblInfo.Text &= line & "
"
End If
Loop While line IsNot Nothing
r.Close()
End Using
End If
End Sub
End Class

Tuesday, November 15, 2011

Tuesday 11.15.11

Module Module1

Sub Main()
Console.WriteLine("***** Simple Exception Example *****")
Console.WriteLine("=> Creating a car and stepping on it!")
Dim myCar As New Car("Zippy", 20)
myCar.CrankTunes(True)

Try
For i As Integer = 0 To 10
myCar.Accelerate(10)
Next
Catch ex As Exception
Console.WriteLine("*** Error! ***")
Console.WriteLine("Method: {0}", ex.TargetSite)
Console.WriteLine("Class defining member: {0}", ex.TargetSite.DeclaringType)
Console.WriteLine("Help Link: {0}", ex.HelpLink)
Console.WriteLine("Member type: {0}", ex.TargetSite.MemberType)
Console.WriteLine("Message: {0}", ex.Message)
Console.WriteLine("Source: {0}", ex.Source)
Console.WriteLine("-> Custom Data:")
If (ex.Data IsNot Nothing) Then
For Each de As DictionaryEntry In ex.Data
Console.WriteLine("-> {0} : {1}", de.Key, de.Value)
Next
End If
End Try

Console.ReadLine()
End Sub

End Module



Sub Main()

'the class type System.GC allows you to programatically interact with the
'garbage collector

Console.WriteLine("***** Fun with System.GC *****")
'print out estimated number of bytes on heap
Console.WriteLine("Estimated bytes on heap: {0}", GC.GetTotalMemory(False))

'MaxGeneration is zero based, so add 1 for display purposes
Console.WriteLine("This OS has {0} object generations.", (GC.MaxGeneration + 1))

Dim refToMyCar As New Car("Zippy", 100)
Console.WriteLine(refToMyCar.ToString())

'print out generation of refToMyCar object
Console.WriteLine("Generation of refToMyCar is: {0}", GC.GetGeneration(refToMyCar))
Console.ReadLine()

'make a ton of objects for testing purposes
Dim tonsOfObjects(5000) As Object
For i As Integer = 0 To UBound(tonsOfObjects)
tonsOfObjects(i) = New Object()
Next

'collect only gen 0 objects
GC.Collect(0)
GC.WaitForPendingFinalizers()

'print out generation of refToMyCar
Console.WriteLine("Generation of refToMyCar is: {0}", GC.GetGeneration(refToMyCar))

'see if tonsOfObjects(4000) is still alive
If (tonsOfObjects(4000) IsNot Nothing) Then
Console.WriteLine("Generation of tonsOfObjects(4000) is: {0}", GC.GetGeneration(tonsOfObjects(4000)))
Else
Console.WriteLine("tonsOfObjects(4000) is no longer alive.")
End If

'print out how many times a generation has been swept
Console.WriteLine("Gen 0 has been swept {0} times", GC.CollectionCount(0))
Console.WriteLine("Gen 2 has been swept {0} times", GC.CollectionCount(1))
Console.WriteLine("Gen 3 has been swept {0} times", GC.CollectionCount(2))
Console.ReadLine()

End Sub



Sub Main()
ArrayListTest()

End Sub

Sub ArrayListTest()
'make ArrayList and add a range of cars
Dim carArList As New ArrayList()
carArList.AddRange(New Car() {New Car("Fred", 90), New Car("Mary", 100), New Car("MB", 190)})
Console.WriteLine("items in carArList: {0}", carArList.Count)

'iterate over contents using For/Each
For Each c As Car In carArList
Console.WriteLine("Car pet name: {0}", c.name)
Next

'insert new car
Console.WriteLine("-> Inserting new Car.")
carArList.Insert(2, New Car("TheNewCar", 0))
Console.WriteLine("Items in carArlist: {0}", carArList.Count)

'get the subobjects as an array
Dim arrayOfCars As Object() = carArList.ToArray()
Dim i As Integer = 0

'now iterate over array using While loop/Length property
While i < arrayOfCars.Length
Console.WriteLine("Car pet name: {0}", CType(arrayOfCars(i), Car).name)
i = i + 1
End While
Console.ReadLine()

End Sub


Public Sub WashCar(ByVal c As Car)
Console.WriteLine("Cleaning {0}", c.name)
End Sub

Sub QueueTest()
'make a Q with three items
Dim carWashQ As New Queue()
carWashQ.Enqueue(New Car("FirstCar", 0))
carWashQ.Enqueue(New Car("SecondCar", 1))
carWashQ.Enqueue(New Car("ThirdCar", 3))

'peek at first car in queue
Console.WriteLine("First in Q is {0}", CType(carWashQ.Peek(), Car).name)
'remove each item from Q
WashCar(CType(carWashQ.Dequeue(), Car))
WashCar(CType(carWashQ.Dequeue(), Car))
WashCar(CType(carWashQ.Dequeue(), Car))

'try to d-Q again?
Try
WashCar(CType(carWashQ.Dequeue(), Car))
Catch ex As Exception
Console.WriteLine("Error!! {0}", ex.Message)
End Try
End Sub


Sub Main()
Dim myPeople As New PeopleCollection()
myPeople.AddPerson(New Person("Homer", "Simpson", 40))
myPeople.AddPerson(New Person("Marge", "Simpson", 38))
myPeople.AddPerson(New Person("Lisa", "Simpson", 7))
myPeople.AddPerson(New Person("Bart", "Simpson", 9))
myPeople.AddPerson(New Person("Maggie", "Simpson", 2))

For Each p As Person In myPeople
Console.WriteLine(p)
Next

myPeople(5) = New Person("Waylon", "Smithers", 47)
Console.WriteLine("Person #5 is {0}", myPeople(5))

Console.ReadLine()
End Sub

Public Class PeopleCollection
Implements IEnumerable

Private arPeople As New ArrayList()

Public Function GetPerson(ByVal pos As Integer) As Person
Return CType(arPeople(pos), Person)
End Function

Public Sub AddPerson(ByVal p As Person)
arPeople.Add(p)
End Sub

Public Sub ClearPeople()
arPeople.Clear()
End Sub

Public ReadOnly Property Count() As Integer
Get
Return arPeople.Count
End Get
End Property

'the 'indexer' of this custom collection
Default Public Property Item(ByVal p As Integer) As Person
Get
Return CType(arPeople(p), Person)
End Get
Set(ByVal value As Person)
arPeople.Insert(p, value)
End Set
End Property

Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return arPeople.GetEnumerator
End Function
End Class

Public Class Person
'Made public for simplicity
Public currAge As Integer
Public fName As String
Public lName As String

'constructors
Public Sub New()

End Sub

Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal age As String)
currAge = age
fName = firstName
lName = lastName
End Sub

Public Overrides Function ToString() As String
Return String.Format("{0}, {1} is {2} years old.", lName, fName, currAge)
End Function
End Class


Sub Main()
Console.WriteLine("***** Fun with Nullable Data ******" & vbLf)
Dim dr As New DatabaseReader()

'get integer from 'database'
Dim i As Nullable(Of Integer) = dr.GetIntFromDatabase()
If (i.HasValue) Then
Console.WriteLine("Value of 'i' is: {0}", i.Value)
Else
Console.WriteLine("Value of 'i' is undefined.")
End If

'get Boolean from "database"
Dim b As Nullable(Of Boolean) = dr.GetBoolFromDatabase()
If (b.HasValue) Then
Console.WriteLine("Value of 'b' is: {0}", b.Value)
Else
Console.WriteLine("Value of 'b' is undefined.")
End If
Console.ReadLine()
End Sub

Public Class DatabaseReader
'nullable data fields
Public numericValue As Nullable(Of Integer) = Nothing
Public boolValue As Nullable(Of Boolean) = True

'note the nullable return type
Public Function GetIntFromDatabase() As Nullable(Of Integer)
Return numericValue
End Function

'note the nullable return type

Public Function GetBoolFromDatabase() As Nullable(Of Boolean)
Return boolValue
End Function
End Class

Monday, November 14, 2011

Monday 11.14.11

Sub Main()
Dim myCar As New Car()
myCar.petName = "Sven"
myCar.currSpeed = 10

'speed up the car a few times and print out the new sate
For i As Integer = 0 To 10
myCar.SpeedUp(5)
myCar.PrintState()
Next
End Sub

Public Class Car
'the state of a car
Public petName As String
Public currSpeed As Integer

'the functionality of the car
Public Sub PrintState()
Console.WriteLine("{0} is going {1} MPH.", petName, currSpeed)
End Sub

Public Sub SpeedUp(ByVal delta As Integer)
currSpeed += delta
End Sub


End Class



Module Module1

Sub Main()
'make a car called chuck going 10 mph
Dim chuck As New Car()
chuck.PrintState()

'make a car call Mary going 0 MPH
Dim mary As New Car("Mary")
mary.PrintState()

'make a car called Daisy going 75 MPH
Dim daisy As New Car("Daisy", 75)
daisy.PrintState()

End Sub


Public Class Car
'the state of a car
Public petName As String
Public currSpeed As Integer

' a custom default constructor
Public Sub New()
petName = "Chuck"
currSpeed = 10
End Sub

'here, currSpeed will receive the default value of an Integer (zero)
Public Sub New(ByVal pn As String)
petName = pn
End Sub

Public Sub New(ByVal pn As String, ByVal cs As Integer)
petName = pn
currSpeed = cs
End Sub

'the functionality of the car
Public Sub PrintState()
Console.WriteLine("{0} is going {1} MPH.", petName, currSpeed)
End Sub

Public Sub SpeedUp(ByVal delta As Integer)
currSpeed += delta
End Sub


End Class



Sub Main()
Dim c As New Motorcycle
c.SetDriverName("Tiny")
c.PopAWheely()
Console.WriteLine("Rider name is {0}", c.driverName)

End Sub

Public Class Motorcycle
Public driverIntensity As Integer
Public driverName As String

'redundant constructor logic below!

Public Sub New()

End Sub

Public Sub New(ByVal intensity As Integer)
ValidateIntensity(intensity)
driverIntensity = intensity
End Sub


Public Sub New(ByVal intensity As Integer, ByVal name As String)
ValidateIntensity(intensity)
driverIntensity = intensity
driverName = name
End Sub

Sub ValidateIntensity(ByRef intensity As Integer)
If intensity > 10 Then
intensity = 10
End If
End Sub

Public Sub PopAWheely()
Console.WriteLine("Yeeeeeeeeee Haaaaaaaaaaaaewwww!")
End Sub

Public Sub SetDriverName(ByVal driverName As String)
Me.driverName = driverName
End Sub
End Class



Public Class Teenager
Public Shared r As New Random()

Public Shared Function GetRandomNumber(ByVal upperLimit As Short) As Integer
Return r.Next(upperLimit)
End Function

Public Shared Function Complain() As String
Dim messages As String() = _
{"Do I have to?", "He started it!", "I'm too tired...", "I hate school!", "You are sooo wrong."}
Return messages(GetRandomNumber(5))
End Function

End Class

Sub Main()
Console.WriteLine("***** Shared Methods *****")
For i As Integer = 0 To 5
Console.WriteLine(Teenager.Complain())
Next

End Sub


Sub Main()
Console.WriteLine("***** Fun with Shared Data *****")
Dim s1 As New SavingsAccount(50)
Dim s2 As New SavingsAccount(100)

'get and set interest rate at object level
Console.WriteLine("Interest rate is: {0}", s1.GetInterestRateObj())
s2.SetInterestRateObj(0.08)

'make new object: this does NOT "reset" the interest rate for this object
Dim s3 As New SavingsAccount(10000.75)
Console.WriteLine("Interest Rate is: {0}", SavingsAccount.GetInterestRate())
Console.ReadLine()
End Sub

Public Class SavingsAccount
Public currBalance As Double
Public Shared currInterestRate As Double = 0.04

Public Sub New(ByVal balance As Double)
currBalance = balance
End Sub

Shared Sub New()
Console.WriteLine("In Shared ctor!")
currInterestRate = 0.04
End Sub

'shared members to get/set interest rate
Public Shared Sub SetInterestRate(ByVal newRate As Double)
currInterestRate = newRate
End Sub

Public Shared Function GetInterestRate() As Double
Return currInterestRate
End Function



'Instance members to get/set interest rate
Public Sub SetInterestRateObj(ByVal newRate As Double)
currInterestRate = newRate
End Sub

Public Function GetInterestRateObj() As Double
Return currInterestRate
End Function

End Class


Public Class Employee
'field data
Private empName As String
Private empID As Integer
Private currPay As Single


Public Sub New()

End Sub

Public Sub New(ByVal name As String, ByVal id As Integer, ByVal pay As Single)
empName = name
empID = id
currPay = pay
End Sub

'methods
Public Sub GiveBonus(ByVal amount As Single)
currPay += amount

End Sub

Public Sub DisplayStats()
Console.WriteLine("Name: {0}", empName)
Console.WriteLine("ID: {0}", empID)
Console.WriteLine("Pay: {0}", currPay)
End Sub

'access (get method)
Public Function GetName() As String
Return empName
End Function

'Mutator (set method)
Public Sub SetName(ByVal name As String)
empName = name
End Sub
End Class


Sub Main()
Console.WriteLine("***** Basic Inheritance *****")
'make a car object
Dim myCar As New Car(80)
myCar.Speed = 50
Console.WriteLine("My car is going {0} MPH", myCar.Speed)
Console.ReadLine()

'now create a minivan object
Dim myVan As New MiniVan()
myVan.Speed = 10
Console.WriteLine("My van is going {0} MPH", myVan.Speed)
Console.ReadLine()
End Sub


Public Class Salespeople
Inherits Employee

Private numberOfSales As Integer
Public Property SalesNumber() As Integer
Get
Return numberOfSales
End Get
Set(ByVal value As Integer)
numberOfSales = value
End Set
End Property

End Class

Public Class Managers
Inherits Employee

Private numberOfOptions As Integer
Public Property StockOptions() As Integer
Get
Return numberOfOptions
End Get
Set(ByVal value As Integer)
numberOfOptions = value
End Set
End Property
End Class
Sub Main()
Console.WriteLine("**** Employee Class Hierarchy ******")
Console.WriteLine()

'make a salesperson
Dim danny As New Salespeople
With danny
.ID = 100
.SalesNumber = 50
.Name = "Dan McCabe"
End With
End Sub


odule Module1

Sub Main()
Console.WriteLine("***** Fun with System.Object *****")
Console.WriteLine()
Dim p1 As New Person("Homer", "Simpson", 50)
Dim p2 As New Person("Homer", "Simpson", 50)

'get stringified version of objects
Console.WriteLine("p1.ToString() = {0}", p1.ToString())
Console.WriteLine("p2.ToString() = {0}", p2.ToString())

'test overridden equals()
Console.WriteLine("p1 = p2?: {0}", p1.Equals(p2))

'test hash codes
Console.WriteLine("Same hash codes?: {0}", p1.GetHashCode() = p2.GetHashCode())
Console.WriteLine()

'change age of p2 and test again
p2.personAge = 45
Console.WriteLine("p1.ToString() = {0}", p1.ToString())
Console.WriteLine("p2.ToString() = {0}", p2.ToString())
Console.WriteLine("p1 = p2?: {0}", p1.Equals(p2))
Console.WriteLine("Same hash codes?: {0}", p1.GetHashCode() = p2.GetHashCode())
Console.ReadLine()

End Sub


End Module


Class Person
'public only for simplicity
'properties and private data would obviously be preferred
Public fName As String
Public lName As String
Public personAge As Byte

Public Sub New(ByVal firstName As String, ByVal lastName As String, ByVal age As Byte)
fName = firstName
lName = lastName
personAge = age
End Sub
Public Sub New()

End Sub

Public Overrides Function ToString() As String
Dim myState As String
myState = String.Format("[First Name: {0}; Last Name: {1}; Age: {2}", fName, lName, personAge)
Return myState

End Function

Public Overrides Function Equals(ByVal obj As Object) As Boolean
If TypeOf obj Is Person AndAlso obj IsNot Nothing Then
Dim temp As Person = CType(obj, Person)
If temp.fName = Me.fName AndAlso temp.lName = Me.fName AndAlso temp.personAge = Me.personAge Then
Return True
Else
Return False
End If
Return False
End If

End Function

'return a hash code based on the person's ToSTring() Value
Public Overrides Function GetHashCode() As Integer
Return Me.ToString().GetHashCode()
End Function
End Class


Saturday, November 12, 2011

Saturday 11.12.11

Module Module1

Sub Main()
Console.WriteLine("**** Fun With Eums ****")


Dim day As DayOfWeek
Dim cc As ConsoleColor

EvaluateEnum(day)
EvaluateEnum(cc)

End Sub

Sub EvaluateEnum(ByVal e As [Enum])
Console.WriteLine("=> Information about {0}", e.GetType().Name)

Console.WriteLine("Underlying storage type: {0}", [Enum].GetUnderlyingType(e.GetType()))


'get all name/value pairs for incoming parameters
Dim enumData As Array = [Enum].GetValues(e.GetType())
Console.WriteLine("This enum has {0} members.", enumData.Length)

'now show the string name and associated value
For i As Integer = 0 To enumData.Length - 1
Console.WriteLine("Name: {0}, Value: {1}", enumData.GetValue(i).ToString(), CInt(enumData.GetValue(i)))
Next
Console.WriteLine()
End Sub
End Module


Module Module1

Structure Point
Public X, Y As Integer

Sub Display()
Console.WriteLine("X = {0}, Y = {1}", X, Y)
End Sub

Sub Increment()
X += 1 : Y += 1
End Sub

Sub Decrement()
X -= 1 : Y -= 1
End Sub

'recall that the 'x' format flag displays the data in hex format
Function PointAsHexString() As String
Return String.Format("X = {0:X}, Y = {1:X}", X, Y)
End Function
End Structure


Sub Main()
Console.WriteLine("***** A First Look At Structures *****")
'create an initial point
Dim myPoint As New Point()
myPoint.X = 349
myPoint.Y = 76
myPoint.Display()

'adjust the X and Y values
myPoint.Increment()
myPoint.Display()
Console.WriteLine("Point in hex: {0}", myPoint.PointAsHexString())
End Sub
End Module

Friday, November 11, 2011

Friday 11.11.11

Imports System.IO

Partial Class StrDirectoryList
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim x As Integer = 0

While x = 0
If Directory.Exists("c:\Temp") Then
Dim strDirectoryName As String = "c:\Temp"

'retrieve the list of files, and display it in the page
Dim fileList As String() = Directory.GetFiles(strDirectoryName)
For Each File As String In fileList
lstFiles.Items.Add(File)
Next
x = 1
Else
Response.Write("Directory C:\Temp does not exist")
Response.Write("
Creating directory...")
Dim myDirectory As New DirectoryInfo("c:\Temp")
Dim myFile As New FileInfo("c:\Temp\readme.txt")

'now create them order here is important
myDirectory.Create()
Dim stream As FileStream = myFile.Create()
stream.Close()
End If
End While


End Sub
End Class


Imports System.IO
Imports System.Diagnostics

Partial Class FileBrowser
Inherits System.Web.UI.Page


Private Sub ShowDirectoryContents(ByVal strPath As String)
'define the current directory
Dim dir As New DirectoryInfo(strPath)

'get the DirectoryInfo and fileInfo objects
Dim files As FileInfo() = dir.GetFiles()
Dim dirs As DirectoryInfo() = dir.GetDirectories()

'show the directory listing
lblCurrentDir.Text = "Currently showing " & strPath
gridFileList.DataSource = files
gridDirList.DataSource = dirs
Page.DataBind()

'clear any selection
gridFileList.SelectedIndex = -1
'keep track of the current path
ViewState("CurrentPath") = strPath

End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.IsPostBack) Then
ShowDirectoryContents(Server.MapPath("."))
End If
End Sub


Protected Sub cmdUp_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUp.Click
Dim strPath As String = CStr(ViewState("CurrentPath"))
strPath = Path.Combine(strPath, "..")
strPath = Path.GetFullPath(strPath)
ShowDirectoryContents(strPath)
End Sub

Protected Sub gridDirList_SelectedIndexChanged(ByVal source As Object, ByVal e As EventArgs)
'get the selected directory
Dim dir As String = CStr(gridDirList.DataKeys(gridDirList.SelectedIndex).Value)
'now refresh the directory list to
'show the selected directory
ShowDirectoryContents(dir)
End Sub

Protected Sub gridFileList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
'get the selected file
Dim file As String = CStr(gridFileList.DataKeys(gridFileList.SelectedIndex).Value)
'the FormView shows a collection (or list) of items
'to accommodate this model you must add the file object
'to a collection of some sort
Dim files As ArrayList = New ArrayList()
files.Add(New FileInfo(file))

'now show the selected file
formFileDetails.DataSource = files
formFileDetails.DataBind()
End Sub

Protected Function GetVersionInfoString(ByVal strPath As Object) As String
Dim info As FileVersionInfo = FileVersionInfo.GetVersionInfo(CStr(strPath))
Return info.FileName & " " & info.FileVersion & "
" & info.ProductName & " " & info.ProductVersion
End Function
End Class


public partial class SimpleADONetGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//create the connection string and command string
string connectionString = @"Data Source=Alfred-PC\SQLExpress" + "Initial Catalog=AdventureWorks; Integrated Security=SSPI";

string commandString = "SELECT [ContactID], [FirstName], [LastName], [EmailAddress] FROM Person.Contact";

//pass the strings to the SqlDataAdapter constructor
SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, connectionString);

//create a dataset
DataSet dataSet = new DataSet();

//fill the dataset object
dataAdapter.Fill(dataSet, "Customers");

//get the table from the dataset
DataTable dataTable = dataSet.Tables["Customers"];

//bind to the gridview
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
}


Module Module1

Sub Main()
SystemArrayFunctionality()
End Sub

Sub SystemArrayFunctionality()
Console.WriteLine("=> Working with System.Array.")
'initialize items at startup
Dim gothicBands() As String = {"Tones on Tail", "Bauhaus", "Sisters of Mercy"}

'print out names in declared order
Console.WriteLine(" -> Here is the array:")
For i As Integer = 0 To gothicBands.GetUpperBound(0)
'print a name
Console.WriteLine(gothicBands(i) & " ")
Next
Console.WriteLine()
Console.WriteLine()

'reverse them
Array.Reverse(gothicBands)
Console.WriteLine(" -> The reversed array")
'and print them
For i As Integer = 0 To gothicBands.GetUpperBound(0)
'print a name
Console.WriteLine(gothicBands(i) & " ")
Next
Console.WriteLine()
Console.WriteLine()

'clear out all but the final member
Console.WriteLine(" -> Cleared out all but one...")
Array.Clear(gothicBands, 1, 2)
For i As Integer = 0 To gothicBands.GetUpperBound(0)
'print a name
Console.WriteLine(gothicBands(i) & " ")
Next
Console.WriteLine()
End Sub
End Module



Module Module1

Enum EmpType As Byte
Manager = 10
Grunt = 1
Contractor = 100
VicePresident = 9
End Enum

Sub Main()
Console.WriteLine("***** Fun with Enums *****")
'make a contractor type
Dim emp As EmpType = EmpType.Contractor
AskForBonus(emp)
Dim emp2 As EmpType = EmpType.Manager
AskForBonus(emp2)
End Sub

Sub AskForBonus(ByVal e As EmpType)
Select Case (e)
Case EmpType.Contractor
Console.WriteLine("You already get enough cash...")
Case EmpType.Grunt
Console.WriteLine("You have got to be kidding...")
Case EmpType.Manager
Console.WriteLine("How about stock options instead?")
Case EmpType.VicePresident
Console.WriteLine("VERY GOOD, Sir!")
End Select
End Sub


End Module

Friday 11.11.11

Imports System.Xml

Partial Class GetElementsByTagName
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xmlFile As String = Server.MapPath("DvdList.xml")
Dim doc As New XmlDocument()
doc.Load(xmlFile)

'find all the elements anywhere in the document<br /> Dim str As New StringBuilder()<br /> Dim nodes As XmlNodeList = doc.GetElementsByTagName("Title")<br /> For Each node As XmlNode In nodes<br /> str.Append("Found: <b>")<br /><br /> 'show the text contained in this <Title> element<br /> str.Append(node.ChildNodes(0).Value)<br /> str.Append("</b><br />")<br /> Next<br /> Response.Write(str.ToString())<br /><br /> 'clear the string builder<br /> str.Length = 0<br /><br /> For Each node As XmlNode In nodes<br /> str.Append("Found: <b>")<br /><br /> 'show the text contained in this <Title> element<br /> Dim name As String = node.ChildNodes(0).Value<br /> str.Append(name)<br /> str.Append("</b><br />")<br /><br /> If name = "Forrest Gump" Then<br /> 'find the stars for just this movie<br /> 'first you need to get the parent node<br /> 'which is the <DVD> element for the movie<br /> Dim parent As XmlNode = node.ParentNode<br /><br /> 'Then you need to search down the tree<br /> Dim childNodes As XmlNodeList = (CType(parent, XmlElement)).GetElementsByTagName("Star")<br /> For Each childNode As XmlNode In childNodes<br /> str.Append("   Found Star: ")<br /> str.Append(childNode.ChildNodes(0).Value)<br /> str.Append("<br />")<br /> Next<br /> End If<br /> Next<br /> Response.Write("<hr> <br /> <br/>")<br /> Response.Write(str.ToString())<br /><br /> End Sub<br />End Class <div style='clear: both;'></div> </div> <div class='post-footer'> <div class='post-footer-line post-footer-line-1'> <span class='post-author vcard'> Posted by <span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'> <meta content='https://www.blogger.com/profile/10483429620186012661' itemprop='url'/> <a class='g-profile' href='https://www.blogger.com/profile/10483429620186012661' rel='author' title='author profile'> <span itemprop='name'>aljensen</span> </a> </span> </span> <span class='post-timestamp'> at <meta content='http://21stcenturymandarin.blogspot.com/2011/11/friday-111111_11.html' itemprop='url'/> <a class='timestamp-link' href='http://21stcenturymandarin.blogspot.com/2011/11/friday-111111_11.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-11-11T11:55:00-08:00'>11:55 AM</abbr></a> </span> <span class='post-comment-link'> <a class='comment-link' href='https://www.blogger.com/comment.g?blogID=1128425782735047114&postID=7773096117467098988' onclick=''> No comments: </a> </span> <span class='post-icons'> <span class='item-control blog-admin pid-2034475012'> <a href='https://www.blogger.com/post-edit.g?blogID=1128425782735047114&postID=7773096117467098988&from=pencil' title='Edit Post'> <img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/> </a> </span> </span> <div class='post-share-buttons goog-inline-block'> </div> </div> <div class='post-footer-line post-footer-line-2'> <span class='post-labels'> </span> </div> <div class='post-footer-line post-footer-line-3'> <span class='post-location'> </span> </div> </div> </div> </div> <div class='post-outer'> <div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'> <meta content='1128425782735047114' itemprop='blogId'/> <meta content='1879276351077154685' itemprop='postId'/> <a name='1879276351077154685'></a> <h3 class='post-title entry-title' itemprop='name'> <a href='http://21stcenturymandarin.blogspot.com/2011/11/friday-111111.html'>Friday 11.11.11</a> </h3> <div class='post-header'> <div class='post-header-line-1'></div> </div> <div class='post-body entry-content' id='post-body-1879276351077154685' itemprop='description articleBody'> Imports System.Xml<br /><br />Partial Class GetElementsByTagName<br /> Inherits System.Web.UI.Page<br /><br /> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load<br /> Dim xmlFile As String = Server.MapPath("DvdList.xml")<br /> Dim doc As New XmlDocument()<br /> doc.Load(xmlFile)<br /><br /> 'find all the <Title> elements anywhere in the document<br /> Dim str As New StringBuilder()<br /> Dim nodes As XmlNodeList = doc.GetElementsByTagName("Title")<br /> For Each node As XmlNode In nodes<br /> str.Append("Found: <b>")<br /><br /> 'show the text contained in this <Title> element<br /> str.Append(node.ChildNodes(0).Value)<br /> str.Append("</b><br />")<br /> Next<br /> Response.Write(str.ToString())<br /><br /> 'clear the string builder<br /> str.Length = 0<br /><br /> For Each node As XmlNode In nodes<br /> str.Append("Found: <b>")<br /><br /> 'show the text contained in this <Title> element<br /> Dim name As String = node.ChildNodes(0).Value<br /> str.Append(name)<br /> str.Append("</b><br />")<br /><br /> If name = "Forrest Gump" Then<br /> 'find the stars for just this movie<br /> 'first you need to get the parent node<br /> 'which is the <DVD> element for the movie<br /> Dim parent As XmlNode = node.ParentNode<br /><br /> 'Then you need to search down the tree<br /> Dim childNodes As XmlNodeList = (CType(parent, XmlElement)).GetElementsByTagName("Star")<br /> For Each childNode As XmlNode In childNodes<br /> str.Append("   Found Star: ")<br /> str.Append(childNode.ChildNodes(0).Value)<br /> str.Append("<br />")<br /> Next<br /> End If<br /> Next<br /> Response.Write("<hr> <br /> <br/>")<br /> Response.Write(str.ToString())<br /><br /> End Sub<br />End Class <div style='clear: both;'></div> </div> <div class='post-footer'> <div class='post-footer-line post-footer-line-1'> <span class='post-author vcard'> Posted by <span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'> <meta content='https://www.blogger.com/profile/10483429620186012661' itemprop='url'/> <a class='g-profile' href='https://www.blogger.com/profile/10483429620186012661' rel='author' title='author profile'> <span itemprop='name'>aljensen</span> </a> </span> </span> <span class='post-timestamp'> at <meta content='http://21stcenturymandarin.blogspot.com/2011/11/friday-111111.html' itemprop='url'/> <a class='timestamp-link' href='http://21stcenturymandarin.blogspot.com/2011/11/friday-111111.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-11-11T11:55:00-08:00'>11:55 AM</abbr></a> </span> <span class='post-comment-link'> <a class='comment-link' href='https://www.blogger.com/comment.g?blogID=1128425782735047114&postID=1879276351077154685' onclick=''> No comments: </a> </span> <span class='post-icons'> <span class='item-control blog-admin pid-2034475012'> <a href='https://www.blogger.com/post-edit.g?blogID=1128425782735047114&postID=1879276351077154685&from=pencil' title='Edit Post'> <img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/> </a> </span> </span> <div class='post-share-buttons goog-inline-block'> </div> </div> <div class='post-footer-line post-footer-line-2'> <span class='post-labels'> </span> </div> <div class='post-footer-line post-footer-line-3'> <span class='post-location'> </span> </div> </div> </div> </div> </div></div> <div class="date-outer"> <h2 class='date-header'><span>Thursday, November 10, 2011</span></h2> <div class="date-posts"> <div class='post-outer'> <div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'> <meta content='1128425782735047114' itemprop='blogId'/> <meta content='7479713982502944755' itemprop='postId'/> <a name='7479713982502944755'></a> <h3 class='post-title entry-title' itemprop='name'> <a href='http://21stcenturymandarin.blogspot.com/2011/11/thursday-111011.html'>Thursday 11.10.11</a> </h3> <div class='post-header'> <div class='post-header-line-1'></div> </div> <div class='post-body entry-content' id='post-body-7479713982502944755' itemprop='description articleBody'> Imports Microsoft.VisualBasic<br /><br />Public Class Product<br /> Private _name As String<br /> Private _price As Decimal<br /> Private _imageUrl As String<br /><br /> Public Property Name() As String<br /> Get<br /> Return _name<br /> End Get<br /> Set(ByVal value As String)<br /> _name = value<br /> End Set<br /> End Property<br /><br /> Public Property Price() As Decimal<br /> Get<br /> Return _price<br /> End Get<br /> Set(ByVal value As Decimal)<br /> _price = value<br /> End Set<br /> End Property<br /><br /> Public Property ImageUrl() As String<br /> Get<br /> Return _imageUrl<br /> End Get<br /> Set(ByVal value As String)<br /> _imageUrl = value<br /> End Set<br /> End Property<br /><br /><br /> Public Sub New(ByVal name As String, ByVal price As Decimal)<br /> _name = name<br /> _price = price<br /> End Sub<br /><br /> Public Function GetHtml() As String<br /> Dim htmlString As String<br /> htmlString = "<h1>" & Name & "</h1><br />"<br /> htmlString &= "<h3>Costs: " & Price.ToString() & "</h3><br />"<br /> htmlString &= "<Img src="" & ImageUrl & "" />"<br /> Return htmlString<br /><br /> End Function<br />End Class <div style='clear: both;'></div> </div> <div class='post-footer'> <div class='post-footer-line post-footer-line-1'> <span class='post-author vcard'> Posted by <span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'> <meta content='https://www.blogger.com/profile/10483429620186012661' itemprop='url'/> <a class='g-profile' href='https://www.blogger.com/profile/10483429620186012661' rel='author' title='author profile'> <span itemprop='name'>aljensen</span> </a> </span> </span> <span class='post-timestamp'> at <meta content='http://21stcenturymandarin.blogspot.com/2011/11/thursday-111011.html' itemprop='url'/> <a class='timestamp-link' href='http://21stcenturymandarin.blogspot.com/2011/11/thursday-111011.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-11-10T18:29:00-08:00'>6:29 PM</abbr></a> </span> <span class='post-comment-link'> <a class='comment-link' href='https://www.blogger.com/comment.g?blogID=1128425782735047114&postID=7479713982502944755' onclick=''> No comments: </a> </span> <span class='post-icons'> <span class='item-control blog-admin pid-2034475012'> <a href='https://www.blogger.com/post-edit.g?blogID=1128425782735047114&postID=7479713982502944755&from=pencil' title='Edit Post'> <img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/> </a> </span> </span> <div class='post-share-buttons goog-inline-block'> </div> </div> <div class='post-footer-line post-footer-line-2'> <span class='post-labels'> </span> </div> <div class='post-footer-line post-footer-line-3'> <span class='post-location'> </span> </div> </div> </div> </div> </div></div> <div class="date-outer"> <h2 class='date-header'><span>Wednesday, November 9, 2011</span></h2> <div class="date-posts"> <div class='post-outer'> <div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'> <meta content='1128425782735047114' itemprop='blogId'/> <meta content='4776495648797544829' itemprop='postId'/> <a name='4776495648797544829'></a> <div class='post-header'> <div class='post-header-line-1'></div> </div> <div class='post-body entry-content' id='post-body-4776495648797544829' itemprop='description articleBody'> Protected Sub gvONe_DataBound(ByVal sender As Object, ByVal e As EventArgs) Handles gvOne.DataBound<br /> Dim valueInStock As Decimal = 0<br /><br /> 'the rows collection includes rows only on the current page<br /> 'not 'virtual' rows<br /> For Each row As GridViewRow In gvOne.Rows<br /> Dim price As Decimal = Decimal.Parse(row.Cells(2).Text)<br /> Dim unitsInStock As Integer = Integer.Parse(row.Cells(3).Text)<br /> valueInStock += price * unitsInStock<br /> Next<br /><br /> 'update the footer<br /> Dim footer As GridViewRow = gvOne.FooterRow<br /> 'set teh first cell to span over the entire row<br /> footer.Cells(0).ColumnSpan = 3<br /> footer.Cells(0).HorizontalAlign = HorizontalAlign.Center<br /><br /> 'remove the unneeded cells<br /> footer.Cells.RemoveAt(2)<br /> footer.Cells.RemoveAt(1)<br /><br /> 'add the text<br /> footer.Cells(0).Text = "Total value in stock (on this page): " & valueInStock.ToString("C")<br /> End Sub<br /><hr><br /><br />Partial Class ItemRemovedCallback<br /> Inherits System.Web.UI.Page<br /><br /> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load<br /> If (Not Me.IsPostBack) Then<br /> lblInfo.Text &= "Creating items...<br/>"<br /> Dim itemA As String = "item A"<br /> Dim itemB As String = "item B"<br /><br /> Cache.Insert("itemA", itemA, Nothing, DateTime.Now.AddMinutes(60), TimeSpan.Zero, CacheItemPriority.Default, AddressOf ItemRemovedCallback)<br /> Cache.Insert("itemB", itemB, Nothing, DateTime.Now.AddMinutes(60), TimeSpan.Zero, CacheItemPriority.Default, AddressOf ItemRemovedCallback)<br /> End If<br /> <br /><br /> End Sub<br /><br /> Protected Sub cmdCheck_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCheck.Click<br /> Dim itemList As String = String.Empty<br /> For Each item As DictionaryEntry In Cache<br /> itemList &= item.Key.ToString() & " "<br /> Next item<br /> lblInfo.Text &= "<br />Found: " & itemList & "<br />"<br /> End Sub<br /><br /><br /> Protected Sub cmdRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdRemove.Click<br /> lblInfo.Text &= "<br />Removing itemA.<br />"<br /> Cache.Remove("itemA")<br /> End Sub<br /><br /> Private Sub ItemRemovedCallback(ByVal key As String, ByVal value As Object, ByVal reason As CacheItemRemovedReason)<br /> 'this fires after the request has ended when the item is removed.<br /> 'if either item has been removed, make sure the othe ritem is also removed<br /> If key = "itemA" OrElse key = "itemB" Then<br /> Cache.Remove("itemA")<br /> Cache.Remove("itemB")<br /> End If<br /><br /> End Sub<br /><br />End Class <div style='clear: both;'></div> </div> <div class='post-footer'> <div class='post-footer-line post-footer-line-1'> <span class='post-author vcard'> Posted by <span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'> <meta content='https://www.blogger.com/profile/10483429620186012661' itemprop='url'/> <a class='g-profile' href='https://www.blogger.com/profile/10483429620186012661' rel='author' title='author profile'> <span itemprop='name'>aljensen</span> </a> </span> </span> <span class='post-timestamp'> at <meta content='http://21stcenturymandarin.blogspot.com/2011/11/protected-sub-gvonedataboundbyval.html' itemprop='url'/> <a class='timestamp-link' href='http://21stcenturymandarin.blogspot.com/2011/11/protected-sub-gvonedataboundbyval.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-11-09T12:26:00-08:00'>12:26 PM</abbr></a> </span> <span class='post-comment-link'> <a class='comment-link' href='https://www.blogger.com/comment.g?blogID=1128425782735047114&postID=4776495648797544829' onclick=''> No comments: </a> </span> <span class='post-icons'> <span class='item-control blog-admin pid-2034475012'> <a href='https://www.blogger.com/post-edit.g?blogID=1128425782735047114&postID=4776495648797544829&from=pencil' title='Edit Post'> <img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/> </a> </span> </span> <div class='post-share-buttons goog-inline-block'> </div> </div> <div class='post-footer-line post-footer-line-2'> <span class='post-labels'> </span> </div> <div class='post-footer-line post-footer-line-3'> <span class='post-location'> </span> </div> </div> </div> </div> </div></div> <div class="date-outer"> <h2 class='date-header'><span>Tuesday, November 8, 2011</span></h2> <div class="date-posts"> <div class='post-outer'> <div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'> <meta content='1128425782735047114' itemprop='blogId'/> <meta content='6235120327065710386' itemprop='postId'/> <a name='6235120327065710386'></a> <h3 class='post-title entry-title' itemprop='name'> <a href='http://21stcenturymandarin.blogspot.com/2011/11/tuesday-11811.html'>Tuesday 11.8.11</a> </h3> <div class='post-header'> <div class='post-header-line-1'></div> </div> <div class='post-body entry-content' id='post-body-6235120327065710386' itemprop='description articleBody'> Sub Main()<br /> Dim myChar As Char = "a"c<br /> Console.WriteLine("Char.IsDigit('a') {0}", Char.IsDigit(myChar))<br /> Console.WriteLine("Char.IsLetter('a') {0}", Char.IsLetter(myChar))<br /> Console.WriteLine("Char.IsWhiteSpace('Hello There', 5): {0}", Char.IsWhiteSpace("Hello There", 5))<br /> Console.WriteLine("Char.IsWhiteSpace('Hello There', 6): {0}", Char.IsWhiteSpace("Hello There", 6))<br /> Console.WriteLine("Char.IsPunctuation('?'): {0}", Char.IsPunctuation("?"c))<br /><br /> Dim c As Char = Char.Parse("w")<br /> Console.WriteLine("Value of myChar: {0}", c)<br /><br /> End Sub<br /><hr><br />Module Module1<br /><br /> Sub Main()<br /> Console.WriteLine("****** Fun With Strings *******")<br /> Dim firstName As String = "June"<br /><br /> Console.WriteLine("Value of firstName: {0}", firstName)<br /> Console.WriteLine("firstName has {0} characters.", firstName.Length)<br /> Console.WriteLine("firstName in uppercase: {0}", firstName.ToUpper())<br /> Console.WriteLine("firstName in lowercase: {0}", firstName.ToLower())<br /><br /> Dim myValue As Integer = 3456789<br /> Console.WriteLine("Hex value fo myValue is: {0:X}", myValue)<br /> Console.WriteLine("Currency value of myValue is: {0:C}", myValue)<br /> End Sub<br /><br />End Module<br /><hr><br /> Sub Main()<br /> 'Use the StringBuilder<br /> Dim sb As New StringBuilder("***** Fantastic Games ******")<br /> sb.Append(vbLf)<br /> sb.AppendLine("Half Life 2")<br /> sb.AppendLine("Beyond Good and Evil")<br /> sb.AppendLine("Deus Ex 1 and 2")<br /> sb.Append("System Shock")<br /> sb.Replace("2", "Deus Ex: Invisible War")<br /> Console.WriteLine(sb)<br /> Console.WriteLine("Sb has {0} chars.", sb.Length)<br /> End Sub<br /><hr><br />Imports System.Text<br /><br />Module Module1<br /><br /> Sub Main()<br /> 'Accept all defaults for the optional<br /> PrintFormattedMessage("Call One")<br /><br /> 'Provide each optional argument<br /> PrintFormattedMessage("Call Two", True, 5, ConsoleColor.Yellow)<br /><br /> 'Print this message in current case, one time, in gray<br /> PrintFormattedMessage("Call Three", , , ConsoleColor.Gray)<br /><br /> 'same as previously show, but Cleaner!<br /> PrintFormattedMessage("Call Four", textColor:=ConsoleColor.Gray)<br /><br /> End Sub<br /><br /><br /> Sub PrintFormattedMessage(ByVal msg As String, _<br /> Optional ByVal upperCase As Boolean = False, _<br /> Optional ByVal timesToRepeat As Integer = 0, _<br /> Optional ByVal textColor As ConsoleColor = ConsoleColor.Green)<br /> 'store current console foreground color<br /> Dim fGroundColor As ConsoleColor = Console.ForegroundColor<br /> 'set console foreground color<br /> Console.ForegroundColor = textColor<br /> 'print message in correct case x number of times<br /> For i As Integer = 0 To timesToRepeat<br /> Console.WriteLine(msg)<br /> Next<br /> 'reset current foreground color<br /> Console.ForegroundColor = fGroundColor<br /> End Sub<br />End Module<br /><hr><br />Imports System.Text<br /><br />Module Module1<br /><br /> Sub Main()<br /> ArrayOfObjects()<br /><br /> End Sub<br /><br /><br /> Sub ArrayOfObjects()<br /> Console.WriteLine("=> Array of Objects.")<br /> ' an array of objects can be anything at all.<br /> Dim myObjects(3) As Object<br /> myObjects(0) = 10<br /> myObjects(1) = False<br /> myObjects(2) = New DateTime(1969, 3, 24)<br /> myObjects(3) = "Form & Void"<br /><br /> For Each obj As Object In myObjects<br /> 'print the type and value for each item in array.<br /> Console.WriteLine("Type: {0}, Value: {1}", obj.GetType(), obj)<br /> Next<br /> End Sub<br />End Module<br /><hr><br />Imports System.Text<br /><br />Module Module1<br /><br /> Sub Main()<br /> RedimPreserve()<br /> End Sub<br /><br /><br /> Sub RedimPreserve()<br /> Console.WriteLine("=> Redim / Preserve keywords.")<br /> 'Make an array with ten slots<br /> Dim myValues(9) As Integer<br /> For i As Integer = 0 To 9<br /> myValues(i) = i<br /> Next<br /> For i As Integer = 0 To UBound(myValues)<br /> Console.WriteLine("{0} ", myValues(i))<br /> Next<br /><br /> 'ReDim the array with extra slots<br /> ReDim Preserve myValues(15)<br /> For i As Integer = 9 To UBound(myValues)<br /> myValues(i) = i<br /> Next<br /><br /> For i As Integer = 0 To UBound(myValues)<br /> Console.WriteLine("{0} ", myValues(i))<br /> Next<br /><br /> Console.WriteLine()<br /> End Sub<br /><br />End Module<br /><hr><br />Imports System.Text<br /><br />Module Module1<br /><br /> Sub Main()<br /> RedimPreserve()<br /> End Sub<br /><br /><br /> Sub RedimPreserve()<br /> Console.WriteLine("=> Redim / Preserve keywords.")<br /> 'Make an array with ten slots<br /> Dim myValues(9) As Integer<br /> For i As Integer = 0 To 9<br /> myValues(i) = i<br /> Next<br /> For i As Integer = 0 To UBound(myValues)<br /> Console.WriteLine("{0} ", myValues(i))<br /> Next<br /><br /> 'ReDim the array with extra slots<br /> ReDim Preserve myValues(15)<br /> For i As Integer = 9 To UBound(myValues)<br /> myValues(i) = i<br /> Next<br /><br /> For i As Integer = 0 To UBound(myValues)<br /> Console.WriteLine("{0} ", myValues(i))<br /> Next<br /><br /> Console.WriteLine()<br /> End Sub<br /><br />End Module<br /><hr><br />Partial Class Paging<br /> Inherits System.Web.UI.Page<br /><br /> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load<br /> Dim connStr As String = WebConfigurationManager.ConnectionStrings("Northwind").ConnectionString<br /> Dim sqlStr As String = "SELECT [ProductID],[ProductName], [UnitPrice], [UnitsInStock] FROM Products"<br /> Dim ds As New DataSet<br /> Dim SqlAdapter As New SqlDataAdapter(sqlStr, connStr)<br /> SqlAdapter.Fill(ds)<br /><br /> GridView1.DataSource = ds<br /> GridView1.DataBind()<br /><br /> End Sub<br /><br /><br /> Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging<br /> GridView1.PageIndex = e.NewPageIndex<br /> GridView1.DataBind()<br /> End Sub<br />End Class <div style='clear: both;'></div> </div> <div class='post-footer'> <div class='post-footer-line post-footer-line-1'> <span class='post-author vcard'> Posted by <span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'> <meta content='https://www.blogger.com/profile/10483429620186012661' itemprop='url'/> <a class='g-profile' href='https://www.blogger.com/profile/10483429620186012661' rel='author' title='author profile'> <span itemprop='name'>aljensen</span> </a> </span> </span> <span class='post-timestamp'> at <meta content='http://21stcenturymandarin.blogspot.com/2011/11/tuesday-11811.html' itemprop='url'/> <a class='timestamp-link' href='http://21stcenturymandarin.blogspot.com/2011/11/tuesday-11811.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-11-08T14:47:00-08:00'>2:47 PM</abbr></a> </span> <span class='post-comment-link'> <a class='comment-link' href='https://www.blogger.com/comment.g?blogID=1128425782735047114&postID=6235120327065710386' onclick=''> No comments: </a> </span> <span class='post-icons'> <span class='item-control blog-admin pid-2034475012'> <a href='https://www.blogger.com/post-edit.g?blogID=1128425782735047114&postID=6235120327065710386&from=pencil' title='Edit Post'> <img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/> </a> </span> </span> <div class='post-share-buttons goog-inline-block'> </div> </div> <div class='post-footer-line post-footer-line-2'> <span class='post-labels'> </span> </div> <div class='post-footer-line post-footer-line-3'> <span class='post-location'> </span> </div> </div> </div> </div> </div></div> <div class="date-outer"> <h2 class='date-header'><span>Monday, November 7, 2011</span></h2> <div class="date-posts"> <div class='post-outer'> <div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'> <meta content='1128425782735047114' itemprop='blogId'/> <meta content='3820634406387385139' itemprop='postId'/> <a name='3820634406387385139'></a> <h3 class='post-title entry-title' itemprop='name'> <a href='http://21stcenturymandarin.blogspot.com/2011/11/monday-11711.html'>Monday 11.7.11</a> </h3> <div class='post-header'> <div class='post-header-line-1'></div> </div> <div class='post-body entry-content' id='post-body-3820634406387385139' itemprop='description articleBody'> using System;<br />using System.Data;<br />using System.Data.SqlClient;<br /><br />namespace CountRecordsMeetingCriteria<br />{<br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress;" +<br /> "Integrated security=SSPI; Initial Catalog=AdventureWorks;";<br /><br /> //create the connection<br /> SqlConnection connection = new SqlConnection(sqlConnectString);<br /><br /> //build the query to count including criteria<br /> string selectText = "SELECT COUNT(*) FROM Person.Contact " + "WHERE LastName Like 'A%'";<br /><br /> //create the command to count the records<br /> SqlCommand command = new SqlCommand(selectText, connection);<br /> //execute the command, storing the results<br /> connection.Open();<br /> int recordCount = (int)command.ExecuteScalar();<br /> connection.Close();<br /><br /> Console.WriteLine("Person.Contact records starting with 'A' = {0}", recordCount);<br /><br /> Console.WriteLine("\nPress any key to continue.");<br /> Console.ReadKey();<br /> }<br /> }<br />}<br /><hr><br />using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br />using System.Data;<br />using System.Data.SqlClient;<br /><br />namespace DataReaderRowCount<br />{<br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress;" +<br /> "Integrated Security=SSPI; Initial Catalog=AdventureWorks;";<br /><br /> //batch query to retrieve the COUNT of records and all of the records<br /> //in the Person.Contact table as two result sets<br /> string sqlSelect = "SELECT COUNT(*) FROM Person.Contact; " +<br /> "SELECT * FROM Person.Contact;";<br /><br /> //create the connection<br /> using (SqlConnection connection = new SqlConnection(sqlConnectString))<br /> {<br /> //create the command<br /> SqlCommand command = new SqlCommand(sqlSelect, connection);<br /><br /> //create a DataReader on the first result set<br /> connection.Open();<br /> SqlDataReader dr = command.ExecuteReader();<br /><br /> //get and output the record count from the <br /> //SELECT COUNT(*) statement<br /> dr.Read();<br /> Console.WriteLine("Record count, using COUNT(*)={0}", dr.GetInt32(0));<br /><br /> //move to the next result in the batch<br /> dr.NextResult();<br /><br /> int count = 0;<br /> //Iterate over the records in the DataReader<br /> while (dr.Read())<br /> {<br /> count++;<br /> }<br /> Console.WriteLine("Record count, iterating over results = {0}", count);<br /> //close the DataReader.<br /> dr.Close();<br /><br /> //create the stored procedure to use in the DataReader<br /> command = new SqlCommand("Person.GetContacts", connection);<br /> command.CommandType = CommandType.StoredProcedure;<br /> //create the output parameter to return @@ROWCOUNT<br /> command.Parameters.Add("@RowCount", SqlDbType.Int).Direction = ParameterDirection.Output;<br /><br /> //create a dataReader for the result set returned by the stored procedure<br /> dr = command.ExecuteReader();<br /><br /> //process the data in the DataReader<br /><br /> //close the DataReader<br /> dr.Close();<br /> //the output parameter containing the Row count is now available<br /> Console.WriteLine("Record count, using @@ROWCOUNT = {0}", command.Parameters["@RowCount"].Value);<br /> }<br /> Console.WriteLine("\nPress any key to continue.");<br /> Console.ReadKey();<br /> }<br /> }<br />}<br /><hr><br />using System;<br />using System.Data;<br />using System.Data.SqlClient;<br /><br />namespace ExecuteBatchQuery<br />{<br /> class Program<br /> {<br /> static void Main(string[] args)<br /> {<br /> string sqlConnectString = @"Data Source=Alfred-PC\SQLExpress;" + <br /> "Integrated security=SSPI; Initial Catalog=AdventureWorks;";<br /><br /> string sqlSelect = "SELECT TOP 3 * FROM Sales.SalesOrderHeader;" +<br /> "SELECT TOP 3 * FROM Sales.SalesOrderDetail";<br /><br /> int rsNumber;<br /><br /> //SQLbatch using a DataSet<br /> Console.WriteLine("-----DataSet----");<br /><br /> //Fill the DataSet with the result of the batch query<br /> SqlDataAdapter da = new SqlDataAdapter(sqlSelect, sqlConnectString);<br /> DataSet ds = new DataSet();<br /> da.Fill(ds);<br /><br /> rsNumber = 0;<br /> //Iterate over the result sets in the DataTable collection<br /> foreach (DataTable dt in ds.Tables)<br /> {<br /> Console.WriteLine("Result set: {0}", ++rsNumber);<br /> <br /> foreach (DataRow row in dt.Rows)<br /> {<br /> //output the first three fields for each record<br /> Console.WriteLine("{0}, {1}, {2}", row[0], row[1], row[2]);<br /> }<br /> Console.WriteLine(Environment.NewLine);<br /> }<br /><br /> using (SqlConnection connection = new SqlConnection(sqlConnectString))<br /> {<br /> //SQL batch using a DataReader<br /> Console.WriteLine("----DataReader----");<br /><br /> //create the DataReader from the batch query<br /> SqlCommand command = new SqlCommand(sqlSelect, connection);<br /> connection.Open();<br /> SqlDataReader dr = command.ExecuteReader();<br /><br /> rsNumber = 0;<br /> //Iterate over the result sets using the NextResult() method<br /><br /> do<br /> {<br /> Console.WriteLine("Result set: {0}", ++rsNumber);<br /> //Iterate over the rows in the DataReader<br /> while (dr.Read())<br /> {<br /> //output the first three fields for each record<br /> Console.WriteLine("{0}, {1}, {2}", dr[0], dr[1], dr[2]);<br /> }<br /> Console.WriteLine(Environment.NewLine);<br /> } while (dr.NextResult());<br /> }<br /><br /> Console.WriteLine("Press any key to continue.");<br /> Console.ReadKey();<br /> }<br /> }<br />} <div style='clear: both;'></div> </div> <div class='post-footer'> <div class='post-footer-line post-footer-line-1'> <span class='post-author vcard'> Posted by <span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'> <meta content='https://www.blogger.com/profile/10483429620186012661' itemprop='url'/> <a class='g-profile' href='https://www.blogger.com/profile/10483429620186012661' rel='author' title='author profile'> <span itemprop='name'>aljensen</span> </a> </span> </span> <span class='post-timestamp'> at <meta content='http://21stcenturymandarin.blogspot.com/2011/11/monday-11711.html' itemprop='url'/> <a class='timestamp-link' href='http://21stcenturymandarin.blogspot.com/2011/11/monday-11711.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-11-07T10:52:00-08:00'>10:52 AM</abbr></a> </span> <span class='post-comment-link'> <a class='comment-link' href='https://www.blogger.com/comment.g?blogID=1128425782735047114&postID=3820634406387385139' onclick=''> No comments: </a> </span> <span class='post-icons'> <span class='item-control blog-admin pid-2034475012'> <a href='https://www.blogger.com/post-edit.g?blogID=1128425782735047114&postID=3820634406387385139&from=pencil' title='Edit Post'> <img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/> </a> </span> </span> <div class='post-share-buttons goog-inline-block'> </div> </div> <div class='post-footer-line post-footer-line-2'> <span class='post-labels'> </span> </div> <div class='post-footer-line post-footer-line-3'> <span class='post-location'> </span> </div> </div> </div> </div> </div></div> <div class="date-outer"> <h2 class='date-header'><span>Friday, November 4, 2011</span></h2> <div class="date-posts"> <div class='post-outer'> <div class='post hentry uncustomized-post-template' itemprop='blogPost' itemscope='itemscope' itemtype='http://schema.org/BlogPosting'> <meta content='1128425782735047114' itemprop='blogId'/> <meta content='525981606497183528' itemprop='postId'/> <a name='525981606497183528'></a> <h3 class='post-title entry-title' itemprop='name'> <a href='http://21stcenturymandarin.blogspot.com/2011/11/friday-11411.html'>Friday 11.4.11</a> </h3> <div class='post-header'> <div class='post-header-line-1'></div> </div> <div class='post-body entry-content' id='post-body-525981606497183528' itemprop='description articleBody'> Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated<br /> If e.Row.RowType = DataControlRowType.DataRow Then<br /> 'get the title of the courtesy for the item that's being created<br /> Dim title As String = CStr(DataBinder.Eval(e.Row.DataItem, "TitleOfCourtesy"))<br /> 'if the title of courtesy is "Ms.", "Mrs." or "Mr." change the item's colors<br /> If title = "Ms." OrElse title = "Mrs." Then<br /> e.Row.BackColor = System.Drawing.Color.LightPink<br /> e.Row.ForeColor = System.Drawing.Color.Maroon<br /> ElseIf title = "Mr." Then<br /> e.Row.BackColor = System.Drawing.Color.LightCyan<br /> e.Row.ForeColor = System.Drawing.Color.DarkBlue<br /> End If<br /> End If<br /> End Sub<br /><hr><br /><br /> Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged<br /> Dim index As Integer = GridView1.SelectedIndex<br /> 'you can retrieve teh key field from the SelectedDataKey property<br /> Dim ID As Integer = CInt(GridView1.SelectedDataKey.Values("EmployeeID"))<br /> 'you can retrieve other data directly from teh Cells colelction<br /> 'as long as you know the column offset<br /> Dim firstName As String = GridView1.SelectedRow.Cells(2).Text<br /> Dim lastName As String = GridView1.SelectedRow.Cells(3).Text<br /><br /> lblRegionCaption.Text = "Regions that " & firstName & " " & lastName & " (employee " & ID.ToString() & ") is responsible For: "<br /><br /> Dim connectionString As String = WebConfigurationManager.ConnectionStrings("Northwind").ConnectionString<br /> Dim con As New SqlConnection(connectionString)<br /><br /> Dim ParamCommand As SqlCommand = New SqlCommand()<br /> ParamCommand.Connection = con<br /> ParamCommand.CommandText = "SELECT Employees.EmployeeID, Territories.TerritoryID, Territories.TerritoryDescription FROM Employees INNER JOIN EmployeeTerritories ON Employees.EmployeeID = EmployeeTerritories.EmployeeID INNER JOIN Territories ON EmployeeTerritories.TerritoryID = Territories.TerritoryID WHERE (Employees.EmployeeID = @EmployeeID)"<br /> ParamCommand.Parameters.Add("@EmployeeID", SqlDbType.Int).Value = GridView1.SelectedDataKey.Values("EmployeeID")<br /><br /> con.Open()<br /> Dim dataAdapter As SqlDataAdapter = New SqlDataAdapter(ParamCommand)<br /> Dim ds As New DataSet()<br /> dataAdapter.Fill(ds, "Territories")<br /> GridView2.DataSource = ds<br /> GridView2.DataBind()<br /> End Sub <div style='clear: both;'></div> </div> <div class='post-footer'> <div class='post-footer-line post-footer-line-1'> <span class='post-author vcard'> Posted by <span class='fn' itemprop='author' itemscope='itemscope' itemtype='http://schema.org/Person'> <meta content='https://www.blogger.com/profile/10483429620186012661' itemprop='url'/> <a class='g-profile' href='https://www.blogger.com/profile/10483429620186012661' rel='author' title='author profile'> <span itemprop='name'>aljensen</span> </a> </span> </span> <span class='post-timestamp'> at <meta content='http://21stcenturymandarin.blogspot.com/2011/11/friday-11411.html' itemprop='url'/> <a class='timestamp-link' href='http://21stcenturymandarin.blogspot.com/2011/11/friday-11411.html' rel='bookmark' title='permanent link'><abbr class='published' itemprop='datePublished' title='2011-11-04T18:16:00-07:00'>6:16 PM</abbr></a> </span> <span class='post-comment-link'> <a class='comment-link' href='https://www.blogger.com/comment.g?blogID=1128425782735047114&postID=525981606497183528' onclick=''> No comments: </a> </span> <span class='post-icons'> <span class='item-control blog-admin pid-2034475012'> <a href='https://www.blogger.com/post-edit.g?blogID=1128425782735047114&postID=525981606497183528&from=pencil' title='Edit Post'> <img alt='' class='icon-action' height='18' src='https://resources.blogblog.com/img/icon18_edit_allbkg.gif' width='18'/> </a> </span> </span> <div class='post-share-buttons goog-inline-block'> </div> </div> <div class='post-footer-line post-footer-line-2'> <span class='post-labels'> </span> </div> <div class='post-footer-line post-footer-line-3'> <span class='post-location'> </span> </div> </div> </div> </div> </div></div> </div> <div class='blog-pager' id='blog-pager'> <span id='blog-pager-newer-link'> <a class='blog-pager-newer-link' href='http://21stcenturymandarin.blogspot.com/search?updated-max=2011-12-13T16:10:00-08:00&max-results=7&reverse-paginate=true' id='Blog1_blog-pager-newer-link' title='Newer Posts'>Newer Posts</a> </span> <span id='blog-pager-older-link'> <a class='blog-pager-older-link' href='http://21stcenturymandarin.blogspot.com/search?updated-max=2011-11-04T18:16:00-07:00&max-results=7' id='Blog1_blog-pager-older-link' title='Older Posts'>Older Posts</a> </span> <a class='home-link' href='http://21stcenturymandarin.blogspot.com/'>Home</a> </div> <div class='clear'></div> <div class='blog-feeds'> <div class='feed-links'> Subscribe to: <a class='feed-link' href='http://21stcenturymandarin.blogspot.com/feeds/posts/default' target='_blank' type='application/atom+xml'>Posts (Atom)</a> </div> </div> </div></div> </div> <div id='sidebar-wrapper'> <div class='sidebar section' id='sidebar'><div class='widget BlogSearch' data-version='1' id='BlogSearch1'> <h2 class='title'>Search This Blog</h2> <div class='widget-content'> <div id='BlogSearch1_form'> <form action='http://21stcenturymandarin.blogspot.com/search' class='gsc-search-box' target='_top'> <table cellpadding='0' cellspacing='0' class='gsc-search-box'> <tbody> <tr> <td class='gsc-input'> <input autocomplete='off' class='gsc-input' name='q' size='10' title='search' type='text' value=''/> </td> <td class='gsc-search-button'> <input class='gsc-search-button' title='search' type='submit' value='Search'/> </td> </tr> </tbody> </table> </form> </div> </div> <div class='clear'></div> </div><div class='widget PageList' data-version='1' id='PageList1'> <h2>Pages</h2> <div class='widget-content'> <ul> <li> <a href='http://21stcenturymandarin.blogspot.com/'>Home</a> </li> <li> <a href='http://21stcenturymandarin.blogspot.com/p/projects.html'>Projects</a> </li> </ul> <div class='clear'></div> </div> </div><div class='widget BlogArchive' data-version='1' id='BlogArchive2'> <h2>Blog Archive</h2> <div class='widget-content'> <div id='ArchiveList'> <div id='BlogArchive2_ArchiveList'> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2012/'> 2012 </a> <span class='post-count' dir='ltr'>(2)</span> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2012/01/'> January </a> <span class='post-count' dir='ltr'>(2)</span> </li> </ul> </li> </ul> <ul class='hierarchy'> <li class='archivedate expanded'> <a class='toggle' href='javascript:void(0)'> <span class='zippy toggle-open'> ▼  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/'> 2011 </a> <span class='post-count' dir='ltr'>(165)</span> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/12/'> December </a> <span class='post-count' dir='ltr'>(17)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate expanded'> <a class='toggle' href='javascript:void(0)'> <span class='zippy toggle-open'> ▼  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/11/'> November </a> <span class='post-count' dir='ltr'>(18)</span> <ul class='posts'> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/tuesday-112211.html'>Tuesday 11.22.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/monday-112111.html'>Monday 11/21/11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/friday-111811.html'>Friday 11.18.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/friday-111711.html'>Friday 11.17.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/wednesday-111611.html'>Wednesday 11.16.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/tuesday-111511.html'>Tuesday 11.15.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/monday-111411.html'>Monday 11.14.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/saturday-111211.html'>Saturday 11.12.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/friday-111111_4291.html'>Friday 11.11.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/friday-111111_11.html'>Friday 11.11.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/friday-111111.html'>Friday 11.11.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/thursday-111011.html'>Thursday 11.10.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/protected-sub-gvonedataboundbyval.html'>Protected Sub gvONe_DataBound(ByVal sender As Obje...</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/tuesday-11811.html'>Tuesday 11.8.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/monday-11711.html'>Monday 11.7.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/friday-11411.html'>Friday 11.4.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/wednesday-11211.html'>Wednesday 11.2.11</a></li> <li><a href='http://21stcenturymandarin.blogspot.com/2011/11/tuesday-11111.html'>Tuesday 11.1.11</a></li> </ul> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/10/'> October </a> <span class='post-count' dir='ltr'>(17)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/09/'> September </a> <span class='post-count' dir='ltr'>(19)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/08/'> August </a> <span class='post-count' dir='ltr'>(20)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/07/'> July </a> <span class='post-count' dir='ltr'>(11)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/06/'> June </a> <span class='post-count' dir='ltr'>(8)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/05/'> May </a> <span class='post-count' dir='ltr'>(3)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/04/'> April </a> <span class='post-count' dir='ltr'>(7)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/03/'> March </a> <span class='post-count' dir='ltr'>(11)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/02/'> February </a> <span class='post-count' dir='ltr'>(13)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2011/01/'> January </a> <span class='post-count' dir='ltr'>(21)</span> </li> </ul> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2010/'> 2010 </a> <span class='post-count' dir='ltr'>(84)</span> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2010/12/'> December </a> <span class='post-count' dir='ltr'>(20)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2010/11/'> November </a> <span class='post-count' dir='ltr'>(17)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2010/10/'> October </a> <span class='post-count' dir='ltr'>(15)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2010/09/'> September </a> <span class='post-count' dir='ltr'>(16)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2010/08/'> August </a> <span class='post-count' dir='ltr'>(13)</span> </li> </ul> <ul class='hierarchy'> <li class='archivedate collapsed'> <a class='toggle' href='javascript:void(0)'> <span class='zippy'> ►  </span> </a> <a class='post-count-link' href='http://21stcenturymandarin.blogspot.com/2010/07/'> July </a> <span class='post-count' dir='ltr'>(3)</span> </li> </ul> </li> </ul> </div> </div> <div class='clear'></div> </div> </div><div class='widget Profile' data-version='1' id='Profile2'> <h2>About Me</h2> <div class='widget-content'> <a href='https://www.blogger.com/profile/10483429620186012661'><img alt='My photo' class='profile-img' height='80' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjs9FSUwUjHI5Vy48ELYdCBgreQIZvijOEA0z9gV1S9Vqx1DnekpRnZIL5iu4AvsJhgpcnEOQfGAq4DuH3Bmpvqkd3ywLa01ZNUJCRJ5J1vHNlGxVDH4yCmkHXMKpJrIj8/s220/shin2.jpg' width='69'/></a> <dl class='profile-datablock'> <dt class='profile-data'> <a class='profile-name-link g-profile' href='https://www.blogger.com/profile/10483429620186012661' rel='author' style='background-image: url(//www.blogger.com/img/logo-16.png);'> aljensen </a> </dt> </dl> <a class='profile-link' href='https://www.blogger.com/profile/10483429620186012661' rel='author'>View my complete profile</a> <div class='clear'></div> </div> </div></div> </div> <!-- spacer for skins that want sidebar and main to be the same height--> <div class='clear'> </div> </div> <!-- end content-wrapper --> <div id='footer-wrapper'> <div class='footer no-items section' id='footer'></div> </div> </div></div> <!-- end outer-wrapper --> <script type="text/javascript" src="https://www.blogger.com/static/v1/widgets/4290687098-widgets.js"></script> <script type='text/javascript'> window['__wavt'] = 'AOuZoY5DkA6HghyTp6dAFeRAcGQQyGdpcA:1714901322953';_WidgetManager._Init('//www.blogger.com/rearrange?blogID\x3d1128425782735047114','//21stcenturymandarin.blogspot.com/2011/11/','1128425782735047114'); _WidgetManager._SetDataContext([{'name': 'blog', 'data': {'blogId': '1128425782735047114', 'title': '21st Century Mandarin', 'url': 'http://21stcenturymandarin.blogspot.com/2011/11/', 'canonicalUrl': 'http://21stcenturymandarin.blogspot.com/2011/11/', 'homepageUrl': 'http://21stcenturymandarin.blogspot.com/', 'searchUrl': 'http://21stcenturymandarin.blogspot.com/search', 'canonicalHomepageUrl': 'http://21stcenturymandarin.blogspot.com/', 'blogspotFaviconUrl': 'http://21stcenturymandarin.blogspot.com/favicon.ico', 'bloggerUrl': 'https://www.blogger.com', 'hasCustomDomain': false, 'httpsEnabled': true, 'enabledCommentProfileImages': true, 'gPlusViewType': 'FILTERED_POSTMOD', 'adultContent': false, 'analyticsAccountNumber': '', 'encoding': 'UTF-8', 'locale': 'en', 'localeUnderscoreDelimited': 'en', 'languageDirection': 'ltr', 'isPrivate': false, 'isMobile': false, 'isMobileRequest': false, 'mobileClass': '', 'isPrivateBlog': false, 'isDynamicViewsAvailable': true, 'feedLinks': '\x3clink rel\x3d\x22alternate\x22 type\x3d\x22application/atom+xml\x22 title\x3d\x2221st Century Mandarin - Atom\x22 href\x3d\x22http://21stcenturymandarin.blogspot.com/feeds/posts/default\x22 /\x3e\n\x3clink rel\x3d\x22alternate\x22 type\x3d\x22application/rss+xml\x22 title\x3d\x2221st Century Mandarin - RSS\x22 href\x3d\x22http://21stcenturymandarin.blogspot.com/feeds/posts/default?alt\x3drss\x22 /\x3e\n\x3clink rel\x3d\x22service.post\x22 type\x3d\x22application/atom+xml\x22 title\x3d\x2221st Century Mandarin - Atom\x22 href\x3d\x22https://www.blogger.com/feeds/1128425782735047114/posts/default\x22 /\x3e\n', 'meTag': '', 'adsenseHostId': 'ca-host-pub-1556223355139109', 'adsenseHasAds': false, 'adsenseAutoAds': false, 'boqCommentIframeForm': true, 'loginRedirectParam': '', 'view': '', 'dynamicViewsCommentsSrc': '//www.blogblog.com/dynamicviews/4224c15c4e7c9321/js/comments.js', 'dynamicViewsScriptSrc': '//www.blogblog.com/dynamicviews/a26ecadc30bb77e6', 'plusOneApiSrc': 'https://apis.google.com/js/platform.js', 'disableGComments': true, 'interstitialAccepted': false, 'sharing': {'platforms': [{'name': 'Get link', 'key': 'link', 'shareMessage': 'Get link', 'target': ''}, {'name': 'Facebook', 'key': 'facebook', 'shareMessage': 'Share to Facebook', 'target': 'facebook'}, {'name': 'BlogThis!', 'key': 'blogThis', 'shareMessage': 'BlogThis!', 'target': 'blog'}, {'name': 'Twitter', 'key': 'twitter', 'shareMessage': 'Share to Twitter', 'target': 'twitter'}, {'name': 'Pinterest', 'key': 'pinterest', 'shareMessage': 'Share to Pinterest', 'target': 'pinterest'}, {'name': 'Email', 'key': 'email', 'shareMessage': 'Email', 'target': 'email'}], 'disableGooglePlus': true, 'googlePlusShareButtonWidth': 0, 'googlePlusBootstrap': '\x3cscript type\x3d\x22text/javascript\x22\x3ewindow.___gcfg \x3d {\x27lang\x27: \x27en\x27};\x3c/script\x3e'}, 'hasCustomJumpLinkMessage': false, 'jumpLinkMessage': 'Read more', 'pageType': 'archive', 'pageName': 'November 2011', 'pageTitle': '21st Century Mandarin: November 2011'}}, {'name': 'features', 'data': {}}, {'name': 'messages', 'data': {'edit': 'Edit', 'linkCopiedToClipboard': 'Link copied to clipboard!', 'ok': 'Ok', 'postLink': 'Post Link'}}, {'name': 'template', 'data': {'isResponsive': false, 'isAlternateRendering': false, 'isCustom': false}}, {'name': 'view', 'data': {'classic': {'name': 'classic', 'url': '?view\x3dclassic'}, 'flipcard': {'name': 'flipcard', 'url': '?view\x3dflipcard'}, 'magazine': {'name': 'magazine', 'url': '?view\x3dmagazine'}, 'mosaic': {'name': 'mosaic', 'url': '?view\x3dmosaic'}, 'sidebar': {'name': 'sidebar', 'url': '?view\x3dsidebar'}, 'snapshot': {'name': 'snapshot', 'url': '?view\x3dsnapshot'}, 'timeslide': {'name': 'timeslide', 'url': '?view\x3dtimeslide'}, 'isMobile': false, 'title': '21st Century Mandarin', 'description': 'Mainly about the process of programming as both work and study, starting from the ground up.', 'url': 'http://21stcenturymandarin.blogspot.com/2011/11/', 'type': 'feed', 'isSingleItem': false, 'isMultipleItems': true, 'isError': false, 'isPage': false, 'isPost': false, 'isHomepage': false, 'isArchive': true, 'isLabelSearch': false, 'archive': {'year': 2011, 'month': 11, 'rangeMessage': 'Showing posts from November, 2011'}}}]); _WidgetManager._RegisterWidget('_NavbarView', new _WidgetInfo('Navbar1', 'navbar', document.getElementById('Navbar1'), {}, 'displayModeFull')); _WidgetManager._RegisterWidget('_HeaderView', new _WidgetInfo('Header1', 'header', document.getElementById('Header1'), {}, 'displayModeFull')); _WidgetManager._RegisterWidget('_BlogView', new _WidgetInfo('Blog1', 'main', document.getElementById('Blog1'), {'cmtInteractionsEnabled': false, 'lightboxEnabled': true, 'lightboxModuleUrl': 'https://www.blogger.com/static/v1/jsbin/1666805145-lbx.js', 'lightboxCssUrl': 'https://www.blogger.com/static/v1/v-css/13464135-lightbox_bundle.css'}, 'displayModeFull')); _WidgetManager._RegisterWidget('_BlogSearchView', new _WidgetInfo('BlogSearch1', 'sidebar', document.getElementById('BlogSearch1'), {}, 'displayModeFull')); _WidgetManager._RegisterWidget('_PageListView', new _WidgetInfo('PageList1', 'sidebar', document.getElementById('PageList1'), {'title': 'Pages', 'links': [{'isCurrentPage': false, 'href': 'http://21stcenturymandarin.blogspot.com/', 'title': 'Home'}, {'isCurrentPage': false, 'href': 'http://21stcenturymandarin.blogspot.com/p/projects.html', 'id': '7060201047768315160', 'title': 'Projects'}], 'mobile': false, 'showPlaceholder': true, 'hasCurrentPage': false}, 'displayModeFull')); _WidgetManager._RegisterWidget('_BlogArchiveView', new _WidgetInfo('BlogArchive2', 'sidebar', document.getElementById('BlogArchive2'), {'languageDirection': 'ltr', 'loadingMessage': 'Loading\x26hellip;'}, 'displayModeFull')); _WidgetManager._RegisterWidget('_ProfileView', new _WidgetInfo('Profile2', 'sidebar', document.getElementById('Profile2'), {}, 'displayModeFull')); </script> </body> </html>