فيجوال بيسك 1

200
 ل اﻷو ﻟﻔ ا:  تو ا تﻨﺎـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ ــــــــــ ــــــــ ـ ع ظ ط ض ص ش س ز ر ذ د خ ح ج ث ت ب ر ذ د خ ح ج ث ت ب ي و ه ن م ل ك ق ف  غ ي و ه ن  ل ك ق ف غ ع ظ ط ض ص ش س  ز ع ظ ط ض ص ش س ز ر ذ د خ ح ج ث ت ب  ر  ذ  د  خ  ح  ج  ث  ت  ب  ي  و  ه  ن  م  ل  ك  ق  ف  غ  ي  و  ه  ن   ل  ك  ق  ف  غ  ع  ظ  ط  ض  ص  ش  س  ز  ح  ج  ث  ت  ب  ع  ظ  ط  ض  ص  ش  س  ز  ر  ذ  د  خ  ر  ذ  د  خ  ح  ج  ث  ت  ب  ي  و  ه  ن  م  ل  ك  ق  ف  غ  ي  و  ه  ن   ل  ك  ق  ف  غ  ع  ظ  ط  ض  ص  ش  س  ز  ع  ظ  ط  ض  ص  ش  س  ز  ر  ذ  د  خ  ح  ج  ث  ت  ب  ر  ذ  د  خ  ح  ج  ث  ت  ب  ي  و  ه  ن  م  ل  ك  ق  ف  غ  ي  و  ه  ن   ل  ك  ق  ف  غ  ع  ظ  ط  ض  ص  ش  س  ز  ع  ظ  ط  ض  ص  ش  س  ز  ر  ذ  د  خ  ح  ج  ث  ت  ب  ف  غ ر  ذ  د  خ  ح  ج  ث  ت  ب  ي  و  ه  ن  م  ل  ك  ق ظ  ط  ض  ص  ش  س  ز ي  و  ه  ن   ل  ك  ق  ف  غ  ع  ع  ظ  ط  ض  ص  ش  س  ز  ر  ذ  د  خ  ح  ج  ث  ت  ب  ر  ذ  د  خ  ح  ج  ث  ت  ب  ي  و  ه  ن  م  ل  ك  ق  ف  غه ك ف ظ ط   لاﻴﺠ ا  ﺑﺮ 2008  ب آ    ب آ : Programming Visual Basic 2008  Mhm76   ا  ا  ا   و  وﺻﺤﺒ  و    ا  ﻠﻰ ما و ةا و ﻟﻤﻟﻌ ا ب ر  ﻟﺤﻤ ا.   لاﺠﻴ ا  ﺑﺮ ب ﺁﺘ ا2008 ا    ب  وﻩئر ﻟﻠﻘ اﺨﺪ ا ن ا ﺪر  وﻟﺖ  و  ا   ﻠﻲ ا  ﺠﺎﻧ ﻟﻌ اﺎﻳ اﻟﻨ  إ ا اﻟ  اﺑ ﺎب اﻟ وع  أن  ا ي با و25 لا ا   اﻟﺒ اﺿﻴ    ﺤﻴ 2008                          ص   و    أ ل أ  و ﻜﺜ ا   ر و  ا ﻠﻢ ن أ     وﻟﻮ  ﺴﻠﺴﻠﺔﻟﻤ ا.  ب ا ا  و ﺣﺎ ﺎب اﻟﻜ عو ةر  أ  و د اﻟﻜ  ت ا  وﺧ    ﺁﻞ  و أ   وﻟﻜ  اﻟ  ﺎﻟﻠﻐ    ل ﺧﻼ     ﺁﺜ.    أ  ﺁﻮﻧ و ﺁﺜﻴ   إﻟﻰ ﺎج  ا  ا ن ون ا  وﺣﺘ  ا أ و  ب  ﺼﻮ  ا   و ب  ﻏﻴ ا"  لاﻴﺠﻮ فا اﻻ 2008 "   أﻧ  يا و ﺁﺧﺮ  ن لا ا ص ن ﻟﻮ و  ﺨﺼﻮﺻﻪ  ﺎب   ن  ر2005 ﺁﺧ ب  ﻮﻓ  ﺟﺐا ا  ن أ أ ا ﺬا ﻜﺎن.   ةﺎﻋﺪ  ﻠﻰ ﻤﻠ و ب ا وع  وع رو اﻟﻀﺮ  ﻮل  تعوﺸﺮ ا   ﺳﺄ  وع ا  ا ﺸﺮ أ   ا ﻠﻪ ﻋﻠﻴ  واﻟﺘ   و ر اﻟﺘ  ات ا  ﻠﺖ   أ  ا ﺸﺎﺁﻞا و  ﻧﺘ ا  ض اﻧ  و    ا ا ﻠﻪ وع ا   اﻟﻨ تﺼﺮ ا.   أﻣ ر   ﻋﻠﻰ و  اﻷﻣﺔ   ن أ ر أ.  ﺠﺎ ب ا ﺬا ا    ا  وﺛ.     ﻮﻇ ق اﻟﺤﻘ ﻤﻴﻊﺟﻢا وmhm76 أﺣ  ن أ ﺟﻮارأ و. ا ب ر  ا و.  

Transcript of فيجوال بيسك 1

8002 : 8002ProgrammingVisualBasic : 67 Mhm . 8002 52 8002 . . " 8002" 5002 . . . . 67 mhm . .

67 mhm

:

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

67 mhm

:

.management CLR manage . manage . .managed code (ActiveX) COM . unmanaged code . . . . . . . TSA . LAX . CLR . . . . ) ( )Microsoft Intermediate Language MSIL (IL assembly language . ! Hello, World : Main1Module Module )(Sub Main )"Console.WriteLine("hell world )(Console.Read End Sub End Module MSIL Main )

. (

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

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

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

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

67 mhm

:

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

.NET Class Libraries . 71 1 : 0 1 . CPU 0 1 1s 0s . 0s 1s . 41.3 3 . 0 1 .award-winning 1 libraries . . . 2 2 4 . . class libraries . ) ( . : ) Base Class Library (BCL FrameworkClass Library ) .(FCL . . Linux . ) !( . . . namespaces . node . ).( . . . System ) ( . 3

67 mhm

:

Windows based web-based -Windows specific . web-specific System Windows . Web Windows Forms . Form . Form : System.Windows.Forms.Form . . System Microsoft.VisualBasic " " Microsoft " " System top-level . Windows 1 WindowsApplication 1 Form : 1WindowsApplication1.Form second-class .System : 1 WindowsApplication System Microsoft . . System 1 WindowsApplication . System.MySuperApp 1 Form: 1System.MySuperApp.Form . . Microsoft-supplied System . System ) system ( . . : CompanyName.ApplicationName.ClassName . . . . : . 8002 5.3 . .

Assemblies and Manifests " " . % 9.99 ) an .exe (file ) . (a .dll file . . manifest single-file manifest : . . CLR . strong name . . . . . ) .Global Assembly Cache (GAC GAC . . GAC

Metadata and Attributes . m .metadata : . .pre-.NET . . . attributes ID. . . . : ObsoleteAttribute 4

67 mhm

:

. ) out-of-date (. ) > If (Len(originalText) = 0) Then Return )lengthOfText = Len(originalText If (lengthOfText = 0) Then Return

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

: . intrinsic functions . . Microsoft.VisualBasic .

Data Types and Variables : ) ( . . .Common Language Runtime . . :

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

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

67 Mhm

: .

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

Variables . . . . Variables : . . . ::1 :2 :3 :4 :5 :6 :7 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

:8

)MsgBox(response

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

response String . = :"response = "The answer

. :"Dim response As String = "The answer

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

: Dim question As String, answer As String

. Dim

Value Types and Reference Types 3

67 Mhm

: .

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

Data Types . data types . . System .Object O. . System.Object : . . System.Object : . "" . : . . ) ( . 12 . .Visual Basic data typesDescription

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

NET Boolean

VB Boolean

Byte

Byte

Char

Char

2 )61 ( . 0 535,56 . 11 13 9999 . : . " " 11 . 001 ) (. Decimal . 97 72 ) 97 72 ( 92 92 . 97 72 . ) ( 7.9 72 . 92 . 0.6 . Currency Double . 423 01 49.4 803+ 01 897.1 . giganto-number )( . 43450000000000000.0 . . Integer 4 )23 ( .DateTime Date

Decimal

Decimal

Double

Double

Int32Integer

4

67 Mhm

: .

846,384,741,2 746,384,741,2 . Long 0.6 . Long :Integer 8 )46 46Int Long ( . 808,577,458,630,273,322,9 708,577,458,630,273,322,9 . 0.6 . . Object Object : . . SByte 8)single-byte( SByte SByte 821 721 . Byte . Short 2 )61 ( . Int16Short 867,23 767,23 Short Integer 0.6. Single Double . Single Single 54 01 4.1 83+ 01 4.3 . Double Single . 2 String String . 2 )61 ( . UInteger 4 )23 ( 23UInt UInteger 0 592,769,492,4 . Integer .

8ULong )46( 46UInt ULong 0 516,155,907,370,447,644,81 . Long . 2UShort )61( UInt16UShort 0 535,56 . Short . . . Integer 23 23 .System.Int . Object String . System.ValueType ) . (System.Object SByte UInteger UShort ULong 5002 System . " ." CLS-compliant . . declaration . : .instantiation :Dim defaultValue As Integer 5 = Dim nonDefaultValue As Integer Dim defaultReference As Object

Advanced Declaration

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

5

67 Mhm5 = Dim nonDefaultValue As Integer Dim defaultReference As Object = Nothing

: .

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

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

: "" = Dim worldsMostBoringString As String

Strings . String literals :String )( String .System.String . . ) ( . ) ( . 52 . M :)52 ,Dim mmGood As String = New String("M"c

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

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

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

Constants

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

Local Declaration and Fields . . : )( . . ) local variables (constants short-lived . ) ( . fields . . Dim Dim . ) ( ) Private ( ) Public ( : Private ForInClassUseOnly As Integer

. .

Comments ) ( human-language . Comments . " " : 6

67 Mhm.' ----- 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 . : 5 = brandNewValue

Dim brandNewValue .Object ! . . )( auto-declared :5 = brandNewValue 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 8002 . . .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 (:

7

67 Mhm

: .

Basic Operators : . . )=( . . ) ( : . :52 = fiveSquared

52 . fiveSquared binary operators : . . :4 + 3 = seven

7 = seven

)=( . unary operator . :7- = negativeSeven

. . . . . . . . )( ) ( . . 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 . . + + _ _ * / \Mod ^ & And AndAlso Or OrElse Not Xor

= >= 9) And(PlayersOnTeam(visitingTeam) >= 9)) Or (justPracticing = True) Then )(PlayBall Else )StadiumLights(turnOff End If

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

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

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

Select Case Statements If then then then:If (billValue = 1) Then = presidentName = ElseIf (billValue = presidentName = ElseIf (billValue = presidentName ... ""Washington 2) Then ""Jefferson 5) Then ""Lincoln

ElseIf . . Select Case ::1 20 :3 :4 :5 :6 :7 :8 :9 Select Case billValue 1 Case presidentName 2 Case presidentName 5 Case presidentName 02 Case presidentName "= "Washington "= "Jefferson "= "Lincoln "= "Jackson

01

67 Mhm:01 :11 :21 :31 :41 :51 :61 :71 :81 05 Case presidentName 001 ,01 Case presidentName 001 > Case Is presidentName Case Else presidentName End Select "= "Grant "= "!! Non-president "= "!! Value too large "= "!! Invalid value

: .

If Select Case . billValue .Case )Case Case ( . )Case Else 61 ( Case . Case . ) 21 ( ) 41 ( .

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

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

. . . IIf IIf . :)) (2purgeResult = IIf(level = 1, PurgeSet1( ), PurgeSet

) (1 PurgeSet ) (2PurgeSet . ) (1 PurgeSet2() PurgeSet : 1 ) (1 PurgeSet ) (2 PurgeSet )(1PurgeSet . 8002 If . IIf If :IIf)) (2ClasspurgeResult = If(level = 1, PurgeSet1( ), PurgeSet

) (1PurgeSet ) (2 PurgeSet . If .ternary . If Boolean .)2realObject = If(object1, object

If Nothing . Nothing . . non-Nothing

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

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

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

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

11

67 Mhm... Next countDown

: .

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

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

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

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

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

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

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

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

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

67 Mhm

: .21 For whichMonth = 1 To )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 :21 For whichMonth = 1 To If (DataAvailable(whichMonth) = False) Then Continue For )RetrieveData(whichMonth )ProcessData(whichMonth )SaveData(whichMonth Next whichMonth

Creating Your Own Procedures . .

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

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

31

67 Mhm . . . .

: .Value type Reference typeByRef ByRef

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 &2 \ For testValue = 2 To source :8 If ((source Mod testValue) = 0) Then :9 Return False :01 End If :11 Next testValue :21 End If :31 Return True 14 End Function

) 1( ) 2 31 ( )Function 41( . . . . IsPrime Boolean :End

)32(primeResult = IsPrime . Return 5 9 31 . ) 0.6 VB

. (

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

. . ) ( :01 Class PercentRange :2 0 001 ' :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 :01 0 = savedPercent :11 ElseIf (value > 100) Then :21 001 = savedPercent :31 Else :41 savedPercent = value :51 End If 16 End Set 17 End Property 18 End Class

41

67 MhmGet

: .

) Percent 4 71 ( ) savedPercent 3 ( -caller supplied 0 001 . . ) accessor 5 7 ( . )Set accessor 8 61 ( . ) 4 ( ) Set accessor 8 ( .

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

. .

Where to Put Your Procedures 0.6 . : . ) (.Class Employee )(Sub StartVacation ... End Sub Function TotalVacationTaken() As Double ... End Function End Class

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

Other Flow Control Features .

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

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

GoTo .GoTo :"Dim importantMessage As String = "Do 2GoTo Step "!Step6: importantMessage &= "AG 7GoTo Step "Step3: importantMessage &= "wit 4GoTo Step " Step2: importantMessage &= "wn 3GoTo Step

51

67 Mhm:5Step :4Step :7Step "importantMessage &= "CK-G 6GoTo Step "importantMessage &= "h I 5GoTo Step )MsgBox(importantMessage

: .

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

.GoTo .

The Return Statement GoTo Return : . Return . Return :Return

: .52 Return

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 ' #0.0 = SafeDivide Exit Function End If Return numerator / denominator End Function

The End and Stop Statements Stop End . End ) (. Stop debugger . Stop . Stop . .

Events and Event Handlers 61

67 Mhm

: .

.event-driven . . . . . . .events message pump . system-generated message queue . . event-handling . ) ( . . . event handler . firing . : )1( . )2( . . . event-firing. . . . event-specific . . Event )( .)Public Event SalaryChanged(ByVal NewSalary As Decimal

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

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

. . WithEvents .Public WithEvents MonitoredEmployee As Employee

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

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

71

67 Mhm

: .

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

event-specific . System.EventArgs .System.EventArgs

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

Forms . : Global.System.Windows.Forms

. : Forms

. Forms .

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

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

67 Mhm

: .

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

Imports . :Imports Fred = System.Windows.Forms

Form. Fred.Form Imports .

Namespaces in Your Project top-level . Windows Forms 1 .WindowsApplication -top level Application . Root namespace : Microsoft-supplied . . .Namespace Namespace .EndNamespace Namespace End Namespace . 1 WindowsApplication : WindowsApplication1.WorkArea.BasicStuff.BusyDataNamespace WorkArea.BasicStuff Class BusyData ... End Class End Namespace

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

The My Namespace 5002 My top-level . 0.6 . . 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

91

67 mhm

:

:The Library Project . . . ) ( . . . . :Library Item Features . : . . ) ...( . )(. . . )(. . . . . Patron Features "" ) ( . : . . . " " PIN . " " )( ) checkout ( renewal . . 1F . . experimentation " " )( .. administrative staff :Administrative Features . . : o " " login . . . o . . . o fines . unpaid fines o . . . . o . o )( . ) (. o . o . 1

67 mhm

:

o . . o . o plug in . :The Application As a Whole : training . .SQL Server database . )( XML . . _ - . The Needs of the Users . : . . . Data and Information . . 3-5 : . )( : . : ) (. . Process : . . " ". . . . . .process . . . :)1( )2( )3( . . Usability . loathe. .

. . . )(. : . . . . . ) ( . . . . ) (Commonality 2

67 mhm

:

touts )( innovation . . : . : consistency . Project : . Project Agreement.doc . . " " Change Order. . Change Order.doc " ". . . Project Acceptance.doc . . " Acceptance " Criteria Testing" " . .

3

67 mhm

:

Designing the Database . . tables records . row column field . .Customer Record ID 13229 23229 33229 43229 53229 Order ID 10001 10001 20001 30001 40001 Customer ID Name Product ID 1AA Al Albertson BEV01COF 1AA Al Albertson BRD05RYE 3BW Bill Williams BEV01COF 3BW Bill Williams BEV01COF 1CC Chuck Charles CHP34PTO Product Price Coffee 99.3 Rye bread 86.2 Coffee 99.3 Tea 99.3 99.0 Potato chips Quantity 3 1 1 2 7

: Relational Databases

. . Customer ID Product . product ID BEV01COF flat file . database table " ." normalization record/row/ ) ( a primary key . data integrity : .respectively asterisk .* Record ID 13229 23229 33229 43229 53229 Order ID 10001 10001 20001 30001 40001 Customer ID 1AA 1AA 3BW 3BW 1CC Product ID BEV01COF BRD05RYE BEV01COF BEV01COF CHP34PTO Quantity 3 1 1 2 7

* Customer ID 1AA 3BW 1CC * Product ID BEV01COF BRD05RYE Rye BEV01COF CHP34PTO

Customer Name Al Albertson Bill Williams Chuck Charles Unit Price 99.3 86.2 99.3 99.0

Product Name Coffee bread Coffee Potato chips

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

. 1

67 mhm

:

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 . 5002 . 5002 SQL Server . SQL Server ) ( . )(. 5002 )( T-SQL scripting language . SQL Server "." server network first establish .server engine . tutorial books 8002 . 8002 . . 5002 . " 5002 " . :

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 2

67 mhm ( ,eldName1dataTypeop ons ,eldName2dataTypeop ons ...andsoon )

:

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

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

Data type Bigint binary Bit char, nchar Cursor Datetime

8-)46-( 708,577,458,630,273,322,9 000,8 . )001(binary :0,1 .NULL . Boolean . )( char ). ( nchar Unicode 000,8 . )001(char stored procedures . 3571 ,1 January999 ,13 December Time accuracy 33.3 . 8002 : )date ( )time ( 2 2datetime ) datetime 001 (100 nanoseconds ) datetimeoffset ( . ) ( precision ) decimal point.( scale )4,01(decimal . 83. numeric synonym decimal .dec )( . )( bits 35. 35 float )35(float

808,577,458,630,273,322,9

decimal, numeric

Float

3

67 mhm8301

:

. real )42(. float 0.1 bits . 8002 )( Hierarchyid ).( tree-shaped data 5002. . image, text, ntext 4-)23-( 846,384,741,2 746,384,741,2 . Int 8 high-accuracy)46( )( currency values Money ) (. 8085.774,586,302,733,229 7085.774,586,302,733,229 . . rowversion,timestamp . timestamp deprecated synonym rowversion rowversion . January 1, 1900 AD .June 6, 2079 AD Smalldatetime Time accuracy . )( 2)61( 867,23 767,23 . Smallint 4)23( )( . Smallmoney 8463.847,412 7463.847,412 . . sql_variant . )( Table . 1 unsigned integer field)8( 0 552. Tinyint )16 globally unique identifier (GUID . )( NEWID Uniqueidentifier . 0008 . parameter Varbinary )001(.varbinary )( . )varbinary(max 2 . )(varchar (nvarchar) Unicode 0008 varchar, nvarchar )001( . varchar . )varchar(max 2 . )( XML typed untyped 2.2 GB Xml " "DML Statements INSERT)( records . Data .) INSERT ( INSERT . .INSERT INTO LineItems )(OrderID, CustomerID, ProductID, Quantity )1 ,'VALUES (10002, 'BW3', 'BEV01COF CREATE TABLE LineItems ) (- primary key ) RecordID .(IDENTITY . . CustomerID Customer 3BW .Customer

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

literal time values :'5002-'7-Nov

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

4

67 mhm

:

DELETE) WHERE() 13229 = .(WHERE RecordID WHERE . WHERE AND OR parentheses.10001 = DELETE FROM LineItems WHERE OrderID 'AND ProductID = 'BRD05RYE

DELETE 0 0001 WHERE . . WHEREDELETE FROM LineItems

" " UPDATE WHERE . UPDATE SET WHERE LineItems 4 = Quantity )13229 = (RecordID

" " SET )(Quantity )4(. .comma formulas. calculations 1 + UPDATE LineItems SET Quantity = Quantity 'ProductID = 'BEV02POP 13229 = WHERE RecordID

,

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

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

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

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

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

" " inner join )( )( .join

:Inner join . .INNER JOIN

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

Right outer join

5

67 mhm

:

. .RIGHT JOIN

Full outer join . it is .reflected in the results .FULL 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 . .

)(Cross join

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

Using Databases in Visual Basic : ADO.NET .NET Framework . . . " " data binding . . . ) ( ADO.NET . . . . . . Documenting the Database . : . source code . :

6

67 mhm

:

. . user documentation . database documentation . . 000,001 )( . .

. :

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

Technical Resource Kit Content . . source code freak out .

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

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

Type Long )05( Text

Field ID FullName

:

7

67 mhm

:

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 )05( Text 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 )05( Text FullName . . UserIDthatgivesthisuseraccesstothesystem.Itisentered )02( Text LoginID intotheLibraryprogramsloginform,alongwiththe .password,togainaccesstoenhancedfeatures.Required . " " . . .Thepasswordforthisuser,inanencryptedformat.Optional )02( Text Password . . .Isthisuserallowedtoaccessthesystem?0forFalse,1forTrue Boolean Active .Required 01 . .

8

67 mhm

:

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 )05( Text FullName . . .CodeCopyStatus " "" circulating " being repaired . checked-in checked-out .reference item Description Type Field Primarykey;automaticallyassigned.Required. LongAuto ID . . .Nameofthisstatusentry.Required )05( Text FullName . . ) ( .CodeLocation . separate sites rooms areas . common location Description Type Field Primarykey;automaticallyassigned.Required. LongAuto ID . Nameofthislocation.Required )05( Text FullName .ThedatewhenDailyProcessingwaslastdoneforthislocation Date LastProcessing . IfNULL,processinghasnotyetbeendone.Optional . .. .CodeMediaType books magazines videos .CDs Description Type Field Primarykey;automaticallyassigned.Required. LongAuto ID . Nameofthismediatype.Required )05( Text FullName Numberofdaysforwhichitemsinthistypecanbechecked Integer CheckoutDays . out,beforerenewal.Required .. Numberofdaystoaddtotheoriginalcheckoutperiodfora Integer RenewDays . renewalofitemswithinthistype.Required .. Maximumnumberoftimestheitemcanberenewedbya Integer RenewTimes . patronbeforeitmustbereturned.Required .. Amountchargedperdayforanoverdueitemofthistype. Currency DailyFine . Required 9

mhm76

:

Description Type Field . . . . CodePatronGroup class/grade . /reporting purposes . Description Type Field Primarykey;automaticallyassigned.Required. LongAuto Nameofthispatrongroup.Required. Text(50) ID FullName

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

mhm76

:

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

mhm76

:

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

mhm76

:

Description Type Field Currentduedateforthisitemcopy.Required. Date DueDate Thedatewhenthisitemcopywasreturned.Optional. Date CheckIn Hastheitemcopybeenreturned?0forFalse,1forTrue. Boolean Returned Required. Istheitemcopymissingandconsideredlost?0forFalse,1for Boolean Missing True.Required. Totalneaccumulatedforthisitemcopy.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 1( )2( .()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

67 mhm

:

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 )001( Informationassociatedwiththisentry.Optional. Text ValueData . .ValueName .ValueData 93 BarcodeCode

"93"93 code"3 9"9 code 3 of bar code number . 0 False )-1 (. .missing or NULLBarcodeFont

. . .DatabaseVersion

"1" . location .DefaultLocation CodeLocation.ID )FineGrace ( NextBarcodeItem

.without incurring a fine . item bar codesNextBarcodeMisc

)( .miscellaneous bar codes ).( patron bar codesPatronCheckOut NextBarcodePatron

. 0)( )-1 (. .SearchLimit

. 052. inclusive 520005.TicketHeading

. . )|( .TicketFooting

. . )|( .UseLC

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

67 mhm

:

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

CREATE TABLE comma-delimited list)( . NULL NOT NULL NULL . PRIMARY KEY " " NOT NULL --. GroupActivity GroupName .Activity

CREATE TABLE GroupActivity ( ,GroupID bigint NOT NULL ,ActivityID bigint NOT NULL )PRIMARY KEY (GroupID, ActivityID ;)

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

entire SQL script 5002 ). Microsoft SQL Server 2005 Management Studio Express management tool - (. tables . Library Project 5002 ) ( new database " " Database " " New Database from . Library Database Name .OK . Database Creation Script.sql . 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 ( .configuration value )SetSystemValue ) ( . . ExecuteSqlReturn .)( system value name .. query sqlText = "SELECT COUNT(*) FROM SystemValue WHERE UPPER(ValueName) = " & _ DBText(UCase(valueName))

System-Level Configuration)(

15

67 Mhm

:

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

. DatabaseVersion . .

61

67 Mhm

:

71

67 Mhm

:

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

Security Features in .NET :

Internal security Classes . ) Code Access Security (CAS unauthorized powerful libraries . . . )( )( " " . " )" Code Access Security (CAS )( ) ..( in-effect security policies . . Encryption digital signatures cryptographic

External security

Data security . - ADO.NET .system security policies . . . . .

Cryptography and Encryption

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

67 Mhm

:

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 0791.

)( Symmetric Cryptography single secret key . ) ( asymmetric cryptography )( . " ." secret key encryption : . ) Data Encryption Standard (DES -56 block cipher .DESCryptoServiceProvider ) ( . . 2)2 RC2 (Rivest Cipher number 65- .RC2CryptoServiceProvider cipher .RijndaelManaged " Advanced Encryption )" Standard (AES . . ) Rijndael Daemen ( Rijmen ) 821 652 ( block

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

2

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

:

.)")stream DESencryption Streams (files " Streams ( Decrypt Encrypt DESCryptoServiceProvider . convoluted

3

67 Mhm : " " generic . . . . . ) (. . . "" generators emit . mask . . notoriously . sluggish . . : . ) Digital Signature Algorithm (DSA .DSACryptoServiceProvider . )RSA Ron Rivest Adi Shamir (Adleman .RSACryptoServiceProvider . .

Asymmetric Cryptography

) ( Hashing

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

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

67 Mhm : 2. ) Message Authentication Code (MAC ) Triple-DESsecret ( . MACTripleDES secret key 61 42 8. 3. . 5)5 Message-Digest algorithm number 5 (MD .MD5CryptoServiceProvider 5MD Ron Rivest . encoding security risk 821. 4. 1HMACSHA 1SHA SHA1Managed class 1-. SHA .NET managed code. 1HMACSHA )() Cryptography API (CAPI SHA1.pre-.NET DLL 061. 5. :652 SHA 483SHA 215SHA 1SHA 652 483215 . . . .

Other Security Features .

)User Authentication and My.User .(My.User My.User ) ( authentication . " " Name . IsInRole . the Administrators security group My.User . authentication systems . Options " " Internet-based Windows Live ID third-party authentication systems . . . . immutable . . . . nefarious System.Security.SecureString . . gibberish

The SecureString Class

Project

: . " " login ) ( . . . . function . user-supplied password . )( authentication. Windows SQL Server ) security ( restrict . )( . . . General.vb .Public LoggedInUserID As Integer Public LoggedInUserName As String Public LoggedInGroupID As Integer

)( Authentication Support

5

67 MhmPublic SecurityProfile(MaxLibrarySecurity) As Boolean

:

LibrarySecurity . Activity . SecurityProfile .' Public Enum LibrarySecurity As Integer 1 = ManageAuthors 2 = ManageAuthorTypes 3 = ManageCopyStatus 4 = ManageMediaTypes 5 = ManageSeries 6 = ManageGroups 7 = ManageItems 8 = ManagePatrons 9 = ManagePublishers 01 = ManageValues 11 = ManageUsers 21 = ProcessFees 31 = ManageLocations 41 = CheckOutItems 51 = CheckInItems 61 = AdminFeatures 71 = DailyProcessing 81 = RunReports 91 = PatronOverride 02 = ManageBarcodeTemplates 12 = ManageHolidays 22 = ManagePatronGroups 32 = ViewAdminPatronMessages End Enum Public Const MaxLibrarySecurity As LibrarySecurity =LibrarySecurity.ViewAdminPatronMessages

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

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

)(InitializeSystem

)( . ReprocessSecuritySet .General' '

)(Public Sub ReprocessSecuritySet . , Dim counter As Integer Dim sqlText As String

Dim dbinfo As SqlClient.SqlDataReader = Nothing ' For counter = 1 To MaxLibrarySecurity SecurityProfile(counter) = False Next counter . ' If (LoggedInUserID = -1) Or (LoggedInGroupID = -1) Then Return Try

6

67 Mhm

:

' 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 ' 1- = LoggedInUserID 1- = LoggedInGroupID )(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 1 HMACSHA . variablesize . UserName . . System.Security.Cryptography System.Text . Import .General.vbImports System.Text Imports System.Security.Cryptography

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

67 Mhm

:

)(. . ))hashValue = hashingFunction.ComputeHash((New UnicodeEncoding).GetBytes(passwordText . . long hex string 1 - For counter = 0 To hashValue.Length ))result &= Hex(hashValue(counter Next counter 02 . )02 ,Return Left(result End Function

security providers )(. GetBytes .UnicodeEncoding login ID password arguments 1.HMACSHA ComputeHash ASCII issued .UserName :basic byte printable hexadecimal equivalent . Hex . UserName 02 )( chop off . EncryptPassword . :

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

Undoing Some Previous Changes UserName GroupName GroupActivity . ) (UserName ) .(GroupName zero GroupActivity . GroupName property forms . . BaseCodeForm.vb . ListEditRecords.vb . users security groups . BaseCodeForm.vb MustInherit MustOverride . . : ) ( instances design time . TextBox . . ) ( MustInherit . " "MustInherit . inherited form . . BaseCodeForm.vb MustInherit MustOverride . .

8

67 Mhm : . . . .

.Managing Security Groups .GroupName . .