Monday, August 24, 2009

70-536 MCTS .NET Foundations #25

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#80 – Q#99

Question: 80

You work as a developer at Company.com. You are developing an application to create a new file on the local file system.

You need to define specific security settings for the file. You must deny the file inheritance of any default security settings.
What should you do?

Answer: ?

K8 – not so good of a question. No answers or answer.

Question: 81

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

A. Public Class Person

Implements IComparable(Of String)Public Function CompareTo(ByVal other As String)

As _Integer Implements IComparable(Of String).CompareTo...End FunctionEnd Class

B. Public Class Person

Implements IComparable(Of String)Public Function CompareTo(ByVal other As Object)

As _Integer Implements IComparable(Of String).CompareTo...End FunctionEnd Class

C. Public Class Person

Implements IComparable(Of String)Public Function CompareTo(ByVal other As String)

_As Boolean Implements IComparable(Of String).CompareTo...End FunctionEnd Class

D. Public Class Person

Implements IComparable(Of String)Public Function CompareTo(ByVal other As Object)

_As Boolean Implements IComparable(Of String).CompareTo...End FunctionEnd Class

Answer: A

K8 – String & IComparable as int

Question: 82

You work as a developer at Company.com. You create a service application that monitors free space on a hard disk drive. You must ensure that the service application runs in the background and monitors the free space every minute.

What should you do?

Answer:

K8 – Another not so good question no answers

Question: 83

You are creating a class that performs complex financial calculations. The class contains a method named GetCurrentRate that retrieves the current interest rate and a variable named currRate that stores the current interest rate.
You write serialized representations of the class. You need to write a code segment that updates the currRate variable with the current interest rate when an instance of the class is deserialized. Which code segment should you use?

A. [OnSerializing]internal void UpdateValue (StreamingContext context) {

currRate = GetCurrentRate();}

B. [OnSerializing]internal void UpdateValue(SerializationInfo info) {

info.AddValue(“currentRate”, GetCurrentRate());}

C. [OnDeserializing]internal void UpdateValue(SerializationInfo info) {

info.AddValue(“currentRate”, GetCurrentRate());}

D. [OnDeserialized]internal void UpdateValue(StreamingContext context) {

currRate = GetCurrentRate();}

Answer: D

K8 – question reads when instance of class is deserialized. Answer is OnDeserialized

Question: 84

You need to write a multicast delegate that accepts a DateTime argument. Which code segment should you use?

A. Public Delegate Function PowerDeviceOn( _

ByVal result As Boolean, _

ByVal autoPowerOff As DateTime) _

As Integer

B. Public Delegate Function PowerDeviceOn( _

ByVal sender As Object, _

ByVal autoPowerOff As EventArgs) _

As Boolean

C. Public Delegate Sub PowerDeviceOn( _

ByVal autoPowerOff As DateTime)

D. Public Delegate Function PowerDeviceOn( _

ByVal autoPowerOff As DateTime) _

As Boolean

Answer: C

K8 – c is the only Sub not a function isn’t that something?

Question: 85

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

ref class Department {

public :

String^ name;

String^ manager;}; 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 ref class deptElement : public ConfigurationElement {

protected :
override void DeserializeElement(XmlReader^ reader,
bool^ serializeCollectionKey) {
Department^ dept = gcnew Department();
dept->name = ConfigurationManager::AppSettings[“name”];
dept->manager = ConfigurationManager::AppSettings[“manager”];
return dept; }};

B. public ref class deptElement : public ConfigurationElement {
protected :
override void DeserializeElement(XmlReader^ reader,
bool^ serializeCollectionKey) {
Department^ dept = gcnew Department();
dept->name = reader->GetAttribute(“name”);
dept->manager = reader->GetAttribute(“manager”); }};

C. public ref class deptHandler :
public IConfigurationSectionHandler {
public :
Object^ Create(Object^ parent, Object^ configContext,
System.Xml.XmlNode section) {
Department^ dept = gcnew Department();
dept->name = section->SelectSingleNode(“name”)->InnerText;
dept->manager = section->SelectSinglenode(“manager”)->InnerText;
return dept; }};
D. public ref class deptHandler : public IConfigurationSectionHandler {

public :
Object^ Create(Object^ parent, Object^ configContext,
System.Xml.XmlNode^ section) {
Department^ dept = gcnew Department();
dept->name = section->Attributes[“name”].Value;
dept->manager = section->Attributes[“manager”].Value;
return dept; }};

Answer: C

K8 – IconfigurationSectionHandler

Question: 86

You need to read the entire contents of a file named Message.txt into a single string variable. Which code segment should you use?

A. String^ result = nullptr;StreamReader^ reader = gcnew

StreamReader(“Message.txt”);result = reader->Read().ToString();

B. String^ result = nullptr;StreamReader^ reader = gcnew

StreamReader(“Message.txt”);
result = reader->ReadToEnd();

C. String^ result =String::Empty;StreamReader^ reader = gcnew

StreamReader(“Message.txt”); while (!reader->EndOfStream) {

result += reader->ToString();}

D. String^ result = nullptr;StreamReader^ reader = gcnew StreamReader(“Message.txt”); result =

reader->ReadLine();

Answer: B

K8 – ReadToEnd Now that I’ve seen this question a few times it gets easier.

Question: 87

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

Dim r As Integer = MessageBox(hWnd, strText, strCaption, strType)

You need to define a method prototype. Which code segment should you use?

A. <DllImport("user32")> _Function MessageBox( _

ByVal hWnd As IntPtr, ByVal text As String, _

ByVal Caption As String, ByVal t As UInt32) As IntegerEnd Function

B. <DllImport("user32")> _Function MessageBoxA( _

ByVal hWnd As IntPtr, ByVal text As String, _

ByVal Caption As String, ByVal t As UInt32) As IntegerEnd Function

C. <DllImport("user32")> _Function Win32API_User32_MessageBox ( _

ByVal hWnd As IntPtr, ByVal text As String, _

ByVal Caption As String, ByVal t As UInt32) As IntegerEnd Function

D. <DllImport("C:\WINDOWS\system32\user32.dll ")> _Function MessageBox( _

ByVal hWnd As IntPtr, ByVal text As String, _

ByVal Caption As String, ByVal t As UInt32) As IntegerEnd Function

Answer: A

K8 – User32 & function messagebox

Question: 88

You are writing an application that uses isolated storage to store user preferences. The application uses multiple assemblies. Multiple users will use this application on the same

computer. You need to create a directory named Preferences in the isolated storage area that is scoped to the current Microsoft Windows identity and assembly. Which code segment should you use?

A. IsolatedStorageFile^ store;store = IsolatedStorageFile::GetUserStoreForAssembly();store-

>CreateDirectory(“Preferences”);

B. IsolatedStorageFile^ store;store =

IsolatedStorageFile::GetMachineStoreForAssembly();store->CreateDirectory(“Preferences”);

C. IsolatedStorageFile^ store;store = IsolatedStorageFile::GetUserStoreForDomain();store-

>CreateDirectory(“Preferences”);

D. IsolatedStorageFile^ store;store =

IsolatedStorageFile::GetMachineStoreForApplication();store-

>CreateDirectory(“Preferences”);

Answer: A

K8 – GetUserStoreForAssembly

Question: 89

You are writing an application that uses isolated storage to store user preferences. The application uses multiple assemblies. Multiple users will use this application on the same
computer. You need to create a directory named Preferences in the isolated storage area that is scoped to the current Microsoft Windows identity and assembly. Which code segment should you use?

A. IsolatedStorageFile store;store =

IsolatedStorageFile.GetUserStoreForAssembly();store.CreateDirectory(“Preferences”);

B. IsolatedStorageFile store;store =

IsolatedStorageFile.GetMachineStoreForAssembly();store.CreateDirectory(“Preferences”);

C. IsolatedStorageFile store;store =

IsolatedStorageFile.GetUserStoreForDomain();store.CreateDirectory(“Preferences”);

D. IsolatedStorageFile store;store =

IsolatedStorageFile.GetMachineStoreForApplication();store.CreateDirectory(“Preferences”);

Answer: A

K8 - GetUserStoreForAssembly

Question: 90

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 – Demand to ensure all callers have required level of trust

Question: 91

You are using the Microsoft Visual Studio 2005 IDE to examine the output of a method that returns a string. You assign the output of the method to a string variable named fName. You need to write a code segment that prints the following on a single line The message: "Test Failed: " The value of fName if the value of fName does not equal "Company" You also need to ensure that the code segment simultaneously facilitates uninterrupted execution of the application. Which code
segment should you use?

A. Debug::Assert(fName == “Company”, “Test Failed: ”, fName);

B. Debug::WriteLinelf(fName != “Company”, fName, “Test Failed”);

C. if (fName != "Company") {

Debug::Print(“Test Failed: ”);

Debug::Print(fName);}

D. if (fName != "Company") {

Debug::WriteLine(“Test Failed: ”);

Debug::WriteLine(fName);}

Answer: B

K8 - WriteLinelf

Question: 92

Your company uses an application named Application1 that was compiled by using the .NET Framework version 1.0. The application currently runs on a shared computer on which the .NET Framework versions 1.0 and 1.1 are installed. You need to move the application to a new computer on which the .NET Framework versions 1.1 and 2.0 are installed. The application is compatible with the .NET Framework 1.1, but it is incompatible with the .NET Framework 2.0. You need to ensure that the application will use the .NET Framework version 1.1 on the new computer. What should you do?

A. Add the following XML element to the application configuration file.

<configuration>
<startup>
<supportedRuntime version="1.1.4322" />
<startup>
</configuration>

B. Add the following XML element to the application configuration file.

<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Application1" publicKeyToken="32ab4ba45e0a69a1" culture="neutral" />
<bindingRedirect oldVersion="1.0.3075.0" newVersion="1.1.4322.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

C. Add the following XML element to the machine configuration file.

<configuration>
<startup>
<requiredRuntime version="1.1.4322" />
<startup>
</configuration>

D. Add the following XML element to the machine configuration file.

<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Application1"
publicKeyToken="32ab4ba45e0a69a1" culture="neutral" />
<bindingRedirect oldVersion="1.0.3075.0" newVersion="1.1.4322.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Answer: A

K8 – set supportedRuntime version="1.1.4322"

Question: 93

You are developing a method that searches a string for a substring. The method will be localized to Italy. Your method accepts the following parameters: The string to be searched, which is named searchListThe string for which to search, which is named searchValue You need to write the code. Which code segment should you use?

A. return searchList->IndexOf(searchValue);

B. CompareInfo^ comparer =
gcnew CultureInfo(“it-IT”)::CompareInfo; return comparer->Compare(searchList, search Value);

C. CultureInfo^ comarer = gcnew CultureInfo(“it-IT”);
if (searchList->IndexOf(searchValue) > 0) {
return true;} else {
return false;}

D. CompareInfo^ comparer = gcnew CultureInfo(“it-IT”)::CompareInfo;
if (comparer->IndexOf(searchList, searchValue) > 0) {
return true;
} else {
return false;}

Answer: D

K8 – Method that searches string for substring CompareInfo IndexOf

Question: 94

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::SetuupInformation;
mySetup->ShadowCopyFiles = “true”;

B. System::Diagnostics::Process^ myProcess;
myProcess = gcnew System::Diagnostics::Process();

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

D. System::ComponentModel::Component^ myComponent;
myComponent = gcnew
System::ComponentModel::Component();

Answer: C

K8 – CLR isolation Appdomaion CreateDomain

Question: 95

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. Evidence evidence = new Evidence(
Assembly.GetExecutingAssembly().Evidence );

B. Evidence evidence = new Evidence();
evidence.AddAssembly(new Zone(SecurityZone.Intranet));

C. Evidence evidence = new Evidence()
;evidence.AddHost(new Zone(SecurityZone.Intranet));

D. Evidence evidence = new Evidence(
AppDomain.CurrentDomain.Evidence );

Answer: C

K8 – Loading Assembly use AddHost along with the Zone(SecurityZone.Intranet)

Question: 96

You are developing a class library that will open the network socket connections to computers on the network. You will deploy the class library to the global assembly cache and grant it full trust. You write the following code to ensure usage of the socket connections.
SocketPermission permission = new

SocketPermission(PermissionState.Unrestricted);
permission.Assert();
Some of the applications that use the class library might not have the necessary permissions to open the network socket
connections. You need to cancel the assertion. Which code segment should you use?

A. CodeAccessPermission.RevertAssert();

B. CodeAccessPermission.RevertDeny();

C. permission.Deny();

D. permission.PermitOnly();

Answer: A

K8 question text Cancel Assertion - Answer RevertAssert();

Question: 97

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. Dim objSecurity As New FileSecurity( _
"MyData.xml", AccessControlSections.All)objSecurity.SetAccessRuleProtection(True, True)File.SetAccessControl("MyData.xml", objSecurity)

B. Dim objSecurity As New FileSecurity()objSecurity.SetAccessRuleProtection(True,
True)File.SetAccessControl("MyData.xml", objSecurity)

C. Dim objSecurity As FileSecurity = _File.GetAccessControl("MyData.xml")objSecurity.SetAccessRuleProtection(True, True)

D. Dim objSecurity As FileSecurity =
_File.GetAccessControl("MyData.xml")objSecurity.SetAuditRuleProtection(True, True)File.SetAccessControl("myData.xml", objSecurity)

Answer: A

K8 – Q: prevent the access rules from inheriting changes A: SetAccessRuleProtection

Question: 98

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 void StartService(string serverName){

02 ServiceController crtl = new

03 ServiceController(“FileService”);

04 if (crtl.Status == ServiceControllerStatus.Stopped){

05 }

06 }

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

Q: need to start if stopped therefore E & MachineName in B will start it on the serverName

Question: 99

You are using the Microsoft Visual Studio 2005 IDE to examine the output of a method that returns a string. You assign the output of the method to a string variable named fName. You need to write a code segment that prints the following on a single line The message: "Test Failed: " The value of fName if the value of fName does not equal "Company" You also need to ensure that the code segment simultaneously facilitates uninterrupted execution of the application. Which code segment should you use?

A. Debug.Assert(fName = "Company", "Test Failed: ", fName)

B. Debug.WriteLineIf(fName <> "Company", _ fName, "Test Failed")

C. If fName <> "Company" Then
Debug.Print("Test Failed: ")
Debug.Print(fName)End If

D. If fName <> "Company" Then
Debug.WriteLine("Test Failed: ")
Debug.WriteLine(fName)End If

Answer: B

K8 – WriteLineIf prints the message if

Sunday, August 23, 2009

70-536 MCTS .NET Sample Questions #24

 

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#60 – Q#79

Question: 60

You are creating a strong-named assembly named Company1 that will be used in multiple applications. Company1 will be rebuilt frequently during the development cycle. You need to ensure that each time the assembly is rebuilt it works correctly with each application that uses it. You need to configure the computer on which you develop Company1 such that each application uses the latest build of Company1. Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)

A. Create a DEVPATH environment variable that points to the build output directory for the strong-named assembly.

B. Add the following XML element to the machine configuration file:

<developmentMode developerInstallation="true"/>

C. Add the following XML element to the machine configuration file:

<dependentAssembly>

<assemblyIdentity name="Company1"

publicKeyToken="32ab4ba45e0a69a1"

language="en-US" version="*.*.*.*" />

<publisherPolicy apply="no" />

</dependentAssembly>

D. Add the following XML element to the configuration file of each application that uses the

strong-named assembly:

<supportedRuntime version="*.*.*.*" />

E. Add the following XML element to the configuration file of each application that uses the

strong-named assembly:

<dependentAssembly>

<assemblyIdentity name="Company1"

publicKeyToken="32ab4ba45e0a69a1"

language="en-US" version="*.*.*.*" />

<bindingRedirect newVersion="*.*.*.*"/>

</dependentAssembly>

Answer: A, B

K8 – developerInstallation = true & create a devpath to point to build.

Question: 61

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 ref class Person : public IComparable<String^>{

public : virtual Int32 CompareTo(String^ other){

}}

B. public ref class Person : public IComparable<String^>{

public : virtual Int32 CompareTo(Object^ other){

}}

C. public ref class Person : public IComparable<String^>{

public : virtual Boolean CompareTo(String^ other){

}}

D. public ref class Person : public IComparable<String^>{

public : virtual Boolean CompareTo(Object^ other){

}}

Answer: A

K8 – use Int32 & CompareTo String

Question: 62

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. Dim objAlgo As HashAlgorithm = HashAlgorithm.Create("MD5")

Dim hash() As Byte = objAlgo.ComputeHash(message)

B. Dim objAlgo As HashAlgorithm = HashAlgorithm.Create("MD5")
Dim hash() As Byte = BitConverter.GetBytes(objAlgo.GetHashCode)

C. Dim objAlgo As HashAlgorithmobjAlgo =

HashAlgorithm.Create(message.ToString)
Dim hash() As Byte = objAlgo.Hash

D. Dim objAlgo As HashAlgorithm = HashAlgorithm.Create("MD5")
Dim hash() As

ByteobjAlgo.TransformBlock(message, 0, message.Length, hash, 0)

Answer: A

K8 – toss c out & ComputeHash is important method too.

Question: 63

You write the following custom exception class named CustomException.

Public Class CustomException

Inherits ApplicationException

Public Shared COR_E_ARGUMENT As Int32 = &H80070057

Public Sub New(ByVal strMessage As String)

MyBase.New(strMessage)

HResult = COR_E_ARGUMENT

End SubEnd Class

You need to write a code segment that will use the CustomException class to immediately return control to the COM caller. You also need to ensure that the caller has access to the error code. Which code segment should you use?

A. Return Marshal.GetExceptionForHR( _

CustomException.COR_E_ARGUMENT)

B. Return CustomException.COR_E_ARGUMENT

C. Marshal.ThrowExceptionForHR( _

CustomException.COR_E_ARGUMENT)

D. Throw New CustomException("Argument is out of bounds")

Answer: D

K8 Throw an exeption so the control will go to the COM

Question: 64

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 = gcnew IsolatedStorageFileStream(

“Settings.dat”, FileMode::Open); String^ result = (gcnew StreamReader(isoStream))-

>ReadToEnd();

B. IsolatedStorageFile^ isoFile;

isoFile = IsolatedStorageFile::GetMachineStoreForAssembly();

IsolatedStorageFileStream^ isoStream;isoStream = gcnew IsolatedStorageFileStream(

“Settings.dat”, FileMode::Open, isoFile); String^ result = (gcnew StreamReader(isoStream))-

>ReadToEnd();

C. IsolatedStorageFileStream^ isoStream;isoStream = gcnew IsolatedStorageFileStream(

“Settings.dat”, FileMode::Open);String^ result = isoStream->ToString();

D. IsolatedStorageFile^ isoFile;isoFile = IsolatedStorageFile::GetMachineStoreForAssemblly();

IsolatedStorageFileStream^ isoStream;isoStream = gcnew IsolatedStorageFileStream(

“Settings.dat”, FileMode::Open, isoFile); String^ result = isoStream->ToString();

Answer: B

Question: 65

You are developing a fiscal report for a customer. Your customer has a main office in the United States and a satellite office in Mexico. You need to ensure that when users in the satellite office generate the report, the current date is displayed in Mexican Spanish format. Which code segment should you use?

A. Dim DTFormat As DateTimeFormatInfo = _

New CultureInfo("es-MX", False).DateTimeFormat

Dim DT As New DateTime( _

DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day)Dim strDate As

String = _

DT.ToString(DTFormat.LongDatePattern)

B. Dim objCalendar As Calendar = _

New CultureInfo("es-MX", False).CalendarDim DT As New DateTime( _

DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day)Dim strDate As

String = DT.ToString

C. Dim strDate As String = _

DateTimeFormatInfo.CurrentInfo.GetMonthName( _

DateTime.Today.Month)

D. Dim strDate As String = _

DateTime.Today.Month.ToString("es-MX")

Answer: A

K8 - DateTimeFormat

Question: 66

You are defining a class named CompanyClass that contains several child objects. CompanyClass contains a method named ProcessChildren that performs actions on the child objects. CompanyClass objects will be serializable. You need to ensure that the ProcessChildren method is executed after the CompanyClass object and all its child objects are reconstructed. Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)

A. Apply the OnDeserializing attribute to the ProcessChildren method.

B. Specify that CompanyClass implements the IDeserializationCallback interface.

C. Specify that CompanyClass inherits from the ObjectManager class.

D. Apply the OnSerialized attribute to the ProcessChildren method.

E. Create a GetObjectData method that calls ProcessChildren.

F. Create an OnDeserialization method that calls ProcessChildren.

Answer: B, F

K8 – Key words in question ‘executed after the class object’ OnDeserialization & IDeserializationCallback

Question: 67

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

A. for each (Object^ e in q) {

q.Dequeue();}

B. for each (Object^ e in q) {

q.Enqueue(0);}

C. q.Clear();

D. q.Dequeue();

Answer: C

K8 – I think 87 year old Granny could get this one right

Question: 71

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

A. Dim e As ObjectFor Each e In qq.Dequeue()Next

B. Dim e As ObjectFor Each e In qq.Enqueue(Nothing)Next

C. q.Clear()

D. q.Dequeue()

Answer: C

Question: 68

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(int i = 0; i < 80; i++){

stream1->WriteByte(byteArray[i]);

bytesTransferred = i;

if (!stream1->CanWrite) {

break;

}}

C. while (bytesTransferred < 80) {

stream1->Seek(1, SeekOrigin::Current);

byteArray[bytesTransferred++] =

Convert::ToByte(stream1->ReadByte());}

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

Answer: A

K8 – Read(byteArray, 0, 80); is the syntax

Question: 69

You are developing an application that dynamically loads assemblies from an application directory. You need to write a code segment that loads an assembly named Company1.dll into the current application domain. Which code segment should you use?

A. AppDomain domain = AppDomain.CurrentDomain;
string myPath = Path.Combine(domain.BaseDirectory,

“Company1.dll”);
Assembly asm = Assembly.LoadFrom(myPath);

B. AppDomain domain = AppDomain.CurrentDomain;
string myPath =

Path.Combine(domain.BaseDirectory, “Company1.dll”);
Assembly asm = Assembly.Load(myPath);

C. AppDomain domain = AppDomain.CurrentDomain;string myPath =

Path.Combine(domain.DynamicDirectory, “Company1.dll”);Assembly asm =

AppDomain.CurrentDomain.Load(myPath);

D. AppDomain domain = AppDomain.CurrentDomain;Assembly asm =

domain.GetData(“Company1.dll”);

Answer: A

K8 – Load From is important in this question

Question: 70

You are developing an application that will use custom authentication and role-based security. You need to write a code segment to make the runtime assign an unauthenticated principal object to each running thread. Which code segment should you use?

A. Dim objDomain As AppDomain =

AppDomain.CurrentDomainobjDomain.SetPrincipalPolicy( _

PrincipalPolicy.WindowsPrincipal)

B. Dim objDomain As AppDomain =

AppDomain.CurrentDomainobjDomain.SetThreadPrincipal(New

WindowsPrincipal(Nothing))

C. Dim objDomain As AppDomain =

AppDomain.CurrentDomainobjDomain.SetAppDomainPolicy( _

PolicyLevel.CreateAppDomainLevel())

D. Dim objDomain As AppDomain =

AppDomain.CurrentDomainobjDomain.SetPrincipalPolicy( _

PrincipalPolicy.UnauthenticatedPrincipal)

Answer: D

K8 – (PrincipalPolicy.UnauthenticatedPrincipal)

Question: 72

You develop a service application that needs to be deployed. Your network administrator creates a specific user account for your service application. You need to configure your service application to run in the context of this specific user account. What should you do?

A. Prior to installation, set the StartType property of the ServiceInstaller class.

B. Prior to installation, set the Account, Username, and Password properties of the ServiceProcessInstaller class.

C. Use the CONFIG option of the net.exe command-line tool to install the service.

D. Use the installutil.exe command-line tool to install the service.

Answer: B

K8 – ServiceProcessInstaller class when run app as user

Question: 73

You need to create a class definition that is interoperable along with COM. You need to ensure that COM applications can create instances of the class and can call the GetAddress method. Which code segment should you use?

A. Public Class Customer
Private m_AddressString As String
Public Sub New(ByVal Address As String)
m_AddressString = Address
End Sub

Public Function GetAddress() As String
Return m_AddressString
End FunctionEnd Class

B. Public Class Customer
Shared m_AddressString As String
Public Sub New()
End Sub
Public Shared Function GetAddress() As String
Return m_AddressString
End FunctionEnd Class

C. Public Class Customer
Private m_AddressString As String
Public Sub New()
End Sub
Public Function GetAddress() As String
Return m_AddressString
End FunctionEnd Class

D. Public Class Customer
Private m_AddressString As String
Public Sub New()
End Sub
Private Function GetAddress() As String
Return m_AddressString
End FunctionEnd Class

Answer: C

K8 – GetAddress should be Public

Question: 74

You are creating a new security policy for an application domain. You write the following lines of code.
Dim objPolicy As PolicyLevel = PolicyLevel.CreateAppDomainLevelDim

noTrustStatement As New PolicyStatement( _

objPolicy.GetNamedPermissionSet("Nothing"))

Dim fullTrustStatement As New PolicyStatement( _

objPolicy.GetNamedPermissionSet("FullTrust"))

You need to arrange code groups for the policy so that loaded assemblies default to the Nothing permission set. If the assembly originates from a trusted zone, the security policy must grant the assembly the FullTrust permission set. Which code segment should you use?

A. Dim objGroup1 As CodeGroup = New FirstMatchCodeGroup(
_ New ZoneMembershipCondition(SecurityZone.Trusted), _

fullTrustStatement)
Dim objGroup2 As CodeGroup = New UnionCodeGroup( _

New AllMembershipCondition, noTrustStatement)

B. Dim objGroup1 As CodeGroup = New FirstMatchCodeGroup( _ New AllMembershipCondition, noTrustStatement)
Dim objGroup2 As CodeGroup = New UnionCodeGroup( _

New ZoneMembershipCondition(SecurityZone.Trusted), _
fullTrustStatement)

C. Dim objGroup As CodeGroup = New UnionCodeGroup( _
New ZoneMembershipCondition(SecurityZone.Trusted), _
fullTrustStatement)

D. Dim objGroup As CodeGroup = New FirstMatchCodeGroup( _
New ZoneMembershipCondition(SecurityZone.Trusted), _
fullTrustStatement)

Answer: B

K8 – AllMembershipCondition & SecurityZone.Trusted

Question: 75

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. Evidence^ evidence = gcnew

Evidence(Assembly::GetExecutingAssembly()->Evidence);

B. Evidence^ evidence = gcnew Evidence();
evidence->AddAssembly(gcnew Zone(SecurityZone::Intranet));

C. Evidence^ evidence = gcnew Evidence();
evidence->AddHost(gcnew Zone(SecurityZone::Intranet));

D. Evidence^ evidence = gcnew Evidence(AppDomain::CurrentDomain->Evidence);

Answer: C

K8 – Question states internet security zone SecurityZone::Intranet

Question: 76

You need to read the entire contents of a file named Message.txt into a single string variable. Which code segment should you use?

A. string result = null;StreamReader reader = new StreamReader(“Message.txt”);result =

reader.Read().ToString();

B. string result = null;
StreamReader reader = new StreamReader(“Message.txt”);
result = reader.ReadToEnd();

C. string result = string.Empty;StreamReader reader = new StreamReader(“Message.txt”);
while

(!reader.EndOfStream) {

result += reader.ToString();}

D. string result = null;StreamReader reader = new StreamReader(“Message.txt”);result =

reader.ReadLine();

Answer: B

K8 – ReadToEnd works to read the entire file. Toss D out readline won’t get entire file

Question: 77

You need to generate a report that lists language codes and region codes. Which code segment should you use?

A. For Each objCulture As CultureInfo In

_CultureInfo.GetCultures(CultureTypes .SpecificCultures)

...Next

B. Dim objCulture As New CultureInfo("")Dim objTypes As CultureTypes = objCulture.CultureTypes ...

C. For Each objCulture As CultureInfo In

_CultureInfo.GetCultures(CultureTypes.NeutralCultures)

...Next

D. For Each objCulture As CultureInfo In

_CultureInfo.GetCultures(CultureTypes.ReplacementCultures)

...Next

Answer: A

K8 – SpecificCultures is needed & loop till we get them all.

Question: 78

You are developing a class library that will open the network socket connections to computers on the network. You will deploy the class library to the global assembly cache and grant it full trust. You write the following code to ensure usage of the socket connections.

Dim objPermission As SocketPermission = New

_SocketPermission(System.Security.Permissions.PermissionState.Unrestricted)objPermission.As

sert()

Some of the applications that use the class library might not have the necessary

permissions to open the network socket connections.

You need to cancel the assertion.

Which code segment should you use?

A. CodeAccessPermission.RevertAssert()

B. CodeAccessPermission.RevertDeny()

C. objPermission.Deny()

D. objPermission.PermitOnly()

Answer: A

K8 – Cancel the assertion – doesn’t RevertAssert() fit like a glove?

Question: 79

You are writing an application that uses SOAP to exchange data with other applications. You use a Department class that inherits from ArrayList to send objects to another application.
The Department object is named dept. You need to ensure that the application serializes the Department object for transport by using SOAP. Which code should you use?

A. Dim formatter As New SoapFormatter()Dim buffer As Byte() = New

Byte(dept.Capacity) {}Dim myStream As New MemoryStream(buffer) Dim o As

ObjectFor Each o In dept

formatter.Serialize(myStream, o)Next

B. Dim formatter As New SoapFormatter()
Dim buffer As Byte() = New Byte(dept.Capacity)Dim myStream As New

MemoryStream(buffer)formatter.Serialize(myStream, dept)

C. Dim formatter As New SoapFormatter()Dim myStream As New MemoryStream()Dim

o as ObjectFor Each o In dept

formatter.Serialize(myStream, o)Next

D. Dim formatter As New SoapFormatter()
Dim myStream As New

MemoryStream()formatter.Serialize(myStream, dept)

Answer: D

K8 – for the serialize the object name dept is needed.

70-536 MCTS .NET Sample Questions #23

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. 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#51 – Q#59

 

Question: 51

You need to create a dynamic assembly named MyAssembly. You also need to save the assembly to disk. Which code segment should you use?

A. AssemblyName myAssemblyName =

new AssemblyName();myAssemblyName.Name = “MyAssembly”;AssemblyBuilder

myAssemblyBuilder =

AppDomain.CurrentDomain.DefineDynamicAssembly

(myAssemblyName,

AssemblyBuilderAccess.Run);myAssemblyBuilder.Save(“MyAssembly.dll”);

B. AssemblyName myAssemblyName =

new AssemblyName();myAssemblyName.Name = “MyAssembly”;AssemblyBuilder

myAssemblyBuilder =

AppDomain.CurrentDomain.DefineDynamicAssembly

(myAssemblyName,

AssemblyBulderAccess.Save);myAssemblyBuilder.Save(“MyAssembly.dll”);

C. AssemblyName myAssemblyName =

new AssemblyName();AssemblyBuilder myAssemblyBuilder =

AppDomain.CurrentDomain.DefineDynamicAssembly

(myAssemblyName,

AssemblyBuilderAccess.RunAndSave);myAssemblyBuilder.Save(“MyAssembly.dll”);

D. AssemblyName myAssemblyName =

new AssemblyName(“MyAssembly”);AssemblyBuilder myAssemblyBuilder =

AppDomain.CurrentDomain.DefineDynamicAssembly

(myAssemblyName,

AssemblyBuilderAccess.Save);myAs semblyBuilder.Save(“c:\\MyAssembly.dll”);

Answer: B

K8 - myAssemblyBuilder.Save is needed

Question: 52

You need to call an unmanaged function from your managed code by using platform invoke services. What should you do?

A. Create a class to hold DLL functions and then create prototype methods by using managed code.

B. Register your assembly by using COM and then reference your managed code from COM.

C. Export a type library for your managed code.

D. Import a type library as an assembly and then create instances of COM object.

Answer: A

K8 – Create a class, in the question pinvoke is stated so DLL is in answer.

Question: 53

You are developing a class library that will open the network socket connections to computers on the network. You will deploy the class library to the Global Assembly Cache and grant it full trust. You write the following code to ensure usage of the socket connections.

SocketPermission^ permission =

gcnew SocketPermission(PermissionState::Unrestricted);permission->Assert(); Some of the

applications that use the class library might not have the necessary permissions to open the

network socket connections.

You need to cancel the assertion. Which code segment should you use?

A. CodeAccessPermission::RevertAssert();

B. CodeAccessPermission::RevertDeny();

C. permission->Deny();

D. permission->PermitOnly();

Answer: A

K8 - CodeAccessPermission & ReverAssert()

Question: 54

You need to identify a type that meets the following criteria:

Is always a number.

Is not greater than 65,535. Which type should you choose?

A. System.UInt16

B. int

C. System.String

D. System.IntPtr

Answer: A

K8 - UInt16 is the type that meets the required.

Question: 55

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))

throw new Exception(“could not authenticate user”);String[] userRolesArray =

LookupUserRoles(userName);

You need to complete this code so that it establishes the user security context. Which code segment should you use?

A. GenericIdentity ident = new GenericIdentity(userName);

GenericPrincipal currentUser = new

GenericPrincipal(ident, userRolesArray);Thread.CurrentPrincipal = currentUser;

B. WindowsIdentity ident = new WindowsIdentity(userName);WindowsPrincipal currentUser =

new WindowsPrincipal(ident);Thread.CurrentPrincipal = currentUser;

C. NTAccount userNTName = new NTAccount(userName);GenericIdentity ident = new

GenericIdentity(userNTName.Value);GenericPrincipal currentUser= new

GenericPrincipal(ident, userRolesArray);Thread.CurrentPrincipal = currentUser;

D. IntPtr token = IntPtr.Zero;token = LogonUserUsingInterop(username,

encryptedPassword);WindowsImpersonationContext ctx =

WindowsIdentity.Impersonate(token);

Answer: A

K8 – GenericIdentity

Question: 56

You are developing an application for a client residing in Hong Kong. You need to display negative currency values by using a minus sign. Which code segment should you use?

A. NumberFormatInfo culture = new CultureInfo(“zh-HK”).NumberFormat;

culture.NumberNegativePattern = 1; return numberToPrint.ToString(“C”, culture);

B. NumberFormatInfo culture = new CultureInfo(“zh-HK”).NumberFormat;

culture.CurrencyNegativePattern = 1; return numberToPrint.ToString(“C”, culture);

C. CultureInfo culture = new CultureInfo(“zh-HK”);return numberToPrint.ToString(“-(0)”, culture);

D. CultureInfo culture = new CultureInfo(“zh-HK”); return numberToPrint.ToString(“()”, culture);

Answer: B

K8 – Cultureinfo & CurrencyNegativePattern

Question: 57

You are developing an application that will perform mathematical calculations. You need to ensure that the application is able to perform multiple calculations simultaneously.

What should you do?

A. Set the IdealProcessor property of the ProcessThread object.

B. Set the ProcessorAffinity property of the ProcessThread object.

C. For each calculation, call the QueueUserWorkItem method of the ThreadPool class.

D. Set the Process.GetCurrentProcess().BasePriority property to High.

Answer: C

K8 – QueueUserWorkItem of Thead pool for multiple simultaneous Calculations.

Question: 58

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.

ref class PollingService : public ServiceBase {

public :

static bool blnExit = false;

protected :

override void OnStart(String^ args) {

do {

DoWork();

} while (!blnExit);

}

override void OnStop() {

blnExit = true;

}

private :

void DoWork() {} };

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 var & set enabled property to true & call start method.

Question: 59

You are creating an assembly named Company1. Company1 contains a public method. The global cache contains a second assembly named Company2. You must ensure that the public method is only called from Company2. Which permission class should you use?

A. GacIdentityPermission

B. PublisherIdentityPermission

C. DataProtectionPermission

D. StrongNameIdentityPermission

Answer: D

K8 – Good Old StrongNameIdentityPermission class

Saturday, August 22, 2009

70-536 MCTS .NET Sample Questions #22

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. 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#33 – Q#50

Question: 33

You are developing an application that receives events asynchronously. You create a WqlEventQuery instance to specify the events and event conditions to which the application must respond. You also create a ManagementEventWatcher instance to subscribe to events matching the query. You need to identify the other actions you must perform before the application can receive events asynchronously. Which two actions should you perform? (Each correct answer presents part of the solution. Choose two.)

A. Start listening for events by calling the Start method of the ManagementEventWatcher.

B. Set up a listener for events by using the EventArrived event of the ManagementEventWatcher.

C. Use the WaitForNextEvent method of the ManagementEventWatcher to wait for the events.

D. Create an event handler class that has a method that receives an ObjectReadyEventArgs

parameter.

E. Set up a listener for events by using the Stopped event of the ManagementEventWatcher.

Answer: A, B

K8 – Start & EventArrived of ManagementEventWatcher

Question: 34

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. MemoryStream^ memStream = gcnew

MemoryStream(8192);memStream->Write(dataToSend, 0, (int) netStream->Length);

B. MemoryStream^ memStream = gcnew

MemoryStream(8192);netStream->Write(dataToSend, 0, (int) memStream->Length);

C. BufferedStream^ bufStream =

gcnew BufferedStream(netStream, 8192);bufStream->Write(dataToSend, 0, dataToSend- >Length);

D. BufferedStream^ bufStream =

gcnew BufferedStream(netStream);bufStream->Write(dataToSend, 0, 8192);

Answer: C

K8 – BufferedStream not Memory Stream C is correct Syntax

Question: 35

You are writing a method to compress an array of bytes. The array is passed to the method in a parameter named document. You need to compress the incoming array of bytes and return the result as an array of bytes. Which code segment should you use?

A. MemoryStream strm = new MemoryStream(document);

B. DeflateStream deflate = new DeflateStream(strm,

CompressionMode.Compress); byte[] result = new byte[document.Length];deflate.Write(result,

0, result.Length); return result;

B. MemoryStream strm = new MemoryStream(document);

DeflateStream deflate = new

DeflateStream(strm,

CompressionMode.Comress);deflate.Write(docemtn, 0,

document.Length);deflate.Close();return strm.ToArray();

C. MemoryStream strm = new MemoryStream();

DeflateStream deflate = new

DeflateStream(strm, CompressionMode.Compress);deflate.Write(decument, 0,

decument.Length);deflate.Close();return strm.ToArray();

D. MemoryStream inStream = new MemoryStream(document);

DeflateStream deflate =

new DeflateStream(inStream, CompressionMode.Compress); MemoryStream outStream =

new MemoryStream();int b;while ((b = deflate.ReadByte()) ! = -1) {

outStream.WriteByte((byte)b);} return outStream.ToArray();

Answer: C

K8 - MemoryStream();

Question: 36

You need to select a class that is optimized for key-based item retrieval from both small and large collections. Which class should you choose?

A. OrderedDictionary class

B. HybridDictionary class

C. ListDictionary class

D. Hashtable class

Answer: B

K8 – Key Based Items Large & small collections HybridDictionary Class.

Question: 37

You are writing an application that uses SOAP to exchange data with other applications. You use a Department class that inherits from ArrayList to send objects to another application.

The Department object is named dept. You need to ensure that the application serializes the Department object for transport by using SOAP. Which code should you use?

A. SoapFormatter formatter = new SoapFormatter();byte[] buffer = new

byte[dept.Capacity];MemoryStream stream = new MemoryStream(buffer);

foreach

(object o in dept) {

formatter.Serialize(stream, o);}

B. SoapFormatter formatter = new SoapFormatter();byte[] buffer = new

byte[dept.Capacity];MemoryStream stream = new MemoryStream(buffer);

formatter.Serialize(stream, dept);

C. SoapFormatter formatter = new SoapFormatter();MemoryStream stream = new

MemoryStream();

foreach (object o in dept) {

Formatter.Serialize(stream, o);}

D. SoapFormatter formatter = new SoapFormatter();

MemoryStream stream = new

MemoryStream(); formatter.Serialize(stream, dept);

Answer: D

K8 Need MemorySteam & dept / class name in the Serialize parameters.

Question: 38

You create a class library that contains the class hierarchy defined in the following code segment. (Line numbers are included for reference only.)

01. public ref class Employee {

02.03. public : 04.

String^ Name;05. };06.07. public ref class Manager : public Employee {08.09.

public :10.

int Level;11. };12.13. public ref class Group {

14.15. public : 16. array<Employee^>^

Employees;17. };

You create an instance of the Group class. You populate the fields of the instance. When you attempt to serialize the instance by using the Serialize method of the XmlSerializer class, you receive InvalidOperationException. You also receive the following error message: "There was an error generating the XML document." You need to modify the code segment so that you can successfully serialize instances of the Group class by using the XmlSerializer class. You also need to ensure that the XML output contains an element for all public fields in the class hierarchy. What should you do?

A. Insert the following code between lines 14 and 15 of the code segment:

[XmlArrayItem(Type = __typeof(Employee))]

[XmlArrayItem(Type = __typeof(Manager))]

B. Insert the following code between lines 14 and 15 of the code segment:

[XmlElement(Type = __typeof(Employees))]

C. Insert the following code between lines 14 and 15 of the code segment:

[XmlArray(ElementName="Employees")]

D. Insert the following code between lines 3 and 4 of the code segment:

[XmlElement(Type = __typeof(Employee))]

andInsert the following code segment between lines 8 and 9 of the code segment:

[XmlElement(Type = __typeof(Manager))]

Answer: A

K8 XmlArrayItem

Question: 39

You need to write a code segment that performs the following tasks:

Retrieves the name of each paused service.

Passes the name to the Add method of Collection1. Which code segment should you use?

A. Dim searcher As ManagementObjectSearcher = _New ManagementObjectSearcher( _

"Select * from Win32_Service where State = 'Paused'")For Each svc As

ManagementObject In searcher.Get()

Collection1.Add(svc("DisplayName"))Next

B. Dim searcher As ManagementObjectSearcher = _New ManagementObjectSearcher ( _

"Select * from Win32_Service", "State = 'Paused'")For Each svc As ManagementObject

In searcher.Get()

Collection1.Add(svc("DisplayName"))Next

C. Dim searcher As ManagementObjectSearcher = _ New ManagementObjectSearcher( _

"Select * from Win32_Service")For Each svc As ManagementObject In searcher.Get()

If svc("State").ToString() = "'Paused'" Then

Collection1.Add(svc("DisplayName"))

End IfNext

D. Dim searcher As New ManagementObjectSearcher()searcher.Scope = New

ManagementScope("Win32_Service")For Each svc As ManagementObject In

searcher.Get()

If svc("State").ToString() = "Paused" Then

Collection1.Add(svc("DisplayName"))

End IfNext

Answer: A

K8 need the where clause to select all the ‘paused’

Question: 40

You are writing a method that accepts a string parameter named message. Your method must break the message parameter into individual lines of text and pass each line to a second method named Process. Which code segment should you use?

A. Dim reader As New

StringReader(message)ProcessMessage(reader.ReadToEnd())reader.Close()

B. Dim reader As New StringReader(message)

While reader.Peek() <> -1

Dim line as String = reader.Read().ToString()

ProcessMessage(line)End Whilereader.Close()

C. Dim reader As New

StringReader(message)ProcessMessage(reader.ToString())reader.Close()

D. Dim reader As New StringReader(message)While reader.Peek() <> -1

ProcessMessage(reader.ReadLine())End Whilereader.Close()

Answer: D

K8 – Need the reader.Peek to find the blank space to break & reader.ReadLine() Looks like A & C can be tossed out.

Question: 41

You need to create a class definition that is interoperable along with COM. You need to ensure that COM applications can create instances of the class and can call the GetAddress method. Which code segment should you use?

A. public class Customer {

string addressString;

public Customer(string address) { addressString = address; }

public string GetAddress() { return addressString; }}

B. public class Customer {

static string addressString;

public Customer() { }

public static string GetAddress() { return addressString; }}

C. public class Customer {

string addressString;

public Customer() { }

public string GetAddress() { return addressString; }}

D. public class Customer {

string addressString;

public Customer() { }

internal string GetAddress() { return addressString; }}

Answer: C

K8 – B can be tossed out with static String adressString; D can be out with the syntax internal string

Question: 42

You are creating a class that performs complex financial calculations. The class contains a method named GetCurrentRate that retrieves the current interest rate and a variable named currRate that stores the current interest rate. You write serialized representations of the class. You need to write a code segment that updates the currRate variable with the current interest rate when an instance of the class is deserialized. Which code segment should you use?

A. [OnSerializing]void UpdateValue (StreamingContext^ context) {

currRate = GetCurrentRate();}

B. [OnSerializing]void UpdateValue(SerializationInfo^ info) {

info->AddValue(“currentRate”, GetCurrentRate());}

C. [OnDeserializing]void UpdateValue(SerializationInfo^ info) {

info->AddValue(“currentRate”, GetCurrentRate());}

D. [OnDeserialized]void UpdateValue(StreamingContext^ context) { currRate = GetCurrentRate();}

Answer: D

K8 – in question states when an instance of the class is deserialized. Therefore we use OnDeserialized.

Question: 43

You are developing a class library. Portions of your code need to access system environment variables. You need to force a runtime SecurityException only when callers that are higher in the call stack do not have the necessary permissions. Which call method should you use?

A. set.Demand();

B. set.Assert();

C. set.PermitOnly();

D. set.Deny();

Answer: A

K8 Demand first thought was deny

Question: 44

You are developing a fiscal report for a customer. Your customer has a main office in the United States and a satellite office in Mexico. You need to ensure that when users in the satellite office generate the report, the current date is displayed in Mexican Spanish format. Which code segment should you use?

A. CultureInfo^ culture = gcnew CultureInfo(“es-MX”, false);DateTimeFormatInfo^ dtfi = culture-

>DateTimeFormat;DateTime^ dt = gcnew DateTime(DateTime::Today::Year,

DateTime::Today::Month, DateTime::Today::Day);String^ dateString = dt->ToString(dtfi-

>LongDatePattern);

B. Calendar^ cal = gcnew CultureInfo(“es-MX”, false)::Calendar; DateTime^dt = gcnew

DateTime(DateTime::Today::Year, DateTime::Today::Month, DateTime::Today::Day);

String^dateString = dt-> ToString();

C. String^ dateString =

DateTimeFormatInfo::CurrentInfo::GetMonthName(DateTime::Today::Month);

D. String^ dateString = DateTime::Today::Month::ToString(“es-MX”);

Answer: A

K8 – need cultureinfo right

Question: 45

You create an application that stores information about your customers who reside in various regions. You are developing internal utilities for this application. You need to gather regional information about your customers in Canada. Which code segment should you use?

A. for each (CultureInfo^ culture in

CultureInfo::GetCultures(CultureTypes::SpecificCultures)) {

// Output the region information...}

B. CultureInfo^ cultureInfo = gcnew CultureInfo(“CA”);

// Output the region information...

C. RegionInfo^ regionInfo = gcnew RegionInfo(“CA

// Output the region information...

D. RegionInfo^ regionInfo = gcnew RegionInfo(“”);if(regionInfo->Name == “CA”){

// Output the region information...}

Answer: C

K8 Region is more specific & is needed for CA nada

Question: 46

You need to generate a report that lists language codes and region codes. Which code segment should you use?

A. for each (CultureInfo^ culture in

CultureInfo::GetCultures(CultureTypes::SpecificCultures)) {

// Output the culture information...}

B. CultureInfo^ culture = gcnew CultureInfo(“”); CultureTypes^ types = culture->CultureTypes;

// Output the culture information...

C. for each (CultureInfo^ culture in

CultureInfo::GetCultures(CultureTypes::NeutralCultures)) {

// Output the culture information...}

D. for each (CultureInfo^ culture in

CultureInfo::GetCultures(CultureTypes::ReplacementCultures)) {

// Output the culture information...}

Answer: A

K8 – just reading answers B can be tossed out since no loop; CultureTypes::SpecificCultures is needed

Question: 47

You are developing a method to hash data with the Secure Hash 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 SHA1. You also need to place the result into a byte array named hash. Which code segment should you use?

A. SHA1 sha = new SHA1CryptoServiceProvider();byte[] hash =

null;sha.TransformBlock(message, 0, message.Length, hash, 0);

B. SHA1 sha = new SHA1CryptoServiceProvider();byte[] hash =

BitConverter.GetBytes(sha.GetHashCode());

C. SHA1 sha = new SHA1CryptoServiceProvider();byte[] hash = sha.ComputeHash(message);

D. SHA1 sha = new SHA1CryptoServiceProvider();sha.GetHashCode();byte[] hash = sha.Hash;

Answer: C

K8 - ComputeHash method

Question: 48

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”);byte[] hash =

algo.ComputeHash(message);

B. HashAlgorithm algo = HashAlgorithm.Create(“MD5”);byte[] hash =

BitConverter.GetBytes(algo.GetHashCode());

C. HashAlgorithm algo;algo = HashAlgorithm.Create(message.ToString());byte[] hash =

algo.Hash;

D. HashAlgorithm algo = HashAlgorithm.Create(“MD5”);byte[] hash =

null;algo.TransformBlock(message, 0, message.Length, hash, 0);

Answer: A

K8 – SHA1 or MD5 the ComputeHash is need for the requirements asked in the question.

Question: 49

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. Dim objUser As WindowsIdentity = WindowsIdentity.GetCurrentFor Each objGroup

As IdentityReference In objUser.Groups

Dim objNT As NTAccount = _

DirectCast(objGroup.Translate( _

Type.GetType("NTAccount")), NTAccount)

Dim blnAuth As Boolean = objNT.Value.Equals( _

Environment.MachineName & "\Clerk")

If blnAuth Then Exit ForNext

B. Dim objUser As WindowsPrincipal = _

DirectCast(Thread.CurrentPrincipal, WindowsPrincipal)Dim blnAuth As Boolean =

objUser.IsInRole("Clerk")

C. Dim objUser As GenericPrincipal = _

DirectCast(Thread.CurrentPrincipal, GenericPrincipal)Dim blnAuth As Boolean =

objUser.IsInRole("Clerk")

D. Dim objUser As WindowsPrincipal = _

DirectCast(Thread.CurrentPrincipal, WindowsPrincipal)Dim blnAuth As Boolean = _

objUser.IsInRole(Environment.MachineName)

Answer: B

K8 – IsInRole is needed & WindowsPrincipal

Question: 50

You write the following code to call a function from the Win32 Application Programming Interface (API) by using platform invoke. int rc = MessageBox(hWnd, text, caption, type); You need to define a method prototype. Which code segment should you use?

A. [DllImport("user32")]extern int MessageBox(int hWnd, String^ text, String^ caption, uint type);

B. [DllImport("user32")]extern int MessageBoxA(int hWnd, String^ text, String^ caption, uint type);

C. [DllImport("user32")]extern int Win32API_User32_MessageBox(

Int hWnd, String^ text, String^ caption, uint type);

D. [DllImport("C:\\WINDOWS\\system32\\user32.dll")]extern int MessageBox(int

hWnd, String^ text,

String^ caption, uint type);

Answer: A

K8 - int rc = MessageBox(hWnd, text, caption, type); in questions in key info.

70-536 MCTS .NET Question Samples #21

 

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. 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. The questions are numbered from  #13 - #32.

Thx,

Catto

 

Question: 13

You are developing an application for a client residing in Hong Kong. You need to display negative currency values by using a minus sign. Which code segment should you use?

A. Dim objCulture As NumberFormatInfo = _

New CultureInfo("zh-HK").NumberFormatobjCulture.NumberNegativePattern = 1

Return NumberToPrint.ToString("C", objCulture)

B. Dim objCulture As NumberFormatInfo = _

New CultureInfo("zh-HK").NumberFormatobjCulture.CurrencyNegativePattern =

1Return NumberToPrint.ToString("C", objCulture)

Exam Code: 70-536

C. Dim objCulture As NumberFormatInfo = _

New CultureInfo("zh-HK").NumberFormatReturn NumberToPrint.ToString("-{0}",

objCulture)

D. Dim objCulture As NumberFormatInfo = _

New CultureInfo("zh-HK").NumberFormatReturn NumberToPrint.ToString("()",

objCulture)

Answer: B

IF answer is B

NumberFormatobjCulture & CurrencyNegativePattern

for the code is important. Along with 1Return NumberToPrint.ToString("C", objCulture)

Question: 18

You are developing an application for a client residing in Hong Kong. You need to display negative currency values by using a minus sign. Which code segment should you use?

A. NumberFormatInfo^ culture =

gcnew CultureInfo(“zh-HK”)::NumberFormat; culture->NumberNegativePattern = 1;

return numberToPrint->ToString(“C”, culture);

Exam Code: 70-536

B. NumberFormatInfo^ culture =

gcnew CultureInfo(“zh-HK”)::NumberFormat; culture->CurrencyNegativePattern = 1;

return numberToPrint->ToString(“C”, culture);

C. CultureInfo^ culture =

gcnew CultureInfo(“zh-HK”); return numberToPrint->ToString(“-(0)”, culture);

D. CultureInfo^ culture =

gcnew CultureInfo(“zh-HK”); return numberToPrint->ToString(“()”, culture);

Answer: B

K8 – Same question as above but differes a little.

Question: 14

Your application uses two threads, named thread One and thread Two. You need to modify the code to prevent the execution of thread One until thread Two completes execution.

What should you do?

A. Configure threadOne to run at a lower priority.

B. Configure threadTwo to run at a higher priority.

C. Use a WaitCallback delegate to synchronize the threads.

D. Call the Sleep method of threadOne.

E. Call the SpinLock method of threadOne.

Answer: C

K8- Course – When I’m thinking theading WaitCallback will prevent execution for another thead to complete.

Question: 15

You are developing a method to hash data with the Secure Hash 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 SHA1. You also need to place the result into a byte array named hash. Which code segment should you use?

A. Dim objSHA As New SHA1CryptoServiceProviderDim hash() As Byte =

NothingobjSHA.TransformBlock(message, 0, message.Length, hash, 0)

B. Dim objSHA As New SHA1CryptoServiceProviderDim hash() As Byte =

BitConverter.GetBytes(objSHA.GetHashCode)

C. Dim objSHA As New SHA1CryptoServiceProviderDim hash() As Byte =

objSHA.ComputeHash(message)

D. Dim objSHA As New SHA1CryptoServiceProviderobjSHA.GetHashCode()Dim

hash() As Byte = objSHA.Hash

Answer: C

K8 – SHA1 – use SHA1CryptoServiceProvider Dim also important for this question objSHA.ComputeHash(message)

Question: 19

You are developing a method to hash data with the Secure Hash 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 SHA1. You also need to place the result into a byte array named hash. Which code segment should you use?

A. SHA1 ^sha = gcnew SHA1CryptoServiceProvider();array<Byte>^hash = nullptr;sha-

>TransformBlock(message, 0, message->Length, hash, 0);

B. SHA1 ^sha = gcnew SHA1CryptoServiceProvider();array<Byte>^hash =

BitConverter::GetBytes(sha->GetHashCode());

C. SHA1 ^sha = gcnew SHA1CryptoServiceProvider();array<Byte>^hash = sha-

>ComputeHash(message);

D. SHA1 ^sha = gcnew

SHA1CryptoServiceProvider();sha->GetHashCode();array<Byte>^hash = sha->Hash;

Answer: C

K8 – Important SHA1CryptoServiceProvider

Question: 16

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. class MyDictionary : Dictionary<string, string>

B. class MyDictionary : HashTable

C. class MyDictionary : IDictionary

D. class MyDictionary { ... }

Dictionary<string, string> t = new Dictionary<string, string>();MyDictionary dictionary =

(MyDictionary)t;

Answer: A

K8 – Dictionary Type safe so Generics are good maybe? When reading this I didn’t think B could be the answer.

Question: 17

Exam Code: 70-536

You work as a developer at Company.com. You are creating an application that provides information about the local computer. The application contains a form that lists each logical drive

with the drive properties, such as type, volume label, and capacity. You are required to write a procedure that retrieves properties of each logical drive on the local computer.

What should you do?

Arrange the appropriate actions in the correct order.

Answer:

K8 – Hmm this didn’t display too well maybe revisit this question later.

Question: 20

You are writing an application that uses SOAP to exchange data with other applications. You use a Department class that inherits from ArrayList to send objects to another application.

The Department object is named dept. You need to ensure that the application serializes the Department object for transport by using SOAP. Which code should you use?

A. SoapFormatter^ formatter = gcnew SoapFormatter();array<Byte>^ buffer = gcnew

array<Byte>(dept->Capacity);MemoryStream^ stream = gcnew MemoryStream(buffer);

for each (Object^ o in dept) {

formatter->Serialize(stream, o);}

B. SoapFormatter^ formatter = gcnew SoapFormatter();array<Byte>^ buffer = gcnew

array<Byte>(dept->Capacity);MemoryStream^ stream = gcnew MemoryStream(buffer);

formatter->Serialize(stream, dept);

C. SoapFormatter^ formatter = gcnew SoapFormatter();MemoryStream^ stream = gcnew

MemoryStream();for each (Object^ o in dept) {

formatter->Serialize(stream, o);}

D. SoapFormatter^ formatter = gcnew SoapFormatter();MemoryStream^ stream = gcnew

MemoryStream();formatter->Serialize(stream, dept);

Answer: D

K8 - SoapFormatter();MemoryStream^ stream & formatter->Serialize(stream, dept);

Question: 21

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. Dim mySetup As AppDomainSetup = _

AppDomain.CurrentDomain.SetupInformationmySetup.ShadowCopyFiles = "true"

Exam Code: 70-536

B. Dim myProcess As System.Diagnostics.Process myProcess = New

System.Diagnostics.Process()

C. Dim domain As AppDomain domain =

AppDomain.CreateDomain("CompanyDomain")

D. Dim myComponent As System.ComponentModel.ComponentmyComponent = New

System.ComponentModel.Component()

Answer: C

K8 – Isolation in question & AppDomain in answer

Question: 22

You are testing a newly developed method named PersistToDB. This method accepts a parameter of type EventLogEntry. This method does not return a value. You need to create a code segment that helps you to test the method. The code segment must read entries from the application log of local computers and then pass the entries on to the PersistToDB method. The

code block must pass only events of type Error or Warning from the source MySource to the PersistToDB method. Which code segment should you use?

A. EventLog^ myLog = gcnew EventLog(“Application”, “.”);

for each (EventLogEntry^ entry in myLog->Entries) {

if (entry->Source == "MySource") {

PersistToDB(entry);

}}

B. EventLog^ myLog = gcnew EventLog(“Application”, “.”);

myLog->Source = “MySource”;

for each (EventLogEntry^ entry in myLog->Entries) {

if (entry->EntryType == (EventLogEntryType::Error &

EventLogEntryType::Warning)) {

PersistToDB(entry);}}

C. EventLog^ myLog = gcnew EventLog(“Application”, “.”);

for each (EventLogEntry^ entry in myLog->Entries) {

if (entry->Source == "MySource") {

if (entry->EntryType == EventLogEntryType::Error ||

entry->EntryType == EventLogEntryType::Warning) {

PersistToDB(entry);

}

}}

D. EventLog^ myLog = gcnew EventLog(“Application”, “.”);

myLog->Source = “MySource”;

for each (EventLogEntry^ entry in myLog->Entries) {

if (entry->EntryType == EventLogEntryType::Error ||

entry->EntryType == EventLogEntryType::Warning) {

PersistToDB(entry);

}}

Answer: C

K8 – Check if the it’s from the “source ” then warning or || Error.

Question: 23

You are developing an application that will use custom authentication and role-based security. You need to write a code segment to make the runtime assign an unauthenticated principal object to each running thread. Which code segment should you use?

A. AppDomain^ domain =

AppDomain::CurrentDomain;domain->

SetPrincipalPolicy(PrincipalPolicy::WindowsPrincipal);

B. AppDomain^ domain =

AppDomain::CurrentDomain;domain->SetThreadPrincipal(gcnew WindowsPrincipal(nullptr));

C. AppDomain^ domain =

AppDomain::CurrentDomain;domain-

>SetAppDomainPolicy(PolicyLevel::CreateAppDomainLevel());

D. AppDomain^ domain =

AppDomain::CurrentDomain;domain-

>SetPrincipalPolicy(PrincipalPolicy::UnauthenticatedPrincipal);

Answer: D

K8 SetPrincipalPolicy along with Unauth

Question: 24

You write the following code. public delegate

void FaxDocs(Object^ sender, FaxArgs^ args); You need to create an event that will invoke FaxDocs. Which code segment should you use?

A. public : static event FaxDocs^ Fax;

B. public : static event Fax^ FaxDocs;

C. public ref class FaxArgs : public EventArgs {

public :

String^ CoverPageInfo;

FaxArgs (String^ coverInfo) {

this->CoverPageInfo = coverInfo;

}};

D. public ref class FaxArgs : public EventArgs {

public :

String^ CoverPageInfo;};

Answer: A

K8 – Public : static event FaxDocs Fax;

Another answer would be I think Public : static event FaxDocs myFaxDocVariable;

Question: 28

You write the following code. public delegate void FaxDocs(object sender, FaxArgs args); You need to create an event that will invoke FaxDocs. Which code segment should you use?

A. pulic static event FaxDocs Fax;

B. public static event Fax FaxDocs;

C. public class FaxArgs : EventArgs {

private string coverPageInfo;

public FaxArgs(string coverInfo) {

this.coverPageInfo = coverPageInfo;

}

public string CoverPageInformation {

get {return this.coverPageInfo;}

}}

D. public class FaxArgs : EventArgs {

private string coverPageInfo;

public string CoverPageInformation {

get {return this.coverPageInfo;}

}}

Answer: A

K8 – Repeat?

Question: 25

You create an application to send a message by e-mail. An SMTP server is available on the local subnet. The SMTP server is named smtp.Company.com. To test the application, you use a source address, me@Company.com, and a target address,

you@Company.com. You need to transmit the e-mail message. Which code segment should you use?

A. MailAddress addrFrom =

new MailAddress(“me@Company.com”, “Me”);MailAddress addrTo =

new MailAddress(“you@Company.com”, “You”);MailMessage message = new

MailMessage(addrFrom, addrTo);message.Subject = “Greetings!”;message.Body =

“Test”;message.Dispose();

B. string strSmtpClient = “mstp.Company.com”;string strFrom = “me@Company.com”;string strTo

= “you@Company.com”;string strSubject = “Greetings!”;string strBody = “Test”;MailMessage

msg = new MailMessage(strFrom, strTo, strSubject, strSmtpClient);

C. MailAddress addrFrom = new MailAddress(“me@Company.com”);MailAddress addrTo = new

MailAddress(“you@Company.com”);MailMessage message = new MailMessage(addrFrom,

addrTo);message.Subject = “Greetings!”;message.Body = “Test”;SmtpClient client = new

SmtpClient(“smtp.Company.com”);client.Send(message);

D. MailAddress addrFrom =

new MailAddress(“me@Company.com”, “Me”);MailAddress addrTo = new

MailAddress(“you@Company.com”, “You”);MailMessage message = new

MailMessage(addrFrom, addrTo);message.Subject = “Greetings!”;message.Body =

“Test”;SocketInformation info = new SocketInformation();Socket client = new

Socket(info);System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();byte[]

msgBytes = enc.GetBytes(message.ToString());client.Send(msgBytes);

Exam Code: 70-536

Answer: C

K8 - SmtpClient( after the MailAddress addForm

Question: 26

You are developing a custom-collection class. You need to create a method in your class. You need to ensure that the method you create in your class returns a type that is compatible with the Foreach statement. Which criterion should the method meet?

A. The method must return a type of either IEnumerator or IEnumerable.

B. The method must return a type of IComparable.

C. The method must explicitly contain a collection.

D. The method must be the only iterator in the class.

Answer: A

K8 – IEnum since For loops need to count

Question: 27

You are developing an application to perform mathematical calculations. You develop a class named CalculationValues. You write a procedure named PerformCalculation that operates on an instance of the class. You need to ensure that the user interface of the application continues to respond while calculations are being performed. You need to write a code segment that calls the PerformCalculation procedure to achieve this goal. Which code segment should you use?

A. private void PerformCalculation() {...} private void DoWork(){

Calculation Values myValues = new Calculation Values();

Thread newThread = new Thread(

new ThreadStart(PerformCalculation));

new Thread.Start(myValues);}

B. private void PerformCalculation() {...} private void DoWork(){

Calculation Values myValues = new Calculation Values();

ThreadStart delStart = new

ThreadStart(PerformCalculation);

Thread newThread = new Thread(delStart);if (newThread.IsAlive)

{newThread.Start(myValues);}}

C. private void PerformCalculation (CalculationValues values) {...} private void

DoWork(){

Calculation Values myValues = new Calculation Values();

Application.DoEvents();

PerformCalculation(myValues);

Application.DoEvents();}

D. private void PerformCalculation(object values) {...} private void DoWork(){

Calculation Values myValues = new Calculation Values();

Thread newThread = new Thread(

new ParameterizedThreadStart(PerformCalculation));

newThread.Start(myValues);}

Answer: D

K8 - Call the procedure & use ParameterizedThreadStart

Question: 29

You are developing a custom event handler to automatically print all open documents. The event handler helps specify the number of copies to be printed. You need to develop a custom event arguments class to pass as a parameter to the event handler. Which code segment should you use?

A. Public Class PrintingArgs

Private _copies As Integer

Public Sub New(ByVal numberOfCopies As Integer)

Me._copies = numberOfCopies

End Sub

Public ReadOnly Property Copies() As Integer

Get

Return Me._copies

End Get

End PropertyEnd Class

B. Public Class PrintingArgs

Inherits EventArgs

Private _copies As Integer

Public Sub New(ByVal numberOfCopies As Integer)

Me._copies = numberOfCopies

End Sub

Public ReadOnly Property Copies() As Integer

Get

Return Me._copies

End Get

End PropertyEnd Class

C. Public Class PrintingArgs

Private eventArgs As EventArgs

Public Sub New(ByVal args As EventArgs)

Me.eventArgs = args

End Sub

Public ReadOnly Property Args() As EventArgs

Get

Return eventArgs

End Get

End PropertyEnd Class

D. Public Class PrintingArgs

Inherits EventArgs

Private copies As IntegerEnd Class

Answer: B

K8 - Inherits EventArgs

Question: 30

You write the following code segment to call a function from the Win32 Application Programming Interface (API) by using platform invoke. string personName = “N?el”;string msg = “Welcome” + personName + “to club”!”;bool rc =

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 static extern bool

MessageBox(int hWnd,

String text,

String caption,

uint type);}

B. [DllImport("user32", EntryPoint = "MessageBoxA", CharSet = CharSet.Ansi)]public

static extern bool MessageBox(int hWnd,

[MarshalAs(UnmanagedType.LPWStr)]String text,

[MarshalAs(UnmanagedType.LPWStr)]String caption,

uint type);}

C. [DllImport("user32", CharSet = CharSet.Unicode)]public static extern bool

MessageBox(int hWnd,

String text,

String caption,

uint type);}

D. [DllImport("user32", EntryPoint = "MessageBoxA", CharSet =

CharSet.Unicode)]public static extern bool MessageBox(int hWnd,

[MarshalAs(UnmanagedType.LPWStr)]String text,

[MarshalAs(UnmanagedType.LPWStr)]String caption,

uint type);}

Answer: C

K8 - CharSet.Unicode not asci & not using MarshaAs

Question: 31

You are developing an application that dynamically loads assemblies from an application directory. You need to write a code segment that loads an assembly named Company1.dll into the current application domain. Which code segment should you use?

A. Dim domain As AppDomain = AppDomain.CurrentDomainDim myPath As String =

_ Path.Combine(domain.BaseDirectory, "Company1.dll")Dim asm As [Assembly] =

[Assembly].LoadFrom(myPath)

B. Dim domain As AppDomain = AppDomain.CurrentDomainDim myPath As String = _

Path.Combine(domain.BaseDirectory, "Company1.dll")Dim asm As [Assembly] =

[Assembly].Load(myPath)

C. Dim domain As AppDomain = AppDomain.CurrentDomainDim myPath As String = _

Path.Combine(domain.DynamicDirectory, "Company1.dll")Dim asm As [Assembly] = _

AppDomain.CurrentDomain.Load(myPath)

D. Dim domain As AppDomain = AppDomain.CurrentDomainDim asm As [Assembly]

= domain.GetData("Company1.dll")

Answer: A

K8 - [Assembly].LoadFrom(myPath)

Question: 32

You need to read the entire contents of a file named Message.txt into a single string variable. Which code segment should you use?

A. Dim result As String = NothingDim reader As New

StreamReader("Message.txt")result = reader.Read().ToString()

B. Dim result As String = NothingDim reader as New

StreamReader("Message.txt")result = reader.ReadToEnd()

C. Dim result As String = string.EmptyDim reader As New

StreamReader("Message.txt")While Not reader.EndOfStream

result &= reader.ToString()End While

D. Dim result as String = NothingDim reader As New

StreamReader("Message.txt")result = reader.ReadLine()

Answer: B

K8 - ReadToEnd will read the entire file.

Friday, August 21, 2009

70-536 MCTS .NET Practice Questions #20

 

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.

Thx,

Catto

Question: 6

You are working on a debug build of an application.

You need to find the line of code that caused an exception to be thrown. Which property of the

Exception class should you use to achieve this goal?

A. Data

B. Message

C. StackTrace

D. Source

Answer: C

(of course the stackTrace)

 

Question: 7

You need to write a code segment that performs the following tasks:

* Retrieves the name of each paused service.

* Passes the name to the Add method of Collection1.

Which code segment should you use?

A. ManagementObjectSearcher^ searcher =

gcnew ManagementObjectSearcher(

“Select * from Win32_Service where State = ‘Paused’”);for each (ManagementObject^

svc in searcher->Get()) {

Collection1->Add(svc[“DisplayName”]);}

B. ManagementObjectSearcher^ searcher =

gcnew ManagementObjectSearcher(

“Select * from Win32_Service”, “State = ‘Paused’”);for each (ManagementObject^ svc in

searcher->Get()) {

Collection1->Add(svc[“DisplayName”]);}

C. ManagementObjectSearcher^ searcher =

gcnew ManagementObjectSearcher(

“Select * from Win32_Service”);for each (ManagementObject^ svc in searcher->Get()) {

if ((String^) svc["State"] == "'Paused'") {

Collection1->Add(svc[“DisplayName”]);

}}

D. ManagementObjectSearcher^ searcher =

gcnew ManagementObjectSearcher();searcher->Scope = gcnew

ManagementScope(“Win32_Service”);for each (ManagementObject^ svc in

searcher->Get()) {

if ((String^)svc["State"] == "Paused") {

Collection1->Add(svc[“DisplayName”]);

}}

Answer: A

 

Question: 8

You need to serialize an object of type List(Of Integer) in a binary format. The object is named data. Which code segment should you use?

A. Dim formatter As New BinaryFormatter()Dim ms As New

MemoryStream()formatter.Serialize(ms, data)

B. Dim formatter As New BinaryFormatter()Dim ms As New MemoryStream() For i As

Integer = 1 To 20

formatter.Serialize(ms, data(i - 1))Next

C. Dim formatter As New BinaryFormatter()Dim buffer As New Byte(data.Count) {}Dim ms As

New MemoryStream(buffer, True)formatter.Serialize(ms, data)

D. Dim formatter As New BinaryFormatter()Dim ms As New MemoryStream()While

ms.CanRead formatter.Serialize(ms, data)End While\

Answer: A

70-536 MCTS .NET Practice Questions #19

 

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.

Thx,

Catto

 

Question: 1

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. Class MyDictionaryImplements Dictionary(Of String, String) B. Class MyDictionary Inherits HashTable

C. Class MyDictionary Implements IDictionary

D. Class MyDictionary

End Class

Dim t As New Dictionary(Of String, String)

Dim dict As MyDictionary = CType(t, MyDictionary)

Answer: A

 

Question: 2

You write a class named Employee that includes the following code segment.

Private m_EmployeeId As String Private m_EmployeeName As String Private m_JobTitleName As String Public Function GetName() As String Return m_EmployeeName

End Function

Public Function GetTitle() As String

Return m_JobTitleName

End Function

End Class

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 EmployeeImplements IEmployee

Answer: D

 

Question: 3

You are developing a custom event handler to automatically print all open documents.

The event handler helps specify the number of copies to be printed. You need to develop a custom event arguments class to pass as a parameter to the event handler.

Which code segment should you use?

A. public class PrintingArgs {

private int copies;

public PrintingArgs(int numberOfCopies) {

clip_image001this.copies = numberOfCopies;

public int Copies {

get { return this.copies; }

}}

B. public class PrintingArgs : EventArgs {

private int copies;

public PrintingArgs(int numberOfCopies) {

this.copies = numberOfCopies;

}

public int Copies {

get { return this.copies; }

}}

C. public class PrintingArgs {

   private EventArgs eventArgs;

   public PrintingArgs(EventArgs ea) {

this.eventArgs = ea;

}public EventArgs Args {get { return eventArgs; }}}

D. public class PrintingArgs : EventArgs {

private int copies;}

Answer: B

 

Question: 4

You use Reflection to obtain information about a method named MyMethod.

You need to ascertain whether MyMethod is accessible to a derived class. What should you do?

A. Call the IsAssembly property of the MethodInfo class.

B. Call the IsVirtual property of the MethodInfo class.

C. Call the IsStatic property of the MethodInfo class.

D. Call the IsFamily property of the MethodInfo class.

Answer: D

 

Question: 5

You are creating a class that uses unmanaged resources. This class maintains references to

managed resources on other objects. You need to ensure that users of this class can explicitly release resources when the class instance ceases to be needed. Which three actions should you perform? (Each correct answer presents part of the solution. Choose three.)

A. Define the class such that it inherits from the WeakReference class.

B. Define the class such that it implements the IDisposable interface.

C. Create a class destructor that calls methods on other objects to release the managed resources.

D. Create a class destructor that releases the unmanaged resources.

E. Create a Dispose method that calls System.GC.Collect to force garbage collection.

F. Create a Dispose method that releases unmanaged resources and calls methods on other objects to release the managed resources.

Answer: B, D, F