Chapter 17 – Files and Streams

Download Report

Transcript Chapter 17 – Files and Streams

1
Chapter 17 – Files and Streams
Outline
17.1
17.2
17.3
17.4
17.5
17.6
17.7
17.8
17.9
17.10
17.11
(只教 17.1 至 17.6)
Introduction
Data Hierarchy
Files and Streams
Classes File and Directory
Creating a Sequential-Access File
Reading Data from a Sequential-Access File
Random-Access Files
Creating a Random-Access File
Writing Data Randomly to a Random-Access File
Reading Data Sequentially from a Random-Access File
Case Study: A Transaction-Processing Program
 2002 Prentice Hall. All rights reserved.
2
17.1 Introduction
• Variables and arrays
– Only temporary
• Variable “goes out of scope”
• Program terminates
• Files
– Long term storage
• Persistent data
– Secondary Storage Devices
• Magnetic disks
• Optical disks
• Magnetic tapes
 2002 Prentice Hall. All rights reserved.
3
17.2 Data Hierarchy
• Data Hierarchy
– Bit (Binary Digit)
• Either zero or one
• All data reduced to combinations of bits for processing
– Byte
• Eight bits
– Character
• Two bytes
• Character set
– Set of all characters used to program and represent data on
a particular computer
 2002 Prentice Hall. All rights reserved.
4
17.2 Data Hierarchy
• Data Hierarchy
– Field
• Group of characters that convey a meaning
– Record
• Group of several, related fields
– File
• Group of related records
– Record key
• Identifies record to a particular entity
– Sequential file
• Records stored in order of record-key
 2002 Prentice Hall. All rights reserved.
5
17.2 Data Hierarchy
Sally
Black
Tom
Blue
Judy
Green
Iris
Orange
Randy
Red
Judy
Green
Judy
Field
01001010
1
byte (ASCII for J)
bit
Fig. 17.1 Data hierarchy.
 2002 Prentice Hall. All rights reserved.
file
record
6
17.3 Files and Streams
• VB views file as sequential streams of bytes
– Ends with end-of-file marker or specific byte number
• VB opens file
– Creates an object
– Associates a stream with that object
• Stream object properties:
– Console.In
• Returns standard input stream object
– Console.Out
• Returns standard output stream object
– Console.Error
• Returns standard error stream object
 2002 Prentice Hall. All rights reserved.
7
17.3 Files and Streams
• BinaryFormatter
– Serialization
• Converting object into a format that can be written to a file
without losing data
– Deserialization
• Reading format from file and reconstructing original object
from it
 2002 Prentice Hall. All rights reserved.
8
17.3 Files and Streams
• System.IO.Stream
– Provides functionality for representing streams as bytes
• FileStream
– Read and write sequential-access and random-access files
• MemoryStream
– Transfer data directly to and from memory
• BufferedStream
– Transfer data to or from stream
 2002 Prentice Hall. All rights reserved.
9
17.4 Classes File and Directory
• Directory
– Used to organize files
• The \ separator character
– Used to separate directories and files in a path
• C:\VisualBasic\MyFile
• Class File
– Used to manipulate and determine information about files
– Cannot instantiate File objects
• Class Directory
– Used to manipulate directories
 2002 Prentice Hall. All rights reserved.
10
17.4 Classes File and Directory
Shared Me thod
De sc rip tio n
AppendText
Returns a StreamWriter that appends to an existing file or
creates a file if one does not exist.
Copy
Copies a file to a new file.
Create
Returns a FileStream associated with the file just created.
CreateText
Returns the StreamWriter associated with the new text file.
Delete
Deletes the specified file.
GetCreationTime
Returns a DateTime object representing the time the file was
created.
GetLastAccessTime
Returns a DateTime object representing the time the file was
last accessed.
GetLastWriteTime
Returns a DateTime object representing the time the file was
last modified.
Move
Moves the specified file to a specified location.
Open
Returns a FileStream associated with the specified file and
having the specified read/write permissions.
OpenRead
Returns a read-only FileStream associated with the specified
file.
OpenText
Returns a StreamReader associated with the specified file.
OpenWrite
Returns a read/write FileStream associated with the specified
file.
Fig. 17.3
Som e m e thod s of c la ss File.
Fig. 17.3 Some methods of class File.
 2002 Prentice Hall. All rights reserved.
11
17.4 Classes File and Directory
Shared Me thod
De sc rip tio n
CreateDirectory
Returns the DirectoryInfo object associated with the newly
created directory.
Delete
Deletes the specified directory.
Exists
Returns True if the specified directory exists; False otherwise.
GetLastWriteTime
Returns a DateTime object representing the time the file was
last modified.
GetDirectories
Returns String array representing the names of the directories
in the specified directory.
GetFiles
Returns String array representing the names of the files in the
specified directory.
GetCreationTime
Returns a DateTime object representing the time the directory
was created.
GetLastAccessTime
Returns a DateTime object representing the time the directory
was last accessed.
GetLastWriteTime
Returns a DateTime object representing the time to which the
directory was last written.
Move
Moves the specified directory to the specified location.
Fig. 17.4
Som e m e thod s of c la ss Directory.
Fig. 17.4 Some methods of class Directory.
 2002 Prentice Hall. All rights reserved.
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Outline
' Fig 17.5: FileTest.vb
' Using classes File and Directory.
Imports System.IO
Imports System.Windows.Forms
FileTest.vb
Public Class FrmFileTest
Inherits Form
' label that gives directions to user
Friend WithEvents lblDirections As Label
' text boxes for inputting and outputting data
Friend WithEvents txtOutput As TextBox
Friend WithEvents txtInput As TextBox
Enables users to input a
file or directory name
' Visual Studio .NET generated code
' invoked when user presses key
Protected Sub txtInput_KeyDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) Handles _
txtInput.KeyDown
' determine whether user pressed Enter key
If e.KeyCode = Keys.Enter Then
Called every time the
user presses a key in the text box
Dim fileName As String ' name of file or directory
' get user-specified file or directory
fileName = txtInput.Text
' determine whether fileName is a file
If File.Exists(fileName) Then
Determines whether the
user-specified text is a file
 2002 Prentice Hall.
All rights reserved.
13
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
' get file's creation date, modification date, etc.
txtOutput.Text = GetInformation(fileName)
' display file contents through StreamReader
Try
' obtain reader and file contents
Dim stream As StreamReader
stream = New StreamReader(fileName)
txtOutput.Text &= stream.ReadToEnd()
Outline
FileTest.vb
The user-specified text is passed
in to get some information on that file
' handle exception if StreamReader is unavailable
Catch exceptionCatch As IOException
File is opened and read
' display error
MessageBox.Show("FILE ERROR", "FILE ERROR", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
' determine whether fileName is a directory
ElseIf Directory.Exists(fileName) Then
Determines whether the
user-specified text is a directory
Dim directoryList As String() ' array for directories
Dim i As Integer
Obtains String array of
' get directory's creation date, modification date, etc
txtOutput.Text = GetInformation(fileName)
subdirectories in the
' obtain directory list of specified directory
directoryList = Directory.GetDirectories(fileName)
txtOutput.Text &= vbCrLf & vbCrLf & _
"Directory contents:" & vbCrLf
specified directory
 2002 Prentice Hall.
All rights reserved.
14
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
' output directoryList contents
For i = 0 To directoryList.Length - 1
txtOutput.Text &= directoryList(i) & vbCrLf
Next
' notify user that neither file nor directory exists
Else
MessageBox.Show(txtInput.Text & " does not exist",
_
Display
"FILE ERROR", MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End If
Outline
FileTest.vb
each element in the
directory
End If ' determine whether user pressed Enter key
End Sub ' txtInput_KeyDown
' get information on file or directory
Private Function GetInformation(ByRef fileName As String) _
As String
Dim information As String
User-specified text is
passed in as variable
' output that file or directory exists
information = fileName & " exists" & vbCrLf & vbCrLf
' output when file or directory was created
information &= "Created : " & _
File.GetCreationTime(fileName) & vbCrLf
' output when file or directory was last modified
information &= "Last modified: " & _
File.GetLastWriteTime(fileName) & vbCrLf
 2002 Prentice Hall.
All rights reserved.
15
103
104
105
106
107
108
109
110
' output when file or directory was last accessed
information &= "Last accessed: " & _
File.GetLastAccessTime(fileName) & vbCrLf & vbCrLf
Return information
End Function ' GetInformation
Outline
FileTest.vb
End Class ' FrmFileTest
 2002 Prentice Hall.
All rights reserved.
16
Outline
FileTest.vb
 2002 Prentice Hall.
All rights reserved.
17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Outline
' Fig 17.6: FileSearch.vb
' Using regular expressions to determine file types.
Imports
Imports
Imports
Imports
System.IO
System.Text.RegularExpressions
System.Collections.Specialized
System.Windows.Forms
FileSearch.vb
Public Class FrmFileSearch
Inherits Form
' label that displays current directory
Friend WithEvents lblDirectory As Label
' label that displays directions to user
Friend WithEvents lblDirections As Label
' button that activates search
Friend WithEvents cmdSearch As Button
' text boxes for inputting and outputting data
Friend WithEvents txtInput As TextBox
Friend WithEvents txtOutput As TextBox
Enables user to input a directory name
' Visual Studio .NET generated code
Dim currentDirectory As String = Directory.GetCurrentDirectory
Dim directoryList As String() ' subdirectories
Dim fileArray As String() ' files in current directory
' store extensions found and number found
Dim found As NameValueCollection = New NameValueCollection()
 2002 Prentice Hall.
All rights reserved.
18
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
' invoked when user types in text box
Private Sub txtInput_KeyDown(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles txtInput.KeyDown
' determine whether user pressed Enter
If (e.KeyCode = Keys.Enter) Then
cmdSearch_Click(sender, e)
End If
Outline
FileSearch.vb
Method cmdSearch_Click
is called if Enter is pressed
End Sub ' txtInput_KeyDown
' invoked when user clicks "Search Directory" button
Private Sub cmdSearch_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdSearch.Click
Searches recursively through
the user specified directory
Dim current As String
' check for user input; default is current directory
If txtInput.Text <> "" Then
' verify that user input is a valid directory name
If Directory.Exists(txtInput.Text) Then
currentDirectory = txtInput.Text
Determines whether the
user-specified text is a directory
' reset input text box and update display
lblDirectory.Text = "Current Directory:" & vbCrLf & _
currentDirectory
' show error if user does not specify valid directory
Else
MessageBox.Show("Invalid Directory", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
 2002 Prentice Hall.
All rights reserved.
19
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
Outline
Return
End If
FileSearch.vb
End If
' clear text boxes
txtInput.Text = ""
txtOutput.Text = ""
' search directory
SearchDirectory(currentDirectory)
The directory name is passed
' summarize and print results
to method SearchDirectory
For Each current In found
txtOutput.Text &= "* Found " & found(current) & " " _
& current & " files." & vbCrLf
Next
' clear output for new search
found.Clear()
End Sub ' cmdSearch_Click
All files found are displayed
' search directory using regular expression
Private Sub SearchDirectory(ByVal currentDirectory As String)
' for file name without directory path
Try
Dim fileName As String = ""
Dim myFile As String
Dim myDirectory As String
A regular expression is defined
to specify file searching criteria
' regular expression for extensions matching pattern
Dim regularExpression As Regex = _
New Regex("([a-zA-Z0-9]+\.(?<extension>\w+))")
 2002 Prentice Hall.
All rights reserved.
20
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
Outline
' stores regular-expression-match result
Dim matchResult As Match
Dim fileExtension As String ' holds file extensions
FileSearch.vb
' number of files with given extension in directory
Dim extensionCount As Integer
' get directories
directoryList = _
Directory.GetDirectories(currentDirectory)
' get list of files in current directory
fileArray = Directory.GetFiles(currentDirectory)
' iterate through list of files
For Each myFile In fileArray
' remove directory path from file name
fileName = myFile.Substring( _
myFile.LastIndexOf("\") + 1)
Iterates through each
file in the current directory
String processing removes
the path from the file name
' obtain result for regular-expression search
matchResult = regularExpression.Match(fileName)
' check for match
If (matchResult.Success) Then
fileExtension = matchResult.Result("${extension}")
Else
fileExtension = "[no extension]"
End If
Checks if file matches the
regular expression
String is tagged with the
name extension
 2002 Prentice Hall.
All rights reserved.
21
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
Outline
' store value from container
If (found(fileExtension) = Nothing) Then
found.Add(fileExtension, "1")
Else
extensionCount = _
Convert.ToInt32(found(fileExtension)) + 1
FileSearch.vb
found(fileExtension) = extensionCount.ToString()
End If
' search for backup(.bak) files
If fileExtension = "bak" Then
' prompt user to delete (.bak) file
Dim result As DialogResult = _
MessageBox.Show("Found backup file " & _
fileName & ". Delete?", "Delete Backup", _
MessageBoxButtons.YesNo, _
MessageBoxIcon.Question)
' delete file if user clicked 'yes'
If (result = DialogResult.Yes) Then
File.Delete(myFile)
extensionCount = _
Convert.ToInt32(found("bak")) - 1
Counts total number
of files with a particular
extension type
If a files extension type
is .bak then a message box
prompts the user
found("bak") = extensionCount.ToString()
End If
End If
 2002 Prentice Hall.
All rights reserved.
22
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
Outline
Next
' recursive call to search files in subdirectory
For Each myDirectory In directoryList
SearchDirectory(myDirectory)
Iterates
Next
through all
subdirectories
FileSearch.vb
' handle exception if files have unauthorized access
Catch unauthorizedAccess As UnauthorizedAccessException
MessageBox.Show("Some files may not be visible due to" _
& " permission settings", "Warning", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub ' SearchDirectory
End Class ' FrmFileSearch
 2002 Prentice Hall.
All rights reserved.
23
Outline
FileSearch.vb
 2002 Prentice Hall.
All rights reserved.
24
17.5 Creating a Sequential-Access File
• VB imposes no structure on files
– Concepts like “record” do not exist
– Programmers must structure files to meet the requirements
of applications
 2002 Prentice Hall. All rights reserved.
25
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Outline
' Fig 17.7: BankUI.vb
' A reusable windows form for the examples in this chapter.
Imports System.Windows.Forms
BankUI.vb
Public Class FrmBankUI
Inherits Form
' labels for TextBoxes
Public WithEvents lblAccount As Label
Public WithEvents lblFirstName As Label
Public WithEvents lblLastName As Label
Public WithEvents lblBalance As Label
' text
Public
Public
Public
Public
boxes that
WithEvents
WithEvents
WithEvents
WithEvents
receive user input
txtAccount As TextBox
txtFirstName As TextBox
txtLastName As TextBox
txtBalance As TextBox
Four text boxes in which
the users can input data
' Visual Studio .NET generated code
' number of TextBoxes on Form
Protected TextBoxCount As Integer = 4
The number of text boxes
on the form is set
' enumeration constants specify TextBox indices
Public Enum TextBoxIndices
ACCOUNT
FIRST
LAST
BALANCE
End Enum
 2002 Prentice Hall.
All rights reserved.
26
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Outline
' clear all TextBoxes
Public Sub ClearTextBoxes()
Dim myControl As Control ' current GUI component
Dim i As Integer
BankUI.vb
' iterate through every Control on form
For i = 0 To Controls.Count - 1
myControl = Controls(i) ' get Control
' determine whether Control is TextBox
If (TypeOf myControl Is TextBox) Then
For structure iterates through
every control on the form
' clear Text property (set to empty String)
myControl.Text = ""
End If
Sets their values
Next
equal to
an empty String
End Sub ' ClearTextBoxes
' set TextBox values to String-array values
Public Sub SetTextBoxValues(ByVal values As String())
' determine whether String array has correct length
If (values.Length <> TextBoxCount) Then
' throw exception if not correct length
Throw New ArgumentException("There must be " & _
TextBoxCount + 1 & " strings in the array")
Sets the values of the text boxes
to the String-array values
 2002 Prentice Hall.
All rights reserved.
27
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
' else set array values to TextBox values
Else
txtAccount.Text = values(TextBoxIndices.ACCOUNT)
txtFirstName.Text = values(TextBoxIndices.FIRST)
txtLastName.Text = values(TextBoxIndices.LAST)
txtBalance.Text = values(TextBoxIndices.BALANCE)
End If
Outline
BankUI.vb
End Sub ' SetTextBoxValues
' return TextBox values as String array
Public Function GetTextBoxValues() As String()
Dim values(TextBoxCount) As String
' copy TextBox fields to String array
values(TextBoxIndices.ACCOUNT) = txtAccount.Text
values(TextBoxIndices.FIRST) = txtFirstName.Text
values(TextBoxIndices.LAST) = txtLastName.Text
values(TextBoxIndices.BALANCE) = txtBalance.Text
Return values
End Function ' GetTextBoxValues
End Class ' FrmBankUI
 2002 Prentice Hall.
All rights reserved.
28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Outline
' Fig. 17.8: CRecord.vb
' Serializable class that represents a data record.
<Serializable()> Public Class CRecord
Private
Private
Private
Private
mAccount As Integer
mFirstName As String
mLastName As String
mBalance As Double
CRecord.vb
Indicates to compiler that
objects of class Crecord
can be serialized
' default constructor sets members to default values
Public Sub New()
Me.New(0, "", "", 0.0)
Sets the four members
End Sub ' New
to their default values
' overloaded constructor sets members to parameter values
Public Sub New(ByVal accountValue As Integer, _
ByVal firstNameValue As String, _
ByVal lastNameValue As String, _
ByVal balanceValue As Double)
Account = accountValue
FirstName = firstNameValue
LastName = lastNameValue
Balance = balanceValue
End Sub ' New
Sets the members to
specified parameter values
' property Account
Public Property Account() As Integer
Get
Return mAccount
End Get
 2002 Prentice Hall.
All rights reserved.
29
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Set(ByVal accountValue As Integer)
mAccount = accountValue
End Set
End Property ' Account
Outline
CRecord.vb
' property FirstName
Public Property FirstName() As String
Get
Return mFirstName
End Get
Set(ByVal firstNameValue As String)
mFirstName = firstNameValue
End Set
Methods for accessing
the data members
End Property ' FirstName
' property LastName
Public Property LastName() As String
Get
Return mLastName
End Get
Set(ByVal lastNameValue As String)
mLastName = lastNameValue
End Set
End Property ' LastName
' property Balance
Public Property Balance() As Double
 2002 Prentice Hall.
All rights reserved.
30
70
71
72
73
74
75
76
77
78
79
80
Get
Return mBalance
End Get
Set(ByVal balanceValue As Double)
mBalance = balanceValue
End Set
Outline
CRecord.vb
End Property ' Balance
End Class ' CRecord
 2002 Prentice Hall.
All rights reserved.
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
' Fig 17.9: CreateSequentialAccessFile.vb
' Creating a sequential-access file.
' Visual Basic namespaces
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports System.Windows.Forms
' Deitel namespaces
Imports BankLibrary
Public Class FrmCreateSequentialAccessFile
Inherits FrmBankUI
CreateSequential
AccessFile.vb
Inherits GUI similar
to that of class FrmBankUI
except has buttons Save As,
Enter and Exit
' GUI buttons to save file, enter data and exit program
Friend WithEvents cmdSave As Button
Friend WithEvents cmdEnter As Button
Friend WithEvents cmdExit As Button
' Visual Studio .NET generated code
' serializes CRecord in binary format
Private formatter As BinaryFormatter = New BinaryFormatter()
' stream through which serializable data is written to file
Private output As FileStream
A save
' invoked when user clicks Save button
Protected Sub cmdSave_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles cmdSave.Click
dialog box appears
and the user is prevented from
interacting with any other window
' create dialog box enabling user to save file
Dim fileChooser As SaveFileDialog = New SaveFileDialog()
Dim result As DialogResult = fileChooser.ShowDialog()
 2002 Prentice Hall.
All rights reserved.
32
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Outline
Dim fileName As String ' name of file to save data
' allow user to create file
fileChooser.CheckFileExists = False
' exit event handler if user clicked "Cancel"
If result = DialogResult.Cancel Then
Return
End If
CreateSequential
AccessFile.vb
Tests whether the user
clicked Cancel
fileName = fileChooser.FileName ' get specified file name
' show error if user specified invalid file
If (fileName = "" OrElse fileName = Nothing) Then
MessageBox.Show("Invalid File Name", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Checks to make sure
that a valid file has been selected
' save file via FileStream if user specified valid file
Try
' open file with write access
output = New FileStream(fileName, _
FileMode.OpenOrCreate, FileAccess.Write)
FileStream object instantiated
cmdSave.Enabled = False ' disable Save button
cmdEnter.Enabled = True ' enable Enter button
' notify user if file does not exist
Catch fileException As FileNotFoundException
MessageBox.Show("File Does Not Exits", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
 2002 Prentice Hall.
All rights reserved.
33
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
Outline
End If
End Sub ' cmdSave_Click
CreateSequential
AccessFile.vb
' invoked when user clicks Enter button
Protected Sub cmdEnter_Click(ByVal sender As Object, _
ByVal Be As System.EventArgs) Handles cmdEnter.Click
' account-number value from TextBox
Dim accountNumber As Integer
' store TextBox-values String array
Dim values As String() = GetTextBoxValues()
' CRecord containing TextBox values to serialize
Dim record As New CRecord()
' determine whether TextBox account field is empty
If values(TextBoxIndices.ACCOUNT) <> "" Then
' store TextBox values in CRecord and serialize CRecord
Try
' get account-number value from TextBox
accountNumber = _
Convert.ToInt32(values(TextBoxIndices.ACCOUNT))
' determine whether accountNumber is valid
If accountNumber > 0 Then
' store TextBox fields in CRecord
record.Account = accountNumber
record.FirstName = values(TextBoxIndices.FIRST)
record.LastName = values(TextBoxIndices.LAST)
Textbox values are stored
in an object of type CRecord
 2002 Prentice Hall.
All rights reserved.
34
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
Outline
record.Balance = Convert.ToDouble( _
values(TextBoxIndices.BALANCE))
' write CRecord to FileStream (Serialize object)
formatter.Serialize(output, record)
' notify user if invalid account number
Else
MessageBox.Show("Invalid Account Number", _
"Error", MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End If
CreateSequential
AccessFile.vb
Writes the record to file
' notify user if error occurs in serialization
Catch serializableException As SerializationException
MessageBox.Show("Error Writing to File", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
' notify user if error occurs regarding parameter format
Catch formattingException As FormatException
MessageBox.Show("Invalid Format", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exception is handled if
user entered an invalid format
End Try
End If
ClearTextBoxes() ' clear TextBox values
End Sub ' cmdEnter_Click
' invoked when user clicks Exit button
Protected Sub cmdExit_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles cmdExit.Click
Method is invoked when
user clicks Exit
 2002 Prentice Hall.
All rights reserved.
35
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
' determine whether file exists
If (output Is Nothing) = False Then
' close file
Try
output.Close()
Outline
CreateSequential
AccessFile.vb
' notify user of error closing file
Catch fileException As IOException
MessageBox.Show("Cannot close file", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
Application.Exit()
End Sub ' cmdExit_Click
End Class ' FrmCreateSequentialAccessFile
 2002 Prentice Hall.
All rights reserved.
36
Outline
CreateSequential
AccessFile.vb
 2002 Prentice Hall.
All rights reserved.
37
Outline
CreateSequential
AccessFile.vb
 2002 Prentice Hall.
All rights reserved.
38
Outline
CreateSequential
AccessFile.vb
 2002 Prentice Hall.
All rights reserved.
39
17.6 Reading Data from a SequentialAccess File
• Sequential retrieval of data
– Start at beginning of file and read data consecutively until
the desired data are found
• Sometimes necessary to process sequentially several times
during execution
– File-position pointer:
• Points to next byte to be read from or written to file
• Can be repositioned to any point in file
 2002 Prentice Hall. All rights reserved.
40
17.6 Reading Data from a SequentialAccess File
Ac c o unt Numb er
First Na me
La st Na me
Ba la nc e
1
Albert
Antstein
24.98
2
Tem
Nieto
33.23
3
Luna
Tic
-4.80
4
D.
Bug
0.00
5
Harvey
Deitel
65.00
6
Ms.
Kito
-100.78
7
Paul
Deitel
40.00
8
Russ
Tic
0.00
Fig. 17.10 Sa m p le d a ta for the p rog ra m of Fig . 17.9.
Fig. 17.10 Sample data for the program of Fig. 17.9.
 2002 Prentice Hall. All rights reserved.
41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
' Fig. 17.11: ReadSequentialAccessFile.vb
' Reading a sequential-access file.
' Visual Basic namespaces
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports System.Windows.Forms
Outline
ReadSequentialAc
cessFile.vb
' Deitel namespaces
Imports BankLibrary
Public Class FrmReadSequentialAccessFile
Inherits FrmBankUI
' GUI buttons for opening file and reading records
Friend WithEvents cmdOpen As Button
Friend WithEvents cmdNext As Button
' Visual Studio .NET generated code
' stream through which serializable data is read from file
Private input As FileStream
' object for deserializing CRecord in binary format
Private reader As BinaryFormatter = New BinaryFormatter()
' invoked when user clicks Open button
Protected Sub cmdOpen_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles cmdOpen.Click
' create dialog box enabling user to open file
Dim fileChooser As OpenFileDialog = New OpenFileDialog()
Dim result As DialogResult = fileChooser.ShowDialog()
Dim fileName As String ' name of file containing data
Instantiates an object of
class OpenFileDialog
 2002 Prentice Hall.
All rights reserved.
42
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Outline
' exit event handler if user clicked Cancel
If result = DialogResult.Cancel Then
Return
End If
ReadSequentialAc
cessFile.vb
fileName = fileChooser.FileName ' get specified file name
ClearTextBoxes()
' show error if user specified invalid file
If (fileName = "" OrElse fileName = Nothing) Then
MessageBox.Show("Invalid File Name", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else ' open file if user specified valid file
' create FileStream to obtain read access to file
input = New FileStream(fileName, FileMode.Open, _
FileAccess.Read)
FileStream object is created
and assigned to reference input
cmdNext.Enabled = True ' enable Next Record button
End If
End Sub ' cmdOpen_Click
Method Next is called,
which reads the next record
from the user-specified file
' invoked when user clicks Next button
Protected Sub cmdNext_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles cmdNext.Click
' deserialize CRecord and store data in TextBoxes
Try
' get next CRecord available in file
Dim record As CRecord = _
CType(reader.Deserialize(input), CRecord)
Method Deserialize reads
the next record and casts
the result to a CRecord
 2002 Prentice Hall.
All rights reserved.
43
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
Outline
' store CRecord values in temporary String array
Dim values As String() = New String() { _
record.Account.ToString(), _
record.FirstName.ToString(), _
record.LastName.ToString(), _
record.Balance.ToString()}
' copy String-array values to TextBox values
SetTextBoxValues(values)
' handle exception when no CRecords in file
Catch serializableException As SerializationException
ReadSequentialAc
cessFile.vb
The values are displayed
in textboxes
input.Close() ' close FileStream if no CRecords in file
cmdOpen.Enabled = True ' enable Open Record button
cmdNext.Enabled = False ' disable Next Record button
ClearTextBoxes()
Exception is caught if record
does not exist in the file
' notify user if no CRecords in file
MessageBox.Show("No more records in file", "", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub ' cmdNext_Click
End Class ' FrmReadSequentialAccessFile
 2002 Prentice Hall.
All rights reserved.
44
Outline
ReadSequentialAc
cessFile.vb
 2002 Prentice Hall.
All rights reserved.
45
Outline
ReadSequentialAc
cessFile.vb
 2002 Prentice Hall.
All rights reserved.
46
Outline
ReadSequentialAc
cessFile.vb
 2002 Prentice Hall.
All rights reserved.
47
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
' Fig. 17.12: CreditInquiry.vb
' Read a file sequentially and display contents based on account
' type specified by user (credit, debit or zero balances).
' Visual Basic namespaces
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports System.Windows.Forms
Outline
CreditInquiry.vb
' Deitel namespaces
Imports BankLibrary
Public Class FrmCreditInquiry
Inherits Form
' displays several lines of output
Friend WithEvents txtDisplay As RichTextBox
' buttons to open
Friend WithEvents
Friend WithEvents
Friend WithEvents
Friend WithEvents
Friend WithEvents
file, read records and exit program
cmdOpen As Button
cmdCredit As Button
cmdDebit As Button
cmdZero As Button
cmdDone As Button
' Visual Studio .NET generated code
' stream through which serializable data is read from file
Private input As FileStream
' object for deserializing CRecord in binary format
Dim reader As BinaryFormatter = New BinaryFormatter()
 2002 Prentice Hall.
All rights reserved.
48
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Outline
' name of file that stores credit, debit and zero balances
Private fileName As String
' invoked when user clicks Open File button
Protected Sub cmdOpen_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles cmdOpen.Click
CreditInquiry.vb
' create dialog box enabling user to open file
Dim fileChooser As OpenFileDialog = New OpenFileDialog()
Dim result As DialogResult = fileChooser.ShowDialog()
' exit event handler if user clicked Cancel
If result = DialogResult.Cancel Then
Return
End If
Instantiates an object of
class OpenFileDialog
Displays an open dialog
fileName = fileChooser.FileName ' get file name from user
' enable buttons allowing user to display balances
cmdCredit.Enabled = True
cmdDebit.Enabled = True
cmdZero.Enabled = True
' show error if user specified invalid file
If (fileName = "" OrElse fileName = Nothing) Then
MessageBox.Show("Invalid File Name", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
' else enable all GUI buttons, except for Open File button
Else
cmdOpen.Enabled = False
cmdCredit.Enabled = True
cmdDebit.Enabled = True
cmdZero.Enabled = True
End If
 2002 Prentice Hall.
All rights reserved.
49
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
Outline
End Sub ' cmdOpen_Click
' invoked when user clicks Credit Balances, Debit Balances
' or Zero Balances button
Protected Sub cmdGet_Click(ByVal senderObject As Object, _
ByVal e As System.EventArgs) Handles cmdCredit.Click, _
cmdZero.Click, cmdDebit.Click
CreditInquiry.vb
' convert senderObject explicitly to object of type Button
Dim senderButton As Button = CType(senderObject, Button)
Casts the senderObject
parameter
' get text from clicked Button, which stores account type
Dim accountType As String = senderButton.Text
' used to store each record read from file
Dim record As CRecord
Extracts the Button
object’s text
' read and display file information
Try
' close file from previous operation
If (input Is Nothing) = False Then
input.Close()
End If
' create FileStream to obtain read access to file
input = New FileStream(fileName, FileMode.Open, _
FileAccess.Read)
Create FileStream object with
read-only file access
txtDisplay.Text = "The accounts are:" & vbCrLf
 2002 Prentice Hall.
All rights reserved.
50
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
Outline
' traverse file until end of file
While True
' get next CRecord available in file
record = CType(reader.Deserialize(input), CRecord)
' store record's last field in balance
Dim balance As Double = record.Balance
CreditInquiry.vb
Method Deserialize obtains
each record repeatedly
throughout the While loop
' determine whether to display balance
If ShouldDisplay(balance, accountType) = True Then
' display record
Method ShouldDisplay
Dim output As String = record.Account & vbTab & _ determines whether to
record.FirstName & vbTab & record.LastName & _
display each record in the file
Space(6) & vbTab
' display balance with correct monetary format
output &= _
String.Format("{0:F}", balance) & vbCrLf
txtDisplay.Text &= output ' copy output to screen
End If
End While
' handle exception when file cannot be closed
Catch fileException As IOException
MessageBox.Show("Cannot Close File", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Method Close of FileStream
closes the file
' handle exception when no more records
Catch serializableException As SerializationException
input.Close() ' close FileStream if no CRecords in file
 2002 Prentice Hall.
All rights reserved.
51
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
End Try
Outline
End Sub ' cmdGet_Click
' determine whether to display given record
Private Function ShouldDisplay(ByVal balance As Double, _
ByVal accountType As String) As Boolean
CreditInquiry.vb
If balance > 0 Then
' display Credit Balances
If accountType = "Credit Balances" Then
Return True
End If
ElseIf balance < 0 Then
' display Debit Balances
If accountType = "Debit Balances" Then
Return True
End If
The three conditions on which
method ShouldDisplay
should return true
Else ' balance = 0
' display Zero Balances
If accountType = "Zero Balances" Then
Return True
End If
End If
Return False
End Function ' ShouldDisplay
 2002 Prentice Hall.
All rights reserved.
52
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
' invoked when user clicks Done button
Protected Sub cmdDone_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles cmdDone.Click
' determine whether file exists
If input Is Nothing = False Then
Outline
CreditInquiry.vb
' close file
Try
input.Close()
' notify user of error closing file
Catch fileException As IOException
MessageBox.Show("Cannot close file", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
Application.Exit()
End Sub ' cmdDone_Click
End Class ' FrmCreditInquiry
 2002 Prentice Hall.
All rights reserved.
53
Outline
CreditInquiry.vb
 2002 Prentice Hall.
All rights reserved.
54
Outline
CreditInquiry.vb
 2002 Prentice Hall.
All rights reserved.
55
Outline
CreditInquiry.vb
 2002 Prentice Hall.
All rights reserved.
56
17.7 Random-Access Files
• Sequential-access file
– Inappropriate for “instant-access”
• Random-access file (Direct-access file)
– Can access individual records quickly
• Airline-reservation systems
• Banking systems
• Point-of-sale systems
 2002 Prentice Hall. All rights reserved.
57
17.7 Random-Access Files
0
100
200
300
400
500
byte offsets
100
bytes
100
bytes
100
bytes
100
bytes
100
bytes
100
bytes
Fig. 17.13 Our view of a random-access file with fixed-length records.
 2002 Prentice Hall. All rights reserved.
58
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
' Fig. 17.14: CRandomAccessRecord.vb
' Data-record class for random-access applications.
Public Class CRandomAccessRecord
CRandomAccessRec
ord.vb
' length of mFirstName and mLastName
Private Const CHAR_ARRAY_LENGTH As Integer = 15
Private Const SIZE_OF_CHAR As Integer = 2
Private Const SIZE_OF_INT32 As Integer = 4
Private Const SIZE_OF_DOUBLE As Integer = 8
' length of record
Public Const SIZE As Integer = SIZE_OF_INT32 + _
2 * (SIZE_OF_CHAR * CHAR_ARRAY_LENGTH) + SIZE_OF_DOUBLE
' record data
Private mAccount As Integer
Private mFirstName(CHAR_ARRAY_LENGTH) As Char
Private mLastName(CHAR_ARRAY_LENGTH) As Char
Private mBalance As Double
Private data members
for storing record information
' default constructor sets members to default values
Public Sub New()
Sets the four members
Me.New(0, "", "", 0.0)
End Sub ' New
to their default values
' overloaded constructor sets members to parameter values
Public Sub New(ByVal accountValue As Integer, _
ByVal firstNameValue As String, _
ByVal lastNameValue As String, _
ByVal balanceValue As Double)
Account = accountValue
FirstName = firstNameValue
 2002 Prentice Hall.
All rights reserved.
59
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
Outline
LastName = lastNameValue
Balance = balanceValue
End Sub ' New
CRandomAccessRec
ord.vb
' property Account
Public Property Account() As Integer
Get
Return mAccount
End Get
Method for accessing
the Account data member
Set(ByVal accountValue As Integer)
mAccount = accountValue
End Set
End Property ' Account
' property FirstName
Public Property FirstName() As String
Get
Return mFirstName
End Get
Set(ByVal firstNameValue As String)
The length of the
first name is determined
' determine length of String parameter
Dim stringSize As Integer = firstNameValue.Length()
' recordFirstName String representation
Dim recordFirstNameString As String = firstNameValue
 2002 Prentice Hall.
All rights reserved.
60
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
' append spaces to String parameter if too short
If CHAR_ARRAY_LENGTH >= stringSize Then
recordFirstNameString = firstNameValue & _
Space(CHAR_ARRAY_LENGTH - stringSize)
Outline
CRandomAccessRec
If the first
name is
long less than ord.vb
15 characters
then spaces are added to the end
' remove characters from String parameter if too
Else
recordFirstNameString = _
firstNameValue.Substring(0, CHAR_ARRAY_LENGTH)
End If
' convert String parameter to Char array
mFirstName = recordFirstNameString.ToCharArray()
Characters are removed if
the name is too long
End Set
End Property ' FirstName
' property LastName
Public Property LastName() As String
Get
Return mLastName
End Get
Set(ByVal lastNameValue As String)
The length of the
last name is determined
' determine length of String parameter
Dim stringSize As Integer = lastNameValue.Length()
' recordLastName String representation
Dim recordLastNameString As String = lastNameValue
 2002 Prentice Hall.
All rights reserved.
61
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
' append spaces to String parameter if too short
If CHAR_ARRAY_LENGTH >= stringSize Then
recordLastNameString = lastNameValue & _
Space(CHAR_ARRAY_LENGTH - stringSize)
Outline
CRandomAccessRec
If the last
name is
long less than ord.vb
15 characters
then spaces are added to the end
' remove characters from String parameter if too
Else
recordLastNameString = _
lastNameValue.Substring(0, CHAR_ARRAY_LENGTH)
End If
' convert String parameter to Char array
mLastName = recordLastNameString.ToCharArray()
Characters are removed if
the name is too long
End Set
End Property ' LastName
' property Balance
Public Property Balance() As Double
Get
Return mBalance
End Get
Method for accessing
the Balance data member
Set(ByVal balanceValue As Double)
mBalance = balanceValue
End Set
End Property ' Balance
End Class ' CRandomAccessRecord
 2002 Prentice Hall.
All rights reserved.
62
17.8 Creating a Random-Access File
• Class BinaryWriter
– Bytes can be written directly to a file
 2002 Prentice Hall. All rights reserved.
63
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
' Fig. 17.15: CreateRandomAccessFile.vb
' Creating a random file.
' Visual Basic namespaces
Imports System.IO
Imports System.Windows.Forms
CreateRandomAcce
ssFile.vb
' Deitel namespaces
Imports BankLibrary
Public Class CCreateRandomAccessFile
' number of records to write to disk
Private Const NUMBER_OF_RECORDS As Integer = 100
' start application
Shared Sub Main()
' create random file, then save to disk
Dim file As CCreateRandomAccessFile = _
New CCreateRandomAccessFile()
file.SaveFile()
End Sub ' Main
Method Main calls user-defined
method SaveFile
' write records to disk
Private Sub SaveFile()
' record for writing to disk
Dim blankRecord As CRandomAccessRecord = _
New CRandomAccessRecord()
' stream through which serializable data is written to file
Dim fileOutput As FileStream
 2002 Prentice Hall.
All rights reserved.
64
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Outline
' stream for writing bytes to file
Dim binaryOutput As BinaryWriter
' create dialog box enabling user to save file
Dim fileChooser As SaveFileDialog = New SaveFileDialog()
Dim result As DialogResult = fileChooser.ShowDialog
' get file name from user
Dim fileName As String = fileChooser.FileName
Dim i As Integer
CreateRandomAcce
ssFile.vb
A SaveFileDialog object is created
' exit event handler if user clicked Cancel
If result = DialogResult.Cancel Then
Return
End If
' show error if user specified invalid file
If (fileName = "" OrElse fileName = Nothing) Then
MessageBox.Show("Invalid File Name", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' write records to file
Try
' create FileStream to hold records
fileOutput = New FileStream(fileName, _
FileMode.Create, FileAccess.Write)
FileStream instantiated
' set length of file
fileOutput.SetLength( _
CRandomAccessRecord.SIZE * NUMBER_OF_RECORDS)
' create object for writing bytes to file
binaryOutput = New BinaryWriter(fileOutput)
The length of the FileStream
is set
 2002 Prentice Hall.
All rights reserved.
65
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
Outline
' write empty records to file
For i = 0 To NUMBER_OF_RECORDS - 1
' set file-position pointer in file
fileOutput.Position = i * CRandomAccessRecord.SIZE
' write
blank record to file
Defines the
For loop
binaryOutput.Write(blankRecord.Account)
that populates the file with
binaryOutput.Write(blankRecord.FirstName)
100 copies of empty
record values
binaryOutput.Write(blankRecord.LastName)
CreateRandomAcce
ssFile.vb
Changes the file-position
pointer
binaryOutput.Write(blankRecord.Balance)
Next
' notify user of success
MessageBox.Show("File Created", "Success", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
' show error if error occurs during writing
Catch fileException As IOException
MessageBox.Show("Cannot write to file", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
' close FileStream
If (fileOutput Is Nothing) <> False Then
fileOutput.Close()
End If
 2002 Prentice Hall.
All rights reserved.
66
103
104
105
106
107
108
109
110
' close BinaryWriter
If (binaryOutput Is Nothing) <> False Then
binaryOutput.Close()
End If
End Sub ' SaveFile
Outline
CreateRandomAcce
ssFile.vb
End Class ' FrmCreateRandomAccessFile
 2002 Prentice Hall.
All rights reserved.
67
17.9 Writing Data Randomly to a RandomAccess File
• Now that we have created a file, we use class
FrmWriteRandomAccessFile to write data
to that file
 2002 Prentice Hall. All rights reserved.
68
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
' Fig 17.16: WriteRandomAccessFile.vb
' Write data to a random-access file.
' Visual Basic namespaces
Imports System.IO
Imports System.Windows.Forms
WriteRandomAcces
sFile.vb
' Deitel namespaces
Imports BankLibrary
Public Class FrmWriteRandomAccessFile
Inherits FrmBankUI
' buttons for opening file and entering data
Friend WithEvents cmdOpen As Button
Friend WithEvents cmdEnter As Button
We use this class to
write data to the file
' Visual Studio .NET generated code
' number of CRandomAccessRecords to write to disk
Private Const NUMBER_OF_RECORDS As Integer = 100
' stream through which data is written to file
Private fileOutput As FileStream
The number of records is
made a constant
' stream for writing bytes to file
Private binaryOutput As BinaryWriter
' invoked when user clicks Open button
Public Sub cmdOpen_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdOpen.Click
' create dialog box enabling user to open file
Dim fileChooser As OpenFileDialog = New OpenFileDialog()
Dim result As DialogResult = fileChooser.ShowDialog()
 2002 Prentice Hall.
All rights reserved.
69
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
Outline
' get file name from user
Dim fileName As String = fileChooser.FileName
WriteRandomAcces
sFile.vb
' exit event handler if user clicked Cancel
If result = DialogResult.Cancel Then
Return
End If
' show error if user specified invalid file
If (fileName = "" OrElse fileName = Nothing) Then
MessageBox.Show("Invalid File Name", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
' open file if user specified valid file
Else
' open file if file already exists
Try
Uses the FileStream reference
to instantiate an object of class
BinaryWriter, enabling writing of bytes
' create FileStream to hold records
fileOutput = New FileStream(fileName, FileMode.Open, _
FileAccess.Write)
' create object for writing bytes to file
binaryOutput = New BinaryWriter(fileOutput)
cmdOpen.Enabled = False ' disable Open button
cmdEnter.Enabled = True ' enable Enter button
' notify user if file does not exist
Catch fileException As IOException
MessageBox.Show("File Does Not Exits", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
 2002 Prentice Hall.
All rights reserved.
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
Outline
End Try
End If
WriteRandomAcces
sFile.vb
End Sub ' cmdOpen_Click
' invoked when user clicks Enter button
Private Sub cmdEnter_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdEnter.Click
' account-number value from TextBox
Dim accountNumber As Integer
' TextBox-values String array
Dim values As String() = GetTextBoxValues()
This method is called
when the user clicks enter
' determine whether TextBox account field is empty
If (values(TextBoxIndices.ACCOUNT) <> "") Then
Retrieves data
' write record to file at appropriate position
Try
' get account-number value from TextBox
accountNumber = _
Convert.ToInt32(values(TextBoxIndices.ACCOUNT))
' determine whether accountNumber is valid
If (accountNumber > 0 AndAlso _
accountNumber <= NUMBER_OF_RECORDS) Then
Determines whether the account
number hold valid information
' move file-position pointer
fileOutput.Seek((accountNumber - 1) * _
CRandomAccessRecord.SIZE, SeekOrigin.Begin)
 2002 Prentice Hall.
All rights reserved.
71
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
' write data to file
binaryOutput.Write(accountNumber)
binaryOutput.Write(values(TextBoxIndices.FIRST))
binaryOutput.Write(values(TextBoxIndices.LAST))
binaryOutput.Write( Convert.ToDouble( _
values(TextBoxIndices.BALANCE)))
' notify user if invalid account number
Else
MessageBox.Show("Invalid Account Number", _
"Error", MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End If
Outline
WriteRandomAcces
sFile.vb
Data is written to file
ClearTextBoxes()
' notify user if error occurs when formatting numbers
Catch formattingException As FormatException
MessageBox.Show("Invalid Balance", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
ClearTextBoxes() ' clear TextBox values
End Sub ' cmdEnter_Click
End Class ' FrmWriteRandomAccessFile
 2002 Prentice Hall.
All rights reserved.
72
Outline
WriteRandomAcces
sFile.vb
 2002 Prentice Hall.
All rights reserved.
73
Outline
WriteRandomAcces
sFile.vb
 2002 Prentice Hall.
All rights reserved.
74
Outline
WriteRandomAcces
sFile.vb
 2002 Prentice Hall.
All rights reserved.
75
17.10 Reading Data Sequentially from a
Random-Access File
• Class BinaryReader
– Bytes can be read directly from a file
 2002 Prentice Hall. All rights reserved.
76
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
' Fig 17.17: ReadRandomAccessFile.vb
' Reads and displays random-access file contents.
' Visual Basic namespaces
Imports System.IO
Imports System.Windows.Forms
Outline
ReadRandomAccess
File.vb
' Deitel namespaces
Imports BankLibrary
Public Class FrmReadRandomAccessFile
Inherits FrmBankUI
' buttons for opening file and reading records
Friend WithEvents cmdOpen As Button
Friend WithEvents cmdNext As Button
' Visual Studio .NET generated code
' stream through which data is read from file
Private fileInput As FileStream
' stream for reading bytes from file
Private binaryInput As BinaryReader
' index of current record to be displayed
Private currentRecordIndex As Integer
' invoked when user clicks Open button
Protected Sub cmdOpen_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdOpen.Click
' create dialog box enabling user to open file
Dim fileChooser As OpenFileDialog = New OpenFileDialog()
Dim result As DialogResult = fileChooser.ShowDialog()
 2002 Prentice Hall.
All rights reserved.
77
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Outline
' get file name from user
Dim fileName As String = fileChooser.FileName
ReadRandomAccess
File.vb
' exit event handler if user clicked Cancel
If result = DialogResult.Cancel Then
Return
End If
' show error if user specified invalid file
If (fileName = "" OrElse fileName = Nothing) Then
MessageBox.Show("Invalid File Name", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
' open file if user specified valid file
Else
' create FileStream to obtain read access to file
fileInput = New FileStream(fileName, FileMode.Open, _
FileAccess.Read)
' use FileStream for BinaryWriter to read bytes from file
binaryInput = New BinaryReader(fileInput)
cmdOpen.Enabled = False ' disable Open button
cmdNext.Enabled = True ' enable Next button
currentRecordIndex = 0
ClearTextBoxes()
End If
Creates an instance
of BinaryReader, which
reads bytes from a stream
End Sub ' cmdOpen_Click
 2002 Prentice Hall.
All rights reserved.
78
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
' invoked when user clicks Next button
Protected Sub cmdNext_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdNext.Click
Outline
ReadRandomAccess
File.vb
' record to store file data
Dim record As CRandomAccessRecord = _
New CRandomAccessRecord()
' read record and store data in TextBoxes
Try
Dim values As String() ' for storing TextBox values
' get next record available in file
While (record.Account = 0)
' set file-position pointer to next record in file
fileInput.Seek( _
currentRecordIndex * CRandomAccessRecord.SIZE, 0)
currentRecordIndex += 1
' read data from record
record.Account = binaryInput.ReadInt32()
record.FirstName = binaryInput.ReadString()
record.LastName = binaryInput.ReadString()
record.Balance = binaryInput.ReadDouble()
End While
' store record values in temporary String array
values = New String() { _
record.Account.ToString(), _
record.FirstName.ToString(), _
record.LastName.ToString(), _
record.Balance.ToString()}
Reads from file until
non-zero account number
is reached
Method Seek moves the pointer
to the appropriate place in the file
where the record must be read
 2002 Prentice Hall.
All rights reserved.
79
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
' copy String-array values to TextBox values
SetTextBoxValues(values)
' handle exception when no records in file
Catch fileException As IOException
' close streams if no records in file
fileInput.Close()
binaryInput.Close()
Outline
ReadRandomAccess
File.vb
Record is displayed
in textboxes
cmdOpen.Enabled = True ' enable Open button
cmdNext.Enabled = False ' disable Next button
ClearTextBoxes()
' notify user if no records in file
MessageBox.Show("No more records in file", "", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub ' cmdNext_Click
End Class ' FrmReadRandomAccessFile
 2002 Prentice Hall.
All rights reserved.
80
Outline
ReadRandomAccess
File.vb
 2002 Prentice Hall.
All rights reserved.
81
Outline
ReadRandomAccess
File.vb
 2002 Prentice Hall.
All rights reserved.
82
Outline
ReadRandomAccess
File.vb
 2002 Prentice Hall.
All rights reserved.
83
17.11 Case Study: A TransactionProcessing Program
• Transaction-Processing Program
– Achieve “instant access” processing
 2002 Prentice Hall. All rights reserved.
84
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
' Fig. 17.18: CTransaction.vb
' Handles record transactions.
' Visual Basic namespaces
Imports System.IO
Imports System.Windows.Forms
CTransaction.vb
' Deitel namespaces
Imports BankLibrary
Public Class CTransaction
' number of records to write to disk
Private Const NUMBER_OF_RECORDS As Integer = 100
' stream through which data moves to and from file
Private file As FileStream
' stream for reading bytes from file
Private binaryInput As BinaryReader
' stream for writing bytes to file
Private binaryOutput As BinaryWriter
' create/open file containing empty records
Public Sub OpenFile(ByVal fileName As String)
' write empty records to file
Try
BinaryReader object created
' create FileStream from new file or existing file
file = New FileStream(fileName, FileMode.OpenOrCreate)
' use FileStream for BinaryWriter to read bytes from file
binaryInput = New BinaryReader(file)
 2002 Prentice Hall.
All rights reserved.
85
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
' use FileStream for BinaryWriter to write bytes to file
binaryOutput = New BinaryWriter(file)
CTransaction.vb
' determine whether file has just been created
If file.Length = 0 Then
' record to be written to file
Dim blankRecord As CRandomAccessRecord = _
New CRandomAccessRecord()
Outline
BinaryWriter object created
Dim i As Integer ' counter
' new record can hold NUMBER_OF_RECORDS records
file.SetLength( _
CRandomAccessRecord.SIZE * NUMBER_OF_RECORDS)
' write blank records to file
For i = 0 To NUMBER_OF_RECORDS - 1
' move file-position pointer to next position
file.Position = i * CRandomAccessRecord.SIZE
' write blank record to file
binaryOutput.Write(blankRecord.Account)
binaryOutput.Write(blankRecord.FirstName)
binaryOutput.Write(blankRecord.LastName)
binaryOutput.Write(blankRecord.Balance)
Next
Populate with empty records
End If
 2002 Prentice Hall.
All rights reserved.
86
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
' notify user of error during writing of blank records
Catch fileException As IOException
MessageBox.Show("Cannot create file", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Outline
CTransaction.vb
End Try
End Sub ' OpenFile
' retrieve record depending on whether account is valid
Public Function GetRecord(ByVal accountValue As String) _
As CRandomAccessRecord
' store file data associated with account in record
Try
' record to store file data
Dim record As CRandomAccessRecord = _
New CRandomAccessRecord()
Instantiate object that
will store the file data
' get value from TextBox's account field
Dim accountNumber As Integer = _
Convert.ToInt32(accountValue)
' if account is invalid, do not read data
If (accountNumber < 1 OrElse _
accountNumber > NUMBER_OF_RECORDS) Then
' set record's account field with account number
record.Account = accountNumber
 2002 Prentice Hall.
All rights reserved.
87
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
Outline
' get data from file if account is valid
Else
' locate position in file where record exists
file.Seek( _
(accountNumber - 1) * CRandomAccessRecord.SIZE, 0)
' read data from record
record.Account = binaryInput.ReadInt32()
record.FirstName = binaryInput.ReadString()
record.LastName = binaryInput.ReadString()
record.Balance = binaryInput.ReadDouble()
End If
CTransaction.vb
Determines the position of
the specified record in the file
Return record
' notify user of error during reading
Catch fileException As IOException
MessageBox.Show("Cannot read file", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
' notify user of error in parameter mismatch
Catch formattingException As FormatException
MessageBox.Show("Invalid Account", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return Nothing
End Function ' GetRecord
' add record to file at position determined by accountNumber
Public Function AddRecord(ByVal record As CRandomAccessRecord, _
ByVal accountNumber As Integer) As Boolean
 2002 Prentice Hall.
All rights reserved.
88
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
Outline
' write record to file
Try
' move file-position pointer to appropriate position
file.Seek( _
(accountNumber - 1) * CRandomAccessRecord.SIZE, 0)
' write data to file
binaryOutput.Write(record.Account)
binaryOutput.Write(record.FirstName)
binaryOutput.Write(record.LastName)
binaryOutput.Write(record.Balance)
CTransaction.vb
Call the overloaded Write
methods and write to the file
' notify user if error occurs during writing
Catch fileException As IOException
MessageBox.Show("Error Writing To File", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Return False ' failure
End Try
Return True ' success
End Sub ' AddRecord
End Class ' CTransaction
 2002 Prentice Hall.
All rights reserved.
89
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
' Fig. 17.19: TransactionProcessor.vb
' MDI parent for transaction-processor application.
Imports System.Windows.Forms
Public Class FrmTransactionProcessor
Inherits Form
Outline
TransactionProce
ssor.vb
' Visual Studio .NET generated code
' reference to Multiple-Document-Interface client
Private childForm As MdiClient
' reference to StartDialog
Private startDialog As FrmStartDialog
End Class ' FrmTransactionProcessor
 2002 Prentice Hall.
All rights reserved.
90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
'
'
'
'
Fig. 17.20: StartDialog.vb
Initial dialog box displayed to user. Provides buttons for
creating/opening file and for adding, updating and removing
records from file.
Outline
StartDialog.vb
' Visual Basic namespaces
Imports System.Windows.Forms
' Deitel namespaces
Imports BankLibrary
Public Class FrmStartDialog
Inherits Form
' buttons for displaying other dialogs
Friend WithEvents cmdOpen As Button
Friend WithEvents cmdNew As Button
Friend WithEvents cmdUpdate As Button
Friend WithEvents cmdDelete As Button
Open, New, Update and Delete Buttons
' Visual Studio .NET generated code
' reference to dialog box for adding record
Private newDialog As FrmNewDialog
' reference to dialog box for updating record
Private updateDialog As FrmUpdateDialog
' reference to dialog box for removing record
Private deleteDialog As FrmDeleteDialog
' reference to object that handles transactions
Private transactionProxy As CTransaction
 2002 Prentice Hall.
All rights reserved.
91
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
Outline
' invoked when user clicks New/Open File button
Protected Sub cmdOpen_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdOpen.Click
' create dialog box enabling user to create or open file
Dim fileChooser As OpenFileDialog = New OpenFileDialog()
Dim result As DialogResult
Dim fileName As String
' enable user to create file if file does not exist
fileChooser.Title = "Create File / Open File"
fileChooser.CheckFileExists = False
StartDialog.vb
User can create a file if
the sepecified file does not exist
result = fileChooser.ShowDialog() ' show dialog box to user
' exit event handler if user clicked Cancel
If result = DialogResult.Cancel Then
Return
End If
' get file name from user
fileName = fileChooser.FileName
Exit event handler if the
user clicks the Cancel button
' show error if user specified invalid file
If (fileName = "" OrElse fileName = Nothing) Then
MessageBox.Show("Invalid File Name", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
' open or create file if user specified valid file
Else
' create CTransaction with specified file
transactionProxy = New CTransaction()
transactionProxy.OpenFile(fileName)
Acts as proxy for creating,
reading and writing
random-access file records
 2002 Prentice Hall.
All rights reserved.
92
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
' enable GUI buttons except for New/Open File button
cmdNew.Enabled = True
cmdUpdate.Enabled = True
cmdDelete.Enabled = True
cmdOpen.Enabled = False
Outline
StartDialog.vb
' instantiate dialog box for creating records
newDialog = New FrmNewDialog(transactionProxy, _
AddressOf ShowStartDialog)
' instantiate dialog box for updating records
updateDialog = New FrmUpdateDialog(transactionProxy, _
AddressOf ShowStartDialog)
' instantiate dialog box for removing records
deleteDialog = New FrmDeleteDialog(transactionProxy, _
AddressOf ShowStartDialog)
Serve as the child windows
' set StartDialog as MdiParent for dialog boxes
newDialog.MdiParent = Me.MdiParent
updateDialog.MdiParent = Me.MdiParent
deleteDialog.MdiParent = Me.MdiParent
End If
End Sub ' cmdOpen_Click
' invoked when user clicks New Record button
Protected Sub cmdNew_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdNew.Click
Hide() ' hide StartDialog
newDialog.Show() ' show NewDialog
End Sub ' cmdNew_Click
 2002 Prentice Hall.
All rights reserved.
93
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
Outline
' invoked when user clicks Update Record button
Protected Sub cmdUpdate_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdUpdate.Click
Hide() ' hide StartDialog
updateDialog.Show() ' show UpdateDialog
End Sub ' cmdUpdate_Click
StartDialog.vb
' invoked when user clicks Delete Record button
Protected Sub cmdDelete_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdDelete.Click
Hide() ' hide StartDialog
deleteDialog.Show() ' show DeleteDialog
End Sub ' cmdDelete_Click
' displays StartDialog
Protected Sub ShowStartDialog()
Show()
End Sub ' ShowStartDialog
The delete dialog is displayed
End Class ' FrmStartDialog
 2002 Prentice Hall.
All rights reserved.
94
Outline
StartDialog.vb
 2002 Prentice Hall.
All rights reserved.
95
Outline
StartDialog.vb
 2002 Prentice Hall.
All rights reserved.
96
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
' Fig. 17.21: NewDialog.vb
' Enables user to insert new record into file.
' Visual Basic namespaces
Imports System.Windows.Forms
Outline
NewDialog.vb
' Deitel namespaces
Imports BankLibrary
Public Class FrmNewDialog
Inherits FrmBankUI
' buttons for creating record and canceling action
Friend WithEvents cmdSave As Button
Friend WithEvents cmdCancel As Button
' Windows Form Designer generated code
' reference to object that handles transactions
Private transactionProxy As CTransaction
' delegate for method that displays previous window
Delegate Sub MyDelegate()
Public showPreviousWindow As MyDelegate
' initialize components and set members to parameter values
Public Sub New(ByVal transactionProxyValue As CTransaction, _
ByVal delegateValue As MyDelegate)
InitializeComponent()
showPreviousWindow = delegateValue
' instantiate object that handles transactions
transactionProxy = transactionProxyValue
End Sub ' New
 2002 Prentice Hall.
All rights reserved.
97
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
' invoked when user clicks Cancel button
Protected Sub cmdCancel_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdCancel.Click
Outline
NewDialog.vb
Hide()
ClearTextBoxes()
showPreviousWindow()
End Sub ' cmdCancel_Click
' invoked when user clicks Save As button
Protected Sub cmdSave_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdSave.Click
Dim record As CRandomAccessRecord = _
transactionProxy.GetRecord( _
GetTextBoxValues(TextBoxIndices.ACCOUNT))
' if record exists, add it to file
If (record Is Nothing) = False Then
InsertRecord(record)
End If
Hide()
ClearTextBoxes()
showPreviousWindow()
End Sub ' cmdSave_Click
Writes the record to disk
Method GetRecord should
return an empty CRandomAccessRecord
Method InsertRecord is called
' insert record in file at position specified by accountNumber
Private Sub InsertRecord(ByVal record As CRandomAccessRecord)
' store TextBox values in String array
Dim textBoxValues As String() = GetTextBoxValues()
 2002 Prentice Hall.
All rights reserved.
98
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
Outline
' store TextBox account field
Dim accountNumber As Integer = _
Convert.ToInt32(textBoxValues(TextBoxIndices.ACCOUNT))
' notify user and return if record account is not empty
If record.Account <> 0 Then
MessageBox.Show( _
"Record Already Exists or Invalid Number", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
NewDialog.vb
If users try to overwrite
an existing file a message box
is displayed
Return
End If
' store values in record
record.Account = accountNumber
record.FirstName = textBoxValues(TextBoxIndices.FIRST)
record.LastName = textBoxValues(TextBoxIndices.LAST)
record.Balance = Convert.ToDouble( _
textBoxValues(TextBoxIndices.BALANCE))
' add record to file
Try
A newly created
CRandomAccessRecord
is inserted into the file
If (transactionProxy.AddRecord( _
record, accountNumber) = False ) Then
Return ' if error
End If
' notify user if error occurs in parameter mismatch
Catch formattingException As FormatException
MessageBox.Show("Invalid Balance", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
 2002 Prentice Hall.
All rights reserved.
99
105
106
107
108
109
110
MessageBox.Show("Record Created", "Success", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub ' InsertRecord
Outline
NewDialog.vb
End Class ' FrmNewDialog
 2002 Prentice Hall.
All rights reserved.
100
Outline
NewDialog.vb
 2002 Prentice Hall.
All rights reserved.
101
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
' Fig. 17.22: UpdateDialog.vb
' Enables user to update records in file.
' Visual Basic namespaces
Imports System.Windows.Forms
' Deitel namespaces
Imports BankLibrary
Outline
UpdateDialog.vb
This method enables users to
update existing records
Public Class FrmUpdateDialog
Inherits FrmBankUI
' label and textbox for user to enter transaction data
Friend WithEvents lblTransaction As Label
Friend WithEvents txtTransaction As TextBox
' buttons for saving data to file and canceling save
Friend WithEvents cmdSave As Button
Friend WithEvents cmdCancel As Button
' Visual Studio .NET generated code
' reference to object that handles transactions
Private transactionProxy As CTransaction
' delegate for method that displays previous window
Delegate Sub MyDelegate()
Public showPreviousWindow As MyDelegate
' initialize components and set members to parameter values
Public Sub New(ByVal transactionProxyValue As CTransaction, _
ByVal delegateValue As MyDelegate)
InitializeComponent()
showPreviousWindow = delegateValue
 2002 Prentice Hall.
All rights reserved.
102
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Outline
' instantiate object that handles transactions
transactionProxy = transactionProxyValue
End Sub ' New
UpdateDialog.vb
' invoked when user enters text in Account TextBox
Protected Sub txtAccountNumber_KeyDown( _
ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles txtAccount.KeyDown
' determine whether user pressed Enter Key
If e.KeyCode = Keys.Enter Then
' retrieve record associated with account from file
Dim record As CRandomAccessRecord = _
transactionProxy.GetRecord( _
GetTextBoxValues(TextBoxIndices.ACCOUNT))
' return if record does not exist
If (record Is Nothing) = True Then
Return
End If
' determine whether record is empty
If record.Account <> 0 Then
Method txtAccountNumber
calls method GetRecord
If record does exist
store the values in an array
' store record values in String array
Dim values As String() = {record.Account.ToString(), _
record.FirstName.ToString(), _
record.LastName.ToString(), _
record.Balance.ToString()}
 2002 Prentice Hall.
All rights reserved.
103
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
Outline
' copy String-array value to TextBox values
SetTextBoxValues(values)
txtTransaction.Text = "[Charge or Payment]"
' notify user if record does not exist
Else
MessageBox.Show("Record Does Not Exist", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
UpdateDialog.vb
End If
Notify the user that the
record does not exist
End If
End Sub ' txtAccountNumber_KeyDown
' invoked when user enters text in Transaction TextBox
Protected Sub txtTransactionNumber_KeyDown( _
ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) _
Handles txtTransaction.KeyDown
' determine whether user pressed Enter key
If e.KeyCode = Keys.Enter Then
This method is invoked
when the user enters text into
the Transaction textbox
' calculate balance using Transaction TextBox value
Try
' retrieve record associated with account from file
Dim record As CRandomAccessRecord = _
transactionProxy.GetRecord( _
GetTextBoxValues(TextBoxIndices.ACCOUNT))
' get Transaction TextBox value
Dim transactionValue As Double = _
Convert.ToDouble(txtTransaction.Text)
 2002 Prentice Hall.
All rights reserved.
104
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
' calculate new balance (old balance + transaction)
Dim newBalance As Double = _
record.Balance + transactionValue
Outline
UpdateDialog.vb
' store record values in String array
Dim values As String() = {record.Account.ToString(), _
record.FirstName.ToString(), _
record.LastName.ToString(), newBalance.ToString()}
' copy String-array value to TextBox values
SetTextBoxValues(values)
' clear txtTransactionNumber
txtTransaction.Text = ""
' notify user if error occurs in parameter mismatch
Catch formattingException As FormatException
MessageBox.Show("Invalid Transaction", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub ' txtTransactionNumber_KeyDown
Invoked when the user
clicks the Save button
' invoked when user clicks Save button
Protected Sub cmdSave_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdSave.Click
Dim record As CRandomAccessRecord = _
transactionProxy.GetRecord( _
GetTextBoxValues(TextBoxIndices.ACCOUNT))
 2002 Prentice Hall.
All rights reserved.
105
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
' if record exists, update in file
If (record Is Nothing) = False Then
UpdateRecord(record)
End If
Outline
UpdateDialog.vb
Hide()
ClearTextBoxes()
showPreviousWindow()
End Sub ' cmdSave_Click
' invoked when user clicks Cancel button
Protected Sub cmdCancel_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdCancel.Click
Hide()
ClearTextBoxes()
showPreviousWindow()
End Sub ' cmdCancel_Click
' update record in file at position specified by accountNumber
Public Sub UpdateRecord(ByVal record As CRandomAccessRecord)
' store TextBox values in record and write record to file
Try
Method UpdateRecord is
Dim accountNumber As Integer = record.Account
Dim values As String() = GetTextBoxValues()
called by method SaveRecord
' store values in record
record.Account = accountNumber
record.FirstName = values(TextBoxIndices.FIRST)
record.LastName = values(TextBoxIndices.LAST)
record.Balance = _
Double.Parse(values(TextBoxIndices.BALANCE))
 2002 Prentice Hall.
All rights reserved.
106
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
' add record to file
If (transactionProxy.AddRecord( _
record, accountNumber) = False ) Then
Return ' if error
End If
Outline
UpdateDialog.vb
Updates record by
overwriting existing value
' notify user if error occurs in parameter mismatch
Catch formattingException As FormatException
MessageBox.Show("Invalid Balance", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End Try
MessageBox.Show("Record Updated", "Success", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub ' UpdateRecord
End Class ' FrmUpdateDialog
 2002 Prentice Hall.
All rights reserved.
107
Outline
UpdateDialog.vb
 2002 Prentice Hall.
All rights reserved.
108
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Outline
' Fig. 17.23: DeleteDialog.vb
' Enables user to delete records in file.
' Visual Basic namespaces
Imports System.Windows.Forms
' Deitel namespaces
Imports BankLibrary
Public Class FrmDeleteDialog
Inherits Form
DeleteDialog.vb
This method enables users
to remove existing records
from file
' label and TextBox enabling user to input account number
Friend WithEvents lblAccount As Label
Enable
Friend WithEvents txtAccount As TextBox
' buttons for deleting record and canceling action
Friend WithEvents cmdDelete As Button
Friend WithEvents cmdCancel As Button
user to enter
an account number
' Visual Studio .NET generated code
' reference to object that handles transactions
Private transactionProxy As CTransaction
' delegate for method that displays previous window
Delegate Sub MyDelegate()
Public showPreviousWindow As MyDelegate
' initialize components and set members to parameter values
Public Sub New(ByVal transactionProxyValue As CTransaction, _
ByVal delegateValue As MyDelegate)
InitializeComponent()
showPreviousWindow = delegateValue
 2002 Prentice Hall.
All rights reserved.
109
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
Outline
' instantiate object that handles transactions
transactionProxy = transactionProxyValue
End Sub ' New
DeleteDialog.vb
' invoked when user clicks Delete Record button
Protected Sub cmdDelete_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdDelete.Click
Dim record As CRandomAccessRecord = _
transactionProxy.GetRecord(txtAccount.Text)
' if record exists, delete it in file
If (record Is Nothing) = False Then
DeleteRecord(record)
End If
Me.Hide()
showPreviousWindow()
End Sub ' cmdDelete_Click
cmdDelete_Click is invoked
when the user clicks the
delete button
If the record exists
method DeleteRecord is called
' invoked when user clicks Cancel button
Protected Sub cmdCancel_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles cmdCancel.Click
Me.Hide()
showPreviousWindow()
End Sub ' cmdCancel_Click
 2002 Prentice Hall.
All rights reserved.
110
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
' delete record in file at position specified by accountNumber
Public Sub DeleteRecord(ByVal record As CRandomAccessRecord)
Dim accountNumber As Integer = record.Account
Outline
DeleteDialog.vb
' display error message if record does not exist
If record.Account = 0 Then
MessageBox.Show("Record Does Not Exist", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
txtAccount.Clear()
Return
End If
' create blank record
record = New CRandomAccessRecord()
' write over file record with empty record
If (transactionProxy.AddRecord( _
record, accountNumber) = True) Then
Record is written
over by an empty record
' notify user of successful deletion
MessageBox.Show("Record Deleted", "Success", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
' notify user of failure
MessageBox.Show("Record could not be deleted", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
txtAccount.Clear() ' clear text box
End Sub ' DeleteRecord
End Class ' FrmDeleteDialog
 2002 Prentice Hall.
All rights reserved.
111
Outline
DeleteDialog.vb
 2002 Prentice Hall.
All rights reserved.