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

Slides:



Advertisements
Similar presentations
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Ticket Information Application.
Advertisements

Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
 2002 Prentice Hall. All rights reserved. 1 Chapter 17 – Files and Streams Outline 17.1 Introduction 17.2 Data Hierarchy 17.3 Files and Streams 17.4 Classes.
Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
 2002 Prentice Hall. All rights reserved. 1 Chapter 17 – Files and Streams Outline 17.1 Introduction 17.2 Data Hierarchy 17.3 Files and Streams 17.4 SKIPPED.
 2002 Prentice Hall. All rights reserved. 1 Chapter 17 – Files and Streams Outline ( 只教 17.1 至 17.6) 17.1Introduction 17.2 Data Hierarchy 17.3 Files and.
Macros Tutorial Week 20. Objectives By the end of this tutorial you should understand how to: Create macros Assign macros to events Associate macros with.
Creating Sequential-Access File  Serializable attribute indicates to the compiler that objects of a class can be serialized– written to or read from a.
Sequential-access file Create, read and write an object into a sequential-access file Serialize and deserialize the object to write and read from a data.
Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements.
Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
1 Graphical User Interfaces Part 2 Outline Multiple Document Interface (MDI) Windows Visual Inheritance User-Defined Controls.
1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
Database-Driven Web Sites, Second Edition1 Chapter 8 Processing ASP.NET Web Forms and Working With Server Controls.
Visual C Sharp – File I/O - 1 Variables and arrays only temporary - lost when a program terminates Files used for long term storage (Data bases considered.
CHAPTER SIX Reducing Program Complexity General Sub Procedures and Developer-defined Functions.
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Introduction to Visual Basic. Quick Links Windows Application Programming Event-Driven Application Becoming familiar with VB Control Objects Saving and.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
© Minder Chen, ASP.NET 2.0: Introduction - 1 ASP.NET 2.0 Minder Chen, Ph.D. Framework Base Class Library ADO.NET: Data & XML.
06/10/ Working with Data. 206/10/2015 Learning Objectives Explain the circumstances when the following might be useful: Disabling buttons and.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
File I/O 11_file_processing.ppt
 2006 Pearson Education, Inc. All rights reserved Files and Streams.
1 14/10/58Dr.Mud-Armeen Munlin 1 Files and Streams ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Ticket Information Application Introducing Sequential-Access Files.
11-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
 2002 Prentice Hall. All rights reserved. 1 Chapter 17 – Files and Streams Outline 17.1 Introduction 17.2 Data Hierarchy 17.3 Files and Streams 17.4 Classes.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
Introduction to Exception Handling and Defensive Programming.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Class Average Application Introducing the Do...Loop While and Do...Loop Until.
Applications Development
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
6c – Function Procedures Lingma Acheson Department of Computer and Information Science, IUPUI CSCI N331 VB.NET Programming.
To retrieve data sequentially from a file, programs normally start from the beginning of the file, reading data consecutively until the desired data are.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
CS 2340: Programming in VB Lab 2 Due 9 pm, Friday, September 14 1.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
Creating Menus Menu Bar – behaves like standard Windows menus Can be used in place of or in addition to buttons to execute a procedure Menu items are controls.
Chapter 21 – Files and Streams 1 Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Error Trapping Exception Catching 1. Syntax & Compile-time  VB – Editor/Compiler Logic and Design  You Runtime  You Types of Errors: 2 When your program.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
IMS 3253: Validation and Errors 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Validation and Error Handling Validation.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Object-Oriented Application Development Using VB.NET 1 Chapter 13 Introduction to Data Access Classes and Persistence.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the 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.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Chapter 11 – Exception Handling
A variable is a name for a value stored in memory.
Programming in visual basic .net Visual Basic Building Blocks
18 Files and Streams.
Exception Handling.
Files and Streams Lect3 CT1411.
Chapter 17 – Files and Streams
Exception Handling.
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

Files and Streams- II

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

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

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

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

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

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

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.

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

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

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

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

Binary serialization - Example

Files using File Dialogues Demo

Files using File Dialogues

1 2

1 2 3

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

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

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

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

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

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

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

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

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

1 ' Fig : 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 Public Class CTransaction ' number of records to write to disk 14 Private Const NUMBER_OF_RECORDS As Integer = ' stream through which data moves to and from file 17 Private file As FileStream ' stream for reading bytes from file 20 Private binaryInput As BinaryReader ' stream for writing bytes to file 23 Private binaryOutput As BinaryWriter ' create/open file containing empty records 26 Public Sub OpenFile(ByVal fileName As String) ' write empty records to file 29 Try ' create FileStream from new file or existing file 32 file = New FileStream(fileName, FileMode.OpenOrCreate) ' use FileStream for BinaryWriter to read bytes from file 35 binaryInput = New BinaryReader(file) BinaryReader object created

36 37 ' use FileStream for BinaryWriter to write bytes to file 38 binaryOutput = New BinaryWriter(file) ' determine whether file has just been created 41 If file.Length = 0 Then ' record to be written to file 44 Dim blankRecord As CRandomAccessRecord = _ 45 New CRandomAccessRecord() Dim i As Integer ' counter ' new record can hold NUMBER_OF_RECORDS records 50 file.SetLength( _ 51 CRandomAccessRecord.SIZE * NUMBER_OF_RECORDS) ' write blank records to file 54 For i = 0 To NUMBER_OF_RECORDS ' move file-position pointer to next position 57 file.Position = i * CRandomAccessRecord.SIZE ' 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 End If 67 BinaryWriter object created Populate with empty records

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) End Try End Sub ' OpenFile ' retrieve record depending on whether account is valid 78 Public Function GetRecord(ByVal accountValue As String) _ 79 As CRandomAccessRecord ' store file data associated with account in record 82 Try ' record to store file data 85 Dim record As CRandomAccessRecord = _ 86 New CRandomAccessRecord() ' get value from TextBox's account field 89 Dim accountNumber As Integer = _ 90 Convert.ToInt32(accountValue) ' if account is invalid, do not read data 93 If (accountNumber < 1 OrElse _ 94 accountNumber > NUMBER_OF_RECORDS) Then ' set record's account field with account number 97 record.Account = accountNumber 98 Instantiate object that will store the file data

99 ' get data from file if account is valid 100 Else ' locate position in file where record exists 103 file.Seek( _ 104 (accountNumber - 1) * CRandomAccessRecord.SIZE, 0) ' 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 Return record ' notify user of error during reading 116 Catch fileException As IOException 117 MessageBox.Show("Cannot read file", "Error", _ 118 MessageBoxButtons.OK, MessageBoxIcon.Error) ' notify user of error in parameter mismatch 121 Catch formattingException As FormatException 122 MessageBox.Show("Invalid Account", "Error", _ 123 MessageBoxButtons.OK, MessageBoxIcon.Error) End Try Return Nothing 128 End Function ' GetRecord ' 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

134 ' write record to file 135 Try ' move file-position pointer to appropriate position 138 file.Seek( _ 139 (accountNumber - 1) * CRandomAccessRecord.SIZE, 0) ' write data to file 142 binaryOutput.Write(record.Account) 143 binaryOutput.Write(record.FirstName) 144 binaryOutput.Write(record.LastName) 145 binaryOutput.Write(record.Balance) ' 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) Return False ' failure 153 End Try Return True ' success 156 End Sub ' AddRecord End Class ' CTransaction Call the overloaded Write methods and write to the file

1 ' Fig : 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 ' reference to Multiple-Document-Interface client 12 Private childForm As MdiClient ' reference to StartDialog 15 Private startDialog As FrmStartDialog End Class ' FrmTransactionProcessor

1 ' Fig : 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 Public Class FrmStartDialog 13 Inherits Form ' 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 ' Visual Studio.NET generated code ' reference to dialog box for adding record 24 Private newDialog As FrmNewDialog ' reference to dialog box for updating record 27 Private updateDialog As FrmUpdateDialog ' reference to dialog box for removing record 30 Private deleteDialog As FrmDeleteDialog ' reference to object that handles transactions 33 Private transactionProxy As CTransaction 34 Open, New, Update and Delete Buttons

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 ' 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 ' enable user to create file if file does not exist 45 fileChooser.Title = "Create File / Open File" 46 fileChooser.CheckFileExists = False result = fileChooser.ShowDialog() ' show dialog box to user ' exit event handler if user clicked Cancel 51 If result = DialogResult.Cancel Then 52 Return 53 End If ' get file name from user 56 fileName = fileChooser.FileName ' 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) ' open or create file if user specified valid file 64 Else ' 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

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 ' instantiate dialog box for creating records 77 newDialog = New FrmNewDialog(transactionProxy, _ 78 AddressOf ShowStartDialog) ' instantiate dialog box for updating records 81 updateDialog = New FrmUpdateDialog(transactionProxy, _ 82 AddressOf ShowStartDialog) ' instantiate dialog box for removing records 85 deleteDialog = New FrmDeleteDialog(transactionProxy, _ 86 AddressOf ShowStartDialog) ' 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 End Sub ' cmdOpen_Click ' 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 Hide() ' hide StartDialog 101 newDialog.Show() ' show NewDialog 102 End Sub ' cmdNew_Click 103 Serve as the child windows

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 Hide() ' hide StartDialog 109 updateDialog.Show() ' show UpdateDialog 110 End Sub ' cmdUpdate_Click ' 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 Hide() ' hide StartDialog 117 deleteDialog.Show() ' show DeleteDialog 118 End Sub ' cmdDelete_Click ' displays StartDialog 121 Protected Sub ShowStartDialog() 122 Show() 123 End Sub ' ShowStartDialog End Class ' FrmStartDialog The delete dialog is displayed

1 ' Fig : 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 ' buttons for creating record and canceling action 14 Friend WithEvents cmdSave As Button 15 Friend WithEvents cmdCancel As Button ' Windows Form Designer generated code ' reference to object that handles transactions 20 Private transactionProxy As CTransaction ' delegate for method that displays previous window 23 Delegate Sub MyDelegate() 24 Public showPreviousWindow As MyDelegate ' initialize components and set members to parameter values 27 Public Sub New(ByVal transactionProxyValue As CTransaction, _ 28 ByVal delegateValue As MyDelegate) InitializeComponent() 31 showPreviousWindow = delegateValue ' instantiate object that handles transactions 34 transactionProxy = transactionProxyValue 35 End Sub ' New

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 Hide() 42 ClearTextBoxes() 43 showPreviousWindow() 44 End Sub ' cmdCancel_Click ' 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 Dim record As CRandomAccessRecord = _ 51 transactionProxy.GetRecord( _ 52 GetTextBoxValues(TextBoxIndices.ACCOUNT)) ' if record exists, add it to file 55 If (record Is Nothing) = False Then 56 InsertRecord(record) 57 End If Hide() 60 ClearTextBoxes() 61 showPreviousWindow() 62 End Sub ' cmdSave_Click ' insert record in file at position specified by accountNumber 65 Private Sub InsertRecord(ByVal record As CRandomAccessRecord) ' store TextBox values in String array 68 Dim textBoxValues As String() = GetTextBoxValues() 69 Method GetRecord should return an empty CRandomAccessRecord Method InsertRecord is called

70 ' store TextBox account field 71 Dim accountNumber As Integer = _ 72 Convert.ToInt32(textBoxValues(TextBoxIndices.ACCOUNT)) ' 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) Return 81 End If ' 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)) ' add record to file 91 Try If (transactionProxy.AddRecord( _ 94 record, accountNumber) = False ) Then Return ' if error 97 End If ' notify user if error occurs in parameter mismatch 100 Catch formattingException As FormatException 101 MessageBox.Show("Invalid Balance", "Error", _ 102 MessageBoxButtons.OK, MessageBoxIcon.Error) End Try A newly created CRandomAccessRecord is inserted into the file

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

NewDialog.vb

1 ' Fig : 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 ' label and textbox for user to enter transaction data 14 Friend WithEvents lblTransaction As Label 15 Friend WithEvents txtTransaction As TextBox ' buttons for saving data to file and canceling save 18 Friend WithEvents cmdSave As Button 19 Friend WithEvents cmdCancel As Button ' Visual Studio.NET generated code ' reference to object that handles transactions 24 Private transactionProxy As CTransaction ' delegate for method that displays previous window 27 Delegate Sub MyDelegate() 28 Public showPreviousWindow As MyDelegate ' initialize components and set members to parameter values 31 Public Sub New(ByVal transactionProxyValue As CTransaction, _ 32 ByVal delegateValue As MyDelegate) InitializeComponent() 35 showPreviousWindow = delegateValue This method enables users to update existing records

36 37 ' instantiate object that handles transactions 38 transactionProxy = transactionProxyValue 39 End Sub ' New ' 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 ' determine whether user pressed Enter Key 48 If e.KeyCode = Keys.Enter Then ' retrieve record associated with account from file 51 Dim record As CRandomAccessRecord = _ 52 transactionProxy.GetRecord( _ 53 GetTextBoxValues(TextBoxIndices.ACCOUNT)) ' return if record does not exist 56 If (record Is Nothing) = True Then 57 Return 58 End If ' determine whether record is empty 61 If record.Account <> 0 Then ' 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

69 ' copy String-array value to TextBox values 70 SetTextBoxValues(values) 71 txtTransaction.Text = "[Charge or Payment]" ' notify user if record does not exist 74 Else 75 MessageBox.Show("Record Does Not Exist", "Error", _ 76 MessageBoxButtons.OK, MessageBoxIcon.Error) End If End If End Sub ' txtAccountNumber_KeyDown ' 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 ' determine whether user pressed Enter key 91 If e.KeyCode = Keys.Enter Then ' calculate balance using Transaction TextBox value 94 Try ' retrieve record associated with account from file 97 Dim record As CRandomAccessRecord = _ 98 transactionProxy.GetRecord( _ 99 GetTextBoxValues(TextBoxIndices.ACCOUNT)) ' 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

' calculate new balance (old balance + transaction) 106 Dim newBalance As Double = _ 107 record.Balance + transactionValue ' store record values in String array 110 Dim values As String() = {record.Account.ToString(), _ 111 record.FirstName.ToString(), _ 112 record.LastName.ToString(), newBalance.ToString()} ' copy String-array value to TextBox values 115 SetTextBoxValues(values) ' clear txtTransactionNumber 118 txtTransaction.Text = "" ' notify user if error occurs in parameter mismatch 121 Catch formattingException As FormatException 122 MessageBox.Show("Invalid Transaction", "Error", _ 123 MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End If End Sub ' txtTransactionNumber_KeyDown ' 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 Dim record As CRandomAccessRecord = _ 136 transactionProxy.GetRecord( _ 137 GetTextBoxValues(TextBoxIndices.ACCOUNT)) 138

139 ' if record exists, update in file 140 If (record Is Nothing) = False Then 141 UpdateRecord(record) 142 End If Hide() 145 ClearTextBoxes() 146 showPreviousWindow() 147 End Sub ' cmdSave_Click ' 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 Hide() 154 ClearTextBoxes() 155 showPreviousWindow() 156 End Sub ' cmdCancel_Click ' update record in file at position specified by accountNumber 159 Public Sub UpdateRecord(ByVal record As CRandomAccessRecord) ' 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() ' 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

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

UpdateDialog.vb

1 ' Fig : 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 ' label and TextBox enabling user to input account number 14 Friend WithEvents lblAccount As Label 15 Friend WithEvents txtAccount As TextBox ' buttons for deleting record and canceling action 18 Friend WithEvents cmdDelete As Button 19 Friend WithEvents cmdCancel As Button ' Visual Studio.NET generated code ' reference to object that handles transactions 24 Private transactionProxy As CTransaction ' delegate for method that displays previous window 27 Delegate Sub MyDelegate() 28 Public showPreviousWindow As MyDelegate ' initialize components and set members to parameter values 31 Public Sub New(ByVal transactionProxyValue As CTransaction, _ 32 ByVal delegateValue As MyDelegate) InitializeComponent() 35 showPreviousWindow = delegateValue

DeleteDialog.vb ' instantiate object that handles transactions 38 transactionProxy = transactionProxyValue 39 End Sub ' New ' 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 Dim record As CRandomAccessRecord = _ 46 transactionProxy.GetRecord(txtAccount.Text) ' if record exists, delete it in file 49 If (record Is Nothing) = False Then 50 DeleteRecord(record) 51 End If Me.Hide() 54 showPreviousWindow() 55 End Sub ' cmdDelete_Click ' 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 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

65 ' delete record in file at position specified by accountNumber 66 Public Sub DeleteRecord(ByVal record As CRandomAccessRecord) Dim accountNumber As Integer = record.Account ' 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() Return 77 End If ' create blank record 80 record = New CRandomAccessRecord() ' write over file record with empty record 83 If (transactionProxy.AddRecord( _ 84 record, accountNumber) = True) Then ' notify user of successful deletion 87 MessageBox.Show("Record Deleted", "Success", _ 88 MessageBoxButtons.OK, MessageBoxIcon.Information) 89 Else ' notify user of failure 92 MessageBox.Show("Record could not be deleted", "Error", _ 93 MessageBoxButtons.OK, MessageBoxIcon.Error) 94 End If txtAccount.Clear() ' clear text box 97 End Sub ' DeleteRecord End Class ' FrmDeleteDialog Record is written over by an empty record