70-536

TS: Microsoft .NET Framework - Application Development Foundation


Note: The answer is for reference only, you need to understand all question.
QUESTION 1
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) { this.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 2
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 3
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: BDF
QUESTION 4
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


QUESTION 5
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 = new EventLog("Application", "."); foreach (EventLogEntry entry in myLog.Entries) { if (entry.Source == "MySource") { PersistToDB(entry); } }
B. EventLog myLog = new EventLog("Application", "."); myLog.Source = "MySource"; foreach (EventLogEntry entry in myLog.Entries) { if (entry.EntryType == (EventLogEntryType.Error & EventLogEntryType.Warning)) { PersistToDB(entry); } }
C. EventLog myLog = new EventLog("Application", "."); foreach (EventLogEntry entry in myLog.Entries) { if (entry.Source == "MySource") {

if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning)
{ PersistToDB(entry); } } }
D. EventLog myLog = new EventLog("Application", "."); myLog.Source = "MySource"; foreach (EventLogEntry entry in myLog.Entries) { if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning) { PersistToDB(entry); } }
Answer: C


QUESTION 6
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


QUESTION 7
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
B. class MyDictionary : HashTable
C. class MyDictionary : IDictionary
D. class MyDictionary { ... }

Dictionary t = new Dictionary(); MyDictionary dictionary = (MyDictionary)t;
Answer: A


QUESTION 8
You are creating an assembly named Assembly1. Assembly1 contains a public method. The global cache contains a second assembly named Assembly2. You must ensure that the public method is only called from Assembly2. Which permission class should you use?
A. GacIdentityPermission
B. StrongNameIdentityPermission
C. DataProtectionPermission
D. PublisherIdentityPermission
Answer: B


QUESTION 9
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.contoso.com.
To test the application, you use a source address, [email protected], and a target address, [email protected].
You need to transmit the e-mail message.
Which code segment should you use?
A.MailAddress addrFrom =
new MailAddress("[email protected]", "Me");
MailAddress addrTo =
new MailAddress("[email protected]", "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); B.MailAddress addrFrom = new MailAddress("[email protected]"); MailAddress addrTo = new
MailAddress("[email protected]"); MailMessage message = new MailMessage(addrFrom, addrTo); message.Subject = "Greetings!";

message.Body = "Test";
SmtpClient client = new SmtpClient("smtp.contoso.com"); client.Send(message);
C.string strSmtpClient = "smtp.contoso.com";
string strFrom = "[email protected]";
string strTo = "[email protected]";
string strSubject = "Greetings!";
string strBody = "Test";
MailMessage msg =
new MailMessage(strFrom, strTo, strSubject, strSmtpClient);
D.MailAddress addrFrom =
new MailAddress("[email protected]", "Me");
MailAddress addrTo =
new MailAddress("[email protected]", "You");
MailMessage message = new MailMessage(addrFrom, addrTo); message.Subject = "Greetings!";
message.Body = "Test";
message.Dispose();
Answer: B


QUESTION 10
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


QUESTION 11
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. public ref class CalculationValues {...}; public ref class Calculator { public : void PerformCalculation(Object= values) {} }; public ref class ThreadTest{ private : void DoWork (){ CalculationValues= myValues = gcnew CalculationValues(); Calculator = calc = gcnew Calculator(); Thread= newThread = gcnew Thread( gcnew ParameterizedThreadStart(calc, &Calculator::PerformCalculation)); newThread->Start(myValues); } };
B. public ref class CalculationValues {...}; public ref class Calculator { public : void PerformCalculation() {} }; public ref class ThreadTest{ private : void DoWork (){ CalculationValues= myValues = gcnew CalculationValues(); Calculator = calc = gcnew Calculator(); ThreadStart= delStart = gcnew ThreadStart(calc, &Calculator::PerformCalculation); Thread= newThread = gcnew Thread(delStart); if (newThread->IsAlive) { newThread->Start(myValues); } } };
C. public ref class CalculationValues {...}; public ref class Calculator { public : void PerformCalculation(CalculationValues= values) {} }; public ref class ThreadTest{ private : void DoWork (){ CalculationValues= myValues = gcnew CalculationValues(); Calculator = calc = gcnew Calculator(); Application::DoEvents(); calc->PerformCalculation(myValues); Application::DoEvents(); }

};
D. public ref class CalculationValues {...}; public ref class Calculator { public : void PerformCalculation() {} }; public ref class ThreadTest{ private : void DoWork (){ CalculationValues= myValues = gcnew CalculationValues(); Calculator = calc = gcnew Calculator(); Thread= newThread = gcnew Thread( gcnew ThreadStart(calc, &Calculator::PerformCalculation)); newThread->Start(myValues); } };
Answer: A


QUESTION 12
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 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


QUESTION 13
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
QUESTION 14
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: AB


QUESTION 15
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); 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(document, 0, document.Length); deflate.Close(); return strm.ToArray();
C. MemoryStream strm = new MemoryStream(); DeflateStream deflate = new DeflateStream(strm, CompressionMode.Compress); deflate.Write(document, 0, document.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


QUESTION 16
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

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


QUESTION 18
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


QUESTION 19
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
QUESTION 20

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(); AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.RunAndSave); myAssemblyBuilder.Save("MyAssembly.dll");
B. AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "MyAssembly"; AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Save); myAssemblyBuilder.Save("MyAssembly.dll");
C. AssemblyName myAssemblyName = new AssemblyName("MyAssembly"); AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Save); myAssemblyBuilder.Save("c:\\MyAssembly.dll");
D. AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "MyAssembly"; AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Run); myAssemblyBuilder.Save("MyAssembly.dll");
Answer: B


QUESTION 21
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


QUESTION 22
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


QUESTION 23
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


QUESTION 24
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->CurrencyNegativePattern = 1; return numberToPrint->ToString("C", culture);
B. NumberFormatInfo= culture = gcnew CultureInfo("zh-HK")::NumberFormat; culture->NumberNegativePattern = 1; return numberToPrint->ToString("C", culture);
C. CultureInfo= culture = gcnew CultureInfo("zh-HK"); return numberToPrint->ToString("()", culture);
D. CultureInfo= culture = gcnew CultureInfo("zh-HK"); return numberToPrint->ToString("-(0)", culture);
Answer: A


QUESTION 25
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 QUESTION 26


You are creating an assembly named Assembly1. Assembly1 contains a public method. The global cache contains a second assembly named Assembly2. You must ensure that the public method is only called from Assembly2. Which permission class should you use?
A. GacIdentityPermission
B. StrongNameIdentityPermission
C. DataProtectionPermission
D. PublisherIdentityPermission
Answer: B


QUESTION 27
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:
C.Add the following XML element to the configuration file of each application that uses the strong-named assembly:
D.Add the following XML element to the machine configuration file:
E.Add the following XML element to the configuration file of each application that uses the strong-named assembly:


Answer: AD


QUESTION 28
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: BF


QUESTION 29
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, "Assembly1.dll"); Assembly= assm = Assembly::LoadFrom(myPath);
B. AppDomain= domain = AppDomain::CurrentDomain; String= myPath = Path::Combine(domain->BaseDirectory, "Assembly1.dll"); Assembly= assm = Assembly::Load(myPath);

C. AppDomain= domain = AppDomain::CurrentDomain;
String= myPath = Path::Combine(domain->DynamicDirectory, "Assembly1.dll"); Assembly= assm = AppDomain::CurrentDomain::Load(myPath);
D. AppDomain= domain = AppDomain::CurrentDomain; Assembly= assm = domain->GetData("Assembly1.dll");
Answer: A


QUESTION 30
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


QUESTION 31
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


QUESTION 32
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


QUESTION 33
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 machine configuration file.
B.Add the following XML element to the application configuration file.
C.Add the following XML element to the application configuration file.
D.Add the following XML element to the machine configuration file.

Answer: B


QUESTION 34
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


QUESTION 35
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
QUESTION 36
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: BE
QUESTION 37
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(); foreach (IdentityReference grp in currentUser.Groups) { NTAccount grpAccount = ((NTAccount)grp.Translate(typeof(NTAccount))); isAuthorized = grpAccount.Value.Equals(Environment.MachineName + @"\Clerk"); if(isAuthorized) break; }
B.WindowsPrincipal currentUser = (WindowsPrincipal)Thread.CurrentPrincipal; isAuthorized = currentUser.IsInRole("Clerk"); C.GenericPrincipal currentUser = (GenericPrincipal) Thread.CurrentPrincipal; isAuthorized = currentUser.IsInRole("Clerk"); D.WindowsPrincipal currentUser = (WindowsPrincipal)Thread.CurrentPrincipal; isAuthorized = currentUser.IsInRole(Environment.MachineName);

Answer: B
QUESTION 38
You need to write a code segment that performs the following tasks:
?Retrieve the name of each paused service.
?Passes the name of each paused service to the Add method of Collection1.
Which code segment should you use?
A.ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Service where State = 'Paused'"); foreach (ManagementObject svc in searcher.Get()) { Collection1.Add(svc["DisplayName"]); }
B.ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Service", "State " ='Paused'"); foreach (ManagementObject svc in searcher.Get()) { Collection1.Add(svc["DisplayName"]); }
C.ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_Service"); foreach (ManagemetnObject svc in searcher.Get()) { if ((string) svc["State"] == "'Paused'") {

Collection1.Add(svc["DisplayName"]);
}
}
D.ManagementObjectSearcher searcher = new ManagementObjectSearcher(); searcher.Scope = new
ManagementScope("Win32_Service"); foreach (ManagementObject svc in searcher.Get())
{
if ((string)svc["State"] == "Paused")
{
Collection1.Add(svc["DisplayName"]);
}
}

Answer: A
QUESTION 39
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 QUESTION 40

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.string dateString = DateTimeFormatInfo.CurrentInfo GetMonthName(DateTime.Today.Month) ;
B.string dateString = DateTime.Today.Month.ToString("es-MX"); C.DateTimeFormatInfo dtfi = new CultureInfo("es-MX", false).DateTimeForwat; DateTirne dt = new DateTime (DateTime. Today. Year, DateTime.Today.Month, DateTime.Today.Day); string dateString = dt.ToString(dtfi.LongDatePattern); D.Calendar cal = new CultureInfo("es-MX", false).Calendar; DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day); Strong dateString = dt.ToString();

Answer: A
QUESTION 41
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. foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes. SpecificCultures)) { // Output the region information... }
B. CultureInfo cultureInfo = new CultureInfo("CA"); // Output the region information...
C. RegionInfo regionInfo = new RegionInfo("CA"); // Output the region information...
D. RegionInfo regionInfo = new RegionInfo(""); if(regionInfo.Name == "CA") { // Output the region information... }
Answer: C QUESTION 42

You are developing a server application that will transmit sensitive information on a network. You create an X509Certificate object named certificate and a TcpClient object named client.
You need to create an SslStream to communicate by using the Transport Layer Security 1.0 protocol.
Which code segment should you use?
A. SslStream ssl = new SslStream(client.GetStream()); ssl.AuthenticateAsServer(certificate,false, SslProtocols.None, true);
B. SslStream ssl = new SslStream(client.GetStream()); ssl.AuthenticateAsServer(certificate,false, SslProtocols.Ssl3, true);
C. SslStream ssl = new SslStream(client.GetStream()); ssl.AuthenticateAsServer(certificate,false, SslProtocols.Ssl2, true);
D. SslStream ssl = new SslStream(client.GetStream()); ssl.AuthenticateAsServer(certificate,false, SslProtocols.Tls, true);

Answer: D
QUESTION 43
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. StringReader reader = new StringReader(message); Process(reader.ReadToEnd()); reader.Close();
B. StringReader reader = new StringReader(message); while (reader.Peek() != -1) { string line = reader.Read().ToString(); Process(line); } reader.Close();
C. StringReader reader = new StringReader(message); Process(reader.ToString()); reader.Close();
D. StringReader reader = new StringReader(message);

while (reader.Peek() != -1) { Process(reader.ReadLine()); } reader.Close();

Answer: D
QUESTION 44
You are developing a method to encrypt sensitive data with the Data Encryption Standard (DES) algorithm. Your method accepts the following parameters:
?The byte array to be encrypted, which is named message
?An encryption key, which is named key
?An initialization vector, which is named iv
You need to encrypt the data. You also need to write the encrypted data to a MemoryStream object. Which code segment should you use?
A.DES des = new DESCryptoServiceProvider(); des.BlockSize = message.Length; ICryptoTransform crypto = des.CreateEncryptor(key, iv); MemoryStream cipherStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write); cryptoStream.Write(message, 0, message.Length);
B.DES des = new DESCryptoServiceProvider(); ICryptoTransform crypto = des.CreateDecryptor(key, iv); MemoryStream cipherStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write); cryptoStream.Write(message, 0, message.Length);
C.DES des = new DESCryptoServiceProvider(); ICryptoTransform crypto = des.CreateEncryptor(); MemoryStream cipherStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write); cryptoStream.Write(message, 0, message.Length);
D.DES des = new DESCryptoServiceProvider(); ICryptoTransform crypto = des.CreateEncryptor(key, iv); MemoryStream cipherStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write);

cryptoStream.Write(message, 0, message.Length);

Answer: D
QUESTION 45
You are creating a new security policy for an application domain. You write the following lines of code.
PolicyLevel policy = PolicyLevel.CreateAppDomainLevel();
PolicyStatement noTrustStatement = new PolicyStatement(policy.
GetNamedPermissionSet("Nothing"));
PolicyStatement fullTrustStatement = new PolicyStatement(policy.
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. CodeGroup group1 = new FirstMatchCodeGroup( new AllMembershipCondition(), noTrustStatement); CodeGroup group2 = new UnionCodeGroup( new ZoneMembershipCondition(SecurityZone.Trusted), fullTrustStatement); group1.AddChild(group2);
B. CodeGroup group = new FirstMatchCodeGroup( new AllMembershipCondition(), noTrustStatement);
C. CodeGroup group = new UnionCodeGroup( new ZoneMembershipCondition(SecurityZone.Trusted), fullTrustStatement);
D. CodeGroup group1 = new FirstMatchCodeGroup( new ZoneMembershipCondition(SecurityZone.Trusted), fullTrustStatement); CodeGroup group2 = new UnionCoderoup( new AllMembershipCondition(), noTrustStatement); group1.AddChild(group2);


Answer: A
QUESTION 46
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 : ServiceBase { bool blnExit = false; public PollingService() {} protected override void OnStart(string[] args) { do { DoWork(); } while (!blnExit); } protected 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 longrunning 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
QUESTION 47
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 = new MemoryStream(8192); memStream.Write(dataToSend, 0, (int) netStream.Length); B.MemoryStream memStream = new MemoryStream(8192); netStream.Write(dataToSend, 0, (int) memStream.Length); C.BufferedStream bufStream = new BufferedStream(netStream, 8192); bufStream.Write(dataToSend, 0, dataToSend.Length); D.BufferedStream bufStream = new BufferedStream(netStream); bufStream.Write(dataToSend, 0, 8192);

Answer: C
QUESTION 48
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. (Click the Exhibit button.) Which code segment should you
choose?
A.Rectangle= rectangle = gcnew Rectangle(10, 10, 450, 25); LinearGradientBrush= rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue, Color::CornflowerBlue, LinearGradientMode::ForwardDiagonal); Pen= rectanglePen = gcnew Pen(rectangleBrush); Graphics= g = this->CreateGraphics(); g->FillRectangle(rectangleBrush, rectangle);
B.RectangleF= rectangle = gcnew RectangleF(10f, 10f, 450f, 25f); SolidBrush= rectangleBrush = gcnew SolidBrush(Color::AliceBlue); Pen= rectanglePen = gcnew Pen(rectangleBrush); Graphics= g = this->CreateGraphics(); g->DrawRectangle(rectangleBrush, rectangle);
C.Rectangle= rectangle = gcnew Rectangle(10, 10, 450, 25); LinearGradientBrush= rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue, Color::CornflowerBlue, LinearGradientMode::ForwardDiagonal); Pen= rectanglePen = gcnew Pen(rectangleBrush); Graphics= g = this->CreateGraphics(); g->DrawRectangle(rectanglePen, rectangle);
D.RectangleF= rectangle = gcnew RectangleF(10f, 10f, 450f, 25f); array= points = gcnew array= {gcnew Point(0, 0), gcnew Point(110, 145)}; LinearGradientBrush= rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue, Color::CornflowerBlue, LinearGradientMode::ForwardDiagonal); Pen= rectanglePen = gcnew Pen(rectangleBrush); Graphics= g = this->CreateGraphics(); g->DrawPolygon(rectanglePen, points);
Answer: A
QUESTION 49
DRAG DROP
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? To answer, you need to move the three appropriate actions from the list of actions to the answer area and arrange them in the correct order.


Answer:

QUESTION 50
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 searchList
?The 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 = new CultureInfo("it-IT").CompareInfo; return comparer.Compare(searchList, searchValue); C.CultureInfo Comparer = new CultureInfo("it-IT"); if (searchList.IndexOf(searchValue) > 0) { return true; } else { return false; } D.CompareInfo comparer = new CultureInfo("it-IT").CompareInfo; if (comparer.IndexOf(searchList, searchValue) > 0) { return true; } else { return false; }

Answer: D
QUESTION 51
You need to serialize an object of type List in a binary format. The object is named data. Which code segment should you use?
A.BinaryFormatter= formatter = gcnew BinaryFormatter(); MemoryStream= stream = gcnew MemoryStream(); formatter->Serialize(stream, data);
B.BinaryFormatter= formatter = gcnew BinaryFormatter(); MemoryStream= stream = gcnew MemoryStream(); Capture c(formatter,stream); data->ForEach(gcnew Action(%c,&Capture::Action));
C.BinaryFormatter= formatter = gcnew BinaryFormatter();a rray= buffer = gcnew array(data->Count); MemoryStream= stream = gcnew MemoryStream(buffer, true); formatter->Serialize(stream, data);
D.BinaryFormatter= formatter = gcnew BinaryFormatter(); MemoryStream= stream = gcnew MemoryStream(); for (int i = 0; i < data->Count; i++) { formatter->Serialize(stream, data[i]); }


Answer: A
QUESTION 52
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 outStream = new MemoryStream(); GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress); zipStream.Write(document, 0, document.Length); zipStream.Close(); return outStream.ToArray();
B.MemoryStream inStream = new MemoryStream(document); GZipStream zipStream = new GZipStream(inStream, CompressionMode.Compress); byte[] result = new byte[document.Length]; zipStream.Write(result, 0, result.Length); return result;
C.MemoryStream stream = new MemoryStream(document); GZipStream zipStream = new GZipStream(stream, CompressionMode.Compress); zipStream.Write(document, 0, document.Length); zipStream.Close(); return stream.ToArray();
D.MemoryStream inStream = new MemoryStream(document); GZipStream zipStream = new GZipStream(inStream, CompressionMode.Compress); MemoryStream outStream = new MemoryStream(); int b; while ((b = zipStream.ReadByte()) != -1) { outStream.WriteByte((byte)b); } return outStream.ToArray();
Answer: A
QUESTION 53
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")] public static extern int MessageBox(int hWnd, String text,String caption, uint type); B.[DllImport("user32")] public static extern int MessageBoxA(int hWnd, String text,String caption, uint type); C.[DllImport("user32")] public static extern int Win32API_User32_MessageBox(int hWnd, String text, String caption, uint type); D.[DllImport(@"C:\WINDOWS\system32\user32.dll")] public static extern int MessageBox(int hWnd, String text,String caption, uint type);

Answer: A
QUESTION 54
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.for each (CultureInfo= culture in CultureInfo::GetCultures(CultureTypes::NeutralCultures)) { // Output the culture information... }
C.for each (CultureInfo= culture in CultureInfo::GetCultures(CultureTypes::ReplacementCultures)) { // Output the culture information... }
D.CultureInfo= culture = gcnew CultureInfo(""); CultureTypes= types = culture->CultureTypes; // Output the culture information...
Answer: A
QUESTION 55
You are creating an application that retrieves values from a custom section of the application configuration file.
The custom section uses XML as shown in the following block.

QUESTION 56 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") { Debug.Print("Test Failed: "); Debug.Print(fName); }
D. if (fName != "Company") { Debug.WriteLine("Test Failed: "); Debug.WriteLine(fName); }

Answer: B
QUESTION 57
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(newWindowsPrincipal(null));
C. AppDomain domain = AppDomain.CurrentDomain; domain.SetAppDomainPolicy(PolicyLevel.CreateAppDomainLevel());
D. AppDomain domain = AppDomain.CurrentDomain; domain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal);


Answer: D
QUESTION 58
You write a class named Employee that includes the following code segment.
public class Employee
{
string employeeId,
string employeeName, string jobTitleName;
public string GetName() { return employeeName; }
public string GetTitle() { return jobTitleName; }
}
You need to expose this class to COM in a type library. The COM interface must also facilitate forwardcompatibility 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
QUESTION 59
You need to write a multicast delegate that accepts a DateTime argument and returns a Boolean value. Which code segment should you use?
A. public delegate int PowerDeviceOn(bool,DateTime);
B. public delegate bool PowerDeviceOn(Object,EventArgs);
C. public delegate void PowerDeviceOn(DateTime);
D. public delegate bool PowerDeviceOn(DateTime);

Answer: A
QUESTION 60
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
QUESTION 61
DRAG DROP
You are creating an application that provides information about the local computer. The application contains a form that lists each logical drive along with the drive properties, such as type, volume label, and capacity.
You need to write a procedure that retrieves properties of each logical drive on the local computer.
What should you do?
To answer, move the three appropriate actions from the list of actions to the answer area and arrange them in the correct order.


Answer:

QUESTION 62
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 undoBuffer = new Stack();
B. Stack undoBuffer = new Stack();
C. Queue undoBuffer = new Queue();
D. Queue undoBuffer = new Queue();
Answer: A QUESTION 63

You create the definition for a Vehicle class by using the following code segment. public ref class Vehicle { public : [XmlAttribute(AttributeName = "category")] String= vehicleType; String= model; [XmlIgnore] int year; [XmlElement(ElementName = "mileage")] int miles; ConditionType condition; Vehicle() {} 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:


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. racer 15000 Excellent
B. racer 15000 AboveAverage
C. racer 15000 Excellent
D. car

racer 15000 Excellent


Answer: A
QUESTION 64
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
QUESTION 65
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 ref class Meeting {
private :
String= title;
public :
int roomNumber;
array= invitees; Meeting(){}

Meeting(String= t){ title = t; } }; The component contains a procedure with the following code segment. Meeting= myMeeting = gcnew Meeting("Goals"); myMeeting->roomNumber=1100; array= attendees = gcnew array(2) {"John", "Mary"}; myMeeting->invitees = attendees; XmlSerializer= xs = gcnew XmlSerializer(__typeof(Meeting)); StreamWriter= writer = gcnew 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. 1100 John Mary

B. 1100 John Mary C. Goals 1100 John Mary D. 1100 John Mary
Answer: D
QUESTION 66
You are creating a class to compare a specially-formatted string. The default collation comparisons do not
apply. You need to implement the IComparable interface. Which code segment should you use?
A. public class Person : IComparable { public int CompareTo(string other) { } }
B. public class Person : IComparable { public int CompareTo(object other) { } }
C. public class Person : IComparable

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

Answer: A
QUESTION 67
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
QUESTION 68
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 QUESTION 69

You need to create a method to clear a Queue named q. Which code segment should you use?
A. foreach (object e in q) {
B. Dequeue(); }
C. foreach (object e in q) { Enqueue(null); }
D. q.Clear();
E. q.Dequeue();

Answer: D
QUESTION 70
You are testing a method that examines a running process. This method returns an ArrayList containing the name and full path of all modules that are loaded by the process. You need to list the modules loaded by a process named C:\TestApps\Process1.exe. Which code segment should you use?
A. ArrayList ar = new ArrayList(); Process[] procs; ProcessModuleCollection modules; procs = Process.GetProcesses(@"Process1"); if (procs.Length > 0) { modules = porcs[0].Modules; foreach (ProcessModule mod in modules) { ar.Add(mod.ModuleName); } }
B. ArrayList ar = new ArrayList(); Process[] procs; ProcessModuleCollection modules; procs = Process.GetProcesses(@"C:\TestApps\Process1.exe"); if (procs.Length > 0) { modules =porcs[0].Modules; foreach (ProcessModule mod in modules) { ar.Add(mod.ModuleName); } }

C. ArrayList ar = new ArrayList(); Process[] procs; ProcessModuleCollection modules; procs = Process.GetProcessesByName(@"Process1"); if (procs.Length > 0) { modules = porcs[0].Modules; foreach (ProcessModule mod in modules) { ar.Add(mod.FileName); } }
D. ArrayList ar = new ArrayList();Process[] procs; ProcessModuleCollection modules;procs = Process.GetProcessesByName(@"C: \TestApps\Process1.exe"); if (procs.Length > 0) { modules = porcs[0].Modules; foreach (ProcessModule mod in modules) { ar.Add(mod.FileName); } }

Answer: C
QUESTION 71
You need to write a multicast delegate that accepts a DateTime argument. Which code segment should you use?
A. public delegate int PowerDeviceOn(bool result,DateTime autoPowerOff);
B. public delegate bool PowerDeviceOn(object sender,EventsArgs autoPowerOff);
C. public delegate void PowerDeviceOn(DataTime autoPowerOff);
D. public delegate bool PowerDeviceOn(DataTime autoPowerOff);
Answer: C
QUESTION 72
Your application uses two threads, named threadOne and threadTwo. You need to modify the code to prevent

the execution of threadOne until threadTwo 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
QUESTION 73
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.Calendar cal = new CultureInfo("es-MX", false).Calendar; DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day); Strong dateString = dt.ToString();
B.string dateString = DateTime.Today.Month.ToString("es-MX"); C.string dateString = DateTimeFormatInfo.CurrentInfo GetMonthName(DateTime.Today.Month); D.DateTimeFormatInfo dtfi = new CultureInfo("es-MX", false).DateTimeFormat; DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day); string dateString = dt.ToString(dtfi.LongDatePattern);
Answer: D
QUESTION 74
You write the following custom exception class named CustomException.
public class CustomException : ApplicationException
{
public static int COR_E_ARGUMENT = unchecked((int)0x80070057); public CustomException(string msg) : base(msg)

{
HResult = COR_E_ARGUMENT;
}
}
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
QUESTION 75
DRAG DROP
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 during creation. What should you do?
To answer, move the three appropriate actions from the list of actions to the answer area and arrange them in the correct order.


Answer:

QUESTION 76
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.

Hardware
Amy

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 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; } };
B.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; } };
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 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"); } };

Answer: C
QUESTION 77
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
QUESTION 78
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
QUESTION 79
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
QUESTION 80
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
QUESTION 81
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.Deny();
C. set.Assert();
D. set.PermitOnly();

Answer: A
QUESTION 82
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 = new CompanyClass(); Type t = typeof(CompanyClass); MethodInfo m = t.GetMethod("MyMethod"); int i = (int)m.Invoke(this, new object[] { 1 });
B.CompanyClass myClass = new CompanyClass(); Type t = typeof(CompanyClass); MethodInfo m = t.GetMethod("MyMethod"); int i = (int) m.Invoke(myClass, new object[] { 1 });
C.CompanyClass myClass = new CompanyClass(); Type t = typeof(CompanyClass); MethodInfo m = t.GetMethod("CompanyClass.MyMethod"); int i = (int)m.Invoke(myClass, new object[] { 1 });
D.Type t = Type.GetType("CompanyClass"); MethodInfo m = t.GetMethod("MyMethod"); int i = (int)m.Invoke(this, new object[] { 1 });


Answer: B
QUESTION 83
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= 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: [XmlArray(ElementName="Employees")]
B.Insert the following code between lines 3 and 4 of the code segment: [XmlElement(Type = __typeof(Employee))] and Insert the following code segment between lines 8 and 9 of the code segment: [XmlElement(Type = __typeof(Manager))]
C.Insert the following code between lines 14 and 15 of the code segment: [XmlArrayItem(Type = __typeof(Employee))] [XmlArrayItem(Type = __typeof(Manager))]
D.Insert the following code between lines 14 and 15 of the code segment: [XmlElement(Type = __typeof(Employees))]

Answer: C
QUESTION 84
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(strComputer); 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(strComputer); 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
QUESTION 85
You are developing a method to decrypt data that was encrypted with the Triple DES Algorithm. The method accepts the following parameters:
The byte array to be decrypted, which is named cipherMessage
The key, which is named key
An initialization vector, which is named iv
You need to decrypt the message by using the TripleDES class and place the result in a string.
Which code segment should you use?
A.TripleDES des = new TripleDESCryptoServiceProvider(); ICryptoTransform crypto = des.CreateDecryptor(); MemoryStream cipherStream = new MemoryStream(cipherMessage); CryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read); string message; message = new StreamReader(cryptoStream).ReadToEnd();
B.TripleDES des = new TripleDESCryptoServiceProvider();ICryptoTransform crypto = des.CreateDecryptor(key, iv); MemoryStream cipherStream = new MemoryStream(cipherMessage);C ryptoStream cryptoStream =

new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read); string message; message = new StreamReader(cryptoStream).ReadToEnd();
C.TripleDES des = new TripleDESCryptoServiceProvider(); des.BlockSize = cipherMessage.Length; ICryptoTransform crypto = des.CreateDecryptor(key, iv); MemoryStream cipherStream = new MemoryStream(cipherMessage); CryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read); string message; message = new StreamReader(cryptoStream).ReadToEnd();
D.TripleDES des = new TripleDESCryptoServiceProvider(); des.FeedbackSize = cipherMessage.Length; ICryptoTransform crypto = des.CreateDecryptor(key, iv); MemoryStream cipherStream = new MemoryStream(cipherMessage); CryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read); string message; message = new StreamReader(cryptoStream).ReadToEnd();

Answer: B
QUESTION 86
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 QUESTION 87

You are developing an assembly to access file system. Need to write a segment code to configure CLR stop loading the assembly if file permssion is absent.
A.[FileIOPermission(SecurityAction.RequestOptional, AllLocalFiles = FileIOPermissionAccess.Read)] B.[FileIOPermission(SecurityAction.RequestMinimum, AllFiles = FileIOPermissionAccess.Read)] C.[FileIOPermission(SecurityAction.RequestRefuse, AllFiles = FileIOPermissionAccess.Read)] D.[FileIOPermission(SecurityAction.RequestOptional, AllFiles = FileIOPermissionAccess.Read)]

Answer: B
QUESTION 88
Given the code like this:
while(!loop)
{
//Thread code here
Dowork();
}
You need to write more code to class to run DoWork() with 30-second intervals using minimum resources
A. Thread.Sleep(30000)
B. Thread.SpinWait(30000)
C. Thread.QueueUserWorkItem(30000)
D. Thread.SpinWait(30)

Answer: A
QUESTION 89
You create an application for your business partners to submit purchase orders. The application deserializes XML documents sent by your partners into instances of an object named PurchaseOrder.
You need to modify the application so that it collects details if the deserialization process encounters any XML content that fails to map to public members of the PurchaseOrder object.

What should you do?
A.Define and implement an event handler for the XmlSerializer.UnknownNode event. B.Define a class that inherits from XmlSerializer and overrides the XmlSerialize.FromMappings method. C.Apply an XmlInclude attribute to the PurchaseOrder class definition. D.Apply an XmlIgnore attribute to the PurchaseOrder class definition

Answer: A
QUESTION 90
You are developing an application that will deploy by using ClickOnce. You need to test if the application executes properly. You need to write a method that returns the object, which prompts the user to install a ClickOnce application. Which code segment should you use?
A. return ApplicationSecurityManager.ApplicationTrustManager;
B. return AppDomain.CurrentDomain.ApplicationTrust;
C. return new HostSecurityManager();
D. return SecurityManager.PolicyHierarchy();

Answer: A
QUESTION 91
You need to write a code segment that will add a string named strConn to the connection string section of the application configuration file. Which code segment should you use?
A.Configuration myConfig = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); myConfig.ConnectionStrings.ConnectionStrings.Add( new ConnectionStringSettings("ConnStr1", strConn)); myConfig.Save();
B.Configuration myConfig =ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); myConfig.ConnectionStrings.ConnectionStrings.Add( new ConnectionStringSettings("ConnStr1",strConn)); ConfigurationManager.RefreshSection( "ConnectionStrings");
C.ConfigurationManager.ConnectionStrings.Add( new ConnectionStringSettings("ConnStr1",strConn)); ConfigurationManager.RefreshSection( "ConnectionStrings");
D.ConfigurationManager.ConnectionStrings.Add( new ConnectionStringSettings("ConnStr1",strConn)); Configuration myConfig = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); myConfig.Save();
Answer: A QUESTION 92

You create a DirectorySecurity object for the working directory.
You need to identify the user accounts and groups that have read and write permissions.
Which method should you use on the DirectorySecurity object?
A. the GetAuditRules method
B. the GetAccessRules method
C. the AccessRuleFactory method
D. the AuditRuleFactory method

Answer: B
QUESTION 93
You are developing an auditing application to display the trusted ClickOnce applications that are installed on a computer.
You need the auditing application to display the origin of each trusted application.
Which code segment should you use?
A.ApplicationTrustCollection trusts; trusts = ApplicationSecurityManager.UserApplicationTrusts; foreach (ApplicationTrust trust in trusts) { Console.WriteLine(trust.ToString()); }
B.ApplicationTrustCollection trusts; trusts = ApplicationSecurityManager.UserApplicationTrusts; foreach (ApplicationTrust trust in trusts) { Console.WriteLine(trust.ExtraInfo.ToString()); }
C.ApplicationTrustCollection trusts; trusts = ApplicationSecurityManager.UserApplicationTrusts; foreach (ApplicationTrust trust in trusts) { Console.WriteLine(trust.ApplicationIdentity.FullName); }
D.ApplicationTrustCollection trusts; trusts = ApplicationSecurityManager.UserApplicationTrusts; foreach (object trust in trusts) { Console.WriteLine(trust.ToString());

}

Answer: C
QUESTION 94
You work as an application developer at Contonso.com. You are currently creating a manifest-activated application on the Contonso.com's intranet using ClickOnce deployment.
The network administrator informs you that each application has to identify its name, version, culture, and requested permissions. You need to ensure that the application you are creating uses the command line to display the required information.
What should you do?
A.Use the following code:
ApplicationSecurityInfo appInfo = new ApplicationSecurityInfo (appDomain.
CurrentDomain);
Console.Writeline (appInfo.ApplicationID.Name);
Console.Writeline (appInfo.ApplicationID.Version);
Console.Writeline (appInfo.ApplicationID.Culture);
Console.Writeline (appInfo.DefaultRequestSet.ToXml ());
B.Use the following code:
ApplicationSecurityInfo appInfo = ActivationContext.GetCurrentContext (); Console.Writeline
(appInfo.ApplicationID.Name);
Console.Writeline (appInfo.ApplicationID.Version);
Console.Writeline (appInfo.ApplicationID.Culture);
Console.Writeline (appInfo.DefaultRequestSet.ToXml ());
C.Use the following code:
ApplicationSecurityInfo appInfo = new ApplicationSecurityInfo ( appDomain.
CurrentDomain.ActivationContext);
Console.Writeline (appInfo.ApplicationID.Name);
Console.Writeline (appInfo.ApplicationID.Version);
Console.Writeline (appInfo.ApplicationID.Culture);
Console.Writeline (appInfo.DefaultRequestSet.ToXml ());
D.Use the following code:
ApplicationSecurityInfo appInfo = ActivationID.GetCurrentApplication (); Console.Writeline
(appInfo.ApplicationID.Name);
Console.Writeline (appInfo.ApplicationID.Version);
Console.Writeline (appInfo.ApplicationID.Culture);
Console.Writeline (appInfo.DefaultRequestSet.ToXml ());
Answer: C QUESTION 95

You are developing an application that stores data about your company's sales and technical support teams.
You need to ensure that the name and contact information for each person is available as a single collection when a user queries details about a specific team.
You also need to ensure that the data collection guarantees type safety.
Which code segment should you use?
A.Hashtable team = new Hashtable(); team.Add(1, "Hance"); team.Add(2, "Jim"); team.Add(3, "Hanif"); team.Add(4, "Kerim"); team.Add(5, "Alex"); team.Add(6, "Mark"); team.Add(7, "Roger"); team.Add(8, "Tommy");
B.ArrayList team = new ArrayList(); team.Add("1, Hance"); team.Add("2, Jim"); team.Add("3, Hanif"); team.Add("4, Kerim"); team.Add("5, Alex"); team.Add("6, Mark"); team.Add("7, Roger"); team.Add("8, Tommy");
C.Dictionary team = new Dictionary(); team.Add(1, "Hance"); team.Add(2, "Jim"); team.Add(3, "Hanif"); team.Add(4, "Kerim"); team.Add(5, "Alex"); team.Add(6, "Mark"); team.Add(7, "Roger"); team.Add(8, "Tommy");
D.string[] team = new string[] {"1, Hance", "2, Jim", "3, Hanif", "4, Kerim", "5, Alex", "6, Mark", "7, Roger", "8, Tommy"};
Answer: C QUESTION 96

You create Microsoft Windows-based applications. You create an application that requires users to be authenticated by a domain controller. The application contains a series of processor intensive method calls that require different database
connections. A bug is reported during testing. The bug description states that the application hangs during one of the processor-intensive calls more than 50
percent of the times when the method is executed. Your unit test for the same method was successful. You need to reproduce the bug. Which two factors should you ascertain from the tester? (Each correct answer presents part of the solution.
Choose two.)
A. Security credentials of the logged on user
B. Code access security settings
C. Hardware settings
D. Network settings
E. Database settings

Answer: DE
QUESTION 97
You are a Web developer for Contonso. You are creating an online inventory Web site to be used by
employees in Germany and the United States. When a user selects a specific item from the inventory, the site needs to display the cost of the item in both United States currency and German currency.
The cost must be displayed appropriately for each locale.
You want to create a function to perform this task.
Which code should you use?

A.private string CKGetDisplayValue(double value,string inputRegion)
{
string display:
RegionInfo region;
region = new RegionInfo(inputRegion);
display = value.ToString("C");
display += region.CurrencySymbol;
return display;
}
B.private string CKGetDisplayValue(double value,string inputCulture) {
string display;
NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.
Clone();
display = value.ToString("C", LocalFormat);
return display;
}
C.private string CKGetDisplayValue(double value,string inputRegion) {
string display;
RegionInfo region;
region = new RegionInfo(inputRegion);
display = value.ToString("C");
display += region.ISOCurrencySymbol;
return display;
}
D.private string CKGetDisplayValue(double value, string inputCulture) {
string display;
CultureInfo culture;
culture = new CultureInfo(inputCulture);
display = value.ToString("C", culture);
return display;
}

Answer: D
QUESTION 98
You work as an application developer at CER-Tech.com. Cert-Tech.com uses Visual studio.NET 2005 as its Application Development platform.
You are developing a .NET Framework 2.0 application used to store a type-safe list of names and e-mail addresses. The list will be populated all at ones from the sorted data which means you will not always need to perform insertion or deletion operations on the data. You are required to choose a data structure that optimizes memory use and has good performance.

What should you do?
A. The System.Collections.Generic.SortedList class should be used
B. The System.Collections.HashTable class should be used
C. The System.Collections.Generic.SortedDictionary class should be used
D. The System.Collections.SortedList class should be used

Answer: A
QUESTION 99
You work as the application developer at Hi-Tech.com. You create a new custom dictionary named MyDictionary.
Choose the code segment which will ensure that MyDictionary is type safe?
A.Class MyDictionary Implements 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 100
What kind of object does the generic Dictionary enumerator return?
A. Object
B. Generic KeyValuePairt object
C. Key
D. Value
Answer: B
QUESTION 101
Which event would you use to run a method immediately after serialization occurs?

A. OnSerializing
B. OnDeserializing
C. OnSerialized
D. OnDeserialized

Answer: C
QUESTION 102
You work as an application developer at Cer-Tech.com.You are in the process of creating an application for
Cert-Tech.com's Human Resources department that tracks employee benefits You have to store current employee data without recompiling the application. You elect to store this employee data as a custom section in the application configuration file. The relevant portion of the application configuration file is shown in the following:
You work as the application developer at Cert-Tech.com. Cert-Tech.com uses Visual Studio.Net 2005 as its application development platform. You use a Windows XP Professional client computer named Client01 as your development computer.
You are developing a .Net Framework 2.0 application on Client01. You write the code shown below: Public Class Shape Private shapeName as String Public Sub Shape(ByVal shapeName as String) Me.shapename=shapeName End Sub Public Overridable Fuction GetName() As String Return shapeName End Function

Private Sub DrawShape()
'Additional code goes here
End Sub
End Class
You later decide to have the application compiled and registered for COM interoperability. The other developers on your team complaing that they are unable to create an instance of the Shape class in their COM applications. You are required to ensure that COM applications are able to create an instance of the Shape class.
What should you do?
A. The following code should be added to the Shape class: Public Sub New() End Sub
B. The following ComVisible attribute to the Shape class:
C. The definition of the GetName method should be modified as below: Public Function GetName() As String Return shapename End Function
D. The follwoing ComVisible attribute should be added to each method of the Shape class:

Answer: A
QUESTION 104
You are developing an application that uses role-based security. The principal policy of the application domain is configured during startup with the following code:
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
You need to restrict access to one of the methods in your application so that only members of the local Administrators group can call the method.
Which attribute should you place on the method?

A.[PrincipalPermission (SecurityAction.Demand, Name = @"BUILTIN\Administrators") ]
B.[PrincipalPermission (SecurityAction.Demand, Role = @"BUILTIN\Administrators") ]
C.[PrincipalPermission (SecurityAction.Assert, Name = @"BUILTIN\Administrators") ] D.[PrincipalPermission (SecurityAction.Assert, Role = @"BUILTIN\Administrators") ]

Answer: B
QUESTION 105
You deploy several .NET-connected applications to a shared folder on your company network. Your applications require full trust to execute correctly. Users report that they receive security exceptions when they attempt to run the applications on their computers. You need to ensure that the applications on the users computers run with full trust. What should you do?
A.Apply a string name to the applications by using the Strong Name tool (Sn.exe) B.Use the security settings of internet explorer to add the shared folder to the list of trusted sites C.Use the Code Access Security Policy tool (Caspol.exe) to add a new code group that has the full trust
permission set. The new code group must also contain a URL membership condition that specifies the URL of the shared folder where your application reside D.Grant the full trust permission set to the Trusted Zone code group by using the Code Access Security Policy Tool (Caspol.exe)

Answer: C
QUESTION 106
You are developing an application that runs by using the credentials of the end user. Only users who are members of the Administrator group get permission to run the application. You write the following security code to protect sensitive data within the application.
bool isAdmin=false;
WindowsBuiltInRole role=WindowsBuiltInRole.Administrator;
......
if(!isAdmin)

throw new Exception("User not permitted");
You need to add a code segment to this security code to ensure that the application throws an exception if a user is not a member of the Administrator group.
Which code segment should you use?
A.WindowsPrincipal currentUser = (WindowsPrincipal)Thread.CurrentPrincipal; IsAdmin=
currentUser.IsInRole(role); B.WindowsIdentity currentUser = WindowsIdentity.GetCurrent(); foreach (IdentityReference grp in
currentUser.Groups) {
NTAccount grpAccount=((NTAccount)grp.Translate(typeof(NTAccount))); isAdmin=grp.Value.Equals(role);
if (isAdmin)
break;
} C.GenericPrincipal currentUser = (GenericPrincipal) Thread.CurrentPrincipal; IsAdmin =
currentUser.IsInRole(role.ToString()); D.WindowsIdentity currentUser = (WindowsIdentity)Thread.CurrentPrincipal.
Identity;
isAdmin=currentUser.Name.EndsWith("Administrator");

Answer: A
QUESTION 107
You work as aplication developer at Cer-Tech.com. You have recently created an aplication that includes the code shown below.
You now need to invoke the GetFileContents method asynchronously.
You have to ensure that the code you use to invoke the GetFileContents method will continue to process other user instructions, and displays the results as soon as the GetFileContents method finishes processing.
What should you do?
A.Use the following code:
GetFileContentsDel delAsync = new GetFileContentsDel (GetFileContents); IAsyncResult result =
delAsync.BeginInvoke (null, null); while (!result.IsCompleted)
{
//Process other user instructions
}
string strFile -delAsync.EndInvoke (result);

B.Use the following code: GetFileContentsDel delAsync = new GetFileContentsDel (GetFileContents); string strFile -delAsync.Invoke ();
C.Use the following code: string strFile -delAsync.Invoke ();
D.Use the following code: GetFileContentsDel delAsync = new GetFileContentsDel (GetFileContents); IAsyncResult result = delAsync.BeginInvoke (null, null); //Process other user instructions string strFile -delAsync.EndInvoke (result);

Answer: A
QUESTION 108
Which methods allow COM components to be used in .NET applications? (Choose all that applay.)
A.Add a reference to the component throudh Microsoft Visual Studio 2005. B.Use the type Library Import tool (TlbImport.exe). C.Use the Regsvr32 tool. D.Ensure thet the application is registered, using the RegSvr tool if necessary. Then either add a reference to it
from the COM tab of the Add Reference dialog box or use TblIpm.exe.

Answer: ABD
QUESTION 109
What types of objects derive from te MemberInfo class? (Chose all that applay.)
A. FieldInfo class
B. MethodInfo class
C. Assembly class
D. Type class

Answer: ABD
QUESTION 110
When compressing data with the DeflateStream class, how do you specify a stream into which to write compressed data?
A.Set the BaseStream property with the destination stream, and set the CompressionMode property to Compression.

B.Specify the stream to write into the DeflateStream object is created (for example, in the constructor).
C.Use the Write method of the DeflateStream class. D.Register for the BaseSream event of the DeflateStream class.

Answer: B
QUESTION 111
You work as an application developer. You are currently in the process of creating an application that reads binary information from a file.
You need to ensure that the only the first kilobyte of data is retrieved.
Vhat should you do?
A.Use the following code: FileStream fs = new FileStream ("C:\\file.txt' FiloModo.Open) BufferedStream bs =
new BufferedStream (fs);
byte [ ] bytes = new byte [1023];
bs. Head (bytes, 0, bytes. Length) ;
bs. Close 0 ;
for (int i = 0; i < bytes, Length-1: i++)
Console, WriteLitie {"{0} : [!}", I, bytes [i]);
B.Use the following code:
FileStream fs = new FileStream ("C:\\file. txt", FileMode.Open); byte [ ] bytes = new byte [1023];
fs. Read (bytes, 0, bytes. Length);
fs. Close 0 ;
for 0tit i = 0; i < bytes. Length-1 ; L++)
Console. WriteLine (*"{0) : (1}", I, bytes [i]);
C.Use the following code:
FileStream fs = new FileStream ("C:\\file. txt", FileMode.Open); BufferedStream bs = new BufferedStream
(Is);
byte [ ] bytes = new byte [1023]:
bytes = bs. ReadAllBytes (0, 1023):
bs. Close () ;
for (int i = 0; i < bytes.Length-l; i++)
Console. WriteLine ("{0} : {1}", I, bytes [i]);
D.Use the following code:
FileStream fs = new FileStream ('CrWfile. txt", FileMode.Open):
BufferedStream bs = new BufferedStream (f s);
byte [ ] bytes = new byte [1023] ;
bs. Read (bytes) ;
bs. Close 0 ;
for (itit i = 0; i < bytes.Length-1; i++) Console. WriteLine {"{0} : {1}", T, bytes [i]):


Answer: B
QUESTION 112
Where can you add items to a LinkedList? (Choose all that apply.)
A. At the beginning of the LitikedList
B. Before any specific node
C. After any specific node
D. At the end of the Linkedlist
E. At any numeric index in the LinkedList

Answer: ABCD
QUESTION 113
Which event would you use Lo run a mothod immediately before deserialization occurs?
A. OnSerializing
B. OnDserializing
C. OnSerialized
D. OnDeserialized

Answer: B
QUESTION 114
You work as the application developer. You are creating a new class which contains a method named GetCurrentRate. GetCurrentRate extracts the current interest rate from a variable named currRate, currRate contains the current interest rate which should be used.
You develop serialized representations of the class and now need to write a code segment which updates the currRate variable with the current interest rate if an instance of the class is deserialized. Choose the code segment which will accomplish this task.
A.[OnSerializing] internal void updateValue (StreamingContext context) {pcurrRate = GetCurrent Rate(); }
B.[OnSerializing] internal void UpdateValue (Serialisationlnfo info) { info.AddValue {"currontRate", GetCurrentRate ()); }

C.[OnDeserializing] internal void UpdateValue {Serializationlnfo info) {info. AddValue ("currentRate",
GetCurrentRate ()); } D.[OnDeserialized] internal void UpdateValue (StreamingContext context) { currRate = GetCurrentRate(); }

Answer: D
QUESTION 115
You work as an application developer. Company wants you to develop an application that handles passes for abc.com' s parking lot. The application has to store and retrieve vehicle information using a vehicle identification number {VIN).
You need to use the correct code to ensure type-safety.
What should you do?
A.Use the following code: Vehicle vl, v2; vl = new Vehicle ("1M2567871Y91234574" , 'Nissan Silvia", 1996): v2 = new Vehicle ("lF2569122491234574" , 'Mitsubishi Lancer", 2005); ArrayList vList = new ArrayList (); vList, Add (vl); vList.Add (v2):
B.Use the following code: Vehicle vl, v2; vl = new Vehicle ("lM2567871Y91234574", 'Nissan Silvia", 1996): v2 = new Vehicle ("1F2569122491234574", "Mitsubishi Lancer", 2005); SortedList vList = new SortedList C.Use the following code: Vehicle vlh v2: vl = new Vehicle ("1M2567871Y91234574", "Nissan Silvia", 1996); v2 = new Vehicle ("IF2569122491234574", 'Mitsubishi Lancer", 2005); List vList = new List (); vList.Add (vl); vList.Add (v2);
D.Use the following code: Vehicle vl, v2; V1 = new Vehicle ("1M2567871Y91234574", "Nissan Silvia', 1996); v2 = new Vehicle ("1F2569122491234574", "Mitsubishi Lancer", 2005) SortedList vList = new SortedList (); vList.Add (vl.VIN, vl) ; vList.Add (v2. YIN, v2) ;


Answer: B
QUESTION 116
You work as the application developer. Company uses Visual Studio. NET 2005 as its application development platform.
You are developing a .NET Framework 2.0 text manipulation application. You make use of the code below in your application:
Dim ckBuilder As StringBuilder = New StringBuildor (":string:")
Dim b() As Char = {"a"c, " b"c, "c"c, "d"c, "e"c, "f"c, "g"c}
Dim ckWriter As StringWriter = New StringWriter (ckBuilder) ckWriter.Write (b, 0, 3)
Console.WriteLine (ckBuilder)
ckWriter.Close ()
You are required to select from the following what the output will be when you execute the application. What should you do?
A. string:abcdefg
B. abc:string
C. Abcstring
D. string:abc
Answer: D
QUESTION 117
You work as an application developer. You are currently in the process of creating a new application.
You are required to read compressed data files that have been sent by company's sales offices. These data files are less than 4 GB in size, but were compressed without cyclic redundancy.
You want to write a method that receives the compressed files and return the uncompressed data as a byte array.
What should you do?
A.Use the following code: public byte [] DecompressFile (string file)

{
FileStream fs = new FileStream (file, FileMode, Open); DeflateStream cs = new DeflateStream (fs,
CompressionModc. Decompress, true) byte [ ] data = new byte [fs.Length -l];
cs. Read (data, (), data, Length);
cs. Close ();
return data;
}
:
B.Use the following code;
public byte [] DecompressFile (string file)
{
FileStream fs = new FileStream (file, FileModc, Open); GZipStream cs = new GZipStream {fs, Compress
iotiMndo. Decompress) byte [ ] data = new byte [fs. Length -1]; cs. Read (data, 0, data.Length);
return data:
}
C.Use the following code:
public byte [] DecompressFile (string file)
FileStream fs = new FileStream (file, FileMode,Open); DeflateStream cs = new DeflateStream (fs,
CompressionMode. Decompress) byte [ ] data = new byte [fs.Length -l];
cs. Read (data, 0, data.Length);
return data;
}
D.Use the following code:
public byte [] DecompressFile (string file)
{
FileStream. fs = new FileStream (file, FileMode. Open); GZipStream cs = new GZipStream (fs,
CompressionMode. Decompress, true) ; byte [ ] data = new byte [fs. Length -1];
cs. Read (data, 0, data. Length);
cs. close 0;
return data;
}
Answer: A
QUESTION 118
You write the following class that has three methods.
public class SimpleEmployee {
public string GetEmployeeId() { return employeeId; } public string GetName() { return employeeName; }

public string GetTitle() { return jobTitleName; }
You need to expose the class to COM in a type library. The COM interface must not expose the method GetEmployeeId. The GetEmployeeId method must still be available to managed code. You need to hide the GetEmployeeID method from the COM interface.
What should you do?
A.Apply the ComVisible attribute to the class and methods in the following manner.
[ComVisible(false)]
public class SimpleEmployee {
public string GetEmployeeId() { return employeeId; } [ComVisible(true)]
public string GetName() { return employeeName; }
[ComVisible(true)]
public string GetTitle() { return jobTitleName; }
B.Apply the ComVisible attribute to the class and methods in the following manner.
[ComVisible(true)]
public class SimpleEmployee {
public string GetEmployeeId() { return employeeId; } [ComVisible(true)]
public string GetName() { return employeeName; }
[ComVisible(true)]
public string GetTitle() { return jobTitleName; }
C.Apply the ComVisible attribute to the GetEmployeeId method in the following manner.
public class SimpleEmployee {
[ComVisible(false)]
public string GetEmployeeId() { return employeeId; } public string GetName() { return employeeName; }
public string GetTitle() { return jobTitleName; }
D.Change the access modifier for the GetEmployeeId method in the following manner.
public class SimpleEmployee {
protected string GetEmployeeId() { return employeeId; } public string GetName() { return employeeName; }
public string GetTitle() { return jobTitleName; }

Answer: C
QUESTION 119
You develop an application that appends text to existing text files. You need to write a code segment that enables the application to append text to a file named C:\MyFile.txt. The application must throw an exception if the file does not exist. You need to ensure that the other applications can read but not modify the file. Which code segment should you use?

A. FileStream fs = new FileStream(@"C:\MyFile.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
B. FileStream fs = new FileStream(@"C:\MyFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
C. FileStream fs = new FileStream(@"C:\MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
D. FileStream fs = new FileStream(@"C:\MyFile.txt", FileMode.Append, FileAccess.ReadWrite);

Answer: A
QUESTION 120
You are creating a class named Temperature. The Temperature class contains a public field named F. The public field F represents a temperature in degrees Fahrenheit. You need to ensure that users can specify whether a string representation of a Temperature instance displays the Fahrenheit value or the equivalent Celsius value. Which code segment should you use?
A.public class Temperature : IFormattable {
public int F;
public string ToString (string format, IFormatProvider fp ) { if ((format == "F")|| (format == null)) return
F.ToString (); if (format == "C") return ((F -32) / 1.8). ToString (); throw new FormatException ("Invalid format
string"); }
}
B.public class Temperature : ICustomFormatter {
public int F;
public string Format(string format, object arg ,
IFormatProvider fp ) {
if (format == "C") return ((F -32) / 1.8). ToString (); if (format == "F") return arg.ToString ();
throw new FormatException ("Invalid format string"); }
}
C.public class Temperature {
public int F;
public string ToString (string format, IFormatProvider fp ) { if (format == "C") {
return ((F -32) / 1.8). ToString ();
} else {
return this.ToString ();
}
}
} D.public class Temperature {
public int F; protected string format;

public override String ToString () {
if (format == "C")
return ((F -32) / 1.8). ToString ();
return F.ToString ();
}
}

Answer: A
QUESTION 121
You are creating an assembly that interacts with the file system. You need to configure a permission request so that the common language runtime (CLR) will stop loading the assembly if the necessary file permissions are absent. Which attribute should you place in your code?
A. [assembly: FileIOPermission( SecurityAction.RequestOptional, AllFiles=FileIOPermissionAccess.Read) ]
B. [assembly: FileIOPermission( SecurityAction.RequestRefuse, AllLocalFiles= FileIOPermissionAccess.Read) ]
C. [assembly: FileIOPermission( SecurityAction.RequestMinimum, AllLocalFiles = FileIOPermissionAccess.Read) ]
D. [assembly: FileIOPermission( SecurityAction.RequestOptional, AllLocalFiles = FileIOPermissionAccess.Read) ]

Answer: C
QUESTION 122
You are developing a multithreaded application. You need to ensure that a shared resource maintains a consistent state when multiple threads update it. You also need to permit multiple threads to read the shared resource concurrently. What should you do?
A.Use the AcquireWriterLock and ReleaseWriterLock methods of the ReaderWriterLock class when updating the shared resource. Use the AcquireReaderLock and ReleaseReaderLock methods of the

ReaderWriterLock class when reading from the shared resource. B.Always access the resource within a lock statement block. C.Create a wrapper class to protect the resource and always access the resource by using static methods of
the wrapper class. D.Always use a single-threaded apartment when accessing the resource.

Answer: A
QUESTION 123
DRAG DROP
You are creating an application that retrieves values from a custom section of the application configuration file. The custom section uses XML, as shown in the following code segment:
QUESTION 124 DRAG DROP
You are creating a class that uses unmanaged resources.
The class maintains references to managed resources on other objects.
You need to ensure that users of the class can explicitly release resources when the class instance is no longer needed.
Which actions should you perform in sequence?
To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.


Answer:

QUESTION 125
DRAG DROP
You develop a service application named FileService. You deploy the service application to multiple servers on your network.
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.

What should you do?
To answer, drag the appropriate code segment or segments to the correct location or locations in the answer area.

Answer:

QUESTION 126
DRAG DROP You need to create a common language runtime (CLR) unit of isolation within an application. Which code segments should you use in sequence?
To answer, move the appropriate code segments from the list of code segments to the answer area and arrange them in the correct order.


Answer:

QUESTION 127
You are developing a routine that will periodically perform a calculation based on regularly changing values from legacy systems. You write the following lines of code. (Line numbers are included for reference only.)
01 Dim exitLoop As Boolean = False
02 Do 04 exitLoop = PerformCalculation()

05 Loop While Not exitLoop
You need to write a code segment to ensure that the calculation is performed at 30-second intervals.
You must ensure that minimum processor resources are used between the calculations. Which code segment should you insert at line 03?
A. Thread.Sleep(30000);
B. Thread.SpinWait(30);
C. Thread.SpinWait(30000);
D. Dim thrdCurrent As Thread = Thread.CurrentThread; thrdCurrent.Priority = ThreadPriority.Lowest;
E. Dim thrdCurrent As Thread = Thread.CurrentThread; thrdCurrent.Priority = ThreadPriority.BelowNormal;

Answer: A
QUESTION 128
DRAG DROP You are writing a method that returns an ArrayList.
You need to ensure that changes to the ArrayList are performed in a thread-safe manner.
Which actions should you perform in sequence?
To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.


Answer:

QUESTION 129
DRAG DROP
You are testing a newly developed method named PersistToDB. The method accepts a parameter of type EventLogEntry and does not return a value. The current test function is shown in the following code segment: 01 public TestPersistToDB() 02 {
04 foreach (EventLogEntry entry in myLog.Entries) 05 { 06 if (entry.Source == "MySource") 07 {
09 } 10 } 11 } The test function must read entries from the application log of local computers and then pass the entries to the
PersistToDB() method. The test function implementation must pass only events of type Error or Warning from a source named MySource to the PersistToDB() method.

You need to complete the code segment.
Which code segments should you add to line 03 and between lines 07 and 09 in sequence?
To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.

Answer:

QUESTION 130
DRAG DROP You need to add a string named strConn to the connection string section of the application configuration file. Which code segments should you use in sequence? To answer, move the appropriate code segments from the list of code segments to the answer area and
arrange them in the correct order.


Answer:

QUESTION 131
DRAG DROP
You create a class library that is used by applications in three different departments of the company. The library contains a Department class with the following definition: public class Department {

public string name;
public 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 segment: HardWare Amy
You need to create a Department object instance by using the field values retrieved from the application configuration file.
How should you complete the code segment? To answer, drag the appropriate code segment or segments to the correct location or locations in the answer area.

Answer: QUESTION 132


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 class Group { 02 public Employee[] Employees; 03 } 04 public class Employee { 05 public string Name; 06 } 07 public class Manager : Employee { 08 public int Level;
09 } 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 1 and 2 of the code segment: [XmlArray(ElementName="Employees")]
B. Insert the following code between lines 1 and 2 of the code segment: [XmlElement(Type = typeof(Employees))]
C. Insert the following code between lines 1 and 2 of the code segment: [XmlArrayItem(Type = typeof(Employee))] [XmlArrayItem(Type = typeof(Manager))]
D. Insert the following code between lines 3 and 4 of the code segment: [XmlElement(Type = typeof(Employee))] and Insert the following code between lines 6 and 7 of the code segment: [XmlElement(Type = typeof(Manager))]

Answer: C
QUESTION 133
You are writing a custom collection class named MyCollection. You need to ensure that the collection is type safe.
Which code segment should you use?
A. class MyCollection: ICollection
B. class MyCollection: ICollection
C. class MyCollection: ArrayList
D. class MyCollection: IComparer

Answer: C
QUESTION 134
You need to write a multicast delegate for an event. The event must also be able to use an EventHandler delegate. Which code segment should you use?
A. public delegate int PowerDeviceOn ( bool result-, DateTime autoPowerOf f );
B. public delegate bool PowerDeviceOn ( DateTime autoPowerOff );
C. public delegate void PowerDeviceOn ( DateTime autoPowerOff );
D. public delegate bool PowerDeviceOn (object sender, EventArgs autoPowerOff ) ;
Answer: D QUESTION 135

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. BitArray answers = new BitArray(-1);
B. BitVector32 answers = new BitVector32(1);
C. BitArray answers = new BitArray (1);
D. BitVector32 answers = new BitVector32(-1);

Answer: D
QUESTION 136
DRAG DROP You are creating a class named Age. You need to ensure that collections of Age objects can be sorted. How should you implement the Age class? To answer, drag the appropriate code segment or segments to the correct location or locations in the answer
area.


Answer:



QUESTION 137
You create a service application that monitors free space on a hard disk drive.
You need to ensure that the service application runs in the background and monitors the free space every minute.
What should you do? (Each correct answer presents part of the solution. Choose three.)
A.Add an instance of the System.Windows.Forms.Timer class to the Service class and configure it to fire every minute B.Add code to the default constructor of the Service class to monitor the free space on the hard disk drive C.Add code to the Tick event handler of the timer to monitor the free space on the hard disk drive D.Add code to the OnStart() method of the Service class to monitor the free space on the hard disk drive E.Add code to the OnStart() method of the Service class to start the timer.
F. Add code to the Elapsed event handler of the timer to monitor the free space on the hard disk drive G.Add an instance of the System.Timers.Timer class to the Service class and configure it to fire every minute
Answer: EFG
QUESTION 138
You write the following code to implement the MyClass.MyMethod function.
public class MyClass { public int MyMethod(int arg) {

return arg;
}
}
You need to call the MyClass.MyMethod function dynamically from an unrelated class in your assembly.
Which code segment should you use?
A.MyClass myClass = new MyClass(); Type t = typeof(MyClass); Methodlnfo m = t.GetMethod("MyClass.MyMethod"); int i = (int)m.Invoke(myClass, new object[] { 1 });
B.MyClass myClass = new MyClass(); Type t = typeof(MyClass); Methodlnfo m = t.GetMethod("MyMethod"); int i = (int)m.Invoke(this, new object[] { 1} );
C.Type t = Type.GetType("MyClass") ; Methodlnfo to = t .GetMethod( "MyMethod") ; int i = (int)m.Invoke(this, new object[] { 1 });
D.MyClass myClass = new MyClass(); Type t = typeof(MyClass); Methodlnfo rn -t.GetMethod ("MyMethod") ; int i = (int) m.Invoke(myClass, new object[] { 1 });

Answer: B
QUESTION 139
You need to ensure that each thread pauses by the number of milliseconds specified in the sleepTime variable. Which code segment should you add at line PO46 of the Poller.cs file?
A. Thread.Sleep(sleepTime);
B. Object wait = "WaitTime"; Thread.VolatileWrite (ref wait, sleepTime);
C. Thread.VolatileRead(ref sleepTime);
D. Thread.SpinWait(sleepTime);
Answer: A
QUESTION 140

You need to retrieve all queued e-mail messages into a collection and ensure type safety. Which code segment should you use to define the signature of the GetQueuedEmailsFromDb() method in the Poller.cs file?
A. private static object[] GetQueuedEmailsFromDb(int queueID)
B. private static ArrayList GetQueuedEmailsFromDb(int queueID)
C. private static EmailMessages GetQueuedEmailsFromDb(int queueID)
D. private static IList GetQueuedEmailsFromDb(int queueID)

Answer: C
QUESTION 141
You need to ensure that the list of queued e-mail messages is sorted by priority value from highest to lowest. Which code segment should you add to line LE13 of the Local Entities?
A. return Priority.GetValueOrDefault(-1).CompareTo(other.Priority.GetValueOrDefault(-1)) * -1;
B. return Priority.GetValueOrDefault(-1).CompareTo(other.Priority.GetValueOrDefault(-1));
C. return Priority.Value.CompareTo(other.Priority.Value);
D. return Priority.Value.CompareTo(other.Priority.Value) * -1;
Answer: A
QUESTION 142
DRAG DROP
You need to complete the btnService_Click event in the ControlService.aspx.cs file. What should you do? To answer, drag the appropriate code segment or segments to the correct location or locations in the work area.


A.
B.
C.
D.

Answer:
QUESTION 143
You need to implement the EmailSenderService class so that the service sends queued e-mail messages when it is started and stops sending e-mail messages when it is stopped. Which code segments should you use? (Each correct answer is part of a complete solution. Choose two.)
A. protected override void OnStop() { Poller p = new Poller();
B. Stop(); }
C. protected void Start(string[] args) {
D. Start(); }
E. protected void Stop() {
F. Stop(); }
G. protected override void OnStart(string[] args) {
H. Start(); }
I. protected override void OnStop() {
J. Stop(); }
K. protected void OnStart() {
L. Start(); }
Answer: DE QUESTION 144

You need to ensure that dates and numbers are displayed correctly for each user based on location.
Which code segment should you add to line GL08 of the Global.asax file?
A.System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo(culture); System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
B.CultureInfo info = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone(); info = CultureInfo.CreateSpecificCulture(culture);
C.System.Globalization.CultureInfo cultureInfo = CultureInfo.GetCultureInfo(culture); System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; D.System.Globalization.CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture(culture); System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
Answer: A
QUESTION 145
DRAG DROP
You need to design The process for keeping track of each user's login to the administrative site.
Which actions should you perform in sequence?
To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.


Answer:

QUESTION 146
You need to store Product, MainProduct, and SecondaryProduct instances that end users place in the shopping cart by using a collection. Which code segment should you use to initiate the collection?
A. List products = new List();
B. ArrayList products = new ArrayList();
C. IList products = new List();
D. SortedList products = new SortedList();

Answer: B
QUESTION 147
You need to read the content of the XML log file. Which code segment should you add to line LO04 of the Login.aspx.cs file?
A. FileInfo fi = new FileInfo(filePath); string xml = fi.ToString(); fi.Refresh();
B. StreamReader sr = File.OpenText(filePath); string xml = sr.ReadToEnd(); sr.Close();
C. FileInfo fi = new FileInfo(filePath); fi.Refresh(); string xml = fi.ToString();
D. StreamReader sr = File.OpenText(filePath); sr.Close(); string xml = sr.ReadToEnd();
Answer: B QUESTION 148

You need to implement the for loop of the Start() method contained in the Poller.cs file. Which code segments should you insert at line PO11 of the Poller.cs file? (Each correct answer presents part of the solution. Choose three.)
A. running.Add(1, false);
B. SenderThread(i);
C. Thread t = new Thread(Start);
D. thread.Start();
E. Thread thread = new Thread(new ParameterizedThreadStart(SenderThread));
F. running.Add(i, true);
G. thread.Start(i);

Answer: DEF
QUESTION 149
You need to complete the SendEmail() method contained in the EmailUtility.cs file. Which code segments should you use? (Each correct answer presents part of the solution. Choose two.)
A. mm.From = new MailAddress(String.Join(mailTo, ";"));
B. foreach (string to in mailTo) mm.Headers.Add("to", to); Next
C. mm.From = new MailAddress(from);
D. foreach (string to in mailTo) mm.To.Add(to.Trim());

Answer: CD
QUESTION 150
You need to log an entry in a custom event log when the EmailSenderService service is started and stopped. What should you do? (Each correct answer presents part of the solution. Choose three.)
A. Add the following code segment to line PO13 of the Poller.cs file: EventLog.WriteEntry("EmailSenderService", "Started", EventLogEntryType.Information);
B. Add the following code segment to line PO25 of the Poller.cs file: EventLog.WriteEntry("Application", "EmailSenderService:Stopped", EventLogEntryType.Information);
C. Add the following code segment to line PO25 of the Poller.cs file: EventLog.WriteEntry("EmailSenderService", "Stopped", EventLogEntryType.Information);

D. Add the following code segment to line ES10 of the EmailSenderService.cs file:
EventLog.CreateEventSource("Application", "EmailSenderService");
E. Add the following code segment to line PO13 of the Poller.cs file: EventLog.WriteEntry("Application", "EmailSenderService:Started", EventLogEntryType.Information);
F. Add the following code segment to line ES10 of the EmailSenderService.cs file: EventLog.CreateEventSource("EmailSenderService", "EmailLog");

Answer: ACF
QUESTION 151
Each order-processing step is a method that takes an Order object. Each method returns true if the step completes successfully or false if the step does not complete.
To support a custom set of steps specific to each client, the steps have been added to an event that is called when an order is processed.
Vou need to ensure that the error property of the Order object is set to true if any method returns false.
With which code segment should you replace line OP48 in the OrderProcessor.es file?
A. foreach (Delegate process in OrderProcesses.GetlnvocationList()) { if ((bool)process.DynamicInvoke(new objectf] { order }) == false) { order.Error = true; } }
B. if (OrderProcesses.Invoke(order) == false) { order.Error = true; }
C. if ((bool)OrderProcesses.Method.Invoke(null, new object[] { order }) == false) { order.Error = true; }
D. OrderProcesses.Invoke(order); foreach (Delegate process in OrderProcesses.GetlnvocationList()) { if ((bool)process.Target == false) { order.Error = true; } }
Answer: A QUESTION 152

A BooleanSwitch instance has been created in the OrderProcessingSteps.es file to enable detailed logging during testing.
You need to ensure that the order-processing service logs all steps.
Which code segment should you add to the order-processing service' s configuration?
A. oystero. diagnostics>
B. oppSettings> odd key="Oi:derProcessingSteps.LogSteps" />
C.
D. Odd key="Switches.LogSteps" value="l" />
Answer: A
QUESTION 153
You need to ensure that the client-supplied DateTime value is stored in the correct format,
Which code segment should you use as the body of the NormalizedOrderDate function in the OrderProcessor.es file? (Each correct answer presents a complete solution. Choose two.)
A.return inputOrderDate.ToUniversalTime(); B.if (inputOrderDate.Kind != DateTimeKind.Utc) return inputOrderDate.ToUniversalTime(); ilse return inputOrderDate; C.if (inputOrderDate.Kind == DateTimeKind.Unspecified) { return inputOrderDate.ToUniversalTime }

else
{
return inputOrderDate;
}
D.DateTime orderDateTime;
if (IDateTime.TryParse(inputOrderDate.ToString("o"), out orderDateTime)) {
return orderDateTime.ToUniversalTime(); >
}
else
{
return orderDateTime.ToLocalTime()
} E.return inputOrderDate.ToLocalTime().ToUniversalTime(); F.return DateTime.ParseExact(inputOrderDate.ToString("o") , "o", DateTimeFormatlnfo.Invariantlnfo);

Answer: DF
QUESTION 154
The ProcessPayment step in the OrderProcessingSteps.es file uses a cornmand-line executable to process payments. The command-line executable accepts a credit card information string on its input stream, submits the credit card charge, and then returns "Approved" if the charge is accepted.
You need to ensure that the ProcessPayment step returns true when a charge is approved and otherwise returns false.
With which code segment should you replace line OS26 in the OrderProcessingSteps.es file?
A. proc.Start(); proc.Standardlnput.WriteLine(order.CreditCardlnformation); proc.WaitForExit () ; taool result = proc.StandardOutput.ReadToEnd().Trim().EndsWith("Approved"); proc.Close(); return result;
B. proc.Start () ; proc.WaitForlnputldle() ; proc.StandardInput.WriteLine(order.CreditCardlnformation) ; bool result -proc.ToString().EndsUith("Approved"); proc.Close() ; return result;
C. proc.Start Info.Arguments = order.CreditCardlnformation; proc.Start(); bool result = proc.StandardOutput.ReadToEnd().EndsUith("Approved"); proc.Close() ; return result;
D. proc.Start Info.Arguments = order.CreditCardlnformation; proc.Start(); bool result = proc.ToString() .EndsUith("Approved"); proc.Close(); return result;


Answer: A
QUESTION 155
You need to write a code segment that will add a string named strConn to the connection string section of the application configuration file. Which code segment should you use?
A. Dim myConfig As Configuration = _ ConfigurationManager.OpenExeConfiguration( _ ConfigurationUserLevel.None) myConfig.ConnectionStrings.ConnectionStrings.Add( _ New ConnectionStringSettings("ConnStr1", strConn)) myConfig.Save()
B. Dim myConfig As Configuration = _ ConfigurationManager.OpenExeConfiguration( _ ConfigurationUserLevel.None) myConfig.ConnectionStrings.ConnectionStrings.Add( _ New ConnectionStringSettings("ConnStr1", strConn)) ConfigurationManager.RefreshSection("ConnectionStrings")
C. ConfigurationManager.ConnectionStrings.Add( _ New ConnectionStringSettings("ConnStr1", strConn)) ConfigurationManager.RefreshSection("ConnectionStrings")
D. ConfigurationManager.ConnectionStrings.Add( New ConnectionStringSettings("ConnStr1", strConn)) Dim myConfig As Configuration = _ ConfigurationManager.OpenExeConfiguration( _ ConfigurationUserLevel.None) myConfig.Save()

Answer: B
QUESTION 156
You are developing an auditing application to display the trusted ClickOnce applications that are installed on a computer. You need the auditing application to display the origin of each trusted application. Which code segment should you use?
A.Dim objTrusts As ApplicationTrustCollection objTrusts = ApplicationSecurityManager.UserApplicationTrusts For Each objTrust As ApplicationTrust In objTrusts Console.WriteLine(objTrust.ToString) Next B.Dim objTrusts As ApplicationTrustCollection

objTrusts = ApplicationSecurityManager.UserApplicationTrusts For Each objTrust As ApplicationTrust In objTrusts Console.WriteLine(objTrust.ExtraInfo.ToString) Next
C.Dim objTrusts As ApplicationTrustCollection objTrusts = ApplicationSecurityManager.UserApplicationTrusts For Each objTrust As ApplicationTrust In objTrusts Console.WriteLine(objTrust.ApplicationIdentity.FullName.ToString) Next
D.Dim objTrusts As ApplicationTrustCollection objTrusts = ApplicationSecurityManager.UserApplicationTrusts For Each objTrust As Object In objTrusts Console.WriteLine(objTrust.ToString) Next

Answer: C
QUESTION 157
You develop an application that appends text to existing text files. You need to write a code segment that enables the application to append text to a file named C:\MyFile.txt. The application must throw an exception if the file does not exist. You need to ensure that the other applications can read but not modify the file. Which code segment should you use?
A. Dim fs As New FileStream("C:\MyFile.txt", _ FileMode.Open, FileAccess.ReadWrite, FileShare.Read)
B. Dim fs As New FileStream("C:\MyFile.txt", _ FileMode.OpenOrCreate, FileAccess.ReadWrite, _ FileShare.Read)
C. Dim fs As New FileStream("C:\MyFile.txt", _ FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
D. Dim fs As New FileStream("C:\MyFile.txt", _ FileMode.Append, FileAccess.ReadWrite)

Answer: A
QUESTION 158
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 domain As AppDomain domain = AppDomain.CreateDomain("MyDomain")
B. Dim myComponent As System.ComponentModel.Component

myComponent = New System.ComponentModel.Component()
C. Dim mySetup As AppDomainSetup = _ AppDomain.CurrentDomain.SetupInformation mySetup.ShadowCopyFiles = "true"
D. Dim myProcess As System.Diagnostics.Process myProcess = New System.Diagnostics.Process()

Answer: A
QUESTION 159
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 Sub PerformCalculation ( _ ByVal values As Object) ... End Sub Private Sub DoWork() Dim myValues As New CalculationValues() Dim newThread As New Thread( _ New ParameterizedThreadStart( _ AddressOf PerformCalculation)) newThread.Start(myValues) End Sub
B. Private Sub PerformCalculation ( _ ByVal values As CalculationValues) ... End Sub Private Sub DoWork() Dim myValues As New CalculationValues() Application.DoEvents() PerformCalculation(myValues) Application.DoEvents() End Sub
C. Private Sub PerformCalculation() ... End Sub

Private Sub DoWork() Dim myValues As New CalculationValues() Dim delStart As New ThreadStart( _ AddressOf PerformCalculation) Dim newThread As New Thread(delStart) If newThread.IsAlive Then newThread.Start(myValues) End If End Sub
D. Private Sub PerformCalculation() ... End Sub Private Sub DoWork() Dim myValues As New CalculationValues() Dim newThread As New Thread( _ New ThreadStart(AddressOf PerformCalculation)) newThread.Start(myValues) End Sub

Answer: A
QUESTION 160
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 Sub
End 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.Move the loop code from the OnStart method into the DoWork method. C.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.
D.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.

Answer: D
QUESTION 161
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 Sub StartService(ByVal serverName As String)
02 Dim crtl As ServiceController = _ 03 New ServiceController("FileService")

04 If crtl.Status = ServiceControllerStatus.Stopped Then
05 End If
06 End Sub
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 04 and 05: crtl.ExecuteCommand(0)
B. Insert the following line of code between lines 04 and 05: crtl.Continue()
C. Insert the following line of code between lines 04 and 05:crtl.Start()
D. Insert the following line of code between lines 03 and 04: crtl.ServiceName = serverName
E. Insert the following line of code between lines 03 and 04: crtl.MachineName = serverName
F. Insert the following line of code between lines 03 and 04: crtl.Site.Name = serverName

Answer: CE
QUESTION 162
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. For each calculation, call the QueueUserWorkItem method of the ThreadPool class.
C. Set the Process.GetCurrentProcess().BasePriority property to High.
D. Set the ProcessorAffinity property of the ProcessThread object.
Answer: B
QUESTION 163
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. Dim al As ArrayList = New ArrayList() Dim sync_al as ArrayList = ArrayList.Synchronized(al) Return sync_al
B. Dim al As ArrayList = New ArrayList() SyncLock al.SyncRoot.GetType() Return al End SyncLock
C. Dim al As ArrayList = New ArrayList() Monitor.Enter(al) Monitor.Exit(al) Return al
D. Dim al As ArrayList = New ArrayList() SyncLock al.SyncRoot Return al End SyncLock

Answer: A
QUESTION 164
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. Dim myLog as New EventLog("Application", ".") myLog.Source = "MySource" For Each entry As EventLogEntry In myLog.Entries If entry.EntryType = (EventLogEntryType.Error And _ EventLogEntryType.Warning) Then PersistToDB(entry) End If Next
B. Dim myLog as New EventLog("Application", ".") myLog.Source = "MySource" For Each entry As EventLogEntry In myLog.Entries If (entry.EntryType = EventLogEntryType.Error) Or _ (entry.EntryType = EventLogEntryType.Warning) Then PersistToDB(entry)

End If
Next
C. Dim myLog as New EventLog("Application", ".") For Each entry As EventLogEntry In myLog.Entries If entry.Source = "MySource" Then If (entry.EntryType = EventLogEntryType.Error) Or _ (entry.EntryType = EventLogEntryType.Warning) Then PersistToDB(entry) End If End If Next
D. Dim myLog As New EventLog("Application", ".") For Each entry As EventLogEntry In myLog.Entries If entry.Source = "MySource" Then PersistToDB(entry) End If Next

Answer: C
QUESTION 165
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. Create an event handler class that has a method that receives an ObjectReadyEventArgs parameter.
B. Set up a listener for events by using the Stopped event of the ManagementEventWatcher.
C. Use the WaitForNextEvent method of the ManagementEventWatcher to wait for the events.
D. Start listening for events by calling the Start method of the ManagementEventWatcher.
E. Set up a listener for events by using the EventArrived event of the ManagementEventWatcher.

Answer: DE
QUESTION 166
You are testing a method that examines a running process. This method returns an ArrayList containing the name and full path of all modules that are loaded by the process. You need to list the modules loaded by a process named C:\TestApps\Process1.exe. Which code segment should you use?

A. Dim ar As New ArrayList() Dim procs As Process() Dim modules As ProcessModuleCollection procs = Process.GetProcesses("Process1") If procs.Length > 0 Then modules = procs(0).Modules For Each pm As ProcessModule In Modules ar.Add(pm.ModuleName) Next End If
B. Dim ar As New ArrayList() Dim procs As Process() Dim modules As ProcessModuleCollection procs = _ Process.GetProcessesByName("C:\TestApps\Process1.exe") If procs.Length > 0 Then modules = procs(0).Modules For Each pm As ProcessModule In Modules ar.Add(pm.FileName) Next End If
C. Dim ar As New ArrayList() Dim procs As Process() Dim modules As ProcessModuleCollection procs = Process.GetProcessesByName("Process1") If procs.Length > 0 Then modules = procs(0).Modules For Each pm As ProcessModule In Modules ar.Add(pm.FileName) Next End If
D. Dim ar As New ArrayList() Dim procs As Process() Dim modules As ProcessModuleCollection procs = Process.GetProcesses("C:\TestApps\Process1.exe") If procs.Length > 0 Then modules = procs(0).Modules For Each pm As ProcessModule In Modules ar.Add(pm.ModuleName) Next End If
Answer: C QUESTION 167

You are creating a strong-named assembly named Assembly1 that will be used in multiple applications. Assembly1 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 Assembly1 such that each application uses the latest build of Assembly1. 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:
C. Add the following XML element to the configuration file of each application that uses the strong-named assembly:
D. Add the following XML element to the machine configuration file:
E. Add the following XML element to the configuration file of each application that uses the strong-named assembly:

Answer: AD
QUESTION 168
You are using the Microsoft Visual Studio 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 "John"
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 = "John", "Test Failed: ", fName)

B. Debug.WriteLineIf(fName < > "John", _ fName, "Test Failed")
C. If fName < > "John" Then Debug.Print("Test Failed: ") Debug.Print(fName) End If
D. If fName < > "John" Then Debug.WriteLine("Test Failed: ") Debug.WriteLine(fName) End If

Answer: B
QUESTION 169
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 machine configuration file.

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


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

Answer: B
QUESTION 170
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. _ Public Class Employee
B. Add the following attribute to the class definition. _ Public Class Employee
C. Add the following attribute to the class definition. _ Public Class Employee
D. Define an interface for the class and add the following attribute to the class definition. _ Public Class Employee Implements IEmployee

Answer: D
QUESTION 171
You write the following class that has three methods.
Public Class SimpleEmployee
Private m_EmployeeId As String
Private m_EmployeeName As String
Private m_JobTitleName As String
Public Function GetID() As String Return m_EmployeeID
End Function
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 the class to COM in a type library. The COM
interface must not expose the method GetEmployeeId. The GetEmployeeId
method must still be available to managed code. You need to hide the
GetEmployeeID method from the COM interface. What should you do?
A. Apply the ComVisible attribute to the class and methods in the following manner. _ Public Class SimpleEmployee Private m_EmployeeId As String Private m_EmployeeName As String Private m_JobTitleName As String Public Function GetID() As String Return m_EmployeeId End Function _ Public Function GetName() As String Return m_EmployeeName End Function _ Public Function GetTitle() As String Return m_JobTitleName End Function End Class
B. Apply the ComVisible attribute to the class and methods in the following manner. [ _ Public Class SimpleEmployee Private m_EmployeeId As String Private m_EmployeeName As String Private m_JobTitleName As String Public Function GetID() As String Return m_EmployeeId End Function _ Public Function GetName() As String Return m_EmployeeName End Function _ Public Function GetTitle() As String Return m_JobTitleName End Function End Class

C. Apply the ComVisible attribute to the GetEmployeeId method in the following manner. Public Class SimpleEmployee Private m_EmployeeId As String Private m_EmployeeName As String Private m_JobTitleName As String _ Public Function GetID() As String Return m_EmployeeID End Function Public Function GetName() As String Return m_EmployeeName End Function Public Function GetTitle() As String Return m_JobTitleName End Function End Class
D. Change the access modifier for the GetEmployeeId method in the following manner. Public Class SimpleEmployee Private m_EmployeeId As String Private m_EmployeeName As String Private m_JobTitleName As String Protected Function GetID() As String Return m_EmployeeID End Function Public Function GetName() As String Return m_EmployeeName End Function Public Function GetTitle() As String Return m_JobTitleName End Function End Class
Answer: C
QUESTION 172
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 Sub End 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 CustomException.COR_E_ARGUMENT
B. Return Marshal.GetExceptionForHR( _ CustomException.COR_E_ARGUMENT)
C. Throw New CustomException("Argument is out of bounds")
D. Marshal.ThrowExceptionForHR( _ CustomException.COR_E_ARGUMENT)

Answer: C
QUESTION 173
You write the following code to implement the MyClass.MyMethod function. Public Class NewClass Public Function MyMethod(ByVal Arg As Integer) As Integer Return Arg End Function End Class You need to call the MyClass.MyMethod function dynamically from an unrelated class in your assembly. Which code segment should you use?
A. Dim objNewClass As New NewClass Dim objType As Type = objNewClass.GetType

Dim objInfo As MethodInfo = _ objType.GetMethod("MyMethod") Dim objParams() As Object = {1} Dim i As Integer = _ DirectCast(objInfo.Invoke(Me, objParams), Integer)
B. Dim objNewClass As New NewClass Dim objType As Type = objNewClass.GetType Dim objInfo As MethodInfo = objType.GetMethod("MyMethod") Dim objParams() As Object = {1} Dim i As Integer = _ DirectCast(objInfo.Invoke(objNewClass, objParams), Integer)
C. Dim objNewClass As New NewClass Dim objType As Type = objNewClass.GetType Dim objInfo As MethodInfo = _ objType.GetMethod("NewClass.MyMethod") Dim objParams() As Object = {1} Dim i As Integer = _ DirectCast(objInfo.Invoke(objNewClass, objParams), Integer)
D. Dim objType As Type = Type.GetType("NewClass") Dim objInfo As MethodInfo = objType.GetMethod("MyMethod") Dim objParams() As Object = {1} Dim i As Integer = _ DirectCast(objInfo.Invoke(Me, objParams), Integer)

Answer: B
QUESTION 174
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. _ Function MessageBox( _ ByVal hWnd As IntPtr, ByVal text As String, _ ByVal Caption As String, ByVal t As UInt32) As Integer End Function
B. _ Function MessageBox( _ ByVal hWnd As IntPtr, ByVal text As String, _ ByVal Caption As String, ByVal t As UInt32) As Integer End Function

C. _
Function Win32API_User32_MessageBox ( _
ByVal hWnd As IntPtr, ByVal text As String, _
ByVal Caption As String, ByVal t As UInt32) As Integer End Function
D. _ Function MessageBoxA( _ ByVal hWnd As IntPtr, ByVal text As String, _ ByVal Caption As String, ByVal t As UInt32) As Integer End Function

Answer: A
QUESTION 175
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. Dim objAssembly As New AssemblyName() objAssembly.Name = "MyAssembly" Dim objBuilder As AssemblyBuilder = _ AppDomain.CurrentDomain.DefineDynamicAssembly( _ objAssembly, AssemblyBuilderAccess.Save) objBuilder.Save("MyAssembly.dll")
B. Dim objAssembly As New AssemblyName() objAssembly.Name = "MyAssembly" Dim objBuilder As AssemblyBuilder = _ AppDomain.CurrentDomain.DefineDynamicAssembly( _ objAssembly, AssemblyBuilderAccess.Save) objBuilder.Save("c:\MyAssembly.dll")
C. Dim objAssembly As New AssemblyName() objAssembly.Name = "MyAssembly" Dim objBuilder As AssemblyBuilder = _ AppDomain.CurrentDomain.DefineDynamicAssembly( _ objAssembly, AssemblyBuilderAccess.Run) objBuilder.Save("MyAssembly.dll")
D. Dim objAssembly As New AssemblyName() objAssembly.Name = "MyAssembly" Dim objBuilder As AssemblyBuilder = _ AppDomain.CurrentDomain.DefineDynamicAssembly( _ objAssembly, AssemblyBuilderAccess.RunAndSave) objBuilder.Save("MyAssembly.dll")
Answer: A QUESTION 176

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 WindowsIdentity(UserName) Dim objUser As New WindowsPrincipal(objID) Thread.CurrentPrincipal = objUser
B.Dim objID As New GenericIdentity(UserName) Dim objUser As New GenericPrincipal(objID, RolesArray) Thread.CurrentPrincipal = objUser
C.Dim objToken As IntPtr = IntPtr.Zero objToken = LogonUserUsingInterop(UserName, EncryptedPassword) Dim objContext As WindowsImpersonationContext = _ WindowsIdentity.Impersonate(objToken)
D.Dim objNT As New NTAccount(UserName) Dim objID As New GenericIdentity(objNT.Value) Dim objUser As New GenericPrincipal(objID, RolesArray) Thread.CurrentPrincipal = objUser
Answer: B
QUESTION 177
You create a DirectorySecurity object for the working directory. You
need to identify the user accounts and groups that have read and write

permissions. Which method should you use on the DirectorySecurity
object?
A. the GetAuditRules method
B. the GetAccessRules method
C. the AccessRuleFactory method
D. the AuditRuleFactory method

Answer: B
QUESTION 178
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.Unrestrict ed) objPermission.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. objPermission.Deny()
D. objPermission.PermitOnly()
Answer: A QUESTION 179

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 WindowsPrincipal = _ DirectCast(Thread.CurrentPrincipal, WindowsPrincipal) Dim blnAuth As Boolean = _ objUser.IsInRole(Environment.MachineName)
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 WindowsIdentity = WindowsIdentity.GetCurrent For 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

Answer: B
QUESTION 180
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.CurrentDomain objDomain.SetAppDomainPolicy( _ PolicyLevel.CreateAppDomainLevel()) B.Dim objDomain As AppDomain = AppDomain.CurrentDomain objDomain.SetPrincipalPolicy( _ PrincipalPolicy.WindowsPrincipal) C.Dim objDomain As AppDomain = AppDomain.CurrentDomain objDomain.SetPrincipalPolicy( _ PrincipalPolicy.UnauthenticatedPrincipal) D.Dim objDomain As AppDomain = AppDomain.CurrentDomain objDomain.SetThreadPrincipal(New WindowsPrincipal(Nothing))

Answer: C
QUESTION 181
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 SHA1CryptoServiceProvider Dim hash() As Byte = objSHA.ComputeHash(message)
B. Dim objSHA As New SHA1CryptoServiceProvider Dim hash() As Byte = Nothing objSHA.TransformBlock(message, 0, message.Length, hash, 0)
C. Dim objSHA As New SHA1CryptoServiceProvider Dim hash() As Byte = BitConverter.GetBytes(objSHA.GetHashCode)
D. Dim objSHA As New SHA1CryptoServiceProvider objSHA.GetHashCode() Dim hash() As Byte = objSHA.Hash

Answer: A
QUESTION 182
You are developing an application that uses role-based security. The
principal policy of the application domain is configured during startup
with the following code. AppDomain.CurrentDomain.SetPrincipalPolicy(
_ PrincipalPolicy.WindowsPrincipal) You need to restrict access to
one of the methods in your application so that only members of the
local Administrators group can call the method. Which attribute
should you place on the method?
A.
B.
C.
D.

Answer: B
QUESTION 183
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.
B.
C.
D.

Answer: B
QUESTION 184
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 = BitConverter.GetBytes(objAlgo.GetHashCode)
B.Dim objAlgo As HashAlgorithm objAlgo = HashAlgorithm.Create(message.ToString) Dim hash() As Byte = objAlgo.Hash
C.Dim objAlgo As HashAlgorithm = HashAlgorithm.Create("MD5") Dim hash() As Byte = objAlgo.ComputeHash(message) D.Dim objAlgo As HashAlgorithm = HashAlgorithm.Create("MD5") Dim hash() As Byte objAlgo.TransformBlock(message, 0, message.Length, hash, 0)

Answer: C
QUESTION 185
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. (Click the Exhibit button.) Which code segment should you choose?
A.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.CreateGraphics
B.DrawRectangle(objPen, 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.CreateGraphics D.DrawPolygon(objPen, points) E.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.CreateGraphics
F. DrawRectangle(objPen, objRect) G.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.CreateGraphics H.FillRectangle(objBrush, objRect)
Answer: D
QUESTION 186
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 SearchList

The string for which to search, which is named SearchValue
You need to write the code.
Which code segment should you use?
A. Dim objComparer As CompareInfo = _ New CultureInfo("it-IT").CompareInfo Return objComparer.Compare(SearchList, SearchValue)
B. Return SearchList.IndexOf(SearchValue)
C. Dim objComparer As CompareInfo = _ New CultureInfo("it-IT").CompareInfo If objComparer.IndexOf(SearchList, SearchValue) > 0 Then Return True Else Return False End If
D. Dim objComparer As CompareInfo = _ New CultureInfo("it-IT").CompareInfo If SearchList.IndexOf(SearchValue) > 0 Then Return True Else Return False End If

Answer: C
QUESTION 187
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").NumberFormat objCulture.NumberNegativePattern = 1 Return NumberToPrint.ToString("C", objCulture)
B. Dim objCulture As NumberFormatInfo = _ New CultureInfo("zh-HK").NumberFormat Return NumberToPrint.ToString("-{0}", objCulture)
C. Dim objCulture As NumberFormatInfo = _ New CultureInfo("zh-HK").NumberFormat

Return NumberToPrint.ToString("()", objCulture)
D. Dim objCulture As NumberFormatInfo = _ New CultureInfo("zh-HK").NumberFormat objCulture.CurrencyNegativePattern = 1 Return NumberToPrint.ToString("C", objCulture)

Answer: D
QUESTION 188
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.NeutralCultures) ... Next
B. For Each objCulture As CultureInfo In _ CultureInfo.GetCultures(CultureTypes.SpecificCultures) ... Next
C. Dim objCulture As New CultureInfo("") Dim objTypes As CultureTypes = objCulture.CultureTypes ...
D. For Each objCulture As CultureInfo In _ CultureInfo.GetCultures(CultureTypes.ReplacementCultures) ... Next

Answer: B
QUESTION 189
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. ListDictionary class
B. HybridDictionary class
C. Hashtable class
D. OrderedDictionary class
Answer: B
QUESTION 190
You are creating a class named Temperature. The Temperature class

contains a public field named F. The public field F represents a
temperature in degrees Fahrenheit. You need to ensure that users can
specify whether a string representation of a Temperature instance
displays the Fahrenheit value or the equivalent Celsius value. Which
code segment should you use?
A. Public Class Temperature Implements IFormattable Public F As Integer Public Function ToString ( ByVal format As String, _ ByVal fp As IFormatProvider ) As String _ Implements IFormattabl Return F.ToString () End If If format = "C" Then Return ((F -32) / 1.8). ToString () End If Throw New FormatException ("Invalid format string") End Function End Class
B. Public Class Temperature Implements ICustomFormatter Public F As Integer Public Function Format( ByVal formatString As String, _ ByVal arg as object, ByVal fp As IFormatProvider ) _ As String If formatString = "C" Then Return ((F -32) / 1.8). ToString () End If If formatString = "F" Then Return arg.ToString () End If Throw New FormatException ("Invalid format string") End Function End Class
C. Public Class Temperature Public F As Integer Public Function ToString ( ByVal format As String, _ ByVal fp As IFormat ToString () Else Return Me.GetType (). ToString () End If End Function End Class
D. Public Class Temperature Public F As Integer Protected format As String Public Overrides Function ToString () As String If format = "C" Then Return ((F -32) / 1.8). ToString () End If

Return F.ToString () End Function End Class

Answer: A
QUESTION 191
You need to create a method to clear a Queue named q. Which code segment should you use?
A. Dim e As Object For Each e In q
B. Dequeue () Next
C. Dim e As Object For Each e In q
D. Enqueue (Nothing) Next
E. q.Clear ()
F. q.Dequeue ()

Answer: C
QUESTION 192
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 implements the IDisposable interface. B.Define the class such that it inherits from the WeakReference class. C.Create a Dispose method that calls System.GC.Collect to force garbage collection. D.Create a Dispose method that releases unmanaged resources and calls methods on other objects to release
the managed resources. E.Create a class destructor that calls methods on other objects to release the managed resources. F.Create a class destructor that releases the unmanaged resources.

Answer: ADF
QUESTION 193
You need to write a multicast delegate that accepts a DateTime argument. Which code segment should you use?

A. Public Delegate Function PowerDeviceOn( _ ByVal autoPowerOff As DateTime) _ As Boolean
B. Public Delegate Sub PowerDeviceOn( _ ByVal autoPowerOff As DateTime)
C. Public Delegate Function PowerDeviceOn( _ ByVal result As Boolean, _ ByVal autoPowerOff As DateTime) _ As Integer
D. Public Delegate Function PowerDeviceOn( _ ByVal sender As Object, _ ByVal autoPowerOff As EventArgs) _ As Boolean

Answer: B
QUESTION 194
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.IntPtr
B. Int
C. System.UInt16
D. System.String
Answer: C
QUESTION 195
You are developing an application that stores data about your company's
sales and technical support teams.
You need to ensure that the name and contact information for each
person is available as a single collection when a user queries details about a specific team. You also need to ensure that the data collection

guarantees type safety.
Which code segment should you use?
A. Dim team As Hashtable = New Hashtable () team.Add (1, " Hance ") team.Add (2, "Jim") team.Add (3, " Hanif ") team.Add (4, " Kerim ") team.Add (5, "Alex") team.Add (6, "Mark") team.Add (7, "Roger") team.Add (8, "Tommy")
B. Dim team As ArrayList = New ArrayList () team.Add ("1, Hance ") team.Add ("2, Jim") team.Add ("3, Hanif ") team.Add ("4, Kerim ") team.Add ("5, Alex") team.Add ("6, Mark") team.Add ("7, Roger") team.Add ("8, Tommy")
C. Dim team As New Dictionary(Of Integer, String) team.Add (1, " Hance ") team.Add (2, "Jim") team.Add (3, " Hanif ") team.Add (4, " Kerim ") team.Add (5, "Alex") team.Add (6, "Mark") team.Add (7, "Roger") team.Add (8, "Tommy")
D. Dim team As String() = New String() { _ "1, Hance ", _ "2, Jim", _ "3, Hanif ", _ "4, Kerim ", _ "5, Alex", _ "6, Mark", _ "7, Roger", _ "8, Tommy"}

Answer: C
QUESTION 196
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 myStream As New MemoryStream() Dim o as Object For 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 buffer As Byte() = New Byte(dept.Capacity) {} Dim myStream As New MemoryStream(buffer) Dim o As Object For 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
QUESTION 197
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. Dim inStream As New MemoryStream(document) Dim zipStream As New GZipStream( _ inStream, CompressionMode.Compress) Dim result(document.Length) As Byte zipStream.Write(result, 0, result.Length) Return result
B. Dim outStream As New MemoryStream Dim zipStream As New GZipStream( _ outStream, CompressionMode.Compress)

zipStream.Write(document, 0, document.Length) zipStream.Close() Return outStream.ToArray
C. Dim objStream As New MemoryStream(document) Dim zipStream As New GZipStream( _ objStream, CompressionMode.Compress) zipStream.Write(document, 0, document.Length) zipStream.Close() Return objStream.ToArray
D. Dim objStream As New MemoryStream(document) Dim zipStream As New GZipStream( _ objStream, CompressionMode.Compress) Dim outStream As New MemoryStream Dim b As Integer While (b = zipStream.ReadByte) outStream.WriteByte(CByte(b)) End While Return outStream.ToArray

Answer: B
QUESTION 198
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 title As String
Public roomNumber As Integer
Public invitees As String()
Public Sub New()
End Sub
Public Sub New(ByVal t As String)
title = t
End Sub End Class

The component contains a procedure with the following code segment.
Dim myMeeting As New Meeting("Goals")
myMeeting.roomNumber = 1100
Dim attendees As String() = New String(1) {"John", "Mary"}
myMeeting.invitees = attendees
Dim xs As New XmlSerializer(GetType(Meeting))
Dim writer As 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. 1100 John Mary
B. Goals 1100 John Mary
C. 1100

John Mary

D. 1100 John Mary

Answer: A
QUESTION 199
You are defining a class named MyClass that contains several child objects. MyClass contains a method named ProcessChildren that performs actions on the child objects. MyClass objects will be serializable. You need to ensure that the ProcessChildren method is executed after the MyClass 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. Specify that MyClass implements the IDeserializationCallback interface.
B. Apply the OnDeserializing attribute to the ProcessChildren method.
C. Create an OnDeserialization method that calls ProcessChildren.
D. Specify that MyClass inherits from the ObjectManager class.
E. Create a GetObjectData method that calls ProcessChildren.
F. Apply the OnSerialized attribute to the ProcessChildren method.

Answer: AC
QUESTION 200
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 bufStream As New BufferedStream(netStream, 8192) bufStream.Write(dataToSend, 0, dataToSend.Length)
C.Dim memStream As New MemoryStream(8192) netStream.Write(dataToSend, 0, _ CType(memStream.Length, Integer))
D.Dim bufStream As New BufferedStream(netStream) bufStream.Write(dataToSend, 0, 8192)

Answer: B
QUESTION 201
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.ToString()) reader.Close()
B.Dim reader As New StringReader(message) While reader.Peek() <> -1 ProcessMessage(reader.ReadLine()) End While reader.Close()
C.Dim reader As New StringReader(message) While reader.Peek() <> -1 Dim line as String = reader.Read().ToString() ProcessMessage(line) End While reader.Close()
D.Dim reader As New StringReader(message) ProcessMessage(reader.ReadToEnd()) reader.Close()

Answer: B
QUESTION 202
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. Dim objStore As IsolatedStorageFile objStore = IsolatedStorageFile.GetUserStoreForAssembly objStore.CreateDirectory("Preferences")
B. Dim objStore As IsolatedStorageFile objStore = IsolatedStorageFile.GetUserStoreForApplication objStore.CreateDirectory("Preferences")
C. Dim objStore As IsolatedStorageFile objStore = IsolatedStorageFile.GetMachineStoreForAssembly objStore.CreateDirectory("Preferences")
D. Dim objStore As IsolatedStorageFile objStore = IsolatedStorageFile.GetUserStoreForDomain objStore.CreateDirectory("Preferences")

Answer: A
QUESTION 203
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 Class Group
02 Public Employees As Employee()
03 End Class 05 Public Class Employee
06 Public Name As String
07 End Class 09 Public Class Manager
10 Inherits Employee
11 Public Level As Integer
12 End Class
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 1 and 2 of the code segment: _ _
B. Insert the following code between lines 1 and 2 of the code segment: _
C. Insert the following code between lines 5 and 6 of the code segment: and Insert the following code between lines 10 and 11 of the code segment:
D. Insert the following code between lines 1 and 2 of the code segment: _

Answer: A
QUESTION 204
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 strDate As String = _ DateTime.Today.Month.ToString("es-MX")
B.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)
C.Dim objCalendar As Calendar = _ New CultureInfo("es-MX", False).Calendar Dim DT As New DateTime( _ DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day) Dim strDate As String = DT.ToString
D.Dim strDate As String = _ DateTimeFormatInfo.CurrentInfo.GetMonthName( _ DateTime.Today.Month)
Answer: B QUESTION 205

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. Dim al As New ArrayList() Dim procs As Process() = Process.GetProcesses(strComputer) Dim proc As Proces For Each proc In procs al.Add(proc) Next
B. Dim al As New ArrayList() Dim procs As Process() = _ Process.GetProcessesByName(strComputer) Dim proc As Process For Each proc In procs al.Add(proc.ProcessName) Next
C. Dim al As New ArrayList() Dim procs As Process() = Process.GetProcesses(strComputer) Dim proc As Process For Each proc In procs al.Add(proc.ProcessName) Next
D. Dim al As New ArrayList() Dim procs As Process() = _ Process.GetProcessesByName(strComputer) Dim proc As Process For Each proc In procs al.Add(proc) Next
Answer: C
QUESTION 206
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.Dim objStream As IsolatedStorageFileStream objStream = New IsolatedStorageFileStream( _ "Settings.dat", FileMode.Open) Dim result As String = New StreamReader(objStream).ReadToEnd
B.Dim objFile As IsolatedStorageFile objFile = IsolatedStorageFile.GetMachineStoreForAssembly Dim objStream As IsolatedStorageFileStream objStream = New IsolatedStorageFileStream( _ "Settings.dat", FileMode.Open, objFile) Dim result As String = objStream.ToString
C.Dim objFile As IsolatedStorageFile objFile = IsolatedStorageFile.GetMachineStoreForAssembly Dim objStream As IsolatedStorageFileStream objStream = New IsolatedStorageFileStream( _ "Settings.dat", FileMode.Open, objFile) Dim result As String = New StreamReader(objStream).ReadToEnd
D.Dim objStream As IsolatedStorageFileStream objStream = New IsolatedStorageFileStream( _ "Settings.dat", FileMode.Open) Dim result As String objStream.toString

Answer: C
QUESTION 207
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 FileSecurity = _ File.GetAccessControl("MyData.xml") objSecurity.SetAccessRuleProtection(True, True)
C. Dim objSecurity As New FileSecurity() objSecurity.SetAccessRuleProtection(True, True) File.SetAccessControl("MyData.xml", objSecurity)
D. Dim objSecurity As FileSecurity = _ File.GetAccessControl("MyData.xml") objSecurity.SetAuditRuleProtection(True, True) File.SetAccessControl("myData.xml", objSecurity)


Answer: A
QUESTION 208
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 Assembly1.dll into the current application domain. Which code segment should you use?
A. Dim domain As AppDomain = AppDomain.CurrentDomain Dim asm As [Assembly] = domain.GetData("Assembly1.dll")
B. Dim domain As AppDomain = AppDomain.CurrentDomain Dim myPath As String = _ Path.Combine(domain.BaseDirectory, "Assembly1.dll") Dim asm As [Assembly] = [Assembly].Load(myPath)
C. Dim domain As AppDomain = AppDomain.CurrentDomain Dim myPath As String = _ Path.Combine(domain.BaseDirectory, "Assembly1.dll") Dim asm As [Assembly] = [Assembly].LoadFrom(myPath)
D. Dim domain As AppDomain = AppDomain.CurrentDomain Dim myPath As String = _ Path.Combine(domain.DynamicDirectory, "Assembly1.dll") Dim asm As [Assembly] = _ AppDomain.CurrentDomain.Load(myPath)

Answer: C
QUESTION 209
You are developing a method to encrypt sensitive data with the Data Encryption Standard (DES) algorithm. Your method accepts the following parameters:
The byte array to be encrypted, which is named message
An encryption key, which is named key
An initialization vector, which is named iv
You need to encrypt the data. You also need to write the encrypted data to a MemoryStream object.
Which code segment should you use?
A.Dim objDES As New DESCryptoServiceProvider objDES.BlockSize = message.Length

Dim objCrypto As ICryptoTransform = objDES.CreateDecryptor(key, iv) Dim cipherStream As New MemoryStream Dim cryptoStream As New CryptoStream(cipherStream, objCrypto, CryptoStreamMode.Write)
B.Dim objDES As New DESCryptoServiceProvider Dim objCrypto As ICryptoTransform = objDES.CreateDecryptor(key, iv) Dim cipherStream As New MemoryStream Dim cryptoStream As New CryptoStream(cipherStream, objCrypto, CryptoStreamMode.Write) cryptoStream.Write(message, 0, message.Length)
C.Dim objDES As New DESCryptoServiceProvider Dim objCrypto As ICryptoTransform = objDES.CreateEncryptor(key, iv) Dim cipherStream As New MemoryStream Dim cryptoStream As New CryptoStream(cipherStream, objCrypto, CryptoStreamMode.Write) cryptoStream.Write(message, 0, message.Length)
D.Dim objDES As New DESCryptoServiceProvider Dim objCrypto As ICryptoTransform = objDES.CreateDecryptor() Dim cipherStream As New MemoryStream Dim cryptoStream As New CryptoStream(cipherStream, objCrypto, CryptoStreamMode.Write)cryptoStream.Write(message, 0, message.Length)

Answer: C
QUESTION 210
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 Queue()
B. Dim undoBuffer As New Stack()
C. Dim undoBuffer As New Queue(Of String)
D. Dim undoBuffer As New Stack(Of String)
Answer: D
QUESTION 211
You need to write a code segment that performs the following tasks:
Retrieve the name of each paused service.
Passe 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") For Each svc As ManagementObject In searcher.Get() If svc("State").ToString() = "'Paused'" Then Collection1.Add(svc("DisplayName")) End If Next
C.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 If Next
D.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

Answer: A
QUESTION 212
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.contoso.com.
To test the application, you use a source address, [email protected], and a target address, [email protected].
You need to transmit the e-mail message.
Which code segment should you use?

A.Dim MailFrom As New MailAddress("[email protected]", "Me") Dim MailTo As New MailAddress("[email protected]", "You") Dim Message As New MailMessage(MailFrom, MailTo) Message.Subject = "Greetings" Message.Body = "Test" Dim objClient As New SmtpClient("smtp.contoso.com") objClient.Send(Message)
B.Dim MailFrom As New MailAddress("[email protected]", "Me") Dim MailTo As New MailAddress("[email protected]", "You") Dim Message As New MailMessage(MailFrom, MailTo) Message.Subject = "Greetings" Message.Body = "Test" Message.Dispose()
C.Dim SMTPClient As String = "smtp.contoso.com" Dim MailFrom As String = "[email protected]" Dim MailTo As String = "[email protected]" Dim Subject As String = "Greetings" Dim Body As String = "Test" Dim Message As New MailMessage(MailFrom, MailTo, Subject, SMTPClient)
D.Dim MailFrom As New MailAddress("[email protected]", "Me") Dim MailTo As New MailAddress("[email protected]", "You") Dim Message As New MailMessage(MailFrom, MailTo) Message.Subject = "Greetings" Message.Body = "Test" Dim Info As New SocketInformation Dim Client As New Socket(Info) Dim Enc As New ASCIIEncoding Dim Bytes() As Byte = Enc.GetBytes(Message.ToString) Client.Send(Bytes)

Answer: A
QUESTION 213
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. Dim objCulture As New CultureInfo("CA") ...
B. For Each objCulture As CultureInfo In _ CultureInfo.GetCultures(CultureTypes.SpecificCultures) ... Next
C. Dim objRegion As New RegionInfo("CA") ...
D. Dim objRegion As New RegionInfo("") If objRegion.Name = "CA" Then

... End If

Answer: C
QUESTION 214
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 = string.Empty Dim reader As New StreamReader("Message.txt") While Not reader.EndOfStream result &= reader.ToString() End While
B.Dim result As String = Nothing Dim reader As New StreamReader("Message.txt") result = reader.Read().ToString()
C.Dim result As String = Nothing Dim reader as New StreamReader("Message.txt") result = reader.ReadToEnd()
D.Dim result as String = Nothing Dim reader As New StreamReader("Message.txt") result = reader.ReadLine()

Answer: C
QUESTION 215
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 Implements IComparable Public Value As Integer Public Function CompareTo(ByVal obj As Object) As Integer _ Implements IComparable.CompareTo Try Return Value.CompareTo((CType(obj, Age)).Value) Catch Return -1 End Try End Function End Class

B.Public Class Age
Public Value As Integer
Public Function CompareTo(ByVal iValue As Integer) As Object Try
Return Value.CompareTo(iValue)
Catch
Throw New ArgumentException ("object not an Age")
End Try
End Function
End Class
C.Public Class Age
Implements IComparable
Public Value As Integer
Public Function CompareTo(ByVal obj As Object) As Integer _ Implements IComparable.CompareTo
If TypeOf obj Is Age Then
Dim _age As Age = CType(obj, Age)
Return Value.CompareTo(_age.Value)
End If
Throw New ArgumentException("object not an Age")
End Function
End Class
D.Public Class Age
Public Value As Integer
Public Function CompareTo(ByVal obj As Object) As Object If TypeOf obj Is Age Then
Dim _age As Age = CType(obj, Age)
Return Value.CompareTo(obj)
End If
Throw New ArgumentException("object not an Age")
End Function
End Class

Answer: C
QUESTION 216
You are developing a server application that will transmit sensitive information on a network. You create an X509Certificate object named certificate and a TcpClient object named client. You need to create an SslStream to communicate by using the Transport Layer Security 1.0 protocol. Which code segment should you use?
A. Dim objSSL As New SslStream(client.GetStream) objSSL.AuthenticateAsServer(certificate, False, _ SslProtocols.Tls, True)
B. Dim objSSL As New SslStream(client.GetStream)

objSSL.AuthenticateAsServer(certificate, False, _ SslProtocols.None, True)
C. Dim objSSL As New SslStream(client.GetStream) objSSL.AuthenticateAsServer(certificate, False, _ SslProtocols.Ssl3, True)
D. Dim objSSL As New SslStream(client.GetStream) objSSL.AuthenticateAsServer(certificate, False, _ SslProtocols.Ssl2, True)

Answer: A
QUESTION 217
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. _ Public Function MessageBox(ByVal hWnd As Int32, _ ByVal text As String, _ ByVal caption As String, _ ByVal t As UInt32) As Boolean End Function
B.DllImport("user32", EntryPoint:="MessageBoxA", _ CharSet:=CharSet.Unicode)> _ Public Function MessageBox(ByVal hWnd As Int32, _ ByVal text As String, _ ByVal caption As String, _ ByVal t As UInt32) As Boolean End Function
C. _ Public Function MessageBox(ByVal hWnd As Int32, _ ByVal text As String, ByVal caption As String, _ ByVal t As UInt32) As Boolean End Function D. _

Public Function MessageBox(ByVal hWnd As Int32, _ ByVal text As String, ByVal caption As String, _ ByVal t As UInt32) As Boolean End Function

Answer: C
QUESTION 218
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 ms As New MemoryStream() While ms.CanRead formatter.Serialize(ms, data) End While
D. Dim formatter As New BinaryFormatter() Dim buffer As New Byte(data.Count) {} Dim ms As New MemoryStream(buffer, True) formatter.Serialize(ms, data)

Answer: A
QUESTION 219
You are developing a method to decrypt data that was encrypted with the Triple DES Algorithm. The method accepts the following parameters:
The byte array to be decrypted, which is named cipherMessage
The key, which is named key
An initialization vector, which is named iv You need to decrypt the message by using the TripleDES class and place the result in a string.

Which code segment should you use?
A. Dim objDES As New TripleDESCryptoServiceProvider Dim objCrypto As ICryptoTransform = _ objDES.CreateDecryptor() Dim cipherStream As New MemoryStream(cipherMessage) Dim cryptoStream As New CryptoStream( _ cipherStream, objCrypto, CryptoStreamMode.Read) Dim message As String message = New StreamReader(cryptoStream).ReadToEnd
B. Dim objDES As New TripleDESCryptoServiceProvider objDES.FeedbackSize = cipherMessage.Length Dim objCrypto As ICryptoTransform = _ objDES.CreateDecryptor(key, iv) Dim cipherStream As New MemoryStream(cipherMessage) Dim cryptoStream As New CryptoStream( _ cipherStream, objCrypto, CryptoStreamMode.Read) Dim message As String message = New StreamReader(cryptoStream).ReadToEnd
C. Dim objDES As New TripleDESCryptoServiceProvider Dim objCrypto As ICryptoTransform = _ objDES.CreateDecryptor(key, iv) Dim cipherStream As New MemoryStream(cipherMessage) Dim cryptoStream As New CryptoStream( _ cipherStream, objCrypto, CryptoStreamMode.Read) Dim message As String message = New StreamReader(cryptoStream).ReadToEnd
D. Dim objDES As New TripleDESCryptoServiceProvider objDES.BlockSize = cipherMessage.Length Dim objCrypto As ICryptoTransform = _ objDES.CreateDecryptor(key, iv) Dim cipherStream As New MemoryStream(cipherMessage) Dim cryptoStream As New CryptoStream( _ cipherStream, objCrypto, CryptoStreamMode.Read) Dim message As String message = New StreamReader(cryptoStream).ReadToEnd
Answer: C QUESTION 220

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.

Hardware
Amy

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 = reader.GetAttribute("name") dept.manager = reader.GetAttribute("manager") End Sub End Class
B.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
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").InnerTex
Return dept
End Function
End Class
D.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
Answer: C
QUESTION 221
You are creating a new security policy for an application domain. You write the following lines of code.
Dim objPolicy As PolicyLevel = PolicyLevel.CreateAppDomainLevel
Dim 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 objGroup As CodeGroup = New UnionCodeGroup( _ New ZoneMembershipCondition(SecurityZone.Trusted), _ fullTrustStatement)
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 FirstMatchCodeGroup( _ New ZoneMembershipCondition(SecurityZone.Trusted), _ fullTrustStatement)
D.Dim objGroup1 As CodeGroup = New FirstMatchCodeGroup( _ New ZoneMembershipCondition(SecurityZone.Trusted), _ fullTrustStatement) Dim objGroup2 As CodeGroup = New UnionCodeGroup( _ New AllMembershipCondition, noTrustStatement)

Answer: B
QUESTION 222
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 ... End Class Dim t As New Dictionary(Of String, String) Dim dict As MyDictionary = CType(t, MyDictionary)
B. Class MyDictionary Implements IDictionary
C. Class MyDictionary Inherits HashTable
D. Class MyDictionary Implements Dictionary(Of String, String)
Answer: D QUESTION 223

You write the following class. Public Class HomePage Public CurrentHeadlines As StringBuilder Private WelcomeMessage As String Dim Stocktickers As Array Dim PriorityList As Dictionary(Of Int32, String) End Class You need to generate a type library for this class. The type library will be used by unmanaged code. Which member should you update?
A. Dim PriorityList As Dictionary(Of Int32, String)
B. Public CurrentHeadlines As StringBuilder
C. Private WelcomeMessage As String
D. Dim Stocktickers As Array

Answer: A
QUESTION 224
DRAG DROP
You need to add a string named strConn to the connection stnng section of an application configuration file.
How should you complete the code segment?
To answer, drag the appropriate code segment or segments to the correct location or locations in the answer area.



QUESTION 225
You are developing a routine that will periodically perform a calculation based on regularly changing values from legacy systems. You write the following lines of code. (Line numbers are
included for reference only.)
01 Dim exitLoop As Boolean = False
02 Do 04 exitLoop = PerformCalculation()
05 Loop While Not exitLoop
You need to write a code segment to ensure that the calculation is performed at 30-second intervals.
You must ensure that minimum processor resources are used between the calculations. Which code segment should you insert at line 03?
A. Thread.Sleep(30000);
B. Thread.SpinWait(30);
C. Thread.SpinWait(30000);
D. Dim thrdCurrent As Thread = Thread.CurrentThread; thrdCurrent.Priority = ThreadPriority.Lowest;
E. Dim thrdCurrent As Thread = Thread.CurrentThread; thrdCurrent.Priority = ThreadPriority.BelowNormal;
Answer: A QUESTION 226

DRAG DROP You are writing a method that returns an Array List.
You need to ensure that changes to the ArrayList are performed in a thread-safe manner. Which actions should you perform in sequence?
To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.

Answer:

QUESTION 227
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. stream1->Write(byteArray, 0, 80); bytesTransferred = byteArray->Length;
C. while (bytesTransferred < 80) { stream1->Seek(1, SeekOrigin::Current); byteArray[bytesTransferred++] = Convert::ToByte(stream1->ReadByte()); }
D. for(inti=0;i<80;i++){ stream1->WriteByte(byteArray[i]); bytesTransferred = i; if (!stream1->CanWrite) { break; } }

Answer: A
QUESTION 228
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. Dim answers As New BitArray (1)
B. Dim answers As New BitVector32(-1)
C. Dim answers As New BitArray (-1)
D. Dim answers As New BicVector32(1)

Answer: B
QUESTION 229
You deploy several ,NET-connected applications to a shared folder on your company network. Your applications require full trust to execute correctly. Users report that they receive security exceptions when they attempt to run the applications on their computers.

You need to ensure that the applications on the users' computers run with full trust.
What should you do?
A.Grant the full trust permission set to the Trusted Zone code group by using the Code Access Security Policy tool (Caspol.exe).
B.Use the security settings of Internet Explorer to add the shared folder to the list of trusted sites.
C.Apply a strong name to the applications by using the Strong Name tool (Sn.exe).
D.Use the Code Access Security Policy tool (Caspol.exe) to add a new code group that has the full trust permission set. The new code group must also contain a URL membership condition that specifies the URL of the shared folder where your applications reside.

Answer: D
QUESTION 230
You are creating an assembly that interacts with the file system.
You need to configure a permission request so that the common language runtime (CLR) will stop loading the assembly if the necessary file permissions are absent.
Which attribute should you place in your code?
A.
B.
C.
D.
Answer: C QUESTION 231

You are developing an application that runs by using the credentials of the end user. Only users who are members of the Administrator group get permission to run the application. You write the following security code to protect sensitive data within the application.
Dim blnAdmin As Boolean = False
Dim objRole As WindowsBuiltlnRole =
WindowsBuiltInRole.Administrator
If blnAdmin = False Then
Throw New Exception("User not permitted")
End If
You need to add a code segment to this security code to ensure that the application throws an exception if a user is not a member of the Administrator group.
Which code segment should you use?
A.Dim objUser As UindowsPrincipal = DirectCast(Thread.CurrentPrincipal, WindowsPrincipal) blnAdmin = objUser.IsInRole(objRole) B.Dim objUser As GenericPrincipal = DirectCast(Thread.CurrentPrincipal, GenericPrincipal) blnAdmin = objUser.IsInRole(objRole.ToString)
C.Dim objUSer As Windowsldentity = DirectCast(Thread.CurrentPrincipal.Identity, Windowsldentity) blnAdmin = objUSer.Name.EndsUith("Administrator")
D.Dim objUser As WindowsIdentity = WindowsIdentity.GetCurrent For Each objGroup As IdentityReference In objUser.Groups Dim objAccount As NTAccount = DirectCast(objGroup.Translate( Type.GetType("NTAccount")),NTAccount) blnAdmin = objGroup.Value.Equals(objRole) Next
Answer: A
QUESTION 232
DRAG DROP You create a class library that is used by applications in three different departments of the 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 segment:

Hardware
Amy

You need to create a Department object instance by using the field values retrieved from the application
configuration file. How should you complete the code segment? To answer, drag the appropriate code segment or segments to the correct location or locations in the answer
area.


Answer:

QUESTION 233
DRAG DROP
You are testing a newly developed method named PersistToDB. The method accepts a parameter of type EventLogEntry and does not return a value.
The current test function is shown in the following code segment:
01 Public Sub TestPersistToDB() 03 For Each entry As EventLogEntry In myLog.Entries 05 If entry.Source = "MySource" Then 07 End If 09 Next
11 End Sub
The test function must read entries from the application log of local computers and then pass the entries to the PersistToDB() method. The test function implementation must pass only events of type Error or Warning from a source named MySource to the PersistToDB() method.
You need to complete the code segment.
Which code segments should you add to line 02 and between lines 05 and 07 in sequence?
To answer, move the appropriate actions from the list of actions to the answer area and arrange them in the correct order.


Answer:

QUESTION 234
DRAG DROP You need to add a string named strConn to the connection string section of the application configuration file. Which code segments should you use in sequence? To answer, move the appropriate code segments from the list of code segments to the answer area and
arrange them in the correct order.


Answer:

QUESTION 235
You write the following class that has three methods. Public Class SimpleEmployee Private ni_EmployeeId As String

Private m_EroployeeName As String Private m_JobTitleName As String Public Function GetID() As String Return m_EmpioyeeID End Function Public Function GetName() As String Return tti_EmployeeNatne End Function Public Function GetTitle() As String Return ra_JobTitleNarne End Function End Class You need to expose the class to COM in a type library. The COM interface must not expose the method
GetEmployeeld. The GetEmployeeld method must still be available to managed code. You need to hide the GetEmployeelD method from the COM interface. What should you do? You need to expose the class to COM in a type library. The COM interface must not expose the method
GetEmployeeld. The GetEmployeeld method must still be available to managed code. You need to hide the GetEmployeelD method from the COM interface. What should you do?
A. Apply the ComVisible attribute to the class and methods in the following manner. [_ Public Class SimpleEmployee Private m_EmployeeId As String Private m_EmployeeName As String

Private m_JobTitleNanne As String Public Function GetID() As String Return m_EroployeeId End Function Public Function GetName() As String Return ro_EroployeeName End Function Public Function GetTitle() As String Return m_JobTitleWame End Function End Class
B. Change the access modifier for the GetEmployeeld method in the following manner. _ Public Class SimpleEmployee Private m_EmployeeId As String Private m_EmployeeName As String Private m_JobTitleName As String Protected Function GetID() As String Return m_EmployeeID End Function Public Function GetName() As String Return m_EmployeeName End Function Public Function GetTitle() As String Return m_JobTitleName End Function End Class
C. Apply the ComVisible attribute to the class and methods in the following manner. Public Class SimpleEmployee Private m_EmployeeId As String Private ro_EmployeeNaine As String Private m_JobTitleName As String Public Function GetID() As String Return m_EroployeeId End Function Public Function GetName() As String Public Function GetName() As String Return m_EttiployeeName End Function Public Function GetTitle() As String Return m_JobTitleWame End Function

End Class
D. Apply the CornVisible attribute to the GetEmployeeld method in the following manner. Public Class SimpleEmployee Private m_EmployeeId As String Private m_EmployeeName As String Private m_JobTitleName As String _ Public Function GetID() As String Return m EmployeelD End Function Public Function GetName() As String Return m_EmployeeNaitie End Function Public Function GetTitlef) As String Return iti_JobTitleNanie End Function End Class

Answer: B
QUESTION 236
DRAG DROP
You are creating an application that retrieves values from a custom section of the application configuration file. The custom section uses XML, as shown in the following code segment:
QUESTION 237 DRAG DROP
You need to create a common language runtime (CLR) unit of isolation within an application.
Which code segments should you use in sequence?
To answer, move the appropriate code segments from the list of code segments to the answer area and arrange them in the correct order.


Answer:

QUESTION 238
You create a service application that monitors free space on a hard disk drive.
You need to ensure that the service application runs in the background and monitors the free space every minute. What should you do? (Each correct answer presents part of the solution. Choose three.)

A. Add an instance of the System.Timers.Timer class to the Service class and configure it to fire every minute.
B. Add code to the OnStart() method of the Service class to monitor the free space on the hard disk drive.
C. Add code to the OnStart() method of the Service class to start the timer.
D. Add code to the Tick event handler of the timer to monitor the free space on the hard disk drive.
E. Add an instance of the System.Windows.Forms.Timer class to the Service class and configure it to fire every minute
F. Add code to the default constructor of the Service class to monitor the free space on the hard disk drive.
G. Add code to the Elapsed event handler of the timer to monitor the free space on the hard disk drive.

Answer: EFG
QUESTION 239
You need to log an entry in a custom event log when the EmailSenderService service is started and stopped. What should you do? (Each correct answer presents part of the solution. Choose three.)
A. Add the following code segment to line PO22 of the Poller.vb file: EventLog.WriteEntry("EmailSenderService", "Stopped", EventLogEntryType.Information)
B. Add the following code segment to line PO12 of the Poller.vb file: EventLog.WriteEntry("EmailSenderService", "Started", EventLogEntryType.Information)
C. Add the following code segment to line PO22 of the Poller.vb file: EventLog.WriteEntry("Application", "EmailSenderService:Stopped", EventLogEntryType.Information)
D. Add the following code segment to line ES10 of the EmailSenderService.vb file: EventLog.CreateEventSource("Application", "EmailSenderService")
E. Add the following code segment to line PO12 of the Poller.vb file: EventLog.WriteEntry("Application", "EmailSenderService:Started", EventLogEntryType.Information)
F. Add the following code segment to line ES10 of the EmailSenderService.vb file: EventLog.CreateEventSource("EmailSenderService", "EmailLog")

Answer: ABF
QUESTION 240
You need to ensure that dates and numbers are displayed correctly for each user based on location. Which code segment should you add to line GL08 of the Global.asax file?
A.Dim info As CultureInfo = CType(System.Threading.Thread.CurrentThread.CurrentCulture.Clone(), CultureInfo) info = CultureInfo.CreateSpecificCulture(culture)
B.Dim cultureInfo As System.Globalization.CultureInfo = cultureInfo.GetCultureInfo(culture) System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo C.Dim cultureInfo As System.Globalization.CultureInfo = cultureInfo.CreateSpecificCulture (culture) System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo

D.Dim cultureInfo As System.Globalization.CultureInfo = New System.Globalization.CultureInfo(culture)
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo

Answer: D
QUESTION 241
You need to retrieve all queued e-mail messages into a collection and ensure type safety. Which code segment should you use to define the signature of the GetQueuedEmailsFromDb() method in the Poller.vb file?
A. Private Shared Function GetQueuedEmailsFromDb(ByVal queueID As Integer) As EmailMessages
B. Private Shared Function GetQueuedEmailsFromDb(ByVal queueID As Integer) As Object()
C. Private Shared Function GetQueuedEmailsFromDb(ByVal queueID As Integer) As IList(Of Object)
D. Private Shared Function GetQueuedEmailsFromDb(ByVal queueID As Integer) As ArrayList

Answer: A
QUESTION 242
You need to ensure that the list of queued e-mail messages is sorted by priority value from highest to lowest. Which code segment should you add to line LE15 of the Local Entities?
A. Return Priority.GetValueOrDefault(-1).CompareTo(other.Priority.GetValueOrDefault(-1)) * -1
B. Return Priority.GetValueOrDefault(-1).CompareTo(other.Priority.GetValueOrDefault(-1))
C. Return Priority.Value.CompareTo(other.Priority.Value)
D. Return Priority.Value.CompareTo(other.Priority.Value) * -1
Answer: A
QUESTION 243
DRAG DROP
You need to complete the btnService_Click event in the ControlService.aspx.vb file. What should you do? To answer, drag the appropriate code segment or segments to the correct location or locations in the work area.


Answer:

QUESTION 244
You need to read the content of the XML log file. Which code segment should you add to line LO04 of the Login.aspx.vb file?
A. Dim fi As FileInfo = New FileInfo(filePath) fi.Refresh() Dim xml As String = fi.ToString()
B. Dim fi As FileInfo = New FileInfo(filePath) Dim xml As String = fi.ToString()

fi.Refresh()
C. Dim sr As StreamReader = File.OpenText(filePath) sr.Close() Dim xml As String = sr.ReadToEnd()
D. Dim sr As StreamReader = File.OpenText(filePath) Dim xml As String = sr.ReadToEnd() sr.Close()

Answer: D
QUESTION 245
You need to store Product, MainProduct, and SecondaryProduct instances that end users place in the shopping cart by using a collection. Which code segment should you use to initiate the collection?
A. Dim products As List(Of Product) = New List(Of Product)()
B. Dim products As IList(Of Product) = New List(Of Product)()
C. Dim products As ArrayList = New ArrayList()
D. Dim products As SortedList(Of String, Product) = New SortedList(Of String, Product)()

Answer: C
QUESTION 246
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.Use the installutil.exe command-line tool to install the service. C.Prior to installation, set the Account, Username, and Password properties of the ServiceProcessInstaller
class. D.Use the CONFIG option of the net.exe command-line tool to install the service.
Answer: C
QUESTION 247
You need to implement the For loop of the Start() method contained in the Poller.vb file.
Which code segments should you insert at line PO10 of the Poller.vb file? (Each correct answer presents part of the solution. Choose three.)

A. thread.Start(i)
B. thread.Start()
C. running.Add(1, False)
D. SenderThread(i)
E. Dim thread As Thread = New ThreadfNew ParameterizedThreadStart(AddressOf SenderThread))
F. running.Add(i, True)
G. Dim t As Thread = New Thread(Start)

Answer: BEF
QUESTION 248
After an order is processed, the ProcessingComplete event is raised.
The ProcessingComplete event must make information available to delegates about the order and the order processor.
You need to ensure that when the ProcessingComplete event is raised, an instance of the ProcessComplete class is provided to event subscribers.
Which base class should you use for the ProcessComplete class?
A. IEnumerable(Of Order)
B. CollectionBase
C. EventArgs
D. Attribute

Answer: C
QUESTION 249
You need to ensure that, for each exception, the central logging system logs the name of the method that caused the exception.
Which code segment should you insert at line AS12 in the ApplicationServices.vb file?
A. Dim source As String = ex.StackTrace(0).ToString()
B. Dim source As String = ex.TargetSite.MethodHandle.Value.ToString()
C. Dim source As String = ex.Data("ExceptionSource").ToString()
D. Dim source As String = ex.TargetSite.Name
Answer: A QUESTION 250

The order-processing service must save submitted orders in a format that persists all properties on the Order object.
You need to serialize Order objects.
Which code segment should you insert at line OR22 in the OrderRepository.vb file?
A.Dim formatter As IFormatter = New BinaryFormatter() Dim storeStream As HemoryStream = New HemoryStream() formatter.Serialize(storeStream, order)
B.Dim serializer as XmlSerializer= new XrolSerializer( GetType (Order), Assembly.GetExecutingAssembly().GetTypes()) Dim storeStream As HemoryStream = New HemoryStream() serializer.Serialize(storeStream, order)
C.Dim serializer as XmlSerializer= new XmlSerializer( GetType (Order)) Dim storeStream As HemoryStream = New HemoryStream() serializer.Serialize(storeStream, order)
D.Dim formatter As IFormatter = New BinaryFormatter(New SurrogateSelector(), New StreamingContext(StreamingContextStates.Persistence)) Dim storeStream As HemoryStream = New MemoryStream() formatter.Serialize(storeStream, order)

Answer: B
QUESTION 251
You need to use the performance counters to ensure that the performance metrics are updated as required.
Which code segment should you use as the body of the LogOrderFinished function in the ApplicationServices.vb file? (Each correct answer presents a complete solution. Choose two.)
A.totalCounter. Increment () averageCounter.IncrementBy(DateTime.Now.Ticks -order.OrderDate.Ticks) averageCounterBase.Increment()
B.totalCounter.IncrementBy(totalCounter-RawValue) averageCounter.Increment() averageCounterBase.IncrementBy(TimeSpan.TicksPerSecond)
C.totalCounter.RawValue += 1 averageCounter.Increment() averageCounterBase . IncrementBy (order .Order Date. Ticks -DateTime. Now. Ticks)
D.totalCounter. RawValue += 1 averageCounter.IncrementBy(DateTime.Now.ToBinary() -order.OrderDate.ToBinary()) averageCounterBase.Increment()
E.totalCounter. Increment ()

averageCounter.Increment() averageCounterBase.IncrementBy(DateTime.Now.Ticks)
F.totalCounter.IncrementBy(totalCounter.RawValue) averageCounter.IncrementBy(TimeSpan.TicksPerSecond) averageCounterBase.Increment()

Answer: CE
QUESTION 252
Your application uses two threads, named threadOne and threadTwo. You need to modify the code to prevent the execution of threadOne until threadTwo completes execution. What should you do?
A. Call the Sleep method of threadOne.
B. Use a WaitCallback delegate to synchronize the threads.
C. Configure threadTwo to run at a higher priority.
D. Call the SpinLock method of threadOne.
E. Configure threadOne to run at a lower priority.

Answer: B
QUESTION 253
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", "."); for each (EventLogEntry= entry in myLog->Entries) { if (entry->Source == "MySource") { if (entry->EntryType == EventLogEntryType::Error || entry->EntryType == EventLogEntryType::Warning) { PersistToDB(entry); } }

}
C. EventLog= myLog = gcnew EventLog("Application", "."); myLog->Source = "MySource"; for each (EventLogEntry= entry in myLog->Entries) { if (entry->EntryType == (EventLogEntryType::Error & 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: B
QUESTION 254
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 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 Property End Class
B. 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 Property End Class
C. 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
D. Public Class PrintingArgs Inherits EventArgs Private copies As Integer End Class

Answer: A
QUESTION 255
You write a class named Employee that includes the following code segment.
public class Employee {
string employeeId, employeeName, jobTitleName;
public string GetName() { return employeeName; }
public string GetTitle() { 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. Define an interface for the class and add the following attribute to the class definition. [ClassInterface(ClassInterfaceType.None)] public class Employee : IEmployee {

B. Add the following attribute to the class definition.
[ComVisible(true)]
public class Employee {
C. Add the following attribute to the class definition. [ClassInterface(ClassInterfaceType.None)] public class Employee {
D. Add the following attribute to the class definition. [ClassInterface(ClassInterfaceType.AutoDual)] public class Employee {

Answer: A
QUESTION 256
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.Site.Name = serverName;
B. Insert the following line of code between lines 04 and 05: crtl.ExecuteCommand(0);
C. Insert the following line of code between lines 04 and 05: crtl.Continue();

D. Insert the following line of code between lines 04 and 05: crtl.Start();
E. Insert the following line of code between lines 03 and 04: crtl.ServiceName = serverName;
F. Insert the following line of code between lines 03 and 04: crtl.MachineName = serverName;

Answer: DF
QUESTION 257
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. IsolatedStorageFile= isoFile; isoFile = IsolatedStorageFile::GetMachineStoreForAssembly(); IsolatedStorageFileStream= isoStream; isoStream = gcnew IsolatedStorageFileStream( "Settings.dat", FileMode::Open, isoFile); String= result = (gcnew StreamReader(isoStream))->ReadToEnd();
B. IsolatedStorageFileStream= isoStream; isoStream = gcnew IsolatedStorageFileStream( "Settings.dat", FileMode::Open); String= result = isoStream->ToString();
C. IsolatedStorageFile= isoFile; isoFile = IsolatedStorageFile::GetMachineStoreForAssembly(); IsolatedStorageFileStream= isoStream; isoStream = gcnew IsolatedStorageFileStream( "Settings.dat", FileMode::Open, isoFile); String= result = isoStream->ToString();
D. IsolatedStorageFileStream= isoStream; isoStream = gcnew IsolatedStorageFileStream( "Settings.dat", FileMode::Open); String= result = (gcnew StreamReader(isoStream))->ReadToEnd();

Answer: A
QUESTION 258
You need to call an unmanaged function from your managed code by using platform invoke services. What should you do?
A. Import a type library as an assembly and then create instances of COM object.
B. Export a type library for your managed code.
C. Create a class to hold DLL functions and then create prototype methods by using managed code.

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

Answer: C
QUESTION 259
You write the following code to implement the MyClass.MyMethod function.
public class MyClass {
public int MyMethod(int arg) {
return arg;
}
}
You need to call the MyClass.MyMethod function dynamically from an unrelated class in your assembly.
Which code segment should you use?
A. MyClass= myClass = gcnew MyClass(); Type= t = MyClass::typeid; MethodInfo= m = t->GetMethod("MyMethod"); int i = (int)m->Invoke(this, gcnew array { 1 });
B. Type= t = Type::GetType("MyClass"); MethodInfo= m = t->GetMethod("MyMethod"); int i = (int)m->Invoke(this, gcnew array { 1 });
C. MyClass= myClass = gcnew MyClass(); Type= t = MyClass::typeid; MethodInfo= m = t->GetMethod("MyMethod"); int i = (int)m->Invoke(myClass, gcnew array { 1 });
D. MyClass= myClass = gcnew MyClass(); Type= t = MyClass::typeid; MethodInfo= m = t->GetMethod("MyClass.MyMethod"); int i = (int)m->Invoke(myClass, gcnew array { 1 });
Answer: C QUESTION 260

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 = null; algo.TransformBlock(message, 0, message.Length, hash, 0);
B. HashAlgorithm algo; algo = HashAlgorithm.Create(message.ToString()); byte[] hash = algo.Hash;
C. HashAlgorithm algo = HashAlgorithm.Create("MD5"); byte[] hash = algo.ComputeHash(message);
D. HashAlgorithm algo = HashAlgorithm.Create("MD5"); byte[] hash = BitConverter.GetBytes(algo.GetHashCode());

Answer: C
QUESTION 261
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("C:\\WINDOWS\\system32\\user32.dll")] extern int MessageBox(int hWnd, String= text, String= caption, uint type);
B. [DllImport("user32")] extern int MessageBox(int hWnd, String= text, String= caption, uint type);
C. [DllImport("user32")] extern int MessageBoxA(int hWnd, String= text, String= caption, uint type);
D. [DllImport("user32")] extern int Win32API_User32_MessageBox( int hWnd, String= text, String= caption, uint type);


Answer: B
QUESTION 262
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.NTAccount userNTName = new NTAccount(userName); GenericIdentity ident = new GenericIdentity(userNTName.Value); GenericPrincipal currentUser= new GenericPrincipal(ident, userRolesArray); Thread.CurrentPrincipal = currentUser;
B.IntPtr token = IntPtr.Zero; token = LogonUserUsingInterop(userName, encryptedPassword); WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(token);
C.WindowsIdentity ident = new WindowsIdentity(userName); WindowsPrincipal currentUser = new WindowsPrincipal(ident); Thread.CurrentPrincipal = currentUser;
D.GenericIdentity ident = new GenericIdentity(userName); GenericPrincipal currentUser = new GenericPrincipal(ident, userRolesArray); Thread.CurrentPrincipal = currentUser;

Answer: D
QUESTION 263
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 ref class Customer { string addressString;

public: Customer(string address) : addressString(address) { } String= GetAddress() { return addressString; } }
B. public ref class Customer { string addressString; public: Customer() { } private: String= GetAddress() { return addressString; } }
C. public ref class Customer { string addressString; public: Customer() { } String= GetAddress() { return addressString; } }
D. public ref class Customer { static string addressString; public: Customer() { } static String= GetAddress() { return addressString; } }

Answer: C
QUESTION 264
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->ReadToEnd();
B. String= result = nullptr; StreamReader= reader = gcnew StreamReader("Message.txt"); result = reader->ReadLine();
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->Read().ToString();

Answer: A QUESTION 265

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. (Click the Exhibit button.) Which code segment should you choose?

A.Rectangle= rectangle = gcnew Rectangle(10, 10, 450, 25); LinearGradientBrush= rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue, Color::CornflowerBlue, LinearGradientMode::ForwardDiagonal); Pen= rectanglePen = gcnew Pen(rectangleBrush); Graphics= g = this->CreateGraphics(); g->FillRectangle(rectangleBrush, rectangle);
B.RectangleF= rectangle = gcnew RectangleF(10f, 10f, 450f, 25f); SolidBrush= rectangleBrush = gcnew SolidBrush(Color::AliceBlue); Pen= rectanglePen = gcnew Pen(rectangleBrush); Graphics= g = this->CreateGraphics(); g->DrawRectangle(rectangleBrush, rectangle);
C.Rectangle= rectangle = gcnew Rectangle(10, 10, 450, 25); LinearGradientBrush= rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue, Color::CornflowerBlue, LinearGradientMode::ForwardDiagonal); Pen= rectanglePen = gcnew Pen(rectangleBrush); Graphics= g = this->CreateGraphics(); g->DrawRectangle(rectanglePen, rectangle);
D.RectangleF= rectangle = gcnew RectangleF(10f, 10f, 450f, 25f); array= points = gcnew array= {gcnew Point(0, 0), gcnew Point(110, 145)}; LinearGradientBrush= rectangleBrush = gcnew LinearGradientBrush(rectangle, Color::AliceBlue, Color::CornflowerBlue, LinearGradientMode::ForwardDiagonal); Pen= rectanglePen = gcnew Pen(rectangleBrush); Graphics= g = this->CreateGraphics(); g->DrawPolygon(rectanglePen, points);
Answer: A
QUESTION 266
You need to write a multicast delegate that accepts a DateTime argument. Which code segment should you use?

A. public delegate void PowerDeviceOn(DateTime autoPowerOff);
B. public delegate bool PowerDeviceOn(DateTime autoPowerOff);
C. public delegate int PowerDeviceOn(bool result, DateTime autoPowerOff);
D. public delegate bool PowerDeviceOn(object sender, EventArgs autoPowerOff);

Answer: A
QUESTION 267
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(); ArrayList sync_al = ArrayList.Synchronized(al); return sync_al;
C. ArrayList al = new ArrayList(); Monitor.Enter(al); Monitor.Exit(al); return al;
D. ArrayList al = new ArrayList(); lock (al.SyncRoot.GetType()){ return al; }

Answer: B
QUESTION 268
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.for each (CultureInfo= culture in CultureInfo::GetCultures(CultureTypes::NeutralCultures)) { // Output the
culture information...

}
C.for each (CultureInfo= culture in CultureInfo::GetCultures(CultureTypes::ReplacementCultures)) { // Output the culture information... }
D.CultureInfo= culture = gcnew CultureInfo(""); CultureTypes= types = culture->CultureTypes; // Output the culture information...

Answer: A
QUESTION 269
You are creating a new security policy for an application domain. You write the following lines of code.
PolicyLevel =policy = PolicyLevel::CreateAppDomainLevel();
PolicyStatement =noTrustStatement =
gcnew PolicyStatement(
policy->GetNamedPermissionSet("Nothing"));
PolicyStatement =fullTrustStatement =
gcnew PolicyStatement(
policy->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. CodeGroup =group1 = gcnew FirstMatchCodeGroup( gcnew ZoneMembershipCondition(SecurityZone::Trusted), fullTrustStatement); CodeGroup =group2 = gcnew UnionCodeGroup( gcnew AllMembershipCondition(), noTrustStatement); group1->AddChild(group2);
B. CodeGroup =group = gcnew FirstMatchCodeGroup( gcnew AllMembershipCondition(), noTrustStatement);

C. CodeGroup =group = gcnew UnionCodeGroup(
gcnew ZoneMembershipCondition(SecurityZone::Trusted), fullTrustStatement);
D. CodeGroup =group1 = gcnew FirstMatchCodeGroup( gcnew AllMembershipCondition(), noTrustStatement); CodeGroup =group2 = gcnew UnionCodeGroup( gcnew ZoneMembershipCondition(SecurityZone::Trusted), fullTrustStatement); group1->AddChild(group2);

Answer: D
QUESTION 270
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("");
if (regionInfo->Name == "CA") {
// Output the region information...
} D.RegionInfo= regionInfo = gcnew RegionInfo("CA");
// Output the region information...

Answer: D
QUESTION 271
You are creating an assembly named Assembly1. Assembly1 contains a public method. The global cache contains a second assembly named Assembly2. You must ensure that the public method is only called from Assembly2. Which permission class should you use?
A. GacIdentityPermission
B. StrongNameIdentityPermission
C. DataProtectionPermission
D. PublisherIdentityPermission


Answer: B
QUESTION 272
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 Shared m_AddressString As String Public Sub New() End Sub Public Shared Function GetAddress() As String Return m_AddressString End Function End Class
B. Public Class Customer Private m_AddressString As String Public Sub New() End Sub Private Function GetAddress() As String Return m_AddressString End Function End Class
C. 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 Function End Class
D. Public Class Customer Private m_AddressString As String Public Sub New() End Sub Public Function GetAddress() As String Return m_AddressString End Function End Class
Answer: D QUESTION 273

You are testing a method that examines a running process. This method returns an ArrayList containing the name and full path of all modules that are loaded by the process. You need to list the modules loaded by a process named C:\TestApps\Process1.exe. Which code segment should you use?
A. ArrayList ar = new ArrayList(); Process[] procs; ProcessModuleCollection modules; procs = Process.GetProcesses(@"Process1"); if (procs.Length > 0) { modules = procs[0].Modules foreach (ProcessModule mod in modules) { ar.Add(mod.ModuleName); } }
B. ArrayList ar = new ArrayList(); Process[] procs; ProcessModuleCollection modules; procs = Process.GetProcessesByName(@"Process1"); if (procs.Length > 0) { modules = procs[0].Modules; foreach (ProcessModule mod in modules) { ar.Add(mod.FileName); } }
C. ArrayList ar = new ArrayList(); Process[] procs; ProcessModuleCollection modules; procs = Process.GetProcesses(@"C:\TestApps\Process1.exe"); if (procs.Length > 0) { modules = procs[0].Modules foreach (ProcessModule mod in modules) { ar.Add(mod.ModuleName); } }
D. ArrayList ar = new ArrayList(); Process[] procs; ProcessModuleCollection modules; procs = Process.GetProcessesByName( @"C:\TestApps\Process1.exe");

if (procs.Length > 0) {
modules = procs[0].Modules;
foreach (ProcessModule mod in modules) {
ar.Add(mod.FileName);
}
}

Answer: B
QUESTION 274
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. System.ComponentModel.Component myComponent; myComponent = new System.ComponentModel.Component();
B. AppDomainSetup mySetup = AppDomain.CurrentDomain.SetupInformation; mySetup.ShadowCopyFiles = "true";
C. System.Diagnostics.Process myProcess; myProcess = new System.Diagnostics.Process();
D. AppDomain domain; domain = AppDomain.CreateDomain("MyDomain");

Answer: D
QUESTION 275
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 IsStatic property of the MethodInfo class.
B. Call the IsVirtual property of the MethodInfo class.
C. Call the IsFamily property of the MethodInfo class.
D. Call the IsAssembly property of the MethodInfo class.

Answer: C
QUESTION 276
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. StringReader reader = new StringReader(message); while (reader.Peek() != -1) { Process(reader.ReadLine()); } reader.Close();
B. StringReader reader = new StringReader(message); while (reader.Peek() != -1) { string line = reader.Read().ToString(); Process(line); } reader.Close();
C. StringReader reader = new StringReader(message); Process(reader.ReadToEnd()); reader.Close();
D. StringReader reader = new StringReader(message); Process(reader.ToString()); reader.Close();

Answer: A
QUESTION 277
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 string name;
public 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.

Hardware
Amy


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: ConfigurationElement { protected override void DeserializeElement( XmlReader reader, bool serializeCollectionKey) { Department dept = new Department(); dept.name = reader.GetAttribute("name"); dept.manager = reader.GetAttribute("manager"); } }
B.public class deptHandler : IConfigurationSectionHandler { public object Create(object parent, object configContext, System.Xml.XmlNode section) { Department dept = new Department(); dept.name = section.Attributes["name"].Value; dept.manager = section.Attributes["manager"].Value; return dept; } }
C.public class deptElement : ConfigurationElement { protected override void DeserializeElement( XmlReader reader, bool serializeCollectionKey) { Department dept = new Department(); dept.name = ConfigurationManager.AppSettings["name"]; dept.manager = ConfigurationManager.AppSettings["manager"]; return dept; } }
D.public class deptHandler : IConfigurationSectionHandler { public object Create(object parent, object configContext, System.Xml.XmlNode section) { Department dept = new Department(); dept.name = section.SelectSingleNode("name").InnerText; dept.manager = section.SelectSingleNode("manager").InnerText; return dept; } }
Answer: D QUESTION 278

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.contoso.com.
To test the application, you use a source address, [email protected], and a target address, [email protected].
You need to transmit the e-mail message.
Which code segment should you use?
A.MailAddress addrFrom =
new MailAddress("[email protected]", "Me");
MailAddress addrTo =
new MailAddress("[email protected]", "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);
B.MailAddress addrFrom = new MailAddress("[email protected]"); MailAddress addrTo = new
MailAddress("[email protected]"); MailMessage message = new MailMessage(addrFrom, addrTo);
message.Subject = "Greetings!";
message.Body = "Test";
SmtpClient client = new SmtpClient("smtp.contoso.com"); client.Send(message);
C.string strSmtpClient = "smtp.contoso.com";
string strFrom = "[email protected]";
string strTo = "[email protected]";
string strSubject = "Greetings!";
string strBody = "Test";
MailMessage msg =
new MailMessage(strFrom, strTo, strSubject, strSmtpClient);
D.MailAddress addrFrom =
new MailAddress("[email protected]", "Me");
MailAddress addrTo =
new MailAddress("[email protected]", "You");
MailMessage message = new MailMessage(addrFrom, addrTo); message.Subject = "Greetings!";
message.Body = "Test";
message.Dispose();


Answer: B
QUESTION 279
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::GetMachineStoreForAssembly(); store->CreateDirectory("Preferences");
B. IsolatedStorageFile= store; store = IsolatedStorageFile::GetUserStoreForAssembly(); store->CreateDirectory("Preferences");
C. IsolatedStorageFile= store; store = IsolatedStorageFile::GetUserStoreForDomain(); store->CreateDirectory("Preferences");
D. IsolatedStorageFile= store; store = IsolatedStorageFile::GetMachineStoreForApplication(); store->CreateDirectory("Preferences");

Answer: B
QUESTION 280
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. CultureInfo culture = new CultureInfo("zh-HK"); return numberToPrint.ToString("-(0)", 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("()", culture);
D. NumberFormatInfo culture = new CultureInfo("zh-HK").NumberFormat; culture.NumberNegativePattern = 1; return numberToPrint.ToString("C", culture);
Answer: B QUESTION 281

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 undoBuffer = gcnew Stack();
B. Queue undoBuffer = gcnew Queue();
C. Stack undoBuffer = gcnew Stack();
D. Queue undoBuffer = gcnew Queue();

Answer: C
QUESTION 282
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(); foreach (IdentityReference grp in currentUser.Groups) { NTAccount grpAccount = ((NTAccount)grp.Translate(typeof(NTAccount))); isAuthorized = grpAccount.Value.Equals( Environment.MachineName + @"\Clerk"); if (isAuthorized) break; }
B.WindowsPrincipal currentUser = (WindowsPrincipal)Thread.CurrentPrincipal; isAuthorized = currentUser.IsInRole( Environment.MachineName);
C.WindowsPrincipal currentUser = (WindowsPrincipal)Thread.CurrentPrincipal; isAuthorized = currentUser.IsInRole("Clerk");
D.GenericPrincipal currentUser = (GenericPrincipal) Thread.CurrentPrincipal; isAuthorized = currentUser.IsInRole("Clerk");

Answer: C
QUESTION 283
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.GetUserStoreForDomain(); store.CreateDirectory("Preferences");
B. IsolatedStorageFile store; store = IsolatedStorageFile.GetMachineStoreForAssembly(); store.CreateDirectory("Preferences");
C. IsolatedStorageFile store; store = IsolatedStorageFile.GetMachineStoreForApplication(); store.CreateDirectory("Preferences");
D. IsolatedStorageFile store; store = IsolatedStorageFile.GetUserStoreForAssembly(); store.CreateDirectory("Preferences");

Answer: D
QUESTION 284
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.RevertDeny();
B. CodeAccessPermission.RevertAssert();
C. permission.Deny();
D. permission.PermitOnly();
Answer: B
QUESTION 285
You create the definition for a Vehicle class by using the following code segment.
public ref class Vehicle { public :

[XmlAttribute(AttributeName = "category")]
String= vehicleType;
String= model;
[XmlIgnore]
int year; [XmlElement(ElementName = "mileage")]
int miles;
ConditionType condition;
Vehicle() {}
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:

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. racer 15000 Excellent
B. racer 15000 AboveAverage
C. racer 15000 Excellent
D. car racer 15000 Excellent
Answer: A QUESTION 286

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(); sha.GetHashCode(); byte[] hash = sha.Hash;
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(); byte[] hash = null; sha.TransformBlock( message, 0, message.Length, hash, 0);

Answer: C
QUESTION 287
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::UnauthenticatedPrincipal);
B. AppDomain= domain = AppDomain::CurrentDomain; domain->SetPrincipalPolicy(PrincipalPolicy::WindowsPrincipal);
C. AppDomain= domain = AppDomain::CurrentDomain; domain->SetThreadPrincipal(gcnew WindowsPrincipal(nullptr));
D. AppDomain= domain = AppDomain::CurrentDomain; domain->SetAppDomainPolicy(PolicyLevel::CreateAppDomainLevel());

Answer: A
QUESTION 288
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 ref class PrintingArgs {

public : EventArgs Args; PrintingArgs(EventArgs ea) { this->Args = ea; } };
B. public ref class PrintingArgs { public : int Copies; PrintingArgs (int numberOfCopies) { this->Copies = numberOfCopies; } };
C. public ref class PrintingArgs : public EventArgs { public : int Copies; };
D. public ref class PrintingArgs : public EventArgs { public : int Copies; PrintingArgs(int numberOfCopies) { this->Copies = numberOfCopies; } };

Answer: D
QUESTION 289
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.GenericPrincipal= currentUser = safe_cast(Thread::CurrentPrincipal); isAuthorized = currentUser->IsInRole("Clerk");
B.WindowsIdentity= currentUser = WindowsIdentity::GetCurrent(); For each (IdentityReference= grp in currentUser->Groups) { NTAccount= grpAccount = safe_cast(grp->Translate(NTAccount::typeid)); isAuthorized = grpAccount->Value->Equals( Environment::MachineName + "\\Clerk"); if (isAuthorized) break ;}
C.WindowsPrincipal= currentUser = safe_cast(Thread::CurrentPrincipal); isAuthorized = currentUser->IsInRole("Clerk"); D.WindowsPrincipal= currentUser =

safe_cast(Thread::CurrentPrincipal); isAuthorized = currentUser->IsInRole( Environment::MachineName);

Answer: C
QUESTION 290
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 ref class Meeting { private : String= title; public : int roomNumber; array= invitees; Meeting(){} Meeting(String= t){ title = t; } }; The component contains a procedure with the following code segment. Meeting= myMeeting = gcnew Meeting("Goals"); myMeeting->roomNumber=1100; array= attendees = gcnew array(2)
{"John", "Mary"};
myMeeting->invitees = attendees; XmlSerializer= xs = gcnew XmlSerializer(__typeof(Meeting));

StreamWriter= writer = gcnew 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. 1100 John Mary
B. 1100 John Mary
C. Goals 1100 John Mary
D. 1100

John Mary


Answer: D
QUESTION 291
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.Calendar cal = new CultureInfo("es-MX", false).Calendar; DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day); Strong dateString = dt.ToString();
B.string dateString = DateTime.Today.Month.ToString("es-MX"); C.string dateString = DateTimeFormatInfo.CurrentInfo GetMonthName(DateTime.Today.Month); D.DateTimeFormatInfo dtfi = new CultureInfo("es-MX", false).DateTimeFormat; DateTime dt = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day); string dateString = dt.ToString(dtfi.LongDatePattern);

Answer: D
QUESTION 292
You need to serialize an object of type List in a binary format. The object is named data. Which code segment should you use?
A.BinaryFormatter= formatter = gcnew BinaryFormatter(); MemoryStream= stream = gcnew MemoryStream(); formatter->Serialize(stream, data);
B.BinaryFormatter= formatter = gcnew BinaryFormatter(); MemoryStream= stream = gcnew MemoryStream(); Capture c(formatter,stream); data->ForEach(gcnew Action(%c,&Capture::Action));
C.BinaryFormatter= formatter = gcnew BinaryFormatter();a rray= buffer = gcnew array(data->Count); MemoryStream= stream = gcnew MemoryStream(buffer, true); formatter->Serialize(stream, data);
D.BinaryFormatter= formatter = gcnew BinaryFormatter(); MemoryStream= stream = gcnew MemoryStream(); for (int i = 0; i < data->Count; i++) {

formatter->Serialize(stream, data[i]); }

Answer: A
QUESTION 293
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"); for each (ManagementObject= svc in searcher->Get()) { if ((String=) svc["State"] == "'Paused'") { 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 where State = 'Paused'"); for each (ManagementObject= svc in searcher->Get()) { 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: C QUESTION 294

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 class FaxArgs : EventArgs { private string coverPageInfo; public FaxArgs(string coverInfo) { this.coverPageInfo = coverPageInfo; } public string CoverPageInformation { get {return this.coverPageInfo;} } }
B. public static event Fax FaxDocs;
C. public class FaxArgs : EventArgs { private string coverPageInfo; public string CoverPageInformation { get {return this.coverPageInfo;} } }
D. public static event FaxDocs Fax;

Answer: D
QUESTION 295
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(int iValue) { try { return Value.CompareTo(iValue); } catch { throw new ArgumentException ("object not an Age"); } } }
B. public class Age { public int Value;

public object CompareTo(object obj) {
if (obj is Age) {
Age _age = (Age) obj;
return Value.CompareTo(obj);
}
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.CompareTo(_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.CompareTo(((Age) obj).Value); } catch { return -1; } } }
Answer: C
QUESTION 296
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. [OnDeserializing] void UpdateValue(SerializationInfo= info) { info->AddValue("currentRate", GetCurrentRate()); }
B. [OnSerializing] void UpdateValue (StreamingContext= context) { currRate = GetCurrentRate(); }
C. [OnDeserialized] void UpdateValue(StreamingContext= context) { currRate = GetCurrentRate(); }
D. [OnSerializing] void UpdateValue(SerializationInfo= info) { info->AddValue("currentRate", GetCurrentRate()); }

Answer: C
QUESTION 297
You are developing a server application that will transmit sensitive information on a network. You create an X509Certificate object named certificate and a TcpClient object named client. You need to create an SslStream to communicate by using the Transport Layer Security 1.0 protocol. Which code segment should you use?
A. SslStream ssl = new SslStream(client.GetStream()); ssl.AuthenticateAsServer( certificate, false, SslProtocols.Ssl2, true);
B. SslStream ssl = new SslStream(client.GetStream()); ssl.AuthenticateAsServer( certificate, false, SslProtocols.None, true);
C. SslStream ssl = new SslStream(client.GetStream()); ssl.AuthenticateAsServer( certificate, false, SslProtocols.Tls, true);
D. SslStream ssl = new SslStream(client.GetStream()); ssl.AuthenticateAsServer( certificate, false, SslProtocols.Ssl3, true);
Answer: C
QUESTION 298
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.Deny();
C. set.Assert();
D. set.PermitOnly();

Answer: A
QUESTION 299
You write the following custom exception class named CustomException. public ref class CustomException : ApplicationException { public: literal int COR_E_ARGUMENT = (int)0x80070057; CustomException(String= msg) : ApplicationException(msg) { HResult = COR_E_ARGUMENT; } }; 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 gcnew CustomException("Argument is out of bounds");


Answer: D
QUESTION 300
You are creating a class to compare a specially-formatted string. The default collation comparisons do not apply. You need to implement the IComparable interface. Which code segment should you use?
A. public ref class Person : public IComparable{ public : virtual Boolean CompareTo(String= other){ ... } }
B. public ref class Person : public IComparable{ public : virtual Int32 CompareTo(Object= other){ ... } }
C. public ref class Person : public IComparable{ public : virtual Int32 CompareTo(String= other){ ... } }
D. public ref class Person : public IComparable{ public : virtual Boolean CompareTo(Object= other){ ... } }

Answer: C
QUESTION 301
You are creating an application that retrieves values from a custom section of the application configuration file. The custom section uses XML as shown in the following block.
QUESTION 302 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 explicitly contain a collection.
B. The method must return a type of either IEnumerator or IEnumerable.
C. The method must be the only iterator in the class.
D. The method must return a type of IComparable.


Answer: B
QUESTION 303
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 Assembly1.dll into the current application domain. Which code segment should you use?
A. AppDomain= domain = AppDomain::CurrentDomain; String= myPath = Path::Combine(domain->BaseDirectory, "Assembly1.dll"); Assembly= assm = Assembly::LoadFrom(myPath);
B. AppDomain= domain = AppDomain::CurrentDomain; String= myPath = Path::Combine(domain->BaseDirectory, "Assembly1.dll"); Assembly= assm = Assembly::Load(myPath);
C. AppDomain= domain = AppDomain::CurrentDomain; String= myPath = Path::Combine(domain->DynamicDirectory, "Assembly1.dll"); Assembly= assm = AppDomain::CurrentDomain::Load(myPath);
D. AppDomain= domain = AppDomain::CurrentDomain; Assembly= assm = domain->GetData("Assembly1.dll");

Answer: A
QUESTION 304
You are developing a method to encrypt sensitive data with the Data Encryption Standard (DES) algorithm. Your method accepts the following parameters:
The byte array to be encrypted, which is named message
An encryption key, which is named key
An initialization vector, which is named iv
You need to encrypt the data. You also need to write the encrypted data to a MemoryStream object.
Which code segment should you use?
A.DES= des = gcnew DESCryptoServiceProvider(); des->BlockSize = message->Length; ICryptoTransform= crypto = des->CreateEncryptor(key, iv); MemoryStream =cipherStream = gcnew MemoryStream(); CryptoStream =cryptoStream = gcnew CryptoStream(cipherStream,crypto, CryptoStreamMode::Write);

cryptoStream->Write(message, 0, message->Length); B.DES =des = gcnew DESCryptoServiceProvider(); ICryptoTransform =crypto = des->CreateEncryptor(key, iv); MemoryStream =cipherStream = gcnew MemoryStream(); CryptoStream =cryptoStream = gcnew CryptoStream(cipherStream, crypto, CryptoStreamMode::Write); cryptoStream->Write(message, 0, message->Length); C.DES =des = gcnew DESCryptoServiceProvider(); ICryptoTransform= crypto = des->CreateEncryptor(); MemoryStream =cipherStream = gcnew MemoryStream(); CryptoStream =cryptoStream = gcnew CryptoStream(cipherStream, crypto, CryptoStreamMode::Write); cryptoStream->Write(message, 0, message->Length); D.DES =des = gcnew DESCryptoServiceProvider(); ICryptoTransform =crypto = des->CreateDecryptor(key, iv); MemoryStream =cipherStream = gcnew MemoryStream(); CryptoStream =cryptoStream = gcnew CryptoStream(cipherStream, crypto, CryptoStreamMode::Write); cryptoStream->Write(message, 0, message->Length);

Answer: B
QUESTION 305
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(); evidence.AddHost(new Zone(SecurityZone.Intranet));
B. Evidence evidence = new Evidence( AppDomain.CurrentDomain.Evidence );
C. Evidence evidence = new Evidence(); evidence.AddAssembly(new Zone(SecurityZone.Intranet));
D. Evidence evidence = new Evidence( Assembly.GetExecutingAssembly().Evidence );

Answer: A
QUESTION 306
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
QUESTION 307
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.RegionInfo regionInfo = new RegionInfo(""); if (regionInfo.Name == "CA") { // Output the region information... }
B.foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) { // Output the region information... }
C.CultureInfo cultureInfo = new CultureInfo("CA"); // Output the region information... D.RegionInfo regionInfo = new RegionInfo("CA"); // Output the region information...

Answer: D
QUESTION 308
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 = File::GetAccessControl("mydata.xml"); security->SetAuditRuleProtection(true, true);
File::SetAccessControl("mydata.xml", security); C.FileSecurity= security = File::GetAccessControl("mydata.xml"); security->SetAccessRuleProtection(true, true); D.FileSecurity= security = gcnew FileSecurity(); security->SetAccessRuleProtection(true, true); File::SetAccessControl("mydata.xml", security);

Answer: A
QUESTION 309
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::AutoDual)] public class Employee {
B.Add the following attribute to the class definition. [ComVisible(true)] public class Employee { C.Add the following attribute to the class definition.

[ClassInterface(ClassInterfaceType::None)] 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
QUESTION 310
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 "John"
You also need to ensure that the code segment simultaneously facilitates uninterrupted execution of the application.
Which code segment should you use?
A.Debug::WriteLineIf(fName != "John", fName, "Test Failed"); B.Debug::Assert(fName == "John", "Test Failed: ", fName); C.if (fName != "John") {
Debug::Print("Test Failed: "); Debug::Print(fName); }
D.if (fName != "John") { Debug::WriteLine("Test Failed: "); Debug::WriteLine(fName); }

Answer: A
QUESTION 311
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(); AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.RunAndSave); myAssemblyBuilder.Save("MyAssembly.dll");
B. AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "MyAssembly"; AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Save); myAssemblyBuilder.Save("MyAssembly.dll");
C. AssemblyName myAssemblyName = new AssemblyName("MyAssembly"); AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Save); myAssemblyBuilder.Save("c:\\MyAssembly.dll");
D. AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "MyAssembly"; AssemblyBuilder myAssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (myAssemblyName, AssemblyBuilderAccess.Run); myAssemblyBuilder.Save("MyAssembly.dll");

Answer: B
QUESTION 312
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 EventArgs eventArgs; public PrintingArgs(EventArgs ea) { this.eventArgs = ea; } public EventArgs Args { get { return eventArgs; } } }

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 : EventArgs { private int copies; }
D. public class PrintingArgs { private int copies; public PrintingArgs(int numberOfCopies) { this.copies = numberOfCopies; } public int Copies { get { return this.copies; } } }

Answer: B
QUESTION 313
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(); evidence->AddHost(gcnew Zone(SecurityZone::Intranet));
B. Evidence= evidence = gcnew Evidence(); evidence->AddAssembly(gcnew Zone(SecurityZone::Intranet));
C. Evidence= evidence = gcnew Evidence(Assembly::GetExecutingAssembly()->Evidence);
D. Evidence= evidence = gcnew Evidence(AppDomain::CurrentDomain->Evidence);
Answer: A
QUESTION 314

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 = gcnew AssemblyName("MyAssembly"); AssemblyBuilder= myAssemblyBuilder = AppDomain::CurrentDomain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::Save); myAssemblyBuilder->Save("c:\\MyAssembly.dll");
B. AssemblyName= myAssemblyName = gcnew AssemblyName(); AssemblyBuilder= myAssemblyBuilder = AppDomain::CurrentDomain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::RunAndSave); myAssemblyBuilder->Save("MyAssembly.dll");
C. AssemblyName= myAssemblyName = gcnew AssemblyName(); myAssemblyName->Name = "MyAssembly"; AssemblyBuilder= myAssemblyBuilder = AppDomain::CurrentDomain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::Save); myAssemblyBuilder->Save("MyAssembly.dll");
D. AssemblyName= myAssemblyName = gcnew AssemblyName(); myAssemblyName->Name = "MyAssembly"; AssemblyBuilder= myAssemblyBuilder = AppDomain::CurrentDomain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::Run); myAssemblyBuilder->Save("MyAssembly.dll");

Answer: C
QUESTION 315
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.Assert, Flags = SecurityPermissionFlag.UnmanagedCode) ]
C. [SecurityPermission( SecurityAction.Deny, Flags = SecurityPermissionFlag.UnmanagedCode)

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

Answer: A
QUESTION 316
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 : ServiceBase { bool blnExit = false; public PollingService() { } protected override void OnStart(string[] args) { do { DoWork(); } while (!blnExit); } protected 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 from the OnStart method into the DoWork method. B.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. C.Move the loop code into the constructor of the service class from the OnStart method. D.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.

Answer: B
QUESTION 317
You need to write a multicast delegate that accepts a DateTime argument and returns a Boolean value. Which code segment should you use?
A. public delegate void PowerDeviceOn(DateTime);
B. public delegate int PowerDeviceOn(bool, DateTime);
C. public delegate bool PowerDeviceOn(Object, EventArgs);
D. public delegate bool PowerDeviceOn(DateTime);

Answer: B
QUESTION 318
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.

Hardware
Amy

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 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;
}
};
B.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;
}
};
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 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");
}
};

Answer: C
QUESTION 319
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 = new EventLog("Application", "."); myLog.Source = "MySource"; foreach (EventLogEntry entry in myLog.Entries) { if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning) { PersistToDB(entry); }
B. EventLog myLog = new EventLog("Application", "."); foreach (EventLogEntry entry in myLog.Entries) { if (entry.Source == "MySource") { if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning) { PersistToDB(entry); } } }
C. EventLog myLog = new EventLog("Application", "."); myLog.Source = "MySource";

foreach (EventLogEntry entry in myLog.Entries) { if (entry.EntryType == (EventLogEntryType.Error & EventLogEntryType.Warning)) { PersistToDB(entry); } }
D. EventLog myLog = new EventLog("Application", "."); foreach (EventLogEntry entry in myLog.Entries) { if (entry.Source == "MySource") { PersistToDB(entry); } }

Answer: B
QUESTION 320
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.GetType()) { return al; }
B. ArrayList= al = gcnew ArrayList(); lock (al->SyncRoot) { return al; }
C. ArrayList= al = gcnew ArrayList(); ArrayList= sync_al = ArrayList::Synchronized(al); return sync_al;
D. ArrayList= al = gcnew ArrayList(); Monitor::Enter(al); Monitor::Exit(al); return al;
Answer: C
QUESTION 321
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){ 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 04 and 05: crtl.ExecuteCommand(0);
C. Insert the following line of code between lines 03 and 04: crtl.MachineName = 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 03 and 04: crtl.Site.Name = serverName;

Answer: CE
QUESTION 322
You are developing a method to encrypt sensitive data with the Data Encryption Standard (DES) algorithm. Your method accepts the following parameters:
The byte array to be encrypted, which is named message
An encryption key, which is named key An initialization vector, which is named iv

You need to encrypt the data. You also need to write the encrypted data to a MemoryStream object.
Which code segment should you use?
A.DES des = new DESCryptoServiceProvider();
ICryptoTransform crypto = des.CreateEncryptor(key, iv); MemoryStream cipherStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write); cryptoStream.Write(message, 0, message.Length);
B.DES des = new DESCryptoServiceProvider(); des.BlockSize = message.Length; ICryptoTransform crypto = des.CreateEncryptor(key, iv); MemoryStream cipherStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write); cryptoStream.Write(message, 0, message.Length);
C.DES des = new DESCryptoServiceProvider(); ICryptoTransform crypto = des.CreateEncryptor(); MemoryStream cipherStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write); cryptoStream.Write(message, 0, message.Length);
D.DES des = new DESCryptoServiceProvider(); ICryptoTransform crypto = des.CreateDecryptor(key, iv); MemoryStream cipherStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(cipherStream, crypto, CryptoStreamMode.Write); cryptoStream.Write(message, 0, message.Length);

Answer: A
QUESTION 323
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=hash = nullptr; sha->TransformBlock(message, 0, message->Length, hash, 0);
B. SHA1 =sha = gcnew SHA1CryptoServiceProvider(); sha->GetHashCode(); array=hash = sha->Hash;
C. SHA1 =sha = gcnew SHA1CryptoServiceProvider();

array=hash = BitConverter::GetBytes(sha->GetHashCode());
D. SHA1 =sha = gcnew SHA1CryptoServiceProvider(); array=hash = sha->ComputeHash(message);

Answer: D
QUESTION 324
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(); MemoryStream stream = new MemoryStream(); foreach (object o in dept) { formatter.Serialize(stream, o); }
C. SoapFormatter formatter = new SoapFormatter(); byte[] buffer = new byte[dept.Capacity]; MemoryStream stream = new MemoryStream(buffer); formatter.Serialize(stream, dept);
D. SoapFormatter formatter = new SoapFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, dept);

Answer: D
QUESTION 325
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->CurrencyNegativePattern = 1; return numberToPrint->ToString("C", culture);

B. NumberFormatInfo= culture =
gcnew CultureInfo("zh-HK")::NumberFormat;
culture->NumberNegativePattern = 1;
return numberToPrint->ToString("C", culture);
C. CultureInfo= culture = gcnew CultureInfo("zh-HK"); return numberToPrint->ToString("()", culture);
D. CultureInfo= culture = gcnew CultureInfo("zh-HK"); return numberToPrint->ToString("-(0)", culture);

Answer: A
QUESTION 326
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. public ref class CalculationValues {...}; public ref class Calculator { public : void PerformCalculation(Object= values) {} }; public ref class ThreadTest{ private : void DoWork (){ CalculationValues= myValues = gcnew CalculationValues(); Calculator = calc = gcnew Calculator(); Thread= newThread = gcnew Thread( gcnew ParameterizedThreadStart(calc, &Calculator::PerformCalculation)); newThread->Start(myValues); } };
B. public ref class CalculationValues {...}; public ref class Calculator { public : void PerformCalculation() {} }; public ref class ThreadTest{ private : void DoWork (){

CalculationValues= myValues = gcnew CalculationValues(); Calculator = calc = gcnew Calculator(); ThreadStart= delStart = gcnew ThreadStart(calc, &Calculator::PerformCalculation); Thread= newThread = gcnew Thread(delStart); if (newThread->IsAlive) { newThread->Start(myValues); } } };
C. public ref class CalculationValues {...}; public ref class Calculator { public : void PerformCalculation(CalculationValues= values) {} }; public ref class ThreadTest{ private : void DoWork (){ CalculationValues= myValues = gcnew CalculationValues(); Calculator = calc = gcnew Calculator(); Application::DoEvents(); calc->PerformCalculation(myValues); Application::DoEvents(); } };
D. public ref class CalculationValues {...}; public ref class Calculator { public : void PerformCalculation() {} }; public ref class ThreadTest{ private : void DoWork (){ CalculationValues= myValues = gcnew CalculationValues(); Calculator = calc = gcnew Calculator(); Thread= newThread = gcnew Thread( gcnew ThreadStart(calc, &Calculator::PerformCalculation)); newThread->Start(myValues); } };
Answer: A
QUESTION 327
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(){ CalculationValues myValues = new CalculationValues(); Thread newThread = new Thread( new ThreadStart(PerformCalculation)); newThread.Start(myValues); }
B. private void PerformCalculation (CalculationValues values) { ... } private void DoWork(){ CalculationValues myValues = new CalculationValues(); Application.DoEvents(); PerformCalculation(myValues); Application.DoEvents(); }
C. private void PerformCalculation() { ... } private void DoWork(){ CalculationValues myValues = new CalculationValues(); ThreadStart delStart = new ThreadStart(PerformCalculation); Thread newThread = new Thread(delStart); if (newThread.IsAlive) { newThread.Start(myValues); } }
D. private void PerformCalculation(object values) { ... } private void DoWork(){ CalculationValues myValues = new CalculationValues(); Thread newThread = new Thread( new ParameterizedThreadStart(PerformCalculation)); newThread.Start(myValues); }
Answer: D
QUESTION 328
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. [OnDeserializing] internal void UpdateValue(SerializationInfo info) { info.AddValue("currentRate", GetCurrentRate()); }
C. [OnSerializing] internal void UpdateValue(SerializationInfo info) { info.AddValue("currentRate", GetCurrentRate()); }
D. [OnDeserialized] internal void UpdateValue(StreamingContext context) { currRate = GetCurrentRate(); }

Answer: D
QUESTION 329
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. (Click the Exhibit button.) Which code segment should you choose?
A. RectangleF rectangle = new RectangleF(10f, 10f, 450f, 25f); SolidBrush rectangleBrush = new SolidBrush(Color.AliceBlue); Pen rectanglePen = new Pen(rectangleBrush); Graphics g = this.CreateGraphics();
B. DrawRectangle(rectangleBrush, rectangle);
C. Rectangle rectangle = new Rectangle(10, 10, 450, 25); LinearGradientBrush rectangleBrush = new LinearGradientBrush(rectangle, Color.AliceBlue, Color.CornflowerBlue,

LinearGradientMode.ForwardDiagonal);
Pen rectanglePen = new Pen(rectangleBrush); Graphics g = this.CreateGraphics();
D. DrawRectangle(rectanglePen, rectangle);
E. RectangleF rectangle = new RectangleF(10f, 10f, 450f, 25f); Point[] points = new Point[] {new Point(0, 0), new Point(110, 145)}; LinearGradientBrush rectangleBrush = new LinearGradientBrush(rectangle, Color.AliceBlue, Color.CornflowerBlue, LinearGradientMode.ForwardDiagonal); Pen rectanglePen = new Pen(rectangleBrush); Graphics g = this.CreateGraphics();
F. DrawPolygon(rectanglePen, points);
G. Rectangle rectangle = new Rectangle(10, 10, 450, 25); LinearGradientBrush rectangleBrush = new LinearGradientBrush(rectangle, Color.AliceBlue, Color.CornflowerBlue, LinearGradientMode.ForwardDiagonal); Pen rectanglePen = new Pen(rectangleBrush); Graphics g = this.CreateGraphics();
H. FillRectangle(rectangleBrush, rectangle);

Answer: D
QUESTION 330
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); netStream->Write(dataToSend, 0, (int) memStream->Length);
B. MemoryStream= memStream = gcnew MemoryStream(8192); memStream->Write(dataToSend, 0, (int) netStream->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 QUESTION 331

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 = new ManagementObjectSearcher(); searcher.Scope = new ManagementScope("Win32_Service"); foreach (ManagementObject svc in searcher.Get()) { if ((string)svc["State"] == "Paused") { Collection1.Add(svc["DisplayName"]); } }
B. ManagementObjectSearcher searcher = new ManagementObjectSearcher( "Select * from Win32_Service", "State = 'Paused'"); foreach (ManagementObject svc in searcher.Get()) { Collection1.Add(svc["DisplayName"]); }
C. ManagementObjectSearcher searcher = new ManagementObjectSearcher( "Select * from Win32_Service where State = 'Paused'"); foreach (ManagementObject svc in searcher.Get()) { Collection1.Add(svc["DisplayName"]); }
D. ManagementObjectSearcher searcher = new ManagementObjectSearcher( "Select * from Win32_Service"); foreach (ManagementObject svc in searcher.Get()) { if ((string) svc["State"] == "'Paused'") { Collection1.Add(svc["DisplayName"]); } }

Answer: C
QUESTION 332
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= buffer = gcnew array(dept->Capacity); MemoryStream= stream = gcnew MemoryStream(buffer); for each (Object= o in dept) { formatter->Serialize(stream, o); }
B.SoapFormatter= formatter = gcnew SoapFormatter(); MemoryStream= stream = gcnew MemoryStream(); for each (Object= o in dept) { formatter->Serialize(stream, o); }
C.SoapFormatter= formatter = gcnew SoapFormatter(); array= buffer = gcnew array(dept->Capacity); MemoryStream= stream = gcnew MemoryStream(buffer); formatter->Serialize(stream, dept);
D.SoapFormatter= formatter = gcnew SoapFormatter(); MemoryStream= stream = gcnew MemoryStream(); formatter->Serialize(stream, dept);

Answer: D
QUESTION 333
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.ReadLine();
B. string result = string.Empty; StreamReader reader = new StreamReader("Message.txt"); while (!reader.EndOfStream) { result += reader.ToString(); }
C. string result = null; StreamReader reader = new StreamReader("Message.txt"); result = reader.Read().ToString();
D. string result = null; StreamReader reader = new StreamReader("Message.txt"); result = reader.ReadToEnd();
Answer: D QUESTION 334

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.String= dateString = DateTimeFormatInfo::CurrentInfo ::GetMonthName(DateTime::Today::Month); String= dateString = DateTime::Today::Month::ToString("es-MX");
C.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();

Answer: A
QUESTION 335
You are creating a class to compare a specially-formatted string. The default collation comparisons do not apply. You need to implement the IComparable interface. Which code segment should you use?
A. public class Person : IComparable{ public int CompareTo(string other){ ... } }
B. public class Person : IComparable{ public bool CompareTo(string other){ ... } }
C. public class Person : IComparable{ public bool CompareTo(object other){ ... } }
D. public class Person : IComparable{ public int CompareTo(object other){

... } }

Answer: A
QUESTION 336
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 : IDictionary
B. class MyDictionary { ... } Dictionary t = new Dictionary(); MyDictionary dictionary = (MyDictionary)t;
C. class MyDictionary : Dictionary
D. class MyDictionary : HashTable

Answer: C
QUESTION 337
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", CharSet = CharSet.Unicode)]

public static extern bool MessageBox(int hWnd String text, String caption, uint type); }
C. [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);}
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: B
QUESTION 338
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.Move the loop code from the OnStart method into the DoWork method.
D.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.

Answer: D
QUESTION 339
You are developing a method to decrypt data that was encrypted with the Triple DES Algorithm. The method accepts the following parameters: The byte array to be decrypted, which is named cipherMessage The key, which is named key An initialization vector, which is named iv You need to decrypt the message by using the TripleDES class and place the result in a string.

Which code segment should you use?
A.TripleDES des = new TripleDESCryptoServiceProvider(); ICryptoTransform crypto = des.CreateDecryptor(); MemoryStream cipherStream = new MemoryStream(cipherMessage); CryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read); string message; message = new StreamReader(cryptoStream).ReadToEnd();
B.TripleDES des = new TripleDESCryptoServiceProvider(); ICryptoTransform crypto = des.CreateDecryptor(key, iv); MemoryStream cipherStream = new MemoryStream(cipherMessage);C ryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read); string message; message = new StreamReader(cryptoStream).ReadToEnd();
C.TripleDES des = new TripleDESCryptoServiceProvider(); des.BlockSize = cipherMessage.Length; ICryptoTransform crypto = des.CreateDecryptor(key, iv); MemoryStream cipherStream = new MemoryStream(cipherMessage); CryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read); string message; message = new StreamReader(cryptoStream).ReadToEnd(); "
D.TripleDES des = new TripleDESCryptoServiceProvider(); des.FeedbackSize = cipherMessage.Length; ICryptoTransform crypto = des.CreateDecryptor(key, iv); MemoryStream cipherStream = new MemoryStream(cipherMessage); CryptoStream cryptoStream = new CryptoStream( cipherStream, crypto, CryptoStreamMode.Read); string message; message = new StreamReader(cryptoStream).ReadToEnd();

Answer: B
QUESTION 340
You are creating an application that retrieves values from a custom section of the application configuration file. The custom section uses XML as shown in the following block.
QUESTION 341

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 searchList
The string for which to search, which is named searchValue
You need to write the code.
Which code segment should you use?
A. CompareInfo comparer = new CultureInfo("it-IT").CompareInfo; if (comparer.IndexOf(searchList, searchValue) > 0) { return true; } else { return false; }
B. CultureInfo comparer = new CultureInfo("it-IT"); if (searchList.IndexOf(searchValue) > 0) { return true; } else { return false; }
C. CompareInfo comparer = new CultureInfo("it-IT").CompareInfo; return comparer.Compare(searchList, searchValue);
D. return searchList.IndexOf(searchValue);

Answer: A
QUESTION 342
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 IDictionary{}; B.public ref class MyDictionary : public Dictionary{}; C.public ref class MyDictionary : public Hashtable{}; D.public ref class MyDictionary{};

Dictionary t = gcnew Dictionary(); MyDictionary dictionary =
(MyDictionary)t;

Answer: B
QUESTION 343
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 Boolean Implements IComparable(Of String).CompareTo ...
End Function
End Class
B.Public Class Person
Implements IComparable(Of String)
Public Function CompareTo(ByVal other As String) As _ Integer Implements IComparable(Of
String).CompareTo
...
End Function
End Class
C.Public Class Person
Implements IComparable(Of String)
Public Function CompareTo(ByVal other As Object) _
As Boolean Implements IComparable(Of String).CompareTo ...
End Function
End Class
D.Public Class Person
Implements IComparable(Of String)
Public Function CompareTo(ByVal other As Object) As _ Integer Implements IComparable(Of
String).CompareTo
...
End Function
End Class
Answer: B
QUESTION 344
You are creating a new security policy for an application domain. You write the following lines of code.

PolicyLevel policy = PolicyLevel.CreateAppDomainLevel();
PolicyStatement noTrustStatement =
new PolicyStatement(
policy.GetNamedPermissionSet("Nothing"));
PolicyStatement fullTrustStatement =
new PolicyStatement(
policy.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. CodeGroup group1 = new FirstMatchCodeGroup( new AllMembershipCondition(), noTrustStatement); CodeGroup group2 = new UnionCodeGroup( new ZoneMembershipCondition(SecurityZone.Trusted), fullTrustStatement); group1.AddChild(group2);
B. CodeGroup group = new FirstMatchCodeGroup( new AllMembershipCondition(), noTrustStatement);
C. CodeGroup group = new UnionCodeGroup( new ZoneMembershipCondition(SecurityZone.Trusted), fullTrustStatement);
D. CodeGroup group1 = new FirstMatchCodeGroup( new ZoneMembershipCondition(SecurityZone.Trusted), fullTrustStatement); CodeGroup group2 = new UnionCoderoup( new AllMembershipCondition(), noTrustStatement); group1.AddChild(group2);
Answer: A QUESTION 345

You are developing a server application that will transmit sensitive information on a network. You create an X509Certificate object named certificate and a TcpClient object named client. You need to create an SslStream to communicate by using the Transport Layer Security 1.0 protocol. Which code segment should you use?
A.SslStream= ssl = gcnew SslStream(Client->GetStream()); ssl->AuthenticateAsServer(certificate, false, SslProtocols::None, true);
B.SslStream =ssl = gcnew SslStream(Client->GetStream()); ssl->AuthenticateAsServer(certificate, false, SslProtocols::Tls, true);
C.SslStream =ssl = gcnew SslStream(Client->GetStream()); ssl->AuthenticateAsServer(certificate, false, SslProtocols::Ssl3, true);
D.SslStream =ssl = gcnew SslStream(Client->GetStream()); ssl->AuthenticateAsServer(certificate, false, SslProtocols::Ssl2, true);

Answer: B
QUESTION 346
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 searchList
The string for which to search, which is named searchValue
You need to write the code.
Which code segment should you use?
A. CompareInfo= comparer = gcnew CultureInfo("it-IT")::CompareInfo; return comparer->Compare(searchList, searchValue);
B. CompareInfo= comparer = gcnew CultureInfo("it-IT")::CompareInfo; if (comparer->IndexOf(searchList, searchValue) > 0) { return true;
} else { return false; }
C. CultureInfo= comparer = gcnew CultureInfo("it-IT"); if (searchList->IndexOf(searchValue)

> 0) {
return true;
} else {
return false;
}
D. return searchList->IndexOf(searchValue);

Answer: B
QUESTION 347
You write the following custom exception class named CustomException.
public class CustomException : ApplicationException {
public static int COR_E_ARGUMENT =
unchecked((int)0x80070057);
public CustomException(string msg) : base(msg) {
HResult = COR_E_ARGUMENT;
}
}
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 CustomException.COR_E_ARGUMENT;
B. throw new CustomException("Argument is out of bounds");
C. Marshal.ThrowExceptionForHR( CustomException.COR_E_ARGUMENT);
D. return Marshal.GetExceptionForHR( CustomException.COR_E_ARGUMENT);
Answer: B QUESTION 348

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= 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: [XmlArray(ElementName="Employees")]
B. Insert the following code between lines 3 and 4 of the code segment: [XmlElement(Type = __typeof(Employee))] and Insert the following code segment between lines 8 and 9 of the code segment: [XmlElement(Type = __typeof(Manager))]
C. Insert the following code between lines 14 and 15 of the code segment: [XmlArrayItem(Type = __typeof(Employee))] [XmlArrayItem(Type = __typeof(Manager))]
D. Insert the following code between lines 14 and 15 of the code segment: [XmlElement(Type = __typeof(Employees))]

Answer: C
QUESTION 349
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 outStream = new MemoryStream(); GZipStream zipStream = new GZipStream(outStream, CompressionMode.Compress); zipStream.Write(document, 0, document.Length); zipStream.Close(); return outStream.ToArray();
B. MemoryStream inStream = new MemoryStream(document); GZipStream zipStream = new GZipStream(inStream, CompressionMode.Compress); byte[] result = new byte[document.Length]; zipStream.Write(result, 0, result.Length); return result;
C. MemoryStream stream = new MemoryStream(document); GZipStream zipStream = new GZipStream(stream, CompressionMode.Compress); zipStream.Write(document, 0, document.Length); zipStream.Close();

return stream.ToArray();
D. MemoryStream inStream = new MemoryStream(document); GZipStream zipStream = new GZipStream(inStream, CompressionMode.Compress); MemoryStream outStream = new MemoryStream(); int b; while ((b = zipStream.ReadByte()) != -1) { outStream.WriteByte((byte)b); } return outStream.ToArray();

Answer: A
QUESTION 350
DRAG DROP
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 during creation.
What should you do?
To answer, move the three appropriate actions from the list of actions to the answer area and arrange them in the correct order.

Answer: QUESTION 351


DRAG DROP
You are creating an application that provides information about the local computer. The application contains a form that lists each logical drive along with the drive properties, such as type, volume label, and capacity. You need to write a procedure that retrieves properties of each logical drive on the local computer. What should you do? To answer, move the three appropriate actions from the list of actions to the answer area and arrange them in
the correct order.

Answer: QUESTION 352


DRAG DROP 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 . What should you do? To answer, you need to move the three appropriate actions from the list of actions to the
answer area and arrange them in the correct order.

Answer: