Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation...

102
Network Programming Chapter 2 Streams in .NET

Transcript of Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation...

Page 1: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Network Programming

Chapter 2Streams in .NET

Page 2: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Basic Outline

• Streams in .NET

• Stream Manipulation

• Serialisation

Page 3: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Introduction

• A stream is an abstract representation of a sequence of bytes (e.g. file, I/O device or TCP/IP socket)

• Abstraction allows us to access different devices in the same manner (like with inheritance)

Page 4: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Streams in .NET

• Stream class– Abstract class– Perform binary I/O operations

• TextReader & TextWriter classes• BinaryReader & BinaryWriter classes

Page 5: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Streams in .NET

• Synchronous and Asynchronous I/O– Stream class provides for both synchronous &

asynchronous• Stream Class• FileStream Class• Reading and Writing with the FileStream

Class• BufferedStream Class• MemoryStream Class• NetworkStream Class• CryptoStream Class

Page 6: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O

• Default “setting”• Simplest method• Blocks processing until operation is complete

(disadvantage)• Not suitable for operations over a network• Not good choice for large files over low bandwidth• Can simulate asynchronous I/O by threading

Page 7: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Asynchronous I/O

• Allows other processing• Operating system notifies caller when I/O

processing is done• Needs separate notification mechanism• Useful when application needs to process other

tasks while doing I/O• A separate thread is created for each I/O thread

(higher O/S overhead)

Page 8: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Streams in .NET

• Synchronous and Asynchronous I/O• Stream Class• FileStream Class• Reading and Writing with the FileStream

Class• BufferedStream Class• MemoryStream Class• NetworkStream Class• CryptoStream Class

Page 9: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

System.Security.Cryptography.CryptoStream

Stream Class

System.Object

System.IO

BinaryReader Stream

BinaryWriter BufferedStream

TextReader FileStream

StreamReader MemoryStream

StringReader

TextWriter

StreamWriter

StringWriter

System.Net.Sockets.NetworkStream

System.Net.Sockets

System.Security.Cryptography

Page 10: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Stream Class

• Base class = System.IO• Stream is base class for all other stream

classes

Page 11: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Classes Derived From the Stream Class

Class Purpose

FileStream Uses files as backing storage. This is the most widely used Stream class

BufferedStream Uses a buffer s backing storage. This class is used as intermediate storage for improving performance

MemoryStream Uses memory as backing storage and performs faster I/O operations when compared to other streams.

NetworkStream Does not have any backing storage. This class is used with other streams for transferring data across a network.

CryptoStream Used with other stream classes for performing encryption and decryption on streams.

Page 12: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Stream MembersStream MembersName Description

CanRead When overridden in a derived class, gets a value indicating whether the current stream supports reading. (Returns true if the stream supports reading, otherwise; it returns false).

CanSeek When overridden in a derived class, gets a value indicating whether the current stream supports seeking. Seeking is used to set the position within the current stream. A NotSupportedException is thrown if seeking is attempted on a stream that does not support it

CanTimeout Gets a value that determines whether the current stream can time out.

CanWrite When overridden in a derived class, gets a value indicating whether the current stream supports writing. Property should be used before doing any write operation.

Length When overridden in a derived class, gets the length in bytes of the stream. This is a read-only property.

Position When overridden in a derived class, gets or sets the position within the current stream. It is used for moving around within a stream. To use this property, the stream must support seeking (see the CanSeek property)

ReadTimeout Gets or sets a value that determines how long the stream will attempt to read before timing out.

WriteTimeout Gets or sets a value that determines how long the stream will attempt to write before timing out.

Page 13: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous Methods for Reading from and Writing to a Stream

Method Description

Read When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. Read reads a specified number of bytes and advances the position within the stream by the number of bytes read.

ReadByte Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.

Write When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

WriteByte Writes a byte to the current position in the stream and advances the position within the stream by one byte.

Page 14: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Asynchronous Methods for Reading from and Writing to a

Stream

Method Description

BeginRead Begins an asynchronous read operation.

BeginWrite Begins an asynchronous write operation.

Write When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.

WriteByte Writes a byte to the current position in the stream and advances the position within the stream by one byte.

Page 15: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Methods for Managing a Stream

Method Description

Flush When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device (moves information to its destination depending on the state of the Stream object).

Close Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. This method automatically flushes any stored data. It is advisable to put a close method in the finally block to ensure that the stream is closed regardless of any exception thrown.

SetLength When overridden in a derived class, sets the length of the current stream. Note that if the specified value is less than the current length of the stream, the stream is truncated. A stream must support both writing and seeking for SetLength

Page 16: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Streams in .NET

• Synchronous and Asynchronous I/O• Stream Class• FileStream Class• Reading and Writing with the FileStream

Class• BufferedStream Class• MemoryStream Class• NetworkStream Class• CryptoStream Class

Page 17: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

FileStream Class

• One of the most widely used of the Stream-derived classes

• Handles files and standard input and output devices

• Several ways to create a FileStream object

Page 18: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Creating a FileStream Instance with a File Path

• Specify a path to a file• Default buffer is 8192 bytes

– Buffer size may be changed in constructor

• Methods of creating a FileStream– Specifying the File Path and Mode– Specifying File Access– Specifying Sharing Permissions– Specifying Buffer Size– Specifying Synchronous or Asynchronous State

Page 19: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

FileMode OptionsMember name Description

Append Opens the file if it exists and seeks to the end of the file, or creates a new file. FileMode.Append can only be used in conjunction with FileAccess.Write. Any attempt to read fails and throws an ArgumentException. 

Create Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires FileIOPermissionAccess.Write. System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. 

CreateNew Specifies that the operating system should create a new file. This requires FileIOPermissionAccess.Write. If the file already exists, an IOException is thrown. 

Open Specifies that the operating system should open an existing file. The ability to open the file is dependent on the the value specified by FileAccess. A System.IO.FileNotFoundException is thrown if the file does not exist. 

OpenOrCreate Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess.Read, FileIOPermissionAccess.Read is required. If the file access is FileAccess.Write or FileAccess.ReadWrite, FileIOPermissionAccess.Write is required. If the file access is FileAccess.Append, then FileIOPermissionAccess.Append is required. 

Truncate Specifies that the operating system should open an existing file. Once opened, the file should be truncated so that its size is zero bytes. This requires FileIOPermissionAccess.Write. Attempts to read from a file opened with Truncate cause an exception. 

Page 20: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

FileMode Syntax

• To create a FileStream object that creates a new file called c:\Networking\MyStream.txt, you would use the following

//Using file path and file modeFileStream inF = new FileStream(“C:\\Networking\\MyStream.txt”, FileMode.CreateNew);

Page 21: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

FileAccess Options

Member name

Description

Read Read access to the file. Data can be read from the file. Combine with Write for read/write access. 

ReadWrite Read and write access to the file. Data can be written to and read from the file. 

Write Write access to the file. Data can be written to the file. Combine with Read for read/write access. 

Page 22: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

FileAccess Syntax

• You can use the CanRead and CanWrite properties to check the FileAccess permission given to the file

• To create a new file called c:\Networking\MyStream.txt with write-only access

//Using file path, file mode and file access

FileStream inF = new FileStream(“C:\\Networking\\MyStream.txt”, FileMode.CreateNew, FileAccess.Write);

Page 23: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

FileShare OptionsMember name Description

Delete Allows subsequent deleting of a file. 

Inheritable Makes the file handle inheritable by child processes. This is not directly supported by Win32. 

None Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed. 

Read Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file. 

ReadWrite Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file. 

Write Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file. 

Page 24: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

FileShare Syntax

• Create a FileStream instance using the FileMode, FileAccess and FileShare properties

//Using file path, file mode, file access and sharing permission

//Open file for writing, other processes will get read-only access

FileStream inF = new FileStream (“C:\\Networking\\MyStream.txt”, FileMode.Open, FileAccess.Write, FileShare.Read);

Page 25: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Specifying Buffer Size

• You can also create a FileStream instance by specifying the size of the buffer in addition to the parameters discussed previously. Here we set the size of the buffer to 1000 bytes:

//using path, mode, access, sharing permission and buffer size

FileStream inF = new FileStream(“C:\\Networking\\MyStream.txt”, FileMode.Open, FileAccess.Write, FileShare.Read, 1000);

• If the buffer size specified is between 0 and 8 bytes, the actually buffer is set to 8 bytes

Page 26: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Specifying Synchronous or Asynchronous State

//Using path, mode, access, sharing permission, buffer size and specifying asynchronous operations

FileStream outF = new FileStream(“C:\\Networking\\MyStream.txt”, FileMode.Open, FileAccess.Write, FileShare.Read, 1000, true);

Page 27: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

File Handle• A file handle is a unique identifier that the

operating system assigns to a file when the file is opened or created

• A file handle is represented using the IntPrt structure, which represents an integer of platform-specific length.

• Using the file handle, you may specify several properties of the stream

• //Create FileStream Instance• FileStream inF = new FileStream( “C:\

Neworking\\MyStream.txt”, FileMode.Open);• Get the file Handle• InterPtr fHanld = infHandle

Page 28: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Streams in .NET

• Synchronous and Asynchronous I/O– Stream class provides for both synchronous &

asynchronous• Stream Class• FileStream Class• Reading and Writing with the FileStream

Class• BufferedStream Class• MemoryStream Class• NetworkStream Class• CryptoStream Class

Page 29: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Reading & Writing

• Synchronous I/O– Stream class

• Asynchronous I/O

Page 30: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O

• Stream class– Read method– Write method

• Example– Performs synchronous I/O operations– Seek method sets the position within the stream– Need System.IO namespace– Need System.Text (convert strings to byte arrays)

Page 31: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O

using System;using System.Collections.Generic;using System.Text;using System.IO;

namespace SyncIO{ class Program {

Note: additional namespace(s)

Page 32: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O

static void Main(string[] args){//Create FileStream instanceFileStream synF = new FileStream("SyncDemo.txt", FileMode.OpenOrCreate); //this will open our file if it exists; otherwise a new file is created.

Page 33: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O

//A character is converted to a byte and then written in a file using the WriteByte method

//After the byte is written, the file position is automatically incremented by 1.

Console.WriteLine("--Writebyte Method demo--");

synF.WriteByte(Convert.ToByte('A'));

Page 34: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O//Converting a string to a byte array (with the GetBytes method of the Encoding class in System.Text//Write takes three parameters:// * the byte array to write// * the position or offset in the array from where to start writing// * the length of data to be writtenConsole.WriteLine("--Write method demo--");byte[] writeBytes = Encoding.ASCII.GetBytes(" is the first character.");

synF.Write(writeBytes, 0, writeBytes.Length);

Page 35: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O

//Reading the data from the file//When reading or writing on a FileStream, the current position(or pointer)of the file automatically//increases by the number of bytes read or written.//set pointer at origin (start of file or start of stream)synF.Seek(0, SeekOrigin.Begin);

//Now we can read. We'll read a single byte with the ReadByte method first. //A byte is read from the stream (with the position automatically increased by 1) and converted by to char.Console.WriteLine("--Readbyte Method demo--");//Read byte and displayConsole.WriteLine("First character is -> " + Convert.ToChar(synF.ReadByte()));

Page 36: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O //Now we read the remainder of the file with the

Read method. //This method takes 3 parameters:// * A byte array that will store the data read

// * the position or offset in the array from where to start reading// * the number of bytes to read//Because we want to read all of the remaining bytes in the file, we want to read in synF.Length - 1 bytes//Use of Read methodConsole.WriteLine("--Read Method demo--");

//Allocate buffer byte[] readBuf = new byte[synF.Length - 1];

//Read filesynF.Read(readBuf, 0, Convert.ToInt32(synF.Length - 1));

Page 37: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Synchronous I/O//The byte array is then converted to string using the GetString method of the Encoding Class//Display contentsConsole.WriteLine("The rest of the file is: " + Encoding.ASCII.GetString(readBuf));

//close the filesynF.Close();

Console.WriteLine("Press a key to continue.");Console.ReadLine();}

}}

Page 38: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Asynchronous I/O

• FileStream opens asynchronously when you pass true to the useAsync flag

• A special call-back mechanism is needed to implement asynchronous I/O, and an AsyncCallback delegate provides a way for client applications to implement this call-back mechanism.

• This call-back delegate is supplied to the BeginRead or BeginWrite method

Page 39: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Asynchronous I/Ousing System;using System.Collections.Generic;using System.Text;using System.IO;using System.Threading;

namespace AsyncDemo{ class Program { //Stream object for reading static FileStream fileStrm; //Buffer to read static byte[] readBuff;

Page 40: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Asynchronous I/O

//We declare an AsyncCallback delegate field for the callback function//AsyncCallback delegatestatic AsyncCallback Callback;//In the Main method, we initialize our callback delegate to point to the Callback function method//This is the method that will be called when the end of the aynchronous read operation is signalled

Page 41: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Asynchronous I/Ostatic void Main(string[] args){

Callback = new AsyncCallback(CallBackFunction);//now we can initialise our FileStream object, specifying asynchronous operationsfileStrm = new FileStream("Test.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 64, true);readBuff = new byte[fileStrm.Length];//we can use the BeginRead method to initiate asynchronous read opeations on the stream.//The callback delegate is passed to the BeginRead method as its second-to-last parameter.//Call async read

fileStrm.BeginRead(readBuff, 0, readBuff.Length, Callback, null);

Page 42: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Asynchronous I/O//Data will be read from FileStream while we continue with other activities. //Here we simply give the appearance of doing some other work by looping and every so often putting the main thread to sleep//Once the loop has finished, the FileStream object is closed.//Simulation of main executionfor (long i = 0; i < 5000; i++){

if (i % 1000 == 0){Console.WriteLine("Executing in Main - " +

i.ToString());Thread.Sleep(10)} //end of if

} //end of for longfileStrm.Close();

Console.WriteLine("Press a key to continue.");Console.ReadLine();

} //end of Main

Page 43: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Asynchronous I/O

static void CallBackFunction(IAsyncResult asyncResult)

{//Gets called when read operation has completedint readB = fileStrm.EndRead(asyncResult);if (readB > 0){

Console.WriteLine(Encoding.ASCII.GetString(readBuff, 0, readB))} //end of if

} //end of CallBackFunction}}

Page 44: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Streams in .NET

• Synchronous and Asynchronous I/O– Stream class provides for both synchronous &

asynchronous• Stream Class• FileStream Class• Reading and Writing with the FileStream

Class• BufferedStream Class• MemoryStream Class• NetworkStream Class• CryptoStream Class

Page 45: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Buffered Stream Class

• A buffer is a reserved area of memory used for storing temporary data.

• Its main purpose is to improve I/O performance, and it’s often used to synchronise data transfer between devices of different speeds. Many online media applications use buffers as intermediate storage.

• BufferedStream Class– Stream object– Generally used with .NetworkStream to store data in memory

• FileStream Class has its own internal buffer• MemoryStream Class does not require buffering

Page 46: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Buffered Stream Classusing System;using System.Collections.Generic;using System.Text;using System.IO;using System.Threading;

namespace BufferedStreamDemo{ class Program { static void Main(string[] args) { FileStream fStr = new FileStream("BufferDemo.txt",

FileMode.OpenOrCreate); byte[] writeBytes = Encoding.ASCII.GetBytes("The difference

between genius and stupidity is that genius has its limits."); fStr.Write(writeBytes, 0, writeBytes.Length); Console.WriteLine("Message written"); fStr.Seek(0, SeekOrigin.Begin); readBufStream(fStr); Console.WriteLine("Press a key to continue"); Console.ReadLine(); }

Page 47: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Buffered Stream Class//Takes a stream object parameters, wraps it in a buffered

stream object and performs a read operaton//Reading Buffered Streampublic static void readBufStream(Stream st){

//Compose BufferedStreamBufferedStream bf = new BufferedStream(st);byte[] inData = new Byte[st.Length];//Read and display buffered databf.Read(inData, 0, Convert.ToInt32(st.Length));Console.WriteLine(Encoding.ASCII.GetString(inData));

}}}

Page 48: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Memory Stream Class

• Situation where application needs data frequently (e.g. lookup table)

• Storing data in file– Cause delays– Reduce performance of application

• Use MemoryStream Class for cases where data needs to be stored in memory

• MemoryStream Class is used for fast, temporary storage

Page 49: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Memory Stream Classusing System;using System.Collections.Generic;using System.Text;using System.IO;using System.Threading;

namespace MemoryStreamDemo{ class Program { static void Main(string[] args) { //Create empty Memory stream MemoryStream ms = new MemoryStream(); byte[] memData = Encoding.ASCII.GetBytes("This will go

in Memory!"); //Write data ms.Write(memData, 0, memData.Length);

Page 50: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Memory Stream Class

//Set pointer at origin ms.Position = 0; byte[] inData = new byte[100]; //Read memory ms.Read(inData, 0, 100);

Console.WriteLine(Encoding.ASCII.GetString(inData));

Stream str = new FileStream("MemOutput.txt", FileMode.OpenOrCreate, FileAccess.Write);

ms.WriteTo(str); str.Close(); } }}

Page 51: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Network Stream Class

• NetworkStream class is in the System.Net.Sockets namespace

• Unbuffered stream

• Does not support random access to data• BufferedStream class is often used to

buffer the NetworkStream

Page 52: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Properties of Network StreamName Description

CanRead Overridden. Gets a value that indicates whether the NetworkStream supports reading.

CanSeek Overridden. Gets a value that indicates whether the stream supports seeking. This property is not currently supported. This property always returns false.

CanTimeout Overridden. Indicates whether timeout properties are usable for NetworkStream.

CanWrite Overridden. Gets a value that indicates whether the NetworkStream supports writing.

DataAvailable Gets a value that indicates whether data is available on the NetworkStream to be read.

Length Overridden. Gets the length of the data available on the stream. This property is not currently supported and always throws a NotSupportedException.

Position Overridden. Gets or sets the current position in the stream. This property is not currently supported and always throws a NotSupportedException.

ReadTimeout Overridden. Gets or sets the amount of time that a read operation blocks waiting for data.

WriteTimeout Overridden. Gets or sets the amount of time that a write operation blocks waiting for data.

Page 53: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Network Stream Class

• Each NetworkStream constructor requires at least one Socket.

• A NetworkStream object can be retrieved from a TcpClient

Page 54: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Network Stream Example (Listener)

using System;using System.Collections.Generic;using System.Text;using System.Net;using System.IO;using System.Net.Sockets;

namespace TCPListenerDemo{ class Program { static void Main(string[] args) { try { //Create TCP Lister to listen on port 5001 IPAddress ipAddress =

Dns.GetHostEntry("localhost").AddressList[0]; TcpListener listener = new TcpListener(ipAddress, 5001);

Page 55: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Network Stream Example (Listener)

//Start listening listener.Start();

//AcceptClient accepts a connection request, returning a TcpClient TcpClient tc = listener.AcceptTcpClient(); //we use the TcpClient's GetStream to create a NetworkStream object NetworkStream stm = tc.GetStream(); //now we can read data as we have with the other streams, using the Read

method byte[] readBuf = new byte[100]; stm.Read(readBuf, 0, 100); //Display data Console.WriteLine(Encoding.ASCII.GetString(readBuf)); stm.Close(); } //end of try catch (Exception ex) { Console.WriteLine(ex.ToString()); } //end of catch } }}

Page 56: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Network Stream Clientusing System;using System.Collections.Generic;using System.Text;using System.Net;using System.IO;using System.Net.Sockets;

namespace TCPClient{ class Program { static void Main(string[] args) { try { //Create TCP Client TcpClient client = new TcpClient();

Page 57: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Network Stream Client //Connect using hostname and port client.Connect("localhost", 5001); //Get network stream instance for sending data NetworkStream ns = client.GetStream(); //Now that we have our NetworkStream, sending data follows

the same process as we've used with the other streams byte[] sendBytes = Encoding.ASCII.GetBytes("This data has

come from another place!"); ns.Write(sendBytes, 0, sendBytes.Length); //Finally, close our client client.Close(); } //end of try catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("The listener has probably not

started."); } //end of catch

} }}

Page 58: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

CryptoStream Class

• Secure data– Encrypt/decrypt with secret key

• CryptoStream derives from Stream class• CryptoStream constructor takes 3 parameters:

– Stream to be used– Cryptographic transformation– Specific read/write access to the cryptographic stream

• Any cryptographic service provider that implements the ICryptoTransform interface can be used

Page 59: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

CryptoStream Classusing System;using System.Collections.Generic;using System.Text;using System.IO;using System.Security.Cryptography;

namespace cryptDemo{ class Program { static void Main(string[] args) { SymmetricAlgorithm des = null; int answer = Menu(ref des); //A file stream is created to save encrypted data FileStream fs = new FileStream("SecretFile.dat", FileMode.Create, FileAccess.Write); //The interface helps define the basic operation of our cryptographic transformation ICryptoTransform desencrypt = des.CreateEncryptor(); //Wrap cryptoStream around fileStream CryptoStream cryptoStream = new CryptoStream(fs, desencrypt, CryptoStreamMode.Write); //Now we encrypt our message //Use a simple string which is converted into a byte array string theMessage = "A top secret message."; byte[] byteArrayInput = Encoding.Unicode.GetBytes(theMessage); Console.WriteLine("Original Message: {0}", theMessage);

Page 60: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

CryptoStream Class //Write byte array to cryptoStream cryptoStream.Write(byteArrayInput, 0, byteArrayInput.Length); cryptoStream.Close(); fs.Close();

//***********Time to Decrypt******************// //Create file stream to read encrypted file back FileStream fsRead = new FileStream("SecretFile.dat", FileMode.Open, FileAccess.ReadWrite); byte[] encByte = new byte[fsRead.Length]; fsRead.Read(encByte, 0, encByte.Length); Console.WriteLine("Encrypted Message: {0}", Encoding.ASCII.GetString(encByte)); //set the position of the within the filestream back to 0 before decrypting fsRead.Position = 0; //Create DES Decryptor from our des instance ICryptoTransform desdecrypt = des.CreateDecryptor(); CryptoStream cryptoStreamDecr = new CryptoStream(fsRead, desdecrypt, CryptoStreamMode.Read); byte[] decrByte = new byte[fsRead.Length]; cryptoStreamDecr.Read(decrByte, 0, (int)fsRead.Length); string output = Encoding.Unicode.GetString(decrByte); Console.WriteLine("Decrypted Message: {0}", output); cryptoStreamDecr.Close(); fsRead.Close(); Console.WriteLine("Press a key to continue."); Console.ReadLine(); } //end of Main

Page 61: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

CryptoStream Classprivate static int Menu(ref SymmetricAlgorithm des){ bool isCorrect = true; int answer = 0; //Ask the user to choose a service provider //All service providers derived from the SymmetricAlgorithm class have a single secret key

that is used for both encrypting and decrypting do { isCorrect = true; Console.WriteLine("Select Service Provider for CryptoStream:"); Console.WriteLine("1 = DESCryptoServiceProvider"); Console.WriteLine("2 = RC2CryptoServiceProvider"); Console.WriteLine("3 = RijndaelManaged"); Console.WriteLine("4 = TripleDESCryptoServiceProvider"); Console.WriteLine("5 = SymmetricAlgorithm"); Console.Write("Enter your choice: ");

//create des object switch (Console.ReadLine()) { case "1": des = new DESCryptoServiceProvider(); answer = 1; break; case "2": des = new RC2CryptoServiceProvider();

Page 62: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

CryptoStream Class answer = 2; break; case "3": des = new RijndaelManaged(); answer = 3; break; case "4": des = new TripleDESCryptoServiceProvider(); answer = 4; break; case "5": des = SymmetricAlgorithm.Create(); answer = 5; break; default: { Console.WriteLine("Wrong Selection"); isCorrect = false; break; } //end of default } //end of switch } while (!(isCorrect)); return answer; } //end of Menu }}

Page 63: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Basic Outline

• Streams in .NET

• Stream Manipulation– Introduction– Encoding String Data– Binary Files– Text Reader– Text Writer

• Serialisation

Page 64: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Stream Manipulation

• System.IO namespace provides classes and methods for manipulating different data types in streams

Page 65: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Encoding String Data

• Without knowing what the bytes mean, transmitted data is meaningless

• Encoding Class in System.Text– Handles UNICODE characters

Page 66: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Encoding Classes and UsesASCIIEncoding encodes Unicode characters as single 7-bit ASCII characters. This encoding only

supports character values between U+0000 and U+007F. Code page 20127. Also available through the ASCII property. This encoding has limitations because it supports 7-bit character values, and it is not a good choice for applications that support multilingual text processing

UTF7Encoding encodes Unicode characters using the UTF-7 encoding. This encoding supports all Unicode character values. Code page 65000. Also available through the UTF7 property. (UTF stands for Universal Translation Format). It is a commonly used format to send Unicode-based data across networks.

UTF8Encoding encodes Unicode characters using the UTF-8 encoding. This encoding supports all Unicode character values. Code page 65001. Also available through the UTF8 property. This class supports 8-bit encoding, or UTF-8. This encoding is widely used with applications that support multilingual text processing. XML uses UTF-8 by default.

UnicodeEncoding encodes Unicode characters using the UTF-16 encoding. Both little-endian (code page 1200) and big-endian (code page 1201) byte orders are supported. Also available through the Unicode property and the BigEndianUnicode property.

UTF32Encoding encodes Unicode characters using the UTF-32 encoding. Both little-endian (code page 65005) and big-endian (code page 65006) byte orders are supported. Also available through the UTF32 property.

Page 67: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Encoding Class Methods

Name Description

Clone When overridden in a derived class, creates a shallow copy of the current Encoding object.

Convert Overloaded. Converts a byte array from one encoding to another.

Equals Overloaded. Overridden.  

GetByteCountOverloaded. When overridden in a derived class, calculates the number of bytes produced by encoding a set of characters.

GetBytesOverloaded. When overridden in a derived class, encodes a set of characters into a sequence of bytes.

GetCharCountOverloaded. When overridden in a derived class, calculates the number of characters produced by decoding a sequence of bytes.

GetCharsOverloaded. When overridden in a derived class, decodes a sequence of bytes into a set of characters.

GetDecoderWhen overridden in a derived class, obtains a decoder that converts an encoded sequence of bytes into a sequence of characters.

GetEncoderWhen overridden in a derived class, obtains an encoder that converts a sequence of Unicode characters into an encoded sequence of bytes.

GetEncoding Overloaded. Returns an encoding for the specified code page.

Page 68: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Encoding Class Methods

Name Description

GetEncodings Returns an array containing all encodings.

GetHashCode Overridden. Returns the hash code for the current instance.

GetMaxByteCountWhen overridden in a derived class, calculates the maximum number of bytes produced by encoding the specified number of characters.

GetMaxCharCountWhen overridden in a derived class, calculates the maximum number of characters produced by decoding the specified number of bytes.

GetPreambleWhen overridden in a derived class, returns a sequence of bytes that specifies the encoding used.

GetString Overloaded. When overridden in a derived class, decodes a sequence of bytes into a string.

GetType  Gets the Type of the current instance. (Inherited from Object.)

IsAlwaysNormalized Overloaded. Gets a value indicating whether the current encoding is always normalized.

ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)

ToString  Returns a String that represents the current Object. (Inherited from Object.)

Page 69: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Encoding String Datausing System;using System.Text;using System.IO;

namespace EncodingStringData{ class Program { static void Main(string[] args) { string test = "This is our test string.";

byte[] asciiBytes; byte[] unicodeBytes; byte[] UTF7Bytes; //convert our test string into the three different encodings

asciiBytes = Encoding.ASCII.GetBytes(test); Console.WriteLine("ASCII Byte String"); Console.WriteLine("ASCII Encoding: {0} bytes", asciiBytes.Length); DisplayArray(asciiBytes); Console.WriteLine("Effect of converting to ASCII"); string asciiString = Encoding.ASCII.GetString(asciiBytes); Console.WriteLine(asciiString);

Console.WriteLine();

Page 70: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Encoding String Data unicodeBytes = Encoding.Unicode.GetBytes(test);

Console.WriteLine("Unicode Byte String"); Console.WriteLine("Unicode Encoding: {0} bytes", unicodeBytes.Length); DisplayArray(unicodeBytes); Console.WriteLine("Effect of converting to Unicode"); string unicodeString = Encoding.ASCII.GetString(unicodeBytes); Console.WriteLine(unicodeString);

Console.WriteLine();

UTF7Bytes = Encoding.UTF7.GetBytes(test); Console.WriteLine("UTF7 Byte String"); Console.WriteLine("UTF7 Encoding: {0} bytes", UTF7Bytes.Length); DisplayArray(UTF7Bytes); Console.WriteLine("Effect of converting to UTF7"); string utf7String = Encoding.ASCII.GetString(UTF7Bytes); Console.WriteLine(utf7String);

Console.WriteLine();

Console.WriteLine("Press a key to continue."); Console.ReadLine();

}

Page 71: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Encoding String Data

static void DisplayArray(byte[] b) {

for (int i = 0; i < b.Length; i++)

Console.Write(b[i] + " ");

Console.WriteLine();

} //end of DisplayArray

}

}

Page 72: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Basic Outline

• Streams in .NET• Stream Manipulation

– Introduction– Encoding String Data– Binary Files

• BinaryReader• BinaryWriter

– Text Reader– Text Writer

• Serialisation

Page 73: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Binary Files

• System.IO namespace contains– BinaryReader– BinaryWriter

• Used for working with primitive data types from streams

• Each class is created around an existing Stream

Page 74: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

BinaryReader

• Default is UTF-8 encoding• Custom encoding is possible (at instantiation)• BinaryReader

– Read• Read bytes from the stream and advances the position in the

stream, returning -1 if the end of the stream is reached

– PeekChar• To read without advancing the position in the stream• Returns -1 if the end of the stream is reached or if the stream

does not support seeking

Page 75: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Binary Reader MethodsName Description

Close Closes the current reader and the underlying stream.

Equals  Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetHashCode 

Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetType  Gets the Type of the current instance. (Inherited from Object.)

PeekChar Returns the next available character and does not advance the byte or character position.

Read Overloaded. Reads characters from the underlying stream and advances the current position of the stream.

ReadBoolean Reads a Boolean value from the current stream and advances the current position of the stream by one byte. Bytes read from Stream = 1.

ReadByte Reads the next byte from the current stream and advances the current position of the stream by one byte. Bytes read from Stream = 1.

ReadBytes (int count)

Reads count bytes from the current stream into a byte array and advances the current position by count bytes. Bytes read from Stream = count.

ReadChar Reads the next character from the current stream and advances the current position of the stream in accordance with the Encoding used and the specific character being read from the stream. Bytes read from Stream depends on the encoding used.

Page 76: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Binary Reader MethodsName Description

ReadChars Reads count characters from the current stream, returns the data in a character array, and advances the current position in accordance with the Encoding used and the specific character being read from the stream.

ReadDecimal Reads a decimal value from the current stream and advances the current position of the stream by sixteen bytes. Bytes read from Stream = 16.

ReadDouble Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes. Bytes read from Stream = 9.

ReadInt16 Reads a 2-byte signed integer from the current stream and advances the current position of the stream by two bytes. Bytes read from Stream = 2.

ReadInt32 Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes. Bytes read from Stream = 4.

ReadInt64 Reads an 8-byte signed integer from the current stream and advances the current position of the stream by eight bytes. Bytes read from Stream = 8.

ReadSByte Reads a signed byte from this stream and advances the current position of the stream by one byte.

ReadSingle Reads a 4-byte floating point value from the current stream and advances the current position of the stream by four bytes. Bytes read from Stream = 4.

ReadString Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time. Bytes read from Stream depends on the length of the string.

ReadUInt16 Reads a 2-byte unsigned integer from the current stream using little endian encoding and advances the position of the stream by two bytes.

Page 77: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Binary Writer

• Used for writing primitive types in binary format to a stream

• Writing to the stream is achieved with the Write method.

• To move around the stream, the Seek method sets the position in the Stream as with the Seek method of the Stream.

• Standard management methods utilised– Close– Flush

Page 78: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Binary Reading and Writing Example

using System;using System.IO;

namespace BinaryReaderAndWriter{ class Program { static void Main(string[] args) { double angle, sinAngle; //Create a file stream called fStream that creates a file called "Sines.dat" //Stream specifies write access FileStream fStream = new FileStream("Sines.dat", FileMode.Create, FileAccess.Write); BinaryWriter bWriter = new BinaryWriter(fStream); //We calculate the sine of angles between 0 and 90 degrees at 5 degree intervals //We have to convert the angle in degrees to radians before we can calculate the sine //Then we use Write to output these values to the stream

for (int i = 0; i <= 90; i += 5) { double angleRads = Math.PI * i / 180; sinAngle = Math.Sin(angleRads); bWriter.Write((double)i); bWriter.Write(sinAngle); } //end of for loop bWriter.Close(); fStream.Close();

Page 79: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Binary Reading and Writing Example

//----------Reading from File-------------- FileStream fStrm = new FileStream("Sines.dat", FileMode.Open, FileAccess.Read); BinaryReader bReader = new BinaryReader(fStrm); int endOfFile; //use the ReadDouble method to read the data back in //If this method tries to read beyond hte end of the stream, an exception will be thrown, //so we use the PeekChar method to detect the end of the file without advancing the position do { endOfFile = bReader.PeekChar(); if (endOfFile != -1) { angle = bReader.ReadDouble(); sinAngle = bReader.ReadDouble(); Console.WriteLine("{0} : {1}", angle, sinAngle); } //end of if } while (endOfFile != -1); bReader.Close(); fStrm.Close();

Console.Write("Press a key to continue."); Console.ReadLine(); } }}

Page 80: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Basic Outline

• Streams in .NET• Stream Manipulation

– Introduction– Encoding String Data– Binary Files– Text Reader

• Working with StreamReader

– Text Writer• Working with StreamWriter

• Serialisation

Page 81: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Text Reader

• Used for reading text or characters in a stream

• It’s an abstract class from which StreamReader and StringReader derive

• The text is read in by a StringReader is stored as a StringBuilder, rather than a plain string

Page 82: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

TextReader Class MethodsName Description

Close Closes the TextReader and releases any system resources associated with the TextReader.

CreateObjRef  Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)

Dispose Overloaded. Releases all resources used by the TextReader object.

Equals  Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

GetHashCode  Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetLifetimeService  Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

GetType  Gets the Type of the current instance. (Inherited from Object.)

Page 83: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

TextReader Class MethodsName Description

InitializeLifetimeService 

Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

Peek Reads the next character without changing the state of the reader or the character source. Returns the next available character without actually reading it from the input stream.

Read Overloaded. Reads data from an input stream.

ReadBlock Reads a maximum of count characters from the current stream and writes the data to buffer, beginning at index.

ReadLine Reads a line of characters from the current stream and returns the data as a string.

ReadToEnd Reads all characters from the current position to the end of the TextReader and returns them as one string.

ReferenceEquals  Determines whether the specified Object instances are the same instance. (Inherited from Object.)

Synchronized Creates a thread-safe wrapper around the specified TextReader.

ToString  Returns a String that represents the current Object. (Inherited from Object.)

Page 84: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Working with StreamReader

• Used to read characters from a byte stream

• Default is UTF-8 encoding

• Provides forward-only access to the stream

Page 85: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Examplepublic static string fileName = @"TextOut.txt";static void Main(string[] args){

Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

//Using Stream ObjectStreamReader sReader = new StreamReader(fs);string data;int line = 0;

while ((data = sReader.ReadLine()) != null){

Console.WriteLine("Line {0}: {1}: Position = {2}", ++line, data, sReader.BaseStream.Position);

//sReader.DiscardBufferedData();}

//Set position using seek property of underlying streamsReader.BaseStream.Seek(0, SeekOrigin.Begin);Console.WriteLine();Console.WriteLine("*Reading entire file using ReadToEnd\n" + sReader.ReadToEnd());sReader.Close();fs.Close();Console.Write("Press a key to continue.");Console.ReadLine();

}

Page 86: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

TextWriter

• Abstract class

• Outputs a sequential series of characters• StreamWriter and StringWriter are

derived from TextWriter

Page 87: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

TextWriter Class MethodsName Description

CloseCloses the current writer and releases any system resources associated with the writer.

CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)

Dispose Overloaded. Releases all resources used by the TextWriter object.

Equals Overloaded. Determines whether two Object instances are equal. (Inherited from Object.)

FlushClears all buffers for the current writer and causes any buffered data to be written to the underlying device.

GetHashCode Serves as a hash function for a particular type. GetHashCode is suitable for use in hashing algorithms and data structures like a hash table. (Inherited from Object.)

GetLifetimeService 

Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

GetType  Gets the Type of the current instance. (Inherited from Object.)

Page 88: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

TextWriter Class Methods

Name Description

InitializeLifetimeService 

Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)

ReferenceEquals Determines whether the specified Object instances are the same instance. (Inherited from Object.)

SynchronizedCreates a thread-safe wrapper around the specified TextWriter.

ToString Returns a String that represents the current Object. (Inherited from Object.)

Write Overloaded. Writes the given data type to a text stream.

WriteLineOverloaded. Writes some data as specified by the overloaded parameters, followed by a line terminator.

Page 89: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Working with StreamWriter

• Used for writing characters in a stream

• Default is UTF-8 Encoding• StreamWriter constructor is overloaded

– Can pass a stream object to a StreamWriter (gives greater control over file accessibility)

Page 90: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

StreamWriterstatic void Main(string[] args){

string s1 = "The length of a film should be directly related to the endurance of the human bladder. - Alfred Hitchcock.";string s2 = "USA Today has come out with a new survey: Apparently three out of four people make up 75 percent of the population.-David Letterman.";

Stream fs = new FileStream("TextOut.txt", FileMode.OpenOrCreate, FileAccess.Write);

//Using Stream Object StreamWriter sWriter = new StreamWriter(fs); //Display the encoding type

Console.WriteLine("Encoding Type: {0}", sWriter.Encoding.ToString()); //Display Format Provider Console.WriteLine("Format Provider: {0}",

sWriter.FormatProvider.ToString()); sWriter.WriteLine("Today is {0}.", DateTime.Today.DayOfWeek);

sWriter.WriteLine(s1);sWriter.WriteLine(s2);

Page 91: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

StreamWriterfor (int i = 0; i < 5; i++)

{sWriter.WriteLine("Value {0}, its square is {1}.", i, i

* i);} //end of for

//Writing arraysWriter.Write("Arrays can be written: ");

char[] myArray = new char[] { 'a', 'r', 'r', 'a', 'y' };sWriter.Write(myArray);

sWriter.WriteLine("\r\nAnd parts of arrays can be written.");sWriter.Write(myArray, 0, 3);

sWriter.Close(); fs.Close(); Console.WriteLine("Press a key to continue."); Console.ReadLine();}

Page 92: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Basic Outline

• Streams in .NET• Stream Manipulation

– Introduction– Encoding String Data– Binary Files– Text Reader– Text Writer

• Serialisation– Serialising into XML Format– Serialising with Formatter Objects

Page 93: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Serialisation

• Serialisation is the process of taking objects and converting their state information into a form that can be stored or transported.

• The stored or transported object can then be de-serialised to re-create the original state of object.

• Key areas where serialisation is beneficial– Object availability: A component can be saved in a file made

available whenever required– Object lifetime: Saving the object with its state increases its life.

In normal practice, when you close an application, all associated objects are destroyed automatically

– Object use within networked applications: The complex form of the object has been transformed to a format that is suitable for transferring across a network and possibly through firewalls

– Object reliability: The saved object can be re-created as is.

Page 94: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Serialising into XML format

• XML has advantages– Transform system-specific state information into text (which is

easily transported over a network)

• XML disadvantage– Does not preserve the type of the various fields involved (it

serialises properties/fields into XML format)

• XMLSerializer class in System.XML.Serialization namespace

• Rules for serializing a class– The class must support a default public constructor with no

parameters– Only public properties that support both get and set operations

and public data members are persisted

Page 95: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Serialisation using XML• The Customer class public class Customer { public int CustomerID; public string CustomerName; public DateTime SignUpDate; private decimal currentCredit; public void SetCurrentCredit(decimal c) { currentCredit = c; } public decimal GetCurrentCredit() { return currentCredit; } } //end of Customer

Notice the public and private fields

Page 96: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Serialising Customer to XMLusing System;using System.IO;using System.Text;using System.Xml.Serialization;static void Main(string[] args){

//prepare object for serialisationCustomer cm = new Customer();

cm.CustomerID = 12;cm.CustomerName = "Stuart Little";cm.SignUpDate = DateTime.Now;

cm.SetCurrentCredit(76.23M);

Console.WriteLine("Now Serialising..."); //Create Stream Writer object StreamWriter writer = new StreamWriter("Customer.xml"); //Create Serialiser XmlSerializer serializer = new XmlSerializer(typeof(Customer)); //Serialise the object serializer.Serialize(writer, cm);

writer.Close();

Page 97: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Serialising an object Console.WriteLine("Now Deserialising..."); //Open and create stream

Stream streamOut = new FileStream("Customer.xml", FileMode.Open, FileAccess.Read);

XmlSerializer deserial = new XmlSerializer(typeof(Customer)); //Deserialise the sotred stream Customer recm = (Customer)deserial.Deserialize(streamOut); streamOut.Close(); //Display sate of object Console.WriteLine("Customer ID = {0}", recm.CustomerID); Console.WriteLine("Customer name = {0}", recm.CustomerName); Console.WriteLine("Sign up Date = {0}", recm.SignUpDate);

Console.WriteLine("Current Credit = {0}", recm.GetCurrentCredit());

Console.ReadLine();}

Page 98: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Serialising with Formatter Objects

• Within the System.Runtime.Serialization.Formatters namespace lie the tools for serializing object state into formats such as binary or SOAP

• The BinaryFormatter class provides functionality for serializing objects into binary format, and the SoapFormatter class serialises into the SOAP format

• Binary format serialises object state and also assembly information allowing exact reproduction of an object and its types. It also produces a compact format

• The SOAP format is more verbose (wordy), but it allows your object state to be passed to a web service

Page 99: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

The Steps for serialising an object/class

• Mark the class with the [Serializable] attribute to make it serializable

• Prepare the object’s state for serialization• Create a new formatter object: BinaryFormatter for binary format or SoapFormatter for SOAP

• Call the Serialize method of the formatter object, passed in the stream to which to output the results and the object to be serialized

Page 100: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Deserializing

• Specify the format for deserializing the object with the relevant formatter object

• Call the Deserialize method of this formatter object

• Cast the object returned to the type you wish to re-create

Page 101: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Serializing

• The [Serializable] attribute is not inherited, thus derived types are not automatically serialisable.

• To protect confidential data, you can make a field [NonSerialized] – any such fields will not be serialised (says the book – need further testing to verify)

Page 102: Network Programming Chapter 2 Streams in.NET. Basic Outline Streams in.NET Stream Manipulation Serialisation.

Summary