Chapter 11 Saving Data and Objects In Files

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

C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Chapter 11 Data Files Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved. McGraw-Hill.
Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Chapter 9: Sequential Access Files and Printing
Using Multiple Forms. Creating a New Form ProjectAdd Windows Form.
ASP.NET Programming with C# and SQL Server First Edition
MIS316 – BUSINESS APPLICATION DEVELOPMENT – Chapter 14 – Files and Streams 1Microsoft Visual C# 2012, Fifth Edition.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Using Arrays and File Handling
Chapter 9 Files I/O: Files, Records and Fields Part 3.
5-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
McGraw-Hill © 2009 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Twelve Access Databases and LINQ.
Chapter 5 Menus, Common Dialog Boxes, and Methods Programming in C#.NET © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.
File I/O 11_file_processing.ppt
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 7 Using Menus, Common Dialogs, Procedures, Functions, and Arrays.
Chapter 5 Menus, Common Dialog Boxes, Sub Procedures, and Function Procedures Copyright © 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.
Chapter 10: Structures and Sequential Access Files
Chapter Ten Structures and Sequential Access Files Programming with Microsoft Visual Basic th Edition.
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.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
File I/O What We’ll Cover –Visual Basic Techniques for Text Files –.NET Techniques for Text Files What We’ll Not Cover –Binary File I/O –XML File I/O.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
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.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
6-1 Chapter 6 Working with Arrays in VB.NET. 6-2 Learning Objectives Understand the use of list and table arrays in VB.NET projects and the difference.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Ten Structures and Sequential Access Files.
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.
McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 11 Data Files.
Creating New Forms Projects can appear more professional when using different windows for different types of information. Select Add Windows Form from.
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.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Use TryParse to Validate User Input
Visual Basic Fundamental Concepts
Microsoft Visual Basic 2010: Reloaded Fourth Edition
IS 350 Application Structure
Apply Procedures to Develop Message, Input, and Dialog Boxes
Files.
Use TryParse to Validate User Input
Using Multiple Forms.
Using Procedures and Exception Handling
Files and Streams.
Files and Streams Lect3 CT1411.
Sequential Input and Output using Text Files
Visual Basic..
Topics Introduction to File Input and Output
WEB PROGRAMMING JavaScript.
Chapter 3.5 Input and Output
Tutorial 9 Sequential Access Files and Printing
Files and Streams Lect10 GC201 12/1/2015.
Tonga Institute of Higher Education
CIS16 Application Development and Programming using Visual Basic.net
Chapter 10 Accessing Database Files
JavaScript: Introduction to Scripting
Input and Output.
Files and Streams.
Chapter 13 Additional Topics in Visual Basic
Topics Introduction to File Input and Output
Input and Output Chapter 3.5
Presentation transcript:

Chapter 11 Saving Data and Objects In Files Programming In Visual Basic .NET

Data Files To save data from one run of the application to the next Use when there is only a small amount of data that would not warrant the use of a database Use for Windows applications, the default security policy for the Internet and Intranets does not allow access to disk files © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Data File Terminology File ==> Entire collection of data Records ==> Rows, one per entity Fields ==> Columns, data elements within row © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Sample Data File Records Fields Last Name First Name Phone Maxwell Harry 909-555-1234 Helm Jennifer 818-555-2222 Colton Craig 909-555-3333 Records Fields © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

File Handling Using Streams A Stream is designed to transfer a series of bytes from one location to another Streams are objects that have methods and properties Found in the System.IO.namespace File handling projects must contain an Imports statement before the statement declaring the form's class © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

File I/O Reading and writing data in a disk file Writing = Output Reading = Input Write Output Read Input Form Data File © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Writing Data in a File User inputs data into text boxes Declare a new StreamWriter object Also declares the name of the data file Use StreamWriter's WriteLine method Copies data to a buffer in memory Call StreamWriter's Close method Transfers data from buffer to the file and releases system resources used by the stream © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Writing Data in a File (continued) Declaring a new StreamWriter object opens the file If the file does not exist, a new one is created Declare the StreamWriter object either in the declarations section of your program or in a procedure © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Instantiating a StreamWriter Object General Form Default location for file is the bin directory beneath the folder for the current project Can specify the complete path of the file Dim ObjectName As New StreamWriter("FileName") Dim ObjectName As New StreamWriter("FileName", BooleanAppend) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Declaring a StreamWriter Object - Examples Dim phoneStreamWriter As New StreamWriter("Phone.txt") Dim namesStreamWriter As New StreamWriter("C:\MyFiles\Names.txt") Dim logFileStreamWriter As New StreamWriter("C:\MyFiles\LogFile.txt", True) True = Append data to this existing file © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Write and WriteLine Methods Write Method Places items consecutively in the file with no delimiter (separator) WriteLine Method Places an enter (carriage return) between items Used in this chapter © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

The WriteLine Method - General Form DataToWrite argument may be string or numeric Converts any numeric data to string and writes string data in the file ObjectName.WriteLine(DataToWrite) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

The WriteLine Method - Examples phoneStreamWriter.WriteLine(nameTextBox.Text) phoneStreamWriter.WriteLine(phoneTextBox.Text) namesStreamWriter.WriteLine("Sammy") bankBalanceStreamWriter.WriteLine(balanceDecimal.ToString( )) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Closing a File Use StreamWriter's Close method Finishes writing all data from the stream's buffer to the disk and releases system resources Commonly coded in form’s closing event procedure © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Closing a File - Example Private Sub exitButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles exitButton.Click ' Close the file and the form. phoneStreamWriter.Close( ) Me.Close( ) End Sub © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Viewing the Contents of a File Text editor, such as Notepad Visual Studio's IDE In the Solution Explorer 1. Select the Project name 2. Click Show All Files button to display the bin folder 3. Select the file to display in the editor window © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Viewing the Contents of a File (continued) Select project name Show All Files button Contents of Data File bin folder New File © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Reading Data from a File Declare an object of the StreamReader class Also declares the name of the data file Opens the file Use StreamReader's ReadLine method May need a loop to retrieve multiple records Call StreamReader's Close method © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Reading Data from a File (continued) The file must exist in the specified location or an exception occurs Declare the StreamReader object in a procedure and enclose it in a Try/Catch block © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Instantiating a StreamReader Object General Form Example Dim ObjectName As New StreamReader("FileName") Try Dim namesStreamReader As New StreamReader("C:\MyFiles\Names.txt") Catch MessageBox.Show("File does not exist") End Try © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Using the ReadLine Method Use to read previously saved data Each time it executes, it reads the next line of data Assign the value from the read to the desired location, such as a label, text box, or string variable © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Using the ReadLine Method -Example nameLabel.Text = phoneStreamReader.ReadLine( ) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Checking for the End of the File Use StreamReader's Peek method Peek looks at the next element without reading it If you Peek beyond the last element the value returned is negative 1 (-1) Code an If statement to execute Peek and compare for <> -1 before reading Read elements in the exact same order as they were written to obtain valid data © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Using the File Common Dialog Box The previous data file examples included hard-coded file names (and paths) May allow the user to browse and enter the file name at run time Use the OpenFileDialog common dialog component to display the dialog box Then use the object's FileName property to open the selected file © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

OpenFileDialog Component Properties Name – Can use default name CheckFileExists CheckPathExists FileName (will be set by user's selection at run time) Filter InitialDirectory (set this property in code) Title © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Displaying the Open File Dialog Box Add OpenFileDialog component to form At design time set initial properties for Name, CheckFileExists, CheckPathExists, Filter and Title In code set InitialDirectory property to Application.StartUpPath Display dialog box using ShowDialog method and retrieve FileName property © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Open File to Read Dialog Box Files of Type Determined by Filter Property © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Open File to Read Dialog Box - Code Example Private Sub fileOpenMenuItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles fileOpenMenuItem.Click ' Open the file. Dim responseDialogResult As DialogResult ' Begin in the project folder. OpenDialog1.InitialDirectory = Application.StartupPath ' Display the File Open dialog box. responseDialogResult = OpenDialog1.ShowDialog( ) ' Make sure that the user didn’t click the Cancel button. If responseDialogResult <> DialogResult.Cancel Then ' Open the output file. phoneStreamWriter = New StreamWriter(OpenDialog1.FileName) End If End Sub © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Checking for Successful File Open If the StreamWriter or StreamReader were not instantiated, the file did not open Use the Nothing keyword to check for instantiation An object that has not been instantiated has a value of Nothing © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Using Nothing Keyword ' Is the file already open? If Not phoneStreamWriter Is Nothing Then phoneStreamWriter.Close( ) End If Must use Keyword Is rather than equal sign © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Saving the Contents of a List Box Do not assign values at design time, when program begins, open data file and read items into Items collection of List Box If user makes changes to list, ask whether to save list when program ends, include a menu option to save list If file of list elements does not exist when program begins, allow user to create new list by adding items © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Loading the List Box Read the file into the list in Form_Load Loop through the file until all elements are read Use the Items.Add method to add the data elements to the list Dim coffeeFlavor As String ' Read all elements into the list. Do Until flavorsStreamReader.Peek = -1 coffeeFlavorString = flavorStreamReader.ReadLine( ) coffeeComboBox.Items.Add(coffeeFlavorString) Loop © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Checking for Existence of the File When the StreamReader object is created, the constructor makes sure the file exists If it does not exist, give the user options Try to locate the data file again Exit the program Begin with an empty list, add items, and create a new file © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Saving the File Provide a menu option for the user to save the file Open a StreamWriter object Loop through the Items collection of the list box, saving each element with a WriteLine method © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Saving the File - Example Private Sub fileSaveMenuItem_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles fileSaveMenuItem.Click ' Save the list box contents in a file. Dim indexInteger As Integer Dim numberItemsInteger As Integer ' Open the file. Dim flavorsStreamWriter As New StreamWriter("Coffees.txt") ' Save the items in the file. numberItemsInteger = coffeeComboBox.Items.Count - 1 For indexInteger = 0 To numberItemsInteger flavorsStreamWriter.WriteLine(coffeeComboBox.Items(indexInteger)) Next indexInteger flavorsStreamWriter.Close( ) ' Close the file. isDirtyBoolean = False ' Reset changed status. End Sub © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Querying the User to Save Good idea to ask users if they want to save any changes made before program ends Use a module-level Boolean variable, isDirtyBoolean, to keep track of changes In procedures that allow changes, set variable to True After saving file set variable to False © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

The Form_Closing Procedure Form’s Closing event procedure is best location to ask user to save the file Closing event executes before the form closes no matter how user exits program or even Windows © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Serialization Save an object and the current value of all of its properties using Serialization Serialization refers to a series or stream of bits Object's state is converted to a series of bits that can be saved and later used to recreate the object Deserialization is reading the saved data back and recreating the object © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Serialization (continued) To save an object Class must be declared as Serializable Must have a Formatter Two types of Formatters Binary, stores data in a binary form SOAP (Simple Object Access Protocol), stores data in an XML format © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Serialization (continued) Make any class module serializable allowing public properties of an object to be saved Declare the class as Serializable Declare a Formatter object Declare a FileStream object that includes the name of the file Use the Formatter object's Serialize method to save the object's properties Close the FileStream © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Making a Class Serializable Modify the class header to include the Serializable attribute Add < Serializable ( ) > in front of the class header Example < Serializable ( ) > Public Class BookSale ' Body of the class. End Class © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Adding a Formatter Object Write the code to store (serialize) the object in your form's code, not in the serialize class Declare a new formatter object using either BinaryFormatter class SoapFormatter class A formatter object requires an Imports statement for the formatter class © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Adding a Formatter Object – Code Example Imports System.IO Imports System.Runtime.Serialization Imports System.Runtime.Serialization.Formatters.Binary Dim FormatObject As SoapFormatter = New SoapFormatter Dim FormatObject As BinaryFormatter = New BinaryFormatter © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Using a FileStream Serialization uses the FileStream class rather than StreamReader and StreamWriter classes Declare a FileStream including Name and Path for file File Mode Create ==> Open the file for output Open ==> Retrieve the file OpenOrCreate (module level, read and write) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Declaring a FileStream Object Constructor Example Dim ObjectName As FileStream = New FileStream("file name", _ FileMode.Open|Create) Dim booksFileStream As FileStream = New FileStream _ ("Books.txt", FileMode.Create) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Saving an Object Use the Serialize method of the Formatter to save an object Serialize method writes data to buffer Include Close method to complete the save operation to disk © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Serialize Method General Form Example FormatterObject.Serialize(StreamObject, ObjectToSave) bookBinaryFormatter.Serialize(booksFileStream, aBookSale) © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.

Recreating an Object Read an object back in with the Deserialize method of the formatter Create a FileStream object in the Open mode Declare a Formatter object Use the Formatter's Deserialize method, converting the input to the desired type Transfer fields from the object to the screen Close the stream Convert input data to correct type © 2005 by The McGraw-Hill Companies, Inc. All rights reserved.