Monday, August 31, 2009

70-536 MCTS .NET Foundations Questions #36

Hey Now,

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 internet & not sure the answers are correct. There were over 200 questions & some duplicates, I hope to study all of them. I’ve also added some of my notes to these so any line starting with K8 (my nickname, first syllable of Catt o ) are my comments.

Whew! 211 Questions reviewed!

Thx,

Catto

Q: #186 - #211

Question: 186

You are writing code for user authentication and authorization. The username, password, and roles are stored in your application data store. You need to establish a user security context that will be used for authorization checks such as IsInRole. You write the following code segment to authorize the user.

If TestPassword(UserName, Password) = False Then
Throw New Exception("Could not authenticate user")End If
Dim RolesArray() As String = LookUpUserRoles(UserName)
You need to complete this code so that it establishes the user security context. Which code segment should you use?

A. Dim objID As New GenericIdentity(UserName)
Dim objUser As New GenericPrincipal(objID, RolesArray)
Thread.CurrentPrincipal = objUser

B. Dim objID As New WindowsIdentity(UserName)
Dim objUser As New WindowsPrincipal(objID)
Thread.CurrentPrincipal = objUser

C. Dim objNT As New NTAccount(UserName)
Dim objID As New GenericIdentity(objNT.Value)
Dim objUser As New GenericPrincipal(objID, RolesArray)
Thread.CurrentPrincipal = objUser

D. Dim objToken As IntPtr = IntPtr.Zeroobj
Token = LogonUserUsingInterop(UserName, EncryptedPassword)
Dim objContext As WindowsImpersonationContext =
_WindowsIdentity.Impersonate(objToken)

Answer: A

K8 – Q: Establishes security context A: GenericIdentity GenericPrincipal

Question: 187

You need to return the contents of an isolated storage file as a string. The file is machine-scoped and is named Settings.dat. Which code segment should you use?

A. IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream( “Settings.dat”, FileMode.Open);
string result = new StreamReader(isoStream).ReadToEnd();

B. IsolatedStorageFile isoFile;
isoFile = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream( “Settings.dat”, FileMode.Open, isoFile);
string result = new StreamReader(isoStream).ReadToEnd();

C. IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream( “Settings.dat”, FileMode.Open);
string result = isoStream.ToString();

D. IsolatedStorageFile isoFile;
isoFile = IsolatedStorageFile.GetMachineStoreForAssembly();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream( “Settings.dat”, FileMode.Open, isoFile);
string result = isoStream.ToString();

Answer: B

K8 - File Stream String to end

Question: 188

You need to write a code segment that will create a common language runtime (CLR) unit of isolation within an application. Which code segment should you use?

A. AppDomainSetup mySetup = AppDomain.CurrentDomain.SetupInformation;
mySetup.ShadowCopyFiles = “true”;

B. System.Diagnostics.Process myProcess;
myProcess = new System.Diagnostics.Process();

C. AppDomain domain;
domain = AppDomain.CreateDomain(“CompanyDomain”):

D. System.ComponentModel.Component myComponent;
myComponent = new System.ComponentModel.Component();

Answer: C

K8 – Q: CLR isolation A: Create AppDomain

Question: 189

You need to create a method to clear a Queue named q. Which code segment should you use?

A. foreach (object e in q) {
q.Dequeue();}

B. foreach (object e in q) {
Enqueue(null);}

C. q.Clear();

D. q.Dequeue();

Answer: C

K8 – ez question right?

Question: 190

You write the following code segment to call a function from the Win32 Application Programming Interface (API) by using platform invoke.

Dim PersonName as String = "N?el"
Dim Msg as String = "Welcome " + PersonName + "to club ''!"
Dim r As Boolean= User32API.MessageBox(0, Msg, PersonName, 0)
You need to define a method prototype that can best marshal the string data. Which code segment should you use?

A. <DllImport("user32", CharSet:=CharSet.Ansi)> _Public Function
MessageBox(ByVal hWnd As Int32, _ByVal text As String, ByVal caption As String, _ByVal t As UInt32) As BooleanEnd Function

B. <DllImport("user32", EntryPoint:="MessageBoxA", _CharSet:=CharSet.Ansi)>
_Public Function MessageBox(ByVal hWnd As Int32,
_<MarshalAs(UnmanagedType.LPWStr)> ByVal text As String,
_<MarshalAs(UnmanagedType.LPWStr)> ByVal caption As String, _ByVal t As UInt32) As BooleanEnd Function

C. <DllImport("user32", CharSet:=CharSet.Unicode)> _Public Function
MessageBox(ByVal hWnd As Int32, _ByVal text As String, ByVal caption As String,
_ByVal t As UInt32) As BooleanEnd Function

D. DllImport("user32", EntryPoint:="MessageBoxA", _CharSet:=CharSet.Unicode)>
_Public Function MessageBox(ByVal hWnd As Int32,

_<MarshalAs(UnmanagedType.LPWStr)> ByVal text As String,

_<MarshalAs(UnmanagedType.LPWStr)> ByVal caption As String, _ByVal t As

UInt32) As BooleanEnd Function

Answer: C

K8 – Q: Marshall String A: CharSet.Unicode

Question: 191

You are writing a method to compress an array of bytes. The bytes to be compressed are passed to the method in a parameter named document. You need to compress the contents of the incoming parameter. Which code segment should you use?

A. MemoryStream^ intStream = gcnew MemoryStream(document);
GZipStream^ zipStream = gcnew GZipStream(inStream, CompressionMode::Compress);
array<Byte>^ result = gcnew array<Byte>(document->Length);
zipStream->Write(result, 0, result->Length);
return result;

B. MemoryStream^ stream = gcnew MemoryStream(document);
GZipStream^ zipStream = gcnew GZipStream(stream,

CompressionMode::Compress);
zipStream->Write(document, 0, document- >Length);
zipStream->Close();
return stream->ToArray();

C. MemoryStream^ outStream = gcnew MemoryStream();
GZipStream^ zipStream = gcnew GZipStream(outStream,
CompressionMode::Compress);
zipStream->Write(document, 0, document->Length);
zipStream->Close();
return outStream->ToArray();

D. MemoryStream^ inStream = gcnew MemoryStream(document);
GZipStream^ zipStream = gcnew GZipStream(inStream,
CompressionMode::Compress);
MemoryStream^ outStream = gcnew MemoryStream();
int b;
while ((b = zipStream->ReadByte()) != -1) {
outStream->WriteByte((Byte)b);
} return outStream->ToArray();

Answer: C

K8 – OutStream!

Question: 192

You develop a service application named PollingService that periodically calls long-running procedures. These procedures are called from the DoWork method. You use the following service application code:

Partial Class PollingService Inherits ServiceBase
Dim blnExit As Boolean = False Protected Overrides Sub OnStart(ByVal args() As String)
Do
DoWork()
Loop While Not blnExit
End Sub
Protected Overrides Sub OnStop()
blnExit = True
End Sub
Private Sub DoWork()
End SubEnd Class

When you attempt to start the service, you receive the following error message: Could not start the PollingService service on the local computer. Error 1053: The service did not respond to the start or control request in a timely fashion. You need to modify the service application code so that the service starts properly. What should you do?

A. Move the loop code into the constructor of the service class from the OnStart method.

B. Drag a timer component onto the design surface of the service. Move the calls to the long-running procedure from the OnStart method into the Tick event procedure of the timer, set
the Enabled property of the timer to True, and call the Start method of the timer in the OnStart method.

C. Add a class-level System.Timers.Timer variable to the service class code. Move the call to the DoWork method into the Elapsed event procedure of the timer, set the Enabled property of the timer to True, and call the Start method of the timer in the OnStart method.

D. Move the loop code from the OnStart method into the DoWork method.

Answer: C

K8 - System.Timers.Timer

Question: 193

You are developing an application to assist the user in conducting electronic surveys. The survey consists of 25 true-or-false questions. You need to perform the following tasks:

Initialize each answer to true.Minimize the amount of memory used by each survey. Which storage option should you choose?

A. BitVector32 answers = new BitVector32(1);

B. BitVector32 answers = new BitVector32(-1);

C. BitArray answers = new BitArray(1);

D. BitArray answers = new BitArray(-1);

Answer: B

K8 – Q: init to true & min mem A: BitVector32(-1);

Question: 194

You create a method that runs by using the credentials of the end user. You need to use Microsoft Windows groups to authorize the user. You must add a code segment that identifies whether a user is in the local group named Clerk.
Which code segment should you use?

A. WindowsIdentity^ currentUser = WindowsIdentity::GetCurrent();
For each
(IdentityReference^ grp in currentUser->Groups) {

NTAccount^ grpAccount =
safe_cast<NTAccount^>(grp->Translate(NTAccount::typeid));
isAuthorized = grpAccount->Value->Equals(
Environment::MachineName + “\\Clerk”);
if(isAuthorized) break;}

B. WindowsPrincipal^ currentUser =
safe_cast<WindowsPrincipal^>(Thread::CurrentPrincipal);
isAuthorized = currentUser->IsInRole(“Clerk”);

C. GenericPrincipal^ currentUser = safe_cast<GenericPrincipal^>(Thread::CurrentPrincipal);
isAuthorized = currentUser->IsInRole(“Clerk”);

D. WindowsPrincipal^ currentUser = safe_cast<WindowsPrincipal^>(Thread::CurrentPrincipal);
isAuthorized = currentUser->IsInRole( Environment::MachineName);

Answer: B

K8 – Q: Identify if user is in local user group A: WindowsPrincipal IsInRole(“rolename”)

Question: 195

You are creating a class named Age. You need to ensure that the Age class is written such that collections of Age objects can be sorted. Which code segment should you use?

A. public class Age {
public int Value;
public object CompareTo(object obj) {
if (obj is Age) { Age_age = (Age) obj;
return Value.ComapreTo(obj);
}
throw new ArgumentException(“object not an Age”);
} }

B. public class Age {
public int Value;
public object CompareTo(int iValue) {
try {
return Value.ComapreTo(iValue);
} catch {
throw new ArgumentException(“object not an Age”);
} } }

C. public class Age : IComparable {
public int Value;
public int CompareTo(object obj) {
if (obj is Age) {
Age_age = (Age) obj;

return Value.ComapreTo(_age.Value);

}
throw new ArgumentException(“object not an Age”);
} }

D. public class Age : IComparable {
public int Value;
public int CompareTo(object obj) {
try {
return Value.ComapreTo(((Age) obj).Value);
} catch {
return -1;
} } }

Answer: C

K8 – Sorting w/ IComparable

Question: 196

You write a class named Employee that includes the following code segment.
public ref
class Employee{
String^ employeeId;
String^ employeeName;
String^ jobTitleName;
public: String^ GetName() { return employeeName; }
String^ GetJobTitle() { return jobTitleName; }

You need to expose this class to COM in a type library. The COM interface must also facilitate forward-compatibility across new versions of the Employee class. You need to choose a method for generating the COM interface. What should you do?

A. Add the following attribute to the class definition.[ClassInterface(ClassInterfaceType::None)]
public class Employee {

B. Add the following attribute to the class
definition.[ClassInterface(ClassInterfaceType::AutoDual)]
public class Employee {

C. Add the following attribute to the class definition.[ComVisible(true)]
public class Employee {

D. Define an interface for the class and add the following attribute to the class definition.[ClassInterface(ClassInterfaceType::None)]
public class Employee : IEmployee

{

Answer: D

K8 – Define an interface

Question: 197

You are developing a method to hash data for later verification by using the MD5 algorithm. The data is passed to your method as a byte array named message. You need to compute the hash
of the incoming parameter by using MD5. You also need to place the result into a byte array. Which code segment should you use?

A. HashAlgorithm ^algo = HashAlgorithm::Create(“MD5”);
hash = algo->CompueHash(message);

B. HashAlgorithm ^algo = HashAlgorithm::Create(“MD5”);
hash = BitConverter::GetBytes(algo->GetHashCode());

C. HashAlgorithm ^algo;
algo = HashAlgorithm::Create(message->ToString());
hash = algo->Hash;

D. HashAlgorithm ^algo = HashAlgorithm::Create(“MD5”);
hash = nullptr;
algo->TransformBlock(message, 0, message->Length, hash, 0);

Answer: A

K8 – Q: Compute Hash A: ComputeHash

Saturday, August 29, 2009

70-536 MCTS .NET Foundations Questions #35

Hey Now,

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 internet & not sure the answers are correct. There were over 200 questions & some duplicates, I hope to study all of them. I’ve also added some of my notes to these so any line starting with K8 (my nickname, first syllable of Catt o ) are my comments.

Thx,

Catto

Q: #176 - #185

Question: 176

You develop a service application named FileService. You deploy the service application to multiple servers on your network. You implement the following code segment. (Line numbers are included for reference only.)

01 public :
02 void StartService(String^ serverName){
03
04 ServiceController^ crtl = gcnew
05 ServiceController(“FileService”);
06 if (crtl->Status == ServiceControllerStatus::Stopped){}
07 }

You need to develop a routine that will start FileService if it stops. The routine must start FileService on the server identified by the serverName input parameter. Which two lines of code should you add to the code segment? (Each correct answer presents part of the solution. Choose two.)

A. Insert the following line of code between lines 03 and 04:crtl.ServiceName = serverName;

B. Insert the following line of code between lines 03 and 04:crtl.MachineName = serverName;

C. Insert the following line of code between lines 03 and 04:crtl.Site.Name = serverName;

D. Insert the following line of code between lines 04 and 05:crtl.Continue();

E. Insert the following line of code between lines 04 and 05:crtl.Start();

F. Insert the following line of code between lines 04 and 05:crtl.ExecuteCommand(0);

Answer: B, E

K8 – Repeated questions are easier the 4th time. Crtl.MachineName = serverName & crtl.Start()

Question: 177

You are changing the security settings of a file named MyData.xml. You need to preserve the existing inherited access rules. You also need to prevent the access rules from inheriting changes in the future. Which code segment should you use?

A. FileSecurity security = new FileSecurity("mydata.xml", AccessControlSections.All);
security.SetAccessRuleProtection(true, true);
File.SetAccessControl(“mydata.xml”, security);

B. FileSecurity security = new FileSecurity();
security.SetAccessRuleProtection(true, true);
File.SetAccessControl(“mydata.xml”, security);

C. FileSecurity security = File.GetAccessControl(“mydata.xml”);
security.SetAccessRuleProtection(true, true);

D. FileSecurity security = File.GetAccessControl(“mydata.xml”);
security.SetAuditRuleProtection(true, true);
File.SetAccessControl(“mydata.xml”, security);

Answer: A

K8 – FileSecurity & AccessControlSections

Question: 178

You write the following code to implement the CompanyClass.MyMethod function.
public class CompanyClass {
public int MyMethod(int arg) {
return arg;
}}

You need to call the CompanyClass.MyMethod function dynamically from an unrelated class in your assembly. Which code segment should you use?

A. CompanyClass^ myClass = gcnew CompanyClass();
Type^ t = CompanyClass::typeid;
MethodInfo^m = t->GetMethod(“MyMethod”);
int i = (int)m->Invoke(this, gcnew array<Object^> {1});

B. CompanyClass^ myClass = gcnew CompanyClass();
Type^ t = CompanyClass::typeid;
MethodInfo^m = t->GetMethod(“MyMethod”);
int i = (int)m->Invoke(myClass, gcnew array<Object^> {1});

C. CompanyClass^ myClass = gcnew CompanyClass();
Type^ t = CompanyClass::typeid;
MethodInfo^m = t->GetMethod(“CompanyClass.MyMethod”);
int i = (int)m->Invoke(myClass, gcnew array<Object^> {1});

D. Type^ t =Type::GetType(“CompanyClass”);
MethodInfo^m = t->GetMethod(“MyMethod”);
int i = (int)m->Invoke(this, gcnew array<Object^> {1});

Answer: B

K8 – Q: Call function dynamically.

Question: 179

You are creating a class to compare a specially-formatted string. The default collation comparisons do not apply. You need to implement the IComparable<string> interface.
Which code segment should you use?

A. public class Person : IComparable<string>{
public int CompareTo(string other){
}}

B. public class Person : IComparable<string>{
public int CompareTo(object other){
}}

C. public class Person : IComparable<string>{
public bool CompareTo(string other){
}}

D. public class Person : IComparable<string>{
public bool CompareTo(object other){
}}

Answer: A

K8 – Compare special string A: int CompareTo(string

Question: 180

You are writing a custom dictionary. The custom-dictionary class is named MyDictionary. You need to ensure that the dictionary is type safe. Which code segment should you use?

A. public ref class MYDictionary : public Dictionary<String^, String^>{};

B. public ref class MYDictionary : public Hashtable{};

C. public ref class MYDictionary : public IDictionary{};

D. public ref class MYDictionary {};Distionary<String^, String^>t = gcnew Dictionary<String^, String^>();
MyDictionary dictionary = (MyDictionary)t;

Answer: A

K8 – Type Safe so use <String>

Question: 181

You are developing a utility screen for a new client application. The utility screen displays a thermometer that conveys the current status of processes being carried out by the application.

You need to draw a rectangle on the screen to serve as the background of the thermometer as shown in the exhibit. The rectangle must be filled with gradient shading. Which code segment should you choose?

Exhibit:

A. Dim objRect As New Rectangle(10, 10, 450, 25)
Dim objBrush As New LinearGradientBrush( _objRect, Color.AliceBlue, Color.CornflowerBlue, _LinearGradientMode.ForwardDiagonal)
Dim objPen As New Pen(objBrush)Dim g As Graphics =
myForm.CreateGraphicsg.DrawRectangle(objPen, objRect)

B. Dim objRect As New Rectangle(10, 10, 450, 25)
Dim objBrush As New LinearGradientBrush( _
objRect, Color.AliceBlue, Color.CornflowerBlue, _
LinearGradientMode.ForwardDiagonal)
Dim objPen As New Pen(objBrush)
Dim g As Graphics = myForm.CreateGraphicsg.FillRectangle(objBrush, objRect)

C. Dim objRect As New RectangleF(10.0F, 10.0F, 450.0F, 25.0F)
Dim points() As System.Drawing.Point = _
{New Point(0, 0), New Point(110, 145)}
Dim objBrush As New LinearGradientBrush( _
objRect, Color.AliceBlue, Color.CornflowerBlue, _
LinearGradientMode.ForwardDiagonal)
Dim objPen As New Pen(objBrush)
Dim g As Graphics = myForm.CreateGraphicsg.DrawPolygon(objPen, points)

D. Dim objRect As New Rectangle(10, 10, 450, 25)
Dim objBrush As New SolidBrush(Color.AliceBlue)
Dim objPen As New Pen(objBrush)Dim g As Graphics =
myForm.CreateGraphicsg.DrawRectangle(objPen, objRect)

Answer: B

K8 - Gradient Brush object.

Question: 182

You are developing a method to call a COM component. You need to use declarative security to explicitly request the runtime to perform a full stack walk. You must ensure that all callers have the required level of trust for COM interop before the callers execute your method. Which attribute should you place on the method?

A. [SecurityPermission(
SecurityAction.Demand,
Flags=SecurityPermissionFlag.UnmanagedCode)]

B. [SecurityPermission(
SecurityAction.LinkDemand,
Flags=SecurityPermissionFlag.UnmanagedCode)]

C. [SecurityPermission(
SecurityAction.Assert,
Flags = SecurityPermissionFlag.UnmanagedCode)]

D. [SecurityPermission(
SecurityAction.Deny,
Flags = SecurityPermissionFlag.UnmanagedCode)]

Answer: A

K8 – All callers have required trust A: Demand

Question: 183

You are writing a method that returns an ArrayList named al. You need to ensure that changes to the ArrayList are performed in a thread-safe manner. Which code segment should you use?

A. ArrayList al = new ArrayList();
lock (al.SyncRoot){
return al;}

B. ArrayList al = new ArrayList();
lock (al.SyncRoot.GetType()){
return al;}

C. ArrayList al = new ArrayList();
Monitor.Enter(al);Monitor.Exit(al);return al;

D. ArrayList al = new ArrayList();
ArrayList sync_al = ArrayList.Synchronized(al);
return sync_al;

Answer: D

K8 – Q: Changes to ArrayList Thread safe A: ArrayList sync_al

Question: 184

You are loading a new assembly into an application. You need to override the default evidence for the assembly. You require the common language runtime (CLR) to grant the assembly a permission set, as if the assembly were loaded from the local intranet zone. You need to build the evidence collection. Which code segment should you use?

A. Dim objEvidence As New Evidence( _
Assembly.GetExecutingAssembly.Evidence

B. Dim objEvidence As New EvidenceobjEvidence.AddAssembly( _
New Zone(SecurityZone.Intranet))

C. Dim objEvidence As New EvidenceobjEvidence.AddHost( _
New Zone(SecurityZone.Intranet))

D. Dim objEvidence As New Evidence( _

AppDomain.CurrentDomain.Evidence)

Answer: C

K8 Q: Grant Assembly permission A: AddHost

Question: 185

You are creating an application that lists processes on remote computers. The application requires a method that performs the following tasks: Accept the remote computer name as a string parameter named strComputer.Return an ArrayList object that contains the names of all processes that are running on that computer. You need to write a code segment that retrieves the name of each process that is running on the remote computer and adds the name to the ArrayList
object. Which code segment should you use?

A. ArrayList al = new ArrayList();
Process[] procs = Process.GetProcessesByName(s trComputer);
foreach (Process proc in procs) {
al.Add(proc);}

B. ArrayList al = new ArrayList();
Process[] procs = Process.GetProcesses(strComputer);
foreach (Process proc in procs) {
al.Add(proc);}

C. ArrayList al = new ArrayList();
Process[] procs = Process.GetProcessesByName(s trComputer);
foreach (Process proc in procs) {
al.Add(proc.ProcessName);}

D. ArrayList al = new ArrayList();
Process[] procs = Process.GetProcesses(strComputer);
foreach (Process proc in procs) {
al.Add(proc.ProcessName);}

Answer: D

K8 Get Process

70-536 MCTS .NET Foundations Questions #34

Hey Now,

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 internet & not sure the answers are correct. There were over 200 questions & some duplicates, I hope to study all of them. I’ve also added some of my notes to these so any line starting with K8 (my nickname, first syllable of Catt o ) are my comments.

Thx,

Catto

#167 - #175

 

Question: 167

You create a class library that is used by applications in three departments of your company. The library contains a Department class with the following definition.

Public Class Department

Public name As String

Public manager As String

End Class

Each application uses a custom configuration section to store department-specific values in the application configuration file as shown in the following code.

<Department>

<name>Hardware</name>

<manager>Company</manager>

</Department>

You need to write a code segment that creates a Department object instance by using the field values retrieved from the application configuration file. Which code segment should you use?

A. Public Class deptElement
Inherits ConfigurationElement
Protected Overrides Sub DeserializeElement( _
ByVal reader As XmlReader, _
ByVal serializeCollectionKey As Boolean)
Dim dept As Department = New Department()
dept.name = ConfigurationManager.AppSettings("name")
dept.manager = _
ConfigurationManager.AppSettings("manager")
End Sub
End Class

B. Public Class deptElement
Inherits ConfigurationElement
Protected Overrides Sub DeserializeElement( _
ByVal reader As XmlReader, _
ByVal serializeCollectionKey As Boolean)
Dim dept As Department = New Department()
dept.name = reader.GetAttribute("name")
dept.manager = reader.GetAttribute("manager")
End Sub
End Class

C. Public Class deptHandler
Implements IConfigurationSectionHandler
Public Function Create(ByVal parent As Object, _
ByVal configContext As Object, _
ByVal section As System.Xml.XmlNode) As Object _
Implements IConfigurationSectionHandler.Create
Dim dept As Department = new Department()
dept.name = section.SelectSingleNode("name").InnerText
dept.manager = _
section.SelectSingleNode("manager").InnerText
Return dept
End Function
End Class

D. Public Class deptHandler
Implements IConfigurationSectionHandler
Public Function Create(ByVal parent As Object, _
ByVal configContext As Object, _
ByVal section As System.Xml.XmlNode) As Object _
Implements IConfigurationSectionHandler.Create
Dim dept As Department = new Department()
dept.name = section.Attributes("name").Value
dept.manager = section.Attributes("manager").Value
Return dept
End Function
End Class

Answer: C

K8 – A: IconfigurationSectionHandler & SelectSingleNode

Question: 168

You are writing a method that returns an ArrayList named al. You need to ensure that changes to the ArrayList are performed in a thread-safe manner. Which code segment should you use?

A. ArrayList^ al = gcnew ArrayList();
lock (al->SyncRoot){
return al;}

B. ArrayList^ al = gcnew ArrayList();
lock (al->SyncRoot.GetType()){
return al;}

C. ArrayList^ al = gcnew ArrayList();
Monitor::Enter(al);
Monitor::Exit(al);
return al;

D. ArrayList^ al = gcnew ArrayList();
ArrayList^ sync_al = ArrayList::Synchronized(al);
return sync_al;

Answer: D

K8 – Q: Thread safe manner to changes in array list A: Synchronized

Question: 169

You need to write a code segment that transfers the contents of a byte array named dataToSend by using a NetworkStream object named netStream. You need to use a cache of size 8,192 bytes. Which code segment should you use?

A. Dim memStream As New MemoryStream(8192)memStream.Write(dataToSend, 0, _
CType(netStream.Length, Integer))

B. Dim memStream As New MemoryStream(8192)netStream.Write(dataToSend, 0, _
CType(memStream.Length, Integer))

C. Dim bufStream As New BufferedStream(netStream, 8192)
bufStream.Write(dataToSend, 0, dataToSend.Length)

D. Dim bufStream As New BufferedStream(netStream)
bufStream.Write(dataToSend, 0, 8192)

Answer: C

K8 – BufferedStream(networkStream, CasheBytes)

Question: 170

You are creating an undo buffer that stores data modifications. You need to ensure that the undo functionality undoes the most recent data modifications first. You also need to ensure that the undo buffer permits the storage of strings only. Which code segment should you use?

A. Dim undoBuffer As New Stack(Of String)

B. Dim undoBuffer As New Stack()

C. Dim undoBuffer As New Queue(Of String)

D. Dim undoBuffer As New Queue()

Answer: A

K8 – Stack Last in first out combied with of string this is VB version

Question: 171

You are creating an undo buffer that stores data modifications. You need to ensure that the undo functionality undoes the most recent data modifications first. You also need to ensure that the undo buffer permits the storage of strings only. Which code segment should you use?

A. Stack<string> undoBuffer = new Stack<string>();

B. Stack undoBuffer = new Stack();

C. Queue<string> undoBuffer = new Queue<string>();

D. Queue undoBuffer = new Queue();

Answer: A

K8 – Stack Last in first out combied with of string C#

Question: 172

You create the definition for a Vehicle class by using the following code segment.

public class Vehicle {
[XmlAttribute(AttributeName = "category")]
public string vehicleType;
public string model;
[XmlIgnore]
public int year;
[XmlElement(ElementName = "mileage")]
public int miles;
public ConditionType condition;
public Vehicle() {
}
public enum ConditionType {
[XmlEnum("Poor")] BelowAverage,
[XmlEnum("Good")] Average,
[XmlEnum("Excellent")] AboveAverage
}}

You create an instance of the Vehicle class. You populate the public fields of the Vehicle class instance as shown in the following table:

MemberValuevehicleTypecarmodelraceryear2002miles15000conditionAboveAverage You need to identify the XML block that is produced when this Vehicle class instance is serialized. Which block of XML represents the output of serializing the Vehicle instance?

A. <?xml version="1.0" encoding="utf-8"?>
<Vehicle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema""
vehicleType="car">
<model>racer</model>
<miles>15000</miles>
<condition>AboveAverage</condition>
</Vehicle>
B. <?xml version="1.0" encoding="utf-8"?>
<Vehicle
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"

category="car">
<model>racer</model>
<mileage>15000</mileage>
<condition>Excellent</condition>
</Vehicle>

C. <?xml version="1.0" encoding="utf-8"?>
<Vehicle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
category="car">
<model>racer</model>
<mileage>15000</mileage>
<conditionType>Excellent</conditionType>
</Vehicle>

D. <?xml version="1.0" encoding="utf-8"?>
<Vehicle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<category>car</category>
<model>racer</model>
<mileage>15000</mileage>
<condition>Excellent</condition>
</Vehicle>

Answer: B

K8 – Car category along with condition Excellent.

Question: 173

You need to write a code segment that transfers the first 80 bytes from a stream variable named stream1 into a new byte array named byteArray. You also need to ensure that the code segment assigns the number of bytes that are transferred to an integer variable named bytesTransferred. Which code segment should you use?

A. bytesTransferred = stream1.Read(byteArray, 0, 80)

B. For i As Integer = 1 To 80
stream1.WriteByte(byteArray(i))
bytesTransferred = i
If Not stream1.CanWrite Then
Exit For
End IfNext

C. While bytesTransferred < 80
stream1.Seek(1, SeekOrigin.Current)
byteArray(bytesTransferred) = _
Convert.ToByte(stream1.ReadByte())bytesTransferred += 1End While

D. stream1.Write(byteArray, 0, 80)bytesTransferred = byteArray.Length

Answer: A

K8 – Bytes transferred with no loop

Question: 174

You are changing the security settings of a file named MyData.xml. You need to preserve the existing inherited access rules. You also need to prevent the access rules from inheriting changes in the future. Which code segment should you use?

A. FileSecurity^ security = gcnew FileSecurity(“mydata.xml”, AccessControlSections::All);
security->SetAccessRuleProtection( true, true);
File::SetAccessControl(“mydata.xml”, security);

B. FileSecurity^ security = gcnew FileSecurity();
security->SetAccess RuleProtection(true,true);
File::SetAccessControl(“mydata.xml”, security);

C. FileSecurity^ security = File::GetAccessControl(“mydata.xml”);
security->SetAccessRuleProtection(true, true);

D. FileSecurity^ security =
File::GetAccessControl(“mydata.xml”);security->SetAuditRuleProtection(true, true);
File::SetAccessControl(“mydata.xml”, security);

Answer: A

K8 – Change Security Settings … FileSecurity

Question: 175

You are testing a component that serializes the Meeting class instances so that they can be saved to the file system. The Meeting class has the following definition:

public class Meeting {
private string title;
public int roomNumber;
public string[] invitees;
public Meeting(){
}
public Meeting(string t){
title = t;
} }

The component contains a procedure with the following code segment.
Meeting myMeeting = new Meeting(“Goals”);
myMeeting.roomNumber = 1100;
string[] attendees = new string[2]{“Company”, “Mary”};
myMeeting.invitees = attendees;
XmlSerializer xs = new XmlSerializer(typeof(Meeting));
StreamWriter writer = new StreamWriter(@"C:\Meeting.xml");
Xs.Serialize(writer, myMeeting);
writer.Close();

You need to identify the XML block that is written to the C:\Meeting.xml file as a result of running this procedure. Which XML block represents the content that will be written to the C:\Meeting.xml file?

A. <?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<title>Goals</title>
<roomNumber>1100</roomNumber>
<invitee>Company</invitee>
<invitee>Mary</invitee>
</Meeting>

B. <?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<roomNumber>1100</roomNumber>
<invitees>
<string>Company</string>
<string>Mary</string>
</invitees>
</Meeting>

C. <?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
title="Goals">
<roomNumber>1100</roomNumber> <invitees>
<string>Company</string>
<string>Mary</string>
</invitees>
</Meeting>

D. <?xml version="1.0" encoding="utf-8"?>
<Meeting xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <roomNumber>1100</roomNumber>
<invitees>
<string>Company</string>
</invitees>
<invitees>
<string>Mary</string>
</invitees>
</Meeting>

Answer: B

K8 – XML

Friday, August 28, 2009

70-536 MCTS .NET 2.0 Configuration #33

 

Hey Now Everybody,

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 section #3 of the exam.NET 2.0 Configuration Debug!.

Thx,

Catto

3. Embedding configuration, diagnostic, management & installation features

  • Code

1. Which of the following configuration files shows the best way to define a database connection string in an application configuration file?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<connectionStrings>

<add name="AdventureWorksString" providerName="System.Data.SqlClient"

connectionString="Data Source=localhost;Initial Catalog=AdventureWorks; Integrated Security=true"/>

</connectionStrings>

</configuration>

Explanation:

The .NET Framework 2.0 adds support for the <connectionStrings> configuration section for defining database connection information. Define this section within the <configuration> section using the <add> element with properties of name, providerName, and connectionString.

While you can define database connection information in the appSettings section (and you had no choice in earlier versions of the .NET Framework), your best choice is to use the strongly-typed <connectionStrings> section.

2. You are writing an application that requires the user to open a second application named "Application.exe", make a configuration change, and then close the application. You want to automatically launch the application for the user, and then wait indefinitely until the user closes the application. Which of the following code samples accomplishes this?

' VB

Dim p As Process = New Process

p.StartInfo.FileName = "Application.exe"

p.Start

p.WaitForExit

Explanation:

To launch a new process, first create an instance of the Process class, and then specify the Process.StartInfo.FileName property. Finally, call the Process.Start method. To stop processing until the application closes, call the Process.WaitForExit method without specifying a time.

You cannot specify an application filename in the Process constructor.

Specifying a time for the Process.WaitForExit method causes the runtime to continue execution after the specified time even if the application hasn't closed.

You cannot specify an application filename in the Process constructor. Additionally, specifying a time for the Process.WaitForExit method causes the runtime to continue execution after the specified time even if the application hasn't closed.

3. As part of a troubleshooting tool for the systems administrators at your organization, you are writing a command-line tool that automatically kills any unresponsive applications. Which of the following code samples accomplishes this?

' VB

For Each p As Process In Process.GetProcesses

If Not p.Responding Then

p.Kill

End If

Next

Explanation: First, you must retrieve an array of all processes by calling Process.GetProcesses. Then you should call Process.Kill for each process that you need to terminate.

There is no Process.GetUnresponsiveProcesses method, and Process.Kill is not a static method.

4. You are creating a tool for the IT department that displays the MAC address and description of every network adapter on a remote computer with the IP address 192.168.1.200. Which of the following code samples does this correctly?

' VB

Dim ms As ManagementScope = New ManagementScope("\\192.168.1.200\root\cimv2")

Dim oq As ObjectQuery = New ObjectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration")

Dim mos As ManagementObjectSearcher = New ManagementObjectSearcher(ms, oq)

Dim moc As ManagementObjectCollection = mos.Get

For Each mo As ManagementObject In moc

Console.WriteLine(mo("MacAddress") + ": " + mo("Description"))

Next

Explanation:

To query running network adapters on a remote computer:

1. Create a ManagementScope object to define the remote computer. The scope is not simply the computer name, however. It must be in the form "\\computername\root\cim2".

2. Create an instance of ObjectQuery using a Windows Management Instrumentation (WMI) query. The WMI query must be in the form "SELECT fields FROM Win32_NetworkAdapterConfiguration".

3. Create an instance of ManagementObjectSearcher by providing both the scope and the query.

4. Create an instance of ManagementObjectCollection by calling the ManagementObjectSearcher.Get method.

You can then iterate through the ManagementObjects in the ManagementObjectCollection to examine individual network adapters.

You can create a ConnectionsOptions object if you want to specify a username and password. However, you cannot use a ConnectionsOptions object in place of a ManagementScope object.

5. You are writing an application that communicates with a database. You need to be able to communicate with any type of database configured by the system administrator. Systems administrators can choose either a Microsoft SQL Server, Oracle, OleDB, or ODBC connection. Which of the following code samples would establish a database connection named db to any of those database types?

' VB

Dim css As ConnectionStringSettings = ConfigurationManager.ConnectionStrings(0)

Dim db As IDBConnection = Nothing

Select css.ProviderName

Case "System.Data.SqlClient"

db = New SqlConnection(css.ConnectionString)

' break

Case "System.Data.OracleClient"

db = New OracleConnection(css.ConnectionString)

' break

Case "System.Data.OleDb"

db = New OleDbConnection(css.ConnectionString)

' break

Case "System.Data.Odbc"

db = New OdbcConnection(css.ConnectionString)

' break

End Select

Explanation:

To determine the database type based on a ConnectionStringSettings object, examine ConnectionStringSettings.ProviderName.

ConnectionStringSettings.Name stores the server name, not the database type.

ConnectionStringSettings.ConnectionString stores the entire connection string, which does not include the database type.

ConnectionStringSettings.ElementInformation.Type describes the type of element, which will always be System.Configuration.ConnectionStringSettings.

6. You are writing an application that stores window state in the application's configuration file. Given the following configuration file, which of the following code samples correctly tests the IsMaximized element in a .NET Framework 2.0 application? (Choose all that apply.)

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="IsMinimized" value="False"/>

<add key="IsMaximized" value="True"/>

<add key="username" value="user1"/>

</appSettings>

</configuration>

Answer ' VB

If ConfigurationManager.AppSettings("IsMaximized") = "True" Then

' VB

If ConfigurationManager.AppSettings.Get("IsMaximized") = "True" Then

Explanation:

The ConfigurationManager.AppSettings collection provides access to elements defined in the <appSettings> section of a configuration file. Because it is a collection, you can access elements as an

array or by using the Get method.

The ConfigurationSettings class is obsolete in the .NET Framework 2.0.

ConfigurationManager does not contain AppSettings elements. You must access ConfigurationManager.AppSettings instead.

7. Which of the following configuration files correctly defines the information required to connect to a database by defining the first element of ConfigurationManager.ConnectionStrings regardless of other configuration files that might exist?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<connectionStrings>

<clear/>

<add name="AdventureWorksString"

providerName="System.Data.SqlClient"

connectionString="Data Source=localhost;Initial Catalog=AdventureWorks; Integrated Security=true"/>

</connectionStrings>

</configuration>

Explanation:

To define the first element of ConfigurationManager.ConnectionStrings, you must include the <clear/> element, which removes any existing <connectionStrings> elements. You must set the providerName attribute to the database type, such as System.Data.SqlClient. The Name element is a friendly name used to refer to that specific connection string.

8. Which of the following code samples successfully writes the entire contents of the Application log to the console?

' VB

Dim el As New EventLog()

el.Log = "Application"

For Each ele As EventLogEntry In el.Entries

Console.WriteLine(ele.Source + ": " + ele.Message)

Next

Explanation: To read an entire log file, create an instance of the EventLog class, specify the EventLog.Log property, and then iterate through EventLog.Entries. EventLog.Entries is an EventLogEntryCollection property containing EventLogEntry objects.

9. While performing a security review of a peer's code, you see an If statement that checks the ConfigurationManager.AppSettings("username") value and grants additional privileges if it is equal to "Tom". You need to test the behavior, but the application does not currently have a configuration file. How would you create the configuration file to define that value?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="username" value="Tom"/>

</appSettings>

</configuration>

Explanation:

Elements accessed through ConfigurationManager.AppSettings must be defined in the application configuration file, in an <appSettings> element nested within <configuration>. To define a specific

key, use the <add key> element.

10. You are writing an application that communicates with a database. The connection string is stored in the application configuration file. Which of the following would correctly retrieve the connection string?

' VB

ConfigurationManager.ConnectionStrings(0).ConnectionString

Explanation: ConfigurationManager.ConnectionStrings is a collection of type ConnectionStringSettingsCollection that contains the connection strings loaded from the application's configuration file. Because it is a collection, you must access it using an index. ConfigurationSettings, which is obsolete, does not contain a ConnectionStrings property.

11. You have created a custom event log for your application. Your application provides tools for managing the event log, and one of the methods you need to implement clears all events from the event log. Which of the following code samples would do this?

' VB

Public Sub ClearEventLog()

Dim el As New EventLog("MyApp")

el.Source = "DemoApp"

el.Clear()

End Sub

Explanation: To clear an event log, create an EventLog object and specify the EventLog.Source property. Then call EventLog.Clear.

There is no EventLog.Commit or EventLog.Log.Clear method.

Iterating through EventLogEntry objects and calling EventLogEntry.Dispose would not remove the events from the event log; it would only destroy the instances of the EventLogEntry objects created

in the runtime.

12. Which of the following code samples correctly displays the modules loaded by Application.exe?

' VB

Dim p As Process = New Process

p.StartInfo.FileName = "Application.exe"

p.Start

For Each m As ProcessModule In p.Modules

Console.WriteLine(m.FileName)

Next

Explanation: To retrieve a list of modules loaded by a process, access the ProcessModule array in Process.Modules.

Process.Modules is an array of ProcessModule objects, not ProcessModuleCollection, and Process.Modules is not a static method.

13. As a favor to your IT department, you are writing a console application that outputs information related to the security of the current computer. Which of the following code samples correctly displays running services?

' VB

Dim oq As New ObjectQuery("SELECT Caption FROM Win32_Service WHERE Started = TRUE")

Dim mos As New ManagementObjectSearcher(oq)

Dim moc As ManagementObjectCollection = mos.Get

For Each mo As ManagementObject In moc

Console.WriteLine(mo("Caption").ToString())

Next

Explanation:

To query running services:

1. Create an instance of ObjectQuery using a Windows Management Instrumentation (WMI) query. The WMI query must be in the form "SELECT fields FROM Win32_Service WHERE criteria". In this case, the criteria must be "WHERE Started = True" to return services that have started.

2. Create an instance of ManagementObjectSearcher based on the query.

3. Next, create an instance of ManagementObjectCollection by calling the ManagementObjectSearcher.Get method.

You can then iterate through the ManagementObjects in the ManagementObjectCollection to examine individual services.

ManagementObjectSearcher.Query is a property used to define the query; it is not a method. You must use ManagementObjectSearcher.Get to run a query.

14. You need to establish a database connection to a server based on configuration information stored in the application's configuration file. Which of the following properties would you examine to determine the server name?

Answer: ConnectionStringSettings.Name

Explanation:

ConnectionStringSettings.Name stores the server name.

The ConnectionStringSettings.ProviderName describes the database type and allows you to distinguish between Oracle, SQL Server, and other databases.

ConnectionStringSettings.ConnectionString stores the entire connection string, which does not include the server name.

ConnectionStringSettings.ElementInformation.Properties contains all the attributes that apply to the element. It does not normally include a Name element.

15. Which class would you use to programmatically access the connection strings stored in the following configuration file?

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<connectionStrings>

<clear/>

<add name="AdventureWorksString"

providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=AdventureWorks; Integrated Security=true"/>

<add name="MarsEnabledSqlServer2005String" providerName="System.Data.SqlClient" connectionString="Server=Aron1;Database=pubs;Trusted_Connection=True;MultipleActiveResultSets=true" />

<add name="OdbcConnectionString"

providerName="System.Data.Odbc"

connectionString="Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\adatabase.mdb;Uid=Admin;Pwd=R3m3emberToUseStrongPasswords;"/>

</connectionStrings>

</configuration>

Answer: ConfigurationManager.ConnectionStrings

Explaination:

Use ConfigurationManager.ConnectionStrings to access database connection strings

16. You are writing an application that performs long-running calculations. To minimize the impact on the responsiveness of the user's computer, you want to warn the user if your application is running at Normal or higher priority. Which of the following code samples accomplishes this?

' VB

If Process.GetCurrentProcess.BasePriority >= 8 Then

Console.WriteLine("For best results, run this application at low priority.")

End If

Explanation: You should examine the Process.GetCurrentProcess().BasePriority property. A value of 4 is considered low priority, 8 is normal priority, 13 is high priority, and 24 is real-time priority. Therefore, a value of 8 or higher indicates the current application is running at Normal priority.

There is no Process.BasePriority.IsNormal property.

There is no Process.BasePriority.IsLow property.

Checking Process.GetCurrentProcess().BasePriority for a value of 4 or higher would be true even if the process were running as a low priority.

17. You are writing an application that remembers a username in the application settings. Which of the following code samples is the best way to retrieve a username?

' VB

Dim nvc As NameValueCollection = ConfigurationManager.AppSettings

Dim un As String = nvc("username")

Explanation: When writing assemblies for the .NET Framework version 2.0, you should use ConfigurationManager.AppSettings instead of ConfigurationSettings.AppSettings. ConfigurationSettings is now obsolete, and using it will result in a compiler warning.

ConfigurationManager.AppSettings does not have a GetSetting method.

18. You are in the process of isolating a complicated bug in a console application that occurs only in rare circumstances. You want to be able to write messages to the Output window in Microsoft Visual Studio 2005, as shown in the following figure. Which of the following code samples accomplishes this by writing the message, "Entering main processing loop"?

clip_image002

Answer:

' VB

Dim dtl As New DefaultTraceListener

Trace.Listeners.Add(dtl)

Debugger.Log(2, "Information", "Entering main processing loop")

Explanation: To write information to the Output window, first create an instance of DefaultTraceListener. Then add it to the Trace.Listeners collection. Finally, call Debugger.Log to write the message. Debugger.Log takes three parameters: a level, a category, and a message. The third parameter is the message that appears in the Output window.

There is no Trace.Listeners.Log method.

19. You need to provide users with a list of network drives so that they can choose where to store a file. Which of the following code samples correctly displays network drives and available space?

' VB

Dim oq As New ObjectQuery("SELECT Size, Name FROM Win32_LogicalDisk where DriveType=4")

Dim mos As New ManagementObjectSearcher(oq)

Dim moc As ManagementObjectCollection = mos.Get

For Each mo As ManagementObject In moc

Console.WriteLine(mo("Name").ToString() + ", Free Space: " + mo("Size").ToString())

Next

Explanation:

To query available drives:

1. Create an instance of ObjectQuery using a Windows Management Instrumentation (WMI) query. The WMI query must be in the form "SELECT fields FROM Win32_LogicalDisk WHERE criteria".

2. Create an instance of ManagementObjectSearcher based on the query.

3. Create an instance of ManagementObjectCollection by calling the ManagementObjectSearcher.Get method.

You can then iterate through the ManagementObjects in the ManagementObjectCollection to examine individual drives.

ManagementObjectSearcher.Get is not a static method; you must create an instance to use it.

  • Installer class: The following steps need to be taken to use a class derived from the Installer class:
    • * Inherit the Installer class.
    • * Override the Install, Commit, Rollback, and Uninstall methods.
    • * Add the RunInstallerAttribute to your derived class, and set it to true.
    • * Put your derived class in the assembly with your application to install.
    • * Invoke the installers.

The Installer class does not have OnInstall, OnCommit, OnRollback, or OnUninstall methods.

  • To uninstall the installation, only the following tasks need to be done:
    • 1. Create a new AssemblyInstaller or ComponentInstaller object.
    • 2. Specify the name of the assembly or application.
    • 3. Call the Uninstall method.

The Rollback method is used to cancel an installation that is in progress before it is committed. The Commit method finalizes an installation.

  • EventLogEntry.InstanceId, in the .NET Framework version 2.0, defines the Event ID number shown in the Event Log console.
    • EventLogEntry.EventID was used to define the Event ID in the .NET Framework versions 1.0 and 1.1; however, it is now obsolete.
    • EventLogEntry.Index gets the index of an event in the Event Log.
    • EventLogEntry.Source gets the name of the application that generated the event.
  • To wait for a management event:

1. Create a new ManagementEventWatcher object.

2. Associate an EventQuery object with the ManagementEventWatcher object.

3. Call the ManagementEventWatcher.WaitForNextEvent method.

4. Call the ManagementEventWatcher.Stop method.

    • You do not need to call the ManagementEventWatcher.Start method when calling ManagementEventWatcher.WaitForNextEvent. You only need to call ManagementEventWatcher.Start when
  • registering an event handler.
  • When writing an Application that must perform event logging, the correct time to create an event source is during installation.

o You should create a new event source durning app installation. This will require the user to have admin privileges.

o You only need to create an event source once. Therefore, it is unnecessary to create it before each event.

o You should create a new event source during application installation, rather than before you write the first event.

· Application that performs event logging are supported by the following OS’

o Windows Server 2003

o Windows XP

· OnBeforeInstall – is the method of the installer class which is called first when installing an app.

o When installing an app, methods are called in the following order: OnBeforeInstaller, Install, OnAfterInstall, OnCommiting, Commit, & finally Oncommitted

  • Debug.Assert – evaluates a condition & displays a message to the debugging output window. Debug methods do not run in release code. Ex. To assist w/ debugging, you want to write an output message if a configuration setting has not been defined. You do not want to waste processing time in released code. You should use the Debug.Assert method
    • Debug.Fail causes the debugger to break @ the line of code & output a failure message.
    • Debug.Flush flushes the debug output buffer
    • Debug.Indent controls the output formatting
  • Debugger.Break – acts just like a hard-coded breakpoint, except you can call it programmatically. You would like to pause execution to examine the value of variables during debugging, but you do not want to pause execution when users run release versions of the app. You should use the Debugger.Break method.
    • Console.Read & Console.ReadLine interrupt processing in both debug & release versions of code.
    • Debug.Assert validates a value & does not stop execution during debugging.
  • Application configuration files should be located in the same folder as the executable file & named <filename.exe> config. ex. You are writing a windows form app called MyApp. You need to define application settings & database connection strings in a custom configuration file in the same folder as your MyApp.exe file You should name the configuration file MyApp.exe.config.
  • You are writing an app that adds events to an event log. Based on the EventLogEntryType enumeration, the following are valid entry types:
    • Error
    • Information
    • Warning
    • FailureAudit
    • SuccessAudit
  • Debugger.Log – Debugger Log posts information to the attached Debugger in one is present. If no Debugger is present, the results is effectively nothing. ex. You need to write info to the debugging console, but you do not want to waste processing cycles when users run release versionso f the application. You should call the Debugger.Log method
  • To query local resources, you need instances of ObjectQuery, ManagementObjectSearcher & ManagementObjectCollection. You need to perform a management query for resources located on the local computer. You’ll need to create instances of the following classes:
    • ManagementObjectSearcher
    • ObjectQuery
    • ManagementObjectCollection
  • PerformanceCounter.RawValue – offers the best performance in single-threaded app. Ex. You are writing a single threaded app that performs custom performance logging to enable users to use the Performance console to track the current number of users who have connected to your app. You should call the PerformanceCounter.RawValue
    • PerformanceCounter.Decrement words well in Multi-Threaded environments. However PerformanceCounter.RawValue offers the best performance in single-treaded apps
  • Rollback method – to remove changes made during installation when install is cancelled.
    • The Install method performs the actual installation
    • The Commit method finalizes the installation changes
    • The OnCommitting method runs immediately before the Commit method
    • There is no OnRollback method
  • PerformanceCounter.Decrement – works well in multithreaded environments, Because users are disconnecting you would want to decrease the user counter. Ex. you’re writing a multithreaed app that performs custom logging to enable users to use the Performance console to track the current number of users who have connected to your app. You should call the PerformanceCounter.Decrement method when a user disconnects.
    • You would call Performancecounter.Increment when a user connects, not disconnects.
    • You would call PerformanceCounter.IncrementBy when a user connects, not disconnects.
    • PerformanceCounter.RawValue would offer better performance than PerformanceCounter.Decrement. However PerformanceCounter.RawValue may yield an inaccurate count in multithreaded apps.
  • Application event log – You should always write events to the Application event log or a custom event log. ex. You are writing an application that implements a custom authentication mechanism. You should write entries related to unsuccessful authentication attempts to the application event log.
    • The Security log is reserved for the operating system to store auditing events.
    • The System event log is reserved for operating system events.
    • The Active Directory event log is reserved for events relating to an Active Directory domain controller.
  • Commit – During a successful installation, Installer.Commit is the last method called, Commit finalizes all changes made during the installation.
  • Debug.Fail – causes the debugger to break at the line of code & output a failure message. ex. you want to verify an important value & stop execution if the value is not set properly. However, you only want to stop execution during debugging. You don’t want users with released versions of your app to experience problems. You should use the Debug.Fail method
    • Debug.Assert evaluates a condition & displays a message, but it does not interrupt processing.
    • Debug.Flush flushes the debug output buffer
    • Debug.Indent controls the output formatting.

Thursday, August 27, 2009

70-536 MCTS .NET 2.0 Configuration #32

 

Hey Now Everybody,

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 .NET 2.0 Configuration GAC GAC!.

Thx,

Catto

  • .NET Framework 2.0 Configuration

clip_image002

          • Chapter 9 Lesson 2
  • Click on the node you should use to view & fix dependencies
    • To view, manage, & fix dependencies. First click the application node. If necessary, add the application. Then select the application & click View The Assembly Dependencies or Fix This App
  • Click on the node you should use to make an assembly globally available
    • The assembly cache contains the set of assemblies available to all applications targeting the .NET Framework. Mutiple versions of the same assembly can be placed in the assembly cache. This allows two applications to correctly execute even if they require different versions of the same shared assembly.
  • Click on the node you should use to configure binding policy.
    • Binding policy allows you to specify a new version of the assembly when an application requests a different version. To configure binding policy the assembly must first be in the global assembly cache (GAC). Then you can configure it from the Configured Assemblies node
  • Click on the node you should use to view permission sets
    • You should use the Runtime Security Policy node. The .NET Framework 2.0 Config tool gives you the ability to evaluate code groups & permissions sets that apply to an assembly. This is especially critical in Active Directory environments, where policy can be applied at the enterprise, machine, & user levels.

70-536 MCTS .NET #31 Implementation Section 4

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
  • 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.
  • 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.
  • 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 arrayFileStream.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.
  • BinaryFormatterclass 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.
  1. 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.
  2. 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.
  3. 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.
  1. 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.

  1. 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.

  1. 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.
  2. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.
  2. 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.

  1. 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.

  1. 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.