Professional Documents
Culture Documents
ProgrammingVisualBasic2008
Mhm76
2008
25
2008
.
.
" "2008
.
2005
.
. .
mhm76 . .
mhm76
mhm76
.
(
Module Module1
)(Sub Main
)"Console.WriteLine("hell world
)(Console.Read
End Sub
End Module
MSIL Main )
.
. CLR
IL . IL .
IL . IL
. IL .
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 ( .
.
mhm76
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
. .
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 .
.
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
.
. ) ( 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.
.
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
: .
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
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
. .
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
seven = 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
* .
)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
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
If (billValue = 1) Then
= presidentName
= ElseIf (billValue
= presidentName
= ElseIf (billValue
= presidentName
...
.
ElseIf .
Select Case :
"= "Washington
"= "Jefferson
"= "Lincoln
"= "Jackson
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 :
)"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
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 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
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
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
. .
.
Dim executive As New Employee
...
)(executive.StartVacation
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 .
:
.
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
: .
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
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
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 .
. :
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
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
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
)
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
1038
.
)( customer product INSERT.
:
''John O''Sullivan
. misinterpret
" " unassigned . "
" null " ." NULL " " NULL
.NOT NULL
:DELETE
DELETE FROM LineItems WHERE RecordID = 92231
mhm76
UPDATE
SET
WHERE
DELETE UPDATE
.WHERE
DML " ." SELECT
SELECT ProductID, Quantity FROM LineItems
WHERE RecordID = 92231
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
:
Inner join:
. .INNER JOIN
mhm76
. .RIGHT 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
. .
mhm76
.
. user documentation .
database documentation .
.
100,000 )(
. .
. :
) (.
. Database Creation Script.sql
SQL Server database script .
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
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
. .
.
DatabaseVersion
""1 .
DefaultLocation
CodeLocation.ID
)FineGrace (
location .
. )0(
) 1-(.
.
SearchLimit
. .250
inclusive 25.5000
TicketHeading
. . )|(
.
TicketFooting
. . )|( .
UseLC
16
mhm76
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);
17
mhm76
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
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#
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
.System.dll
) ( libraries .GAC private assemblies
DLL .
.NET Framework WindowsApplication1
.WindowsApplication1
. .GAC
.
My
)( 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.
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
:
My.User.Name
.
mark down .
professionalVersion = True . #Const .compiler constants
#Const fullVersion = True
#. . If
:
If (professionalVersion = True) Then
)(ShowWhizBangFeatures
Else
)(ShowLaughableFeatures
End If
mhm76
.
. .
Compile ) project properties (.
Advanced Compile Options " " Custom constants
Project
:
.version number
conveys .
(1/ )(2 .
Adding Controls
excels .
. ) Integrated Development Environment (IDE .
.
A
B
:
. A toolbox:
.
mhm76
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.
.
. " " 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:
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 .
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
mhm76
1.0Revision 0, :
.
. " " 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 .
10
mhm76
)(Name
FormBorderStyle
MaximizeBox
Size
Text
MainForm
FixedSingle
False
576, 459
)(Name
Size
Text
ActHelpAbout
80, 24
&...
.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 .
11
: .
Mhm76
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
)(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:
System.DateTime ) (. DateTime
. " " ticks12:00 1.
1 ).(12:00 a.m. on January 1, 1 AD tick 100 .
31 9999 )(.
. ) ( 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
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
.
. .
. System.Int32 Integer
.
.
4
: .
Mhm76
Literals
)(.
:
)"!MsgBox("Hello, World
&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 .
.
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 .
processResult .For...Next
For . immediate error
lifetime procedure-level variable
. .
)(
.
)fields ( class-level variables scope
. )( .
.
Variable and Constant Naming Conventions
.
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
.
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) :
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 .
For...Next ) (
. Dim
ReDim .
.
String .
0 .1
-)( .
) (
)(.
Multidimensional Arrays
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
)(
.
. ) ( curly braces
Dim squares( ) As Integer = {0, 1, 4, 9, 16, 25}
lower and upper bound specifications . " squares
" 0 .5
'
?Public FireDate As Date
Public FireDate2? As Date
. .
.
FireDate = Nothing
FireDate = #7/18/2008#
If (FireDate Is Nothing) Then...
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 .
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
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
.
.
. . .
. :
.
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 \ .
' ,
.
15
: .
Mhm76
.
16
Mhm76
Windows Forms
)( .
). 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.
Mhm76
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
Main .
" ." Startup form .
" " Main )( Main routine
.
.
) ( " " Enable application framework
) ) (( " " Startup form
).( compatible cool
functionality . )(.
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
Module Module1
)(Public Sub Main
)System.Windows.Forms.Application.Run(Form1
End Sub
End Module
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
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
ToolTip
TrackBar
TreeView
VScrollBar
10
Mhm76
WebBrowser
.
.
Internet Explorer URL HTML
DocumentText .
firm grasp
. . RaiseEvent
. message pump
WndProc . event handlers
. WndProc .
11
Mhm76
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
.
.
)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
RemoveHandler .
.
.
. Delegate AddHandler Handles WithEventsRaiseEvent Event
RemoveHandler .
employee " " Fired .
class logic .
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
.
. )
(.
) 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
. 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 :
15
Mhm76
.
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
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
19
Mhm76
.
( ).
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 .
21
: .
Mhm76
. )(
. .
. .
.
. 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
: .
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
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
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
.
. 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
. ) (Code
CodeCopyStatus )( collections.
Field
ID
FullName
Description
Type
Primarykey;automaticallyassigned.Required. LongAuto
. .
Nameofthisstatusentry.Required.
) Text(50
. .
ID -
. ) ( derived versions
.
:")" summary (")" detail
(. "
."summary " ." detail
BaseCodeForm
False
FixedDialog
False
406, 173
CenterScreen
Code Form
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 "
. . :
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
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
. :
19
: .
Mhm76
"" ) (.
"" ) (
. .
.
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
:
Function(x As Integer) x * x
Function passed-in .
x * x . .
.Return .
" 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 (. )(.
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
) (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
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
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
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 - -
.
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.
. .
.
Ignoring Errors
. :
ErrorHandler:
Resume Next
. .
On Error Resume Next
. ) ( .
.
: .
Mhm76
)My.Computer.FileSystem.RenameFile(existingFile, newName
Catch ex As Exception
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
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
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 .
.
Description
.
Data
.
HelpLink
.
InnerException
.
Message
.
Source
.
StackTrace
.
TargetSite
System.Exception .
Description
.
. . Raise .
. .
.0
.
. HelpFile
.
.
.
Mhm76
: .
.
Raise method
Err . Raise
.
.
Source property
) System.Exception (
Project
. Error-handling
. .
.
. .GeneralError
)(Public Sub SomeRoutine
On Error GoTo ErrorHandler
' ----- Lots of code here.
Return
ErrorHandler:
))(GeneralError("SomeRoutine", Err.GetException
Resume Next
End Sub
:
Try
10
: .
Mhm76
)GeneralError("SomeRoutine", ex
End Try
GeneralError: . .
) log listener( .
.GeneralError
)My.Application.Log.WriteException(theError
.GeneralError
On Error Resume Next
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
Mhm76
. .
)( .
SQL . .
.
" " SELECT .
. ) 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
. foreign-key
relationships fields . tables internals unfathomable mystery
DataSet .XML .
Mhm76
)( -)(
. 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
. .
wizards" " code generators .
.
DataReaders . DataSets
DataTable . DataSet
MARS Support .
. .
. .
Mhm76
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
.
" " Activity " . " drag-and-drop "
" Activity . "" ). Form1 1 (.
Activity .Form1
non-userinterface ). (.
Mhm76
" ."Activity
.F5 "
)"Activity (. )
(. ! .
Data Binding
. 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
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 .
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
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
Data mapping
Mhm76
Entity inheritance
.
InternalOrder "
"Order .
Boolean . : . )(
InternalOrder .
"" .
.
17
. .DB2
2008 Entity Framework
) (. .
.
Project
%50 .ADO.NET
.
. boilerplate
10
Mhm76
HoldTransaction SqlTransaction . .
CenterText .
Public LibraryDB As System.Data.SqlClient.SqlConnection
Public HoldTransaction As System.Data.SqlClient.SqlTransaction
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
. :
data readers tables SQL. :
11
Mhm76
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 .
.
) (
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
.
DBDate(Date)
.
DBGetDecimal
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
.
DatabaseVersion .
.
16
Mhm76
17
Mhm76
Security
. " " Secret
" " Japanese Cooking Secrets
era information overload increasingly permissive moral
standards . .
.
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
.
.
.
. .
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
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
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 .
.
.
.
.
. .
immutable . .
.
. nefarious
System.Security.SecureString .
. gibberish
Project
:
. " " login ) ( .
. .
. function . user-supplied password
. )( authentication.
)( Authentication Support
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
'
'
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
MsgBox("Alice/none: " & EncryptPassword("Alice", "") & vbCrLf & "Alice/password: " & EncryptPassword("Alice",
& " "password") & vbCrLf & "Bob/none: " & EncryptPassword("Bob", "") & vbCrLf & "Bob/password:
))"EncryptPassword("Bob", "password
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
:
.
.
. .
Mhm76
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
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 .
PrepareFormFields .
.
. RecordFullName . TextBox
' .
sqlText = "SELECT FullName FROM GroupName WHERE ID = " & ActiveID
))RecordFullName.Text = CStr(ExecuteSQLReturn(sqlText
GroupName overrides .BaseCodeForm
.
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
. 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
Per-User Experience.
.
.
.
. ActOK_Click . ChangeUser.vb
( ) " "
LoggedInUserID = -1
LoggedInUserName = ""
LoggedInGroupID = -1
ReprocessSecuritySet()
. ActLogin_Click
. Login MainForm.vb
15
Mhm76
ShowLoginForm()
End Sub
'
Case Keys.F12
.
ShowLoginForm()
e.Handled = True
'
UpdateDisplayForUser ShowLoginForm
. MainForm . security profile
. 1- LoggedInUserID
16
Mhm76
:
ID . password
UpdateDisplayForUser . .MainForm_Load
'
)(UpdateDisplayForUser
) ( .
. TaskReports
.
.
PanelReports.Visible = True
.
PanelCheckOut.Visible = True .TaskCheckOut
. UserName .
.
17
Mhm76
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
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
. 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
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
.
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
Mhm76
Extension attribute . :
)FormatAuthorName(dbInfo
. 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
ListEditRecords .
Keywords subjects . ) (
) NamedItem (.
NamedItem ItemKeyword ItemSubject . KeywordAdd SubjectAdd
. :
. KeywordAdd.vb.
. SubjectAdd.vb.
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
. .
12 . BaseCodeForm :
Author.vb
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.
.
. 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
CodePatronGroup.vb
.CodePatronGroup
CodeSeries.vb
.
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 .
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
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
14
Mhm76
ListEditRecords .
.ItemAuthor " " ListView
ListBox. View
" " ListView "" Details FullRowSelect True ) Columns
( listbox . multicolumn
" ." OK ID .
SaveFormData " )" Cancel 1- "
"( SaveFormData .SessionSaved
SessionSaved = True
. NamedItem
AddRecord EditRecord .
15
Mhm76
. .
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 .
16
: .
Mhm76
?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 :
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 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 .
THE RULE
If you open it, close it.
.. .
: .
Mhm76
></there
></hello
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.
XML . .
XML. supplier XML
supplier ) (.
. .
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 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 ) (
: .
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 .
.XSD
System.Xml.Serialization
XPath .XML
System.Xml.Xsl
.XSL
XML XSLT. XSD
. :
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)
Mhm76
: .
)( XML
XmlTextReader XmlTextWriter XML . text stream
XML Load Save XmlDocument .
)(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
: .
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
products . 17
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
1: Chai
2: Chang
3: Aniseed Syrup
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
11
: .
Mhm76
'
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
) (.
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
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
15
: .
Mhm76
. Process.Start URL
)( XML .
16