Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File."— Presentation transcript:

1 Files and Streams- II

2 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

3 Public Class myCar Public Make As String Public Model As String Public Year As Integer End Class Dim car1 = New myCar car1.Make = "Honda" car1.Model = "Accord“ car1.Year = 1990 How can we save car1 object to a file? Serialization

4 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

5 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

6 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

7 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

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

9 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

10 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 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

11 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

12 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

13 Binary serialization - Example

14

15

16

17 Files using File Dialogues Demo

18 Files using File Dialogues

19

20 1 2

21

22 1 2 3

23

24 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

25 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

26 fs = new FileStream(FileName, FileMode.Open, FileAccess.Read) FileName = “C:\test10.txt”

27 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

28 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

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

30 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

31 There is one last part of the Try … Catch Statement that VB.NET doesn’t add for you  Finally: Try Catch ex As Exception Finally End 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

32 Case Study: A Transaction- Processing Program Transaction-Processing Program – Achieve “instant access” processing

33 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

34 36 37 ' use FileStream for BinaryWriter to write bytes to file 38 binaryOutput = New BinaryWriter(file) 39 40 ' determine whether file has just been created 41 If file.Length = 0 Then 42 43 ' record to be written to file 44 Dim blankRecord As CRandomAccessRecord = _ 45 New CRandomAccessRecord() 46 47 Dim i As Integer ' counter 48 49 ' new record can hold NUMBER_OF_RECORDS records 50 file.SetLength( _ 51 CRandomAccessRecord.SIZE * NUMBER_OF_RECORDS) 52 53 ' write blank records to file 54 For i = 0 To NUMBER_OF_RECORDS - 1 55 56 ' move file-position pointer to next position 57 file.Position = i * CRandomAccessRecord.SIZE 58 59 ' write blank record to file 60 binaryOutput.Write(blankRecord.Account) 61 binaryOutput.Write(blankRecord.FirstName) 62 binaryOutput.Write(blankRecord.LastName) 63 binaryOutput.Write(blankRecord.Balance) 64 Next 65 66 End If 67 BinaryWriter object created Populate with empty records

35 68 ' notify user of error during writing of blank records 69 Catch fileException As IOException 70 MessageBox.Show("Cannot create file", "Error", _ 71 MessageBoxButtons.OK, MessageBoxIcon.Error) 72 73 End Try 74 75 End Sub ' OpenFile 76 77 ' retrieve record depending on whether account is valid 78 Public Function GetRecord(ByVal accountValue As String) _ 79 As CRandomAccessRecord 80 81 ' store file data associated with account in record 82 Try 83 84 ' record to store file data 85 Dim record As CRandomAccessRecord = _ 86 New CRandomAccessRecord() 87 88 ' get value from TextBox's account field 89 Dim accountNumber As Integer = _ 90 Convert.ToInt32(accountValue) 91 92 ' if account is invalid, do not read data 93 If (accountNumber < 1 OrElse _ 94 accountNumber > NUMBER_OF_RECORDS) Then 95 96 ' set record's account field with account number 97 record.Account = accountNumber 98 Instantiate object that will store the file data

36 99 ' get data from file if account is valid 100 Else 101 102 ' locate position in file where record exists 103 file.Seek( _ 104 (accountNumber - 1) * CRandomAccessRecord.SIZE, 0) 105 106 ' read data from record 107 record.Account = binaryInput.ReadInt32() 108 record.FirstName = binaryInput.ReadString() 109 record.LastName = binaryInput.ReadString() 110 record.Balance = binaryInput.ReadDouble() 111 End If 112 113 Return record 114 115 ' notify user of error during reading 116 Catch fileException As IOException 117 MessageBox.Show("Cannot read file", "Error", _ 118 MessageBoxButtons.OK, MessageBoxIcon.Error) 119 120 ' notify user of error in parameter mismatch 121 Catch formattingException As FormatException 122 MessageBox.Show("Invalid Account", "Error", _ 123 MessageBoxButtons.OK, MessageBoxIcon.Error) 124 125 End Try 126 127 Return Nothing 128 End Function ' GetRecord 129 130 ' add record to file at position determined by accountNumber 131 Public Function AddRecord(ByVal record As CRandomAccessRecord, _ 132 ByVal accountNumber As Integer) As Boolean 133 Determines the position of the specified record in the file

37 134 ' write record to file 135 Try 136 137 ' move file-position pointer to appropriate position 138 file.Seek( _ 139 (accountNumber - 1) * CRandomAccessRecord.SIZE, 0) 140 141 ' write data to file 142 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 writing 148 Catch fileException As IOException 149 MessageBox.Show("Error Writing To File", "Error", _ 150 MessageBoxButtons.OK, MessageBoxIcon.Error) 151 152 Return False ' failure 153 End Try 154 155 Return True ' success 156 End Sub ' AddRecord 157 158 End Class ' CTransaction Call the overloaded Write methods and write to the file

38 1 ' Fig. 17.19: TransactionProcessor.vb 2 ' MDI parent for transaction-processor application. 3 4 Imports System.Windows.Forms 5 6 Public Class FrmTransactionProcessor 7 Inherits Form 8 9 ' Visual Studio.NET generated code 10 11 ' reference to Multiple-Document-Interface client 12 Private childForm As MdiClient 13 14 ' reference to StartDialog 15 Private startDialog As FrmStartDialog 16 17 End Class ' FrmTransactionProcessor

39 1 ' Fig. 17.20: StartDialog.vb 2 ' 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 namespaces 7 Imports System.Windows.Forms 8 9 ' Deitel namespaces 10 Imports BankLibrary 11 12 Public Class FrmStartDialog 13 Inherits Form 14 15 ' buttons for displaying other dialogs 16 Friend WithEvents cmdOpen As Button 17 Friend WithEvents cmdNew As Button 18 Friend WithEvents cmdUpdate As Button 19 Friend WithEvents cmdDelete As Button 20 21 ' Visual Studio.NET generated code 22 23 ' reference to dialog box for adding record 24 Private newDialog As FrmNewDialog 25 26 ' reference to dialog box for updating record 27 Private updateDialog As FrmUpdateDialog 28 29 ' reference to dialog box for removing record 30 Private deleteDialog As FrmDeleteDialog 31 32 ' reference to object that handles transactions 33 Private transactionProxy As CTransaction 34 Open, New, Update and Delete Buttons

40 35 ' invoked when user clicks New/Open File button 36 Protected Sub cmdOpen_Click(ByVal sender As System.Object, _ 37 ByVal e As System.EventArgs) Handles cmdOpen.Click 38 39 ' create dialog box enabling user to create or open file 40 Dim fileChooser As OpenFileDialog = New OpenFileDialog() 41 Dim result As DialogResult 42 Dim fileName As String 43 44 ' enable user to create file if file does not exist 45 fileChooser.Title = "Create File / Open File" 46 fileChooser.CheckFileExists = False 47 48 result = fileChooser.ShowDialog() ' show dialog box to user 49 50 ' exit event handler if user clicked Cancel 51 If result = DialogResult.Cancel Then 52 Return 53 End If 54 55 ' get file name from user 56 fileName = fileChooser.FileName 57 58 ' show error if user specified invalid file 59 If (fileName = "" OrElse fileName = Nothing) Then 60 MessageBox.Show("Invalid File Name", "Error", _ 61 MessageBoxButtons.OK, MessageBoxIcon.Error) 62 63 ' open or create file if user specified valid file 64 Else 65 66 ' create CTransaction with specified file 67 transactionProxy = New CTransaction() 68 transactionProxy.OpenFile(fileName) 69 User can create a file if the specified file does not exist Exit event handler if the user clicks the Cancel button

41 70 ' enable GUI buttons except for New/Open File button 71 cmdNew.Enabled = True 72 cmdUpdate.Enabled = True 73 cmdDelete.Enabled = True 74 cmdOpen.Enabled = False 75 76 ' instantiate dialog box for creating records 77 newDialog = New FrmNewDialog(transactionProxy, _ 78 AddressOf ShowStartDialog) 79 80 ' instantiate dialog box for updating records 81 updateDialog = New FrmUpdateDialog(transactionProxy, _ 82 AddressOf ShowStartDialog) 83 84 ' instantiate dialog box for removing records 85 deleteDialog = New FrmDeleteDialog(transactionProxy, _ 86 AddressOf ShowStartDialog) 87 88 ' set StartDialog as MdiParent for dialog boxes 89 newDialog.MdiParent = Me.MdiParent 90 updateDialog.MdiParent = Me.MdiParent 91 deleteDialog.MdiParent = Me.MdiParent 92 End If 93 94 End Sub ' cmdOpen_Click 95 96 ' invoked when user clicks New Record button 97 Protected Sub cmdNew_Click(ByVal sender As System.Object, _ 98 ByVal e As System.EventArgs) Handles cmdNew.Click 99 100 Hide() ' hide StartDialog 101 newDialog.Show() ' show NewDialog 102 End Sub ' cmdNew_Click 103 Serve as the child windows

42 104 ' invoked when user clicks Update Record button 105 Protected Sub cmdUpdate_Click(ByVal sender As System.Object, _ 106 ByVal e As System.EventArgs) Handles cmdUpdate.Click 107 108 Hide() ' hide StartDialog 109 updateDialog.Show() ' show UpdateDialog 110 End Sub ' cmdUpdate_Click 111 112 ' invoked when user clicks Delete Record button 113 Protected Sub cmdDelete_Click(ByVal sender As System.Object, _ 114 ByVal e As System.EventArgs) Handles cmdDelete.Click 115 116 Hide() ' hide StartDialog 117 deleteDialog.Show() ' show DeleteDialog 118 End Sub ' cmdDelete_Click 119 120 ' displays StartDialog 121 Protected Sub ShowStartDialog() 122 Show() 123 End Sub ' ShowStartDialog 124 125 End Class ' FrmStartDialog The delete dialog is displayed

43

44

45 1 ' Fig. 17.21: NewDialog.vb 2 ' Enables user to insert new record into file. 3 4 ' Visual Basic namespaces 5 Imports System.Windows.Forms 6 7 ' Deitel namespaces 8 Imports BankLibrary 9 10 Public Class FrmNewDialog 11 Inherits FrmBankUI 12 13 ' buttons for creating record and canceling action 14 Friend WithEvents cmdSave As Button 15 Friend WithEvents cmdCancel As Button 16 17 ' Windows Form Designer generated code 18 19 ' reference to object that handles transactions 20 Private transactionProxy As CTransaction 21 22 ' delegate for method that displays previous window 23 Delegate Sub MyDelegate() 24 Public showPreviousWindow As MyDelegate 25 26 ' initialize components and set members to parameter values 27 Public Sub New(ByVal transactionProxyValue As CTransaction, _ 28 ByVal delegateValue As MyDelegate) 29 30 InitializeComponent() 31 showPreviousWindow = delegateValue 32 33 ' instantiate object that handles transactions 34 transactionProxy = transactionProxyValue 35 End Sub ' New

46 36 37 ' invoked when user clicks Cancel button 38 Protected Sub cmdCancel_Click(ByVal sender As System.Object, _ 39 ByVal e As System.EventArgs) Handles cmdCancel.Click 40 41 Hide() 42 ClearTextBoxes() 43 showPreviousWindow() 44 End Sub ' cmdCancel_Click 45 46 ' invoked when user clicks Save As button 47 Protected Sub cmdSave_Click(ByVal sender As System.Object, _ 48 ByVal e As System.EventArgs) Handles cmdSave.Click 49 50 Dim record As CRandomAccessRecord = _ 51 transactionProxy.GetRecord( _ 52 GetTextBoxValues(TextBoxIndices.ACCOUNT)) 53 54 ' if record exists, add it to file 55 If (record Is Nothing) = False Then 56 InsertRecord(record) 57 End If 58 59 Hide() 60 ClearTextBoxes() 61 showPreviousWindow() 62 End Sub ' cmdSave_Click 63 64 ' insert record in file at position specified by accountNumber 65 Private Sub InsertRecord(ByVal record As CRandomAccessRecord) 66 67 ' store TextBox values in String array 68 Dim textBoxValues As String() = GetTextBoxValues() 69 Method GetRecord should return an empty CRandomAccessRecord Method InsertRecord is called

47 70 ' store TextBox account field 71 Dim accountNumber As Integer = _ 72 Convert.ToInt32(textBoxValues(TextBoxIndices.ACCOUNT)) 73 74 ' notify user and return if record account is not empty 75 If record.Account <> 0 Then 76 MessageBox.Show( _ 77 "Record Already Exists or Invalid Number", "Error", _ 78 MessageBoxButtons.OK, MessageBoxIcon.Error) 79 80 Return 81 End If 82 83 ' store values in record 84 record.Account = accountNumber 85 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 file 91 Try 92 93 If (transactionProxy.AddRecord( _ 94 record, accountNumber) = False ) Then 95 96 Return ' if error 97 End If 98 99 ' notify user if error occurs in parameter mismatch 100 Catch formattingException As FormatException 101 MessageBox.Show("Invalid Balance", "Error", _ 102 MessageBoxButtons.OK, MessageBoxIcon.Error) 103 104 End Try A newly created CRandomAccessRecord is inserted into the file

48 105 106 MessageBox.Show("Record Created", "Success", _ 107 MessageBoxButtons.OK, MessageBoxIcon.Information) 108 End Sub ' InsertRecord 109 110 End Class ' FrmNewDialog

49 NewDialog.vb

50 1 ' Fig. 17.22: UpdateDialog.vb 2 ' Enables user to update records in file. 3 4 ' Visual Basic namespaces 5 Imports System.Windows.Forms 6 7 ' Deitel namespaces 8 Imports BankLibrary 9 10 Public Class FrmUpdateDialog 11 Inherits FrmBankUI 12 13 ' label and textbox for user to enter transaction data 14 Friend WithEvents lblTransaction As Label 15 Friend WithEvents txtTransaction As TextBox 16 17 ' buttons for saving data to file and canceling save 18 Friend WithEvents cmdSave As Button 19 Friend WithEvents cmdCancel As Button 20 21 ' Visual Studio.NET generated code 22 23 ' reference to object that handles transactions 24 Private transactionProxy As CTransaction 25 26 ' delegate for method that displays previous window 27 Delegate Sub MyDelegate() 28 Public showPreviousWindow As MyDelegate 29 30 ' initialize components and set members to parameter values 31 Public Sub New(ByVal transactionProxyValue As CTransaction, _ 32 ByVal delegateValue As MyDelegate) 33 34 InitializeComponent() 35 showPreviousWindow = delegateValue This method enables users to update existing records

51 36 37 ' instantiate object that handles transactions 38 transactionProxy = transactionProxyValue 39 End Sub ' New 40 41 ' invoked when user enters text in Account TextBox 42 Protected Sub txtAccountNumber_KeyDown( _ 43 ByVal sender As System.Object, _ 44 ByVal e As System.Windows.Forms.KeyEventArgs) _ 45 Handles txtAccount.KeyDown 46 47 ' determine whether user pressed Enter Key 48 If e.KeyCode = Keys.Enter Then 49 50 ' retrieve record associated with account from file 51 Dim record As CRandomAccessRecord = _ 52 transactionProxy.GetRecord( _ 53 GetTextBoxValues(TextBoxIndices.ACCOUNT)) 54 55 ' return if record does not exist 56 If (record Is Nothing) = True Then 57 Return 58 End If 59 60 ' determine whether record is empty 61 If record.Account <> 0 Then 62 63 ' store record values in String array 64 Dim values As String() = {record.Account.ToString(), _ 65 record.FirstName.ToString(), _ 66 record.LastName.ToString(), _ 67 record.Balance.ToString()} 68 Method txtAccountNumber calls method GetRecord If record does exist store the values in an array

52 69 ' copy String-array value to TextBox values 70 SetTextBoxValues(values) 71 txtTransaction.Text = "[Charge or Payment]" 72 73 ' notify user if record does not exist 74 Else 75 MessageBox.Show("Record Does Not Exist", "Error", _ 76 MessageBoxButtons.OK, MessageBoxIcon.Error) 77 78 End If 79 80 End If 81 82 End Sub ' txtAccountNumber_KeyDown 83 84 ' invoked when user enters text in Transaction TextBox 85 Protected Sub txtTransactionNumber_KeyDown( _ 86 ByVal sender As System.Object, _ 87 ByVal e As System.Windows.Forms.KeyEventArgs) _ 88 Handles txtTransaction.KeyDown 89 90 ' determine whether user pressed Enter key 91 If e.KeyCode = Keys.Enter Then 92 93 ' calculate balance using Transaction TextBox value 94 Try 95 96 ' retrieve record associated with account from file 97 Dim record As CRandomAccessRecord = _ 98 transactionProxy.GetRecord( _ 99 GetTextBoxValues(TextBoxIndices.ACCOUNT)) 100 101 ' get Transaction TextBox value 102 Dim transactionValue As Double = _ 103 Convert.ToDouble(txtTransaction.Text) Notify the user that the record does not exist This method is invoked when the user enters text into the Transaction textbox

53 104 105 ' calculate new balance (old balance + transaction) 106 Dim newBalance As Double = _ 107 record.Balance + transactionValue 108 109 ' store record values in String array 110 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 values 115 SetTextBoxValues(values) 116 117 ' clear txtTransactionNumber 118 txtTransaction.Text = "" 119 120 ' notify user if error occurs in parameter mismatch 121 Catch formattingException As FormatException 122 MessageBox.Show("Invalid Transaction", "Error", _ 123 MessageBoxButtons.OK, MessageBoxIcon.Error) 124 125 End Try 126 127 End If 128 129 End Sub ' txtTransactionNumber_KeyDown 130 131 ' invoked when user clicks Save button 132 Protected Sub cmdSave_Click(ByVal sender As System.Object, _ 133 ByVal e As System.EventArgs) Handles cmdSave.Click 134 135 Dim record As CRandomAccessRecord = _ 136 transactionProxy.GetRecord( _ 137 GetTextBoxValues(TextBoxIndices.ACCOUNT)) 138

54 139 ' if record exists, update in file 140 If (record Is Nothing) = False Then 141 UpdateRecord(record) 142 End If 143 144 Hide() 145 ClearTextBoxes() 146 showPreviousWindow() 147 End Sub ' cmdSave_Click 148 149 ' invoked when user clicks Cancel button 150 Protected Sub cmdCancel_Click(ByVal sender As System.Object, _ 151 ByVal e As System.EventArgs) Handles cmdCancel.Click 152 153 Hide() 154 ClearTextBoxes() 155 showPreviousWindow() 156 End Sub ' cmdCancel_Click 157 158 ' update record in file at position specified by accountNumber 159 Public Sub UpdateRecord(ByVal record As CRandomAccessRecord) 160 161 ' store TextBox values in record and write record to file 162 Try 163 Dim accountNumber As Integer = record.Account 164 Dim values As String() = GetTextBoxValues() 165 166 ' store values in record 167 record.Account = accountNumber 168 record.FirstName = values(TextBoxIndices.FIRST) 169 record.LastName = values(TextBoxIndices.LAST) 170 record.Balance = _ 171 Double.Parse(values(TextBoxIndices.BALANCE)) 172

55 173 ' add record to file 174 If (transactionProxy.AddRecord( _ 175 record, accountNumber) = False ) Then 176 177 Return ' if error 178 End If 179 180 ' notify user if error occurs in parameter mismatch 181 Catch formattingException As FormatException 182 MessageBox.Show("Invalid Balance", "Error", _ 183 MessageBoxButtons.OK, MessageBoxIcon.Error) 184 185 Return 186 End Try 187 188 MessageBox.Show("Record Updated", "Success", _ 189 MessageBoxButtons.OK, MessageBoxIcon.Information) 190 End Sub ' UpdateRecord 191 192 End Class ' FrmUpdateDialog

56 UpdateDialog.vb

57 1 ' Fig. 17.23: DeleteDialog.vb 2 ' Enables user to delete records in file. 3 4 ' Visual Basic namespaces 5 Imports System.Windows.Forms 6 7 ' Deitel namespaces 8 Imports BankLibrary 9 10 Public Class FrmDeleteDialog 11 Inherits Form 12 13 ' label and TextBox enabling user to input account number 14 Friend WithEvents lblAccount As Label 15 Friend WithEvents txtAccount As TextBox 16 17 ' buttons for deleting record and canceling action 18 Friend WithEvents cmdDelete As Button 19 Friend WithEvents cmdCancel As Button 20 21 ' Visual Studio.NET generated code 22 23 ' reference to object that handles transactions 24 Private transactionProxy As CTransaction 25 26 ' delegate for method that displays previous window 27 Delegate Sub MyDelegate() 28 Public showPreviousWindow As MyDelegate 29 30 ' initialize components and set members to parameter values 31 Public Sub New(ByVal transactionProxyValue As CTransaction, _ 32 ByVal delegateValue As MyDelegate) 33 34 InitializeComponent() 35 showPreviousWindow = delegateValue

58 DeleteDialog.vb 36 37 ' instantiate object that handles transactions 38 transactionProxy = transactionProxyValue 39 End Sub ' New 40 41 ' invoked when user clicks Delete Record button 42 Protected Sub cmdDelete_Click(ByVal sender As System.Object, _ 43 ByVal e As System.EventArgs) Handles cmdDelete.Click 44 45 Dim record As CRandomAccessRecord = _ 46 transactionProxy.GetRecord(txtAccount.Text) 47 48 ' if record exists, delete it in file 49 If (record Is Nothing) = False Then 50 DeleteRecord(record) 51 End If 52 53 Me.Hide() 54 showPreviousWindow() 55 End Sub ' cmdDelete_Click 56 57 ' invoked when user clicks Cancel button 58 Protected Sub cmdCancel_Click(ByVal sender As System.Object, _ 59 ByVal e As System.EventArgs) Handles cmdCancel.Click 60 61 Me.Hide() 62 showPreviousWindow() 63 End Sub ' cmdCancel_Click 64 cmdDelete_Click is invoked when the user clicks the delete button If the record exists method DeleteRecord is called

59 65 ' delete record in file at position specified by accountNumber 66 Public Sub DeleteRecord(ByVal record As CRandomAccessRecord) 67 68 Dim accountNumber As Integer = record.Account 69 70 ' display error message if record does not exist 71 If record.Account = 0 Then 72 MessageBox.Show("Record Does Not Exist", "Error", _ 73 MessageBoxButtons.OK, MessageBoxIcon.Error) 74 txtAccount.Clear() 75 76 Return 77 End If 78 79 ' create blank record 80 record = New CRandomAccessRecord() 81 82 ' write over file record with empty record 83 If (transactionProxy.AddRecord( _ 84 record, accountNumber) = True) Then 85 86 ' notify user of successful deletion 87 MessageBox.Show("Record Deleted", "Success", _ 88 MessageBoxButtons.OK, MessageBoxIcon.Information) 89 Else 90 91 ' notify user of failure 92 MessageBox.Show("Record could not be deleted", "Error", _ 93 MessageBoxButtons.OK, MessageBoxIcon.Error) 94 End If 95 96 txtAccount.Clear() ' clear text box 97 End Sub ' DeleteRecord 98 99 End Class ' FrmDeleteDialog Record is written over by an empty record

60


Download ppt "Files and Streams- II. Outline Introduction Data Hierarchy Files and Streams Creating a Sequential-Access File Reading Data from a Sequential-Access File."

Similar presentations


Ads by Google