Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a...

60
Files and Streams- II
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    233
  • download

    0

Transcript of Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a...

Page 1: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Files and Streams- II

Page 2: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File Serialization Using Dialogs File Exception Handling Case Study: A Transaction-Processing Program

Page 3: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Public Class myCar Public Make As String Public Model As String Public Year As IntegerEnd Class

Dim car1 = New myCar car1.Make = "Honda" car1.Model = "Accord“ car1.Year = 1990

How can we save car1 object to a file?

Serialization

Page 4: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• In traditional file processing supported by most compiled languages you learn to create values from primitive types (int, double, char, etc) and save them to a medium.

• Many libraries such as the .NET Framework provide built-in classes you can use to save a variable of your class as if the variable had been created from a primitive data type.

• Object serialization consists of saving the state of any object as a whole.

• Serialization makes it possible to easily create a file-based database since you are able to save and restore the object the same way you would use file processing of primitive types.

Serialization

Page 5: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• This is an example of the techniques used in file processing to save individual data of primitive types.

• Object serialization consists of saving a whole object as one instead of its individual fields:

Serialization

Page 6: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Serialization• Converting object into a format that

can be written to a file without losing data as a whole object.

Deserialization• Reading format from file and

reconstructing original object from it

Serialization

Page 7: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Different Types of Serialization

• The Microsoft .NET Framework provides an almost bewildering variety of ways to serialize an object. XML serialization , binary serialization and SOAP Serialization.

• This lecture focuses on Binary Serialization.

Serialization

Page 8: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Binary serialization

• To proceed with object serialization, you must first specify the object you would use.

• As with any other program, you can either use one of the classes built-in the .NET Framework or you can use your own programmer-created class.

Page 9: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• For a class to be serializable, it must be marked with the Serializable attribute.

• This means that, when checking the MSDN documentation, any class you see with this attribute is already configured to be serialized.

• This is the case for almost all list-oriented classes such as Array, ArrayList, etc.

Binary serialization

Page 10: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1. Creating a Serializable Class

• If you create your own class and want to be able to save values from its variables, you can (must) mark the class with the Serializable attribute.

• To do this, type <Serializable> before starting to create the class or the structure.

• The Serializable attribute informs the compiler that values from the class can be serialized.

• Ex:

Binary serialization

Page 11: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

2. Serializing an Object:• To support serialization of an object, the .NET

Framework provides the BinaryFormatter class from the

system.Runtime.Serialization.Formatters.Binary namespace.

• One of the methods of this class is called Serialize().

Binary serialization

Page 12: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

3. Deserializing an Object • The opposite of serialization is deserialization. Deserialization

is the process of retrieving an object that was serialized. • When this is done, an exact copy of the object that was saved

is created and restored as the origin.• To support deserialization, the BinaryFormatter class provides

the Deserialize() method,• The binary format is not human-readable, which makes it

more difficult to work with if the original program that produced the data is not available.

Binary serialization

Page 13: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Binary serialization - Example

Page 14: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.
Page 15: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.
Page 16: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.
Page 17: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Files using File Dialogues

Demo

Page 18: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Files using File Dialogues

Page 19: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.
Page 20: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1

2

Page 21: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.
Page 22: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1

2

3

Page 23: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.
Page 24: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Exception Handling• VB.NET has an inbuilt class that deals with errors. The Class is

called Exception. • When an exception error is found, an Exception object is

created. The coding structure VB.NET uses to deal with such Exceptions is called the Try … Catch structure.

• In the coding area for your button, type the word Try. Then hit the return key on your keyboard. VB.NET completes the rest of the structure for you:

Try

Catch ex As Exception

End Try

Page 25: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• The Try word means “Try to execute this code”. • The Catch word means “Catch any errors here”. • The ex is a variable, and the type of variable is an

Exception object.• When you run your program, VB will Try to execute

any code in the Try part. If everything goes well, then it skips the Catch part. However, if an error occurs, VB.NET jumps straight to Catch.

Exception Handling

Page 26: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Exception Handling

fs = new FileStream(FileName, FileMode.Open, FileAccess.Read)

FileName = “C:\test10.txt”

Page 27: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• Because ex is an object variable, it now has its own Properties and methods.

• One of these is the Message property. Run your program and test it out. Click your button.

• You should see the following error message:

Exception Handling

Page 28: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• The point about this new message box is that it will not crash your program. You have handled the Exception, and displayed an appropriate message for the user.

• If you know the kind of error that a program might throw, you can get what Type it is from the Error message box you saw earlier. This one:

Exception Handling

Page 29: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• Click the View Details links under Actions to see the following:

Page 30: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• The first line tells us the Type of Exception it is: System.IO.FileNotFoundException

• You can add this directly to the catch part. Previously, you were just catching any error that might be thrown: Catch ex As Exception

• But if you know a “file not found” error might be thrown, you can add that to the Catch line, instead of Exception: Catch ex As System.IO.FileNotFoundException

• You can keep the Exception line as well. (You can have as many Catch parts as you want.) This will Catch any other errors that may occur:

Try fs = new FileStream(FileName, FileMode.Open, FileAccess.Read)Catch ex As System.IO.FileNotFoundException MsgBox(“Can’t find this file”)Catch ex As Exception MsgBox(ex.Message)End Try

Exception Handling

Page 31: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

• There is one last part of the Try … Catch Statement that VB.NET doesn’t add for you Finally:

TryCatch ex As ExceptionFinallyEnd Try

• The Finally part is always executed, whether an error occurs or not. You typically add a Finally part to perform any cleanup operations that are needed.

• For example, you may have opened a file before going into a Try … Catch Statement. If an error occurs, the file will still be open. Whether an error occurs or not, you still need to close the file. You can do that in the Finally part.

Exception Handling

Page 32: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

Case Study: A Transaction-Processing Program

• Transaction-Processing Program– Achieve “instant access” processing

Page 33: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1 ' Fig. 17.18: CTransaction.vb

2 ' Handles record transactions.

3

4 ' Visual Basic namespaces

5 Imports System.IO

6 Imports System.Windows.Forms

7

8 ' Deitel namespaces

9 Imports BankLibrary

10

11 Public Class CTransaction

12

13 ' number of records to write to disk

14 Private Const NUMBER_OF_RECORDS As Integer = 100

15

16 ' stream through which data moves to and from file

17 Private file As FileStream

18

19 ' stream for reading bytes from file

20 Private binaryInput As BinaryReader

21

22 ' stream for writing bytes to file

23 Private binaryOutput As BinaryWriter

24

25 ' create/open file containing empty records

26 Public Sub OpenFile(ByVal fileName As String)

27

28 ' write empty records to file

29 Try

30

31 ' create FileStream from new file or existing file

32 file = New FileStream(fileName, FileMode.OpenOrCreate)

33

34 ' use FileStream for BinaryWriter to read bytes from file

35 binaryInput = New BinaryReader(file)

BinaryReader object created

Page 34: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

36 37 ' use FileStream for BinaryWriter to write bytes to file38 binaryOutput = New BinaryWriter(file)39 40 ' determine whether file has just been created41 If file.Length = 0 Then42 43 ' record to be written to file44 Dim blankRecord As CRandomAccessRecord = _45 New CRandomAccessRecord()46 47 Dim i As Integer ' counter48 49 ' new record can hold NUMBER_OF_RECORDS records50 file.SetLength( _51 CRandomAccessRecord.SIZE * NUMBER_OF_RECORDS)52 53 ' write blank records to file54 For i = 0 To NUMBER_OF_RECORDS - 155 56 ' move file-position pointer to next position57 file.Position = i * CRandomAccessRecord.SIZE58 59 ' write blank record to file60 binaryOutput.Write(blankRecord.Account)61 binaryOutput.Write(blankRecord.FirstName)62 binaryOutput.Write(blankRecord.LastName)63 binaryOutput.Write(blankRecord.Balance)64 Next65 66 End If67

BinaryWriter object created

Populate with empty records

Page 35: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

68 ' notify user of error during writing of blank records69 Catch fileException As IOException70 MessageBox.Show("Cannot create file", "Error", _71 MessageBoxButtons.OK, MessageBoxIcon.Error)72 73 End Try74 75 End Sub ' OpenFile76 77 ' retrieve record depending on whether account is valid78 Public Function GetRecord(ByVal accountValue As String) _79 As CRandomAccessRecord80 81 ' store file data associated with account in record82 Try83 84 ' record to store file data85 Dim record As CRandomAccessRecord = _86 New CRandomAccessRecord()87 88 ' get value from TextBox's account field89 Dim accountNumber As Integer = _90 Convert.ToInt32(accountValue)91 92 ' if account is invalid, do not read data93 If (accountNumber < 1 OrElse _94 accountNumber > NUMBER_OF_RECORDS) Then95 96 ' set record's account field with account number97 record.Account = accountNumber98

Instantiate object thatwill store the file data

Page 36: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

99 ' get data from file if account is valid100 Else101 102 ' locate position in file where record exists103 file.Seek( _104 (accountNumber - 1) * CRandomAccessRecord.SIZE, 0)105 106 ' read data from record107 record.Account = binaryInput.ReadInt32()108 record.FirstName = binaryInput.ReadString()109 record.LastName = binaryInput.ReadString()110 record.Balance = binaryInput.ReadDouble()111 End If112 113 Return record114 115 ' notify user of error during reading116 Catch fileException As IOException117 MessageBox.Show("Cannot read file", "Error", _118 MessageBoxButtons.OK, MessageBoxIcon.Error)119 120 ' notify user of error in parameter mismatch121 Catch formattingException As FormatException122 MessageBox.Show("Invalid Account", "Error", _123 MessageBoxButtons.OK, MessageBoxIcon.Error)124 125 End Try126 127 Return Nothing128 End Function ' GetRecord129 130 ' add record to file at position determined by accountNumber131 Public Function AddRecord(ByVal record As CRandomAccessRecord, _132 ByVal accountNumber As Integer) As Boolean133

Determines the position ofthe specified record in the file

Page 37: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

134 ' write record to file135 Try136 137 ' move file-position pointer to appropriate position138 file.Seek( _139 (accountNumber - 1) * CRandomAccessRecord.SIZE, 0)140 141 ' write data to file142 binaryOutput.Write(record.Account)143 binaryOutput.Write(record.FirstName)144 binaryOutput.Write(record.LastName)145 binaryOutput.Write(record.Balance)146 147 ' notify user if error occurs during writing148 Catch fileException As IOException149 MessageBox.Show("Error Writing To File", "Error", _150 MessageBoxButtons.OK, MessageBoxIcon.Error)151 152 Return False ' failure153 End Try154 155 Return True ' success156 End Sub ' AddRecord157 158 End Class ' CTransaction

Call the overloaded Write methods and write to the file

Page 38: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1 ' Fig. 17.19: TransactionProcessor.vb2 ' MDI parent for transaction-processor application.3 4 Imports System.Windows.Forms5 6 Public Class FrmTransactionProcessor7 Inherits Form8 9 ' Visual Studio .NET generated code10 11 ' reference to Multiple-Document-Interface client12 Private childForm As MdiClient13 14 ' reference to StartDialog15 Private startDialog As FrmStartDialog16 17 End Class ' FrmTransactionProcessor

Page 39: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1 ' Fig. 17.20: StartDialog.vb2 ' Initial dialog box displayed to user. Provides buttons for 3 ' creating/opening file and for adding, updating and removing 4 ' records from file.5 6 ' Visual Basic namespaces7 Imports System.Windows.Forms8 9 ' Deitel namespaces10 Imports BankLibrary11 12 Public Class FrmStartDialog13 Inherits Form14 15 ' buttons for displaying other dialogs16 Friend WithEvents cmdOpen As Button17 Friend WithEvents cmdNew As Button18 Friend WithEvents cmdUpdate As Button19 Friend WithEvents cmdDelete As Button20 21 ' Visual Studio .NET generated code22 23 ' reference to dialog box for adding record24 Private newDialog As FrmNewDialog25 26 ' reference to dialog box for updating record27 Private updateDialog As FrmUpdateDialog28 29 ' reference to dialog box for removing record30 Private deleteDialog As FrmDeleteDialog31 32 ' reference to object that handles transactions33 Private transactionProxy As CTransaction34

Open, New, Update and Delete Buttons

Page 40: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

35 ' invoked when user clicks New/Open File button36 Protected Sub cmdOpen_Click(ByVal sender As System.Object, _37 ByVal e As System.EventArgs) Handles cmdOpen.Click38 39 ' create dialog box enabling user to create or open file40 Dim fileChooser As OpenFileDialog = New OpenFileDialog()41 Dim result As DialogResult42 Dim fileName As String43 44 ' enable user to create file if file does not exist45 fileChooser.Title = "Create File / Open File"46 fileChooser.CheckFileExists = False47 48 result = fileChooser.ShowDialog() ' show dialog box to user49 50 ' exit event handler if user clicked Cancel51 If result = DialogResult.Cancel Then52 Return53 End If54 55 ' get file name from user56 fileName = fileChooser.FileName57 58 ' show error if user specified invalid file59 If (fileName = "" OrElse fileName = Nothing) Then60 MessageBox.Show("Invalid File Name", "Error", _61 MessageBoxButtons.OK, MessageBoxIcon.Error)62 63 ' open or create file if user specified valid file64 Else65 66 ' create CTransaction with specified file67 transactionProxy = New CTransaction()68 transactionProxy.OpenFile(fileName)69

User can create a file ifthe specified file does not exist

Exit event handler if the user clicks the Cancel button

Page 41: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

70 ' enable GUI buttons except for New/Open File button71 cmdNew.Enabled = True72 cmdUpdate.Enabled = True73 cmdDelete.Enabled = True74 cmdOpen.Enabled = False75 76 ' instantiate dialog box for creating records77 newDialog = New FrmNewDialog(transactionProxy, _78 AddressOf ShowStartDialog)79 80 ' instantiate dialog box for updating records81 updateDialog = New FrmUpdateDialog(transactionProxy, _82 AddressOf ShowStartDialog)83 84 ' instantiate dialog box for removing records85 deleteDialog = New FrmDeleteDialog(transactionProxy, _86 AddressOf ShowStartDialog)87 88 ' set StartDialog as MdiParent for dialog boxes89 newDialog.MdiParent = Me.MdiParent90 updateDialog.MdiParent = Me.MdiParent91 deleteDialog.MdiParent = Me.MdiParent92 End If93 94 End Sub ' cmdOpen_Click95 96 ' invoked when user clicks New Record button97 Protected Sub cmdNew_Click(ByVal sender As System.Object, _98 ByVal e As System.EventArgs) Handles cmdNew.Click99 100 Hide() ' hide StartDialog101 newDialog.Show() ' show NewDialog102 End Sub ' cmdNew_Click103

Serve as the child windows

Page 42: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

104 ' invoked when user clicks Update Record button105 Protected Sub cmdUpdate_Click(ByVal sender As System.Object, _106 ByVal e As System.EventArgs) Handles cmdUpdate.Click107 108 Hide() ' hide StartDialog109 updateDialog.Show() ' show UpdateDialog110 End Sub ' cmdUpdate_Click111 112 ' invoked when user clicks Delete Record button113 Protected Sub cmdDelete_Click(ByVal sender As System.Object, _114 ByVal e As System.EventArgs) Handles cmdDelete.Click115 116 Hide() ' hide StartDialog117 deleteDialog.Show() ' show DeleteDialog118 End Sub ' cmdDelete_Click119 120 ' displays StartDialog121 Protected Sub ShowStartDialog()122 Show()123 End Sub ' ShowStartDialog124 125 End Class ' FrmStartDialog

The delete dialog is displayed

Page 43: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.
Page 44: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.
Page 45: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1 ' Fig. 17.21: NewDialog.vb2 ' Enables user to insert new record into file.3 4 ' Visual Basic namespaces5 Imports System.Windows.Forms6 7 ' Deitel namespaces8 Imports BankLibrary9 10 Public Class FrmNewDialog11 Inherits FrmBankUI12 13 ' buttons for creating record and canceling action14 Friend WithEvents cmdSave As Button15 Friend WithEvents cmdCancel As Button16 17 ' Windows Form Designer generated code18 19 ' reference to object that handles transactions20 Private transactionProxy As CTransaction21 22 ' delegate for method that displays previous window23 Delegate Sub MyDelegate()24 Public showPreviousWindow As MyDelegate25 26 ' initialize components and set members to parameter values27 Public Sub New(ByVal transactionProxyValue As CTransaction, _28 ByVal delegateValue As MyDelegate)29 30 InitializeComponent()31 showPreviousWindow = delegateValue32 33 ' instantiate object that handles transactions34 transactionProxy = transactionProxyValue35 End Sub ' New

Page 46: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

36 37 ' invoked when user clicks Cancel button38 Protected Sub cmdCancel_Click(ByVal sender As System.Object, _39 ByVal e As System.EventArgs) Handles cmdCancel.Click40 41 Hide()42 ClearTextBoxes()43 showPreviousWindow()44 End Sub ' cmdCancel_Click45 46 ' invoked when user clicks Save As button47 Protected Sub cmdSave_Click(ByVal sender As System.Object, _48 ByVal e As System.EventArgs) Handles cmdSave.Click49 50 Dim record As CRandomAccessRecord = _51 transactionProxy.GetRecord( _52 GetTextBoxValues(TextBoxIndices.ACCOUNT))53 54 ' if record exists, add it to file55 If (record Is Nothing) = False Then56 InsertRecord(record)57 End If58 59 Hide()60 ClearTextBoxes()61 showPreviousWindow()62 End Sub ' cmdSave_Click63 64 ' insert record in file at position specified by accountNumber65 Private Sub InsertRecord(ByVal record As CRandomAccessRecord)66 67 ' store TextBox values in String array68 Dim textBoxValues As String() = GetTextBoxValues()69

Method GetRecord shouldreturn an empty CRandomAccessRecord

Method InsertRecord is called

Page 47: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

70 ' store TextBox account field71 Dim accountNumber As Integer = _72 Convert.ToInt32(textBoxValues(TextBoxIndices.ACCOUNT))73 74 ' notify user and return if record account is not empty75 If record.Account <> 0 Then76 MessageBox.Show( _77 "Record Already Exists or Invalid Number", "Error", _78 MessageBoxButtons.OK, MessageBoxIcon.Error)79 80 Return81 End If82 83 ' store values in record84 record.Account = accountNumber85 record.FirstName = textBoxValues(TextBoxIndices.FIRST)86 record.LastName = textBoxValues(TextBoxIndices.LAST)87 record.Balance = Convert.ToDouble( _88 textBoxValues(TextBoxIndices.BALANCE))89 90 ' add record to file91 Try92 93 If (transactionProxy.AddRecord( _94 record, accountNumber) = False ) Then95 96 Return ' if error97 End If98 99 ' notify user if error occurs in parameter mismatch100 Catch formattingException As FormatException101 MessageBox.Show("Invalid Balance", "Error", _102 MessageBoxButtons.OK, MessageBoxIcon.Error)103 104 End Try

A newly created CRandomAccessRecordis inserted into the file

Page 48: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

105 106 MessageBox.Show("Record Created", "Success", _107 MessageBoxButtons.OK, MessageBoxIcon.Information)108 End Sub ' InsertRecord109 110 End Class ' FrmNewDialog

Page 49: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

NewDialog.vb

Page 50: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1 ' Fig. 17.22: UpdateDialog.vb2 ' Enables user to update records in file.3 4 ' Visual Basic namespaces5 Imports System.Windows.Forms6 7 ' Deitel namespaces8 Imports BankLibrary9 10 Public Class FrmUpdateDialog11 Inherits FrmBankUI12 13 ' label and textbox for user to enter transaction data14 Friend WithEvents lblTransaction As Label15 Friend WithEvents txtTransaction As TextBox16 17 ' buttons for saving data to file and canceling save18 Friend WithEvents cmdSave As Button19 Friend WithEvents cmdCancel As Button20 21 ' Visual Studio .NET generated code22 23 ' reference to object that handles transactions24 Private transactionProxy As CTransaction25 26 ' delegate for method that displays previous window27 Delegate Sub MyDelegate()28 Public showPreviousWindow As MyDelegate29 30 ' initialize components and set members to parameter values31 Public Sub New(ByVal transactionProxyValue As CTransaction, _32 ByVal delegateValue As MyDelegate)33 34 InitializeComponent()35 showPreviousWindow = delegateValue

This method enables users toupdate existing records

Page 51: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

36 37 ' instantiate object that handles transactions38 transactionProxy = transactionProxyValue39 End Sub ' New40 41 ' invoked when user enters text in Account TextBox42 Protected Sub txtAccountNumber_KeyDown( _43 ByVal sender As System.Object, _44 ByVal e As System.Windows.Forms.KeyEventArgs) _45 Handles txtAccount.KeyDown46 47 ' determine whether user pressed Enter Key48 If e.KeyCode = Keys.Enter Then49 50 ' retrieve record associated with account from file51 Dim record As CRandomAccessRecord = _52 transactionProxy.GetRecord( _53 GetTextBoxValues(TextBoxIndices.ACCOUNT))54 55 ' return if record does not exist56 If (record Is Nothing) = True Then57 Return58 End If59 60 ' determine whether record is empty61 If record.Account <> 0 Then62 63 ' store record values in String array64 Dim values As String() = {record.Account.ToString(), _65 record.FirstName.ToString(), _66 record.LastName.ToString(), _67 record.Balance.ToString()}68

Method txtAccountNumbercalls method GetRecord

If record does existstore the values in an array

Page 52: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

69 ' copy String-array value to TextBox values70 SetTextBoxValues(values)71 txtTransaction.Text = "[Charge or Payment]"72 73 ' notify user if record does not exist74 Else75 MessageBox.Show("Record Does Not Exist", "Error", _76 MessageBoxButtons.OK, MessageBoxIcon.Error)77 78 End If79 80 End If81 82 End Sub ' txtAccountNumber_KeyDown83 84 ' invoked when user enters text in Transaction TextBox85 Protected Sub txtTransactionNumber_KeyDown( _86 ByVal sender As System.Object, _87 ByVal e As System.Windows.Forms.KeyEventArgs) _88 Handles txtTransaction.KeyDown89 90 ' determine whether user pressed Enter key91 If e.KeyCode = Keys.Enter Then92 93 ' calculate balance using Transaction TextBox value94 Try95 96 ' retrieve record associated with account from file97 Dim record As CRandomAccessRecord = _98 transactionProxy.GetRecord( _99 GetTextBoxValues(TextBoxIndices.ACCOUNT))100 101 ' get Transaction TextBox value102 Dim transactionValue As Double = _103 Convert.ToDouble(txtTransaction.Text)

Notify the user that the record does not exist

This method is invokedwhen the user enters text into

the Transaction textbox

Page 53: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

104 105 ' calculate new balance (old balance + transaction)106 Dim newBalance As Double = _107 record.Balance + transactionValue108 109 ' store record values in String array110 Dim values As String() = {record.Account.ToString(), _111 record.FirstName.ToString(), _112 record.LastName.ToString(), newBalance.ToString()}113 114 ' copy String-array value to TextBox values115 SetTextBoxValues(values)116 117 ' clear txtTransactionNumber118 txtTransaction.Text = ""119 120 ' notify user if error occurs in parameter mismatch121 Catch formattingException As FormatException122 MessageBox.Show("Invalid Transaction", "Error", _123 MessageBoxButtons.OK, MessageBoxIcon.Error)124 125 End Try126 127 End If128 129 End Sub ' txtTransactionNumber_KeyDown130 131 ' invoked when user clicks Save button132 Protected Sub cmdSave_Click(ByVal sender As System.Object, _133 ByVal e As System.EventArgs) Handles cmdSave.Click134 135 Dim record As CRandomAccessRecord = _136 transactionProxy.GetRecord( _137 GetTextBoxValues(TextBoxIndices.ACCOUNT))138

Page 54: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

139 ' if record exists, update in file140 If (record Is Nothing) = False Then141 UpdateRecord(record)142 End If143 144 Hide()145 ClearTextBoxes()146 showPreviousWindow()147 End Sub ' cmdSave_Click148 149 ' invoked when user clicks Cancel button150 Protected Sub cmdCancel_Click(ByVal sender As System.Object, _151 ByVal e As System.EventArgs) Handles cmdCancel.Click152 153 Hide()154 ClearTextBoxes()155 showPreviousWindow()156 End Sub ' cmdCancel_Click157 158 ' update record in file at position specified by accountNumber159 Public Sub UpdateRecord(ByVal record As CRandomAccessRecord)160 161 ' store TextBox values in record and write record to file162 Try163 Dim accountNumber As Integer = record.Account164 Dim values As String() = GetTextBoxValues()165 166 ' store values in record167 record.Account = accountNumber168 record.FirstName = values(TextBoxIndices.FIRST)169 record.LastName = values(TextBoxIndices.LAST)170 record.Balance = _171 Double.Parse(values(TextBoxIndices.BALANCE))172

Page 55: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

173 ' add record to file174 If (transactionProxy.AddRecord( _175 record, accountNumber) = False ) Then176 177 Return ' if error178 End If179 180 ' notify user if error occurs in parameter mismatch181 Catch formattingException As FormatException182 MessageBox.Show("Invalid Balance", "Error", _183 MessageBoxButtons.OK, MessageBoxIcon.Error)184 185 Return186 End Try187 188 MessageBox.Show("Record Updated", "Success", _189 MessageBoxButtons.OK, MessageBoxIcon.Information)190 End Sub ' UpdateRecord191 192 End Class ' FrmUpdateDialog

Page 56: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

UpdateDialog.vb

Page 57: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

1 ' Fig. 17.23: DeleteDialog.vb2 ' Enables user to delete records in file.3 4 ' Visual Basic namespaces5 Imports System.Windows.Forms6 7 ' Deitel namespaces8 Imports BankLibrary9 10 Public Class FrmDeleteDialog11 Inherits Form12 13 ' label and TextBox enabling user to input account number14 Friend WithEvents lblAccount As Label15 Friend WithEvents txtAccount As TextBox16 17 ' buttons for deleting record and canceling action18 Friend WithEvents cmdDelete As Button19 Friend WithEvents cmdCancel As Button20 21 ' Visual Studio .NET generated code22 23 ' reference to object that handles transactions24 Private transactionProxy As CTransaction25 26 ' delegate for method that displays previous window27 Delegate Sub MyDelegate()28 Public showPreviousWindow As MyDelegate29 30 ' initialize components and set members to parameter values31 Public Sub New(ByVal transactionProxyValue As CTransaction, _32 ByVal delegateValue As MyDelegate)33 34 InitializeComponent()35 showPreviousWindow = delegateValue

Page 58: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

DeleteDialog.vb

36 37 ' instantiate object that handles transactions38 transactionProxy = transactionProxyValue39 End Sub ' New40 41 ' invoked when user clicks Delete Record button42 Protected Sub cmdDelete_Click(ByVal sender As System.Object, _43 ByVal e As System.EventArgs) Handles cmdDelete.Click44 45 Dim record As CRandomAccessRecord = _46 transactionProxy.GetRecord(txtAccount.Text)47 48 ' if record exists, delete it in file49 If (record Is Nothing) = False Then50 DeleteRecord(record)51 End If52 53 Me.Hide()54 showPreviousWindow()55 End Sub ' cmdDelete_Click56 57 ' invoked when user clicks Cancel button58 Protected Sub cmdCancel_Click(ByVal sender As System.Object, _59 ByVal e As System.EventArgs) Handles cmdCancel.Click60 61 Me.Hide()62 showPreviousWindow()63 End Sub ' cmdCancel_Click64

cmdDelete_Click is invokedwhen the user clicks the

delete button

If the record existsmethod DeleteRecord is called

Page 59: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.

65 ' delete record in file at position specified by accountNumber66 Public Sub DeleteRecord(ByVal record As CRandomAccessRecord)67 68 Dim accountNumber As Integer = record.Account69 70 ' display error message if record does not exist71 If record.Account = 0 Then72 MessageBox.Show("Record Does Not Exist", "Error", _73 MessageBoxButtons.OK, MessageBoxIcon.Error)74 txtAccount.Clear()75 76 Return77 End If78 79 ' create blank record80 record = New CRandomAccessRecord()81 82 ' write over file record with empty record83 If (transactionProxy.AddRecord( _84 record, accountNumber) = True) Then85 86 ' notify user of successful deletion87 MessageBox.Show("Record Deleted", "Success", _88 MessageBoxButtons.OK, MessageBoxIcon.Information)89 Else90 91 ' notify user of failure92 MessageBox.Show("Record could not be deleted", "Error", _93 MessageBoxButtons.OK, MessageBoxIcon.Error)94 End If95 96 txtAccount.Clear() ' clear text box97 End Sub ' DeleteRecord98 99 End Class ' FrmDeleteDialog

Record is writtenover by an empty record

Page 60: Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File.