Presentation is loading. Please wait.

Presentation is loading. Please wait.

T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 23 Ticket Information Application Introducing Sequential-Access Files.

Similar presentations


Presentation on theme: "T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 23 Ticket Information Application Introducing Sequential-Access Files."— Presentation transcript:

1 T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 23 Ticket Information Application Introducing Sequential-Access Files

2  2009 Pearson Education, Inc. All rights reserved. 2 Outline 23.1 Test-Driving the Ticket Information Application 23.2 Data Hierarchy 23.3 Files and Streams 23.4 Writing to a File—Creating the Write Event Application 23.5 Building the Ticket Information Application 23.6 Using LINQ and Class File to Extract Data from a Text File

3  2009 Pearson Education, Inc. All rights reserved. 3 In this tutorial you will learn: ■Create, read from, write to and update files. ■Understand a computer ’ s data hierarchy. ■Become familiar with sequential-access file processing. ■Use StreamReader and StreamWriter classes to read from, and write to, sequential-access files. ■Use the OpenFileDialog component. ■Add and configure a MonthCalendar control. ■Use LINQ to query a sequential-access file. Objectives

4  2009 Pearson Education, Inc. All rights reserved. 4 ■A file is a collection of data that is given a name, such as data.txt or Welcome.sln. ■Data in files exists even after the application that created the data terminates—such data is called persistent data. ■Sequential-access files contain information that is read from a file in the order in which it was originally written to the file. ■This application allows the user to create or open a text file with information. Introduction

5 Application Requirements  2009 Pearson Education, Inc. All rights reserved. 5 23.1 Test-Driving the Ticket Information Application A local town has asked you to write an application that allows its residents to view community events for the current month. When the user selects a date, the application must indicate whether there are events scheduled for that day. The application must list the scheduled events and allow the user to select one. When the user selects an event, the application must display its time and price and a brief description of the event. The community-event information is stored in a sequential-access file named calendar.txt.

6  2009 Pearson Education, Inc. All rights reserved. 6 ■Run the completed Ticket Information application (Fig. 23.1). ■The MonthCalendar control should show the day and month on which you actually run the application. Test-Driving the Ticket Information Application Figure 23.1 | Ticket Information application’s GUI. Arrow buttons allow user to scroll through months MonthCalendar control ComboBox lists any events TextBox displays event details

7  2009 Pearson Education, Inc. All rights reserved. 7 ■Select the 13th in the MonthCalendar. Note that the ComboBox displays "- No Events -" (Fig. 23.2). ■Select the 19th. Click the ComboBox to view the scheduled events, then select an event to view its information. Test-Driving the Ticket Information Application (Cont.) Figure 23.2 | Ticket Information application displaying event information. 13th day of the month selected No events displayed 19th day of the month selected Event information displayed

8  2009 Pearson Education, Inc. All rights reserved. 8 ■Data items processed by computers form a data hierarchy (Fig. 23.3). ■Digits, letters and special symbols are referred to as characters. ■The set of all characters representing data items on a particular computer is called that computer’s character set. 23.2 Data Hierarchy

9  2009 Pearson Education, Inc. All rights reserved. 9 Figure 23.3 | Data hierarchy. 23.2 Data Hierarchy (Cont.)

10  2009 Pearson Education, Inc. All rights reserved. 10 ■The smallest data item is called a bit—a digit that can hold only 0 or 1. ■Computer circuitry performs various simple bit manipulations such as: –examining the value of a bit –setting the value of a bit –reversing the value of a bit ■Bytes are composed of eight bits. ■Characters in Visual Basic are Unicode characters, which are composed of two bytes. 23.2 Data Hierarchy (Cont.)

11  2009 Pearson Education, Inc. All rights reserved. 11 ■Fields are composed of characters and convey meaningful information. ■A record is a collection of several related fields. –A payroll system, for example, would have a record for each employee, with several information fields. ■A group of related records is stored in a file. A payroll file for a company might contain thousands of employee records. 23.2 Data Hierarchy (Cont.)

12  2009 Pearson Education, Inc. All rights reserved. 12 ■A record key identifies a record as belonging to a particular person or entity. –The record key must be unique. –In the payroll record just described, the employee identification number normally would be chosen as the record key. ■The most common type of organization is called a sequential-access file, in which records are stored in order. ■Sometimes a group of related files is called a database. 23.2 Data Hierarchy (Cont.)

13  2009 Pearson Education, Inc. All rights reserved. 13 ■Files are viewed as sequential streams of bytes (Fig. 23.4). ■When a file is opened, Visual Basic creates an object and associates a stream with that object: – StreamReader takes text input from a file. – StreamWriter outputs text to a file. 23.3 Files and Streams Figure 23.4 | Visual Basic’s conceptual view of an n-byte file.

14  2009 Pearson Education, Inc. All rights reserved. 14 Common Programming Error Attempting to open a file from multiple programs at once (or even the same program) is a logic error. A file can be opened by only one program at a time.

15  2009 Pearson Education, Inc. All rights reserved. 15 ■Open the WriteEvent template application (Fig. 23.5). ■Add an OpenFileDialog component from the All Windows Forms category of the Toolbox. ■Name it openFileDialog, and change its FileName property to calendar.txt. ■Set property CheckFileExists to False so that if the user specifies a nonexistent file, that file is created. Adding a Dialog to Open or Create a File

16  2009 Pearson Education, Inc. All rights reserved. 16 Figure 23.5 | openFileDialog added and renamed. OpenFileDialog component Adding a Dialog to Open or Create a File (Cont.)

17  2009 Pearson Education, Inc. All rights reserved. 17 Determining Whether a File Name Is Valid ■Method CheckValidity (Fig. 23.6) receives a file name as a String. ■If the file name is valid, the Function returns True. Figure 23.6 | Method CheckValidity header. CheckValidity Function procedure header

18  2009 Pearson Education, Inc. All rights reserved. 18 Determining Whether a File Name Is Valid (Cont.) ■ String method EndsWith (Fig. 23.7) returns False if the value of variable name does not end with. txt. ■In this case, a MessageBox is displayed, informing the user that the application expects a text file. Figure 23.7 | Displaying an error message indicating an invalid file name. Displaying error message if incorrect file type is provided

19  2009 Pearson Education, Inc. All rights reserved. 19 Determining Whether a File Name Is Valid (Cont.) ■After the user enters a file name, line 13 (Fig. 23.8) disables the Open File... Button. ■Lines 14–15 enable the Enter and Close File Button s. Figure 23.8 | Changing the GUI if a valid file name is entered. Enabling and disabling Buttons

20  2009 Pearson Education, Inc. All rights reserved. 20 Creating a StreamWriter Object ■To access the classes that enable you to perform file processing, import namespace System.IO (Fig. 23.9). Figure 23.9 | System.IO namespace imported into class WriteEventForm. Importing namespace System.IO

21  2009 Pearson Education, Inc. All rights reserved. 21 Creating a StreamWriter Object (Cont.) ■Namespace System.IO includes class StreamWriter, which is used to create objects for writing text to a file (Fig. 23.10). Figure 23.10 | Declaring a StreamWriter variable. Declaring StreamWriter variable

22  2009 Pearson Education, Inc. All rights reserved. 22 ■Double click the Open File... Button to create the empty event handler (Fig. 23.11). ■The ShowDialog method displays the Open dialog to allow the user to open a file, and returns a value of type DialogResult. Creating a StreamWriter Object (Cont.) Figure 23.11 | Displaying the Open dialog and retrieving the result. Displaying Open dialog If the user clicks Cancel, the event handler exits without performing any actions

23  2009 Pearson Education, Inc. All rights reserved. 23 Creating a StreamWriter Object (Cont.) ■Property FileName of OpenFileDialog (Fig. 23.12) specifies the full path of the file the user selected. Figure 23.12 | Retrieving the name and path of selected file. Setting variable to user- specified file name

24  2009 Pearson Education, Inc. All rights reserved. 24 ■Method CheckValidity determines whether the specified file is a text file (that is, the file name ends with ".txt" ). ■The StreamWriter constructor takes two arguments. –The first indicates the name of the file to which you write information. –The second is a Boolean value that determines whether the StreamWriter appends information to the end of the file. Creating a StreamWriter Object (Cont.)

25  2009 Pearson Education, Inc. All rights reserved. 25 Creating a StreamWriter Object (Cont.) Figure 23.13 | Validating the filename and initializing a StreamWriter object. Check for valid filename Create StreamWriter object

26  2009 Pearson Education, Inc. All rights reserved. 26 Common Programming Error When you open an existing file by invoking the StreamWriter constructor with a False second argument, data previously contained in the file is lost.

27  2009 Pearson Education, Inc. All rights reserved. 27 Writing Information to a Sequential-Access File ■Method ClearUserInput (Fig. 23.14) clears the TextBox es and resets the NumericUpDown control’s value. Figure 23.14 | Clearing user input. Clearing user input

28  2009 Pearson Education, Inc. All rights reserved. 28 ■Double click the Enter Button to create its event handler (Fig. 23.15). ■Write the user input to the file by using the Write method. –Each field is separated by a Tab character. ■The WriteLine method writes its argument to the file, followed by a newline character. Writing Information to a Sequential-Access File (Cont.) Figure 23.15 | StreamWriter writing to a file. Writing information to a file

29  2009 Pearson Education, Inc. All rights reserved. 29 ■Double click the Close File Button to create its event handler (Fig. 23.16). ■The StreamWriter ’s Close method closes the stream. –You should always close the file after you’ve finished processing it to ensure that you don’t lose any data. Closing the StreamWriter Figure 23.16 | Closing the StreamWriter. Closing StreamWriter object

30  2009 Pearson Education, Inc. All rights reserved. 30 Writing Event Information to a File ■Run your application (Fig. 23.17). Figure 23.17 | Write Event application running.

31  2009 Pearson Education, Inc. All rights reserved. 31 ■Click the Open File... Button and open the existing calendar.txt file from: – C:\Examples\Tutorial23\TemplateApplication\ TicketInformation\TicketInformation\bin\ Debug (Fig. 23.18). Writing Event Information to a File (Cont.) Figure 23.18 | Open dialog displaying contents of the template Ticket Information application’s Debug folder.

32  2009 Pearson Education, Inc. All rights reserved. 32 ■Enter event information, then click Enter to add an event to the calendar.txt file. ■When you have entered all the events you wish, click the Close File Button. ■Use the IDE to open calendar.txt (Fig. 23.19). Figure 23.19 | Sequential-access file generated by Write Event application. Writing Event Information to a File (Cont.) Day and time of event, ticket price, event name and description

33  2009 Pearson Education, Inc. All rights reserved. 33 ■Figure 23.20 presents the source code for the Write Event application. Outline System.IO (1 of 4 ) Importing namespace System.IO StreamWriter used to write text to a file

34  2009 Pearson Education, Inc. All rights reserved. 34 Outline System.IO (2 of 4 ) Retrieve user input from Open dialog Storing filename entered by user Create StreamWriter object to associate a stream with the user-specified text file

35  2009 Pearson Education, Inc. All rights reserved. 35 Outline System.IO (3 of 4 ) Append data to end of file

36  2009 Pearson Education, Inc. All rights reserved. 36 Outline System.IO (4 of 4 ) Closing the file’s associated stream

37  2009 Pearson Education, Inc. All rights reserved. 37 When the Form loads: Display the current day’s events When the user selects a date on the calendar: Display the selected day’s events When the user selects an event from the Pick an event: ComboBox: Retrieve index of selected item in the Pick an event: ComboBox Display event information in the Description: TextBox When procedure CreateEventList is called: Extract data for the selected day from calendar.txt Clear the Pick an event: ComboBox 23.5 Building the Ticket Information Application

38  2009 Pearson Education, Inc. All rights reserved. 38 If events are scheduled for that day Add each event to the Pick an event: ComboBox Display "- Events -" in the Pick an event: ComboBox Display "Pick an event." in the Description: TextBox Else Display "- No Events -" in the Pick an event: ComboBox Display "No events today." in the Description: TextBox When procedure ExtractData is called: Clear the community events collection Open calendar.txt file for reading Until there are no events left in the file Read the next line of the file If the current event is for the day selected by the user Store the event information 23.5 Building the Ticket Information Application (Cont.)

39  2009 Pearson Education, Inc. All rights reserved. 39 ■Use an ACE table to convert the pseudocode into Visual Basic (Figure 23.21). Figure 23.21 | ACE table for the Ticket Information application. (Part 1 of 3.) Action/Control/Event (ACE) Table for the Ticket Information Application

40  2009 Pearson Education, Inc. All rights reserved. 40 Figure 23.21 | ACE table for the Ticket Information application. (Part 2 of 3.) Action/Control/Event (ACE) Table for the Ticket Information Application (Cont.)

41  2009 Pearson Education, Inc. All rights reserved. 41 Figure 23.21 | ACE table for the Ticket Information application. (Part 3 of 3.) Action/Control/Event (ACE) Table for the Ticket Information Application (Cont.)

42  2009 Pearson Education, Inc. All rights reserved. 42 ■Open the TicketInformation template application and add the MonthCalendar control (Fig. 23.22). ■Change its Name to dateMonthCalendar. Adding a MonthCalendar Control Figure 23.22 | Ticket Information template application’s Form.

43  2009 Pearson Education, Inc. All rights reserved. 43 Good Programming Practice Append the MonthCalendar suffix to MonthCalendar control names.

44  2009 Pearson Education, Inc. All rights reserved. 44 ■Import namespace System.IO, which allows the application to use class StreamReader (Fig. 23.23). Figure 23.23 | Importing the System.IO namespace. Beginning to Build the Ticket Information Application

45  2009 Pearson Education, Inc. All rights reserved. 45 ■Store the event information read from the file in a List(Of CommunityEvent) named communityEvents (Fig. 23.24). ■In the Solution Explorer, right click the TicketInformation project. –Select Add > Existing Item... –Select the CommunityEvent.vb file and click Add. Beginning to Build the Ticket Information Application (Cont.) Figure 23.24 | List declared to hold event information. Creating a List of CommunityEvents

46  2009 Pearson Education, Inc. All rights reserved. 46 ■Double click the Form to generate its event handler (Fig. 23.25). Figure 23.25 | Load event handler calling method CreateEventList. Handling the Form ’s Load Event You add code to the CreateEventList procedure later

47  2009 Pearson Education, Inc. All rights reserved. 47 ■Double click the MonthCalendar to generate the empty DateChanged event handler (Fig. 23.26). Figure 23.26 | dateMonthCalendar ’s DateChanged event handler. Handling the MonthCalendar ’s DateChanged Event Calling method CreateEventList

48  2009 Pearson Education, Inc. All rights reserved. 48 ■The CreateEventList method (Fig. 23.27) declares currentEvent to iterate through the events. –The currently selected date is specified by the MonthCalendar control’s SelectionStart property, which is the first date in any range selected. Defining the CreateEventList Method Figure 23.27 | CreateEventList calls method ExtractData and clears the ComboBox. You add code to the ExtractData procedure in the next box

49  2009 Pearson Education, Inc. All rights reserved. 49 ■The CreateEventList method (Fig. 23.28) has a For Each...Next statement. –The statement iterates through List communityEvents and adds the name of each event to the ComboBox. Defining the CreateEventList Method (Cont.) Figure 23.28 | Displaying the events scheduled for the specified day. Extracting event name from currentEvent and displaying it in the ComboBox Indicating that events are scheduled for the day Indicating that no events are scheduled for the day

50  2009 Pearson Education, Inc. All rights reserved. 50 ■The Date selected in the MonthCalendar control is passed to the ExtractData method (Fig. 23.29). ■Variable chosenDay is the selected day returned by the Day property of the currentDate parameter. ■The eventInfo variable is an array of String s used to store the event information retrieved from the file. Reading a Sequential-Access File Figure 23.29 | ExtractData method’s variable declarations.

51  2009 Pearson Education, Inc. All rights reserved. 51 ■ ExtractData creates a new StreamReader object (Fig. 23.30), passing the name of the file to be read. Figure 23.30 | Initializing the StreamReader used to read data from a sequential-access file. Creating a StreamReader object to read the calendar.txt file Reading a Sequential-Access File (Cont.)

52  2009 Pearson Education, Inc. All rights reserved. 52 ■The Do Until...Loop statement (Fig. 23.31) determines whether the end of the file has been reached. ■The ReadLine method reads one line of text from the specified stream. ■ String method Split, splits the String at each Tab character, and assigns the resulting array of String s to array eventInfo. –This character is called a delimiter and is used to mark the boundaries between fields. Reading a Sequential-Access File (Cont.)

53  2009 Pearson Education, Inc. All rights reserved. 53 Figure 23.31 | Extracting the day from an event entry in the file. Verify that the end of the file has not been reached Reading a Sequential-Access File (Cont.) Read a line of text from the file Split the line of text into an array of Strings containing each field in the record

54  2009 Pearson Education, Inc. All rights reserved. 54 ■If the day of the event read from the file and the specified day are the same, then the event information is stored in a CommunityEvent object (Fig. 23.32). Reading a Sequential-Access File (Cont.) Figure 23.32 | Storing event information in the List of CommunityEvents. Store event information in a CommunityEvent object Add the event to the List

55  2009 Pearson Education, Inc. All rights reserved. 55 ■Double click the Pick an event: ComboBox to generate its event handler (Fig. 23.33). –The SelectedIndex property of the ComboBox returns the index number of the selected event. Handling the SelectedIndexChanged Event Displaying event information in the Description: TextBox Figure 23.33 | D isplay information for selected event.

56  2009 Pearson Education, Inc. All rights reserved. 56 ■Rewrite the ExtractData method (Fig. 23.34). Figure 23.34 | Removed Do Until...Loop and local variables. Using LINQ to Select Events From a Text File

57  2009 Pearson Education, Inc. All rights reserved. 57 ■Variable eventQuery stores the LINQ query (Fig. 23.35) used to search the data from calendar.txt. ■The From clause specifies the range variable and the data source. ■ File method ReadAllLines returns an array of String s in which each element is a line from the text file passed as an argument. Using LINQ to Select Events From a Text File (Cont.)

58  2009 Pearson Education, Inc. All rights reserved. 58 Figure 23.35 | Specifying the data source. Using LINQ to Select Events From a Text File (Cont.) Specifying the query’s data source

59  2009 Pearson Education, Inc. All rights reserved. 59 ■A Let clause (Fig. 23.36) allows you to create and initialize a variable in a LINQ query. –Line 47 declares an array of String s named eventInfo. ■The Where clause uses the array to determine whether the day of the event matches the selected day. Declaring variable eventInfo inside the LINQ query Figure 23.36 | Declaring a variable in a LINQ query. Using LINQ to Select Events From a Text File (Cont.)

60  2009 Pearson Education, Inc. All rights reserved. 60 ■As a LINQ query executes, it can create new objects which are returned as the query’s result (Fig. 23.37). –The With keyword specifies that the property names used are from the new CommunityEvent object. Using LINQ to Select Events From a Text File (Cont.) Figure 23.37 | Creating CommunityEvent objects in the Select clause. Creates a new CommunityEvent object

61  2009 Pearson Education, Inc. All rights reserved. 61 ■Interface IEnumerable ’s ToList method (Fig. 23.38) assigns the selected events to the List object communityEvents. ■Method ToList returns a List of the items selected by the LINQ query. Figure 23.38 | Assigning the query result to the List. Using LINQ to Select Events From a Text File (Cont.)

62  2009 Pearson Education, Inc. All rights reserved. 62 ■Figure 23.39 presents the source code for the application. Outline System.IO (1 of 5 ) Importing namespace System.IO

63  2009 Pearson Education, Inc. All rights reserved. 63 Outline System.IO (2 of 5 )

64  2009 Pearson Education, Inc. All rights reserved. 64 Outline System.IO (3 of 5 ) Retrieve an array containing each line of calendar.txt Split line into array of Strings Check whether chosenDay is the day from the line being processed Creating a CommunityEvent object with an object initializer

65  2009 Pearson Education, Inc. All rights reserved. 65 Outline System.IO (4 of 5 ) Retrieve a List containing each CommunityEvent object in the query result

66  2009 Pearson Education, Inc. All rights reserved. 66 Outline System.IO (5 of 5 )


Download ppt "T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 23 Ticket Information Application Introducing Sequential-Access Files."

Similar presentations


Ads by Google