Hey Now Everybody,
Section 4 Study Notes from Implementing serialization and input/output functionality in a .NET Framework app
Please feel free to check out my MCTS 70-536 reference page on Chris Catto.com. It’s a page with a summary of all of my posts.
As I study for this test I thought this would be good to post on to learn the content & others would be able to view & comment on it.
This content below is from some practice questions from the book exam.Please feel free to comment.
Thx,
Catto
Implementing serialization and input/output functionality in a .NET Framework app
- Per-user storage – is appropriate for isolated storage
- Isolated storage is perfect for storing data that should be kept separate for different users
- The following ways isolated storage can be separated by:
- User
- Assembly
- Application Domain
- Isolated Storage is always separated by user & assembly. It can also be separated by application domain.
- The following classes you can use when serializing data to be consumed by applications running on a UNIX-based OS:
- SoapFormatter
- XmlSerializer
- Both SoapFiormatter & XMLSerializer serialize data using open standards that other platforms can consume.
- BinaryFormatter provides very efficient serialization, but it is not open-standards based
- Iserializable is an interface that you can use to implement custom serialization. You cannot use it directly to perform serialization
- SerializationBinder allows users to control class loading & mandate what class to load. You cannot use it to perform serialization.
- FileSystemWatcher.Created – occurs when a file or directory in the specified path is created.
- When you are writing an app that needs to process files when they are added to a folder. FileSystemWatcher.Created is the event you should be respond to.
- FileSystemWatcher.Changed only occurs when an existing file is modified.
- FileSystemWatcher.Deleted occurs when a file is removed.
- FileSystemWatcher.Renamed occurs when a file is renamed
- Serialized event occurs immediately after serialization
- Serialized is the serialization event that you should respond to if you need to run code after serialization occurs when creating a class that implements the ISerializable interface.
- Serializing event occurs prior to serialization
- Deserializing event occurs prior to deserialization
- Deserializied event occurs immediately after serialization.
- OptionalField – attribute prevents deserialization from throwing an exception if the member is not present while still serializing the member.
- You are adding a new member to class that is already in use. You want to provide backward compatibility with serialized data that was created before the member was added. Which attribute would you add to the new member so that it would be serialized in the future, but deserialization would not throw an exception if the member class was not present in the serialized data? OptionalField
- ISerializable & IDeserializationCallback are interfaces that you can implement when you need to control the serialization process
- NonSerialized attribute would prevent the runtime from throwing an exception if the member was not present, however, it Also prevents the member from being serialized.
- BinaryFormatter – Only the BinaryFormatter class supports serialization events
- When creating a class that responds to serialization events BinaryFormatter class will trigger the serialization events.
- The SoapFormatter class does not support serialization events
- XMLSerializer does not support serialization events
- IFormatter is an interface & cannot be directly used to perform serialization.
- During Deserialization, track which objects have been deserialized & which are pending. This is a task performed by the ObjectManager class as part of serialization.
- The ObjectManager class keeps track of objects as they are deserialized.
- Classes that interact with the file system
- StreamReader
- FileStream
- You can directly interact with the file system by using FileStream or StreamReader
- MemoryStream & StringReader both interact w/ Memory not the file system. SslStream interacts with a remote host
- When you need to create a text file using the static FileCreateText.method the following values are acceptable parameters:
- C:\text.txt
- \\server\text.txt
- File.CreateText can accept local file paths or universal naming convention (UNC) paths
- File.CreateText cannot accept URL’s
- You have written an app that stores compressed data using the DeflateStream class. The following methods you can use to open the compressed file:
- Read the file from a .NET app using the DeflateStream class
- DeflateStream does not use the commonly used zip format nor is it natively supported by Windows Explorer. Therefore, only other .NET applications can read the compressed data
- WinZip cannot open the compressed with DeflateStream
- Compressed Folders cannot open files compressed with DeflateStream
- Notepad cannot open files compressed with DeflateStream
- Read the file from a .NET app using the DeflateStream class
- You are writing a class that implements the ISerializable interface. Which of the following are requirements for a method that responds to the Deserialized event?
- Accepts a StreamingContext object as a parameter
- Returns a void
- Methods that respond to serialization events must accept a Streaming Context object as a parameter & return void.
- A method cannot respond to a serialization event if it accepts zero parameters. It must accept a StreamingContext object
- Methods that respond to serialization events cannot return a StreamingContext object. They must return void.
- A method cannot respond to a serialization event if it accepts a SerializationInfo object. It must accept a SerializationInfo Object. It must accept a StreamingContext object
- You would use the System.IO.Path to test the past users provide when writing an app that will run on a computer that acts as kiosk. Users should be able to save files to the local disk, but users should only be able to specify a relative path to their files, you don’t want users to be able to specify an absolute path. You can test a path to determine weather it is absolute or relative by calling the Path.IsPathRooted method
- System.IO.Directory contains static methods for processing directories, but it does not enable you to test whether a pst is absolute.
- System.IO.DirectoryInfo provides directory management capabilities, but it does not enable you to test whether a past is absolute.
- SystemIO.DriveInfo enables you to examine the properties of a drive, & does not enable you to test whether a path is absolute.
- Serializing – you are creating a class that implements the ISerializable interface. Serializing is the serialization event should you respond to if you need to run code prior to serialization.
- Serializing event occurs prior to serialization
- Serialized event occurs immediaFtely after serialization
- Deserializing event occurs prior to deserialization
- Deserialized event occurs immediately after serialization.
- You need to define a value that is not available in the serialized data is a valid reason to Implement the ISerializable interface & respond to the Deserialized event
- You should respond to the Deserialized event when you need to define a value that was not contained in the serialized data. Typically, summary values such as totals are not serialized & must be defined by responding to the Deserialized event.
- The Deserialized event occurs after deserialization & cannot be used to read custom formatting in serialized data.
- XML serialization does not support serialization events.
- To define a value prior to serialization, you should repond to the Serializing event, not the Deserialized event.
- Deserialized –is the serialization event you should respond to if you need to initialize a variable after deserialization occurs when you are creating a class that implements the ISerializable interface.
- Deserialized event occurs immediately after serialization
- Serializing event occrs prioer to serialization
- Serialized event occurs immediately after serialization
- Deserializing event occurs prior to deserialization
- Xsd.exe – is a tool you would use to create a class that, when serialiezed using XMlSerializer, would conform to a specific schema.
- If you have an XML Schema you can run the XML Schema Definition tool (Xsd.exe) to produce a set of classes that are strongly typed to the schema & annotated with attributes.
- XmlSerializer.exe, Schema.exe & Xml.exe are not .NET Framework tools.
- If you have an XML Schema you can run the XML Schema Definition tool (Xsd.exe) to produce a set of classes that are strongly typed to the schema & annotated with attributes.
- Deserializing – is the serialization event you should respond to if you need to initialize a variable before deserialization occurs when creating a class that implements the ISerializable interface.
- Deserializing event occurs prior to deserialization
- Serializing event occurs prior to serialization
- Serialized event occurs immediately after serialization
- Deserialized event occurs immediately after serialization
- The following are requirements for implementing custom serialization using the ISerializable interface:
- Override the GetObjectData method
- Implement a constructor that accepts SerializationInfo & StreamingContext object as parameters.
- To implement ISerializable, you must override the GetObjectData method & create a constructor that accepts SerializationInfo & StreamingContext objects as parameters.
- You can respond to the Serializing & Deserializing events, but it is not a requirement
- You can respond to the Serialized & Deserialized events, but it is not a requirement
- You must override the OnDeserialization method when you implement the IDeserializationCallback interface. It is not a member of the ISerializable interface.
- IFormatter – interface you should implement when you are writing an application that uses serialization & you need complete control over how the serialized data is formatted.
- You should implement the IFormatter interface, which is the same interface that BinaryFormatter & SoapFormatter implement.
- IFormatterConverter includes methods for converting values between core types, such as converting a Decimal to a Double or a signed integer to an unsigned integer. You typically do not need to implement the IFormatterConverter interface when using serialization.
- You should implement ISerializable when you need to control the serialization process, but not when you need to control the formatting of the actual serialized data
- You should implement IDeserializationCallback when you need to calculate the value of a member after deserialization. You cannot control formatting with IDeserializationCallback.
- You should implement the IFormatter interface, which is the same interface that BinaryFormatter & SoapFormatter implement.
- XmlSerializer – is the most efficient way to write an object to an XML document. ex. You are responsible for an internal database application. Your organization would now like to selectively send information from the database to external customers using XML documents. Currently you have custom classes that stroe this information. XmlSerializer is the class you should use to write the XML docs.
- BinaryFormatter would write the object to disk, but it would not use XML
- TextWriter & StreamWriter could be used to create XML docs, but it would be very inefficient because you would have to create the XML formatting manually.
- StreamingContext is the type of object you would use during custom serialization to determine how the serialized data will be transferred & used. The StreamingContext structure describes the source & destination of a given serialized stream & provides an additional caller defined context. However, the method performing the serialization must define the StreamingContext structure it does not happen automatically.
- The SerializationEntry structure holds the value type & name of a serialized object. It does not describe the context of serialization
- SerializationInfo class stores all the data needed to serialize or deserialized an object. It does contain a StreamingContext structure as a member, but you would need to directly access the StreamingContext object to determine how serialization data will be transferred.
- ObjectManager class keeps track of objects as they are deserialized & does not describe the serialization context.
- Storeadm – is a command that you would use to view isolated storage stores.
- Storeadm tool is a command line tool for listing & deleting isolated storage stores. Use the command storeadm / list to view stores & storeadm / remove to delete stores.
- NonSerialized attribute you would add to a member class to prevent if from being serialized.
- NonSerialized attribute prevents a member from being serialized.
- Iserializable & IDeserializationCallback are interfaces that you can implement when you need to control the serialization process.
- OptionalField does not affect the serialzation of a member. OptionalField affects only deserialization by preventing the runtime from throwing an exception if the member is not present in serialized data.
- IDeserializationCallback is the interface you would use to most efficiently automatically initialize a nonserialized member when Deserializing data.
- The simplest way to initialize nonserialized members is to implement the IDeserialiationCallback interface & override the OnDeserialization method
- The IFormatter interface provides functionality for formatting serialized objects, but it is not the most efficient way to initialize nonserialized members
- The ISerializable interface allows an object to control its own serialization & deserialization, however, it is not the most efficient way to initialize nonserialized members.
- IFormatterConverter interface provides the connection between an instance of SerializationInfo & the formatter-provided class best suited to parse the data inside SerializationInfo. It cannot be used to initialize nonserialized members.
- 4GB is the maximum file size you can compress by using the DeflateStream class
- Byte array – FileStream.Write only supports byte arrays. To write other types, create a Writer class based on the FileStream object such as StreamWriter, BinaryWriter or TextWriter. data
- You can create a custom class when you need to implement a custom compression algorithm in a custom class by the following:
- Derive from GZipStream
- Derive from DeflateStream
- You can derive from GZipStream or DeflateStream, GZipStream is base on the GZip algorithm, whi8le DeflateStream is base on the Deflate algorithm, Alternatively, you could create an entirely unique compression algorithm by implementing the Stream interface.
- BinaryFormatter – class you should use when serializaiing data to be consumed only by .NET Apps
- BinaryFormatter provides the best efficiency when only .NET apps will consume the serialized data
- SoapFormatter provides standards-based serialization, but it is not as efficient as BinaryFormatter.
- ISerializable is an interface you can use to implement custom serialization. You cannot use it directly to perform serialization.
- XmlSerializer provides standards based serialization, but it si not as efficient as BinaryFormatter.
- You are working with your IT department to deploy an application that you wrote. The IT department asks if your application needs access to any folders on the local hard disk. Your application only uses isolated storage. Your application will be deployed only to Microsoft new computers running Windows XP. Your IT department does not use roaming profiles. To which folder does your application require access?
- Answer
- <systemdrive>\Documents and Settings\<user>\ Local Settings\Application Data
- Explanation: Ch 2 Lesson 4
- On Windows XP computers that were not upgraded and do not use roaming profiles, isolated storage is physically located in the <systemdrive>\Documents and Settings\<user>\ Local Settings\Application Data folder.
- The <systemroot>\Profiles\<user>\Application Data folder is used by Windows 2000, Windows XP, and Windows Server 2003 when upgraded from Windows NT 4.0 in environments that use roaming profiles
- The <systemroot>\Application Data folder is used by Microsoft Windows 98 and Windows ME without user profiles.
- The <systemroot>\Documents and Settings\<user>\Application Data folder is used by Windows XP and Windows Server 2003, when upgraded from Windows 2000 and Windows 98, or when not upgraded in environments that use roaming profiles.
- You are working with your IT department to deploy an application that you wrote. The IT department asks if your application needs access to any folders on the local hard disk. Your application only uses isolated storage. Your application will be deployed only to Microsoft Windows XP computers that had been upgraded from Windows 2000. Your IT department does use roaming profiles. To which folder does your application require access?
- <systemroot>\Documents and Settings\<user>\Application Data
- Explanation: Ch 2 Lesson 4
- The <systemroot>\Documents and Settings\<user>\Application Data folder is used by Windows XP when upgraded from Windows 2000 in environments that use roaming profiles.
- On Windows XP computers that were not upgraded and do not use roaming profiles, isolated storage is physically located in the <systemdrive>\Documents and Settings\<user>\ Local
- Settings\Application Data folder.
- The <systemroot>\Profiles\<user>\Application Data folder is used by Windows 2000, Windows XP, and Windows Server 2003 when upgraded from Windows NT 4.0 in environments that use roaming profiles.
- The <systemroot>\Application Data folder is used by Microsoft Windows 98 and Windows ME without user profiles.
- Which of the following code samples is the most efficient way to rename a file from "File1.txt" to "File2.txt"?
' VB
File.Move("File1.txt", "File2.txt")
- Explanation: Ch2 Lesson 1
- Use the static System.IO.File.Move method to rename files.
- There is no File.Rename method. You should use File.Move instead.
- Although copying and then deleting a file does effectively rename the file, it is not the most efficient way to rename a file.
- Use File.Replace to copy a file while overwriting the destination file. File.Replace does not rename files.
- Which of the following code samples correctly creates a new file named "Hello.dat" and writes the string "Hello, world!" to it?
' VB
Dim fs As New FileStream("Hello.dat", FileMode.CreateNew)
Dim bw As New BinaryWriter(fs)
bw.Write("Hello, World!")
bw.Close()
fs.Close()
Explanation: Ch2 Lesson 2
To write to a file with BinaryWriter, first create a FileStream object and use that to create the BinaryWriter object. Then call the BinaryWriter.Write method. Finally, close both the BinaryWriter object and the FileStream object.
You can write directly to a FileStream object; however, the FileStream.Write method does not accept a string parameter.
You cannot use a BinaryWriter object without creating a FileStream object first.
- Which of the following code samples writes a string to a text file? (Choose all that apply.)
' VB
Dim s As String = "Hello, World!"
File.WriteAllText("Text.txt", s)
' VB
Dim s As String = "Hello, World!"
Dim sw As StreamWriter = New StreamWriter("Text.txt")
Try
sw.WriteLine(s)
Finally
Sw.Close()
End Try
Explanation: Ch 2 Lesson 1
To write a string to a file, you can call the static File.WriteAllText method or you can create a StreamWriter object.
The String class does not have a WriteFile method.
The File class contains only static methods; you cannot create an instance of the File class.
- Which of the following is the most efficient way to create a name for a new temp file?
- ' VB
- Path.GetTempFileName()
- Explanation: Ch2 lesson 1
- Path.GetTempFileName() is the most efficient way to identify a name for a new temp file.
- Combining both Path.GetTempPath() and Path.GetTempFileName() is unnecessary because Path.GetTempFileName() already includes the path.
- Given the following class, which of the following files represents how an instance of that class would be serialized using the XmlSerializer class?
' VB
Public Class ShoppingCartItem
Public productId As Int32
Public price As Decimal
Public quantity As Int32
Public total As Decimal
Public Sub New()
MyBase.New
End Sub
End Class
Answer
<?xml version="1.0" ?>
<CartItem>
<productId>100</productId>
<price>10.25</price>
<quantity>2</quantity>
</CartItem>
Explanation: Ch5 Lesson 2
· The specified attributes change the root XML element to CartItem from the default ShoppingCartItem, and they cause the total to be ignored during serialization.
· By default, XmlSerializer serializes all members as elements, not attributes.
· By default, XmlSerializer serializes all members as elements, not attributes. Additionally, the total member would be left out of serialization.
· The specified attributes change the root XML element to CartItem from the default ShoppingCartItem.
- Given the following class, which of the following files represents how an instance of that class would be serialized using the XmlSerializer class?
' VB
Public Class ShoppingCartItem
Public productId As Int32
Public price As Decimal
Public quantity As Int32
Public total As Decimal
Public Sub New()
MyBase.New
End Sub
End Class
· Answer:
<?xml version="1.0" ?>
<ShoppingCartItem>
<productId>100</productId>
<price>10.25</price>
<quantity>2</quantity>
<total>20.50</total>
</ShoppingCartItem>
· Explaination: Ch 5 Lesson 2
· By default, XmlSerializer serializes all members as XML elements.
· XmlSerializer serializes members as attributes only if each member has the XmlAttribute attribute.
· XmlSerializer would ignore the total member only if it had the XmlIgnore attribute.
· XmlSerializer creates an element for the class and makes each member a subelement within the class element.
- You are developing version 2.0 of your application. One of the changes you are making is to change the file extension of a configuration settings file from .txt to .dat. The contents of the file do not need to change--just the file extension itself. In the following code samples, the current path and filename are stored in the String named "sn". Which of the following is the most reliable way to change the file extension?
' VB
File.Move(sn, Path.ChangeExtension(sn, "dat"))
Explanation: Ch2 Lesson 1
Combining the static File.Move method with the static Path.ChangeExtension method is the most efficient and reliable way to change the extension of a file.
Path.ChangeExtension does not directly make changes to the file system.
Providing a wildcard to the File.Move method results in an exception because the destination path includes an illegal character.
Using String.Replace to change the extension would work in most circumstances. However, if the filename included another occurrence of "txt" (for example, if the file were named "mytxt.txt"), both occurrences of "txt" would be changed.
- You are creating a class that implements the ISerializable interface to perform custom serialization. Which of the following code samples correctly overrides the GetObjectData method and serializes the firstName, lastName, and age values?
' VB
Public Overridable Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData
info.AddValue("First Name", firstName)
info.AddValue("Last Name", lastName)
info.AddValue("Age", age)
End Sub
Explanation: Ch 5 lesson 3
Methods that override GetObjectData must accept a SerializationInfo object and a SerializationContext structure as parameters. To add values to be serialized, call the SerializationInfo.AddValue method.
You cannot add data to be serialized to a StreamingContext object.
You cannot add data to be serialized to a SerializationInfo member. Additionally, the GetObjectData method must accept a SerializationInfo object and a SerializationContext structure as parameters.
The GetObjectData method must accept a SerializationInfo object and a SerializationContext structure as parameters.
- You need to create a directory if it does not yet exist. Of the following code samples, which most efficiently creates a directory without throwing an exception if it already exists? If more than one code sample would work correctly, choose the sample that performs the desired task with the fewest lines of code.
- ' VB
- Directory.CreateDirectory("C:\dir\")
- Explanation: Ch 2 Lesson 1
- All of these code samples creates a directory without causing the runtime to throw an exception if the directory already exists. The most efficient technique is to call the static Directory.CreateDirectory
- Calling DirectoryInfo.Create does create a directory without causing the runtime to throw an exception if the directory already exists. However, the most efficient technique is to call the static Directory.CreateDirectory method.
- It is unnecessary to test whether a directory already exists before creating it.
- Which of the following code samples does not result in an exception being thrown if the directory "C:\Dir\" does not exist? (Choose all that apply.)
' VB
Dim d As String = "C:\dir\"
Dim di As DirectoryInfo = New DirectoryInfo(d)
If di.Exists Then
Dim sw As StreamWriter = New StreamWriter(d + "Text.txt")
sw.WriteLine("Hello, World!")
End If
' VB
Dim d As String = "C:\dir\"
If Directory.Exists(d) Then
Dim sw As StreamWriter = New StreamWriter(d + "Text.txt")
sw.WriteLine("Hello, World!")
End If
Explanation: Ch 2 Lesson 1
To check whether a directory exists, you can call the static Directory.Exists method, or you can create a DirectoryInfo object and call DirectoryInfo.Exists.
The StreamWriter constructor cannot automatically create a directory if the specified directory does not exist. Therefore, the runtime throws an exception.
This code sample tests attempts to create a file only if the directory does not exist. Therefore, it will always throw an exception.
- Which of the following code samples correctly deserializes the current date and time from an XML file?
- ' VB
- Dim fs As FileStream = New FileStream("SerializedDate.XML", FileMode.Open)
- Dim xs As XmlSerializer = New XmlSerializer(GetType(DateTime))
- Dim t As DateTime = CType(xs.Deserialize(fs),DateTime)
- Explanation: Ch 5 Lesson 2
- To deserialize an object, first create a Stream, TextReader, or XmlReader object to read the serialized input. Then create an XmlSerializer object (in the System.Xml.Serialization namespace) by passing it the type of object you plan to deserialize. Finally, call the XmlSerializer.Deserialize method to deserialize the object, and cast it to the correct type.
- No overload for the XmlSerializer constructor takes zero parameters.
- There is no static XmlSerializer.Read method.
- The XmlSerializer constructor requires a Type object and cannot accept a FileStream object.
- How would you rewrite the following piece of code to store the information in isolated storage, isolated by user, domain, and assembly? Assume all code samples use the System.IO and System.IO.IsolatedStorage namespaces.
- ' VB
- Dim sw As StreamWriter = File.CreateText("mytemp.txt")
- sw.WriteLine("Hello, world!")
- sw.Close()
- Explanation: Ch 2 Lesson 4
- The easiest way to rewrite code that uses StreamWriter objects to use isolated storage is to use the overloaded StreamWriter constructor that accepts an IsolatedStorageFileSystem object.
- IsolatedStorageFileSystem does not have a WriteLine method.
- You cannot pass an IsolatedStorage object to the StreamWriter constructor.
- The File class does not have a static CreateIsolatedStorageText method.
- You need to verify that the C:\ drive is a fixed drive and throw an exception if it is not. Which of the following code samples accomplishes this in the most efficient manner?
- ' VB
- Dim di As DriveInfo = New DriveInfo("C")
- If Not (di.DriveType = DriveType.Fixed) Then
- Throw New Exception("The C:\ drive must be fixed")
- End If
- Explanation: Ch 2 Lesson 1
- To determine if a drive is fixed, create an instance of the DriveInfo class and then check DriveInfo.DriveType.
- DriveInfo does not have a static GetDriveType method.
- The DriveInfo.GetDrives static method does not accept a drive letter as a parameter.
- The DriveInfo.GetDrives static method returns a standard, integer-indexed array of DriveInfo objects. The array cannot be accessed with the drive letter.
- You are writing a security tool that aggregates firewall logs from client computers in your organization. IT will distribute your application to the approximately 2,000 client computers. Then the client portion of the application will run nightly to compress the %windir%\pfirewall.log file and copy it to a shared folder. After the file has been stored on the server, a separate server application will decompress and process the log files. Which of the following code samples correctly compresses and stores the logfile?
- ' VB
- Dim readpath As String = Path.Combine(System.Environment.GetEnvironmentVariable("windir"), "pfirewall.log")
- Dim writepath As String = "\\server\folder"
- Dim reader As FileStream = New FileStream(readpath, FileMode.Open)
- Dim writer As FileStream = New FileStream(writepath, FileMode.Create)
- Dim compress As DeflateStream = New DeflateStream(writer, CompressionMode.Compress)
- Dim b(reader.Length) As Byte
- reader.Read(b, 0, CType(reader.Length, Integer))
- reader.Close
- compress.Write(b, 0, CType(b.Length, Integer))
- compress.Close
- Explanation: Ch2 lesson 3
- To accomplish this task, you must create streams for both reading and writing the file. Then, based on the stream for writing the file, you can create a DeflateStream instance. Because DeflateStream requires a byte array, you must first read the contents of the file to be compressed into the byte array.
- The FileStream class does not have a ReadToEnd method. Additionally, the DeflateStream.Write() method can only accept a byte array. Finally, you cannot provide a file path to the DeflateStream constructor. You must first construct a stream object.
- Which of the following code samples correctly serializes the current date and time to an XML file?
- ' VB
- Dim fs As FileStream = New FileStream("SerializedDate.XML", FileMode.Create)
- Dim xs As XmlSerializer = New XmlSerializer(GetType(DateTime)
- xs.Serialize(fs, System.DateTime.Now)
- Explanation: Ch 5 Lesson 2
- To perform XML serialization, first create a FileStream, TextWriter, or XmlWriter object to hold the serialized output. Then create an XmlSerializer object (in the System.Xml.Serialization namespace) by passing it the type of object you plan to serialize. Finally, call the XmlSerializer.Serialize method to serialize the object and output the results to the stream.
- No overload for the XmlSerializer constructor takes zero parameters.
- You can only pass an array of bytes to the FileStream.Write method.
- You cannot declare a filename in the XmlSerializer constructor--you must always pass a Type object.
- You are writing an assembly that analyzes all files ending in a .txt or .dat extension in a specific folder. Which of the following code samples stores an array of all files with a .txt or a .dat extension contained in the C:\Windows folder in the allFiles array?
- ' VB
- Dim directoryInfo As DirectoryInfo = New DirectoryInfo("c:\windows")
- Dim txtFiles As FileInfo() = directoryInfo.GetFiles("*.txt")
- Dim datFiles As FileInfo() = directoryInfo.GetFiles("*.dat")
- Dim allFiles(txtFiles.Length + datFiles.Length - 1) As FileInfo
- Array.Copy(datFiles, 0, allFiles, 0, datFiles.Length)
- Array.Copy(txtFiles, 0, allFiles, datFiles.Length, txtFiles.Length)
- Explanation: Ch 2 Lesson 1
- DirectoryInfo.GetFiles can perform only one search at a time. Therefore, you would need to perform multiple searches and add the arrays using Array.Copy.
- You cannot add arrays using the + operator.
- Which of the following code samples does not result in an exception being thrown if "text.txt" does not exist? (Choose all that apply.)
- ' VB
- Dim fn As String = "Text.txt"
- If File.Exists(fn) Then
- Dim sr As StreamReader = New StreamReader(fn)
- Console.WriteLine(sr.ReadToEnd)
- End If
- ' VB
- Dim fn As String = "Text.txt"
- Dim fi As FileInfo = New FileInfo(fn)
- If fi.Exists Then
- Dim sr As StreamReader = New StreamReader(fn)
- Console.WriteLine(sr.ReadToEnd)
- End If
- Explanation: Ch 2 Lesson 1
- To check whether a file exists, you can call the static File.Exists method, or you can create a FileInfo object and call FileInfo.Exists.
- The StreamReader constructor cannot take an instance of the class FileInfo.
- FileInfo.Exists is not a static method. You must first create an instance of FileInfo to call this method.
- Given the following class, which of the following files represents how an instance of that class would be serialized using the XmlSerializer class?
- ' VB
- <XmlRoot("CartItem")> Public Class ShoppingCartItem
- Public productId As Int32
- Public price As Decimal
- Public quantity As Int32
- <XmlIgnore()> Public total As Decimal
- Public Sub New()
- MyBase.New
- End Sub
- End Class
- Answer
- <?xml version="1.0" ?>
- <CartItem>
- <productId>100</productId>
- <price>10.25</price>
- <quantity>2</quantity>
- </CartItem>
- Explanation: Ch5 lesson 2
- The specified attributes change the root XML element to CartItem from the default ShoppingCartItem, and they cause the total to be ignored during serialization.
- By default, XmlSerializer serializes all members as elements, not attributes.
- By default, XmlSerializer serializes all members as elements, not attributes. Additionally, the total member would be left out of serialization.
- Given the following class, which of the following files represents how an instance of that class would be serialized using the XmlSerializer class?
' VB
Public Class ShoppingCartItem
<XmlAttribute()> Public productId As Int32
Public price As Decimal
Public quantity As Int32
Public total As Decimal
Public Sub New()
MyBase.New
End Sub
End Class
Answer
<?xml version="1.0" ?>
<ShoppingCartItem productId="100">
<price>10.25</price>
<quantity>2</quantity>
<total>20.50</total>
</ShoppingCartItem>
Explanation: Ch 5 Lesson 2
By default, XmlSerializer serializes all members as XML elements. The productId member has the XmlAttribute attribute, which causes it to be serialized as an attribute.
XmlSerializer serializes members as attributes only if each member has the XmlAttribute attribute.
XmlSerializer would ignore the productId member only if it had the XmlIgnore attribute.
The productId member has the XmlAttribute attribute, which causes it to be serialized as an attribute.
- You are creating a custom class that implements the ISerializable interface. The following code shows the deserialization constructor in its current state:
' VB
' The following constructor is for deserialization
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New()
' TODO: Copy deserialized data
End Sub
How will you retrieve the deserialized data?
Answer Copy the data from the info.GetValue method.
Explanation: Chapter 5 Lesson 3
Deserialized data is stored in the SerializationInfo object, and it can be retrieved using the GetValue method or one of the other Get methods.
The StreamingContext object describes the source that provided the serialized data and does not contain the data itself.
There is no Data collection in either the SerializationInfo or StreamingContext classes.
- You need to write text to a file. Which of the following demonstrates the most efficient way to use the TextWriter class?
' VB
Dim fs As FileStream = New FileStream("Hello.dat", FileMode.Create)
Dim tw As TextWriter = New StreamWriter(fs)
tw.Write("Hello, world!")
tw.Close
fs.Close
Explanation: Ch 2 Lesson 2
The TextWriter class does not have a constructor. Instead, you should create it using the StreamWriter constructor. To create a StreamWriter object, you must use an existing Stream object, such as an instance of FileStream.
2 comments:
It is a useful resource.
On the last example: Which of the following Visual Basic demonstrates the most efficient way to use the TextWriter class?
How is this more efficient than:
Dim tw As TextWriter = New StreamWriter("Hello.dat")
tw.Write("Hello, world!")
tw.Close()
Post a Comment