# C# Exam Questions 70-483 Reading - Widget - Part 1
###### tags: `C#` `70-483` `Exam Questions`
https://www.briefmenow.org/microsoft/category/exam-70-483-programming-in-c-update-july-21th-2017/page/23/
https://www.examtopics.com/exams/microsoft/70-483/
* [Link Part 2](https://hackmd.io/@sfRJH1u7S464tSaizL7ZsQ/Hyq_GQX6v)
---
# JSON serialization and deserialization
## 1. ``JavaScriptSerializer``
### 1.
Which code segment should you insert at line 20?
You need to serialize the Location object as a JSON object.
Which code segment should you insert at line 20?
A. ``New DataContractSerializer(typeof(Location))``
B. ``New XmlSerializer(typeof(Location))``
C. ``New NetDataContractSenalizer()``
D. ``New DataContractJsonSerializer(typeof(Location))``
Answer:
* [public class JavaScriptSerializer](https://docs.microsoft.com/zh-tw/dotnet/api/system.web.script.serialization.javascriptserializer?view=netframework-4.8&viewFallbackFrom=netcore-3.1)
```
var serializer = new JavaScriptSerializer();
var serializedResult = serializer.Serialize(RegisteredUsers);
serializer.Deserialize<List<Person>>(serializedResult);
```
---
### 2. https://www.briefmenow.org/microsoft/which-code-should-you-insert-at-line-03-21/
You are creating a console application named App1.
App1 retrieves data from the Internet by using JavaScript Object Notation (JSON).
You are developing the following code segment:
```
public bool ValidateJson(string json, Dictionary<string, object> result) {
[]
try {
result = serializer.Deserialize<Dictionary<string, object>>(json);
return true;
} catch {
return false;
}
}
```
A. ``DataContractSerializer serializer = new DataContractSerializer();``
B. ``var serializer = new DataContractSerializer();``
C. ``XmlSerlalizer serializer = new XmlSerlalizer();``
D. ``var serializer = new JavaScriptSerializer();``
Answer: D.
---
### 3. https://www.briefmenow.org/microsoft/which-code-should-you-insert-at-line-03-23/
You are creating a console application named ``App1``.
``App1`` retrieves data from the Internet by using JavaScript Object Notation (JSON).
You are developing the following code segment:
```
public bool ValidateJson(string json, Dictionary<string, object> result) {
[]
try {
result = serializer.Deserialize<Dictionary<string, object>>(json);
return true;
} catch {
return false;
}
}
```
You need to ensure that the code validates the JSON string.
Which code should you insert at line 03?
A. ``DataContractSerializer serializer = new DataContractSerializer();``
B. ``var serializer = new DataContractSerializer();``
C. ``DataContractSerializer serializer = new DataContractSerializer();``
D. ``JavaScriptSerializer serializer = new JavaScriptSerializer();``
Answer: D
---
### 4. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-10-16/
An application receives ``JSON`` data in the following format:
```
{
"FirstName": "David",
"LastName": "Jones",
"Values": [0, 1, 2]
}
```
The application includes the following code segment.
```
public class Name {
public int[] Values { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public static Name ConvertToName(string json) {
var ser = JavaScriptSerializer();
}
```
You need to ensure that the ``ConvertToName()`` method
returns the JSON input ``string`` as a ``Name`` object.
Which code segment should you insert at line 10?
A. ``Return ser.Desenalize (json, typeof(Name));``
B. ``Return ser.ConvertToType<Name>(json);``
C. ``Return ser.Deserialize<Name>(json);``
D. ``Return ser.ConvertToType (json, typeof (Name));``
Answer: C
---
## 2. ``DataContractJsonSerializer``
### 1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1246/
You are developing an application that retrieves patient data from a web service.
The application stores the JSON messages returned from the web service
in a ``string`` variable named ``PatientAsJson``.
The variable is encoded as ``UTF-8``.
The application includes a class named ``Patient`` that is defined by the following code:
```
public class Patient {
public bool IsActive { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
```
You need to populate the ``Patient`` class with the data returned from the web service.
Which code segment should you use?
A.
```
DataContractJsonSerializer jsSerializer = new DataContractJsonSerializer(typeof(Patient));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(PatientAsJson))) {
Patient patientFromJson = (Patient) jsSerializer.ReadObject(steam);
}
```
B.
```
XmlSerializer xmlSerializer = new XmlSerializer()
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Patient));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(PatientAsJson))) {
Patient patientFromJson = (Patient) xmlSerializer.Deserialize(steam);
}
```
C.
```
DataContractSerializer jsSerializer = new DataContractSerializer(typeof(Patient));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(PatientAsJson))) {
Patient patientFromJson = new Patient();
jsSerializer.WriteObject(stream, patientFromJson);
}
```
D.
```
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(PatientAsJson, FileMode.Open, FileAccess.Read, FileShare.Read);
Patient patientAsJson = (Patient) formatter.Deserializer(stream);
stream.close();
```
Answer: A
---
### [DataContractJsonSerializer](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.json.datacontractjsonserializer?view=netcore-3.1)
* Namespace: ``System.Runtime.Serialization.Json``
```
public sealed class DataContractJsonSerializer : System.Runtime.Serialization.XmlObjectSerializer
```
### [How to use DataContractJsonSerializer](https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-serialize-and-deserialize-json-data)
#### To define the data contract for a Person type
```
[DataContract]
internal class Person {
[DataMember]
internal string name;
[DataMember]
internal int age;
}
```
#### To serialize an instance of type Person to JSON
1. Create an instance of the Person type.
```
var p = new Person();
p.name = "John";
p.age = 42;
```
2. Serialize the Person object to a memory stream by using the DataContractJsonSerializer.
```
var stream1 = new MemoryStream();
var ser = new DataContractJsonSerializer(typeof(Person));
```
3. Use the WriteObject method to write JSON data to the stream.
```
ser.WriteObject(stream1, p);
```
4. Show the JSON output.
```
stream1.Position = 0;
var sr = new StreamReader(stream1);
Console.Write("JSON form of Person object: ");
Console.WriteLine(sr.ReadToEnd());
```
#### To deserialize an instance of type Person from JSON
1. Deserialize the JSON-encoded data into a new instance of Person by using the ReadObject method of the DataContractJsonSerializer.
```
stream1.Position = 0;
var p2 = (Person)ser.ReadObject(stream1);
```
2. Show the results.
```
Console.WriteLine($"Deserialized back, got name={p2.name}, age={p2.age}");
```
#### Example
```
// Create a User object and serialize it to a JSON stream.
public static string WriteFromObject() {
// Create User object.
var user = new User("Bob", 42);
// Create a stream to serialize the object to.
var ms = new MemoryStream();
// Serializer the User object to the stream.
var ser = new DataContractJsonSerializer(typeof(User));
ser.WriteObject(ms, user);
byte[] json = ms.ToArray();
ms.Close();
return Encoding.UTF8.GetString(json, 0, json.Length);
}
// Deserialize a JSON stream to a User object.
public static User ReadToObject(string json) {
var deserializedUser = new User();
var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
var ser = new DataContractJsonSerializer(deserializedUser.GetType());
deserializedUser = ser.ReadObject(ms) as User;
ms.Close();
return deserializedUser;
}
```
---
# XML serialization and deserialization
## 1. DataContractSerializer
### 1.1.
The application reads the XML streams by using a DataContractSerializer object that is declared by the
following code segment:
var ser = new DataContractSerializer(typeof(Name));
You need to ensure that the application
preserves the element ordering as provided in the XML stream.
How should you complete the relevant code?
(To answer, drag the appropriate attributes to the correct
locations in the answer area-Each attribute may be used once, more than once, or not at all. You may need to
drag the split bar between panes or scroll to view content.)
* [Datacontractserializer](https://docs.microsoft.com/zh-tw/dotnet/api/system.runtime.serialization.datacontractserializer?view=netcore-3.1)
* [DataMemberAttribute](https://docs.microsoft.com/zh-tw/dotnet/api/system.runtime.serialization.datamemberattribute?view=netcore-3.1)
Attribute | Explanation
--- | ---
EmitDefaultValue | 取得或設定值,這個值會指定即將序列化之欄位或屬性的預設值是否要加以序列化。
IsNameSetExplicitly | 確認是否已明確設定 Name。
IsRequired | 取得或設定值,這個值會指示序列化引擎在讀取或還原序列化時成員是否必須存在於其中。
Name | 取得或設定資料成員名稱。
Order | 取得或設定成員之序列化和還原序列化的順序。
TypeId | 在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。(繼承來源 Attribute)
```
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(Person));
```
```
// You must apply a DataContractAttribute or SerializableAttribute
// to a class to have it serialized by the DataContractSerializer.
[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person : IExtensibleDataObject {
[DataMember()]
public string FirstName;
[DataMember]
public string LastName;
[DataMember()]
public int ID;
public Person(string newfName, string newLName, int newID) {
FirstName = newfName;
LastName = newLName;
ID = newID;
}
private ExtensionDataObject extensionData_Value;
public ExtensionDataObject ExtensionData {
get { return extensionData_Value; }
set { extensionData_Value = value; }
}
}
```
```
try {
WriteObject("DataContractSerializerExample.xml");
ReadObject("DataContractSerializerExample.xml");
}
catch (SerializationException serExc) {
Console.WriteLine("Serialization Failed");
Console.WriteLine(serExc.Message);
}
catch (Exception exc) {
Console.WriteLine("The serialization operation failed: {0} StackTrace: {1}", exc.Message, exc.StackTrace);
}
```
---
### 1.2. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-20-12/
You are developing an application.
The application converts a ``Location`` object to a ``string``
by using a method named ``WriteObject``.
The ``WriteObject()`` method accepts two parameters,
a ``Location`` object and an ``XmlObjectSerializer`` object.
The application includes the following code.
```
public enum Compass {
North,
South,
East,
West
}
[DataContract]
public class Location {
[DataMember]
public string Label { get; set; }
[DataMember]
public Compass Direction { get; set; }
}
void DoWork() {
var location = new Location { Label = "Test", Direction = "Compass.West" }
Console.WriteLine(WriteObject(location) );
}
```
You need to serialize the ``Location`` object as XML.
Which code segment should you insert at line 20?
A. ``new XmlSerializer(typeof(Location))``
B. ``new NetDataContractSerializer()``
C. ``new DataContractJsonSerializer(typeof (Location))``
D. ``new DataContractSerializer(typeof(Location))``
Answer: D
---
### 1.3 https://www.briefmenow.org/microsoft/hot-area-85/
You have the following code:
```
[DataContract(Name = "Individual", Namespace = "http://www.contoso.com")]
public class Individual {
private string m_FirstName;
private string m_LastName;
[DataMember()]
public string FirstName {
get { return m_FirstName; }
set { this.m_FirstName = value; }
}
[DataMember(EmitDefaultValue=false)]
public string LastName {
get { return m_LastName; }
set { this.m_LastName = value; }
}
public Individual {}
public Individual {}
public Person(string firstName, string lastName) {
this.m_FirstName = firstName;
this.m_LastName = lastName;
}
}
```
For each of the following statements,
select Yes if the statement is true. Otherwise, select No.
* ``LastName`` will se serialized after ``FirstName``.
--> Yes
* The namespace used in the serialized XML will be ``Individual``.
--> No
* The ``LastName`` node will always appear in the serialized XML.
--> No
---
### 1.4
## https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-09-18/
You are troubleshooting an application that uses a class named ``FullName``.
The class is decorated with the ``DataContractAttribute`` attribute.
The application includes the following code.
```
class Program {
MemoryStream WriteName(Name name) {
var ms = new MemoryStream();
var binary = XmlDictionaryWriter.CreateBinaryWriter(ms);
var ser = new DataContractSerializer(typeof(FullName));
ser.WriteObject(binary, name);
[]
return ms;
}
}
```
You need to ensure that the entire ``FullName`` object is serialized to the memory stream object.
Which code segment should you insert at line 09?
A. ``binary.WriteEndDocument();``
B. ``binary.WriteEndDocumentAsync();``
C. ``binary.WriteEndElementAsync();``
D. ``binary.Flush();``
Answer: D
### [DataContractSerializer Sample](https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/datacontractserializer-sample?redirectedfrom=MSDN)
By default, the ``DataContractSerializer`` encodes objects into a stream
using a textual representation of XML.
However, you can influence the encoding of the XML by passing in a different writer.
The sample creates a binary writer by calling ``CreateBinaryWriter``.
It then passes the writer and the record object to the serializer
when it calls ``WriteObjectContent``. Finally,
the sample flushes the writer and reports on the length of the streams.
```
MemoryStream stream2 = new MemoryStream();
XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream2);
serializer.WriteObject(binaryDictionaryWriter, record1);
binaryDictionaryWriter.Flush();
//report the length of the streams
Console.WriteLine("Text Stream is {0} bytes long", stream1.Length);
Console.WriteLine("Binary Stream is {0} bytes long", stream2.Length);
```
已經有 ``ser.WriteObject(binary, name);``
所以直接 ``binary.Flush();``
---
### [DataMemberAttribute.EmitDefaultValue Property](https://docs.microsoft.com/zh-tw/dotnet/api/system.runtime.serialization.datamemberattribute.emitdefaultvalue?view=netcore-3.1)
Gets or sets a value that specifies whether to serialize the default value
for a field or property being serialized.
```
public bool EmitDefaultValue { get; set; }
```
```
[DataContract]
public class Employee {
// The CLR default for as string is a null value.
// This will be written as <employeeName xsi:nill="true" />
[DataMember]
public string EmployeeName = null;
// This will be written as <employeeID>0</employeeID>
[DataMember]
public int employeeID = 0;
// The next three will not be written because the EmitDefaultValue = false.
[DataMember(EmitDefaultValue = false)]
public string position = null;
[DataMember(EmitDefaultValue = false)]
public int salary = 0;
[DataMember(EmitDefaultValue = false)]
public int? bonus = null;
// This will be written as <targetSalary>57800</targetSalary>
[DataMember(EmitDefaultValue = false)]
public int targetSalary = 57800;
}
```
---
## 2. XmlSerializer
### 2.1. https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-308/
You are developing an application that includes a class named ``Customer``.
The application will output the ``Customer`` class
as a structured XML document by using the following code segment:
```
<?xml version="1.0" encoding="utf-8"?>
<Prospect xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
ProspectId="9c027bb8-65f1-40a9-8afa-ac839f3cdc5d"
xmlns="http://prospect">
<FullName>David Jones</FullName>
<DateOfBirth>1977-06-11T00:00:00</DateOfBirth>
</<Prospect>
```
You need to ensure that the Customer class will serialize to XML.
How should you complete the relevant code?
* ``{XmlRoot (Name = "Customer", Namespace = "http://customer")}``
* ``{XmlRoot (Name = "Prospect", Namespace = "http://prospect")}``
* ``{XmlAttribute("ProspectId)}``
* ``{XmlElement("ProspectId")}``
* ``{XmlChoiceIdentifier}``
* ``{XmlIgnore}``
* ``{XmlArrayItem}``
* ``{XmlElement("FullName")}``
Answer:
```
{XmlRoot (Name = "Prospect", Namespace = "http://prospect")}
public class Customer {
{XmlAttribute("ProspectId)}
public Guid Id { get; set; }
{XmlElement("FullName")}
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
{XmlIgnore}
public int Tin { get; set; }
}
```
### [XmlSerializer Class](https://docs.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlserializer?view=netcore-3.1)
### [XML Serialization and Deserialization: Part 1](https://www.codeproject.com/Articles/483055/XML-Serialization-and-Deserialization-Part-1)
The following points should be noted while creating a class for serialization:
1. XML serialization only serializes public fields and properties.
2. XML serialization does not include any type information.
3. We need to have a default/non-parameterised constructor in order to serialize an object.
4. ReadOnly properties are not serialized.
#### XML Serialization and Attributes
Some common attributes that are available during Serialization are:
* ``XmlAttribute``: This member will be serialized as an XML attribute.
* ``XmlElement``: The field will be serialized as an XML element.
* ``XmlIgnore``: Field will be ignored during Serialization.
* ``XmlRoot``: Represent XML document's root Element.
#### Use of ``XmlElement``
``[XmlElement("Number")]`` specifies that the property ``HouseNo``
will be serialized with the ``Tag`` name ``Number`` in the XML File.
It helps us to map between the XML ``Tag`` name and the class ``Property`` Name.
The resultant XML string with the ``Custom`` tag name is given below:
```
public class AddressDetails {
[XmlElement("Number")]
public int HouseNo { get; set; }
[XmlElement("Street")]
public string StreetName { get; set; }
[XmlElement("CityName")]
}
```
```
<AddressDetails>
<Number>4</Number>
<Street>Rohini</Street>
<CityName>Delhi</CityName>
</AddressDetails>
```
#### Use of ``XmlAttribute``
If we want that the property ``HouseNo`` should occur
as the ``attribute`` for the Tag AddressDetails,
then we should use ``XmlAttribute``.
``XmlAttribute`` __serializes the object property
as the attribute for the parent tag__.
```
public class AddresssDetails {
[XmlAttribute]("Number")]
public int HouseNo { get; set; }
[XmlElement("Street")]
public string StreetName { get; set; }
[XmlElement("CityName")]
public string City {get; set;}
}
```
<AddressDetails Number="4">
<Street>Rohini</Street>
<CityName>Delhi</CityName>
</AddressDetails>
### Use to ``XmlIgnore``
By default, all public fields and public read/write properties
are serialized by the XmlSerializer. That is,
the value of each __public field or property__ is persisted
as an XML element or XML attribute in an XML-document instance.
In order to override this property, apply ``XmlIgnore`` attribute to it.
This will __remove the element from the XML__.
The code below explains the following:
```
public class AddressDetails {
[XmlElement("Number")]
public int HouseNo;
[XmlElement("Street")]
public string StreetName;
[XmlIgnore]
public string City;
}
```
```
<AddressDetails>
<Number>4</Number>
<Street>ABC</Street>
</AddressDetails>
```
Here, we can see that the property ``City`` contains ``XmlIgnore`` attribute.
The resultant XML created won't contain the ``City`` tag in it.
Notice here that the property ``City`` __is not serialized
because of the attribute ``XmlIgnore`` placed on it__.
#### Use of ``XmlRoot``
__Every XML has a root element__. __By default,
the name of the root element is the same
as the name of the class that is serialized__.
In order to __give a custom name to the root element of XML__,
we use ``XmlRoot`` attribute.
```
[XmlRoot("Root")]
public class AddressDetails {
[XmlElement("Number")]
public int HouseNo;
[XmlElement("Street")]
public string StreetName;
[XmlElement("CityName")]
public string City;
}
```
```
<Root>
<HouseNo>4</HouseNo>
<StreetName>Rohini</StreetName>
<City>Delhi</City>
</Root>
```
Here, we can see that the attribute ``XmlRoot`` is placed over AddressDetails class.
This will now __override the default serialization behavior__
which __takes XML tag root name same as the class name__.
The XML will now have "Root" as the root tag.
Notice here that the root tag here is now ``Root`` and not the Class name.
---
# WebClient
## https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-04-78/
An application will upload data by using HTML form-based encoding.
The application uses a method named ``SendMessage``.
The ``SendMessage()`` method includes the following code.
```
public Task<byte[]> SendMessage(string url, int intA, int intB) {
var client = new WebClient();
}
```
The receiving URL accepts parameters as ``form-encoded`` values.
You need to send the values ``intA`` and ``intB``
as __form-encoded__ values named ``a`` and ``b``, respectively.
Which code segment should you insert at line 04?
A.
```
var data string.Format("a={0}&b={1}", intA, intB);
return client.UploadStringTaskAsync(new Uri(url), data);
```
B.
```
var data string.Format("a={0}&b={1}", intA, intB);
var data string.Format("a={0}&b={1}", intA, intB);
return client.UploadFileTaskAsync(new Uri(url), data);
```
C.
```
var data string.Format("a={0}&b={1}", intA, intB);
return client.UploadDataTaskAsync(new Uri(url), Encoding.UTF8.GetBytes(data));
```
D.
```
var nvc = new NameValueCollection() {
{"a", intA.ToString()},
{"b", intB.ToString()}
};
return client.UploadValuesTaskAsync(new Uri(url), nvc);
```
Answer: D
---
### [WebClient.UploadStringTaskAsync Method](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadstringtaskasync?view=netcore-3.1)
Uploads the specified string to the specified resource as an asynchronous operation using a task object.
### [WebClient.UploadFileTaskAsync Method](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadfiletaskasync?view=netcore-3.1)
Uploads the specified local file to a resource as an asynchronous operation using a task object.
### [WebClient.UploadDataTaskAsync Method](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploaddatataskasync?view=netcore-3.1)
Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task object.
### [WebClient.UploadValuesTaskAsync Method](https://docs.microsoft.com/en-us/dotnet/api/system.net.webclient.uploadvaluestaskasync?redirectedfrom=MSDN&view=netcore-3.1#overloads)
Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous operation using a task object.
```
public System.Threading.Tasks.Task<byte[]> UploadValuesTaskAsync(
string address,
string method,
System.Collections.Specialized.NameValueCollection data);
```
#### Remark
If the Content-type header is null, this method sets it to ``application/x-www-form-urlencoded``.
#### Parameters
* ``address`` String
The URI of the resource to receive the collection.
* ``method`` String
The HTTP method used to send the collection to the resource. If null, the default is POST for http and STOR for ftp.
* ``data`` [NameValueCollection](https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.namevaluecollection?view=netcore-3.1)
The [NameValueCollection](https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.namevaluecollection?view=netcore-3.1) to send to the resource.
---
# File Access
## 1.
The application includes a method named ReadFile that reads data from a
file.
The ReadFile() method must meet the following requirements:
It must not make changes to the data file.
--> FileAccess.Read
--> A ``FileAccess`` value that specifies the operations that can be performed on the file.
It must allow other processes to access the data file.
--> FileShare.ReadWrite
-->A ``FileShare`` value specifying the type of access other threads have to the file.
It must not throw an exception if the application attempts to open a data file that does not exist.
--> FileMode.OpenOrCreate
--> A ``FileMode`` value that specifies whether a file is created if one does not exist,
and determines whether the contents of existing files are retained or overwritten.
You need to implement the ReadFile() method.
Which code segment should you use?
```
var fs = File.Open(Filename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
```
* ``FileMode.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`` permission is required.
If the file access is ``FileAccess.Write``,
``FileIOPermissionAccess.Write`` permission is required.
If the fileis opened with ``FileAccess.ReadWrite``,
both ``FileIOPermissionAccess.Read`` and ``FileIOPermissionAccess.Write`` permissions are required.
* ``FileShare.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.
http://msdn.microsoft.com/pl-pl/library/system.io.fileshare.aspx
---
### [File.Open Method - Open(String, FileMode, FileAccess, FileShare)](https://docs.microsoft.com/en-us/dotnet/api/system.io.file.open?view=netcore-3.1)
* Opens a FileStream on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.
```
public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share);
```
```
using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) {
}
```
```
FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read);
```
---
### [FileStream](https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream.-ctor?view=netcore-3.1)
FileStream Constructors
```
public FileStream (Microsoft.Win32.SafeHandles.SafeFileHandle handle, System.IO.FileAccess access);
```
```
FileStream fStream = new FileStream("Test#@@#.dat", FileMode.Create, FileAccess.ReadWrite, FileShare.None, 4096, true);
```
---
## 2. ``File.OpenWrite`` / ``File.OpenRead``
### 2.1. https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-313/
You are creating a method that will split a single input file into two smaller output files.
The method must perform the following actions:
Create a file named header.dat that contains the first 20 bytes of the input file.
Create a file named body.dat that contains the remainder of the input file.
You need to create the method.
How should you complete the relevant code? (
* ``fsSource.Seek(20, SeekOrigin.Current);``
* ``byte[] body = new byte[fsSource.Length];``
* ``byte[] body = new byte[fsSource.Length - 20];``
* ``fsHeader.Write(header, 0, header.Length);``
* ``fsHeader.Write(header, 20, header.Length);``
* ``fsBody.Write(body, 0, body.Length);``
* ``fsBody.Write(body, 20, body.Length);``
```
using (FileStream fsSource = File.OpenRead(SourceFilePath))
using (FileStream fsHeader = File.OpenWrite(HeaderFilePath))
using (FileStream fsBody = File.OpenWrite(BodyFilePath))
{
byte[] header = new byte[20];
fsSource.Read(header, 0, header.Length);
fsSource.Read(header, 0, header.Length);
}
```
Answer:
```
{
byte[] header = new byte[20];
byte[] body = new byte[fsSource.Length - 20]; #1
fsSource.Read(header, 0, header.Length);
fsHeader.Write(header, 0, header.Length); #2
fsSource.Read(header, 0, header.Length);
fsBody.Write(body, 0, body.Length); // #3
}
```
---
### [File.OpenWrite(String) Method](https://docs.microsoft.com/en-us/dotnet/api/system.io.file.openwrite?view=netcore-3.1)
### [File.OpenRead(String) Method](https://docs.microsoft.com/en-us/dotnet/api/system.io.file.openread?view=netcore-3.1)
```
// Open the stream and write to it.
using (FileStream fs = File.OpenWrite(path)) {
Byte[] info = new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Open the stream and read it back.
using (FileStream fs = File.OpenRead(path)) {
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0) {
Console.WriteLine(temp.GetString(b));
}
}
```
---
# ``SqlConnection`` / ``SqlDataReader``
### 1.
The ``GetAnimals()`` method must meet the following requirements:
Connect to a Microsoft SQL Server database.
Create ``Animal`` objects and populate them with data from the database.
Return a sequence of populated ``Animal`` objects.
Which two actions should you perform?
A.
Insert the following code segment at line 16:
``while(sqlDataReader.NextResult())``
B.
Insert the following code segment at line 13:
``sqlConnection.Open();``
C.
Insert the following code segment at line 13:
``sqlConnection.BeginTransaction();``
D.
Insert the following code segment at line 16:
``while(sqlDataReader.Read())``
E.
Insert the following code segment at line 16:
``while(sqlDataReader.GetValues())``
Answer: BD
### [SqlConnection](https://docs.microsoft.com/zh-tw/dotnet/api/system.data.sqlclient.sqlconnection?view=dotnet-plat-ext-5.0&viewFallbackFrom=netcore-3.1)
```
private static void CreateCommand(string queryString, string connectionString) {
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
```
```
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
// Do work here; connection closed on following line.
}
```
### [SqlDataReader 類別](https://docs.microsoft.com/zh-tw/dotnet/api/system.data.sqlclient.sqldatareader?view=dotnet-plat-ext-5.0&viewFallbackFrom=netcore-3.1)
Represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database.
```
public sealed class SqlDataAdapter : System.Data.Common.DbDataAdapter, ICloneable
```
```
private static void ReadOrderData(string connectionString) {
string queryString ="SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read()) {
ReadSingleRow((IDataRecord)reader);
}
// Call Close when done reading.
reader.Close();
}
}
```
---
### 2. https://www.briefmenow.org/microsoft/which-two-actions-should-you-perform-1393/
```
class Customer {
public string CompanyName { get; set; }
public string Id { get; set; }
}
const static string sqlSelectCustomers = "SELECT CustomerID, CompanyName FROM Customers";
private static IEnumerable<Customer> GetCustomer(string sqlConnectionString) {
List<Customer> customers = new List<Customer>();
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
using(sqlConnection) {
SqlCommand sqlCommand = new SqlCommand(sqlSelectCustomers, sqlConnection);
sqlConnection.Open(); // --> Option B
using(SqlDataReader sqlDataReader = sqlCommand.ExecuteReader()) {
while (sqlDataReader.Read()) // --> Option D
{
Customer customer = new Customer();
customer.Id = (string) sqlDataReader["CustomerID"];
customer.CompanyName = (string) sqlDataReader["CompanyName"];
customers.Add(customer);
}
}
}
return customers;
}
```
The ``GetCustomers()`` method must meet the following requirements:
Connect to a Microsoft SQL Server database.
Populate ``Customer`` objects with data from the database.
Return an ``IEnumerable<Customer>`` collection that contains the populated ``Customer`` objects.
You need to meet the requirements. Which two actions should you perform?
A.
Insert the following code segment at line 17:
``while (sqlDataReader.GetValues())``
B.
Insert the following code segment at line 14:
``sqlConnection.Open();``
C.
Insert the following code segment at line 14:
``sqlConnection.BeginTransaction();``
D.
Insert the following code segment at line 17:
``while (sqlDataReader.Read())``
E.
Insert the following code segment at line 17:
``while (sqlDataReader.NextResult())``
Answer: BD
---
### 3. https://www.briefmenow.org/microsoft/which-line-of-code-should-you-identify-9/
You have the following code
```
class Bar {
public string barColor { get; set; }
public string barName { get; set; }
}
const static string sqlSelectCustomers = "SELECT CustomerID, CompanyName FROM Customers";
private static IEnumerable<Customer> GetBars(string sqlConnectionString) {
var bars = new List<Bar>();
SqlConnection fooSqlConn = new SqlConnection(sqlConnectionString);
using(fooSqlConn) {
SqlCommand fooSqlCmd = new SqlCommand(
"SELECT sqlName, sqlColor, from Bars", fooSqlConn);
fooSqlConn.Open();
using(SqlDataReader fooSqlReader = fooSqlCmd.ExecuteReader()) {
while (fooSqlReader.Read()) // --> Option B
{
var bar = new Bar();
bar.Id = (string) fooSqlReader["sqlName"];
bar.CompanyName = (string) fooSqlReader["sqlColor"];
bars.Add(bar);
}
}
}
return bars;
}
```
You need to identify the missing line of code at line 15.
Which line of code should you identify?
A. ``using (fooSqlConn.BeginTransaction())``
B. ``while (fooSqlReader.Read())``
C. ``while (fooSqlReader.NextResult())``
D. ``while (fooSqlReader.GetBoolean(0))``
Answer: B
---
### 4. https://www.briefmenow.org/microsoft/hot-area-89/
You have the following code (line numbers are included for reference only):
```
DataTable dataTable;
string connString = "Data Source=192.168.1.100;Initial Catalog=Database1;User Id=sa;Password=p@ssw0rd";
using (SqlConnection sqlConn = new SqlConnection(connString)) {
connection.Open();
using(SqlCommand sqlCmand = new SqlCommand()) {
sqlCmand.Connection = sqlConn;
sqlCmand.CommandType = CommandType.StoredProcedure;
sqlCmand.CommandType = "p_Procedure1";
using(SqlDataAdapter adapter = new SqlDataAdapter(sqlCmd)) {
using(dataTable = new DataTable()) {
adapter.Fill(dataTable);
}
}
}
}
```
To answer, complete each statement according to the information presented in the code.
* The dataTable connection gets closed at line...
-> 19
* The adapter object gets disposed at line...
-> 17
離開 ``using {}`` 就會回收或關閉
---
## 2. OleDbDataReader
### 2.1. https://www.briefmenow.org/microsoft/which-type-of-object-should-you-use-in-the-method-8/
You need to write a method that retrieves data from a Microsoft Access 2013 database.
The method must meet the following requirements:
Be read-only.
Be able to use the data before the entire data set is retrieved.
Minimize the amount of system overhead and the amount of memory usage.
Which type of object should you use in the method?
A. ``SqlDataAdapter``
B. ``DataContext``
C. ``DbDataAdapter``
D. ``OleDbDataReader``
Answer: D
---
### [OleDbDataReader Class](https://docs.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbdatareader?view=dotnet-plat-ext-5.0&viewFallbackFrom=netcore-3.1)
Provides a way of reading a forward-only stream of data rows from a data source.
This class cannot be inherited.
```
public sealed class OleDbDataReader : System.Data.Common.DbDataReader
```
### [DataContext Class](https://docs.microsoft.com/en-us/dotnet/api/system.data.linq.datacontext?view=netframework-4.8&viewFallbackFrom=netcore-3.1)
Represents the main entry point for the LINQ to SQL framework.
```
public class DataContext : IDisposable
```
### [DbDataAdapter Class](https://docs.microsoft.com/en-us/dotnet/api/system.data.common.dbdataadapter?view=netcore-3.1)
```
public abstract class DbDataAdapter : System.Data.Common.DataAdapter, ICloneable, System.Data.IDbDataAdapter
```
#### Remarks
Classes that inherit ``DbDataAdapter`` must implement the inherited members,
and typically define additional members to add provider-specific functionality.
For example, the ``DbDataAdapter`` class defines the ``SelectCommand`` property,
and the ``DbDataAdapter`` class defines eight overloads of the ``Fill`` method.
In turn, the ``OleDbDataAdapter`` class inherits the ``Fill`` method,
and also defines two additional overloads of ``Fill``
that take an ADO Recordset object as a parameter.
### [OleDbDataAdapter](https://docs.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbdataadapter?view=dotnet-plat-ext-5.0&viewFallbackFrom=netcore-3.1)
```
Explanation:
OleDbDataReader Class
Provides a way of reading a forward-only stream of data rows from a data source.
Example:
OleDbConnection cn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
DataTable schemaTable;
OleDbDataReader myReader;
//Open a connection to the SQL Server Northwind database.
cn.ConnectionString = “Provider=SQLOLEDB;Data Source=server;User ID=login;
Password=password;Initial Catalog=Northwind”;
```
---
### 2.2. https://www.briefmenow.org/microsoft/which-type-of-object-should-you-use-in-the-method-9/
You need to write a method that retrieves data from a Microsoft Access 2013 database.
The method must meet the following requirements:
Be read-only.
Be able to use the data before the entire data set is retrieved.
Minimize the amount of system overhead and the amount of memory usage.
Which type of object should you use in the method?
A. ``DbDataReader``
B. ``DataContext``
C. ``unTyped DataSet``
D. ``DbDataAdapter``
Answer: D
---
# IEquatable
## https://www.briefmenow.org/microsoft/you-need-to-implement-iequatable-3/
You have the following class:
```
public class Class1: IEquatable<Class1> {
public Int32 ID { get; set; }
public String Name { get; set; }
public bool Equals { get; set; }
}
```
You need to implement ``IEquatable``.
The ``Equals`` method must return ``true``
if both ``ID`` and ``Name`` are set to the identical values.
Otherwise, the method must return ``false``.
``Equals`` must not throw an exception.
What should you do?
* ``if (!Object.Equals(this.Name, other.Name) { return false; }``
* ``if (this.ID == other.ID) { return false; }``
* ``return false;``
* ``return true;``
* ``if (null == other) { return false; }``
* ``break``
* ``if (this.ID != other.ID) { return false; }``
* ``if (!this.Name.Equals(other.Name) { return false; }``
---
Answer:
```
public class Class1: IEquatable<Class1> {
public Int32 ID { get; set; }
public String Name { get; set; }
public bool Equals { get; set; }
public override bool Equals(Object other) {
if (null == other) { return false; }
if (this.ID != other.ID) { return false; }
if (!this.Name.Equals(other.Name) { return false; }
return true;
}
}
```
### [IEquatable<T> Interface](https://docs.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=netcore-3.1)
Namespace: ``System``
Defines a generalized method that a value type or class implements to create a type-specific method for determining equality of instances.
```
public interface IEquatable<T>
```
### [IEquatable<T>.Equals(T) Method](https://docs.microsoft.com/en-us/dotnet/api/system.iequatable-1.equals?view=netcore-3.1)
Indicates whether the current object is equal to another object of the same type.
```
public bool Equals (T other);
```
```
public class Person : IEquatable<Person> {
//...
public override bool Equals(Object obj) {
if (obj == null) { return false; }
Person personObj = obj as Person;
if (personObj == null) { return false; }
else { return Equals(personObj); }
}
}
```
---
# IComparable
## 1. https://www.briefmenow.org/microsoft/how-should-you-complete-the-relevant-code-segment-8/
You are developing a class named ``Temperature``.
You need to ensure that collections of ``Temperature`` objects are sortable.
How should you complete the relevant code segment?
* ``public class Temperature: IComparable``
* ``public class Temperature: IComparer``
* ``CompareTo``
* ``Equals``
* ``this.Fahrenheit.CompareTo(otherTemperature.Fahrenheit);``
* ``otherTemperature.Fahrenheit.CompareTo(this.Fahrenheit);``
```
{
public double Fahrenheit { get; set; }
public int
(object obj)
{
if (null == obj) { return 1; }
var otherTemperature = obj as Temperature;
if (null != otherTemperature) {
return
}
throw new ArgumentException("Object is not a Temperature");
}
}
```
Answer:
### [IComparable](https://docs.microsoft.com/zh-tw/dotnet/api/system.icomparable?view=netcore-3.1)
Defines a generalized type-specific comparison method that
a value type or class implements to order or sort its instances.
```
public class Temperature : IComparable {
// The temperature value
protected double temperatureF;
public int CompareTo(object obj) {
if (obj == null) return 1;
Temperature otherTemperature = obj as Temperature;
if (otherTemperature != null) {
return this.temperatureF.CompareTo(otherTemperature.temperatureF);
} else {
throw new ArgumentException("Object is not a Temperature");
}
}
}
```
---
## 2. https://www.briefmenow.org/microsoft/hot-area-91/
```
public class Class1 : IComparable<Class1> {
public Int32 ID { get; set; }
public String Name { get; set; }
public int CompareTo(Class1 other) {
if (ID == other.ID) return 0;
else { return ID.CompareTo(other.ID); }
}
}
```
You write the following code for a method:
```
List<Class1> list = new List<Class1>() {
new Class1() { ID = 5, Name = "User1" },
new Class1() { ID = 5, Name = "User1" },
new Class1() { ID = 5, Name = "User1" },
new Class1() { ID = 5, Name = "User1" },
};
Console.WriteLine(list.Count);
list.Sort();
Console.WriteLine(list[0].Name);
```
To answer, complete each statement according to the information presented in the code.
Line 07 of the method will display
--> 4
Line 09 of the method will display
--> User3
---
### [IComparable<T> Interface](https://docs.microsoft.com/en-us/dotnet/api/system.icomparable-1?view=netcore-3.1)
* Namespace: ``System``
* Defines a generalized comparison method that a value type or class implements
to create a type-specific comparison method for ordering or sorting its instances.
```
public interface IComparable<in T>
```
```
public class Temperature : IComparable<Temperature> {
// Implement the generic CompareTo method with the Temperature
// class as the Type parameter.
//
public int CompareTo(Temperature other) {
// If other is not a valid object reference, this instance is greater.
if (other == null) return 1;
// The temperature comparison depends on the comparison of
// the underlying Double values.
return m_value.CompareTo(other.m_value);
}
}
```
```
public class Temperature : IComparable {
// The temperature value
protected double temperatureF;
public int CompareTo(object obj) {
if (obj == null) return 1;
Temperature otherTemperature = obj as Temperature;
if (otherTemperature != null)
return this.temperatureF.CompareTo(otherTemperature.temperatureF);
else
throw new ArgumentException("Object is not a Temperature");
}
}
```
---
# IEumerable
## 1.
You are developing __a custom collection__ named ``LoanCollection`` for a class named ``Loan`` class.
You need to ensure that you can process each ``Loan`` object
in the ``LoanCollection`` collection by using a ``foreach`` loop.
How should you complete the relevant code?
```
: IEumerable
public IEumerator GetEnumberator() {
return _loanCollection.GetEnumberator();
}
```
---
## 2. https://www.briefmenow.org/microsoft/which-two-interfaces-should-you-implement-5/
You are modifying an existing application that manages employee payroll.
The application includes a class named ``PayrollProcessor``.
The ``PayrollProcessor`` class connects to a ``payroll`` database
and processes batches of paychecks once a week.
You need to ensure that the ``PayrollProcessor`` class
supports iteration and releases database connections
after the batch processing completes.
Which two interfaces should you implement?
A. ``IEquatable``
B. ``IEnumerable``
C. ``IDisposable``
D. ``IComparable``
Answer: B, C
* ``IEquatable``:
Defines a generalized method that a value type or class implements
to create a type-specific method for determining equality of instances.
* ``IEnumerable``:
Returns an enumerator that iterates through a collection.
* ``IDisposable``:
Provides a mechanism for releasing unmanaged resources.
* ``IComparable``:
Defines a generalized type-specific comparison method
that a value type or class implements to order or sort its instances.
---
### [IEumerable](https://docs.microsoft.com/zh-tw/dotnet/api/system.collections.ienumerable.getenumerator?view=netcore-3.1):
```
public System.Collections.IEnumerator GetEnumerator ();
// Collection of Person objects.
// This class implements IEnumerable so that it can be used with ForEach syntax.
public class People : IEnumerable {...}
// Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator() {
return (IEnumerator) GetEnumerator();
}
public PeopleEnum GetEnumerator() {
return new PeopleEnum(_people);
}
```
---
# string / StringBuilder
## 1. string / StringBuilder 字串拼接時的效能, 取決於 memory allocation 的次數
You are developing an application that
will convert data into multiple output formats.
The application includes the following code.
```
public class TabDelmitedFormatter : IOutputFormatter<string> {
readonly Func<int, char> suffix = col => col % 2 == 0 ? '\n' : '\t';
public string GetOutput(IEnumerator<string> iterator, int recordSize) {}
}
```
You are developing a code segment that will produce tab-delimited output.
All output routines implement the following interface:
```
public interface IOutputFormatter<T> {
string GetOutput(IEnumerator<T> iterator, int recordSize);
}
```
You need to __minimize the completion time__ of the ``GetOutput()`` method.
* A ``string`` object __concatenation__ operation always
creates a new object from the existing ``string`` and the new data.
* A ``StringBuilder`` object maintains a buffer
to accommodate the concatenation of new data.
New data is appended to the buffer if room is available;
otherwise, a new, larger buffer is allocated,
data from the original buffer is copied to the new buffer,
and the new data is then appended to the new buffer.
* __The performance of a concatenation operation__
for a ``string`` or ``StringBuilder`` object depends on
__the frequency of memory allocations__.
A String concatenation operation __always allocates memory__,
whereas a StringBuilder concatenation operation __allocates memory
only if the StringBuilder object buffer
is too small to accommodatethe new data__.
* Use the ``string`` class if you are concatenating
a fixed number of String objects. In that case,
the compiler may even combine individual concatenation operations
into a single operation.
* Use a ``StringBuilder`` object if you are concatenating an arbitrary number of strings;
for example, if you’re using a loop
to concatenate a random number of strings of user input.
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx
---
## 2. Usage of StringBuilder
### https://www.briefmenow.org/microsoft/which-four-code-segments-should-you-use-in-sequence-5/
You are developing an application by using C#.
The application will __output the text string ``First Line``
followed by the text string ``Second Line``.
You need to ensure that __an empty line separates the text strings__.
Which four code segments should you use in sequence?
* ``sb.Append("\l");``
* ``var sb = new StringBuilder();``
* ``sb.Append("First Line");``
* ``sb.Append("\t");``
* ``sb.AppendLine();``
* ``sb.Append(String.Empty);``
* ``sb.Append("Second Line");``
Answer:
```
var sb = new StringBuilder();
sb.Append("First Line");
sb.AppendLine();
sb.Append("Second Line");
```
---
## 3. String.Format
### 3.1. https://www.briefmenow.org/microsoft/which-code-should-you-insert-at-line-04-4/
You are developing an application in C#.
The application will display the temperature and the time
at which the temperature was recorded.
You have the following method
```
public void DisplayTemperature(DateTime date, double temp) {
string output;
string lblMessage = output;
}
```
You need to ensure that the message displayed in the ``lblMessage`` object
shows the time formatted according to the following requirements:
The time must be formatted as hour:minute AM/PM, for example 2:00 PM.
The date must be formatted as month/day/year, for example 04/21/2013.
The temperature must be formatted to have two decimal places, for example 23-45.
Which code should you insert at line 04?
---
My test:
```
Console.WriteLine("outpout: " + string.Format("Temperature at {0:N2} on {1:t} on {1:dd/mm/yy}", 105.629, DateTime.Now));
// Temperature at 105.63 on 下午 11:27 on 20/27/20
```
### [String.Format Method](https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=netcore-3.1)
### [DateTime.ToString Method](https://docs.microsoft.com/zh-tw/dotnet/api/system.datetime.tostring?view=netcore-3.1)
### [Double.ToString Method](https://docs.microsoft.com/en-us/dotnet/api/system.double.tostring?view=netcore-3.1)
```
string s = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
Console.WriteLine(s);
// Output similar to: 'It is now 4/10/2015 at 10:04 AM'
```
---
### 3.2. https://www.briefmenow.org/microsoft/which-code-segment-should-you-insert-at-line-03-58/
You are developing a game that allows players to collect from ``0`` through ``1000`` coins.
You are creating a method that will be used in the game.
The method includes the following code.
```
public string FormatCoins(string name, int coins) {
}
```
The method must meet the following requirements:
Return a string that includes the player name and the number of coins.
Display the number of coins __without leading zeros__ if the number is ``1`` or greater.
Display the number of coins as __a single ``0`` if the number is 0__.
You need to ensure that the method meets the requirements.
Which code segment should you insert at line 03?
A. ``return String.Format("Player {0}, collected {1} coins.", name, coins.ToString("###0"));``
B. ``return String.Format("Player {0}, collected {1:000#} coins.", name, coins);``
C. ``return String.Format("Player {name}, collected {coins.ToString('000')} coins.");``
D. ``return String.Format("Player {1}, collected {2:D3} coins.", name, coins);``
Answer: A
After testing:
```
int numberOfCoins = 599;
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1} coins.", "John", numberOfCoins.ToString("###0")));
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1:000#} coins.", "John", numberOfCoins));
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1:D3} coins.", "John", numberOfCoins));
numberOfCoins = 0;
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1} coins.", "Mary", numberOfCoins.ToString("###0")));
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1:000#} coins.", "Mary", numberOfCoins));
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1:D3} coins.", "Mary", numberOfCoins));
numberOfCoins = 55;
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1} coins.", "Alice", numberOfCoins.ToString("###0")));
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1:000#} coins.", "Alice", numberOfCoins));
Console.WriteLine("outpout2: " + string.Format("Player {0}, collected {1:D3} coins.", "Alice", numberOfCoins));
outpout2: Player John, collected 599 coins.
outpout2: Player John, collected 0599 coins.
outpout2: Player John, collected 599 coins.
outpout2: Player Mary, collected 0 coins.
outpout2: Player Mary, collected 0000 coins.
outpout2: Player Mary, collected 000 coins.
outpout2: Player Alice, collected 55 coins.
outpout2: Player Alice, collected 0055 coins.
outpout2: Player Alice, collected 055 coins.
```
---
# StringReader
## 1. https://www.briefmenow.org/microsoft/which-object-type-should-you-use-6/
You are developing an application that will parse a large amount of text.
You need to parse the text into separate lines and minimize memory use while processing data.
Which object type should you use?
A. ``DataContractSerializer``
B. ``StringBuilder``
C. ``StringReader``
D. ``JsonSerializer``
Answer: C
### [StringReader Class](https://docs.microsoft.com/en-us/dotnet/api/system.io.stringreader?view=netcore-3.1)
``StringReader`` enables you to read a string synchronously or asynchronously.
You can read a character at a time with the ``Read`` or the ``ReadAsync`` method,
a line at a time using the ``ReadLine`` or the ``ReadLineAsync`` method
and an entire string using the ``ReadToEnd`` or the ``ReadToEndAsync`` method.
---
# StreamReader
## 1. https://www.briefmenow.org/microsoft/which-code-segment-should-you-use-1245/
You are developing an application that will read data from a text file
and display the file contents. You need to read data from the file,
display it, and correctly release the file resources.
Which code segment should you use?
A.
```
string inputLine;
using (StreamReader reader = new StreamReader("data.txt")) {
while (null != (inputLine = reader.ReadLine())) {
Console.WriteLine(inputLine);
}
}
```
B.
```
string inputLine;
StreamReader reader = null;
using (reader = new StreamReader("data.txt"));
while (null != (inputLine = reader.ReadLine())) {
Console.WriteLine(inputLine);
}
```
C.
```
string inputLine;
StreamReader reader = new StreamReader("data.txt");
while (null != (inputLine = reader.ReadLine())) {
Console.WriteLine(inputLine);
}
```
D.
```
string inputLine;
StreamReader reader = null;
try {
reader = new StreamReader("data.txt");
while (null != (inputLine = reader.ReadLine())) {
Console.WriteLine(inputLine);
}
reader.Close();
reader.Dispose();
}
finally {
}
```
Answer: A
---
## 2. StreamReader + throw
You develop an application that displays information
from log files when errors occur.
The application will prompt the user to create an error report
that sends details about the error and the session to the administrator.
When a user opens a log file by using the application,
__the application throws an exception and closes__.
The application __must preserve the original stack trace information__
when an exception occurs during this process.
You need to implement the method that reads the log files.
```
[Target 1]
{
try {
string line;
while ((line) = sr.ReadLine()) != null) {
Console.WriteLine(line);
}
}
catch(FileNotFoundException e) {
Console.WriteLine(e.ToString());
[Target 2]
}
}
```
Which code segments should you include in Target 1 and Target 2 to complete the code?
* StringReader – Implements a TextReader that reads from a string.
http://msdn.microsoft.com/en-us/library/system.io.stringreader(v=vs.110).aspx
* StreamReader – Implements a TextReader that
reads characters from a byte stream in a particular encoding.
http://msdn.microsoft.com/en-us/library/system.io.streamreader(v=vs.110).aspx
---