You are on page 1of 200

2008

ProgrammingVisualBasic2008

Mhm76

2008
25
2008
.


.
" "2008
.
2005


.

. .
mhm76 . .

mhm76

The .NET Object.


).
(.
. Objects and Data.
:
9 data .
9 data
.
9 data .
9 data
)( ) ( .
.data .
featuresthe ability datareal .
High-level programming languages
.
assembly memory address
. )(procedural
. variables . ) LISP List
Processing ( Lots of Irritating Silly Parentheses list set .
. object
.
) ( ) ( OOP languages
. .
)( real-world )(.
fields properties
. : method .
.members .
: .
: .
) (. :
.
.
)( ) (.
Objects and Interfaces
.interface .
.
. )
( .
.
) (Objects and Instances
.
. . )
( class .
instances . )( .OOP
.
. :
: listbox : .
The Parts of the .NET Framework
.
(ALT) three-letter acronym .
The Common Language Runtime
) Common Language Runtime (CLR
managed . CLR CLR
1

mhm76

.management CLR manage


. manage
. .managed code
(ActiveX) COM . unmanaged code
. .
. .
. . .
TSA . LAX
. CLR
.
.
. . ) (
)Microsoft Intermediate Language MSIL (IL
assembly language .
! Hello, World : Main

.
(

Module Module1
)(Sub Main
)"Console.WriteLine("hell world
)(Console.Read
End Sub
End Module
MSIL Main )

.method public static void Main( ) cil managed


{
)(.entrypoint
.custom instance void [mscorlib]System.
) STAThreadAttribute::.ctor( ) = ( 01 00 00 00
)// Code size 11 (0xb
).maxstack(8
)"!IL_0000: ldstr("Hello, World
IL_0005: call
)void [mscorlib]System.Console::WriteLine(string
)(IL_000a: ret
} // end of method Module1::Main

.
. CLR
IL . IL .
IL . IL
. IL .

The Common Language Specification


. .
) . Common Language Specification (CLS CLS
. CLS-compliant

.
. .

The Common Type System


CLR
. ) Common Type System (CTS
. : .
object .
CTS . : value types
. 32 integer 32-bit
. : .reference types
2

mhm76

.
.
hindrances
) . core
( .
.
.classes.
.
structures, .
/ . structure skeletons
.
) (signature events )
( ! .Get to work now Modules
. Enumerations
.
) class structure interface delegate
module (enumeration
.types. :
. type .
. : CTS
) . (data types
user-defined types, .type.
Type . user-defined types
type classes interfaces

enumerations . . type
.
.
nested . . access levels
.
. access
) ( ) private ( .
.

.NET Class Libraries


. 17 : 1

0 . 1 CPU 0 1
1s 0s . 0s 1s .
3.14 3 .
0 1 .award-winning
1 libraries .
.
.
.
2 2 . 4

class libraries . ) (
.
: ) Base Class Library (BCL FrameworkClass Library
) .(FCL .
. Linux

. ) !(
.
. . namespaces
. node .
) . (.
. . System
) ( .
3

mhm76

Windows based web-based Windows-


specific . web-specific System Windows . Web
Windows Forms
. Form .
Form System.Windows.Forms.Form :
. System.
" " System
Microsoft.VisualBasic " " Microsoft
top-level . Windows
WindowsApplication1 Form1 :
WindowsApplication1.Form1
second-class .System
: WindowsApplication1 System Microsoft
.
. System WindowsApplication1 System.MySuperApp. Form1:
System.MySuperApp.Form1

. . Microsoft-supplied
System . System
) system ( . .
:
CompanyName.ApplicationName.ClassName
.
.
.
. :
.
2008 3.5
.
.

Assemblies and Manifests


" " . 99.9 % ) an .exe
(file ) . (a .dll file
. . manifest single-file
manifest : .

. CLR . strong
name . .
. .

.
) .Global Assembly Cache (GAC
GAC . . GAC

Metadata and Attributes


. m .metadata
:
.
.pre-.NET .

.
. attributes ID .
.
. .
: ObsoleteAttribute
4

mhm76


) .
out-of-date ( .
) ><(:
Class MyClassWithOldMembers
)(<ObsoleteAttribute()> Sub DoSomeWork
End Sub
End Class
) (MyClassWithOldMembers ) (DoSomeWork

. .ObsoleteAttribute . Attribute
:
Class MyClassWithOldMembers
)(<Obsolete()> Sub DoSomeWork
End Sub
End Class

> <ObsoleteAttribute . DoSomeWork



ObsoleteAttribute :
!DoSomeWork Procedure: Obsolete, don't use it

. .
form-editing
) (
)Properties (.

Button Properties .
Button Properties
. .

Versioning
.
M one-up
improved . M
1.0 . M
1.0 . M )
(2.0
. .
.
.
. versioning
.
. GAC
side-by-side .deployment .
.

From Source Code to EXE


5

mhm76

.
) (:

1 ) (a .
) . (.vb )
(.
2 ) . (b manifest
.metadata MSIL ready-to-execute
. decompiled
) ( ) ildasm.exe Disassembler
( .
) ( obfuscator
.
3 ) (c . ) (1
(2) : ClickOnce ) (3 xcopy
. .NET runtime ) (d
.
4 ) . (e just-in-
(JIT) time . .
.

: .

Mhm76

Introducing Visual Basic


The Basics of Logic and Data

.
. ) ( pseudocode )(
( ) (sketch ) (:
1 ) ( .
2
.
3 .
4 :
5
6 .
7 .
8 ] [
9 .
: . :
) (:
)"originalText = InputBox("Enter text to reverse.
If (Len(originalText) = 0) Then Return
"" = finalText
)"" >< Do While (originalText
)oneCharacter = Right(originalText, 1
finalText &= oneCharacter
_ originalText = Left(originalText,
)Len(originalText) - 1
Loop
MsgBox("The reverse is: " & finalText)

1:
2:
3:
4:
5:
6:
7:
8:
9:

source code . :
step-by-step . statements
. space-underscore
7 .
.logical line ) If Do
]=[( .
.
top-to-bottom Do While...Loop 4 8 .
flow control ) ( )
( ) ( .
variables . :
finalText oneCharacter originalText ) ( .
) (CTS : )text
( )numbers ( )dates (
)Booleans ( . .
. assignment.
( =) assignment operator .
" finalText = " 3 )""( .finalText =&
6 .
function calls .
return .
arguments
. Right . 5
rightmost . :
. )Right(originalText, 1
) (1 .originalText

1

: .

Mhm76

:
.
. 2
:
' Replacing --> If (Len(originalText) = 0) Then Return
)lengthOfText = Len(originalText
If (lengthOfText = 0) Then Return

.Procedures Procedures
.functions . :
. MsgBox 9 MsgBox ) .
.
.

string-reversal : StrReverse
)"originalText = InputBox("Enter text to reverse.
If (Len(originalText) = 0) Then Return
)finalText = StrReverse(originalText
)MsgBox("The reverse is: " & finalText

: .
intrinsic functions .
Microsoft.VisualBasic.
.

Data Types and Variables


: ) (
. .
.Common Language Runtime
.
.
:


content .type : abc,
5 . .
nullable ) ( .
. .
: .

Literals
.
MsgBox . MsgBox("The answer is " &" 42) : The " literal string
" answer is ) . 42 "&" (.
. )" ("The answer is 42
.
. String literals .quote marks
"This is ""literally"" an example." :


2

: .

Mhm76

String literals 2 :
63 . character
literal : .
c . A "A"c :
. ) (
number signs
. Visual Studio
#7/4/1776#:
floating-point core
. 11 110300
. 27 . 3.1415926535
. 27 . 27
" "decimal, 27@:(@) at
)@( . . Boolean
: .
. Booleans .
. love .
.
True .False True
.False .Boolean values ) (0
) 1- .( everything else

Variables
. .

.
.
Variables : .
. .
:
Dim response As String
"response = "A
)"!'MsgBox("Give me an 'A
)MsgBox(response
)"!'MsgBox("Give me another 'A
)MsgBox(response
)"?MsgBox("What's that spell
)"response = StrDup(2, "A

)MsgBox(response

1:
2:
3:
4:
5:
6:
7:

8:

response ) A : (1 ) AA . (7
: 3 A 5 . )( :
.response 7 StrDup two-character
AA . response . two-step
declare
assign . Dim :declaration name
type . syntax .
Dim response As String

response String . = :
"response = "The answer

.
:
"Dim response As String = "The answer

: . Dim :
Dim question As String
Dim answer As String

:
Dim question As String, answer As String

. Dim

Value Types and Reference Types



3

: .

Mhm76

: )( .
Strings . value types "" reference types "
.
. .
Nothing . :Nothing
default ) ( . "
"nullable Nothing " "
. nullable.

Data Types
. data types
. . System
.Object O.
. System.Object :

. System.Object. : .
"" . :

. . ) (
.
1 . 2 .Visual Basic data types
VB
Boolean

NET
Boolean

Byte

Byte

Char

Char

Description

True . False
: 0 .
0 1 .
)8 (
.255
.
Char .

2 ) 16(

.
0
65,535 .
Date

DateTime

Decimal

Decimal

Double

Double

Int32Integer

11 31
9999 . :
.
" " 11
. 100 ) (.
Decimal .
79 27
) 79 27( 29
.
29
79 27
. )
( 9.7 27 .
29
. 6.0
. Currency
Double
. 324 4.94 10 1.798 10 +308
.
giganto-number )(
.
0.00000000000005434 .
.
Integer 4 ) 32( .

: .

Mhm76

2,147,483,648 . 2,147,483,647

Long . 6.0
Long :Integer 8 ) 64

Int64
Long
( .
9,223,372,036,854,775,808 . 9,223,372,036,854,775,807
6.0
.
.
Object Object
: .
.
SByte 8)single-byte(
SByte
SByte
128 . 127
Byte .
Short 2 ) 16 ( .
Int16Short
32,768 32,767
Short
Integer .6.0
Single Double .
Single
Single
45 1.4 10 3.4 10 +38
. Double
Single .
2
String
String
. 2 )16 (

.
UInteger 4 )32 (
UInt32
UInteger
0 . 4,294,967,295
Integer .

8ULong )64(
UInt64
ULong
0 . 18,446,744,073,709,551,615
Long .
2UShort )16(
UInt16UShort
0 . 65,535
Short .

.
. Integer .System.Int32 32

.
Object String . System.ValueType
) . (System.Object SByte UInteger
UShort ULong 2005
System .
" ." CLS-compliant
. .

Advanced Declaration

.
declaration
: .instantiation :
Dim defaultValue As Integer
Dim nonDefaultValue As Integer = 5
Dim defaultReference As Object

: ) ( Integers ) .( Object
.
.
Dim defaultValue As Integer = 0

: .

Mhm76
Dim nonDefaultValue As Integer = 5
Dim defaultReference As Object = Nothing

. Dim defaultValue
. defaultReference
. Nothing
. .
:New
Dim defaultReference As Object = New Object

defaultReference : defaultReference
System.Object . .
initialization .
. default constructor
: .
. .Strings
blank :zerolength
Dim worldsMostBoringString As String = New String

:
"" = Dim worldsMostBoringString As String

Strings . String literals


:String )( String .System.String
. ) . ( .
) ( .
25 . M :
)Dim mmGood As String = New String("M"c, 25

As New
) ( :
)Dim mmGood As New String("M"c, 25

:
Dim mmGood As String
)mmGood = New String("M"c, 25

Constants

. Constants :
never-changing .
: Dim
Const
Const SpeedOfLight As Integer = 186000

= .
:
)MsgBox("Lightspeed in miles/second: " & SpeedOfLight

Local Declaration and Fields


. .
: )( .
. ) local variables
(constants short-lived
. ) ( . fields
.
. Dim Dim
. ) ( ) Private

( ) Public ( :
Private ForInClassUseOnly As Integer

. .

Comments

) ( human-language .
Comments .
" " :

6

: .

Mhm76
' ----- This is a standalone comment, on a line by itself.
Dim counter As Integer ' This is a trailing comment.
!MsgBox("The counter starts at " & _ ' INVALID COMMENT HERE
counter) ' But this one is valid.

)( .
. .
)"MsgBox("No 'comments' in this text.

.
) REM " (" REMark

Option Statements
default assignment
. declaration . :
brandNewValue = 5

Dim brandNewValue
.Object ! .
.
)( auto-declared
:
brandNewValue = 5
MsgBox(brandNewVlaue

5

Option . :
: Option Explicit On

) Dim ( . On Off
.
: Option Strict On

. 64Long
32Integer .
.
) Integer Long
( . Option Strict On .
explicit . .
On Off : .
: Option Infer On
2008 .
. On.
:Option Compare Binary and Option Compare Text
Option Compare .
Binary case-sensitive Text .
: .
:
Option Explicit On
Option Strict On

.
Project .Properties Compile
:
Option compare Option strict, Option explicit ) Option infer (:

: .

Mhm76

Basic Operators
: .

.
)=( . .
) ( : . :
fiveSquared = 25

25 . fiveSquared binary operators


: . .
:
seven = 3 + 4

seven = 7

)=( . unary operator .


:
negativeSeven = -7

+
+
_
_
*
/
\
Mod
^
&
And
AndAlso
Or
OrElse
Not
Xor
<<
>>

=
<
=<
>
=>
><
Like
Is

.
.
.

.
.
.
.
)( ) ( .
.
True .True
And . False
True .True
Or .True
.
"" True .True
.
.
equal-to True equal .
less-than True less than .
less-than-or-equal-to True
. less than or equal to
greater-than True . greater than
greater-than-or-equal-to True
". greater than or equal to
not-equal-to True . not equal to
.
.

: .
IsNot

Mhm76

Nothing .
not-equal-to .Is

.
. .
)circleArea = pi * (radius ^ 2

* .

Using Functions and Subroutines


. " "
:
. Visual Basic :
:Subroutines
subprocedures .
. argument list
. .
: Functions
: .
.
: Properties
. .

.
.
.
.methods .
. .
ID :startDate

)DoSomeWork(customerID, startDate

.
optional arguments .
.overloaded .
.
. :

Dim balanceDue As Boolean
balanceDue = HasOutstandingBalance(customerID)

. .
MsgBox on-screen . OK )
( .
)"MsgBox("Go ahead, click the OK button.

:
)whichButton = MsgBox("Click Yes or No.", MsgBoxStyle.YesNo

whichButton MsgBoxResult.Yes MsgBoxResult.No


.MsgBox

Conditions
.
.

If
. If " " .
" $20 " If
:
If (hadAHammer = True) Then
)DoHammer(inTheMorning, allOverThisLand
)DoHammer(inTheEvening, allOverThisLand
ElseIf (hadAShovel = True) Then
)DoShovel(inTheNoontime, allOverThisLand
Else
)TakeNap(allDayLong, onMySofa
End If

1:
2:
3:
4:
5:
6:
7:
8:

: .

Mhm76

If . : .
: Conditions
) If (ElseIf Then . 1 . 4
Boolean True .False
.
_ If ((PlayersOnTeam(homeTeam) >= 9) And(PlayersOnTeam(visitingTeam) >= 9)) Or
(justPracticing = True) Then
)(PlayBall
Else
)StadiumLights(turnOff
End If

.If ElseIf . 4

ElseIf . Else .
If .ElseIf Else . If
: Branches
Then
.True ElseIf Else End If )
( . If .

2 3 hadAHammer . 5
. hadAShovel True Else 7 .
:Statement keywords
If End
) If ( . If Else ElseIf Then If : End If
. Else ElseIf . If If.
If (phoneNumberLength = 10) Then
)DialNumber(phoneNumber
End If

ElseIf .
)"If (SaveData() = True) Then MsgBox("Data saved.
= If (TimeOfDay >= #1:00:00 PM#) Then currentStatus = WorkStatus.GoHome Else currentStatus
WorkStatus.BusyWorking

If .
. . If
.
If...End If .End If

Select Case Statements


If then then then:
""Washington
2) Then
""Jefferson
5) Then
""Lincoln

If (billValue = 1) Then
= presidentName
= ElseIf (billValue
= presidentName
= ElseIf (billValue
= presidentName
...

.
ElseIf .
Select Case :
"= "Washington
"= "Jefferson
"= "Lincoln
"= "Jackson

Select Case billValue


Case 1
presidentName
Case 2
presidentName
Case 5
presidentName
Case 20
presidentName

1:
02
3:
4:
5:
6:
7:
8:
9:


10

: .

Mhm76
"= "Grant
"= "!! Non-president
"= "!! Value too large
"= "!! Invalid value

Case 50
presidentName
Case 10, 100
presidentName
Case Is > 100
presidentName
Case Else
presidentName
End Select

10:
11:
12:
13:
14:
15:
16:
17:
18:

If Select Case .
billValue .Case )Case
Case ( . )Case Else ( 16
Case . Case .
) ( 12 ) . ( 14

IIf ( IIf and If Functions) If


If . :
"If (gender = "F") Then fullGender = "Female" Else fullGender = "Male

IIf :
)"fullGender = IIf(gender = "F", "Female", "Male
IIf . comma-delimited
Boolean True . False :True

. .
. IIf IIf . :
)) (purgeResult = IIf(level = 1, PurgeSet1( ), PurgeSet2

) ( PurgeSet1 ) (PurgeSet2 .
PurgeSet2() PurgeSet1( ) : 1 ) ( PurgeSet1 ) ( PurgeSet2

)(PurgeSet1 .
2008 If . IIf
If :IIf
)) (ClasspurgeResult = If(level = 1, PurgeSet1( ), PurgeSet2

) (PurgeSet1 ) ( PurgeSet2 . If

.ternary
. If Boolean .
)realObject = If(object1, object2

If Nothing .
.
Nothing
. non-Nothing

Loops
For...Next : For Each...Next . Do...Loop
.

For...Next
.
For...Next
Dim whichMonth As Integer
For whichMonth = 1 To 12
)ProcessMonthlyData(whichMonth
Next whichMonth

12 ) 1 ( 12 . :
.
.
)' ----- Month(Today
'
)For whichMonth = 1 To Month(Today
)ProcessMonthlyData(whichMonth
Next whichMonth

) (1 . Step :For
For countDown = 60 To 0 Step -1


11

: .

Mhm76
...
Next countDown

.
.
For whichMonth As Integer = 1 To 12
)ProcessMonthlyData(whichMonth
Next whichMonth

For Each. . .Next


For Each...Next For .
Arrays .collection .IEnumerabl
: For
For Each oneRecord In setOfRecords
)ProcessRecord(oneRecord
Next oneRecord

Do. . .Loop

. Do...Loop
. Do...Loop While Until .
:
Dim processDate As Date = #1/1/2000#
)Do While (processDate < #2/1/2000#
'
)ProcessContent(processDate
'
)processDate = processDate.AddDays(1
Loop
processDate 2/1/2000 .

Until :
)Do Until (processDate >= #2/1/2000#
...
Loop

. Until While
:
Do
...
)Loop Until (processDate >= #2/1/2000#

. ) (
. Do...Loop .While...End While
.
.Do...Loop

"" Exit Statements


. For
. Do
. . .Exit
Exit : loop-specific :
: Exit For
For...Next For Each...Next .

Exit Do

Do...Loop.
Exit : :
For whichMonth = 1 To 12
If (ProcessMonthlyData(whichMonth) = False) Then Exit For
Next whichMonth
'

12 . 12
. Exit Do Do...Loop.
Exit )nested loops (
:

12

: .

Mhm76

For whichMonth = 1 To 12
)For whichDay = 1 To DaysInMonth(whichMonth
_ )If (ProcessDailyData(whichMonth, whichDay) = False
Then Exit For
Next whichDay
'
'

Next whichMonth

Continue Statements

Continue . Continue
:
: Continue For
For...Next For Each...Next .
.
: Continue Do
Do...Loop . Until .While
Continue Continue
. Continue For :
For whichMonth = 1 To 12
If (DataAvailable(whichMonth) = False) Then Continue For
)RetrieveData(whichMonth
)ProcessData(whichMonth
)SaveData(whichMonth
Next whichMonth

Creating Your Own Procedures


.
.

Subroutines
Sub .End Sub .
)01 Sub ShowIngredients(ByVal gender As Char
2:
"Dim theMessage As String = "Unknown.
3:
If (gender = "M"c) Then
4:
"theMessage = "Snips and snails and puppy dog tails.
5:
ElseIf (gender = "F"c) Then
6:
"theMessage = "Sugar and spice and everything nice.
7:
End If
8:
)MsgBox(theMessage
09 End Sub

1 :
. ) Sub ( . ShowIngredients
parameters .
. : .
) gender ( ) . (Char
gender 3 . 5
.arguments by value
.by reference gender .ByVal
ByRef . . ByVal
.
value type .reference type
.



ByVal

Value type

ByVal

Reference type


.
members
.


13

: .
ByRef

Value type

ByRef

Reference type

Mhm76
.

.
.
.

ByRef
.ByVal 2 8 body .
theMessage 2 .End Sub

Functions
.
01 Function IsPrime(ByVal source As Long) As Boolean
2:
. '
3:
Dim testValue As Long
4:
If (source < 2) Then
5:
Return False
6:
ElseIf (source > 2) Then
7:
&For testValue = 2 To source \ 2
8:
If ((source Mod testValue) = 0) Then
9:
Return False
10:
End If
11:
Next testValue
12:
End If
13:
Return True
14 End Function

) (1 ) 2 ( 13

)Function . (14 .
. . IsPrime
Boolean :
End

)primeResult = IsPrime(23
. Return 5 9 ) . 13 VB 6.0

( .

Properties
.

01 Class PercentRange
2:
Public Percent As Integer
03 End Class
: .class-level

.
. ) ( :
01 Class PercentRange
2:
0 100 '
3:
Private savedPercent As Integer
04 Public Property Percent( ) As Integer
05 Get
6:
Return savedPercent
07 End Get
)08 Set(ByVal value As Integer
9:
If (value < 0) Then
10:
savedPercent = 0
11:
ElseIf (value > 100) Then
12:
savedPercent = 100
13:
Else
14:
savedPercent = value
15:
End If
16 End Set
17 End Property
18 End Class


14

: .

Mhm76

) Percent 4 ( 17 ) savedPercent ( 3 caller-


supplied 0 . 100 .
) accessor 5 ( 7 . )Set accessor 8 ( 16
. ) ( 4 ) Set accessor . ( 8

Get

. Percent PercentRange
:
Dim activePercent As New PercentRange
activePercent.Percent = 107 ' An out-of-range Integer
"MsgBox(activePercent.Percent) ' Displays "100", not "107
read-only write-only ReadOnly
WriteOnly Property ) (4 accessor

. .

Where to Put Your Procedures


6.0 .
.
:
) (.
Class Employee
)(Sub StartVacation
...
End Sub
Function TotalVacationTaken() As Double
...
End Function
End Class

.
Dim executive As New Employee
...
)(executive.StartVacation

Other Flow Control Features



.

GoTo
GoTo . line label
. .
PromptUser:
)GetValuesFromUser(numerator, denominator
If (denominator = 0) Then GoTo PromptUser
quotient = numerator / denominator

GoTo PromptUser .
.PromptUser
.
.
LabelAlone:
)"MsgBox("It's all alone.
)"LabelAndCode: MsgBox("Together again.

GoTo
.GoTo

:
"Dim importantMessage As String = "Do
GoTo Step2
"!Step6: importantMessage &= "AG
GoTo Step7
"Step3: importantMessage &= "wit
GoTo Step4
" Step2: importantMessage &= "wn
GoTo Step3


15

: .

Mhm76
"importantMessage &= "CK-G
GoTo Step6
"importantMessage &= "h I
GoTo Step5
)MsgBox(importantMessage

Step5:
Step4:
Step7:

. . .
:GoTo .
.GoTo
. For...Next
.
" " '
GoTo InsideTheLoop
For counter = 1 To 10
InsideTheLoop:
)MsgBox("Loop number: " & counter
Next counter


.GoTo .

The Return Statement


GoTo
Return :
. Return . Return
:
Return

:
.
Return 25

Pre-.NET Exit . .
:
:Exit Sub
.
:Exit Function

.
:Exit Property

Exit Function .
.
_ Function SafeDivide(ByVal numerator As Double,
ByVal denominator As Double) As Double
# '
If (denominator = 0.0#) Then
'
SafeDivide = 0.0#
Exit Function
End If
Return numerator / denominator
End Function

The End and Stop Statements


Stop End . End
) (.
Stop debugger . Stop
. Stop
.
.

Events and Event Handlers



16

: .

Mhm76

.event-driven .
. . .
. . .events
message pump .
system-generated
message queue . .


event-handling . ) ( .
. .
event handler
. firing .
(1) : (2) . .

.
.


event-firing . .
.
.
event-specific .

. Event )( .
)Public Event SalaryChanged(ByVal NewSalary As Decimal

Event SalaryChanged .Decimal


.
Sub EmployeePayChanged(ByVal updatedSalary As Decimal)...

Events : .
. RaiseEvent
.
Public Class Employee
Public Name As String
Private currentSalary As Decimal
Public Property Salary() As Decimal
Get
Return currentSalary
End Get
)Set(ByVal value As Decimal
currentSalary = value
)RaiseEvent SalaryChanged(currentSalary
End Set
End Property
)Public Event SalaryChanged(ByVal NewSalary As Decimal
End Class

. .
WithEvents .
Public WithEvents MonitoredEmployee As Employee

Handles .
Private Sub EmployeePayChanged(ByVal updatedSalary As Decimal)Handles
MonitoredEmployee.SalaryChanged
)MsgBox("The new salary for " & MonitoredEmployee.Name & " is " & updatedSalary
End Sub

.
)(Public Sub HireFred
MonitoredEmployee = New Employee
"MonitoredEmployee.Name = "Fred
MonitoredEmployee.Salary = 50000 ' Triggers event
End Sub


17

: .

Mhm76

Salary Employee SalaryChanged


.RaiseEvent EmployeePayChanged .
.
Windows Forms .NET
. .
)Event EventName(ByVal sender As System.Object,ByVal e As System.EventArgs
sender . e

event-specific . System.EventArgs
.System.EventArgs

Namespaces
.
namespaces
tree-shaped ) ( System
. System.Timers .
.
Global .
Global .
Global top-level System .Microsoft
top-level third-level .
. dot
System.Windows.Forms

Forms . :
Global.System.Windows.Forms

. :
Forms

.
Forms .

Referencing Namespaces
referenced imported .
DLL .
" "References ) .projects Properties (

DLL .
DLLs . DLLs
. System.dll .System System.Windows.Forms.dll
Windows Forms System.Windows.Forms .
DLL .
. Windows Forms :
System.Deployment System.Data.DataSetExtensions System.Data System.Core System
System.Xml System.Windows.FormsSystem.Drawin. System.Xml.Linq

18

: .

Mhm76

) (
. on-screen .System.Windows.Forms.Form
.
.imports
. System.Windows.Forms
Form .Form .
Imported namespaces .
System.Windows.Forms .WindowsForms
. Imports :
Imports System.Windows.Forms

Imports . :
Imports Fred = System.Windows.Forms

Form Fred.Form.
Imports .

Namespaces in Your Project


top-level .
Windows Forms .WindowsApplication1 top-
level Application . Root namespace
: Microsoft-supplied
.
.
.Namespace Namespace
.EndNamespace Namespace End Namespace
WindowsApplication1
.
: WindowsApplication1.WorkArea.BasicStuff.BusyData
Namespace WorkArea.BasicStuff
Class BusyData
...
End Class
End Namespace

. :
Namespace WorkArea
Namespace BasicStuff
Class BusyData
...
End Class
End Namespace
End Namespace

The My Namespace
2005 My top-level .
6.0 . . My
(FCL) Framework Class Library mini-
hierarchy . .
. Imports .
My :
)MsgBox(My.Application.Info.Version.ToString

My : . Windows Forms
My.Forms . .
My.Forms .
"My.Forms.Form1.Text = "Welcome


19

mhm76

The Library Project:


.
. .
) ( .
.
. .
Library Item Features:

. :
9 .
.
9 )
(...
.
9 )( .
9 .
.
9 )(.
.
9 .
. .
Patron Features
"" ) ( .
:
.
.
.
" " PIN .
" " )( ) checkout ( renewal
.
.
F1 .
. experimentation
" " )( . administrative staff.
Administrative Features:
.
. :
o " " login .
. .
o .
.
.
o fines
. unpaid fines
o . .
. .
o
.
o )( .
) ( .
o .
o .

mhm76

o . .
o .
o plug in
.
The Application As a Whole:
:
training .
.SQL Server database
.
)( XML .

. _ - .
The Needs of the Users

. :
. .
.
Data and Information
.
. 5-3
: . )(
: . :
) (.
.
Process
:

.

. " ".
.
.
.
. .process
.
. .
(1): (2) )(3
. .
Usability
.
loathe. .

.
.
)(.
.
:
. .
.

.
.
) ( .
. .
.
) (Commonality

mhm76

touts )( innovation .
. :

. :
consistency
.
Project
:
. Project Agreement.doc
. .
" " Change Order.
. Change Order.doc
" ".
.
. Project Acceptance.doc
. . " Acceptance
" Criteria Testing" " .
.

mhm76

Designing the Database


.
.

Relational Databases :

tables records
. row column
field .
.
Quantity
3
1
1
2
7

Product
Price
Coffee
3.99
Rye bread
2.68
Coffee
3.99
Tea
3.99
Potato chips 0.99

Customer ID
Name
Product ID
AA1
Al Albertson
BEV01COF
AA1
Al Albertson
BRD05RYE
BW3
Bill Williams
BEV01COF
BW3
Bill Williams
BEV01COF
CC1
Chuck Charles CHP34PTO

Order ID
10001
10001
10002
10003
10004

Customer
Record ID
92231
92232
92233
92234
92235

.
.
Customer ID Product .

product ID BEV01COF
flat file . database table "
." normalization
record/row/ ) ( a primary key
. data integrity
:

.respectively asterisk .
Quantity
3
1
1
2
7

Product ID
BEV01COF
BRD05RYE
BEV01COF
BEV01COF
CHP34PTO

Customer Name
Al Albertson
Bill Williams
Chuck Charles
Unit Price
3.99
2.68
3.99
0.99

Customer ID
AA1
AA1
BW3
BW3
CC1

Order ID
10001
10001
10002
10003
10004

* Record ID
92231
92232
92233
92234
92235

* Customer ID
AA1
BW3
CC1

Product Name
Coffee
bread
Coffee
Potato chips

* Product ID
BEV01COF
BRD05RYE Rye
BEV01COF
CHP34PTO

)( . Customer ID
.
. customer name
. customer product . order line

mhm76

query languages
) relational algebra (
SQL
. " " SELECT .
INSERT UPDATE, DELETE
: ) Data Manipulation Language (DML
. SQL
) data definition language (DDL
. .
Vendor-specific systems Microsofts SQL Server Oracles
Oracle Microsofts Access DDL DML
.
data replication crash-proof
data integrity .
SQL Server 2005 . 2005
. SQL Server
) (
.

)(. 2005
)( T-SQL scripting
language .
SQL Server "." server
network first establish .server engine
.
tutorial books 2008
.
2008.

.
2005 . " 2005
" . :

http://www.microsoft.com/sql/express
) ()structuredquerylanguage(SQL

. :
. SQL Structured
.Query Language .
DDL DML .
picky . Upper-
and lowercase distinctions SELECT select ).SeLeCt ) Traditional SQL ( T-SQL
(
tables fields .
. ) whitespace
( . . .
) (
. semicolon
semicolon . )
(
. .
SQL script GO "
For all of the other statements that
."appeared so far, go ahead and process them now.
" " DDL Statements
.
: " ." CREATE TABLE . basic syntax
:

CREATETABLEtableName

mhm76
(
fieldName1dataTypeop ons,
fieldName2dataTypeop ons,
andsoon...
)

) (.
.
data types . options
data constraints .
Extensions constraints ) indexes
( .
" " . order line
CREATE TABLE LineItems
(
RecordID bigint IDENTITY PRIMARY KEY,
OrderID bigint NOT NULL,
CustomerID varchar(20) NOT NULL
REFERENCES Customers (CustomerID),
ProductID varchar(20) NOT NULL,
Quantity smallint NOT NULL
)

IDENTITY SQL Server RecordID


sequential counter RecordID . "
" PRIMARY KEY RecordID . bigint
smallint varchar
).(20 characters REFERENCES LineItems
Customers LineItems.CustomerID ) .Customers.CustomerID
" " dot . () (References
)( ) ( . foreign references
ALTER TABLE
. DROP TABLE .
.
.SQL Server

Data type
Bigint
binary
Bit
char, nchar
Cursor
Datetime

decimal, numeric

Float

Description
9,223,372,036,854,775,808

-8)-64(
9,223,372,036,854,775,807
8,000 .
)binary(100
1,0: .NULL . Boolean
.
)( char ). ( nchar Unicode 8,000
. )char(100
stored procedures .
January 1, 1753 December 31, 999
Time accuracy 3.33 . 2008
)date : ( )time ( datetime2 2
) datetime 100 (100 nanoseconds
) datetimeoffset (
.
) ( precision
) decimal point.( scale )decimal(10,4
. .38
numeric synonym decimal .dec
)( . )( bits
.53 53 float )float(53

mhm76

. real ). float(24 1.0


bits .
2008 )(
Hierarchyid
).( tree-shaped data .2005
.
image, text, ntext
-4)-32( 2,147,483,648. 2,147,483,647
Int
8 high-accuracy)64( )( currency values
Money
) (. 922,337,203,685,477.5808
. 922,337,203,685,477.5807
.
rowversion,timestamp
timestamp . deprecated synonym
.
rowversion rowversion
January 1, 1900 AD .June 6, 2079 AD
Smalldatetime
Time accuracy .
)( 2)16( 32,768 . 32,767
Smallint
4)32( )( .
Smallmoney
214,748.3648 . 214,748.3647
.
sql_variant
. )(
Table
.
1 unsigned integer field)8( 0 .255
Tinyint
)16 globally unique identifier (GUID . )( NEWID
Uniqueidentifier
.
8000 . parameter
Varbinary
).varbinary(100 )( .
)varbinary(max 2 .
)(varchar (nvarchar) Unicode 8000
varchar, nvarchar
) . varchar(100 .
)varchar(max 2 .
)( XML typed untyped 2.2 GB
Xml
" "DML Statements

1038

INSERT)( records . Data ).


INSERT (
INSERT .
.
INSERT INTO LineItems
)(OrderID, CustomerID, ProductID, Quantity
VALUES (10002, 'BW3', 'BEV01COF', 1)
CREATE TABLE LineItems
) (- primary key ) RecordID
.(IDENTITY .
. CustomerID Customer BW3
.Customer

.
)( customer product INSERT.
:
''John O''Sullivan

literal time values :


''7-Nov-2005

. misinterpret
" " unassigned . "
" null " ." NULL " " NULL
.NOT NULL
:DELETE
DELETE FROM LineItems WHERE RecordID = 92231

mhm76

DELETE) WHERE() .(WHERE RecordID = 92231 WHERE


. WHERE AND OR
parentheses.
DELETE FROM LineItems WHERE OrderID = 10001
'AND ProductID = 'BRD05RYE

DELETE 0 1000 WHERE .


. WHERE
DELETE FROM LineItems

" " UPDATE WHERE .


LineItems
Quantity = 4
)(RecordID = 92231

UPDATE
SET
WHERE

" " SET )(Quantity


).(4 .comma
formulas. calculations

UPDATE LineItems SET Quantity = Quantity + 1


'ProductID = 'BEV02POP
WHERE RecordID = 92231

DELETE UPDATE
.WHERE
DML " ." SELECT
SELECT ProductID, Quantity FROM LineItems
WHERE RecordID = 92231

SELECT )(LineItems ) = RecordID


(92231 ) (Quantity ProductID .
)( )( SELECT * FROM LineItems :
LineItems . asterisk)*(
. include all fields.
" " ORDER BY )(:
SELECT * FROM LineItems
WHERE Quantity > 5
ORDER BY ProductID, Quantity DESC

Quantity 5 ProductID
) ( ascending order ) numeric quantity in descending
order .(DESC
)( Aggregate functions grouping features
. total ordered quantity product :
SELECT ProductID, SUM(Quantity) FROM LineItems
GROUP BY ProductID

joins . LineItems
Customer CustomerID . SELECT abbreviations
) LI (CU AS
:

SELECT LI.OrderID, CU.CustomerName, LI.ProductID


FROM LineItems AS LI INNER JOIN Customer AS CU
ON LI.CustomerID = CU.CustomerID
ORDER BY LI.OrderID, CU.CustomerName

" " inner join


)( )( .join

Inner join:
. .INNER JOIN

Left outer join :



" ." NULL
.LEFT JOIN Product. LineItems
.
Product left outer join
) .(LineItems

Right outer join

mhm76


. .RIGHT JOIN

Full outer join


. it is
.reflected in the results .FULL JOIN

)(Cross join

) Cartesian join (.
. .CROSS JOIN
). "" relational
(database " -" parent-child ""
. " orders " order header " " line items
one-to-many .
-
.
- one-to-one .
.
many-to-many
.
. ) (
.semester
- : " " go-between
. .

Beyond Basic SQL


scratch the surface
. )(
. SEQUEL "
" Structured English Query Language
.
.
.

Using Databases in Visual Basic


:
9 ADO.NET .NET Framework
. .
.
9 " " data binding .
.
. )
( ADO.NET .
.
9 .

.
9 .
.
Documenting the Database

. :
. source code

.
:

mhm76


.
. user documentation .
database documentation .


.
100,000 )(
. .


. :

) (.
. Database Creation Script.sql
SQL Server database script .

Technical Resource Kit Content


.
. source code
freak out .

Security-related tables
patrons log in look up administrators
. security credentials
. Windows-based security credentials
initially, ) (restrict.
.Activity . group rights
) (GroupName . particular group

Field

Type

ID

Long

FullName

) Text(50

Description
.
. .
Descriptivenameofthisactivity.Required.
.

:
1Manageauthorsandnames
2Manageauthorandnametypes
3Managecopystatuscodes
4Managemediatypes
5Manageseries
6Managesecuritygroups
7Managelibrarymaterials
8Managepatrons
9Managepublishers
10Managesystemvalues

mhm76

11Manageadministrativeusers
12Processandacceptfees
13Managelocations
14Checkoutlibraryitems
15Checkinlibraryitems
16Accessadministrativefeatures
17Performdailyprocessing
18Runsystemreports
19Accesspatronswithoutpatronpassword
20Managebarcodes
21Manageholidays
22Managepatrongroups
23Viewadministrativepatronmessages
.GroupName . Librarians administrators
.
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
.
Nameofthisgroup.Required.
) Text(50
FullName
.
.GroupActivity Activity )GroupName
-- ( many-to-many .
Description
Type
Field
Primarykey.Theassociatedsecuritygroup.Foreignreference
Long
GroupID
toGroupName.ID.Required.
. . ) (
. GroupName.ID
Primarykey.Theactivitythatmembersoftheassociated
Long
ActivityID
securitygroupcanperform.ForeignreferencetoActivity.ID.
Required.
. .
.Activity.ID .
.UserName .
.
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
.
Nameofthisuser,administrator,orlibrarian.Required.
) Text(50
FullName
. .
UserIDthatgivesthisuseraccesstothesystem.Itisentered
) Text(20
LoginID
intotheLibraryprogramsloginform,alongwiththe
password,togainaccesstoenhancedfeatures.Required.
.
" "
. .
Thepasswordforthisuser,inanencryptedformat.Optional.
) Text(20
Password
. .
Isthisuserallowedtoaccessthesystem?0forFalse,1forTrue.
Boolean
Active
Required.
0 1.
.

mhm76

Description
Type
Field
Towhichsecuritygroupdoesthisuserbelong?Foreign
Long
GroupID
referencetoGroupName.ID.Required.
.GroupName.ID
.
Support code tables
.
") drop-down .(" combo box
) ( .CodeAuthorType author authors
editors contributor . librarys inventory )
.(roles
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
. .
Nameofthistypeofauthororcontributor.Required.
) Text(50
FullName
. .
.CodeCopyStatus " "" circulating " being repaired
. checked-in checked-out
.reference item
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
. .
Nameofthisstatusentry.Required.
) Text(50
FullName
. .
) ( .CodeLocation . separate sites
rooms areas . common location
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthislocation.Required.
) Text(50
FullName
ThedatewhenDailyProcessingwaslastdoneforthislocation.
Date LastProcessing
IfNULL,processinghasnotyetbeendone.Optional.
.
..
.CodeMediaType books magazines videos .CDs
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthismediatype.Required.
) Text(50
FullName
Numberofdaysforwhichitemsinthistypecanbechecked
Integer CheckoutDays
out,beforerenewal.Required.

..
Numberofdaystoaddtotheoriginalcheckoutperiodfora
Integer
RenewDays
renewalofitemswithinthistype.Required.

..
Maximumnumberoftimestheitemcanberenewedbya
Integer RenewTimes
patronbeforeitmustbereturned.Required.

..
Amountchargedperdayforanoverdueitemofthistype. Currency
DailyFine
Required.

mhm76

Description
Type
Field
..
. .CodePatronGroup
class/grade / . reporting purposes
.
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
Nameofthispatrongroup.Required.

Text(50)

ID
FullName

. . collection larger series .CodeSeries


Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthisseriesorcollection.Required.
Text(50)
FullName
Library items
. actual inventory
. copies " named item"
. . . NamedItem
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Titleofthisitem.Required. Text(150)
Title
Subtitleofthisitem.Optional. Text(150)
Subtitle
Fulldescriptionofthisitem.Optional.
Memo Description
Editionnumberforthisitem.Optional.
Text(10)
Edition
Thisitemspublisher.ForeignreferencetoPublisher.ID.
Long
Publisher
Optional.
Deweydecimalnumber.Use/forlinebreaks.Optional.
Text(20)
Dewey
LibraryofCongressnumber.Use/forlinebreaks.Optional.
Text(25)
LC
ISBN,ISSN,orotherstandardizednumberofthisitem.
Text(20)
ISxN
Optional.
LibraryofCongresscontrolnumber.Optional.
Text(12)
LCCN
Yearoforiginalcopyright,orofbelievedoriginalcopyright.
Integer
Copyright
Optional.
Theseriesorcollectioninwhichthisitemappears.Foreign
Long
Series
referencetoCodeSeries.ID.Optional.
Themediaclassificationofthisitem.Foreignreferenceto
Long MediaType
CodeMediaType.ID.Required.
Isthis tleoutofprint?0forFalse,1forTrue.Required.
Boolean
OutOfPrint
. . ItemCopy
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Therelatednameditemrecord.Foreignreferenceto
Long
ItemID
NamedItem.ID.Required.
Numberedpositionofthisitemwithinthesetofcopiesfora
Integer CopyNumber
nameditem.Required,anduniqueamongitemswiththesame
ItemIDfieldvalue.
Commentsspecifictothiscopyoftheitem.Optional.
Memo Description
Isthiscopyavailableforcheckoutorcircula on?0forFalse,1
Boolean
Available
forTrue.Required.

10

mhm76

Description
Type
Field
Hasthiscopybeenreportedmissing?0forFalse,1forTrue.
Boolean
Missing
Required.
Isthisareferencecopy?0forFalse,1forTrue.Required.
Boolean
Reference
Anycommentsrelevanttotheconditionofthiscopy.Optional.
Text(30)
Condition
Datethiscopywasacquiredbythelibrary.Optional.
Date
Acquired
Valueofthisitem,eitheroriginalorreplacementvalue. Currency
Cost
Optional.
Thegeneralstatusofthiscopy.Foreignreferenceto
Long
Status
CodeCopyStatus.ID.Required.
Barcodefoundonthecopy.Atthistime,onlynumericbar
Text(20)
Barcode
codesaresupported.Optional.
Thesiteorroomlocationofthisitem.Foreignreferenceto
Long
Location
CodeLocation.ID.Optional.
. Publisher
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthepublisher.Required. Text(100)
FullName
URLforthispublisherswebsite.Optional. Text(255)
WebSite
. contributes illustrates edits writes Author
. author
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Lastnameofthisauthor.Required.
Text(50)
LastName
Firstnameofthisauthor.Optional.
Text(30)
FirstName
Middlenameorinitialofthisauthor.Optional.
Text(30) MiddleName
Namesuffix,suchasJr.Optional.
Text(10)
Suffix
Yearofbirth.UsenegativenumbersforBC.Optional
Integer
BirthYear
Yearofdeath.UsenegativenumbersforBC.Optional.
Integer
DeathYear
Miscellaneouscommentsaboutthisauthor.Optional. Text(250)
Comments
NamedItem many-to-many -- . ItemAuthor
.Author
Description
Type
Field
Primarykey.Theassociatednameditem.Foreignreferenceto
Long
ItemID
NamedItem.ID.Required.
Primarykey.Theauthorassociatedwiththenameditem.
Long
AuthorID
ForeignreferencetoAuthor.ID.Required.
Relativeorderofthisauthoramongtheauthorsforthisnamed
Integer
Sequence
item.Authorswithsmallernumbersappearfirst.Required.
Thespecifictypeofcontributiongivenbythisauthorforthis
Long AuthorType
nameditem.ForeignreferencetoCodeAuthorType.ID.
Required.
. named items Keyword
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthiskeyword.Required.
Text(50)
FullName
NamedItem -- ( named item ) keyword ItemKeyword
.Keyword
Description
Type
Field
Primarykey.Theassociatednameditem.Foreignreferenceto
Long
ItemID

11

mhm76

Description
Type
Field
NamedItem.ID.Required.
Primarykey.Thekeywordtoassociatewiththenameditem.
Long
KeywordID
ForeignreferencetoKeyword.ID.Required.
.( ) Subject headings Subject
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthissubject.Required. Text(150)
FullName
.Subject NamedItem -- ItemSubject
Description
Type
Field
Primarykey.Theassociatednameditem.Foreignreferenceto
Long
ItemID
NamedItem.ID.Required.
Primarykey.Thesubjecttoassociatewiththenameditem.
Long
SubjectID
ForeignreferencetoSubject.ID.Required.
Patron-related tables
) item copies (
. (
.(checkout ) privileges Patrons .Patron
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Lastnameofthispatron.Required.
Text(30)
LastName
Firstnameofthispatron.Required.
Text(30)
FirstName
Dateoflastcheckout,renewal,orreturn.Optional.
Date
LastActivity
Isthisanac vepatron?0forFalse,1forTrue.Required.
Boolean
Active
Anycommentsassociatedwiththispatron.Optional.
Memo
Comments
Commentsthataredisplayedtoadministrativeuserswhenthe
Memo AdminMessage
patronsrecordisaccessed.Optional.
Barcodefoundonthispatronslibrarycard.Atthistime,only
Text(20)
Barcode
numericbarcodesaresupported.Optional.
Patronspassword,inanencryptedformat.Required.
Text(20)
Password
Patronsemailaddress.Optional. Text(100)
Email
Patronsphonenumber.Optional.
Text(20)
Phone
Patronsstreetaddress.Optional.
Text(50)
Address
Patronscity.Optional.
Text(20)
City
Patronsstateabbreviation.Optional.
Text(2)
State
Patronspostalcode.Optional.
Text(10)
Postal
Thegroupinwhichthispatronappears.Foreignreferenceto
Long PatronGroup
CodePatronGroup.ID.Optional.
. item copies PatronCopy
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Theassociatedpatron.ForeignreferencetoPatron.ID.
Long
Patron
Required.
Theitemcopycurrentlyorpreviouslycheckedoutbythe
Long
ItemCopy
patron.ForeignreferencetoItemCopy.ID.Required.
Thedatewhenthisitemcopywasinitiallycheckedout.
Date
CheckOut
Required.
Thenumberoftimesthisitemcopyhasbeenrenewed.Setto0
Integer
Renewal
whentheitemcopyisfirstcheckedout.Required.

12

mhm76

Description
Type
Field
Currentduedateforthisitemcopy.Required.
Date
DueDate
Thedatewhenthisitemcopywasreturned.Optional.
Date
CheckIn
Hastheitemcopybeenreturned?0forFalse,1forTrue.
Boolean
Returned
Required.
Istheitemcopymissingandconsideredlost?0forFalse,1for
Boolean
Missing
True.Required.
Totalfineaccumulatedforthisitemcopy.Defaultsto0.00.An Currency
Fine
administratormayreduceanaccumulatedfine.Required.
Totalamountpaid(infees)forthisitemcopy.Required.
Currency
Paid
Whenanitemcopyisprocessedforoverduefines,thisfield
Date ProcessDate
containsthelastdateforwhichprocessingwasdone.Optional.
patron copy dismissals ( payments) Fines.PatronPayment
Overdue fines .record
.
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Theassociateditemcheckedoutbythepatron.Foreign
Long PatronCopy
referencetoPatronCopy.ID.Required.
Dateandtimewhenthisentrywasrecorded.Required.
Date
EntryDate
Thetypeofpaymententry.Required.Thepossiblevaluesare:
Text(1)
EntryType
PThepatronmadeapayment.
FAfine(otherthanastandardoverduefine)was
imposedbyanadministrator.
DAportion(orall)ofthefinewasdismissed.
RArefundwasgiventothepatronduetooverpayment.
Theamountassociatedwiththisentry.Thevalueisalways Currency
Amount
positive.Required.
Ashortcommentaboutthisentry.Optional.
Text(50)
Comment
Theuserwhoaddedthispaymentevent.Foreignreferenceto
Long
UserID
UserName.ID.Optional.
Bar code-related tables
)single label ( 2)( 1/
. .( 3)(sheet
. BarcodeSheet
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthissheettemplate.Required.
Text(50)
FullName
Unitsusedinthevariousmeasurementsfoundinmostfieldsin
Text(1)
UnitType
thisrecord.Required.
I=Inches
C=Centimeters
P=Points
T=Twips
Widthoftheentirepage.Required.
Number
PageWidth
Heightoftheentirepage.Required.
Number
PageHeight
Leftborder,uptotheedgeoftheprintablelabelarea.
Number
MarginLeft
Required.
Rightborder,uptotheedgeoftheprintablelabelarea.
Number MarginRight
Required.

13

mhm76

Description
Type
Field
Topborder,uptotheedgeoftheprintablelabelarea.
Number
MarginTop
Required.
Bottomborder,uptotheedgeoftheprintablelabelarea.
Number MarginBottom
Required.
Thewidthoftheblankareabetweenlabelcolumns.Required.
Number IntraColumn
Theheightoftheblankareabetweenlabelrows.Required.
Number
IntraRow
Thenumberoflabelcolumnsonthistemplate.Required.
Integer ColumnsCount
Thenumberoflabelrowsonthistemplate.Required.
Integer
RowsCount
. BarcodeLabel
.( format)shape
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthislabeltemplate.Required.
Text(50)
FullName
Thesheettemplateonwhichthislabeltemplateappears.
Long BarcodeSheet
ForeignreferencetoBarcodeSheet.ID.Required.
Unitsusedinthevariousmeasurementsfoundinmostfieldsin
Text(1)
UnitType
thisrecord.Required.
I=Inches
C=Centimeters
P=Points
T=Twips
. BarcodeLabelItem
.
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Identifiestheorderinwhichitemsonthelabelareprinted.
Integer
Priority
Lowernumbersareprintedfirst.Required.
Thelabeltemplateonwhichthisitemappears.Foreign
Long BarcodeLabel
referencetoBarcodeLabel.ID.Required.
Whattypeofitemdoesthisrecordrepresent?Required.
Text(1)
ItemType
T=Statictext
B=Barcode
N=Barcodenumber
L=Line
R=Rectangle
Leftedgeoftheitemrelativetotheleftedgeofthelabel.
Number
PosLeft
MeasuredaccordingtotherelatedBarcodeLabel.UnitType
field.Required.
Topedgeoftheitemrelativetothetopedgeofthelabel.
Number
PosTop
MeasuredaccordingtotherelatedBarcodeLabel.UnitType
field.Required.
Widthoftheitem,oroftheboxinwhichtheitemisdrawn.For
Number
PosWidth
lines,thisisthexcoordinateoftheendpoint.Measured
accordingtotherelatedBarcodeLabel.UnitTypefield.Required.
Heightoftheitem,oroftheboxinwhichtheitemisdrawn.For
Number
PosHeight
lines,thisistheycoordinateoftheendpoint.Measured
accordingtotherelatedBarcodeLabel.UnitTypefield.Required.
Rotationangle,indegrees,oftheboxinwhichtheitemis
Integer
Rotation
drawn.Zero(0)equalsnoangle,andincreasinganglesproceed

14

mhm76

Description
Type
Field
clockwise.Rangesfrom0to359.OnlyusedwhenItemTypeisT,
B,N,orR.Optional.
Thenameofthefontusedtowritethetext.Validonlywhen
Text(50)
FontName
ItemTypeisTorN.Optional.
Thesizeofthefontusedtowritethetext.Validonlywhen
Number
FontSize
ItemTypeisT,B,orN.Optional.
Thestatictexttodisplayonthelabel.ValidonlywhenItemType Text(100)
StaticText
isT.Optional.
Thestyleofthefonttext.Maybeanycombinationofthe
Text(4)
FontStyle
followingfourcodes.
B=Bold
I=Italic
U=Underline
K=Strikeout
LeavethisfieldNULLtousethenormalstyle.Validonlywhen
ItemTypeisTorN.Optional.
Themaincolorofthetext,barcode,orline.Whenprintinga
Long
Color1
rectangle,thisisthebordercolor.IfNULL,blackisused.A
standardWindows32bitRGBcolorvalue.Optional.
Thefillcolorwhenprintingarectangle.IfNULL,whiteisused.A
Long
Color2
standardWindows32bitRGBcolorvalue.Optional.
Thealignmentofthetextwithintheboundingbox.Validonly
Integer
Alignment
whenItemTypeisT,B,orN.
1=Alignintopleftcornerofbox
2=Alignintopcenterareaofbox
4=Alignintoprightcornerofbox
16=Aligninmiddleleftareaofbox
32=Aligninmiddlecenterareaofbox
64=Aligninmiddlerightareaofbox
256=Aligninbottomleftcornerofbox
512=Aligninbo omcenterareaofbox
1024=Aligninbo omrightcornerofbox
Thenumberofdigitsinwhichtopadthebarcodenumber.Set
Integer
PadDigits
tozero(0)toignorepadding.Rangesfrom0to20.Ifthebar
codelengthislessthanthespecifiednumberofdigits,itis
paddedontheleftwithzeros.OnlyappliestoItemTypesofB
andN.
Other miscellaneous tables( )
.
( ) Holiday
.recurring holidays )( .
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthisholiday.Notnecessarilyunique.Required.
Text(50)
FullName
Thetypeofentry.Required.Fromthefollowinglist.
Text(1)
EntryType
A=Annual(asineveryDecember25)
E=Weekly(asineverySunday)
O=One me(asin2/16/2004isPresidentsDay)
Entrytypespecificdetail.Required.Differsforeachentrytype.
Text(10)
EntryDetail

15

mhm76

Description
Type
Field
DetailValue EntryType
MonthandDayinmm/ddformat
A
Singledigit:1=Sundaythrough7=Saturday
E
Dateinyyyy/mm/ddformat
O
SystemValue miscellaneous enterprise-wide settings
. workstation Local workstation-specific settings
.
Description
Type
Field
Primarykey;automaticallyassigned.Required. LongAuto
ID
Nameofthisvalue.Required.
Text(50) ValueName
) Informationassociatedwiththisentry.Optional. Text(100
ValueData
. .ValueName .ValueData

BarcodeCode39

"code 39"39"3 code 3 of 9"9


bar code number . 0 False ) 1-(.
.missing or NULL
BarcodeFont

. .
.
DatabaseVersion

""1 .
DefaultLocation
CodeLocation.ID
)FineGrace (

location .

.without incurring a fine


NextBarcodeItem

. item bar codes


NextBarcodeMisc

)( .miscellaneous bar codes


NextBarcodePatron

).( patron bar codes


PatronCheckOut

. )0(
) 1-(.
.
SearchLimit

. .250
inclusive 25.5000
TicketHeading

. . )|(
.
TicketFooting

. . )|( .
UseLC

Dewey ) ( ).Library of Congress (LC


)0( Dewey 1-)LC(. .Dewey
Creating the Database
. CREATE TABLE
. ). Database CreationScript.sql
(.
2005. SQL Server 2005 Management Studio Express
2005 command-line tools
. CREATE TABLE . .

16

mhm76

2005 ) SQL Server 2005 Express Edition (.


2005 .
. . Author .
CREATE TABLE Author
(
ID bigint IDENTITY PRIMARY KEY,
LastName varchar(50) NOT NULL,
FirstName varchar(30) NULL,
MiddleName varchar(30) NULL,
Suffix varchar(10) NULL,
BirthYear smallint NULL,
DeathYear smallint NULL,
Comments varchar(250) NULL
);

CREATE TABLE comma-delimited list)( .


NULL NOT NULL NULL .
PRIMARY KEY " " NOT NULL
--. GroupActivity GroupName
.Activity

CREATE TABLE GroupActivity


(
GroupID bigint NOT NULL,
ActivityID bigint NOT NULL,
)PRIMARY KEY (GroupID, ActivityID
;)

Author ID .
) ( PRIMARY KEY
GroupActivity
).PRIMARY KEY (GroupID, ActivityID
)( REFERENCES constraint
.CREATE TABLE ). (.
GroupActivity .GroupName
ALTER TABLE GroupActivity
)ADD FOREIGN KEY (GroupID
REFERENCES GroupName (ID);

entire SQL script


2005 ). Microsoft SQL Server 2005 Management Studio Express
management tool - (.
tables . Library Project 2005
) ( new database " " Database
" " New Database from . Library
Database Name .OK
. Database Creation Script.sql
. <<File <<Open File menu command
).Database Creation Script.sql (
.Management Studio Express

17

mhm76

SQL Server 2005 Management Studio Express main form

. script " " toolbar " " Library )


(. Execute .F5 not a lot going on
) ( .

. script panel Object Explorer


Library Refresh .
) (.
.

Partial list of database tables

Database Creation Script.sql :


----- */ACMELibraryProject
* Databasecreationscript.
* StarttoFinishVisualBasic2005
* Copyright(c)2006byTimPatrick
/*

CREATETABLEActivity
)
IDbigintPRIMARYKEY
FullNamevarchar(50)NOTNULL
(
GO

18

mhm76

INSERTINTOAc vity(ID,FullName)VALUES(1,'Manageauthorsandnames'(
INSERTINTOAc vity(ID,FullName)VALUES(2,'Manageauthorandnametypes'(
INSERTINTOAc vity(ID,FullName)VALUES(3,'Managecopystatuscodes'(
INSERTINTOAc vity(ID,FullName)VALUES(4,'Managemediatypes'(
INSERTINTOAc vity(ID,FullName)VALUES(5,'Manageseries'(
INSERTINTOActivity(ID,FullName)VALUES(6,'Managesecuritygroups'(
INSERTINTOAc vity(ID,FullName)VALUES(7,'Managelibrarymaterials'(
INSERTINTOAc vity(ID,FullName)VALUES(8,'Managepatrons'(
INSERTINTOAc vity(ID,FullName)VALUES(9,'Managepublishers'(
INSERTINTOAc vity(ID,FullName)VALUES(10,'Managesystemvalues'(
INSERTINTOAc vity(ID,FullName)VALUES(11,'Manageadministra veusers'(
INSERTINTOAc vity(ID,FullName)VALUES(12,'Processandacceptfees'(
INSERTINTOActivity(ID,FullName)VALUES(13,'Manageloca ons'(
INSERTINTOAc vity(ID,FullName)VALUES(14,'Checkoutlibraryitems'(
INSERTINTOAc vity(ID,FullName)VALUES(15,'Checkinlibraryitems'(
INSERTINTOAc vity(ID,FullName)VALUES(16,'Accessadministrativefeatures'(
INSERTINTOAc vity(ID,FullName)VALUES(17,'Performdailyprocessing'(
INSERTINTOAc vity(ID,FullName)VALUES(18,'Runsystemreports'(
INSERTINTOAc vity(ID,FullName)VALUES(19,'Accesspatronswithoutpatronpassword'(
INSERTINTOAc vity(ID,FullName)VALUES(20,'Managebarcodes'(
INSERTINTOAc vity(ID,FullName)VALUES(21,'Manageholidays'(
INSERTINTOAc vity(ID,FullName)VALUES(22,'Managepatrongroups'(
INSERTINTOAc vity(ID,FullName)VALUES(23,'Viewadministrativepatronmessages'(
GO

CREATETABLEAuthor
)
IDbigintIDENTITYPRIMARYKEY
LastNamevarchar(50)NOTNULL
FirstNamevarchar(30)NULL
MiddleNamevarchar(30)NULL
Suffixvarchar(10)NULL
BirthYearsmallintNULL
DeathYearsmallintNULL
Commentsvarchar(250)NULL
(
GO

CREATETABLEBarcodeLabel
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
BarcodeSheetbigintNOTNULL
UnitTypevarchar(1)NOTNULL
(
GO

CREATETABLEBarcodeLabelItem
)
IDbigintIDENTITYPRIMARYKEY

19

mhm76

PrioritysmallintNOTNULL
BarcodeLabelbigintNOTNULL
ItemTypevarchar(1)NOTNULL
PosLe decimal(10,4)NOTNULL
PosTopdecimal(10,4)NOTNULL
PosWidthdecimal(10,4)NOTNULL
PosHeightdecimal(10,4)NOTNULL
RotationsmallintNULL
FontNamevarchar(50)NULL
FontSizedecimal(10,4)NULL
Sta cTextvarchar(100)NULL
FontStylevarchar(4)NULL
Color1bigintNULL
Color2bigintNULL
AlignmentsmallintNULL
PadDigitssmallintNULL
(
GO

CREATETABLEBarcodeSheet
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
UnitTypevarchar(1)NOTNULL
PageWidthdecimal(10,4)NOTNULL
PageHeightdecimal(10,4)NOTNULL
MarginLe decimal(10,4)NOTNULL
MarginRightdecimal(10,4)NOTNULL
MarginTopdecimal(10,4)NOTNULL
MarginBo omdecimal(10,4)NOTNULL
IntraColumndecimal(10,4)NOTNULL
IntraRowdecimal(10,4)NOTNULL
ColumnsCountsmallintNOTNULL
RowsCountsmallintNOTNULL
(
GO

CREATETABLECodeAuthorType
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
(
GO

CREATETABLECodeCopyStatus
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
(
GO

CREATETABLECodeLocation

20

mhm76

)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
LastProcessingdatetimeNULL
(
GO

CREATETABLECodeMediaType
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
CheckoutDayssmallintNOTNULL
RenewDayssmallintNOTNULL
RenewTimessmallintNOTNULL
DailyFinemoneyNOTNULL
(
GO

CREATETABLECodePatronGroup
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
(
GO

CREATETABLECodeSeries
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
(
GO

CREATETABLEGroupActivity
)
GroupIDbigintNOTNULL
ActivityIDbigintNOTNULL
PRIMARYKEY(GroupID,ActivityID(
(
GO

CREATETABLEGroupName
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
(
GO

CREATETABLEHoliday
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
EntryTypevarchar(1)NOTNULL

21

mhm76

EntryDetailvarchar(10)NOTNULL
(
GO

CREATETABLEItemAuthor
)
ItemIDbigintNOTNULL
AuthorIDbigintNOTNULL
SequencesmallintNOTNULL
AuthorTypebigintNOTNULL
PRIMARYKEY(ItemID,AuthorID(
(
GO

CREATETABLEItemCopy
)
IDbigintIDENTITYPRIMARYKEY
ItemIDbigintNOTNULL
CopyNumbersmallintNOTNULL
Descriptionvarchar(max)NULL
AvailablebitNOTNULL
MissingbitNOTNULL
ReferencebitNOTNULL
Condi onvarchar(30)NULL
AcquireddatetimeNULL
CostmoneyNULL
StatusbigintNOTNULL
Barcodevarchar(20)NULL
LocationbigintNULL
(
GO

CREATETABLEItemKeyword
)
ItemIDbigintNOTNULL
KeywordIDbigintNOTNULL
PRIMARYKEY(ItemID,KeywordID(
(
GO

CREATETABLEItemSubject
)
ItemIDbigintNOTNULL
SubjectIDbigintNOTNULL
PRIMARYKEY(ItemID,SubjectID(
(
GO

CREATETABLEKeyword
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL

22

mhm76

(
GO

CREATETABLENamedItem
)
IDbigintIDENTITYPRIMARYKEY
Titlevarchar(150)NOTNULL
Sub tlevarchar(150)NULL
Descriptionvarchar(max)NULL
Edi onvarchar(10)NULL
PublisherbigintNULL
Deweyvarchar(20)NULL
LCvarchar(25)NULL
ISxNvarchar(20)NULL
LCCNvarchar(12)NULL
CopyrightsmallintNULL
SeriesbigintNULL
MediaTypebigintNOTNULL
OutOfPrintbitNOTNULL
(
GO

CREATETABLEPatron
)
IDbigintIDENTITYPRIMARYKEY
LastNamevarchar(30)NOTNULL
FirstNamevarchar(30)NOTNULL
LastActivitydatetimeNULL
ActivebitNOTNULL
Commentsvarchar(max)NULL
AdminMessagevarchar(max)NULL
Barcodevarchar(20)NULL
Passwordvarchar(20)NOTNULL
Emailvarchar(100)NULL
Phonevarchar(20)NULL
Addressvarchar(50)NULL
Cityvarchar(20)NULL
Statevarchar(2)NULL
Postalvarchar(10)NULL
PatronGroupbigintNULL
(
GO

CREATETABLEPatronCopy
)
IDbigintIDENTITYPRIMARYKEY
PatronbigintNOTNULL
ItemCopybigintNOTNULL
CheckOutdatetimeNOTNULL
RenewalsmallintNOTNULL
DueDatedatetimeNOTNULL
CheckIndatetimeNULL

23

mhm76

ReturnedbitNOTNULL
MissingbitNOTNULL
FinemoneyNOTNULL
PaidmoneyNOTNULL
ProcessDatedatetimeNULL
(
GO

CREATETABLEPatronPayment
)
IDbigintIDENTITYPRIMARYKEY
PatronCopybigintNOTNULL
EntryDatedatetimeNOTNULL
EntryTypevarchar(1)NOTNULL
AmountmoneyNOTNULL
Commentvarchar(50)NULL
UserIDbigintNULL
(
GO

CREATETABLEPublisher
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(100)NOTNULL
WebSitevarchar(255)NULL
(
GO

CREATETABLESubject
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(150)NOTNULL
(
GO

CREATETABLESystemValue
)
IDbigintIDENTITYPRIMARYKEY
ValueNamevarchar(50)NOTNULL
ValueDatavarchar(100)NULL
(
GO

INSERTINTOSystemValue(ValueName,ValueData)VALUES('BarcodeCode39','0'(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('BarcodeFont',NULL(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('DatabaseVersion','1'(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('DefaultLocation',NULL(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('FineGrace','3'(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('Licensee',NULL(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('LicenseCode',NULL(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('NextBarcodeItem','2000001'(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('NextBarcodeMisc','1000001'(

24

mhm76

INSERTINTOSystemValue(ValueName,ValueData)VALUES('NextBarcodePatron','1'(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('PatronCheckOut','1'(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('SearchLimit','250'(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('TicketHeading','LibrarySystem'(
INSERTINTOSystemValue(ValueName,ValueData)VALUES('TicketFooting','Thankyou'(.
INSERTINTOSystemValue(ValueName,ValueData)VALUES('UseLC','0'(
GO

CREATETABLEUserName
)
IDbigintIDENTITYPRIMARYKEY
FullNamevarchar(50)NOTNULL
LoginIDvarchar(20)NOTNULL
Passwordvarchar(20)NULL
ActivebitNOTNULL
GroupIDbigintNOTNULL
(
GO

ALTERTABLEGroupActivityADDFOREIGNKEY(GroupID)REFERENCESGroupName(ID(
ALTERTABLEGroupActivityADDFOREIGNKEY(ActivityID)REFERENCESActivity(ID(
ALTERTABLEUserNameADDFOREIGNKEY(GroupID)REFERENCESGroupName(ID(
ALTERTABLENamedItemADDFOREIGNKEY(Publisher)REFERENCESPublisher(ID(
ALTERTABLENamedItemADDFOREIGNKEY(Series)REFERENCESCodeSeries(ID(
ALTERTABLENamedItemADDFOREIGNKEY(MediaType)REFERENCESCodeMediaType(ID(
ALTERTABLEItemCopyADDFOREIGNKEY(ItemID)REFERENCESNamedItem(ID(
ALTERTABLEItemCopyADDFOREIGNKEY(Status)REFERENCESCodeCopyStatus(ID(
ALTERTABLEItemCopyADDFOREIGNKEY(Location)REFERENCESCodeLocation(ID(
ALTERTABLEItemAuthorADDFOREIGNKEY(ItemID)REFERENCESNamedItem(ID(
ALTERTABLEItemAuthorADDFOREIGNKEY(AuthorID)REFERENCESAuthor(ID(
ALTERTABLEItemAuthorADDFOREIGNKEY(AuthorType)REFERENCESCodeAuthorType(ID(
ALTERTABLEItemKeywordADDFOREIGNKEY(ItemID)REFERENCESNamedItem(ID(
ALTERTABLEItemKeywordADDFOREIGNKEY(KeywordID)REFERENCESKeyword(ID(
ALTERTABLEItemSubjectADDFOREIGNKEY(ItemID)REFERENCESNamedItem(ID(
ALTERTABLEItemSubjectADDFOREIGNKEY(SubjectID)REFERENCESSubject(ID(
ALTERTABLEPatronADDFOREIGNKEY(PatronGroup)REFERENCESCodePatronGroup(ID(
ALTERTABLEPatronCopyADDFOREIGNKEY(Patron)REFERENCESPatron(ID(
ALTERTABLEPatronCopyADDFOREIGNKEY(ItemCopy)REFERENCESItemCopy(ID(
ALTERTABLEPatronPaymentADDFOREIGNKEY(PatronCopy)REFERENCESPatronCopy(ID(
ALTERTABLEPatronPaymentADDFOREIGNKEY(UserID)REFERENCESUserName(ID(
ALTERTABLEBarcodeLabelADDFOREIGNKEY(BarcodeSheet)REFERENCESBarcodeSheet(ID(
ALTERTABLEBarcodeLabelItemADDFOREIGNKEY(BarcodeLabel)REFERENCESBarcodeLabel(ID(
GO

----- */Createthebasicsecurityaccount/* .
INSERTINTOGroupName(FullName(
VALUES('Administrators'(

INSERTINTOGroupActivity(GroupID,ActivityID(
SELECT1,IDFROMAc vity

25

mhm76
INSERTINTOUserName(FullName,LoginID,Active,GroupID(
(VALUES('Administrator','admin',1,1
GO

26

mhm76

Assembly
EXE )DLL .(dynamiclinklibrary
. .

What Is an Assembly
" " unit of deployment . repository
. )EXE ( )DLL code libraries (.
.assembly
private . public Private assemblies .
DLLs EXE . installation directory .
bother .
)(. WindowsApplication1.Class1 interfere
private private . private
Public assemblies . multiple .NET applications
Public assemblies private assemblies :
strong name encrypted digital signature
named vendor ) . source (.
)( " " public key digital signature
.manifest )(sn.exe
) . compilation process projects
.(properties ) ( .
).Global Assembly Cache (GAC
applications install directory .GAC GAC
assembly ). computers Windows directory c:\windows\assembly
( GAC assembly
). Global Assembly Cache Tool (gacutil.exe
.installed files. .NET 400 GAC DLLs
). Framework Class Libraries (FCLs .NET multiple versions
assembly ) .(versioning )(EXE)libraries (DLL
.GAC GACs assembly Explorer
folder " " Details sort . Assembly Name
. . cache Microsoft.VisualStudio.Windows.Forms
) ( Microsoft. VisualStudio.Windows.Forms.dll 2.0 .9.0.
- . multiple files
)( graphics assembly view .
. modified deleted maimed .
. single-file assemblies

The GAC has this duplication under control

?Whats Inside an Assembly


EXE DLL " PE " Portable Execution
) EXE .(DLL .NET PE files

mhm76

extra stuff . .
" " . .NET PE :
" " A PE header
PE )( .
The MSIL code section
).semicompiled Microsoft Intermediate Language (MSIL
chip Intel AMD
just-in-time (JIT)compiler MSIL x86 . at a moments notice
The Metadata section
rummage through .
)assemblys manifest (.
metadata elements :manifest
The name of the assembly
) ( application .projects properties
)( The version number of the assembly.
) ( 1.2.3.4. .
"" .
Strong name content
) ( manifest .publishers public key
Culture and language settings
) ( .
Assembly file listing
) (. EXE DLL .
directory subordinate .manifest
Exported type information
) ( "" . .
References
) ( metadata
external assemblies) ( private .GAC
specific version culture platformtarget .
Internal type information
) manifest ( )( )( metadata
. additional metadata Visual Basics attribute
.feature manifest-specific elements main .
)( . .
).( legit.
executables libraries " )(
).( extensible
. MSIL metadata
. With the right tools .

. casual reading . third parties
) (obfuscators ) (
obfuscation .

Reflection
.
reflection . metadata
. .System.Reflection namespace
metadata
. obfuscation vendors compiled MSIL
metadata .
. C#

Assemblies and Applications


) (EXE )( instance
. list all assemblies actively actively
.WindowsApplication1 :
mscorlib
Microsoft.VisualStudio.HostingProcess.Utilities
System.Windows.Forms

mhm76

System
System.Drawing
Microsoft.VisualStudio.HostingProcess.Utilities.Sync
Microsoft.VisualStudio.Debugger.Runtime
vshost
System.Data
System.Deployment
System.Xml
System.Core
System.Xml.Linq
System.Data.DataSetExtensions
Microsoft.VisualBasic
WindowsApplication1
System.Runtime.Remoting

17 WindowsApplication1 . main program DLLs framework-


.supplied . Microsoft.VisualBasic Microsoft.VisualBasic.dll System

.System.dll
) ( libraries .GAC private assemblies
DLL .
.NET Framework WindowsApplication1

.WindowsApplication1
. .GAC
.

My

The My Namespace and Assemblies

)( packaged logic .
. . FCL documentation
shudder
)( .
. sheltered
. . "
" : . Make Windows Development Fast and Easy esoteric
bowels System namespace .
My 2005
. My FCL hierarchy
. My .
pretend namespace My System.Reflection System .System.Windows.Forms
- .pretend
Imports ) ( .
nodes .
Available features
Branch
.
My.Application
name .version
My.Application.Info

My.Application.Log
.
My.Computer
.
My.Computer.Audio
.
My.Computer.Clipboard
.
My.Computer.Clock
My.Computer.FileSystem filesystems .
My.Computer.FileSystem.

Documents Desktop .Temp

SpecialDirectories
My.Computer.Info
My.Computer.Keyboard
My.Computer.Mouse
My.Computer.Network
My.Computer.Ports
My.Computer.Registry
My.Forms
My.Log
My.Request
My.Resources

.
.
)(.
.
) ( .systems serial ports
keys values .registry
. .
. ASP.NET .
Active Server Pages .Request
.ASP.NET
.


My.Response

mhm76
Active Server Pages .Response
ASP.NET

My.Settings
.application settings system
My.User
Windows user .authentication information
My.WebServices
available web services .
.ASP.NET


System.Reflection. whatever
major :
My.Application.Info.Version.Major

Reflection :
My.Application.Info.LoadedAssemblies

:
My.Computer.Clock.GmtTime

:local area network :


My.Computer.Network.IsAvailable

:
My.User.Name

" "Kill . My.Computer.FileSystem.Delete


)(.
Recycle Bin

)( Directives and Assemblies


. #Const #If
). #Region
( .
.
" " express " " professional .
.
.
.
If (professionalVersion = True) Then
)(ShowWhizBangFeatures
Else
)(ShowLaughableFeatures
End If

.
mark down .
professionalVersion = True . #Const .compiler constants
#Const fullVersion = True

. Boolean compiler constant fullVersion


. complain . #If
#If (fullVersion = True) Then
) (ShowWhizBangFeatures
#Else
)(ShowLaughableFeatures
#End If

#. . If
:
If (professionalVersion = True) Then
)(ShowWhizBangFeatures
Else
)(ShowLaughableFeatures
End If

. .fullVersion fullVersion True


:
)( ShowWhizBangFeatures
. .
)( ) ( .

fullVersion full version #If:
#Const fullVersion = True
"" " :" False
#Const fullVersion = False

mhm76

.
. .
Compile ) project properties (.
Advanced Compile Options " " Custom constants

fullVersion = True fullVersion = False . Visual Basic


compiler different compile scripts.
MSBuild .
compiler constants numbers strings . Booleans
. DEBUG TRACE " Define DEBUG
" constant" " Define TRACE constant .

Project
:
.version number
conveys .
(1/ )(2 .

Adding Controls
excels .
. ) Integrated Development Environment (IDE .
.

A
B

:
. A toolbox:
.

mhm76

. B The form surface


. " " WYSIWYG
.
. C The Solution Explorer
. My Project . Form1.vbform .
.
. D The Properties panel
.
. .
" " labels " "shape"" line web-style hyperlinks
button picture .
:
Setting
Property
)(Name
ControlBox
FormBorderStyle
Size
StartPosition

AboutProgram
False
FixedDialog
440, 311
CenterScreen


Text
" " Label " ."Label
.


(Name): ProgramName
Label1
AutoSize: True
Font/Bold: True
Location: 136, 16
Text:
(Name): ProgramVersion
Label2
AutoSize: True
Location: 136, 32
. Text:

Label3

(Name): LicenseInfo
AutoSize: False
Location: 136, 48
Size: 280, 32
Text:

(Name): DevelopedBy
Label4
AutoSize: True
Location: 136, 88
Text:
(Name): DeveloperName
Label5
AutoSize: True
Location: 160, 112
Text: MHM
(Name): DeveloperBook
Label6
AutoSize: True
Location: 160, 128
Text: Programming Visual Basic 2008
(Name): DeveloperProject
Label7
AutoSize: True
Location: 160, 144
Text: In-book Project
(Name): CompanyCopyright
Label8
AutoSize: True
Location: 136, 208
Text: Copyright (c) 2009 by MHM.

. 6 lines rectangles ellipses

.
. " " Label sans .


(Name): VersionDivider
Label9
AutoSize: False
BackColor: Black
Location: 136, 80
Size: 280,1
) (Text:

Label10

(Name): BackgroundSide

mhm76
AutoSize: False
BackColor: White
Location: 0, 0
Size: 120, 296
) (Text:

Label11

(Name): BackgroundDivider
AutoSize: False
BackColor: Black
Location: 120, 0
Size: 1, 296
) (Text:

Label11 " ." Send To Back


" "LinkLabel Label " " links clickable
sections . . " "LinkLabel
.

LinkLabel1

LinkLabel2


(Name): CompanyWeb
AutoSize: True
LinkBehavior: HoverUnderline
Location: 160, 160
Text: http://www.mhm.com
(Name): CompanyEmail
AutoSize: True
LinkBehavior: HoverUnderline
Location: 160, 176
Text: MHM@yahoo.com

. Button :


(Name): ActClose
Bu on1
DialogResult: Cancel
Location: 344, 240
Size: 80, 24
Text:

Esc .Esc
CancelButton .ActClose
.
" " Tab . View
<< " " Tab Order . .
). (. <<View
Tab Order Esc .
CancelButton

TabIndex .

Adding the Code to the Form


. " Show All Files
" Form1.vb )Form1.Designer.vb (.

mhm76

200
. ) forms class
.(System.Windows.Forms.Form Partial .
Partial Class AboutProgram
Inherits System.Windows.Forms.Form

.InitializeComponent .
:
. .
. .
. .
.
)( )( .
. . ) (
) (ActClose_Click
Public Class AboutProgram
Private Sub ActClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActClose.Click
End Sub
End Class

) ( (1/ sender
) (2 e sender .
sender ActClose . Click
e System.EventArgs placeholder
e ) (.
ActClose_Click . ) .
(Handles ActClose.Click . intact event handler .
. :
Private Sub ActClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActClose.Click
)(Me.Close
End Sub

)()Me.Close / (. ) (F5
"". .
.
) .(LinkClicked )
( ) (

mhm76

)( . ) Method
CompanyWeb
.(Name CompanyWebs LinkClicked
) (. :
Private Sub CompanyWeb_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles CompanyWeb.LinkClicked
End Sub

e .System.Windows.Forms.LinkLabelLinkClickedEventArgs. :
LinkLabel interspersed . e " " Link
. labels .
.
Private Sub CompanyWeb_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles CompanyWeb.LinkClicked
' ----- Show the company web page.

)"Process.Start("http://www.mhm.com
End Sub

Process System.Diagnostics Start .


URL . URL
.CompanyEmails LinkClicked . email
Private Sub CompanyEmail_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles CompanyEmail.LinkClicked
' ----- Send email to the company.
)"Process.Start("mailto:MHM@yahoo.com
End Sub
: form .Load
. ).
.( Load
My.Application.Info.Version )( .System.Version
Private Sub AboutProgram_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
' ----- Update the version number.
With My.Application.Info.Version
ProgramVersion.Text = "Version " & .Major & "." &.Minor & " Revision " & .Revision
End With
End Sub

With . With...End With


With .My.Application.Info.Version
)(. .

mhm76


1.0Revision 0, :

" " ) ( metadata .


. ) My Project
( Application ) Assembly Information (
. Build Minor Major .Revision
OK .

.
. " " Show All Files Solution
.Explorer My Project .AssemblyInfo.vb
) assembly-specific attributes (18 :
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
>)"<Assembly: AssemblyTitle("LIBRARY
>)""(<Assembly: AssemblyDescription
>)"<Assembly: AssemblyCompany("mst
>)"<Assembly: AssemblyProduct("LIBRARY
>)"<Assembly: AssemblyCopyright("Copyright mst 2009
>)""(<Assembly: AssemblyTrademark
>)<Assembly: ComVisible(False
'The following GUID is for the ID of the typelib if this project is exposed to COM
>)"<Assembly: Guid("44d7c504-bcd1-4d64-89fe-bbf91d2e1875
' Version information for an assembly consists of the following four values:
'
Major Version
'
Minor Version
'
Build Number
'
Revision
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
>)"*' <Assembly: AssemblyVersion("1.0.
>)"<Assembly: AssemblyVersion("1.0.0.0
>)"<Assembly: AssemblyFileVersion("1.0.0.0
. AssemblyVersion .

. ) <<File ( Save All

10

mhm76

Adding the Main Form


AboutProgram .
)( Main .
<< Project .Add Windows Form Add New Item Windows
Form MainForm.vb .Add
:

)(Name
FormBorderStyle
MaximizeBox
Size
Text

MainForm
FixedSingle
False
576, 459

)(Name
Size
Text

ActHelpAbout
80, 24
&...

& shortcut. Alt & ) (


.
:
Private Sub ActHelpAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActHelpAbout.Click
' ----- Show the About form.
)(AboutProgram.ShowDialog
End Sub

.AboutProgram 2005 )(
:
) ((New AboutProgram).ShowDialog

.
) (AboutProgram.ShowDialog .
.My :
)(My.Forms.AboutProgram.ShowDialog

My.Forms . My.Forms
default instances .
.AboutProgram AboutProgram
.startup projects properties Application "
" Startup form " " MainForm
AboutProgram")" dialog (ShowDialog
DialogResult ShowDialog . button
. " " AboutProgram DialogResult " " Cancel
DialogResult "". ) (
DialogResult .
upshot .
ActClose_Click AboutProgram .
AboutProgram .
DialogResult "" :
Me.DialogResult = Windows.Forms.DialogResult.Cancel

.AboutProgram .

: Extra Credit: Adding an Icon


. :
.1 MainForm.vb . Solution Explorer
.2
.3 Icon .Properties
.4 " "... . .ico

11

: .

Mhm76

Data and Data Types


.
The Nature of Computer Data
) ( bits 1 on 0 off
true .false - 0 .1
.

2,135

. .2 :
3

) (8=2

) (16=2

) (4=2

) (32=2

) (2=2
0

) (1=2

) (64=2

01001100

) (128=2

"8"8 .

) 01001100

)( (2
:
76=1280+641+320+160+81+41+20+10 .
1 . -8)-8( - 0
255 .
.
.
.
" " data types .
) ( interpreter utilize .
ultimately )( .
Vitamin . -8
)( .
). (

76 .01001100
)( 76
- .L ) (
. ) ASCII American Standard Code for Information
(Interchange . -8 0 255

.
1

: .

Mhm76

punctuation)( miscellaneous
.characters
. Unicode -16 65,000 .
" ." string
Boolean single bit ) True (1 False
).(0 Negative integers floating-point fixed-point dates
times .
.

Data in .NET
classes .System System.Byte
-8 . 0.255 8
decimal form .
15 8: core interpretive data types
3integers 2 decimal numbers character data dates and
times . Boolean
Integer Data Types
)8 ( 15
.
)( .
.
) (signed integers
) ( unsigned
.

Style

Range of values

System.Byte
System.SByte
System.Int16
System.UInt16
System.Int32
System.UInt32
System.Int64

8
8
16
16
32
32
64

Unsigned
Signed
Signed
Unsigned
Signed
Unsigned
Signed

System.UInt64

64

Unsigned

0 to 255
128 to 127
32,768 to 32,767
0 to 65,535
2,147,483,648 to 2,147,483,647
0 to 4,294,967,295
9,223,372,036,854,775,808
to9,223,372,036,854,775,807
0 to 18,446,744,073,709,551,615

.NET data

Bits

Decimal Data Types


fractions
)( 2/1: 0.5 4/1 0.25 3/1 0.33333 ...
.3 2,000 . 3
. .0.33333333
computer-based decimal
.values . .
. . ) perfect
(accuracy . .
Description
NET data type AccuracyRange
System.Decimal

)(Perfect

28 .
. .
.

vice versa
79,228,162,514,264,337,593,543,950,335 to
)79,228,162,514,264,337,593,543,950,335. (Thats 29 digits
)(0 :
0.0000000000000000000000000001 to
0.0000000000000000000000000001

System.Single

.
2

: .

Mhm76
.0.0000000000023

:3.402823E+38
1.401298E45 1.401298E45
3.402823E+38

System.Double

. :
1.79769313486231E+3084.94065645841247E324:
:
4.94065645841247E324 1.79769313486232E+308:

Character Data Types


System.Char .System.String Char
. 16 .
String 2
. ) (immutable
. )(
.

.

Date and Time Data Type

System.DateTime ) (. DateTime
. " " ticks12:00 1.
1 ).(12:00 a.m. on January 1, 1 AD tick 100 .
31 9999 )(.

Boolean Data Type

System.Boolean essence : . bit : True


. False
Shockingly 24)32( )(
. .
. boil down Boolean . operations
. )(0 .
) (0 )).(1-
C# 11- 1 -
.1
C# interpret (.

The System.Object Class

) ( object-oriented development environment


- - )( .System.Object :
. )( .
.
-)( System.Object ) ( .
System.Int32 System.Object System.Int32 .

Value Types and Reference Types

. ) ( buckets
instructions .
.
. System.Object
. .
System.Object . System.ValueType
. .

Value types:

.1 System.ValueType .System.Object
.2 : Boolean Byte Char DateTime Decimal
Double Int16 Int32 Int64 SByte Single UInt16
UInt32 . UInt64
.3 .structures
.4 Enumerations .System.Object << System.ValueType <<System.Enum:
.5 .
.6 )( ")" Nothing " " nullable
(limitation
.7 . )( System.Int32
integer .32-bit

.
3

: .

Mhm76

.8 ..NET garbage collection

Reference types

.1 .System.Object
.2 : .String
.3 ".Visual Basic classes
.4 Delegates)( class methods << System.Delegate:
System.Object " " multicast delegate . System.MulticastDelegate:
.5 ) (
.6 )( " " Nothing
.7 )( ) ( .
System.String System.String .base class
.8 .garbage collection
) " ." modules modules
)( instances(.
.
System.Object .)( System.Object
. )(
. System.Objec )
(mark . )( ) (boxing
).(unboxing. boxing
.substantial performance hit

Visual Basic Data Types

.
. .

. System.Int32 Integer
.

.
4

: .

Mhm76

Literals
)(.
:
)"!MsgBox("Hello, World

MsgBox . . double quotes


data-type-defining character . literal
.
Description
Example
Literal type
: True .False
True
Boolean
.c
"Q"c
Char
Char .String
.#
#11/7/2005#
Date
.

.
Floating-point Decimal D .@.
@123.45D,123.45
Decimal
Double R .#
123.45# 123.45R
Double

.Double
Hexadecimal

&HABCD
123.45%123.45I

Integer

123.45&123.45L

Long

hexadecimal
. hex digits

&H

Integer I . %.
Integer
.Integer
Long L &.
Long
. Long
octal &O
.octal digits

Octal

&O7654

Short
Single
String

Short .S
123.45S
123.45!123.45F Single F . !.
String
""A ""B"" C
.
.

Constants
. )(
)( .
. .Const
Const MonthsInYear As Short = 12

:
name
MonthsInYear:
data type
. Short .As
As .
: Boolean Byte Char Date Decimal Double Integer Long
Object SByte Short Single String UInteger ULong
UShort . enumeration
initializer
.12 .
. :
Const Seven As Integer = 3 + 4

access level
MonthsInYear .
. access modifier .Const
. access modifier
. .
"!Const GreatGreeting As String = "Hello, World
...Later...
)MsgBox(GreatGreeting

Enumerations

.
5

: .

Mhm76

.
.
.
End Enum .
Enum CarType As Integer
Sedan = 1
StationWagon = 2
Truck = 3
SUV = 4
Other = 5
End Enum
Enum )(CarType ).(Integer As
. Integer
: Byte Integer Long SByte Short
UInteger ULong .UShort
) 2 (6 ) .(Sedan
. .
0 1 .
. .
CarType.Sedan
Enum method . procedure ) class
structure (module .
intended features . System.DayOfWeek
.

Variables
.
.
. . :
Dim customerName As String
Dim dimension customerName
.String string literals
string variables functions . strings
" )" Nothing " "(
customerName = Nothing ' Nothing,
" ' Literal" = customerName
customerName = GetCustomerName(customerID) ' Function result,

.
nullable " " Nothing 0 Booleans
False Dim override .
Dim countdownSeconds As Short = 60
Dim processingDate As Date = Today
Dim customerName As String = GetCustomerName(customerID)
- - . new
. New "
". .
' ----- One-line variation.
Dim someEmployee As New Employee
' ----- Another one-line variation.
Dim someEmployee As Employee = New Employee
' ----- Two-line variation.
Dim someEmployee As Employee
someEmployee = New Employee

buckets directions
. Nothing bucket instructions
. new instance
memory dumped .
New )( .
.someEmployee
constructors initialization routines initial
values. .New string constructors
. .
25 .lotsOfStars
8 .

Dim lotsOfStars As New String("*"c, 25)

.
6

: .

Mhm76

Dim .
'

)(Sub MyProcedure
Dim myVariable As Integer
...
End Sub

).
. fields local variables local
constants (. Dim access modifiers
:fields

Private:
Private variables .
new class base class private
.

Friend
. assembly .
. .

Public
. .
.

Protected
.
Protected
class structure . module

Protected Friend
. .
fields local variables .constants
Class mclass
' ----- Here's a field.
Private InternalUseOnly As Boolean
)(Sub MyProcedure
' ----- Here's a local variable.
Dim myVariable As Integer
End Sub
End Class

Dim .

Scope and Lifetime

procedure . procedure-level scope


. " " block statements For...Next
If...Then . Dim
. block-level scope
.
For counter = 1 To 10
Dim processResult As Integer
' ----- More code here.
Next counter
' )MsgBox(processResult

processResult .For...Next
For . immediate error
lifetime procedure-level variable
. .
)(
.
)fields ( class-level variables scope
. )( .
.
Variable and Constant Naming Conventions
.

Local Type Inference

operators

. assignment operator

)=( . )(
. :

.
7

: .

Mhm76
squareArea = length * width

: assignment .multiplication ) ( .
.squareArea area
. complex formula
: non-assignment operators unary : binary
. Operands . Operands
) ( literals constants variables . function return values
.

Operator
+

*
/

Mod
^
&
And

Or

AndAlso

OrElse

Not

Xor

<<

>>

Description

).( Addition . sum


string concatenation )& (
.:+operand1 1.operand2 23+2:
. Unary plus .
) ( redundant " operator overloading
".+: .+operand. 5+:
. )( )( ..operand1 operand2 :.4-10:
. Unary negation . .
. operand2:. 34-:
. ..operand1 * operand2 :. 8 * 3:
. )( )( . 0
). Single Double "" " " .
.operand1 / operand2 : . 9 / 3
truncating
. Integer division )( )(
. )
.(/.operand1 \ operand2 :. 9 \ 4:
. Modulo )( )( .
) .( /operand1 Mod operand2 :.10 Mod 3 :
).( Exponentiation )( )(..operand1 ^ operand2 :.2 ^ 8 :
) .( String concatenation .
String ..operand1 & operand2 :."O" & "K" :
"" .Conjunction. )( bitwise .
) ( Boolean . )
( )( bit 1 )(
.1.operand1 And operand2 :.isOfficer And isGentleman :
. Disjunction )( . )(
. ) (
1 .1.operand1 Or operand2 :.enjoyMountains Or enjoySea :
. Short-circuited conjunction And
. . bitwise
. operand1 AndAlso operand2:. : isOfficer AndAlso isGentleman:
. Short-circuited disjunction Or
. ) bitwise (
.operand1 OrElse operand2 :.enjoyMountains OrElse enjoySea :
. Negation . )(
. ) ( 1
0 0 .1
.Not operand1 :.Not readyToSend :
. Exclusion " ) ( " exclusive or . )(
) .( True or False ) (
1 .
.operand1 Xor operand2 :.chickenDish Xor beefDish :
. Shift left Shift Left
. lost .0
.
.operand1 << operand2 :.&H25 << 3 :
. Shift right Shift Right
. . )(
. .
.operand1 >> operand2 :.&H25 >> 2 :

.
8

: .
=
><
<

>

=<
=>
Like

Is

IsNot

TypeOf

AddressOf

GetType

Mhm76

) equals.(comparison). .
.operand1 = operand2 :.expectedAmount = actualAmount :
. Not equals True .
.operand1 <> operand2 :.startValue <> endValue :
. Less than .
.

.operand1 < operand2 :.raiseRate < inflationRate :
)( Greater than. .
.
.operand1 > operand2 :.raiseRate > inflationRate :
.Less than or equal to .
.operand1 <= operand2 :.raiseRate <= inflationRate :
.Greater than or equal to .
.operand1 >= operand2 :.raiseRate >= inflationRate :
)( . Pattern comparison )(
. )()( Pattern ) wildcard (
.

regular expressions )( .solution
.operand1 Like operand2 :.governmentID Like ssnPattern :
. Type comparison object data type "" Nothing
. . .
.operand1 Is operand2 :.someVariable Is Nothing :
. Negated type comparison )( Is Not .
Not (first Is second): first IsNot second :
.operand1 IsNot operand2 :.something IsNot somethingElse :
)(. Instance comparison .
)( .System.Type TypeOf .Is
.TypeOf operand1 Is typeOperand :.TypeOf someVariable Is Integer :
. Delegate retrieval ) ( .
. : AddressOf method1:.AddressOf one.SomeMethod :
. Type retrieval . .TypeOf GetType )(
.Is
.GetType(operand1) :.GetType(one) :

Non-assignment operators operands


. . )(
. .

Operator
=
=+
=
=*
=/
=\
=^
=&
=<<
=>>

Based on
.
)+( addition
)( subtraction*) (multiplication
)/ (division
\) ( integer division
^ ))( (exponentiation
&)) ( .(concatenation
<<) (shift left
>> ) (shift right

. 1
:
' ---- totalSoFar. 1totalSoFar = totalSoFar + 1
totalSoFar. 1
' ----totalSoFar += 1

Static Variables
.
. .
. . static variables
Static .Dim
Static keepingTrack As Integer = 0

.
9

: .

Mhm76

. )( . .
)(.
.

Arrays
.
:) collections ( .arrays
)( 0 1 )(.
0 .4 .
animals :
. :0# Aardvark
. :1#Baboon
.:2# Chimpanzee
. :3# Donkey

. .
array elements parenthesized number .
.
"animal(0) = "Aardvark
"animal(1) = "Baboon
"animal(2) = "Chimpanzee
"animal(3) = "Donkey

:
MsgBox("The first animal is: " & animal(0))

.
: ) animal(0 )animal(1.
. .For...Next
" :" eachItem 0 .2 .

Dim totalAmount As Integer


totalAmount = eachItem(0) + eachItem(1) + eachItem(2)

For...Next ) (

Dim totalAmount As Integer = 0


For counter As Integer = 0 To 2
' ----- Keep a running total of the items.
)totalAmount += eachItem(counter
Next counter

. Dim
ReDim .

Dim animal(0 To 25) As String ' 26-element array


Dim moreAnimals() As String ' An undefined String array
ReDim moreAnimals(0 To 25) ' Now it has elements

ReDim wipe . Preserve


retains .

ReDim Preserve moreAnimals(0 To 30) ' Keeps elements 0 to 25

.
String .
0 .1
-)( .
) (
)(.

Multidimensional Arrays

) one dimension " .(" rank dimensions


. one-dimensional array animal .
comma-delimited ranges
.
Dim ticTacToeBoard(0 To 2, 0 To 2) As Char ' 3 x 3 board

60 .

Array Boundaries
0 0 To x . redimensioning
0 To . upper bound
' ----- These two lines are equivalent.
Dim animal(0 To 25) As String
Dim animal(25) As String

26. 0.25
.COM-generated arrays

.
10

: .

Mhm76

) .( nonzero lower bounds


LBound .UBound
_ & )MsgBox("The board is " & (UBound(ticTacToeBoard, 1) + 1
" by " & (UBound(ticTacToeBoard, 2) + 1))

MsgBox("The upper element is numbered " & UBound(animal))

GetLowerBound GetUpperBound LBound


UBound . GetLowerBound GetUpperBound 0
LBound UBound .1

_ & )MsgBox("The board is " &(ticTacToeBoard.GetUpperBound(0) + 1


" by " & (ticTacToeBoard.GetUpperBound(1) + 1))

)(
.
. ) ( curly braces
Dim squares( ) As Integer = {0, 1, 4, 9, 16, 25}
lower and upper bound specifications . " squares


" 0 .5

" "Nullable Types


.
.Nothing . 2008
. Nothing " " nullable
) (. :
Public Class Employee
Public Name As String
Public HireDate As Date
Public FireDate As Date
)Public Sub New(ByVal employeeName As String,ByVal dateHired As Date
Me.Name = employeeName
Me.HireDate = dateHired
End Sub
End Class

" " FireDate . FireDate 1


1 12:00 " ".
" " nullable
. enriched .

'
?Public FireDate As Date
Public FireDate2? As Date

. .
.
FireDate = Nothing
FireDate = #7/18/2008#
If (FireDate Is Nothing) Then...

" " nullable " generics


" 16 .

Common Visual Basic Functions


.
)Framework Class Library (FCL
.

Conversion Functions
.
"" .
. ) (CType :
)dest = CXxxx(source
source . CXxxx dest
.
Function
CBool
CByte
CChar
CDate
CDbl

Description


Byte
. Char string .
. Date . .
.Double
Boolean

.
11

: .
CDec
CInt
CLng
CObj
CSByte
CShort
CSng
CType

Mhm76

.Decimal
.Integer
.Long
. Object . Object
.SByte
.Short
.Single
. FCL :
)CType(sourceData, newType

newType :
Dim x As String
x = CType(5, String)

CUInt
CULng
CUShort

5 .
.
. UInteger
. ULong
.UShort

Date-Related Functions
. .
arguments Date String .numeric result
Function
DateAdd
DateDiff
DatePart
DateSerial
DateString
DateValue
Day
FormatDateTime
Hour
IsDate
Minute
Month
MonthName
Now
Second
TimeOfDay
Timer
TimeSerial
TimeString
TimeValue
Today
Weekday
WeekdayName
Year

Description
12
.

. .
. .
Date .
. .
)( )()() (
.
.
.VBScript code
.
. valid date
.
.
1 .12
. .TimeOfDay
.
. .Now
. 0 .
Date .
. .
portion ).( discarded
.
.
.
.

) System.DateTime (
"" .
Dim meetingTime As Date
meetingTime = #11/7/2005 8:00:03 AM#
'MsgBox(meetingTime.Second) ' Displays '3
MsgBox(Second(meetingTime)) ' Also displays '3'

) ( intrinsic System.DateTime .
.

Numeric Functions

.
Function
Fix

Description
)( . .Int

.
12

: .
FormatCurrency
FormatNumber
FormatPercent
Int
IsNumeric
Oct
Val

Mhm76

. currency .
VBScript.
. .
.
. .
.
. .Fix
.valid number
. octal . string representation
first valid number string .

.System.Math . Sin Round


Log 6 Math .
financial) .( accounting
.6
IPmt, IRR, MIRR, NPer, NPV, Pmt, PPmt, PV, Rate, SLN, and SYD. DDB, FV,:

String Functions
. XML string-
manipulation routines hidden from view .
strings. characters
. intact
) ( lone Mid . source variables value
Function
Asc, AscW
Chr, ChrW
Filter
Format
GetChar
InStr
InStrRev
Join
LCase
Left
Len
LSet
LTrim
Mid
Mid
Replace
Right
RSet
RTrim
Space
Split
Str
StrComp
StrConv
StrDup
StrReverse
Trim
UCase

Description
ASCII Unicode .
ASCII .Unicode
.
.
.
.
.
string concatenation . array of strings
.lowercase equivalent
leftmost .
.
)(.
.
middle .
. .
.
.
rightmost .
).( spaces
.
. space characters .StrDup
.delimiter
.
.sort order
. .
. .Space .
)( .
.
.uppercase equivalent

) System.String (.
Length .
"Dim simpleString As String = "abcde
'MsgBox(simpleString.Length) ' Displays '5
MsgBox(Len(simpleString)) ' Also displays '5

intrinsic Visual Basic functions System.String


. . ).( vary

Other Functions
squeezed . .

.
13

: .
Function
DirectCast
ErrorToString
IsArray
IsDBNull
IsError
IsNothing
IsReference
QBColor
RGB
SystemTypeName
TryCast
TypeName
VarType

Mhm76
Description
. . TryCast .CType
. 6
.
) .( valid array
" ." NULL
.error condition
.Nothing
.
.
.
.
. . DirectCast .CType
.
generalized summary " " true
.

Project

" " General .General.vb
)
<<PROJECT module (General.vb
.Friend
Friend Module general
End Module

.
.
. . .
. :

Friend Module general


' ----- Public constants.
"Public Const ProgramTitle As String = "The Library Project
_ = Public Const NotAuthorizedMessage As String
""You are not authorized to perform this task.
Public Const UseDBVersion As Integer = 1
' ----- Constants for the MatchingImages image list.
Public Const MatchPresent As Integer = 0
Public Const MatchNone As Integer = 1
Public Enum LookupMethods As Integer
ByTitle = 1
ByAuthor = 2
BySubject = 3
ByKeywordAny = 4
ByKeywordAll = 5
ByPublisher = 6
BySeries = 7
BySeriesID = 8
ByBarcode = 9
ByDatabaseID = 10
ByAuthorID = 11
BySubjectID = 12
ByPublisherID = 13
End Enum
' ----- Security values.
Public Enum LibrarySecurity As Integer
ManageAuthors = 1
ManageAuthorTypes = 2
ManageCopyStatus = 3
ManageMediaTypes = 4
ManageSeries = 5
ManageGroups = 6
ManageItems = 7
ManagePatrons = 8
ManagePublishers = 9
ManageValues = 10
ManageUsers = 11
ProcessFees = 12

.
14

: .

Mhm76

ManageLocations = 13
CheckOutItems = 14
CheckInItems = 15
AdminFeatures = 16
DailyProcessing = 17
RunReports = 18
PatronOverride = 19
ManageBarcodeTemplates = 20
ManageHolidays = 21
ManagePatronGroups = 22
ViewAdminPatronMessages = 23
End Enum
Public Const MaxLibrarySecurity As LibrarySecurity = LibrarySecurity.ViewAdminPatronMessages
End Module

UseDBVersion
.
MatchPresent MatchNone .
) (LookupMethods administrator
)(LibrarySecurity
. CenterText . " Hello, World
")12 ( 40 14 )
1240 .(2 ) Left Trim
(Len \ .

Public Function CenterText(ByVal origText As String, ByVal textWidth As Integer) As String

' ,

Dim resultText As String


)resultText = Trim(origText
If (Len(resultText) >= textWidth) Then
'
))Return Trim(Left(origText, textWidth
Else
'
Return Space((textWidth - Len(origText)) \ 2) & resultText
End If
End Function
_ Public Function LeftAndRightText(ByVal origLeft As String, ByVal origRight As String,
ByVal textWidth As Integer) As String
'
Dim leftText As String
Dim rightText As String
)leftText = Trim(origLeft
)rightText = Trim(origRight
If (Len(leftText & rightText) >= textWidth) Then
))Return Trim(Left(leftText & rightText, textWidth
Else
Return leftText & Space(textWidth - Len(leftText & rightText)) & rightText
End If
End Function

CenterText )(origText .Trim


. chops off ) ( .
textWidth .
.LeftAndRightText CenterText
.
.DigitsOnly
origText IsNumeric origText .
) ( .destText
Public Function DigitsOnly(ByVal origText As String) As String
'
Dim destText As String
Dim counter As Integer
'
"" = destText
)For counter = 1 To Len(origText
_ If (IsNumeric(Mid(origText, counter, 1))) Then
)destText &= Mid(origText, counter, 1
Next counter
Return destText
End Function

.
15

: .

Mhm76

CountSubStr GetSubStr substrings


. delimiter Mid GetChar
. CountSubStr GetSubStr delimiter
.
Public Function CountSubStr(ByVal mainText As String, ByVal subText As String) As Integer
'
Dim totalTimes As Integer
Dim startPos As Integer
Dim foundPos As Integer
totalTimes = 0
startPos = 1
'

Do
'
)foundPos = InStr(startPos, mainText, subText
If (foundPos = 0) Then Exit Do
totalTimes += 1
'
)startPos = foundPos + Len(subText
Loop
'
Return totalTimes
End Function
Public Function GetSubStr(ByVal origString As String, ByVal delim As String, ByVal whichField As
Integer) As String
'
Dim stringParts() As String
. '
"" If (whichField < 0) Then Return
"" If (Len(origString) < 1) Then Return
"" If (Len(delim) = 0) Then Return
'
)stringParts = Split(origString, delim
'
)If (whichField > UBound(stringParts) + 1) Then Return "" Else Return stringParts(whichField - 1
End Function
CountSubStr . InStr ) (subText
).(mainText mainText ) (totalTimes .
. GetSubStr .
comma-delimited portion .bigString
"bigString = "abc,def,ghi,jkl,mno
MsgBox(GetSubStr(bigString, ",", 3)) ' Displays: ghi
Split )(origString )(stringParts delim .
whichField . whichField 1 0 .

.
16

Mhm76

Windows Forms

Windows Forms " "


.
....

Messages and the Message Pump

)( .

). threads .
( .
) ( system message queue ) ( driver
.
.
.
) ( message pump
. ) ( ID .
) (WndProc . C
:
)while (!done
{
/* ----- Extract and examine the next message. */
;MSG msg
))if (GetMessage(&msg, NULL, 0, 0
{
/* ----- WM_QUIT means it's time to exit the program. */
)if (msg.message == WM_QUIT
;done = true
/* ----- Send the message to the right window. */
;)TranslateMessage(&msg
;)DispatchMessage(&msg
}
}

) ( .
.

Window Procedures.

WndProc
. ) ( :
)If (message type is a mouse click
Do mouse-click related code
)Else If (message type is a key press
Do key-press related code
)Else If (message type is a window resize
Do window-resizing-related code
Else...
) If " " Select Case
(. .
. .
) ( .
1.0 message pump WndProc
. WndProc .

Windows in .NET.

: C message pumps window


procedures .
Message Crackers . MFC
. programmer-friendly logical system
.NET Framework
WndProc .
.Windows Forms .System.Windows.Forms
.

Mhm76

message pump WndProc.


WndProc .
.System.Windows.Forms.Application.Run
message pump .

Forms and Controls


.
)(
System.Windows.Forms.Control ).( window
) ( "Timer
" .

Designing Windows Forms Applications


Windows Forms application
New Project File .

" Project type " Windows Templates Windows


.Forms Application Name . OK
)( Form1 . 250
. Show All Files ) Solution Explorer
( . Form1.Designer.vb
:
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
_ >)(<System.Diagnostics.DebuggerNonUserCode
)Protected Overrides Sub Dispose(ByVal disposing As Boolean
Try
If disposing AndAlso components IsNot Nothing Then
)(components.Dispose
End If
Finally
)MyBase.Dispose(disposing
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.

Mhm76
'Do not modify it using the code editor.
_ >)(<System.Diagnostics.DebuggerStepThrough
)(Private Sub InitializeComponent
)(components = New System.ComponentModel.Container
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
"Me.Text = "Form1
End Sub
End Class

)( Form class . System.Windows.Forms


Form1 base form .
Form1 "
"InitializeComponent .
periodically .

. . unpredictable starting
projects properties " " Startup form ) Application
() projects properties << Project Properties
My Project (. Solution Explorer

Main .
" ." Startup form .
" " Main )( Main routine
.
.

) ( " " Enable application framework
) ) (( " " Startup form
).( compatible cool
functionality . )(.

Main Using Custom Main Methods


" " Main .
6 ":" Show

Mhm76

Form1.Show
2002 .2005
Sub Main module . main form
module . << Project . Add Module
:
Module Module1
)(Public Sub Main
)(Form1.Show
End Sub
End Module

" " Enable application framework Module1 Sub Main


.Startup form . . Form1
. Form1
. message pump ) ( " " WndProc
message pump . thread Form1 " " WndProc
. .message pump
standard message pump
System.Windows.Forms.Application.Run Sub Main 1 :

Module Module1
)(Public Sub Main
)System.Windows.Forms.Application.Run(Form1
End Sub
End Module

Sub Main main form


.
<< Project . Add Windows Form

Working with Forms


.System.Windows.Forms.Form
. common Form class
fields methods bugs properties events
.
source code drag-and-drop Visual Studio
.Forms Designer
form ) Properties (
. .
text.
Text Form1 .Cool Form

Mhm76

Property

Description

. Formx
)(Name
. .
.Enter
AcceptButton

AutoScroll
.
.
BackColor
BackgroundImageLayout .
BackgroundImage
AcceptButton .Esc
CancelButton
. ContextMenuStrip
ContextMenuStrip
.
.
ControlBox
.
Cursor
. .Sizable
FormBorderStyle
.
Icon
" " multiple document interface .
IsMdiContainer
.
. MDI style
KeyDown KeyPress
KeyPreview
.
F1 .
StartPosition .
Location
" " MenuStrip . MenuStrip
MainMenuStrip
.
.
MaximizeBox
.
MinimizeBox
). (.
MinimumSize

Opacity
.
ShowInTaskbar
Width. Height
Size
.
StartPosition

5
x

:
Tag

Mhm76
.

.
. System.Windows.Forms.Control
mutual . base class
Location BackColor Text caption Text
.
"Form1.Text = "This is a form caption.
"Button1.Text = "This is a button caption.

.

. "
"InitializeComponent . Form1.Designer.vb TopMost
.
Me.TopMost = True

.TopMost
"Me.Text = "The Library Project
:
) " & Me.Text MsgBox(":
. :
)(Me.Close
event handler Click event

. Access Form1.vb
Solution Explorer View Code .
.
Public Class Form1
End Class
Form1 )
. (Form1.Designer.vb . Click event forms
surface ) (Form1 Events ) Class Name (
Method Name :

:
Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Click
"Me.Text = "The Library Project
)MsgBox("The form's caption is: " & Me.Text

Mhm76
)(Me.Close
End Sub

Adding Controls

. .

Toolbox high-
quality
. pathetic low-quality - -
<< View . Toolbox

:
.1 .
.
.2 Toolbox . form

Mhm76

.3 .
ComboBox .
.4 .
. Form1.Designer.vb
InitializeComponents
. .
.
.
. .
) ( anchors
. . ComboBox
font .
. . )( Label AutoSize
False.
. )
(Smart Tag .
. .

Windows Forms
application . Toolbox web-based applications
- ASP.NET .

Icon

Control

Description

BackgroundWorker

.multithreaded
BackgroundWorker background task .

worker. RunWorkerAsync
.DoWork

Button

. Click .
DialogResult .

CheckBox

) on ( off ) on off ( other


"." checked ThreeState .
" " Checked checkboxes CheckState
.
ListBox CheckBox
. GetItemChecked
)GetItemCheckState "(" Set .
CheckBoxList ASP.NET.
.

CheckedListBox

ColorDialog

Mhm76
ShowDialog .Color

ComboBox

ContextMenuStrip

DataGridView

DateTimePicker

DomainUpDown
FolderBrowserDialog
FontDialog

GroupBox
HelpProvider

HScrollBar

ImageList

Label
LinkLabel

ListBox

ListView
MaskedTextBox

MenuStrip

MonthCalendar

NotifyIcon

NumericUpDown
OpenFileDialog

ComboBox .
. strings
ownerdraw .
"" context
.
.MenuStrip
.
.
. virtual data .

.
. .
MonthCalendar .
.
ComboBox TrackBar . warranted
.
ShowDialog .SelectedPath
.
ShowDialog . Font

. .
. Panel
.
"" Help .
F1 .
.
. VScrollBar
.
.
ListView Toolbar
.TreeView
. .
links .
LinkClicked
.
.
. ownerdraw
.
.
. details .ListViewItem

" "-
.
.
)( . ToolStripMenuItem
. .
.ContextMenuStrip
.
. . DateTimePicker
.
" " system tray
.
.
/ .
TrackBar TextBox HScrollBar VScrollBar .
.
. ShowDialog
FileName FileNames OpenFile
.

Mhm76

PageSetupDialog

.
ShowDialog PageSettings .PrinterSettings

Panel

.
.GroupBox
.
.
.ShowDialog
System.Drawing.Printing.PrintDocument .PrintDocument
.
.
.
PrintDocument .
.
. % 0%100
. Value Minimum .Maximum

PictureBox
PrintDialog

PrintDocument
PrintPreviewDialog

ProgressBar
PropertyGrid

RadioButton

ReportViewer

SaveFileDialog

SplitContainer

StatusStrip

TabControl
TextBox

Timer

.
.
.
radio .
toggle button Appearance . Checked
. RadioButton " " group context
Panel GroupBox .

.ADO.NET SQL Server .
.rdlc .
save .
.
. ShowDialog
.FileName OpenFile .
) (split ba
. Panel Orientation .
SplitContainer .
status bar
. ProgressBar
StatusStripPanel . ToolStripLabel
. )( TabPage
. .TabPage
singleline . multiline
. Text PasswordChar
UseSystemPasswordChar .
interval . milliseconds
.Interval Enabled True Tick
) (.
.

ToolStrip

toolba .
.

ToolStripContainer

MenuStrip StatusStrip ToolStrip


.

ToolTip

" " tool tip .


" " ToolTip .

.
. ) (
. HScrollBar NumericUpDown VScrollBar
.

TrackBar

TreeView
VScrollBar

. " " directory tree


. node .
.
HScrollBar

10

Mhm76

WebBrowser

.
.
Internet Explorer URL HTML
DocumentText .

Events and Delegates


WndProc
. events Events - -
.
. . event handler
.
)( .

mystery . Controls - classes


. : Click
MouseDown KeyPress . SizeChanged
) TabIndexChanged : tab-key(
BackgroundImageChanged CursorChanged
. system-level changes
SystemColorsChanged system-wide color scheme
. control panel
)Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs
Handles Button1.Click
End Sub

arguments System.Object:)( sender


System.EventArgs ) ( e

. Event . C#
:
)Public Event Click(ByVal sender As System.Object, ByVal e As System.EventArgs

)(Private Sub . Event)(


parameter- passing contract )( .event notifications
promises . sender )
(reference . Button controls ) (
. e . System.EventArgs
System.EventArgs .
.
: delegate
.

)Public Delegate Sub StandardEventDelegate(ByVal sender As System.Object, ByVal e As System.EventArgs

Public Event Click As StandardEventDelegate

firm grasp
. . RaiseEvent
. message pump
WndProc . event handlers
. WndProc .

11

Mhm76

)RaiseEvent Click(Me, New System.EventArgs


Me )( . e
)( System.EventArgs WndProc )( .
.
.
)(.
. ) ( your form class " )
(" .
source code . Form1.designer.vb
)Button1 (.
Partial Class Form1
Inherits System.Windows.Forms.Form
Friend WithEvents Button1 As System.Windows.Forms.Button
) (Private Sub InitializeComponent
Me.Button1 = New System.Windows.Forms.Button
)Me.Button1.Location = New System.Drawing.Point(48, 16
"Me.Button1.Name = "Button1
)Me.Button1.Size = New System.Drawing.Size(75, 23
Me.Button1.TabIndex = 0
"Me.Button1.Text = "Button1
Me.Button1.UseVisualStyleBackColor = True
)Me.Controls.Add(Me.Button1
End Sub
End Class

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18

InitializeComponent )(7
) 9 (14 .16
) reference type variable: (4

Friend WithEvents Button1 As System.Windows.Forms.Button

class-level fields Button1 .


WithEvents .
Form1 ).( watching and listening
: )event-to-handler connection process
(. Click event handler . Button1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


Button1.Click
End Sub

Handles . event handler


Button1.Click. Handles .
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click, Button2.Click, Button3.Click
End Sub

.
.
)Private Sub ManyEvents(ByVal sender As System.Object, ByVal e As System.EventArgs
Handles Button1.MouseDown,Button2.MouseUp
End Sub

Private Sub FirstHandler(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
End Sub
Private Sub SecondHandler(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles
Button1.Click
End Sub

12

Mhm76

events event handlers WithEvents


Handles .
event-exposing class . AddHandler
Button1 . MyHandler MyHandler .
AddHandler Button1.Click, AddressOf MyHandler

RemoveHandler .
.
.
. Delegate AddHandler Handles WithEventsRaiseEvent Event
RemoveHandler .
employee " " Fired .
class logic .

Making Forms Useful


.
"" Show " " ShowDialog .
Form2 : Show
)(Form2.Show
Show . modeless form
.
. input focus
.
Modal forms .
"" dialogs
. MsgBox . ShowDialog
. .System.Windows.Forms.DialogResult
ShowDialog .
Dim theResult As DialogResult
)(theResult = Form2.ShowDialog

Modal dialogs OK .
. (1/ (2)
)( . ) ID
( . DialogResult
ShowDialog public method
. . )
(BookEntry ) ( BookTitle )OK (ActOK )Cancel (ActCancel
.

)
( . Cancel
Public Class BookEntry
Public Function EditTitle() As String
' ----- Show the form, and return what the user enters.
If (Me.ShowDialog() = DialogResult.OK) Then
Return BookTitle.Text.Trim
Else
"" Return
End If
End Function
Private Sub ActCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActCancel.Click
"' ----- Return a blank title for "Cancel.
Me.DialogResult = DialogResult.Cancel
) (' ----- Continue with EditTitle

13

Mhm76

End Sub
Private Sub ActOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActOK.Click
' ----- Only accept valid titles.
If (Len(BookTitle.Text.Trim) = 0) Then
)"MsgBox("Please supply a valid title.
Else
Me.DialogResult = DialogResult.OK
) (' ----- Continue with EditTitle
End If
End Sub
End Class

EditTitle .
)(Dim newTitle As String = BookEntry.EditTitle
EditTitle form modally ShowDialog
. DialogResult .
EditTitle .
: . .

Project
Main " " Splash
.
. )
(.

" " Startup form" " Splash screen main splash


. .
.

Configuring the Splash Screen

) Splash.vb (Splash
. . " " PictureBox
resource strings images . Resources
. Image .
. startup.
) ( " " Splash screen .Splash
My.Application.SplashScreen .Splash . 1/100
.
" " Splash screen splash screen.
. .

14

Mhm76

bunch of database-related startup code .


. fake model
)(Startup
. My
ApplicationEvents.vb file . "
" View Application Events project properties Application
.
Namespace My
Partial Friend Class MyApplication
End Class
End Namespace

. Sleep
.

Namespace My
Partial Friend Class MyApplication
Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As
Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
' ----- Take a three-second nap.
)System.Threading.Thread.Sleep(3000
End Sub
End Class
End Namespace

)3000 (.
SQL
.blazing fast
. My.Application
. MinimumSplashScreenDisplayTime
.
.
MyApplication_Startup. .

Namespace My
Partial Friend Class MyApplication
_ Protected Overrides Function OnInitialize (ByVal commandLineArgs As System.Collections.
ObjectModel.ReadOnlyCollection(Of String)) As Boolean
' ----- Display the splash form for at least 3 seconds.
My.Application.MinimumSplashScreenDisplayTime = 3000
)Return MyBase.OnInitialize(commandLineArgs
End Function
End Class
End Namespace

.
OnInitialize
.MinimumSplashScreenDisplayTime
splash screen version
.number Load
event. Splash copyright Splash :

Public Class Splash


Private Sub Splash_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
'
With My.Application.Info.Version
_ & "ProgramVersion.Text = "Version " & .Major & ".
.Minor & " Revision " & .Revision
End With
ProgramCopyright.Text = My.Application.Info.Copyright
End Sub
End Class

15

Mhm76

Configuring the Main Form


." About "
) .
. pizzazz .(

.
Private Sub ActLibraryItem_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles ActLibraryItem.LinkClicked
' ----- Library Item mode.
TaskLibraryItem()
End Sub
Private Sub PicLibraryItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles PicLibraryItem.Click
' ----- Library Item mode.
TaskLibraryItem()
End Sub
Private Sub ActPatronRecord_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles ActPatronRecord.LinkClicked
' ----- Patron Record mode.
TaskPatronRecord()
End Sub
Private Sub PicPatronRecord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles PicPatronRecord.Click
' ----- Patron Record mode.
TaskPatronRecord()
End Sub
Private Sub ActHelp_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles ActHelp.LinkClicked
' ----- Help mode.
TaskHelp()
End Sub
Private Sub PicHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
PicHelp.Click
' ----- Help mode.
TaskHelp()
End Sub
Private Sub ActCheckOut_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles ActCheckOut.LinkClicked
' ----- Check Out mode.
TaskCheckOut()
End Sub
Private Sub PicCheckOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles PicCheckOut.Click
' ----- Check Out mode.
TaskCheckOut()
End Sub
Private Sub ActCheckIn_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles ActCheckIn.LinkClicked

16

Mhm76

' ----- Check In mode.


TaskCheckIn()
End Sub
Private Sub PicCheckIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles PicCheckIn.Click
' ----- Check In mode.
TaskCheckIn()
End Sub
Private Sub ActAdmin_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles ActAdmin.LinkClicked
' ----- Administration mode.
TaskAdmin()
End Sub
Private Sub PicAdmin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
PicAdmin.Click
' ----- Administration mode.
TaskAdmin()
End Sub
Private Sub ActProcess_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles ActProcess.LinkClicked
' ----- Daily Processing mode.
TaskProcess()
End Sub
Private Sub PicProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles PicProcess.Click
' ----- Daily Processing mode.
TaskProcess()
End Sub
Private Sub ActReports_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles ActReports.LinkClicked
' ----- Print Reports mode.
TaskReports()
End Sub
Private Sub PicReports_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles PicReports.Click
' ----- Print Reports mode.
TaskReports()
End Sub
Private Sub TaskLibraryItem()
' ----- Library item task.
' ----- Update the display.
AllPanelsInvisible()
PanelLibraryItem.Visible = True
ActLibraryItem.BackColor = SystemColors.Control
LabelSelected.Location = New System.Drawing.Point(LabelSelected.Left, PicLibraryItem.Top)
Me.AcceptButton = ActSearch
' ----- Get ready for a new search.
On Error Resume Next
SearchText.Focus()
End Sub
Private Sub TaskPatronRecord()
' ----- Patron Record mode.
' ----- Update the display.
AllPanelsInvisible()
PanelPatronRecord.Visible = True
ActPatronRecord.BackColor = SystemColors.Control
LabelSelected.Location = New System.Drawing.Point(LabelSelected.Left, PicPatronRecord.Top)
Me.AcceptButton = ActAccessPatron
End Sub
Private Sub TaskHelp()
' ----- Help mode.
' ----- Update the display.

17

Mhm76

AllPanelsInvisible()
PanelHelp.Visible = True
ActHelp.BackColor = SystemColors.Control
LabelSelected.Location = New System.Drawing.Point(LabelSelected.Left, PicHelp.Top)
Me.AcceptButton = Nothing
End Sub
Private Sub TaskCheckOut()
' ----- Check Out mode.
' ----- Update the display.
AllPanelsInvisible()
PanelCheckOut.Visible = True
ActCheckOut.BackColor = SystemColors.Control
LabelSelected.Location = New System.Drawing.Point(LabelSelected.Left, PicCheckOut.Top)
Me.AcceptButton = ActDoCheckOut
End Sub
Private Sub TaskCheckIn()
' ----- Check In mode.
' ----- Update the display.
AllPanelsInvisible()
PanelCheckIn.Visible = True
ActCheckIn.BackColor = SystemColors.Control
LabelSelected.Location = New System.Drawing.Point(LabelSelected.Left, PicCheckIn.Top)
Me.AcceptButton = ActDoCheckIn
' ----- Reset the input fields.
CheckInDate.Value = Today
CheckInDate.MaxDate = Today
CheckInDate.MinDate = DateAdd(DateInterval.Day, -6, Today)
CheckInDay.Text = "Today"
CheckInDay.BackColor = SystemColors.Control
CheckInDay.ForeColor = SystemColors.ControlText
CheckInBarcode.Text = ""
LabelCheckedIn.Visible = False
CheckedInDetail.Visible = False
CheckedInDetail.Text = "No information available."
CheckInBarcode.Focus()
End Sub
Private Sub TaskAdmin()
' ----- Administration mode.
' ----- Update the display.
AllPanelsInvisible()
PanelAdmin.Visible = True
ActAdmin.BackColor = SystemColors.Control
LabelSelected.Location = New System.Drawing.Point(LabelSelected.Left, PicAdmin.Top)
Me.AcceptButton = Nothing
End Sub
Private Sub TaskProcess()
' ----- Daily Processing mode.
' ----- Update the display.
AllPanelsInvisible()
PanelProcess.Visible = True
ActProcess.BackColor = SystemColors.Control
LabelSelected.Location = New System.Drawing.Point(LabelSelected.Left, PicProcess.Top)
Me.AcceptButton = ActDoProcess
End Sub
Private Sub TaskReports()
' ----- Print Reports mode.
' ----- Update the display.
AllPanelsInvisible()
PanelReports.Visible = True
ActReports.BackColor = SystemColors.Control

18

Mhm76

LabelSelected.Location = New System.Drawing.Point(LabelSelected.Left, PicReports.Top)


Me.AcceptButton = ActDoReports
End Sub
Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles
MyBase.Load
' ----- Prepare the form.
' ----- Adjust the various panel positions.
PanelLibraryItem.Location = New Point(TaskListBackground.Width, WelcomeBackground.Height)
PanelPatronRecord.Location = PanelLibraryItem.Location
PanelHelp.Location = PanelLibraryItem.Location
PanelCheckOut.Location = PanelLibraryItem.Location
PanelCheckIn.Location = PanelLibraryItem.Location
PanelAdmin.Location = PanelLibraryItem.Location
PanelProcess.Location = PanelLibraryItem.Location
PanelReports.Location = PanelLibraryItem.Location
PanelLibraryItem.Visible = True
ActSearchLimits.PerformClick()
End Sub
Private Sub AllPanelsInvisible()
' ----- Hide all work panels.
PanelLibraryItem.Visible = False
PanelPatronRecord.Visible = False
PanelHelp.Visible = False
PanelCheckOut.Visible = False
PanelCheckIn.Visible = False
PanelAdmin.Visible = False
PanelProcess.Visible = False
PanelReports.Visible = False
' ----- Correctly color all action labels.
ActLibraryItem.BackColor = Color.White
ActPatronRecord.BackColor = Color.White
ActHelp.BackColor = Color.White
ActCheckOut.BackColor = Color.White
ActCheckIn.BackColor = Color.White
ActAdmin.BackColor = Color.White
ActProcess.BackColor = Color.White
ActReports.BackColor = Color.White
End Sub
Private Sub SearchText_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles
SearchText.Enter
' ----- Highlight the entire text.
SearchText.SelectAll()
End Sub
Private Sub ActSearchLimits_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles ActSearchLimits.Click
' ----- Toggle the display of the media type and location fields.
If (ActSearchLimits.Top = LabelMoreLimitsTop.Top) Then
' ----- Hide the two fields.
LabelSearchMediaType.Visible = False
SearchMediaType.Visible = False
LabelSearchLocation.Visible = False
SearchLocation.Visible = False
ActSearchClear.Location = New System.Drawing.Point(ActSearchClear.Left,
SearchMediaType.Top)
ActSearchLimits.Location = New System.Drawing.Point(ActSearchLimits.Left,
SearchMediaType.Top)
ActSearch.Location = New System.Drawing.Point(ActSearch.Left, SearchMediaType.Top)
ActSearchLimits.Text = "Mor&e >>"
Else
' ----- Show the two fields.
ActSearchClear.Location = New System.Drawing.Point(ActSearchClear.Left,
LabelMoreLimitsTop.Top)
ActSearchLimits.Location = New System.Drawing.Point(ActSearchLimits.Left,
LabelMoreLimitsTop.Top)

19

Mhm76

ActSearch.Location = New System.Drawing.Point(ActSearch.Left, LabelMoreLimitsTop.Top)


LabelSearchMediaType.Visible = True
SearchMediaType.Visible = True
LabelSearchLocation.Visible = True
SearchLocation.Visible = True
ActSearchLimits.Text = "<< L&ess"
End If
End Sub
Private Sub CheckInBarcode_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles
CheckInBarcode.Enter
' ----- Highlight the entire text.
CheckInBarcode.SelectAll()
End Sub
Private Sub CheckOutBarcode_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles CheckOutBarcode.Enter
' ----- Highlight the entire text.
CheckOutBarcode.SelectAll()
End Sub
Private Sub MainForm_KeyDown(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
' ----- The keys F2 through F9 access the different sections of the form.
Select Case (e.KeyCode)
Case Keys.F2
TaskLibraryItem()
e.Handled = True
Case Keys.F3
TaskPatronRecord()
e.Handled = True
Case Keys.F4
' ----- Allow form to handle Alt+F4.
If (e.Alt = True) Then
Me.Close()
Else
TaskHelp()
End If
e.Handled = True
Case Keys.F5
TaskCheckOut()
e.Handled = True
Case Keys.F6
TaskCheckIn()
e.Handled = True
Case Keys.F7
TaskAdmin()
e.Handled = True
Case Keys.F8
TaskProcess()
e.Handled = True
Case Keys.F9
TaskReports()
e.Handled = True
End Select
End Sub

.
( ).
TaskLibraryItem PicLibraryItem .
.
TaskLibraryItem
.
. AllPanelsInvisible
SelectAll text . TextBox
TextBox Enter .
.(Private Sub SearchText_Enter) . keyboard

20

Mhm76

) (
F2 ).F9 ) Private Sub
.((MainForm_KeyDown
keystroke KeyDown Select Case.
Case . F2 . Keys.F2
.
.F4 Alt-F4
.
keystrokes . MainForm.KeyDown
KeyPreview . True .

) (Making the Program Single-Instance.


workstations
10 . .
" " single-instance application
) (.
.
single-instance application the project properties
Application " ." Make single instance application
.
. StartupNextInstance
. Startup StartupNextInstance
.ApplicationEvents.vb

. . pplicationEvents.vb .StartupNextInstance
Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As
Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles
Me.StartupNextInstance
' ----- Force the main form to the front.
)(My.Application.MainForm.Activate
End Sub

21

: .

Mhm76

Classes and Inheritance


)) (object-oriented programming (OOP . ) (OOP
System.Object basic foundation .

. .
.
Object-Oriented Programming Concepts
CPU :
. bits
. bytes
CPU MS-DOS.
. .
)( )( EXE
.file ordinary procedural languages
assembly language . OOP
The Object
object-oriented programming . object .
noun . noun )(
....
. real-world objects
DVD
. "" )
( .
)( .
: abstraction encapsulation inheritance .polymorphism
" " object )(
. Class . implementation
Abstraction
. )
(.

. )(
. .
. .
.
. software object

: .

Mhm76

.
:
.1 .
.2 ) (
.3)(
.4 ) (.
.5 .
.
. properties processing rules calculations
) properties ( . methods
)( . members of the object
Encapsulation
.
. "
" . encapsulated
.
" ." interfaces
. .
.
.
) ( keyboard display mouse
1394 USB power connector ports speakers microphone jack . power button
blackboxes .
. printer driver USB
inexplicable .
Inheritance
.
. original class . base class
. derived .
. .
override .
. animals )(
.
. mammal gestation
avian-derived class . mammal avian name
species leg count animal.)( avian animal)(
mammal . animal . generic instance animal
.
private
. .
protected . Public
).
.friend friend assembly .
Public (.
. )(.
.
Polymorphism

: .

Mhm76

.
. non-OOP language C : flag flag field" " type
"" mammal mammal-specific fields.
.
Polymorphism . " ." many forms )
( overridden mammal generic animal
)( .
derived instance
. base instance . animal
animal mammal avian . subtyping
polymorphism .
" ." Overloading Overloading ) (
. "") (
) ( ) )((.
)
(.
Interfaces and Implementation
)( ) ( )(
. ) ( .
. ) () interface ( )
( .
. implementation .
. implementation
) (.
. object ) ( instance .
distinct instance .
OOP in Visual Basic and .NET

.
.
.
.
Classes
classes structures . .
Class :
] [ Class

'
End Class
: Class . ) (.
. )
top-level namespace( assembly ) Namespace
(.
Namespace GoodGuys
Class Superhero
End Class
End Namespace
WindowsApplication1 :
WindowsApplication1.GoodGuys.Superhero

: .

Mhm76

. .
Class. End Class .
Partial :
Partial Class Superhero
End Class
: Public Private Protected
Friend . Protected Friend
) .NET Framework Class Libraries (FCLs
":." Class
Class Members
Superhero members. Class
.End Class Partial sprinkle
.
11 .
:
Variable fields
. top-level members
.
.access modifiers
Class Superhero
Public Name As String
Protected TrueIdentity As String
End Class

. . LINQ
members . properties .
Constant fields
constants . Const local
procedure-level constants literals .
Private Const BaseStrengthFactor As Integer = 1
Enumerations
. .
Private Enum GeneralSuperPower
Flight
Strength
Speed
VisionRelated
HearingRelated
WaterRelated
TemperatureRelated
ToolsAndGadgets
GreatCostume
End Enum
.
Sub methods
: subs. functions logic code
properties . Sub
.
)Public Sub DemonstrateMainPower(ByVal strengthFactor As Integer
' ----- Logic code appears here.
End Sub

: .

Mhm76

DemonstrateMainPower )(
. strengthFactor data
.arguments
Return .Exit Sub
Function methods
Function sub . return value
As . return .
Public Function GetSecretIdentity(ByVal secretPassword As String) As String
If (secretPassword = "Krypton") Then
' ----- I created a class field named
' TrueIdentity earlier.
Return TrueIdentity
Else
"GetSecretIdentity = "FORGET IT BAD GUY
End If
End Function
assignment-to-function-name style return value assignment
Exit Function .
Properties
Properties fields. methods read-write read-
only write-only " accessors "Get" ." Set :
Public WriteOnly Property SecretIdentity() As String
)Set(ByVal value As String
TrueIdentity = value
End Set
End Property
Delegates
arguments values method) (
. .
)Public Delegate Sub GenericPowerCall(ByVal strengthFactor As Integer
.
Events
)( actions . syntax
method )
(signature.
' ----- Non-delegate definition.
)Public Event PerformPower(ByVal strengthFactor As Integer
' ----- Delegate definition.
Public Event PerformPower As GenericPowerCall
Declares
Declare DLL external DLL .
.
Public Declare Function TalkToBadGuy Lib "evil.dll" (ByVal message As String) As String
) built-
.(in . DLL
" " unmanaged .evil.dll
Interfaces
Interfaces abstract classes . class templates
.
Nested types
) ( . " " child.
)( " " parent.

: .

Mhm76

Class Superhero
Class Superpower
End Class
End Class
. dont go overboard
. . .
variety . .
Shared Class Members
) ( .
.
.
Shared . Shared variable
field sub function property . shared member
instance . .
Class ClassWithSharedValue
Public Shared TheSharedValue As Integer
End Class
'...later, in some other code...
ClassWithSharedValue.TheSharedValue = 10
" " shared instances .
.
. . instance members
Overloaded Members and Optional Arguments
method Overloads .
Class House
)(Public Overloads Sub PaintHouse
' ----- Use the same color(s) as before.
End Sub
)Public Overloads Sub PaintHouse(ByVal baseColor As Color
' ----- Paint the house a solid color.
End Sub
)Public Overloads Sub PaintHouse(ByVal baseColor As Color,ByVal trimColor As Color
' ----- Paint using a main and a trim color.
End Sub
)Public Overloads Sub PaintHouse(ByVal baseColor As Color,ByVal coats As Integer
' ----- Possibly paint with many coats, of paint
' that is, not of fabric.
End Sub
End Class
PaintHouse .
signature . .
: coats
)Public Overloads Sub PaintHouse(ByVal whichColor As Color
Public Overloads Sub PaintHouse(ByVal baseColor As Color, ByVal coats As Integer)
optional argument .coats
Public Overloads Sub PaintHouse(ByVal baseColor As Color, Optional ByVal coats As Integer
)= 1
End Sub
Optional
. coats
. default value
. coats 1 . = 1
Inheritance

: .

Mhm76

)(-).( ancestor-descendant base


class derived class .Inherits
Class Animal
' ----- Animal class members go here.
End Class
Class Mammal
Inherits Animal
' ----- All members of Animal are automatically
' part of Mammal. Add additional Mammal
' features here.
End Class
Inherits . .
Partial Inherits .
Inherits ).
(.
.
overrides . (1/
Overridable)(2 .Overrides
Class Animal
)(Public Overridable Sub Speak
)"MsgBox("Grrrr.
End Sub
End Class
Class Canine
Inherits Animal
)(Public Overrides Sub Speak
)"MsgBox("Bark.
End Sub
End Class
Animal .Speak
" " Canine . attribute
. NotOverridable
nonoverridable Overridable
.
Class Canine
Inherits Animal
)(Public NotOverridable Overrides Sub Speak
)"MsgBox("Bark.
End Sub
End Class

. MustOverride .
Class Animal
)(Public MustOverride Sub DefenseTactic
End Class
MustOverride ). DefenseTactic End
.(Sub . deficiency
Animal DefenseTactic .
" ." MustOverride . MustInherit
Public MustInherit Class Animal
)(Public MustOverride Sub DefenseTactic
End Class

: .

Mhm76

Animal
. ) Animal ( reference type Animal-derived class
) (.
Dim zooMember As Animal
Dim monkey As New Simian ' Simian is derived from Animal
zooMember = monkey
.
)( )( . .
.NotInheritable
NotInheritable Class Animal
End Class
NotInheritable ).
noninheritable (.
Inherits MustInherit NotInheritable Overrides Overridable
NotOverridable . : inimitable
.Shadows .
override function String
Integer return code . .
" " ).( grabs .
PeanutButter ) constant enumeration nested
(class .PeanutButter
Class Food
)(Public Sub PeanutButter
End Sub
End Class
Class Snack
Inherits Food
Public Shadows PeanutButter As String
"' Hey, it's not even a "Sub
End Class
Shadows Snack .
Creating Instances of Classes
: . designing classes : . deriving classes : creating class
.instances New instances .
Dim myPet As Animal = New Animal
' ----- Or...
Dim myPet As New Animal
' ----- Or...
Dim myPet As Animal
myPet = New Animal
. " " dot
"myPet.Name = "Fido
) ( .
Dim myPet As Animal
Dim myDog As Canine
myDog = New Canine
"myDog.Name = "Fido
myPet = myDog ' Since Canine derives from Animal
"MsgBox(myPet.Name) ' Displays "Fido
Option Strict) On( narrowing
) conversions (. ) CType
( .
)myDog = CType(myPet, Canine

: .

Mhm76

. .
) ( ) (qualification
.Me
Class Animal
Public Name As String
)(Public Sub DisplayName
' ----- Either of these lines will work.
)MsgBox(Name
)MsgBox(Me.Name
End Sub
End Class
MyClass Me
) (. "" Canine Animal
Me " " Canine MyClass . Animal
MyClass .
.
MyBase . .
Class5 Class4 Class3 Class2 .Class1
. System.Object MyBase Class5 . Class4 .
MyBase.MemberName MemberName Class4 MyBase
.MemberName
Class Animal
)(Public Overridable Sub ObtainLicense
' ----- Perform Animal-specific licensing code.
End Sub
End Class
Class Canine
Inherits Animal
)(Public Overrides Sub ObtainLicense
' ----- Perform Canine-specific licensing code, then...
MyBase.ObtainLicense() ' Calls code from Animal class
End Sub
End Class
Constructors and Destructors
: . constructor
dictated destructor garbage collection .
explicit . implicit
minimal constructor-level activities reserving memory space instance
variable field. .
. default constructor
.
Class Animal
Public Name As String
)(Public Sub New
' ----- Every animal must have some name.
"Name = "John Doe of the Jungle
End Sub
End Class
constructor Animal . Name String
reference types "." Nothing
.
" " New argument signature.
Class Animal
Public Name As String

: .

Mhm76
)(Public Sub New
' ----- Every animal must have some name.
"Name = "John Doe of the Jungle
End Sub
)Public Sub New(ByVal startingName As String
' ----- Use the caller-supplied name.
Name = startingName
End Sub
)Public Sub New(ByVal startingCode As Integer
' ----- Build a name from a numeric code.
)Name = "Animal Number " & CStr(startingCode
End Sub
End Class

:
)MsgBox((New Animal).Name
"' Displays "John Doe of the Jungle
)MsgBox((New Animal("Fido")).Name
"' Displays "Fido
)MsgBox((New Animal(5)).Name
"' Displays "Animal Number 5
.
System.Object
.
Class Canine
Inherits Animal
)(Public Sub New
) (MyBase.New() ' Calls Animal.New
' ----- Now add other code.
End Sub
End Class
Killing .
.
.
. . .
myDog = Nothing
.
myDog = New Canine
"myDog.Name = "Fido
myDog = New Canine ' Sorry Fido, you're gone
. Finalize .
Finalize Protected System.Object override
.
Class Animal
)(Protected Overrides Sub Finalize
' ----- Cleanup code goes here. Be sure to call the
' base class's Finalize method.
)(MyBase.Finalize
End Sub
End Class
Finalize )( . garbage collection
) (. ) ( .
.
30 . .
. cleanup .
). (.
).IDisposable (.

10

: .

Mhm76

Class Animal
Implements IDisposable
)(Protected Overrides Sub Finalize
' ----- Cleanup code goes here. Be sure to call the
' base class's Finalize method.
)(MyBase.Finalize
End Sub
Public Overloads Sub Dispose() Implements IDisposable.Dispose
' ----- Put cleanup code here. Also make these calls.
MyBase.Dispose() ' Only if base class is disposable.
)System.GC.SuppressFinalize(Me
End Sub
End Class
SuppressFinalize " garbage collector Finalize ".
Dispose .
)( . . Using
.
Using myPet As New Animal
' ----- Code here uses myPet.
End Using
' ----- At this point, myPet is destroyed, and Dispose is
' called automatically by the End Using statement.
Interfaces
MustOverride MustInherit .
MustOverride
.interface Interfaces abstract classes definitions
).implementation MustOverride abstract
.(class contract agreement )( .
. interface )( By convention .
Interface IBuilding
Function FloorArea() As Double
)(Sub AlterExterior
End Interface
.
.access modifiers .
properties events interfaces classes structures
interfaces interfaces) ( Inherits .
. Implements
.
Class House
Implements IBuilding
Public Function FloorArea() As Double Implements IBuilding.FloorArea
' ----- Add implementation here.
End Function
Public Sub PaintHouse() Implements IBuilding.AlterExterior
' ----- Add implementation here.
End Sub
End Class
)
(. FloorArea AlterExterior
.PaintHouse .
Dim someHouse As New House
Dim someBuilding As IBuilding
someBuilding = someHouse
) (someBuilding.AlterExterior() ' Calls someHouse.PaintHouse

11

: .

Mhm76

.
Class House
Implements IBuilding, IDisposable
.
Public Sub PaintHouse() Implements IBuilding.AlterExterior, IContractor.DoWork
End Sub
generic
. House Animal Superhero logic
)( . IDisposable
.
Modules and Structures
: structures . modules
.
. .
Shared :
. . .
" " Modules
)(.
Friend Module GenericDataAndCode
' ----- Application-global constant.
"Public Const AllDigits As String = "0123456789
' ----- Application-global function.
Public Function GetEmbeddedDigits(ByVal sourceString As String) As String
End Function
End Module
. .
.
)( qualification).
( Private
Structures . modules .
) System.ValueType .( System.Object
Integer syntax .
) ( . constructor
destructors .
.
.
Partial Methods
.
. code generators
. partial Form class
: .
Partial methods 2008
. )(
.
" " .
(1/ unimplemented half)(2 implemented half. optional
. .
Partial.
)(Partial Private Sub ImplementIfYouDare
End Sub

12

: .

Mhm76

sub functions . Private


ByVal . ByRef
implemented half ) ( "" Partial
.jaws
)(Private Sub ImplementIfYouDare
)"MsgBox("I did it, so there.
End Sub
.
Animal . auto-generated side.
Partial Class Animal
)(Public Sub Move
' ----- Interesting movement code, then...
)(MoveSideEffects
End Sub
)(Partial Private Sub MoveSideEffects
End Sub
End Class
moves side effects .
.
. .

. :
Partial Class Animal
)(Public Sub Move
' ----- Interesting movement code, then...
End Sub
End Class
MoveSideEffects Move .
) (Related Issues

.
MsgBox
" ." MsgBox
"Microsoft.VisualBasic " MsgBox carryover MsgBox
. ..
. MsgBoxResult :
= Public Function MsgBox(ByVal Prompt As Object, Optional ByVal Buttons As MsgBoxStyle
MsgBoxStyle.OkOnly,Optional ByVal Title As Object = Nothing) As MsgBoxResult
Prompt string Buttons buttons icons
Title .
:
Dim result As MsgBoxResult = MsgBox("It's safe to click; the computer won't explode.",
)"MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, "Click Something

13

: .

Mhm76

MsgBox . Microsoft.VisualBasic
. C# . MessageBox.Show
MsgBox .
Using DoEvents
.
. defers .
" ) )((" .
. patient
) ( )( Refresh .
)( "" ) (.
.DoEvents
" )" paint .( screen update DoEvents My
.
)(My.Application.DoEvents
DoEvents .

.
) ParamArray Arguments ( ParamArray
optional arguments .


parameter array argument .ParamArray

. ParamArray .
Public Function CalculateAverage(ByVal ParamArray sourceData() As Decimal) As Decimal
' ----- Calculate the average for a set of numbers.
Dim singleValue As Decimal
@Dim runningTotal As Decimal = 0
If (sourceData.GetLength(0) = 0) Then
@Return 0
Else
For Each singleValue In sourceData
runningTotal += singleValue
Next singleValue
)Return runningTotal / sourceData.GetLength(0
End If
End Function
CalculateAverage . decimal
MsgBox(CalculateAverage(1, 2, 3, 4, 5)) ' Displays: 3

(1/ ListBox ComboBox


)(2 .

Supporting List and Combo Boxes

6 ListBox ComboBox : List


) ( ) ItemData -32 (.
. ItemData
.
)"cboMonth.AddItem("January
cboMonth.ItemData(cboMonth.NewIndex) = 1
)"cboMonth.AddItem("February
cboMonth.ItemData(cboMonth.NewIndex) = 2

14

: .

Mhm76
...

)"cboMonth.AddItem("December
cboMonth.ItemData(cboMonth.NewIndex) = 12
ID .
)nMonth = cboMonth.ItemData(cboMonth.ListIndex
List ItemData ListBox
.ComboBox :. Items :
. . )( System.Object
. collection ) (
. list
ListBox " " ToString
. ToString System.Object override . ListBox
" " DisplayMember .
. ListBox .
Public Class Form1
)Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs
Handles MyBase.Load
)ListBox1.Items.Add(1
)"ListBox1.Items.Add("Easy
)ListBox1.Items.Add(#5/3/2006#
End Sub
End Class
.

ItemData ListBox ValueMember identifier


. Items .ValueMember
Items .
.6 Items
.
ListBox ComboBox .
ID . .
. .
. <<Project Add
.Class ListItemData.vb . Add .
Public Class ListItemData
End Class

. DisplayMember
ToString initialization .
:
Public Class ListItemData
Public ItemText As String
Public ItemData As Integer
)Public Sub New(ByVal displayText As String, ByVal itemID As Integer

15

: .

Mhm76
' ----- Initialize the record.
ItemText = displayText
ItemData = itemID
End Sub
Public Overrides Function ToString() As String
' ----- Display the basic item text.
Return ItemText
End Function
Public Overrides Function Equals(ByVal obj As Object) As Boolean
' ----- Allow IndexOf() and Contains() searches by ItemData.
If (TypeOf obj Is Integer) Then
)Return CBool(CInt(obj) = ItemData
Else
)Return MyBase.Equals(obj
End If
End Function
End Class

ListBox .
ListBox1.Items.Add(New ListItemData("Item Text", 25))
Equals ) ( .
Items IndexOf .
ListItemData . ListBox Equals True
Integer value .
)Dim itemPosition As Integer = SomeListBox.Items.IndexOf(5

Editing Code Tables


ComboBox

. ) (Code
CodeCopyStatus )( collections.

Field
ID
FullName

Description
Type
Primarykey;automaticallyassigned.Required. LongAuto
. .
Nameofthisstatusentry.Required.
) Text(50
. .

ID -
. ) ( derived versions
.
:")" summary (")" detail
(. "
."summary " ." detail

The Generic Detail Form


) << Project ( New Windows Form BaseCodeForm.vb
:
Setting
Property
)(Name
ControlBox
FormBorderStyle
ShowInTaskbar
Size
StartPosition
Text

BaseCodeForm
False
FixedDialog
False
406, 173
CenterScreen
Code Form

) << View.( Code


instantiation .MustInherit
Public MustInherit Class BaseCodeForm

16

. :

Mhm76
End Class

.
MustOverride .
.
Public Overridable Function AddRecord() As Integer
' ----- Prompt to add a new record. Return the ID
'
when added, or -1 if cancelled.
Return -1
End Function
Public Overridable Function DeleteRecord(ByVal recordID As Integer) As Boolean
' ----- Prompt the user to delete a record.
'
Return True on delete.
Return False
End Function
Public Overridable Function EditRecord(ByVal recordID As Integer) As Integer
' ----- Prompt the user to edit the record. Return the
'
record's ID if saved, or -1 on cancel.
Return -1
End Function
. "summary "ListBox " detail "

. . :

' ----- Fill a ListBox control with existing records.


Public MustOverride Sub FillListWithRecords( ByRef destList As ListBox, ByRef exceededMatches
As Boolean)
' ----- Return the formatted name of a single record.
Public MustOverride Function FormatRecordName(ByVal recordID As Integer) As String

." "" "


' ----- Return a description
Public MustOverride Function
' ----- Return the title-bar
Public MustOverride Function

of this editor.
GetEditDescription() As String
text for this editor.
GetEditTitle() As String

. ) (
. " summary "
.MustOverride
Public Overridable Sub SearchForRecord(ByRef destList As ListBox, ByRef exceededMatches As Boolean)
' ----- Prompt the user to search for a record.
Return
End Sub

." "
.
Public Overridable Function CanUserAdd() As Boolean
' ----- Check the security of current user to see
'
if adding is allowed.
Return False
End Function
Public Overridable Function CanUserEdit() As Boolean
' ----- Check the security of the user to see
'
if editing is allowed.
Return False
End Function
Public Overridable Function CanUserDelete() As Boolean
' ----- Check the security of the user to see
'
if deleting is allowed.
Return False
End Function
Public Overridable Function UsesSearch() As Boolean
' ----- Does this editor support searching?
Return False
End Function

. generic detail form


.code tables

The Generic Summary Form. ""

17

. :

Mhm76

)( .
ListEditRecords.vb . )(
.
"" " "" "" ". ListBox
.() : .

:
Public Class ListEditRecordsvb
Private DetailEditor As Library.BaseCodeForm
Public Sub ManageRecords(ByRef UseDetail As Library.BaseCodeForm)
' ----- Set up the form for use with this code set.
Dim exceededMatches As Boolean
DetailEditor = UseDetail
RecordsTitle.Text = DetailEditor.GetEditTitle()
RecordsInfo.Text = DetailEditor.GetEditDescription()
Me.Text = DetailEditor.GetEditTitle()
ActAdd.Visible = DetailEditor.CanUserAdd()
ActEdit.Visible = DetailEditor.CanUserEdit()
ActDelete.Visible = DetailEditor.CanUserDelete()
ActLookup.Visible = DetailEditor.UsesSearch()
DetailEditor.FillListWithRecords(RecordsList, exceededMatches)
RefreshItemCount(exceededMatches)
Me.ShowDialog()
End Sub
Private Sub RefreshButtons()
' ----- Update the buttons as needed.
ActEdit.Enabled = CBool(RecordsList.SelectedIndex <> -1)
ActDelete.Enabled = CBool(RecordsList.SelectedIndex <> -1)
End Sub
Private Sub RefreshItemCount(ByVal exceededMatches As Boolean)
If (exceededMatches) Then
ResultCount.Text = "Results limited to first " & _
RecordsList.Items.Count & " items"
ElseIf (RecordsList.Items.Count = 1) Then
ResultCount.Text = "1 record displayed"
Else
ResultCount.Text = RecordsList.Items.Count & " records displayed"
End If
End Sub
Private Sub ActClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActClose.Click

18

Mhm76

. :

' ----- Close the form.


DetailEditor.Close()
DetailEditor = Nothing
Me.Close()
End Sub
Private Sub ActAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActAdd.Click
' ----- Let the user add a record.
Dim newID As Integer
Dim newPosition As Integer
' ----- Prompt the user.
newID = DetailEditor.AddRecord()
If (newID = -1) Then Return
' ----- Add this record to the list.
newPosition = RecordsList.Items.Add((New Library.ListItemData( _
DetailEditor.FormatRecordName(newID), newID)))
RecordsList.SelectedIndex = newPosition
RefreshButtons()
RefreshItemCount(False)
End Sub
Private Sub ActEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActEdit.Click
' ----- Let the user edit a record.
Dim newID As Integer
Dim listItem As Library.ListItemData
' ----- Retrieve the item to edit.
If (RecordsList.SelectedIndex = -1) Then Return
listItem = CType(RecordsList.SelectedItem, Library.ListItemData)
' ----- Prompt the user.
newID = DetailEditor.EditRecord(listItem.ItemData)
If (newID = -1) Then Return
' ----- Modify the text of this item.
listItem.ItemText = DetailEditor.FormatRecordName(newID)
RecordsList.Items(RecordsList.SelectedIndex) = listItem
RefreshItemCount(False)
End Sub
Private Sub ActDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActDelete.Click
' ----- Let the user edit a record.
Dim listItem As Library.ListItemData
' ----- Retrieve the item to edit.
If (RecordsList.SelectedIndex = -1) Then Return
listItem = CType(RecordsList.SelectedItem, Library.ListItemData)
' ----- Prompt the user.
If (DetailEditor.DeleteRecord(listItem.ItemData) = False) Then Return
' ----- Remove this item from the display.
RecordsList.Items.RemoveAt(RecordsList.SelectedIndex)
RefreshButtons()
RefreshItemCount(False)
End Sub
Private Sub ActLookup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
ActLookup.Click
' ----- Prompt for user limitation of the displayed items.
Dim exceededMatches As Boolean
DetailEditor.SearchForRecord(RecordsList, exceededMatches)
RefreshButtons()
RefreshItemCount(exceededMatches)
End Sub
Private Sub RecordsList_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
RecordsList.Click

19

: .

Mhm76

' ----- Enable controls as needed.


)(RefreshButtons
End Sub
)Private Sub RecordsList_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs
Handles RecordsList.DoubleClick
' ----- Same as the edit button.
)(If (ActEdit.Visible = True) Then ActEdit.PerformClick
End Sub
Private Sub RecordsList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles RecordsList.SelectedIndexChanged
' ----- Enable controls as needed.
)(RefreshButtons
End Sub
@@End Class

"" ) (.

Private DetailEditor As Library.BaseCodeForm


.BaseCodeForm . ManageRecords
)Public Sub ManageRecords(ByRef UseDetail As Library.BaseCodeForm
ManageRecords BaseCodeForm.

DetailEditor "." summary


" CanUserAdd " detail Boolean " " Visible " ." ActAdd
FillListWithRecords "" ListBox .
Me.ShowDialog"".
"" "" .DetailEditor
"" .AddRecord ""
.

Private Sub ActAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


ActAdd.Click
' ----- Let the user add a record.
Dim newID As Integer
Dim newPosition As Integer
' ----- Prompt the user.
)(newID = DetailEditor.AddRecord
If (newID = -1) Then Return
' ----- Add this record to the list.
_ (newPosition = RecordsList.Items.Add((New Library.ListItemData
)))DetailEditor.FormatRecordName(newID), newID
RecordsList.SelectedIndex = newPosition
)(RefreshButtons
)RefreshItemCount(False
End Sub

"" ) (
. .
.

20

: .

Mhm76

Functional Programming
: )( Lambda . error handling
.
functional programming )(
willy-nilly .
) ( lambda 2008
.

Lambda Expressions
) lambda calculus (-calculus 1930s Alonzo
Church .
rationale functions arguments return values .
lambda .

. .
BASIC . BASIC PLUS DEF
.
)DEF(SQR(X) = X * X
For I = 1 To 5
))Print(I, SQR(I
Next I
End

100:
110:
120:
130:
140:

)( 100 . 120 :
1 1
24
39
4 16
5 25

. :
Dim sqr As Func(Of Integer, Integer) = Function(x As Integer) x * x
For i As Integer = 1 To 5

))MsgBox(i & vbTab & sqr(i


Next i

:
Function(x As Integer) x * x
Function passed-in .
x * x . .
.Return .

definition return result .


)Dim sqr As Func(Of Integer, Integer
. Func
Integer . Integer
. Boolean
)(Public Sub TestNumber
Dim IsEven As Func(Of Integer, Boolean) = Function(x As Integer) (x Mod 2) = 0
))MsgBox("Is 5 Even? " & IsEven(5
End Sub

" 5 2" )
( .
Private Function HiddenFunction1(ByVal x As Integer) As Boolean
Return (x Mod 2) = 0
End Function
Private Delegate Function HiddenDelegate1(ByVal x As Integer) As Boolean
)(Public Sub TestNumber
Dim IsEven As HiddenDelegate1 = AddressOf HiddenFunction1
))MsgBox("Is 5 Even? " & IsEven(5
End Sub
IsEven )(HiddenFunction1 ).(HiddenDelegate1


2008 .
delegate-referenced function .

Mhm76
: .
2008 ).(17
)( ) (. ) (
.

Implying Lambdas
. - function-
delegate )(. type inference .

. . .
Dim mult As Func(Of Integer, Integer, Integer) = Function(x As Integer, y As Integer) x * y
MsgBox(mult(5, 6)) ' Displays 30

: . laissez faire
.
Dim mult = Function(x As Integer, y As Integer) x * y
. Integer . mult )(
. mult ) Function(Integer, Integer) As Integer (. )(.

" "Option Infe" " On ) Project properties


(. mult .
Dim mult = Function(x, y) x * y

Object . Integer "


" Option Strict ")" On ( As.

Expression Trees
" " operands . operators
.
Dim calculateIt = Function(x, y, z) (x * y) ^ z

calculateIt .

.
.System.Linq.Expressions .
.
Complex Lambdas
For...Next
. . mult . MultiplyIt
)(Private Sub DoSomeMultiplication
Dim mult = Function(x As Integer, y As Integer) MultiplyIt(x, y) + 10
MsgBox(mult(5, 6)) ' Displays 40
End Sub
Public Function MultiplyIt(ByVal x As Integer, ByVal y As Integer) As Integer
Return x * y
End Function

. .
. )( . .3

: .

Mhm76
Dim three = Function() 3

:
Dim mult1 = Function(x As Integer, y As Integer) x * y

.
Dim mult2 = Function(x As Integer) Function(y As Integer) x * y

mult2 mult1 x. y mult1 x y .


)Function(x As Integer x . " "5 x
mult2
Function(y As Integer) 5 * y:
. .
5 y . mult2
x y .
))MsgBox(mult2(5)(6

) (6 . y .
) mult2(5 .
)(.
. LINQ 17
LINQ ) (.

)( Variable Lifting
.
)(Private Sub NameMyChild
)(Dim nameLogic = GetChildNamingLogic
MsgBox(nameLogic("John")) ' Displays: Johnson
End Sub
)Private Function GetChildNamingLogic() As Func(Of String, String
"Dim nameSuffix As String = "son
Dim newLogic = Function(baseName As String) baseName & nameSuffix
Return newLogic
End Function
GetChildNamingLogic . NameMyChild John .
. nameSuffix . GetChildNamingLogic
. MsgBox nameSuffix . nameSuffix
. . variable lifting nameSuffix )(
.GetChildNamingLogic . wider scope

):( closure class


.
.
)(Private Sub NameMyChild
)(Dim nameLogic = GetChildNamingLogic
MsgBox(nameLogic("John")) ' Displays: Johnson
End Sub
Public Class GeneratedClosureClass
"Public nameSuffix As String = "son
Public newLogic As Func(Of String, String) = Function(baseName As String) baseName & Me.nameSuffix

End Class
)Private Function GetChildNamingLogic() As Func(Of String, String
Dim localClosure As New GeneratedClosureClass
"localClosure.nameSuffix = "son
Return localClosure.newLogic
End Function

- . .
)( .

Object Initializers
object properties .
Dim newHire As New Employee
"newHire.Name = "John Doe
newHire.HireDate = #2/27/2008#
newHire.Salary = 50000@

With .
Dim newHire As New Employee
With newHire
".Name = "John Doe
.HireDate = #2/27/2008#

: .

Mhm76
@.Salary = 50000
End With

2008 syntax ) ( New . .With


}@Dim newHire As New Employee With {.Name = "John Doe", .HireDate = #2/27/2008#, .Salary = 50000

Error Handling in Visual Basic


.

. %50
" ." bloatware

The Nature of Errors in Visual Basic


:

Compile-time errors

)( .
. .
Option Strict" " On .
: Option Strict On ' -----
&Dim bigData As Long = 5
Dim smallData As Integer
' ----- The next line will not compile.
smallData = bigData

2008 . " " blue squiggle


)( .

Runtime errors

)( )(.
. :
Public Function GetNumber() As Integer
' ----- Prompt the user for a number.
' Return zero if the user clicks Cancel.
Dim useAmount As String
' ----- InputBox returns a string with whatever
' the user types in.
)"useAmount = InputBox("Enter number.
If (IsNumeric(useAmount) = True) Then
' ----- Convert to an integer and return it.
)Return CInt(useAmount
Else
' ----- Invalid data. Return zero.
Return 0
End If
End Function

. .
IsNumeric )( . 0
.

Mhm76
: .
""342304923940234 IsNumeric
.

)( GetNumber
.

Logic errors

. .
.
.
.
. compile-time errors
2008 . compile-time errors
:
. DVD .
.
: )
( ) (.
.
.
.
: unstructured error handling structured error handling
. unhandled error handling - -
.

Unstructured Error Handling


.1990
.
- .
. "
." " " ." error handler
)(Public Sub ErrorProneRoutine
' ----- Any code you put here before enabling the
' error handler should be pretty resistant to
' runtime errors.
' ----- Turn on the error handler.
On Error GoTo ErrorHandler
' ----- More code here with the risk of runtime errors.
' When all logic is complete, exit the routine.
Return
ErrorHandler:
' ----- When an error occurs, the code temporarily jumps
' down here, where you can deal with it. When you're
' finished, call this statement:
Resume
' ----- which will jump back to the code that caused
' the error. The "Resume" statement has a few
' variations available. If you don't want to go
' back to main code, but just want to get out of
' this routine as quickly as possible, call:
Return
End Sub

Mhm76
: .
On Error . . global Err object
) ) (( .
.
On Error . )(.
.
If...Then...Else Err. global Err object
ErrorHandler:
If (Err.Number = 5) Then
' ----- Handle error-code-5 issues here.


. .

.

)(Public Sub DoSomeWork


On Error GoTo ErrorHandler
' ----- Logic code goes here.
Return
ErrorHandler:
)MsgBox("An error occurred in 'DoTheWork':" & Err.Description
Resume Next
End Sub
) Resume Next (Resume
. )" "( Resume some_other_label

Disabling Error Handling


On Error GoTo . On Error GoTo
. )(
turn off )(.
On Error GoTo 0:

Ignoring Errors
. :
ErrorHandler:
Resume Next

. .
On Error Resume Next

. ) ( .
.

Structured Error Handling


.
2002 .

structured error handling
.
Try...Catch...Finally .
Try
' ----- Add error-prone code here.
Catch ex As Exception
' ----- Error-handling code here.
Finally
' ----- Cleanup code goes here.
End Try

)( The Try Clause


Try . Try
.
Try

: .

Mhm76
)My.Computer.FileSystem.RenameFile(existingFile, newName
Catch ex As Exception

Try. Try...End Try .


(1/
)(2 .

)( The Catch Clause


Catch . Try
. Catch .
Catch ex As ErrorClass

ex . Catch
.
ErrorClass : exception . System.Exception
.System.Exception Try...End Try" object-oriented error
" processing .
System.Exception . System.DivideByZeroException )(
.0
Try
result = firstNumber / secondNumber
Catch ex As System.DivideByZeroException
)"MsgBox("Divide by zero error.
Catch ex As System.OverflowException
)"MsgBox("Divide resulting in an overflow.
Catch ex As System.Exception
)"MsgBox("Some other error occurred.
End Try
Catch . Catch
System.Exception Catch Try
. System.Exception Catch exceptions . Catch
On Error Resume Next Try .
Finally .Try

)( The Finally Clause


Finally Try " ". Try Finally
Catch ) (. Finally . Try Return
Try Finally )(. Exit Try Try
Finally . Try Finally .
Finally Finally . Finally
Catch .Try

Unhandled Errors
.
.
. . :
!
. :
)(Private Sub Level1
On Error GoTo ErrorHandler
)(Level2
Return
ErrorHandler:
)"MsgBox("Error Handled.
Resume Next
End Sub
)(Private Sub Level2
)(Level3
End Sub
)(Private Sub Level3
' ----- The Err.Raise method forces an
' unstructured-style error.
)Err.Raise(1

: .

Mhm76
End Sub

13 . 13
12 . . 12
11 . . ErrorHandler .
11 )
( . Disappointment
" " catchall
. " " Enable application framework
Application . project properties " View Application
" Events .") (" MyApplication Events Class Name
UnhandledException . Method Name :
Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As
Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
End Sub
. e . System.Exception
e.ExitApplication Boolean .

.
)( . )(
abandoned .

Managing Errors
.

Generating Errors
.
Framework Class Libraries (FCLs) . .
0100 .
Private StoredPercent As Integer
Public Property InEffectPercent() As Integer
Get
Return StoredPercent
End Get
)Set(ByVal value As Integer
StoredPercent = value
End Set
End Property

847 847 .
If accessor Set .
.
)Set(ByVal value As Integer
If (value < 0) Or (value > 100) Then
Throw New ArgumentOutOfRangeException("value",value, "The allowed range is
)"from 0 to 100.
Else
StoredPercent = value
End If
End Set
InEffectPercent 0-to-100 On Error

.Try...Catch Throw System.Exception


.
Throw .Err.Raise 6
. Throw .

Mixing Error-Handling Methods


.
On Error Try...Catch...Finally . On Error Try...Catch...Finally
.
"
".

Mhm76
: .
On Error .
OOP .
On Error .
. ) (Err.GetException
.
C# .
. esoteric )
( 99.9 .
. .
.
On Error Resume Next
)(RefreshPart1
)(RefreshPart2
)(RefreshPart3
RefreshPart1

.
RefreshPart2 . . . .
.

Try

)(RefreshPart1
Catch
End Try
Try
)(RefreshPart2
Catch
End Try
Try
)(RefreshPart3
Catch
End Try

. . On Error .
.

System.Exception. The System.Exception Class


System.Exception . structured exceptions .
. ) ( in anticipation . Throw
. System.Exception
Object member

Description

.
Data
.
HelpLink
.
InnerException
.
Message
.
Source
.
StackTrace
.
TargetSite
System.Exception .

Err The Err Object


Err .
. ) ( . .Err
Object member
Clear
Erl property
Description property
HelpContext property
LastDLLError
Number property

Description

.
. . Raise .
. .
.0
.
. HelpFile
.
.
.

Mhm76
: .
.
Raise method
Err . Raise
.
.
Source property

The Debug Object


)6( " Immediate
" Window .
)"Debug.Print("Reached point G in code

Debug . Print WriteLine Write


carriage return .
)"Debug.WriteLine("Reached point G in code

) WriteLine ( " " listeners )( . Debug


. Debug .
.
) My.Application.Log My.Log .( ASP.NET
Debug . registered listeners )
( Debug logfile . applications assembly

Other Visual Basic Error Features


:
) ErrorToString function( ErrorToString
numeric system error ErrorToString(10) "
" This array is fixed or temporarily locked .

) IsError function( IsError

) System.Exception (

Project


. Error-handling
. .
.

General Error Handler


.
(1/ (2) (3)
.
.
)(.
.
.
General.vb .General
)Public Sub GeneralError(ByVal routineName As String, ByVal theError As System.Exception
' ----- Report an error to the user.
On Error Resume Next
'" & routineName & "':" & vbCrLf & vbCrLf & theError.Message, "(MsgBox
)MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, ProgramTitle
)My.Application.Log.WriteException(theError
End Sub

. .GeneralError
)(Public Sub SomeRoutine
On Error GoTo ErrorHandler
' ----- Lots of code here.
Return
ErrorHandler:
))(GeneralError("SomeRoutine", Err.GetException
Resume Next
End Sub

:
Try

' ----- Troubling code here.


Catch ex As System.Exception

10

: .

Mhm76
)GeneralError("SomeRoutine", ex
End Try

GeneralError: . .
) log listener( .
.GeneralError
)My.Application.Log.WriteException(theError

.GeneralError
On Error Resume Next

Unhandled Error Capture.


.
" " Show All Files ApplicationEvents.vb .MyApplication

Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As


Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
' ----- Record the error, and keep running.
e.ExitApplication = False
)GeneralError("Unhandled Exception", e.Exception
End Sub
GeneralError .

11

Mhm76

ADO.NET

:
ODBC. ODBCOpen Database Connectivity.
ISAM. ISAMIndexed Sequential Access Method.
DAO. Data Access Objects.
RDO. Remote Data Objects
OLE . Object Linking and Embedding for Databases
ADO. ActiveX Data Objects .
) (. .
. interfaces .
" "
. .
ADO . . ADO
.
?What Is ADO.NET

.
)( " " SELECT
.
System.Data ) ( subordinate
)( System.Data.SqlClient SQL Server databases
System.Data.OracleClient Oracle RDBMSsystems
.
ADO.NET . disconnected data experience desktop
applications . .
.
)( .
fulfills .
. :
SELECT * FROM Customer WHERE BalanceDue > 0
)(
)(2
. .
)( frowns upon . . disconnected nature
.
)" (" pessimistic concurrency . )(
.
Overview of ADO.NET
: providers . data set .
) (.
.
.

Providers

database systems SQL Server Oracle


.. / TCP/IP port
. authenticated . 1990
) )( ODBC (
.. .ODBC
) OLE DB ( .ActiveX
OLE DB ODBC ODBC .OLE DB

Mhm76

ODBC OLE DB libraries providers .


ADO.NET .
OLE DB .
:

The Connection object

. .
)( .

The Command object

SQL . .

The DataReader object

.
" " SELECT .

The DataAdapter object

. ) SELECT
INSERT UPDATE (DELETE ) (.

. :
.1 .
.2 .
.3 .
.4 DataReader )( " " DataAdapter
" ) DataSet "( DataTable .
.5 .

.System.Data.SqlClient
: 2005 " " User Instances 2005 .
low-privilege administrator
. " )" ClickOnce
25 ( . administrator .
" " " " Working with User Instances . MSDN
. MSDN

Data Sets

scan DataReader data set


. ) ( generic disconnected view
. ) ( )
(OLE DB .
: data sets

The DataSet object

. foreign-key
relationships fields . tables internals unfathomable mystery
DataSet .XML .

The DataTable object

table DataSet Data Table Tables collection


. DataSet . DataSet
DataTable . DataSet DataTable DataColumn
DataRow field values .

The DataRelation object

DataRelation DataSets Relations collection


field-level relationships constraints . DataTable
data sets providers
. " " client-side record sets

Mhm76

pre-.NET ADO ADO.NET data sets older


.record sets
: 2008" " Typed DataSets DataSet
. record format LINQ . database tables

Data Sets Versus No Data Sets

)( -)(
. DataRow .
provider . data sets
:
With data sets
Without data sets
. DataSet DataAdapter
.
SELECT INSERT UPDATE .DELETE
DataReader .
.

.

.
DataReader )
MARS (
DataReader
.

.
DataReaders .
.
) (
.
Command Connection
.
SQL )
(relatively .


.

.

.
.
.

.
.
.
DataTables DataSet
).( distinct data sources
DataRow .
abstracted ) (
)
(.

Mhm76

Providers and data sets in action

. .
wizards" " code generators .
.
DataReaders . DataSets
DataTable . DataSet

MARS Support .

MARS MARS" " Multiple Active Result Sets


Connection DataReader . . bidirectional
" " SELECT INSERT UPDATE DELETE
. DataReader MARS . MARS .2005
MARS . MARS .
. . multithreaded applications

Connecting to SQL Server with Visual Studio.

. .
. .

Creating a Data Source

<< Data " " Show Data Sources


.

Mhm76

. . " Add New Data


" Source " ." Data Sources" " :
.1 " " " Database " )" Next
) ((.

1
2
3

.2 " "
. " )" New Connection ) ((
.3 . Microsoft SQL Server " " Data source
" ." Continue " " Always use this selection
.
.4 Add Connection .. " " Data source
" " Microsoft SQL Server " " Change .
.5 " " " " Server name SQL Server instance.
.
"." \SQLEXPRESS " " MYSYSTEM " )"MYSYSTEM\SQLEXPRESS.
) 3 .((mhm\ SQLEXPRESS
.6 )( " ." Log on to the server
.
.7 " " Connect to a database " "Library .
.8 " " Test Connection . " " OK ..
.9 " " OK .
) (.
.10 this data source should become part
.of the configurable settings for this project .14
"." Next
.11 . . Tables "
" Activity . "." Finish

Mhm76

. " "LibraryDataSet " ."Activity

Using a Data Source

.
" " Activity " . " drag-and-drop "
" Activity . "" ). Form1 1 (.

Activity .Form1
non-userinterface ). (.

Mhm76

" ."Activity
.F5 "
)"Activity (. )
(. ! .

Data Binding

. " " Data binding )


(.
. )( . FullNameTextBox .
" " DataBindings " " ActivityBindingSource FullName
ActivityBindingSource . ActivityBindingSource
) LibraryDataSet data source (. SQL
Server Library database Activity .FullName
5238 .
. .
.
.: ) ( .
.
. .
. . .

.
.

Interacting with SQL Server in Code.

Building the Connection String

. ADO
ADO.NET connection strings.
tight rein . .
parameters . stuff of legend MSDN

Mhm76

. ttp://www.connectionstrings.com
.
.
) (
Data Source=instance_name;Initial Catalog=Library;Integrated Security=true

:
Data Source=MHM\SQLEXPRESS;Initial Catalog=Library;Integrated Security=True
instance_name
MYSYSTEM\SQLEXPRESS .
SQL Server user IDs passwords :
Data Source=instance_name;Initial Catalog=Library;User ID=sa;Password=xyz

(sa) user ID (xyz) password . MARS


:
MultipleActiveResultSets=true
: Other connection string options SQL Server
)Express (SSE " )" user instancing ClickOnce-deployed
(databases MSDN .

Establishing the Connection.

SqlConnection . .
. .
' ----- Assumes:
' Imports System.Data
Dim libraryDB As New SqlClient.SqlConnection("Data Source=mhm\SQLEXPRESS;" & "Initial
)"Catalog=Library;Integrated Security=true
)(libraryDB.Open
" " mhm mhm .

Using SQL Statements

""" SELECT"" UPDATE"" DELETE " INSERT


)data manipulation language (DML )data definition language (DDL .
SqlCommand SQL . 1 .Activity
SELECT FullName FROM Activity WHERE ID = 1

SqlCommand . SqlCommand SQL .SqlConnection


:
)Dim sqlStatement As New SqlClient.SqlCommand("SELECT FullName FROM Activity WHERE ID = 1", libraryDB

Processing the Results

SQL .SqlDataReader
. Read Item.
:
)(Dim sqlResults As SqlClient.SqlDataReader = sqlStatement.ExecuteReader
)(sqlResults.Read
)))"MsgBox(CStr(sqlResults.Item("FullName
Item '

)))"' MsgBox(CStr(sqlResults("FullName
'

))' MsgBox(CStr(sqlResults!FullName

. . :
)(sqlResults.Close

Modifying Data

Mhm76
)(libraryDB.Close

" ".

ExecuteReader ExecuteNonQuery .
" & "'Dim sqlStatement As New SqlClient.SqlCommand("UPDATE Activity SET FullName = 'Sleeps all day
)WHERE ID = 1", libraryDB
)(sqlStatement.ExecuteNonQuery
2005 " ." INSERT

ID .
ID
INSERT " "SELECT
ID :.
)INSERT INTO CodeSeries (FullName
)'VALUES ('Children''s Books
SELECT ID FROM CodeSeries
'WHERE FullName = 'Children''s Books

:
)INSERT INTO CodeSeries (FullName

.ID
)'VALUES ('Children''s Books

INSERT ID result set " "SELECT.


ExecuteScalar SqlCommand .
sqlStatement = New SqlClient.SqlCommand("INSERT INTO CodeSeries (FullName) " & "OUTPUT INSERTED.ID VALUES
)('Children''s Books')",libraryDB
))(Dim newID As Integer = CInt(sqlStatement.ExecuteScalar

Database Transactions

"Transactions " .
. 10 updates roll back
. reverses ). (.
commit transaction . permanent
SQL Server databases . SqlTransaction ADO.NET .
BeginTransaction . connection
)(Public atomicSet As SqlClient.SqlTransaction = libraryDB.BeginTransaction
SqlTransaction " " Transaction .SqlCommand

sqlStatement.Transaction = atomicSet
. Commit transaction . permanent
)(atomicSet.Commit
transaction " " Rollback
) (atomicSet.Rollback

ADO.NET Entity Framework.

ADO.NET 3.5 ) (2008


: . ADO.NET Entity Framework Part entity-relationship modeling tool
part code generator logical data views
.
Entity Framework : ) entities (
)relationships ( ) entity sets ) ((.
)( . in a more programmable fashion
fields .single record DataTable
ADO.NET (1/ (2) views entity
(3)inheritance .ADO.NET

Data mapping

" " view


. multiple database tables - parent-child views " " Order
order " " Order .
. .

Mhm76

Entity inheritance

.
InternalOrder "
"Order .
Boolean . : . )(
InternalOrder .

ADO.NET provider support

"" .
.
17
. .DB2
2008 Entity Framework
) (. .
.

Project

%50 .ADO.NET
.
. boilerplate

Reference the Data Namespaces

System System.Windows.Forms .Microsoft.VisualBasic


) . ADO.NET " " referencing
.NET DLL ( ) (.
project properties " ." References
) (.

" " Add .


. .
System.Data System.Xml . OK
.
System.Data . System.Data data-related class
. Imports System.Data .
References " ." Imported namespaces
. Imports
. System.Data .
.project properties
General.vb . )(
. LibraryDB SqlConnection connection string .

10

Mhm76

HoldTransaction SqlTransaction . .
CenterText .
Public LibraryDB As System.Data.SqlClient.SqlConnection
Public HoldTransaction As System.Data.SqlClient.SqlTransaction

Connecting to the Database

SqlConnection .
:
.
.
.
ConnectDatabase . connection string
. . . General
) ( MYSYSTEM .
Public Function ConnectDatabase() As Boolean
' ----- Connect to the database. Return True on success.
Dim connectionString As String
' ----- Initialize.
HoldTransaction = Nothing
' ----- Build the connection string.
' !!! WARNING: Hardcoded for now.
connectionString = "Data Source=MYSYSTEM\SQLEXPRESS;" & "Initial Catalog=Library;Integrated
"Security=true
' ----- Attempt to open the database.
Try
)LibraryDB = New SqlClient.SqlConnection(connectionString
)(LibraryDB.Open
Catch ex As Exception
)GeneralError("ConnectDatabase", ex
Return False
End Try
' ----- Success.
Return True
End Function
MyApplication_Startup ApplicationEvents.vb

.
Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As
Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
' ----- Connect to the database.
If (ConnectDatabase() = False) Then
)(Me.HideSplashScreen
e.Cancel = True
Return
End If
End Sub
CleanUpProgram .

General.vb .
)(Public Sub CleanUpProgram
. ' -----
On Error Resume Next
)(LibraryDB.Close
End Sub
MyApplication_Shutdown .ApplicationEvents.vb :
Private Sub MyApplication_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Shutdown
. ' -----
)(CleanUpProgram
End Sub

Interacting with the Database.

. :
data readers tables SQL. :

11

Mhm76

Public Function CreateDataTable(ByVal sqlText As String) As Data.DataTable


' ----- .
Dim dbCommand As SqlClient.SqlCommand
Dim dbAdapter As SqlClient.SqlDataAdapter
Dim dbTable As Data.DataTable
' -----
'.
dbCommand = New SqlClient.SqlCommand(sqlText, LibraryDB)
If Not (HoldTransaction Is Nothing) Then dbCommand.Transaction = HoldTransaction
dbAdapter = New SqlClient.SqlDataAdapter(dbCommand)
dbTable = New Data.DataTable
dbAdapter.Fill(dbTable)
dbAdapter = Nothing
dbCommand = Nothing
Return dbTable
End Function
Public Function CreateReader(ByVal sqlText As String) As SqlClient.SqlDataReader
' -----
Dim dbCommand As SqlClient.SqlCommand
Dim dbScan As SqlClient.SqlDataReader
.
.
dbCommand = New SqlClient.SqlCommand(sqlText, LibraryDB)
If Not (HoldTransaction Is Nothing) Then dbCommand.Transaction = HoldTransaction
dbScan = dbCommand.ExecuteReader()
dbCommand = Nothing
Return dbScan
End Function
Public Sub ExecuteSQL(ByVal sqlText As String)
.
Dim DBCommand As SqlClient.SqlCommand
. .
.
DBCommand = New SqlClient.SqlCommand(sqlText, LibraryDB)
If Not (HoldTransaction Is Nothing) Then DBCommand.Transaction = HoldTransaction
DBCommand.ExecuteNonQuery()
End Sub
Public Function ExecuteSQLReturn(ByVal sqlText As String) As Object

Dim DBCommand As SqlClient.SqlCommand
.
.
DBCommand = New SqlClient.SqlCommand(sqlText, LibraryDB)
If Not (HoldTransaction Is Nothing) Then DBCommand.Transaction = HoldTransaction
Return DBCommand.ExecuteScalar()
End Function
Public Sub TransactionBegin()
.
On Error Resume Next
HoldTransaction = LibraryDB.BeginTransaction()
End Sub
Public Sub TransactionCommit()
.
On Error Resume Next
If (HoldTransaction Is Nothing) Then Return
' ----- Commit the transaction.

12

Mhm76
.
)(HoldTransaction.Commit
HoldTransaction = Nothing
End Sub
)(Public Sub TransactionRollback
' ----- Ignore if there is no transaction.
.
On Error Resume Next
If (HoldTransaction Is Nothing) Then Return
' ----- Rollback the transaction.
.
)(HoldTransaction.Rollback
HoldTransaction = Nothing
End Sub

:
Function CreateDataTable
. DataTable SqlDataAdapter
SqlDataReader .DataTable
Function CreateReader.
SqlDataReader .
Sub ExecuteSQL .
.
Function ExecuteSQLReturn.
.
Sub TransactionBegin.
.
Sub TransactionCommit .
. .permanent
Sub TransactionRollback.
.
)( " "
. . .
CreateReader HoldTransaction .

If Not (HoldTransaction Is Nothing) Then dbCommand.Transaction = HoldTransaction

Processing Data Values.

.
) (
zerolength . ) (
.
Public Function DBCombo(ByRef whichField As ComboBox) As String

Dim listItem As Library.ListItemData
.
"If (whichField.SelectedItem Is Nothing) Then Return "NULL
)listItem = CType(whichField.SelectedItem, Library.ListItemData
)(1- :
If (listItem.ItemData = -1) Then
"Return "NULL
Else
)Return CStr(listItem.ItemData
End If
End Function
Public Function DBDate(ByVal origText As String) As String
' ----- Prepare a date for insertion in a SQL statement.
If (Trim(origText) = "") Then
"Return "NULL

13

Mhm76
ElseIf (IsDate(origText)) Then
Return "'" & Format(CDate(origText), "d-MMM-yyyy") & "'"
Else
Return "NULL"
End If
End Function
Public Function DBDate(ByVal origDate As Date) As String
' ----- Prepare a date for insertion in a SQL statement.
Return "'" & Format(origDate, "d-MMM-yyyy") & "'"
End Function
Public Function DBGetDecimal(ByRef dataField As Object) As Decimal
' ----- Return the decimal equivalent of an optional database field.
If (IsDbNull(dataField) = True) Then
Return 0@
Else
Return CDec(dataField)
End If
End Function
Public Function DBGetInteger(ByRef dataField As Object) As Integer
' ----- Return the integer equivalent of an optional database field.
If (IsDbNull(dataField) = True) Then
Return 0
Else
Return CInt(dataField)
End If
End Function
Public Function DBGetText(ByRef dataField As Object) As String
' ----- Return the text equivalent of an optional database field.
If (IsDbNull(dataField) = True) Then
Return ""
Else
Return CStr(dataField)
End If
End Function
Public Function DBNum(ByVal origText As String) As String
' ----- Prepare a number for insertion in a SQL statement.
If (Trim(origText) = "") Then
Return "NULL"
Else
Return Trim(origText)
End If
End Function
Public Function DBText(ByVal origText As String) As String
' ----- Prepare a string for insertion in a SQL statement.
If (Trim(origText) = "") Then
Return "NULL"
Else
Return "'" & Replace(origText, "'", "''" ) & "'"
End If
End Function

DBCombo

1- . ComboBox numeric code


." NULL "
DBDate(String)

.
DBDate(Date)

.
DBGetDecimal

." NULL "


DBGetInteger

14

Mhm76

:
." NULL "
DBGetText

." "
DBNum

.
DBText

. .
.

System-Level Configuration)(

. SystemValue
( )) SetSystemValue . value name GetSystemValue
.General .(
Public Function GetSystemValue(ByVal valueName As String) As String
' ----- Return the data portion of a system value name-data pair.
Dim sqlText As String
Dim returnValue As String
' ----- Retrieve the value.
returnValue = ""
sqlText = "SELECT ValueData FROM SystemValue WHERE UPPER(ValueName) = " & _
DBText(UCase(valueName))
Try
returnValue = DBGetText(ExecuteSQLReturn(sqlText))
Catch ex As Exception
GeneralError("GetSystemValue", ex)
End Try
Return returnValue
End Function
Public Sub SetSystemValue(ByVal valueName As String, ByVal valueData As String)
' ----- Update a record in the SystemValue table.
Dim sqlText As String
Dim dbInfo As SqlClient.SqlDataReader
Try
' ----- See if the entry already exists.
sqlText = "SELECT COUNT(*) FROM SystemValue WHERE UPPER(ValueName) = " & _
DBText(UCase(valueName))
If (CInt(ExecuteSQLReturn(sqlText)) > 0) Then
' ----- Value already exists.
sqlText = "UPDATE SystemValue SET ValueData = " & DBText(valueData) & _
" WHERE UPPER(ValueName) = " & DBText(UCase(valueName))
Else
' ----- Need to create value.
sqlText = "INSERT INTO SystemValue (ValueName, ValueData) VALUES (" & _
DBText(valueName) & ", " & DBText(valueData) & ")"
End If
' ----- Update the value.
ExecuteSQL(sqlText)
Catch ex As System.Exception
GeneralError("SetSystemValue", ex)
End Try
End Sub
. .GetSystemValue
SetSystemValue
. ( configuration value )
. . ) (
ExecuteSqlReturn)( . system value name
. .query
sqlText = "SELECT COUNT(*) FROM SystemValue WHERE UPPER(ValueName) = " & _
DBText(UCase(valueName))

15

Mhm76

If (CInt(ExecuteSQLReturn(sqlText)) > 0) Then


GetSystemValue . MyApplication_Startup ApplicationEvents.vb
:
' ----- Check the database version.
Dim productionDBVersion As String
))"productionDBVersion = Trim(GetSystemValue("DatabaseVersion
If (CInt(Val(productionDBVersion)) <> UseDBVersion) Then
_ & " MsgBox("The program cannot continue due to an incompatible database.
_ & "The current database version is '" & productionDBVersion
_ "'. The application version is '" & UseDBVersion & "'.",
)MsgBoxStyle.OkOnly Or MsgBoxStyle.Critical, ProgramTitle
)(CleanUpProgram
)(Me.HideSplashScreen
e.Cancel = True
Return
End If

.
DatabaseVersion .
.

16

Mhm76

17

Mhm76

Security

. " " Secret
" " Japanese Cooking Secrets
era information overload increasingly permissive moral
standards . .
.

Security Features in .NET


:

Internal security
Classes .
) Code Access Security (CAS unauthorized
powerful libraries . .

External security

.
)( )( " " .
" )" Code Access Security (CAS
)(
) .( in-effect security policies.

Data security
.
. Encryption digital signatures cryptographic

-
ADO.NET .system security policies
.

Cryptography and Encryption

.
.
. .

Keeping Secrets
encryption data security " ."keeping secrets
) ( adversary
. ) letter substitutions
) (( cryptogram puzzles enigma-machine-quality encoding
.systems . ) (
-128.
encryption hashing functions
encryption algorithms sensitive content
. Symmetric cryptography encryption single
.secret key Public-key encryption - asymmetric cryptography
encrypt decrypt. .
.
private key . )
( .
.
. .

Mhm76

Data Stability
.
.
.
.
" " checksum . " " checksum
" -" hash value short value .
" ") ( hashing algorithms
." "
.
" " . " " .
" " . Bidirectional
encryption " ." Keeping Secrets
bidirectional encryption .

Identity Verification

. trustworthy
digital signatures .

. " " .
. " "
.

Encryption in .NET.
. System.Security.Cryptography
.
DESCryptoServiceProvider )Data Encryption Standard (DES
algorithm
IBM .1970

)( Symmetric Cryptography
single secret key .
) ( asymmetric cryptography
)( . " ." secret key encryption
:
. ) Data Encryption Standard (DES -56 block cipher
.DESCryptoServiceProvider ) (
.
. RC2 (Rivest Cipher number 2)2 -56 .RC2CryptoServiceProvider
. ) Rijndael Daemen ( Rijmen ) 128 256( block

cipher .RijndaelManaged " Advanced Encryption


)" Standard (AES .

. Triple DES DESalgorithm


. TripleDESCryptoServiceProvider DES vulnerable
Rijndael . AES
" " provider .
) (MSDN DESCryptoServiceProvider CryptoStream
System.Security.Cryptography :
Imports System

Mhm76

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Class CryptoMemoryStream
Public Shared Sub Main()
' ----- Encrypt then decrypt some text.
Dim key As New DESCryptoServiceProvider
Dim encryptedVersion() As Byte
Dim decryptedVersion As String
' ----- First, encrypt some text.
encryptedVersion = Encrypt("This is a secret.", key)
' ----- Then, decrypt it to get the original.
decryptedVersion = Decrypt(encryptedVersion, key)
End Sub
Public Shared Function Encrypt(ByVal origText As String, _
ByVal key As SymmetricAlgorithm) As Byte()
' ----- Uses a crytographic memory stream and a
' secret key provider (DES in this case)
' to encrypt some text.
Dim baseStream As New MemoryStream
Dim secretStream As CryptoStream
Dim streamOut As StreamWriter
Dim encryptedText() As Byte
' ----- A memory stream just shuffles data from
' end to end. Adding a CryptoStream to it
' will encrypt the data as it moves through
' the stream.
secretStream = New CryptoStream(baseStream, _
key.CreateEncryptor(), CryptoStreamMode.Write)
streamOut = New StreamWriter(secretStream)
streamOut.WriteLine(origText)
streamOut.Close()
secretStream.Close()
' ----- Move the encrypted content into a useful
' byte array.
encryptedText = baseStream.ToArray()
baseStream.Close()
Return encryptedText
End Function
Public Shared Function Decrypt(ByVal encryptedText() As Byte, _
ByVal key As SymmetricAlgorithm) As String
' ----- Clearly, this is the opposite of the
' Encrypt( ) function, using a stream reader
' instead of a writer, and the key's
' "decryptor" instead of its "encryptor."
Dim baseStream As MemoryStream
Dim secretStream As CryptoStream
Dim streamIn As StreamReader
Dim origText As String
' ----- Build a stream that automatically decrypts
' as data is passed through it.
baseStream = New MemoryStream(encryptedText)
secretStream = New CryptoStream(baseStream, _
key.CreateDecryptor(), CryptoStreamMode.Read)
streamIn = New StreamReader(secretStream)
' ----- Move the decrypted content back to a string.
origText = streamIn.ReadLine()
streamIn.Close()
secretStream.Close()
baseStream.Close()
Return origText
End Function
End Class

)"). stream DESencryption


Streams (files " Streams (
convoluted
Decrypt Encrypt DESCryptoServiceProvider .

Mhm76
:
" " generic .
. .

Asymmetric Cryptography

.
. ) (.
. .
"" generators emit .
mask .
.
notoriously .
sluggish .

. :
. ) Digital Signature Algorithm (DSA
.DSACryptoServiceProvider
. )RSA Ron Rivest Adi Shamir (Adleman
.RSACryptoServiceProvider
.
.

) ( Hashing

) ) (( hashing algorithms
.
.
.
. :
Public Function HashSomeText(ByVal origText As String) As Long
' ----- Create a hash value from some data.
&Dim hashValue As Long = 0
Dim counter As Long
)For counter = 1 To Len(origText
))hashValue += Asc(Mid(origText, counter, 1
_ If (hashValue > (Long.MaxValue * 0.9)) Then
hashValue /= 2
Next counter
Return hashValue
End Function

.
%90 hashValue . HashSomeText
hashed representation : deficiencies
. hash .
.
. .
. A B T S .
. .
. :
.1 ) ( )Hash-based Message Authentication Code (HMAC
Secure Hash Algorithm number 1 (SHA-1)1 .HMACSHA1
160 . restrictions secret key .
SHA-1 )(.

Mhm76
:
.2 ) Message Authentication Code (MAC ) Triple-DESsecret
( . MACTripleDES secret key 16 24
8.
.3 . Message-Digest algorithm number 5 (MD5)5
.MD5CryptoServiceProvider MD5 Ron Rivest
. encoding security risk 128.
.4 HMACSHA1 SHA1 SHA1Managed class . SHA-1
.NET managed code. HMACSHA1
)() Cryptography API (CAPI SHA1.pre-.NET DLL
160.
.5 SHA256:SHA384 SHA512 SHA1 256
384512 .
.
.
.

Other Security Features


.

)User Authentication and My.User .(My.User


My.User ) ( authentication
. " " Name . IsInRole
. the Administrators security group My.User
. authentication systems
. Options " " Internet-based Windows Live
ID third-party authentication systems
.

The SecureString Class

.
. .
immutable . .
.
. nefarious

System.Security.SecureString .
. gibberish

Project

:
. " " login ) ( .
. .
. function . user-supplied password
. )( authentication.

)( Authentication Support

Windows SQL Server


) security ( restrict . )(
. .
.
General.vb .
Public LoggedInUserID As Integer
Public LoggedInUserName As String
Public LoggedInGroupID As Integer

Mhm76
Public SecurityProfile(MaxLibrarySecurity) As Boolean

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

administrator.
. InitializeSystem
. .General
)(Public Sub InitializeSystem
.
'
Dim counter As Integer
.
'
LoggedInUserID = -1
"" = LoggedInUserName
LoggedInGroupID = -1
For counter = 1 To MaxLibrarySecurity
SecurityProfile(counter) = False
Next counter
End Sub

) SecurityProfile 0 MaxLibrarySecurity 1
1 .(0 InitializeSystem MyApplication_Startup
ApplicationEvents.vb . .

Activity


)(InitializeSystem

)(
. ReprocessSecuritySet .General
'
'

)(Public Sub ReprocessSecuritySet


.
,
Dim counter As Integer
Dim sqlText As String

Dim dbinfo As SqlClient.SqlDataReader = Nothing



'
For counter = 1 To MaxLibrarySecurity
SecurityProfile(counter) = False
Next counter
.
'
If (LoggedInUserID = -1) Or (LoggedInGroupID = -1) Then Return
Try

Mhm76


'
sqlText = "SELECT ActivityID FROM GroupActivity WHERE GroupID = " & LoggedInGroupID
)dbInfo = CreateReader(sqlText
)Do While (dbInfo.Read
SecurityProfile(CInt(dbInfo!ActivityID)) = True
Loop
)(dbInfo.Close
Catch ex As Exception

'
)GeneralError("ReprocessSecuritySet", ex
)(If (dbInfo IsNot Nothing) Then dbInfo.Close

'
LoggedInUserID = -1
LoggedInGroupID = -1
)(ReprocessSecuritySet
Finally
dbInfo = Nothing
End Try
End Sub

. ) ()
(LoggedInUserID SqlDataReader
.SecurityProfile True administrator
. GroupActivity .
recursive
ReprocessSecuritySet ). SecurityProfile Recursion
(.

Encrypting Passwords
)( .
UserName profile .
).

(.
)( scramble )(
password .
)( )( .
)( .
"." secret HMACSHA1
. variablesize
. UserName
.

. System.Security.Cryptography System.Text
. Import .General.vb
Imports System.Text
Imports System.Security.Cryptography

)( EncryptPassword .General
Public Function EncryptPassword(ByVal loginID As String, ByVal passwordText As String) As String
.
.
Dim hashingFunction As HMACSHA1
Dim secretKey() As Byte
Dim hashValue() As Byte
Dim counter As Integer
"" = Dim result As String
. .
.
))secretKey = (New UnicodeEncoding).GetBytes(UCase(loginID
)( SHA-1
)hashingFunction = New HMACSHA1(secretKey, True

Mhm76

)(. .
))hashValue = hashingFunction.ComputeHash((New UnicodeEncoding).GetBytes(passwordText

. . long hex string
For counter = 0 To hashValue.Length - 1
))result &= Hex(hashValue(counter
Next counter
20.
)Return Left(result, 20
End Function

security providers )(.


GetBytes .UnicodeEncoding
login ID password arguments .HMACSHA1
ComputeHash
ASCII issued .UserName
:basic byte printable hexadecimal equivalent . Hex
. UserName 20 )( chop off
. EncryptPassword .

MsgBox("Alice/none: " & EncryptPassword("Alice", "") & vbCrLf & "Alice/password: " & EncryptPassword("Alice",
& " "password") & vbCrLf & "Bob/none: " & EncryptPassword("Bob", "") & vbCrLf & "Bob/password:
))"EncryptPassword("Bob", "password

Undoing Some Previous Changes


UserName GroupName GroupActivity . )
(UserName ) .(GroupName zero
GroupActivity . GroupName

property forms .
. BaseCodeForm.vb .
ListEditRecords.vb .
users security groups .
BaseCodeForm.vb MustInherit MustOverride
. . :
) ( instances design time .
TextBox .
.
) ( MustInherit

. "
"MustInherit .
inherited form .
.
BaseCodeForm.vb MustInherit MustOverride .
.

Mhm76
:
.
.
. .

Managing Security Groups.


.GroupName .

. << Build
. Build Library
form << Project . Add Windows Form
Windows Forms Categories Inherited Form . Templates
GroupName.vb . Add ) Inheritance Picker form (
BaseCodeForm . OK GroupName .BaseCodeForm

)( Label TextBox Button CheckedListBox


) (.
) ( :
Public Class GroupName
Private ActiveID As Integer
Private StartingOver As Boolean
Public Overrides Function AddRecord() As Integer
.
ActiveID = -1
)(PrepareFormFields
)(Me.ShowDialog
_ If (Me.DialogResult = Windows.Forms.DialogResult.OK) Then
Return ActiveID Else Return -1
End Function
Public Overrides Function CanUserAdd() As Boolean
:.
)Return SecurityProfile(LibrarySecurity.ManageGroups
End Function
Public Overrides Function CanUserEdit() As Boolean
:.
)Return SecurityProfile(LibrarySecurity.ManageGroups
End Function
Public Overrides Function CanUserDelete() As Boolean
:.
)Return SecurityProfile(LibrarySecurity.ManageGroups
End Function
Public Overrides Function DeleteRecord(ByVal recordID As Integer) As Boolean
.

Mhm76

Dim sqlText As String


On Error GoTo ErrorHandler
' ----- Confirm with the user.
If (MsgBox("
" , _
MsgBoxStyle.YesNo Or MsgBoxStyle.Question, ProgramTitle) <> MsgBoxResult.Yes) _
Then Return False

sqlText = "SELECT COUNT(*) FROM UserName WHERE GroupID = " & recordID
If (CInt(ExecuteSQLReturn(sqlText)) > 0) Then
MsgBox("" , _
MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, ProgramTitle)
Return False
End If
.
TransactionBegin()
sqlText = "DELETE FROM GroupActivity WHERE GroupID = " & recordID
ExecuteSQL(sqlText)
sqlText = "DELETE FROM GroupName WHERE ID = " & recordID
ExecuteSQL(sqlText)
TransactionCommit()
Return True
ErrorHandler:
GeneralError("GroupName.DeleteRecord", Err.GetException())
TransactionRollback()
Return False
End Function
Public Overrides Function EditRecord(ByVal recordID As Integer) As Integer
.
ActiveID = recordID
PrepareFormFields()
Me.ShowDialog()
If (Me.DialogResult = Windows.Forms.DialogResult.OK) Then _
Return ActiveID Else Return -1
End Function
Public Overrides Sub FillListWithRecords(ByRef destList As ListBox, _
ByRef exceededMatches As Boolean)
.
Dim sqlText As String
Dim dbInfo As SqlClient.SqlDataReader
On Error GoTo ErrorHandler
.
destList.Items.Clear()
exceededMatches = False
.
sqlText = "SELECT * FROM GroupName ORDER BY FullName"
dbInfo = CreateReader(sqlText)
Do While dbInfo.Read
.
destList.Items.Add(New ListItemData(CStr(dbInfo!FullName), CInt(dbInfo!ID)))
Loop
dbInfo.Close()
dbInfo = Nothing
Return
ErrorHandler:
GeneralError("GroupName.FillListWithRecords", Err.GetException())
On Error Resume Next
If Not (dbInfo Is Nothing) Then dbInfo.Close() : dbInfo = Nothing
Return
End Sub
Public Overrides Function FormatRecordName(ByVal recordID As Integer) As String
.
Dim sqlText As String
On Error GoTo ErrorHandler
.
sqlText = "SELECT FullName FROM GroupName WHERE ID = " & recordID
Return CStr(ExecuteSQLReturn(sqlText))
ErrorHandler:
GeneralError("GroupName.FormatRecordName", Err.GetException())
Return "Error"

10

Mhm76

End Function
Public Overrides Function GetEditDescription() As String

Return "_ & "
" ._ & "
""
End Function
Public Overrides Function GetEditTitle() As String
.
Return "Security Groups"
End Function
Private Sub PrepareFormFields()
.
Dim sqlText As String
Dim dbInfo As SqlClient.SqlDataReader
Dim matchPos As Integer
On Error GoTo ErrorHandler
.
If (ActivityList.Items.Count = 0) Then
.
ActivityList.Items.Clear()
sqlText = "SELECT * FROM Activity ORDER BY FullName"
dbInfo = CreateReader(sqlText)
Do While (dbInfo.Read)
ActivityList.Items.Add _
(New ListItemData(CStr(dbInfo!FullName), CInt(dbInfo!ID)))
Loop
dbInfo.Close()
dbInfo = Nothing
Else
. .
.
Do While (ActivityList.CheckedItems.Count > 0)
ActivityList.SetItemChecked(ActivityList.CheckedIndices(0), False)
Loop
If (ActivityList.Items.Count > 0) Then ActivityList.TopIndex = 0
End If
.
StartingOver = True
RecordFullName.Text = ""
If (ActiveID = -1) Then Return
.
sqlText = "SELECT FullName FROM GroupName WHERE ID = " & ActiveID
RecordFullName.Text = CStr(ExecuteSQLReturn(sqlText))
.
sqlText = "SELECT ActivityID FROM GroupActivity WHERE GroupID = " & ActiveID
dbInfo = CreateReader(sqlText)
Do While (dbInfo.Read)
matchPos = ActivityList.Items.IndexOf(CInt(dbInfo!ActivityID))
If (matchPos <> -1) Then ActivityList.SetItemChecked(matchPos, True)
Loop
dbInfo.Close()
dbInfo = Nothing
Return
ErrorHandler:
GeneralError("GroupName.PrepareFormFields", Err.GetException())
On Error Resume Next
If Not (dbInfo Is Nothing) Then dbInfo.Close() : dbInfo = Nothing
Return
End Sub
Private Function SaveFormData() As Boolean
. .
Dim sqlText As String
Dim newID As Integer = -1
On Error GoTo ErrorHandler
.
Me.Cursor = Windows.Forms.Cursors.WaitCursor
TransactionBegin()
.

11

Mhm76

If (ActiveID = -1) Then


.
sqlText = "INSERT INTO GroupName (FullName) OUTPUT INSERTED.ID VALUES (" & _
DBText(Trim(RecordFullName.Text)) & ")"
newID = CInt(ExecuteSQLReturn(sqlText))
Else
.
newID = ActiveID
sqlText = "UPDATE GroupName SET FullName = " & _
DBText(Trim(RecordFullName.Text)) & " WHERE ID = " & ActiveID
ExecuteSQL(sqlText)
End If
.
sqlText = "DELETE FROM GroupActivity WHERE GroupID = " & newID
ExecuteSQL(sqlText)
' ----- Save the selected security settings.
.
For Each itemChecked As ListItemData In ActivityList.CheckedItems
sqlText = "INSERT INTO GroupActivity (GroupID, ActivityID) VALUES (" & _
newID & ", " & itemChecked.ItemData & ")"
ExecuteSQL(sqlText)
Next itemChecked
.
TransactionCommit()
ActiveID = newID
.
If (LoggedInGroupID = ActiveID) Then ReprocessSecuritySet()
.
ActiveID = newID
Me.Cursor = Windows.Forms.Cursors.Default
Return True
ErrorHandler:
Me.Cursor = Windows.Forms.Cursors.Default
GeneralError("GroupName.SaveFormData", Err.GetException())
TransactionRollback()
Return False
End Function
Private Function ValidateFormData() As Boolean
. .
Dim sqlText As String
On Error GoTo ErrorHandler
' ----- Name is a required field.
.
If (Trim(RecordFullName.Text) = "") Then
MsgBox("Please supply the security group name.", _
MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, ProgramTitle)
RecordFullName.Focus()
Return False
End If
.

sqlText = "SELECT COUNT(*) FROM GroupName WHERE UPPER(FullName) = " & _
DBText(UCase(Trim(RecordFullName.Text)))
If (ActiveID <> -1) Then sqlText &= " AND ID <> " & ActiveID
If (CInt(ExecuteSQLReturn(sqlText)) > 0) Then
MsgBox("A record already exists with the name '" & Trim(RecordFullName.Text) & _
"'.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, ProgramTitle)
RecordFullName.Focus()
Return False
End If
.
Return True
ErrorHandler:
GeneralError("GroupName.ValidateFormData", Err.GetException())
Return False
End Function
Private Sub GroupName_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles
Me.Activated
.
If (StartingOver) Then RecordFullName.Focus()

12

Mhm76

StartingOver = False
End Sub
Private Sub RecordFullName_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles
RecordFullName.Enter
.
)(RecordFullName.SelectAll
End Sub
Private Sub ActOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
ActOK.Click
.
If (ValidateFormData() = False) Then Return
If (SaveFormData() = False) Then Return
Me.DialogResult = Windows.Forms.DialogResult.OK
End Sub
End Class

. ActiveID ID GroupName 1- .
StartingOver . GroupName .
ListEditRecords.vb ) GroupName.vb (
:

)ListEditRecordsvb.ManageRecords(New LIBRARY.GroupName

ListEditRecordsvb GroupName
. GroupName
. . StartingOver
Activated .

Private Sub GroupName_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles


Me.Activated
.
)(If (StartingOver) Then RecordFullName.Focus
StartingOver = False
End Sub

PrepareFormFields .
.
. RecordFullName . TextBox

' .
sqlText = "SELECT FullName FROM GroupName WHERE ID = " & ActiveID
))RecordFullName.Text = CStr(ExecuteSQLReturn(sqlText
GroupName overrides .BaseCodeForm

CanUserAdd False . SecurityProfile


. group records

Public Overrides Function CanUserAdd() As Boolean


:.
'
)Return SecurityProfile(LibrarySecurity.ManageGroups
End Function
overrides BaseCodeForm UsesSearch. SearchForRecord

.
adds edits deletes AddRecord EditRecord DeleteRecord
. ListEditRecords .EditRecord
Public Overrides Function EditRecord(ByVal recordID As Integer) As Integer
.
ActiveID = recordID
)(PrepareFormFields
)(Me.ShowDialog
_ If (Me.DialogResult = Windows.Forms.DialogResult.OK) Then
Return ActiveID Else Return -1
End Function

ID ActiveID PrepareFormFields
. Me.ShowDialog . DialogResult

13

Mhm76
:
ActOK_Click DialogResult ActCancel
. ActCancel
AddRecord EditRecord 1- ActiveID . DeleteRecord
) (DeleteRecord
group . UserName
.DELETE
.transaction .TransactionRollback

: Database Integrity Warning.

. delete

. )( .
conflicts .
referential integrity
. GroupName.ID UserName.GroupID .
.
.
. )( .
" " OK .
ActOK_Click .
.
If (ValidateFormData() = False) Then Return
If (SaveFormData() = False) Then Return
Me.DialogResult = Windows.Forms.DialogResult.OK

ValidateFormData security
group name . SaveFormData )

.(SaveFormData GroupName .

Managing Users.

. UserName GroupName
. UserName.vb .
. Solution Explorer Properties Build Action
None .Compile

GroupName . password
.
)( hashed version . Login ID
password . Login ID OrigLoginID

Login ID .
.
))passwordResult = EncryptPassword(Trim(RecordLoginID.Text), Trim(RecordPassword.Text
UserName GroupName . main form

:
Private Sub AdminLinkGroups_LinkClicked(ByVal sender As Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles AdminLinkGroups.LinkClicked
' ----- Let the user edit the list of security groups.
.
'
If (SecurityProfile(LibrarySecurity.ManageGroups) = False) Then
_ MsgBox(NotAuthorizedMessage, MsgBoxStyle.OkOnly Or
)MsgBoxStyle.Exclamation, ProgramTitle
Return
End If
' ----- Edit the records.
.
'
)ListEditRecords.ManageRecords(New Library.GroupName
ListEditRecords = Nothing

14

Mhm76

End Sub
Private Sub AdminLinkUsers_LinkClicked(ByVal sender As Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles AdminLinkUsers.LinkClicked
' ----- Let the user edit the list of administrative users.
.
'
If (SecurityProfile(LibrarySecurity.ManageUsers) = False) Then
MsgBox(NotAuthorizedMessage, MsgBoxStyle.OkOnly Or _
MsgBoxStyle.Exclamation, ProgramTitle)
Return
End If
' ----- Edit the records.
.
'
ListEditRecords.ManageRecords(New Library.UserName)
ListEditRecords = Nothing
End Sub

web-style link labels AdminLinkUsers AdminLinkGroups


.GroupName . Clicked LinkClicked .

Private Sub AdminLinkGroups_LinkClicked(ByVal sender As Object, ByVal e As


System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles AdminLinkGroups.LinkClicked
' ----- Let the user edit the list of security groups.
.
If (SecurityProfile(LibrarySecurity.ManageGroups) = False) Then
MsgBox(NotAuthorizedMessage, MsgBoxStyle.OkOnly Or _
MsgBoxStyle.Exclamation, ProgramTitle)
Return
End If
' ----- Edit the records.
.
ListEditRecords.ManageRecords(New Library.GroupName)
ListEditRecords = Nothing
End Sub

Per-User Experience.

.

.

.

. ActOK_Click . ChangeUser.vb
( ) " "
LoggedInUserID = -1
LoggedInUserName = ""
LoggedInGroupID = -1
ReprocessSecuritySet()

. ActLogin_Click
. Login MainForm.vb

Private Sub ActLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


ActLogin.Click

15

Mhm76

ShowLoginForm()
End Sub

'

Private Sub ShowLoginForm()



'
Dim userChoice As Windows.Forms.DialogResult
userChoice = ChangeUser.ShowDialog()
ChangeUser = Nothing
If (userChoice = Windows.Forms.DialogResult.OK) Then UpdateDisplayForUser()
End Sub

" Select Case " . login F12


.MainForm_KeyDown

Case Keys.F12
.
ShowLoginForm()
e.Handled = True

'

UpdateDisplayForUser ShowLoginForm
. MainForm . security profile
. 1- LoggedInUserID

Private Sub UpdateDisplayForUser()



'
Dim sqlText As String
If (LoggedInUserID = -1) Then

'
ActiveMode.Text = "
"
LabelTasks.Visible = False
LineTasks.Visible = False
PicCheckOut.Visible = False
ActCheckOut.Visible = False
PicCheckIn.Visible = False
ActCheckIn.Visible = False
PicAdmin.Visible = False
ActAdmin.Visible = False
PicProcess.Visible = False
ActProcess.Visible = False
PicReports.Visible = False
ActReports.Visible = False
ActLogin.Visible = True

'
TaskLibraryItem()
Else

'
Try
sqlText = "SELECT FullName FROM UserName WHERE ID = " & LoggedInUserID
ActiveMode.Text = "Administrative User: " & CStr(ExecuteSQLReturn(sqlText))
Catch ex As Exception
GeneralError("MainForm.UpdateDisplayForUser", Err.GetException())
ActiveMode.Text = "Administrative User: Unknown"
End Try
LabelTasks.Visible = True
LineTasks.Visible = True
PicCheckOut.Visible = True
ActCheckOut.Visible = True
PicCheckIn.Visible = True
ActCheckIn.Visible = True
PicAdmin.Visible = True
ActAdmin.Visible = True
PicProcess.Visible = True
ActProcess.Visible = True
PicReports.Visible = True
ActReports.Visible = True
ActLogin.Visible = True
End If
End Sub

16

Mhm76
:
ID . password
UpdateDisplayForUser . .MainForm_Load
'
)(UpdateDisplayForUser

) ( .
. TaskReports
.
.

PanelReports.Visible = True

If (SecurityProfile(LibrarySecurity.RunReports)) Then PanelReports.Visible = True

TaskAdmin TaskCheckOut. TaskProcess :


Panel???.Visible = True

.
PanelCheckOut.Visible = True .TaskCheckOut

If (SecurityProfile(LibrarySecurity.CheckOutItems)) Then PanelCheckOut.Visible = True


PanelCheckIn.Visible = True .TaskCheckIn
If (SecurityProfile(LibrarySecurity.CheckInItems)) Then PanelCheckIn.Visible = True
PanelAdmin.Visible = True .TaskAdmin
If (SecurityProfile(LibrarySecurity.AdminFeatures)) Then PanelAdmin.Visible = True
PanelProcess.Visible = True . TaskProcess
If (SecurityProfile(LibrarySecurity.DailyProcessing)) Then PanelProcess.Visible = True

. " " admin

. UserName .

.

17

Mhm76

Overloads and Extensions


operator overloading ).(+
. ) ( extension
.
?What Is Operator Overloading
.
. )*(
" " Bumblebee .
Dim swarm As Bumblebee
Dim oneBumblebee As New Bumblebee
Dim twoBumblebee As New Bumblebee
swarm = oneBumblebee * twoBumblebee
. )(
. .
.
. .
: unary binary ) ( .
)( . symbol " " Not :
oppositeValue = Not originalValue
)( . :
ten = two * five
)( .
)(10/5
)(2 . :
'
' theAnswer
theAnswer = 2 * 5
)theAnswer = DoubleIt(5
. .
:
Public Shared Function *(ByVal firstOperand As Integer, ByVal secondOperand As Integer) As Integer
)*( operands .
.
Bumblebee Operator" " multiplication function
.Bumblebee
Partial Class Bumblebee
_ Public Shared Operator *(ByVal operand1 As Bumblebee,
ByVal operand2 As Bumblebee) As Bumblebee
' ----- Multiply two bumblebees together.
Dim finalResult As New Bumblebee
' ----- Add special "multiplication" code here, then...
Return finalResult
End Operator
End Class
Bumblebee "*1 "2
Bumblebee .
Public . Shared shared
.
?What Can You Overload
) Is( IsNot .
. . .
XX :
)Public Shared Operator XX(...
Mathematical Operators

Mhm76

10 ) ( . pseudo-mathematical .
(&) string concatenation .
(+) plus (-) minus unary. binary minus sign "
" negation )"("5- " " subtraction) ""2-5(.
.
Public Shared Operator -(ByVal operand1 As SomeClass) As SomeClass
' ----- This is the unary "negation" version.
End Operator
:
Comments
OperatorType
"" . ).(5+
Unary
+
)( ) (.

.
' ---- + ...Dim oneBuzz As New Bumblebee
Dim moreBuzz As Bumblebee = +oneBuzz
. Operator
)(. ""
Binary
+
.

.
")"( negation .
Unary
. subtraction
Binary
.multiplication
Binary
*
. standard division operator
Binary
/
. integer division operator
Binary
\
" " integer .
") exponentiation (" to the power of
Binary
^
modulo remainder operator
Binary
Mod
.
.string concatenation operator
Binary
&
Comparison Operators
If . Boolean
Operator .
) <( ) > (
.argument signature
. .
Public Shared Operator <=(ByVal operand1 As SomeClass, ByVal operand2 As SomeClass) As Boolean
' ----- The <= operator returns a Boolean result.
End Operator
. "" buddy
.
Comments
OperatorBuddy
operands equivalence True
><
=
.
.
=
><
" " less than.
>
<
" " greater than.
<
>
"
=>
=<
" less than or equal to.
"
=<
=>
" greater than or equal to.

Mhm76

. Like "" pattern


. wildcards
If (someValue Like somePattern) Then
pattern Like pattern
. Boolean
Public Shared Operator Like(ByVal operand1 As Bumblebee, ByVal operand2 As Integer) As Boolean
' ----- See if Bumblebee matches an Integer pattern.
End Operator
" " buddy .Like
Logical Bitwise Bitwise and Logical Operators
logical ) (
. ) () XorOr And (Not integer
)( . Boolean
. .
override ) ( bitwise versions
. logical . Boolean
.
Comments
Operator
shift left bits
<<
.
) ( Integer .
Public Shared Operator <<(ByVal operand1 As Bumblebee, ByVal operand2 As Integer) As Bumblebee
' ----- Add shifting code here.
End Operator
shift right "
>>

." right . conservative


Integer .
.
Not
conjunction bit
And
.
disjunction ) (
Or
.
bitwise exclusion operator
Xor
.
Or OrElse . OrElse
IsTrue
IsTrue. .
OrElse Or IsTrue .
.IsTrue
. Or . OrElse Bumblebee
Or .Bumblebee
. IsTrue )(Bumblebee . Boolean
. .IsFalse
truth Bumblebee .
IsFalse IsTrue And. AndAlso
IsFalse

" " The CType Operator

CType :
)result = CType(source, Type
. looks are deceiving ) (CInt
. conversions
. compatible Bumblebee . Integer
Public Shared Operator CType(ByVal operand1 As Bumblebee) As Integer
' ----- Perform conversion here, returning an Integer.

Mhm76

End Operator
complain Widening
)Narrowing (.

narrowing widening .
.
Short . Byte
Dim quiteBig As Short = 5000
Dim quiteSmall As Byte
'
quiteSmall = quiteBig
)quiteSmall = CByte(quiteBig
: .5000
Dim quiteBig As Short = 5
Dim quiteSmall As Byte
' ----- These next two lines will succeed.
quiteSmall = quiteBig
)quiteSmall = CByte(quiteBig
5 ). Option Strict On
( 5000 quiteBig . potential
.
narrowing
.conversion narrowing conversion
.
Widening conversions .
. .
. CType .
Bumblebee Integer Option Strict On :
Dim sourceValue As New bumblebee
Dim destValue As Integer = sourceValue
CType :
Dim sourceValue As New bumblebee
)Dim destValue As Integer = CType(sourceValue, Integer
CType
Widening Narrowing Shared . Operator
Public Shared Narrowing Operator CType(ByVal operand1 As bumblebee) As Integer
' ----- Perform narrowing conversion here.
End Operator
Other Operator Overloading Issues.
Bumblebee .
Class Bumblebee
Public Bees As Integer
)(Public Sub New
' ----- Default constructor.
Bees = 0
End Sub
)Public Sub New(ByVal startingBees As Integer

Mhm76

' ----- Assign an initial number of bees.


Bees = startingBees
End Sub
Public Shared Operator +(ByVal operand1 As Bumblebee, ByVal operand2 As Bumblebee) As Bumblebee
' ----- Join bumblebee groups.
Dim newGroup As New Bumblebee
newGroup.Bees = operand1.Bees + operand2.Bees
Return newGroup
End Operator
Public Shared Operator -(ByVal operand1 As Bumblebee, ByVal operand2 As Bumblebee) As Bumblebee
' ----- Separate bumblebee groups.
Dim newGroup As New Bumblebee
newGroup.Bees = operand1.Bees - operand2.Bees
If (newGroup.Bees < 0) Then newGroup.Bees = 0
Return newGroup
End Operator
Public Shared Operator *(ByVal operand1 As Bumblebee, ByVal operand2 As Bumblebee) As Bumblebee
' ----- Create a swarm.
Dim newGroup As New Bumblebee
newGroup.Bees = operand1.Bees * operand2.Bees
Return newGroup
End Operator
Public Shared Widening Operator CType(ByVal operand1 As Bumblebee) As Integer
' ----- Perform conversion here.
Return operand1.Bees
End Operator
End Class
"" .
.
Dim quiteBig As Short = 5
Dim studyGroup1 As New Bumblebee(20)
Dim studyGroup2 As New Bumblebee(15)
Dim swarmGroup As Bumblebee = studyGroup1 * studyGroup2
MsgBox("The swarm contains " & CInt(swarmGroup) & " bees.")
:

. CInt Bumblebee Integer CType


.CType
MsgBox("The swarm contains " & CType(swarmGroup, Integer) & " bees.")
Declaration Requirements

. Public Shared
) .
: Bumblebee (
Public Shared Operator <=(ByVal operand1 As Bumblebee, ByVal operand2 As Integer) As Boolean
' ----- Compare a bumblebee to a value.
End Operator
Public Shared Operator <=(ByVal operand1 As Date, ByVal operand2 As Bumblebee) As Boolean

Mhm76

' ----- Compare a date to a bumblebee.


End Operator
Bumblebee .Bumblebee
Class Bumblebee
Public Shared Operator <=(ByVal operand1 As Date,ByVal operand2 As Integer) As Boolean
. ' -----
End Operator
End Class

Overloading Overloads.

. .
Public Shared Widening Operator CType(ByVal operand1 As Bumblebee) As Integer
. ' -----
End Operator
Public Shared Widening Operator CType(ByVal operand1 As Bumblebee) As Date
. ' -----
End Operator
argument signatures .
Overloads

)(Extension Methods


. tight-fisted .
2008 : )(. extension methods :
.1 .
.2 Module .
.3 .
) String( ) ( .
:
"?Dim bossyString As String = "are you talking to me
))(MsgBox(bossyString.ToUpper
uppercase ToUpper )(
. ToLower ) ( " " ToTitle
.
)) (MsgBox(bossyString.ToTitle
" "ToTitle )(.
module .
Module MyExtensions
<System.Runtime.CompilerServices.Extension()> Public Function ToTitle(ByVal sourceText As String) As String
)Return StrConv(sourceText, VbStrConv.ProperCase
End Function
End Module

))MsgBox(ToTitle(bossyString
) ( System.Runtime.CompilerServices ToTitle
. . new
method-like syntax old function-like syntax .ToTitle
. )ToTitle(bossyString ) (.bossyString.ToTitle
2008 raise . LINQ.

Project.

%25 .
.

Overloading a Conversion

Mhm76

. CType CType ListItemData


. ItemText ItemData textual numeric
. ID . ID )
(SomeList :
Dim recordID As Integer = CType(SomeList.SelectedItem, ListItemData).ItemData
. " CInt
ItemData"
))Dim recordID As Integer = CInt(CType(SomeList.SelectedItem, ListItemData
. CType .ListItemData .
Public Shared Widening Operator CType(ByVal sourceItem As ListItemData) As Integer
,
Return sourceItem.ItemData
End Operator
ListItemData .
ItemData .

Global Support Features.

.
SystemValue . )General (General.vb
Public DefaultItemLocation As Integer
Public SearchMatchLimit As Integer
)( . DefaultItemLocation
CodeLocation . DefaultLocation SystemValue
. SearchMatchLimit
. . SearchLimit
General :
Public Function ConfirmDefaultLocation() As Boolean
.
'
Dim locationID As String
.
'
If (DefaultItemLocation = -1) Then
)"locationID = GetSystemValue("DefaultLocation
"If (locationID = "") Then locationID = "-1
)DefaultItemLocation = CInt(locationID
End If
.
'
If (DefaultItemLocation = -1) Then
_ MsgBox("You must first define the default item location.",
)MsgBoxStyle.OKOnly Or MsgBoxStyle.Exclamation, ProgramTitle
Return False
Else
Return True
End If
End Function
Public Function GetCopyDisposition(ByVal copyID As Integer) As String
' ----- Given the ID of an item copy, return it's current status.
'
The available results are:
'
New Item Copy
Error or missing record
'
Checked In
Copy is checked in and available
'
Checked Out
Copy is checked out by a patron
'
Overdue
Copy is checked out and late
'
Missing
Copy has been reported missing
'
Reference
Copy is a reference copy
Dim sqlText As String
Dim dbInfo As SqlClient.SqlDataReader
Dim response As String
On Error GoTo ErrorHandler
' ----- Retrieve information about the book.
_ & " sqlText = "SELECT IC.Reference, IC.Missing, PC.Missing AS PatronMissing,
_ & " "PC.DueDate, PC.Patron FROM ItemCopy AS IC LEFT JOIN PatronCopy AS PC
_ & "ON IC.ID = PC.ItemCopy WHERE IC.ID = " & copyID
"" AND PC.Returned = 0

Mhm76

dbInfo = CreateReader(sqlText)
If (dbInfo.Read = False) Then
' ----- Perhaps the database, due to the JOIN clause, could not return
'
the base record of a checked-in book.
dbInfo.Close()
sqlText = "SELECT Reference, Missing, NULL AS PatronMissing, " & _
"NULL AS DueDate, NULL AS Patron FROM ItemCopy WHERE ID = " & copyID
dbInfo = CreateReader(sqlText)
If (dbInfo.Read = False) Then
' ----- What happened to the record?
dbInfo.Close()
dbInfo = Nothing
Return "New Item Copy"
End If
End If
' ----- We found the record. Check its details.
If (IsDBNull(dbInfo!Patron) = False) Then
' ----- This item is checked out.
If (CBool(dbInfo!Missing) = True) Or (CBool(dbInfo!PatronMissing) = True) Then
response = "Missing"
ElseIf (CDate(dbInfo!DueDate) < Today) Then
response = "Overdue"
Else
response = "Checked Out"
End If
Else
' ----- This book is currently checked in.
If (CBool(dbInfo!Missing) = True) Then
response = "Missing"
ElseIf (CBool(dbInfo!Reference) = True) Then
response = "Reference"
Else
response = "Checked In"
End If
End If
dbInfo.Close()
dbInfo = Nothing
Return response
ErrorHandler:
GeneralError("GetCopyDisposition", Err.GetException())
On Error Resume Next
If Not (dbInfo Is Nothing) Then dbInfo.Close() : dbInfo = Nothing
Return "New Item Copy"
End Function
ConfirmDefaultLocation
. .SystemValue DefaultLocation
GetCopyDisposition
New : .
.( Reference ) Missing Overdue Checked Out Checked InItem Copy

Extending a Framework-Supplied Class.

first and last names author


. birth and death dates (")"suffixes (Dr ")"prefixes
.
. FormatAuthorName
<System.Runtime.CompilerServices.Extension()> Public Function FormatAuthorName(ByRef dbInfo As
SqlClient.SqlDataReader) As String
' ----- Given an author record, return the formatted name.
Dim authorName As String
On Error Resume Next
' ----- Format the name.
authorName = CStr(dbInfo!LastName)
If (IsDBNull(dbInfo!FirstName) = False) Then
authorName &= ", " & CStr(dbInfo!FirstName)
If (IsDBNull(dbInfo!MiddleName) = False) Then _
authorName &= " " & CStr(dbInfo!MiddleName)
End If

Mhm76

_ If (IsDBNull(dbInfo!Suffix) = False) Then


)authorName &= ", " & CStr(dbInfo!Suffix
' ----- Add in the birth and death years.
_ If (IsDBNull(dbInfo!BirthYear) = False) Or
(IsDBNull(dbInfo!DeathYear) = False) Then
"( " =& authorName
If (IsDBNull(dbInfo!BirthYear) = True) Then
"????" =& authorName
Else
)))authorName &= CStr(Math.Abs(CInt(dbInfo!BirthYear
"If (CInt(dbInfo!BirthYear) < 0) Then authorName &= "BC
End If
"authorName &= "-
If (IsDBNull(dbInfo!DeathYear) = False) Then
)))authorName &= CStr(Math.Abs(CInt(dbInfo!DeathYear
"If (CInt(dbInfo!DeathYear) < 0) Then authorName &= "BC
End If
")" =& authorName
End If
' ----- Finished.
Return authorName
End Function
.SqlClient.SqlDataReader Extension
. SqlDataReader SqlDataReader Author

" ."Public, John Q, Jr. (19001999). :


) (dbInfo.FormatAuthorName

Extension attribute . :
)FormatAuthorName(dbInfo

Record Editors and Supporting Forms.

. 23 . UserName.vb
GroupName.vb .11 .

Search-limiting forms

)( books
authors . publishers ListEditRecords
. security groups GroupName .
.
.
"-" . librarian
ItemLimit )( .

) (.
" " Lookup ListEditRecords
)(. :

AuthorLimit.vb

. Author

ItemLimit.vb

. .NamedItem

PatronLimit.vb

Mhm76

.Patron

PublisherLimit.vb

.Publisher

Keyword and subject editors.

ListEditRecords .
Keywords subjects . ) (
) NamedItem (.
NamedItem ItemKeyword ItemSubject . KeywordAdd SubjectAdd
. :
. KeywordAdd.vb.
. SubjectAdd.vb.

More named item support forms.

NamedItem . )
(. . .
) (KeywordAdd : .SubjectAdd .

AuthorAddLocate.vb

.
authors editors illustrators performers
)(1 (2)CodeAuthorType )(3 .
. .

. Next )
ActivePanel (. : author type
If (CInt(CType(NameType.SelectedItem,ListItemData)) = -1) Then
",MsgBoxStyle.OkOnly Or "(MsgBox
)MsgBoxStyle.Exclamation,ProgramTitle
)(NameType.Focus
Return
End If
'
ActivePanel = PanelCriteria
SecondPanel.Visible = True
FirstPanel.Visible = False
ActBack.Enabled = True
)(LastName.Focus
CInt ItemData . CType
.ListItemData

PublisherAddLocate.vb

. . type
. Publisher
.PublisherAddLocate.PromptUser ID 1- . 2-
.

SeriesAddLocate.vb

PublisherAddLocate .CodeSeries

ItemAuthorEdit.vb

10

Mhm76


.AuthorAddLocate ) " " Editor " (" Illustrator
. . ItemAuthorEdit .
.ItemAuthor.AuthorType

ItemCopy.vb

. NamedItem
ItemCopy . ) (.

BaseCodeForm
SaveFormData .
. wedge
keyboard input stream. .
) ( ) ( Enter .
. Enter " " OK . .
" " OK .
_ )Private Sub RecordBarcode_Enter(ByVal sender As Object, ByVal e As System.EventArgs
Handles RecordBarcode.Enter
'
)(RecordBarcode.SelectAll
'
Me.AcceptButton = Nothing
End Sub
_ (Private Sub RecordBarcode_Leave
_ )ByVal sender As Object, ByVal e As System.EventArgs
Handles RecordBarcode.Leave
'

Me.AcceptButton = ActOK
End Sub
_ Private Sub RecordBarcode_KeyPress(ByVal sender As Object,
_ )ByVal e As System.Windows.Forms.KeyPressEventArgs
Handles RecordBarcode.KeyPress
'
If (e.KeyChar = ChrW(Keys.Return)) Then e.Handled = True
End Sub

. .

Inherited code editors.

12 . BaseCodeForm :

Author.vb

Author . Author . BaseCodeForm


. UsesSearch .SearchForRecord
ListEditRecords AuthorLimit ).
FillListWithRecords SearchForRecord (.
SearchForLimit AuthorLimit.PromptUser " Last." First

11

Mhm76
'
exceededMatches = False
)(userLimit = (New AuthorLimit).PromptUser
If (userLimit = "") Then Return

)*( wildcard .
. wildcard " ." SELECT ) (%
) ( SearchForLimit
.

'
))limitLast = Trim(GetSubStr(userLimit, ",", 1
))limitFirst = Trim(GetSubStr(userLimit, ",", 2
If ((limitLast & limitFirst) = "") Then Return
"*" =& If (InStr(limitLast, "*") = 0) Then limitLast
"*" =& If (InStr(limitFirst, "*") = 0) Then limitFirst
)"limitLast = Replace(limitLast, "*", "%
)"limitFirst = Replace(limitFirst, "*", "%
GetSubStr .General
Replace * .% .
Publisher .
. Imports.

Imports MVB = Microsoft.VisualBasic


Imports . = MVB Microsoft.VisualBasic
. )(
. Left .RIGHT Author
Left Left
. Left .
)smallerString = Left(largerString, 5
.Me.Left Left .
)smallerString = Microsoft.VisualBasic.Left( largerString, 5
Imports Microsoft.VisualBasic .
)smallerString = MVB.Left(largerString, 5
.MVB
Name Matches . :

.
. Author RefreshMatchingAuthors :
& " sqlText = "SELECT COUNT(*) AS TheCount " & "FROM Author WHERE LastName LIKE
))DBText(Trim(RecordLastName.Text
If (Trim(RecordFirstName.Text) <> "") Then
)"sqlText &= " AND FirstName LIKE " & DBText(MVB.Left(Trim(RecordFirstName.Text), 1) & "%
End If
))matchCount = CInt(ExecuteSQLReturn(sqlText
SearchForLimit wildcard .

CodeAuthorType.vb

.CodeAuthorType

CodeCopyStatus.vb

.CodeCopyStatus

CodeLocation.vb

.CodeLocation
. .

CodeMediaType.vb

. CodeMediaType . Code
) (

12

Mhm76

. RecordCheckoutDays text fields


KeyPress :
'
If (e.KeyChar = vbBack) Or (sNumeric(e.KeyChar)) Then Return
e.Handled = True
e.Handled True .

CodePatronGroup.vb

.CodePatronGroup

CodeSeries.vb

. CodeSeries keywords series names


.named items . .
: ListEditRecords
NamedItem .

.
CodeSeries .
. AddRecord .
Public Overrides Function AddRecord() As Integer
'
ActiveID = -1
)(PrepareFormFields
)(Me.ShowDialog
_ If (Me.DialogResult = Windows.Forms.DialogResult.OK) Then
Return ActiveID Else Return -1
End Function

. .
Text RecordFullName .

Public Overloads Function AddRecord(ByVal seriesText As String) As Integer


ActiveID = -1
)(PrepareFormFields
RecordFullName.Text = seriesText
)(Me.ShowDialog
If (Me.DialogResult = Windows.Forms.DialogResult.OK) Then Return ActiveID Else Return -1
End Function
AddRecord . overload ) (.

Holiday.vb

. .

Patron.vb

Patron .

TabControl . tab
6 . .
TabPage. TabPage
SelectedTab .TabControl .ValidateFormData
TabPatron.SelectedTab = TabGeneral

13

Mhm76

. BaseCodeForm
) ( ) bar code ( ItemCopy password
UserName .Author
Manage Patrons Items .
EditRecordLimited .

Publisher.vb

. Publisher . " " Status


" " NamedItem . . "
" ShowWeb .
" ".

SystemValue.vb

'
Dim newProcess As ProcessStartInfo
On Error Resume Next
If (Trim(RecordWeb.Text) = "") Then Return
))newProcess = New ProcessStartInfo(Trim(RecordWeb.Text
)Process.Start(newProcess

. SystemValue
.
11 12 . NamedItem .

NamedItem . BaseCodeForm
.NamedItem ) (ItemCopy ItemAuthor :
ItemSubject ItemKeyword Publisher Keyword Author : .Subject

"" NamedItem
. Series Publisher ) PublisherAddLocate (SeriesAddLocate
ID .NamedItem :
'
)(newPublisher = (New PublisherAddLocate).PromptUser
If (newPublisher = -1) Then Return
'
If (newPublisher = -2) Then
"RecordPublisher.Text = "Not Available
PublisherID = -1
Return
End If

-/ Authors/Names Subjects Keywords- Copies .


) ( /) (.

14

Mhm76

ListEditRecords .
.ItemAuthor " " ListView
ListBox. View
" " ListView "" Details FullRowSelect True ) Columns
( listbox . multicolumn

" " subitems .


)"Dim newItem As Windows.Forms.ListViewItem = AuthorsList.Items.Add("John Smith
)"newItem.SubItems.Add("Illustrator
" "Add AuthorAddLocate " " Properties .ItemAuthorEdit

" " parent . " " child ID


ID.
" " Add :
'

If (ActiveID = -1) Then
'
" & " "(If (MsgBox
_ ", MsgBoxStyle.YesNo Or MsgBoxStyle.Question, " & "
ProgramTitle) <> MsgBoxResult.Yes) Then Return
'
If (ValidateFormData() = False) Then Return
If (SaveFormData() = False) Then Return
End If
NamedItem )(ActiveID = 1 .
ValidateFormData ValidateFormData SaveFormData

" ." OK ID .
SaveFormData " )" Cancel 1- "
"( SaveFormData .SessionSaved
SessionSaved = True
. NamedItem
AddRecord EditRecord .

15

Mhm76

If (Me.DialogResult = Windows.Forms.DialogResult.OK) Or (SessionSaved = True) Then Return


ActiveID Else Return -1
. NamedItem .

Connecting the Editors to the Main Form.

. .
LinkLabel ).(PanelAdmin 12 LinkClicked
. .
LinkClicked . :
Private Sub AdminLinkPublishers_LinkClicked(ByVal sender As System.Object, ByVal e As
_ )System.Windows.Forms.LinkLabelLinkClickedEventArgs
Handles AdminLinkPublishers.LinkClicked
_ = )If (SecurityProfile(LibrarySecurity.ManagePublishers
False) Then
_ MsgBox(NotAuthorizedMessage, MsgBoxStyle.OkOnly Or
)MsgBoxStyle.Exclamation, ProgramTitle
Return
End If
)ListEditRecords.ManageRecords(New Library.Publisher
ListEditRecords = Nothing
End Sub
ListEditRecords .

Setting the Default Location.

. " " Login


. " " admin
. item copies
. default location :
.1 " " Locations .
.2 ID CodeLocation .
SQL Server Management Studio Express
. CodeLocation ID 1.
.3 SystemValue System Values .
.4 " " DefaultLocation ID .

" " DefaultLocation SystemValue


. SQL Server Management Studio Express ID location 1 :
)Update(SystemValue
'SET ValueData = '1
'WHERE ValueName = 'DefaultLocation
.

16

: .

Mhm76

(Extensible Markup Language)XML


XML .
)SGML ( Standard Generalized Markup Language )HTML
)( (Hyper Text Markup Language SGML )GML Generalized Markup
(Language " ) metalanguage ( IBM .1960
Xs.

?What Is XML
XML .
. sift out )(.
. proprietary binary format proprietary . .
binary .
).
. willy-nilly
(

Binary files : . :
. secrecy
.
.
. ) tab-delimited (
)CSV ( comma-separated value )( .
" " Northwind . comma-separated values
ProductID,ProductName,SupplierID,Category,UnitPrice,Available
""1""Chai","652","Beverages","$18.00","Yes
""2""Chang","9874","Beverages","$19.00","No
""3""Aniseed Syrup","9874","Condiments","On Sale","Yes
. . .
. .csv
.
. " "652" "9874 Aniseed Syrup
" " On Sale

XML
XML .
XML . XML
simpler text . binary proprietary formats
proprietary .
XML contender :

Its straightforward to read


.

Its easy to process

Mhm76
: .
. ruin
.

Its flexible
.XML . XML 1
2 1 2 .

Its self-describing
XML . XML ) DTD Document Type
(Definition) XSD .(( XML Schema Definition) XML
. XML .

Its self-verifying
XML DTD XSD
. .

Its an open standard


XML widespread acceptance . divergent computer platforms

)( Its built into .NET


. XML . .
:

) ( Its bulky
XML . abbreviate
) whitespace (XML .
platforms cell phone browser XML . .

Its text
. binary .
XML XML: ! -
)64 (

Its inefficient
)( .
)(

.

Its human-readable
.XML
.XML

Its machine-readable.
XML .

)( Its not immune to errors .


XML . .

The XML Rule.


XML . obey XML .

THE RULE
If you open it, close it.

.. .

XML Content. XML


XML HTML .

Some Basic XML


XML .
>?"<?xml version="1.0
><hello
><there
><!-- Finally, real data here. --
><world target="everyone">think XML</world
><totalCount>694.34</totalCount
><goodbye /

: .

Mhm76
></there
></hello

XMLIts obviously XML .


<?xml... XML )XML
(parsers .

Its structured
XML . .
totalCount world there hello .goodbye > < angle brackets
>). <hello>...</hello " "( " " / .
.
)<tagname /> ( shortened syntax .goodbye
By the way XML case-sensitive .

Its readable
.XML.
consistent.

Its a single unit of data


XML root element . <hello>
)(. ) ( .

Its got comments


><!-- Finally, real data here. -- . free-floating
.tags

) (Its got attributes.


XML varieties real data: .attributes. innermost
think XML 694.34 . . attribute
target .world )""(.
. disagreement
subelement
) conscience ()(.

- Some Basicand MeaningfulXML .XML


" " Northwind .XML
>?"<?xml version="1.0
><productList
>"<supplier ID="652" fullName="Beverages R Us
>"<product ID="1" available="Yes
><productName>Chai</productName
><category>Beverages</category
><unitPrice>18.00</unitPrice
></product
></supplier
>"<supplier ID="9874" fullName="We Sell Food
>"<product ID="2" available="No
><productName>Chang</productName
><category>Beverages</category
><unitPrice>19.00</unitPrice
></product
>"<product ID="3" available="Yes" onSale="true
><productName>Aniseed Syrup</productName
><category>Condiments</category
><unitPrice>12.00</unitPrice
></product
></supplier
></productList

XML . .
XML. supplier XML
supplier ) (.
. .

?What About the Human-Readable Part

Mhm76
: .
XML XSLT Transformations XSL ) XSL
.( eXtensible Stylesheet Language XSLT scripting language
XML . XSL XML
. XSL XML ) >(<productList ?xml :
>?"<?xml version="1.0
>?"<?xml-stylesheet type="text/xsl" href="hello.xsl
hello.xml: XSLT .hello.xsl
>?"<?xml version="1.0
>"<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0
>"<xsl:template match="/
><xsl:text
ProductID,ProductName,SupplierID,Category,UnitPrice,Available
></xsl:text
><BR/
><xsl:apply-templates/
></xsl:template
>"<xsl:template match="supplier
><xsl:variable name="supID" select="@ID"/
">"<xsl:for-each select="product
"<xsl:value-of select="@ID"/> ",
<xsl:value-of select="productName"/> ",
"<xsl:value-of select="$supID"/> ",
"<xsl:value-of select="category"/> ",
><xsl:choose
><xsl:when test="@onSale='true'">On Sale</xsl:when
<xsl:otherwise>$
><xsl:value-of select="unitPrice"/
></xsl:otherwise
"</xsl:choose> ",
" ><xsl:value-of select="@available"/
><BR/
></xsl:for-each
></xsl:template
></xsl:stylesheet

. . Internet Explorer
. hello.xml :
ProductID,ProductName,SupplierID,Category,UnitPrice,Available
"1","Chai","652","Beverages","$18.00","Yes"
"2","Chang","9874","Beverages","$19.00","No"
""3","AniseedSyrup","9874","Condiments","OnSale","Yes
XML XSLT ).
> <BR/ XSLT . (
comma-separated data set XSLT XSLT
HTML XML XML .
> <xsl:template parser XML )( ) pattern
.(supplier ><xsl:template XML .)(
match XML: XPath .XML
! .

XML Schemas .XML


) XSD (XML Structure Definitions XML " " language " " vocabulary
XML . XML
. . XSD XML
.
) DTD Document Type Definition XSD . XML
. XSD XSD XSD (.
XSD )( endearing .XSLT XSD <productList> XML
.
XML XSD . :
>"xml version="1.0<
><productList

:
>"xml version="1.0<

Mhm76
. :
"productList xmlns="SimpleProductList>
"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
<"xsi:noNamespaceSchemaLocation="hello.xsd
hello.xsd . . hello.xsd XML ( directives )
:
"xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema>
<"targetNamespace="SimpleProductList
</"xs:element name="productList" type="ProductListType>
<"xs:complexType name="ProductListType>
<xs:sequence>
"xs:element name="supplier" type="SupplierType>
</"maxOccurs="unbounded
<xs:sequence/>
<xs:complexType/>
<"xs:complexType name="SupplierType>
<xs:sequence>
"xs:element name="product" type="ProductType>
</"maxOccurs="unbounded
<xs:sequence/>
</"xs:attribute name="ID" type="xs:integer>
</"xs:attribute name="fullName" type="xs:string>
<xs:complexType/>
<"xs:complexType name="ProductType>
<xs:sequence>
</"xs:element name="productName" type="xs:string>
</"xs:element name="category" type="xs:string>
</"xs:element name="unitPrice" type="xs:decimal>
<xs:sequence/>
</"xs:attribute name="ID" type="xs:integer>
</"xs:attribute name="available" type="YesOrNoType>
</"xs:attribute name="onSale" type="xs:boolean>
<xs:complexType/>
<"xs:simpleType name="YesOrNoType>
<"xs:restriction base="xs:string>
</"xs:enumeration value="Yes>
</"xs:enumeration value="No>
<xs:restriction/>
<xs:simpleType/>
<xs:schema/>
"(node " "tag ) " .XSLT
. attributes subelements XML
( limiting factors ( )pseudodata)
.No Yes YesOrNoType
.XML . .)( XSD XML
. XML ) (

XML Namespaces .XML


XML product list
:
<"xml version="1.0>
<allProducts>
<"vendor ID="652" vendorName="Beverages R Us>
<"item ID="1" available="Yes>
<itemName>Chai</itemName>
<group>Beverages</group>
<priceEach>18.00</priceEach>
<item/>

: .

Mhm76
><vendor/
><allProducts/

tags. incompatible .
XSD bogus data set
. . namespaces
namespaces " XML XSD-defined language
". XSD :
>"xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema
xs ).xmlns :xs XML (.
)( ) Uniform Resource Identifier (URI .
.
.
XML " " xs:schema
" " schema. " XSD ". xs
" " default descendants xmlns .
. :
<productList xmlns="SimpleProductList"...

XML .
XML publicly published standard . )(
XML .XML XML
. namespaces
XSD XML flexible. powerful
tools .
XML XML ensure .

XML : Using XML in .NET: The Old Way


: XML . System.Xml
object-based XML attributes. data
2008 System.Xml.Linq XML
. .
XML .XML
System.Xml :
System.Xml

XML . old-way XML-related classes


System.Xml.Linq

)XML ( integrate . LINQ .


System.Xml.Schema

.XSD
System.Xml.Serialization

XML . standard .NET stream


System.Xml.XPath

XPath .XML
System.Xml.Xsl

.XSL
XML XSLT. XSD

XML The Basic XML Classes, Basically.


The System.Xml . XML XmlDocument
XML:
Dim myData As New System.Xml.XmlDocument
) declarations >? <?xml... ( ) data elements tags
( ) attributes (. comments XmlDeclaration

XmlComment XmlAttributeXmlElement . " " nodes


). XmlNode(. XML
.XmlElement XmlNode.
product data. XML
>?"<?xml version="1.0
><productList
><!-- We currently sell these items. --

. :

Mhm76
<supplier ID="652" fullName="Beverages R Us">
<product ID="1" available="Yes">
<productName>Chai</productName>
<category>Beverages</category>
<unitPrice>18.00</unitPrice>
</product>
</supplier>
</productList>

.
Dim products As Xml.XmlDocument
Dim prodDeclare As Xml.XmlDeclaration
Dim rootSet As Xml.XmlElement
Dim supplier As Xml.XmlElement
Dim product As Xml.XmlElement
Dim productValue As Xml.XmlElement
Dim comment As Xml.XmlComment
' ----- Create the document with a valid declaration.
products = New Xml.XmlDocument
prodDeclare = products.CreateXmlDeclaration("1.0", _
Nothing, String.Empty)
products.InsertBefore(prodDeclare, products.DocumentElement)
' ----- Create the root element, <productList>.
rootSet = products.CreateElement("productList")
products.InsertAfter(rootSet, prodDeclare)
' ----- Add a nice comment.
comment = products.CreateComment( _
" We currently sell these items. ")
rootSet.AppendChild(comment)
' ------ Create the supplier element, <supplier>.
' Include the attributes.
supplier = products.CreateElement("supplier")
supplier.SetAttribute("ID", "652")
supplier.SetAttribute("fullName", "Beverages R Us")
rootSet.AppendChild(supplier)
' ----- Create the product element, <product>, with the
' subordinate data values.
product = products.CreateElement("product")
product.SetAttribute("ID", "1")
product.SetAttribute("available", "yes")
supplier.AppendChild(product)
productValue = products.CreateElement("productName")
productValue.InnerText = "Chai"
product.AppendChild(productValue)
productValue = products.CreateElement("category")
productValue.InnerText = "Beverages"
product.AppendChild(productValue)
productValue = products.CreateElement("unitPrice")
productValue.InnerText = "18.00"
product.AppendChild(productValue)

.( )
products.Save("c:\products.xml")
XML XML .XML product data c:\products.xml
productsupplier SetAttribute .

.
Dim attrData As XmlAttribute
attrData = products.CreateAttribute("ID")
attrData.Value = "652"
supplier.SetAttributeNode(attrData)

Load XmlDocument XML


.XmlDocument
Dim products As XmlDocument
products = New XmlDocument
products.Load("c:\products.xml")

Mhm76
: .
)( XML
XmlTextReader XmlTextWriter XML . text stream
XML Load Save XmlDocument .

Finding Needles and Haystacks


products . products
supplier XmlDocument .XmlNodeList
Dim justProducts As XmlNodeList
Dim oneProduct As XmlNode
' ----- First, get the list.
)"justProducts = products.GetElementsByTagName("product
' ----- Then do something with them.
For Each oneProduct In justProducts
' ----- Put interesting code here.
Next oneProduct
)"MsgBox("Processed " & justProducts.Count.ToString() & " product(s).
System.Xml.XPath XPath .

)(Schema Verification.
XmlDocument XML .XSD
XML XSD DTD )XDR XML XML Data Reduced schemas
( XSD XmlReader XmlReaderSettings XML
.
Dim products As New XmlDocument
Dim xmlRead As XmlTextReader
Dim withVerify As New XmlReaderSettings
Dim xmlReadGood As XmlReader
' ----- Open the XML file and process schemas
' referenced within the content.
withVerify.ValidationType = ValidationType.Schema
)"xmlRead = New XmlTextReader("c:\temp\products.xml
)xmlReadGood = XmlReader.Create(xmlRead, withVerify
' ----- Load content, or throw exception on
' validation failure.
)products.Load(xmlReadGood
' ----- Clean up.
)(xmlReadGood.Close
)(xmlRead.Close

XML Transformations .XML


XSL . XML )XML
XmlDocument( . input file
output file . System.Xml.Xsl.XslCompiledTransform .
' ----- Above: Imports System.Xml.Xsl
Dim xslTrans As XslCompiledTransform
' ----- Open the XSL file as a transformation.
)(xslTrans = New XslCompiledTransform
)"xslTrans.Load("c:\convert.xsl
' ----- Convert and save the output.
)"xslTrans.Transform("c:\input.xml", "c:\output.txt

XML : Using XML in .NET: The New Way.


.XML . 2008
.
)( XML . XML product list
" " Chai XML 11 50 . XML
11 .
>?"Dim chaiItem As System.Xml.Linq.XDocument = <?xml version="1.0
><productList
><!-- We currently sell these items. --
>"<supplier ID="652" fullName="Beverages R Us
>"<product ID="1" available="Yes

: .

Mhm76

><productName>Chai</productName
><category>Beverages</category
><unitPrice>18.00</unitPrice
></product
></supplier
></productList
. XML. XML new XML Literals feature XML

. XDocument . System.Xml.Linq XML

.
XElement
_ = Dim productSection As System.Xml.Linq.XElement
>"<product ID="1" available="Yes
><productName>Chai</productName
><category>Beverages</category
><unitPrice>18.00</unitPrice
></product

)( ) ( Option Infer On XElement


.XDocument
_ = Dim productSection
>"<product ID="1" available="Yes
><productName>Chai</productName
><category>Beverages</category
><unitPrice>18.00</unitPrice
></product
XmlDocument XDocument " "Load" " Save .XML

XML Embedded XML Expressions.


XML " " Chai " "$18.00 . XML
. XML "" Literal XML XML
. embedded XML expressions =<%> %
.
"Dim productName As String = "Chai
"Dim productCategory As String = "Beverage
@Dim productPrice As Decimal = 18
Dim isAvailable As Boolean = True
_ = Dim productSection
><product ID=<%= productID %
>>available=<%= Format(isAvailable, "Yes/No") %
><productName><%= productName %></productName
><category><%= productCategory %></category
><unitPrice><%= productPrice %></unitPrice
></product

products . 17
XML .

XML Axis Properties .XML


" " Finding Needles and Haystacks
XML . XML XML.
XML :

Child-member axis
)( XElement :
>childElement = parentElement.<childName

Descendent-member axis
) (.
.
):(.
>setOfElements = parentElement...<descendentName

Attribute axis .
@ .
attributeValue = parentElement.@attributeName
ID . console
>For Each oneProduct In allProducts...<product

: .

Mhm76

_ & " Console.WriteLine(oneProduct.@ID & ":


)oneProduct.<productName>.Value
Next oneProduct
. axis styles For Each...Next ><product
descendent-member axis ID attribute axis
child-member axis Value . :

1: Chai
2: Chang
3: Aniseed Syrup

Namespaces and Schemas for XML Literals .XML


XML .XML XML
.
_ = Dim foodItems
>?"<?xml version="1.0
>"<menu:items xmlns:menu="http://www.timaki.com/menu
><menu:item
><menu:name>Pizza</menu:name
><menu:price>12.99</menu:price
></menu:item
><menu:item
><menu:name>Breadsticks</menu:name
><menu:price>1.99</menu:price
></menu:item
></menu:items
xmlns ) ( variation . Imports
>"Imports <xmlns:menu="http://www.timaki.com/menu
'...later...
_ = Dim foodItems
>?"<?xml version="1.0
><menu:items
...and so on...
xmlns . XML XNamespace XDocument

.XElement XNamespace )( GetXmlNamespace .


)Dim justTheNamespace = GetXmlNamespace(menu

Project .
.
conceivable

. )(

. .
. .
XML .
.
XML indent.
) (.
Detail Reports
Daily Report
Monthly Reports
Monthly Value
Monthly Inventory
)(Summary Reports
Inventory Summary
XML :
>"<Group name="Detail Reports
><Item name="Daily Report"/
>"<Group name="Monthly Reports
><Item name="Monthly Value"/
><Item name="Monthly Inventory"/
></Group
></Group

10

: .

Mhm76
>"<Group name="SummaryReports
><Item name="Inventory Summary"/
></Group

XML ) ( noncompliant .
:
) (Built-in reports.
).( assembly 1
. XML .
absence . ) 1(5
display text . long description
Application reports.
EXE initiation . display
text identity of the user ) ( .
URL reports :
. URL URL .
) (XML

Update Technical Documentation.


. XML XML

)(.
Report Configuration File.
. .XML
" " groups"." items .
)( .
.
XML > <reportList > <reportGroup>:<reportItem
>:<reportItem . attribute )( subordinate
:
) type:( attribute :
.) ( :built-in ) (. > <displayText
> <reportPath>. <description
.: program EXE. ><reportArgs> <reportPath> <displayText
<reportFlags>>. <description
. : url ) URL (Uniform Resource Locator " " mailto
. > <reportPath> <displayText>.<description
>: <displayText . .
>: <reportPath full path URL number of the report
. )( EXE UNC .
) ( built-in 1 )5 (. URL
http://mysite.com/myreport.aspx .mailto:helpdesk@mysite.com.
.
>: <reportArgs )( EXE arguments commandline
. )( .
>:<reportFlags )( EXE
. .U U -u userid ) userid
.( UserName.LoginID EXE .
>: <description verbose 200 Report form
. .
.
. >:<reportGroup category group indent
. > <displayText > <reportItem><reportGroup
><displayText : . .
"" :
1. )( Items Checked Out Report.
2. Items Overdue Report.
3. Items Missing Report.

11

: .

Mhm76

4. Fines Owed by Patrons Report.


5. Library Database Statistics Report.

Create Report Entry Class .


ListBox items
. " "ToString
.
ReportItem.vb <<Project . Add Class
.Class...End Class . :
Public Class ReportItem
.
.
.
End Class
Public Enum ReportItemEnum

'
GroupLabel = 0
BuiltInCheckedOut = 1
BuiltInOverdue = 2
BuiltInMissing = 3
BuiltInFinesOwed = 4
BuiltInStatistics = 5
ExeProgram = 6
UrlProgram = 7
End Enum

.ReportItem configuration
.file
'
'ReportSelect
Public ItemType As ReportItemEnum
'
Public Indent As Integer
Public DisplayText As String
Public ReportPath As String ' ExeProgram / UrlProgram only
Public ReportArgs As String ' ExeProgram only
Public Description As String
Public Overrides Function ToString() As String
. '
Return StrDup(Indent * 5, " ") & DisplayText
End Function

Design the Report Form.


Librarians administrators ) ( .
ListBox Run .
label .

) (.

12

Mhm76
. :
.
" FullDescription " label .
. .
Private Sub AllReports_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Handles AllReports.SelectedIndexChanged
,
'
Dim reportEntry As Library.ReportItem

'
FullDescription.Text = ""
If (AllReports.SelectedIndex <> -1) Then

'
reportEntry = CType(AllReports.SelectedItem, Library.ReportItem)
FullDescription.Text = reportEntry.Description
End If
End Sub

Populate Reports from Configuration File.


. RefreshReportList
.
XML XML .
.
Private Sub RefreshReportList()

'
Dim configFile As String
Dim configData As Xml.XmlDocument
Dim reportEntry As ReportItem
Dim counter As Integer
On Error GoTo ErrorHandler

'
AllReports.Items.Clear()

'

, :
'
configFile = "c:\ReportConfig.txt"

'
If (configFile <> "") Then
If (System.IO.File.Exists(configFile)) Then

'
configData = New Xml.XmlDocument
configData.Load(configFile)

'
LoadReportGroup(configData.DocumentElement, 0)
End If
End If

'

'
If (AllReports.Items.Count = 0) Then
For counter = 1 To CInt(ReportItemEnum.BuiltInStatistics)

'
reportEntry = New ReportItem
reportEntry.Indent = 0
reportEntry.ItemType = CType(counter, ReportItemEnum)
Select Case reportEntry.ItemType
Case ReportItemEnum.BuiltInCheckedOut
reportEntry.DisplayText = ""
Case ReportItemEnum.BuiltInOverdue
reportEntry.DisplayText = ""
Case ReportItemEnum.BuiltInMissing
reportEntry.DisplayText = ""
Case ReportItemEnum.BuiltInFinesOwed
reportEntry.DisplayText = ""
Case ReportItemEnum.BuiltInStatistics
reportEntry.DisplayText = ""
End Select

'
' ----- Add the report entry to the list.
AllReports.Items.Add(reportEntry)
Next counter

13

Mhm76

. :

End If
Return
ErrorHandler:
GeneralError("ReportSelect.RefreshReportList", Err.GetException())
Resume Next
End Sub

( )recursive
RefreshReportList LoadReportGroup .
. <reportList>( LoadReportGroup) .
.<reportGroup> reference point <reportGroup>
Private Sub LoadReportGroup(ByVal groupNode As Xml.XmlNode, ByVal indentLevel As Integer)
' .
' .
Dim scanNode As Xml.XmlNode
Dim detailNode As Xml.XmlNode
Dim reportEntry As ReportItem
On Error GoTo ErrorHandler
' .
For Each scanNode In groupNode.ChildNodes
' .
reportEntry = New ReportItem
reportEntry.Indent = indentLevel
' .
detailNode = scanNode.SelectSingleNode("displayText")
If (detailNode Is Nothing) Then Continue For
reportEntry.DisplayText = Trim(detailNode.InnerText)
If (scanNode.Name = "reportGroup") Then
' .
reportEntry.ItemType = ReportItemEnum.GroupLabel
AllReports.Items.Add(reportEntry)
'
LoadReportGroup(scanNode, indentLevel + 1)
ElseIf (scanNode.Name = "reportItem") Then
' , .
detailNode = scanNode.SelectSingleNode("reportPath")
If Not (detailNode Is Nothing) Then reportEntry.ReportPath =
Trim(detailNode.InnerText)
' .
detailNode = scanNode.SelectSingleNode("reportArgs")
If Not (detailNode Is Nothing) Then reportEntry.ReportArgs =
Trim(detailNode.InnerText)
'
detailNode = scanNode.SelectSingleNode("reportFlags")
If Not (detailNode Is Nothing) Then
If (InStr(UCase(detailNode.InnerText), "U") > 0) And (LoggedInUserName <> "")
Then reportEntry.ReportArgs = _
Trim(reportEntry.ReportArgs & " -u " & LoggedInUserName)
End If
detailNode = scanNode.SelectSingleNode("description")
If Not (detailNode Is Nothing) Then reportEntry.Description =
Trim(detailNode.InnerText)
If (scanNode.Attributes("type").Value = "built-in") Then
If (IsNumeric(reportEntry.ReportPath) = False) Or (Val(reportEntry.ReportPath)
< 1) Or (Val(reportEntry.ReportPath) > _
CInt(ReportItemEnum.BuiltInStatistics)) Then Continue For
reportEntry.ItemType = CType(CInt(reportEntry.ReportPath), ReportItemEnum)
AllReports.Items.Add(reportEntry)
ElseIf (scanNode.Attributes("type").Value = "program") Then
If (reportEntry.ReportPath = "") Then Continue For
reportEntry.ItemType = ReportItemEnum.ExeProgram
AllReports.Items.Add(reportEntry)
ElseIf (scanNode.Attributes("type").Value = "url") Then
If (reportEntry.ReportPath = "") Then Continue For
reportEntry.ItemType = ReportItemEnum.UrlProgram
AllReports.Items.Add(reportEntry)
End If
End If
Next scanNode

14

Mhm76

. :

Return
ErrorHandler:
GeneralError("ReportSelect.LoadReportGroup", Err.GetException())
Resume Next
End Sub

. Load
Private Sub ReportSelect_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RefreshReportList()
End Sub

Running the Reports.


. " ActRun ".
.21 )(" built-in " .
Private Sub ActRun_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
ActRun.Click

'
Dim reportEntry As Library.ReportItem
On Error GoTo ErrorHandler

'
If (AllReports.SelectedIndex = -1) Then
MsgBox("" , MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, _
ProgramTitle)
Return
End If

'
reportEntry = CType(AllReports.SelectedItem, Library.ReportItem)
Me.Cursor = Windows.Forms.Cursors.WaitCursor
Select Case reportEntry.ItemType
Case ReportItemEnum.GroupLabel

'
MsgBox("" , MsgBoxStyle.OkOnly Or
MsgBoxStyle.Exclamation, ProgramTitle)
Case ReportItemEnum.BuiltInCheckedOut

'
:
'
'BasicReportCheckedOut()
Case ReportItemEnum.BuiltInOverdue

'
:
'
' BasicReportOverdue()
Case ReportItemEnum.BuiltInMissing

'
:
'
' BasicReportMissing()
Case ReportItemEnum.BuiltInFinesOwed

'
:
'
' BasicReportFines()
Case ReportItemEnum.BuiltInStatistics

'
:
'
' BasicReportStatistics()
Case ReportItemEnum.ExeProgram

'
Process.Start("""" & reportEntry.ReportPath & """ " & _
reportEntry.ReportArgs)
Case ReportItemEnum.UrlProgram

'
' ----- Start a URL.
Process.Start(reportEntry.ReportPath)
End Select
Me.Cursor = Windows.Forms.Cursors.Default
Return
ErrorHandler:
GeneralError("ReportSelect.ActRun_Click", Err.GetException())
Resume Next
End Sub

15

: .

Mhm76

. Process.Start URL

Connecting the Select Report Form.


.
." " ActDoReports . "
" ActDoReports .
Private Sub ActDoReports_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
ActDoReports.Click
)(ReportSelect.ShowDialog
End Sub

)( XML .

16

You might also like