Вы находитесь на странице: 1из 273

Microsoft (70-536) TS: Microsoft .

NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-069

____________________________________________________________________________________________________________________ You are writing a graphical analysis application by using the .NET Framework. You need to save a graphic object from the application. A graphic object is a collection of x and y points, each represented by using a single precision floating point number. You must minimize the disk space taken by the saved object. Which class should you use? 1. StreamWriter 2. BinaryWriter <Correct> 3. StringWriter 4. TextWriter Explanation : The BinaryWriter class stores the data in a binary format, which provides the most compact format for storing data among the given classes. The StreamWriter, StringWriter, and TextWriter classes store the data in the text format, which takes more storage space than the binary format. These classes are useful for storing data in human readable format. But if human-readability is not a concern and disk space must be minimized, you should use the BinaryWriter class. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Manage .NET Framework application data by using Reader and Writer classes. (Refer System.IO namespace) BinaryWriter Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.binarywriter.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-051

____________________________________________________________________________________________________________________ You are creating a class library application by using the .NET Framework. You create a class named Area: class Area { // Additional code goes here } In your code, you create a SortedList collection with the Area objects as keys. The SortedList collection must be able to sort the items in a collection so that they are arranged in order from biggest to smallest area. No item has exactly the same area as another item. You need to implement a custom sort order. What should you do? 1. Modify the Area class to implement the IComparer interface. 2. Modify the Area class to implement the IEquatable interface. 3. Modify the Area class to implement the IConvertible interface. 4. Modify the Area class to implement the IComparable interface. <Correct>

Explanation : You should modify the Area class to implement the IComparable interface. The IComparable interface implements a CompareTo method, which determines how objects of the class that implements the IComparable interface should be sorted when they are added to a SortedList. You should not modify the Area class to implement the IEquatable interface. The IEquatable interface is only used to check two type instances for equality. To determine the correct sort order, you must compare two objects to find the bigger and smaller objects. You should not modify the Area class to implement the IComparer interface. The SortedList class has a constructor that accepts an object that implements the IComparer interface. When this constructor is used, the object's implementation defines the sort order. However, implementing the IComparer interface on objects that will be used as keys in the collection is not the way to define the sort order. You should not modify the Area class to use the IConvertible interface. Implementing the IConvertible interface allows you to define methods that allow you to convert the value of the Area object to an equivalent value of any other type supported by the common language runtime. In this case, comparison rather than conversion is a requirement. Objective: Developing applications that use system types and collections Sub Objective(s): Implement .NET Framework interfaces to cause components to comply with standard contracts. (Refer System namespace) IComparable Generic Interface MSDN Link: http://msdn2.microsoft.com/en-us/library/4d7sx9hd(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-011

____________________________________________________________________________________________________________________ You are developing a .NET Framework application that uses a Dictionary generic class. You write the following code to create the dictionary. string sName = ""; string hmaNum; Dictionary<string, string> sailors = new Dictionary<string, string>(); hmaNum = txtNumber.Text; sName = txtName.Text; You need to write code that checks whether a key exists before adding a record and displays a message with the value currently associated with that key if it exists. Your solution must offer the best performance. Which code segment should you use? 1. try { sailors.Add(hmaNum, sName) } catch { MessageBox.Show("The HMA number " + hmaNum + " is assigned to ' + sailors.item(hmaNum)); } 2. string sCurrentName=""; if (sailors.TryGetValue(hmaNum, out sCurrentName)) { MessageBox.Show("The HMA number " + hmaNum + " is assigned to " + sCurrentame); } <Correct> 3. try { sailors.Add(hmaNum, sName) } catch (KeyNotFoundException) { MessageBox.Show("The HMA number " + hmaNum + " is assigned to ' + sCurrentName); } 4. if (sailors.ContainsKey(hmaNum) { sailors.Add(hmaNum, sName) } else { MessageBox.Show("The HMA number " + hmaNum + " is assigned to ' + sailors.Item(hmaNum)); } Explanation : Using the TryGetValue method is an efficient way to check for a key in a Dictionary and return its current value. If a key is not in the dictionary, this method returns False. If the key is in the dictionary, the method returns True. Using the TryGetValue method is more efficient than catching the exception thrown by the Add method when you try to add a key that already exists. Whenever possible, you should use exceptions only to handle unexpected events, not routine checks. Although the ContainsKey method is an efficient way to check if a key exists, the code shown will produce the opposite result from what you want because the element will be added when ContainsKey evaluates to True. Objective: Developing applications that use system types and collections

Sub Objective(s): Improve type safety and application performance in a .NET Framework application by using generic collections. (Refer System.Collections.Generic namespace) Dictionary Generic Class MSDN Link: http://msdn2.microsoft.com/en-us/library/xfhwa508(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-083

____________________________________________________________________________________________________________________ You are writing an application that saves configuration settings in the configuration file. You need to modify the settings that will apply to all users of the application. The settings are in a custom section named LookAndFeel. You have defined the class for the section as LookAndFeelSection and inherited from ConfigurationSection. What code should you use to open the file and retrieve the settings? 1. Configuration cfgFile; LookAndFeelSection cfgSection; cfgFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); cfgSection = cfgFile.GetSection("LookAndFeel"); <Correct> 2. ConfigurationSettings cfgFile = new ConfigurationSettings(); ConfigurationSection cfgSection; cfgSection =cfgFile.GetConfig("LookAndFeel"); 3. Configuration cfgFile; LookAndFeelSection cfgSection; cfgFile = ConfigurationManager.OpenMachineConfiguration(); cfgSection = cfgFile.GetSection("LookAndFeel"); 4. LookAndFeelSection cfgSection; cfgSection = ConfigurationSettings.GetConfig("LookAndFeel"); Explanation : You should use the following code: Configuration cfgFile; LookAndFeelSection cfgSection; cfgFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); cfgSection = cfgFile.GetSection("LookAndFeel"); The ConfigurationManager class implements an OpenExeConfiguration method that allows you to retrieve a reference to the application's configuration file or a user-specific configuration file, depending on the value passed as the argument. To open the application configuration file, use the ConfigurationUserLevel.None value. After you have a reference to the file, you can use the GetSection method to return the specific section you want to modify. You should not use the following code: Configuration cfgFile; LookAndFeelSection cfgSection; cfgFile = ConfigurationManager.OpenMachineConfiguration(); cfgSection = cfgFile.GetSection("LookAndFeel"); The OpenMachineConfiguration method opens the machine.cfg file, not the application-specific file. You should not use the following code: LookAndFeelSection cfgSection; cfgSection = ConfigurationSettings.GetConfig("LookAndFeel"); The ConfigurationSettings class has been deprecated. Also, the GetConfig method returns an object of type ConfigurationSection. You should not use the following code: ConfigurationSettings cfgFile = new ConfigurationSettings(); ConfigurationSection cfgSection; cfgSection =cfgFile.GetConfig("LookAndFeel");

The ConfigurationSettings class has been deprecated. Also, the GetConfig method is a shared method, so it cannot be called on an instance of the ConfigurationSettings class. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Embed configuration management functionality into a .NET Framework application (Refer System.Configuration namespace) ConfigurationManager Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.configuration.configurationmanager(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-048

____________________________________________________________________________________________________________________ You are developing a .NET Framework application that uses the LinkedList generic class. You use the following code to add items to the LinkedList: LinkedList<string> list = new LinkedList<string>(); list.AddLast("Monday"); list.AddLast("Tuesday"); list.AddLast("Wednesday"); list.AddLast("Thursday"); list.AddLast("Friday"); You need to write code that allows you to print all the items in the linked list. Your code must generate five lines of output, where the name of each day is printed on a separate line as shown below: Monday Tuesday Wednesday Thursday Friday Which code segment should you use? 1. IEnumerator<string> en = list.GetEnumerator(); do { Console.WriteLine(en.Current); } while (en.MoveNext()); 2. IEnumerator<string> en = list.GetEnumerator(); while(en.MoveNext()) { Console.WriteLine(en.Current); } <Correct> 3. IEnumerator<string> en = list.GetEnumerator(); while(en.MoveNext()) { Console.Write(en.Current); } 4. IEnumerator<string> en = list.GetEnumerator(); do { en.MoveNext(); Console.WriteLine(en.Current); } while (en.MoveNext()); 5. IEnumerator<string> en = list.GetEnumerator(); en.MoveNext(); do { Console.WriteLine(en.Current); } while (!en.MoveNext()); Explanation : You should use the following code segment:

IEnumerator<string> en = list.GetEnumerator(); while(en.MoveNext()) { Console.WriteLine(en.Current); } The first call to the MoveNext method positions the enumerator at the first element. The Current property returns the element at the current position. When the enumerator is positioned past the last element, it returns false, which causes the while loop to terminate. The following code does not produce the desired output. It instead prints only the first element, "Monday". The problem lies in the condition specified with the while keyword. Because of the use of the not operator (!), the expression returns a false value when the enumerator is not yet past the last element: IEnumerator<string> en = list.GetEnumerator(); en.MoveNext(); do { Console.WriteLine(en.Current); } while (!en.MoveNext()); The following code does not produce the desired output. It instead prints only alternate values, "Monday", "Wednesday", and "Friday". The problem lies with invoking the MoveNext method twice within the while loop: IEnumerator<string> en = list.GetEnumerator(); do { en.MoveNext(); Console.WriteLine(en.Current); } while (en.MoveNext()); The following code does not produce the desired output. It instead prints an extra blank line and, therefore, prints six lines of output instead of five lines. When the enumerator is first instantiated, Current points to the location before the first record. It does not point to the first record until MoveNext is called. IEnumerator<string> en = list.GetEnumerator(); do { Console.WriteLine(en.Current); } while (en.MoveNext()); The following code does not produce the desired output. It instead prints all the items on the same line. The problem lies with the use of the Console.Write method instead of the Console.WriteLine method: IEnumerator<string> en = list.GetEnumerator(); while(en.MoveNext()) { Console.Write(en.Current); } Objective: Developing applications that use system types and collections Sub Objective(s): Improve type safety and application performance in a .NET Framework application by using generic collections. (Refer System.Collections.Generic namespace) IEnumerator Generic Interface MSDN Link: http://msdn2.microsoft.com/en-us/library/78dfe2yb(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-017

____________________________________________________________________________________________________________________ You are developing a mathematical library by using the .NET Framework. You write the following code in your program: foreach (int i in Power(2, 8)) { Console.Write("{0} ", i); } Here the method Power displays the powers of 2 up to the exponent 8 (2 to the 8th power). For example, the following output is desired: 2 4 8 16 32 64 128 256 You must write code for the Power method. Which code should you use? 1. public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; } yield return result; } 2. public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; } return result; } 3. public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; return result; } } 4. public static IEnumerable Power(int number, int exponent) { int counter = 0; int result = 1; while (counter++ < exponent) { result = result * number; yield return result; } } <Correct> Explanation : An iterator is a method, get accessor, or operator that enables you to support foreach iteration in a class or struct without having to implement the entire IEnumerable interface. The yield

keyword is used in an iterator block to provide a value to the enumerator object or to signal the end of iteration. It takes one of the following forms: yield return expression; yield break; Writing yield outside the while block will only display one value: 256. You must write yield inside the while block to get correct results. Using a return statement without the yield is incorrect because the method's return type is IEnumerable rather than a numeric data type. Objective: Developing applications that use system types and collections Sub Objective(s): Manage a group of associated data in a .NET Framework application by using collections (Refer System.Collections namespace) Using Iterators (C# Programming Guide) MSDN Link: http://msdn2.microsoft.com/en-us/library/65zzykke(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-068

____________________________________________________________________________________________________________________ You are working as a developer on a financial application. You are developing a module that backs up the critical data on a separate hard drive. You need to find the type of the file system (such as FAT or NTFS) and the free space on the drive. The application should not take the user disk quota into account. Which properties of the DriveInfo class should you use? (Each correct answer presents part of the solution. Choose two.) 1. DriveType 2. VolumeLabel 3. DriveFormat <Correct> 4. TotalSize 5. TotalFreeSpace 6. AvailableFreeSpace Explanation : The DriveFormat property of the DriveInfo class specifies the type of the file system (such as FAT or NTFS). The TotalFreeSpace property specifies the total available free space on the hard drive. You should not use the DriveType property because the DriveType property specifies the type of drive such as a CD-ROM drive, fixed drive, or removable drive. You should not use the VolumeLabel property because the VolumeLabel property specifies the volume label string assigned to the drive (for example "C_Drive" or "Finance_Data"). You should not use the AvailableFreeSpace property because this property takes the user disk quota into account. You should not use the TotalSize property because this property specifies the total size of the disk, not just the free space. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Access files and folders by using the File System classes. (Refer System.IO namespace) DriveInfo Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.driveinfo(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-096

____________________________________________________________________________________________________________________ You are developing a .NET Framework component that publishes its own custom performance counter. The component might be used by multiple threads on the computer. You want to increase the value of a performance counter by 5. You need to minimize the amount of code that you need to write. However, you need to ensure that counter modifications made on other threads are not lost. Which method or property of the PerformanceCounter object should you use? 1. Increment 2. RawValue 3. NextValue 4. IncrementBy<Correct> Explanation : The IncrementBy method is the best way to increase or decrease the value of a counter by a specified amount. The IncrementBy method is thread safe. The Increment method increases the value of a counter by one. Therefore to increase by five, you would need to call the Increment method five times. You should not use the RawValue method. Although it provides better performance than IncrementBy and Increment, it is not thread safe. If multiple threads attempt to change the value at the same time, data could be lost. The NextValue method returns the value of the counter and cannot be used to increase the value of the counter. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Manage system processes and monitor the performance of a .NET Framework application by using the diagnostics functionality of the .NET Framework 2.0. (Refer System.Diagnostics namespace) PerformanceCounter Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.performancecounter(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-040

____________________________________________________________________________________________________________________ You are developing a new customer information system by using the .NET Framework. You need to provide locale-specific services to customers. You must use a unique country identifier that can be used as a key to access a database record that contains specific information about a country. You must use minimum storage for storing the key value. What should you use in your code as an identifier for a country? 1. RegionInfo.GetHashCode 2. CultureInfo.GetHashCode 3. RegionInfo.Name 4. CultureInfo.Name Explanation : You should use the RegionInfo.Name property. The RegionInfo.Name property gets the name or ISO 3166 two-letter country/region code for the current RegionInfo object. As required by the scenario, this value can be used as a key to access a database record that contains specific information about a country. Using the GetHashCode property is not correct because it generates a hash value that can be used to tell whether the two RegionInfo or CultureInfo objects are the same or not. The CultureInfo.Name property returns the culture name instead of the country name. It may contain additional information such as the language code and the region code in addition to the country code. This does not meet the requirement of using the minimum storage for the key value. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) RegionInfo Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.globalization.regioninfo.aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-038

____________________________________________________________________________________________________________________ You are developing an enterprise application by using the .NET Framework. You write the following code in your application (line numbers are for reference purposes only): 01 string num; 02 int val; 03 num = " (37)"; 04 At line 04, you must write code that correctly parses the string value and assigns the results to the integer variable named val. When the code executes, the variable val must hold a value of -37. Which code should you use? 1. val = int.Parse(num, NumberStyles.AllowParentheses & NumberStyles.AllowLeadingWhite) 2. val = int.Parse(num, NumberStyles.AllowLeadingSign & NumberStyles.AllowLeadingWhite & NumberStyles.AllowTrailingSign) 3. val = int.Parse(num, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingSign) 4. val = int.Parse(num, NumberStyles.AllowParentheses | NumberStyles.AllowLeadingWhite) <Correct> Explanation : You should use the following statement to correctly parse the string: val = int.Parse(num, NumberStyles.AllowParentheses | NumberStyles.AllowLeadingWhite) The NumberStyles.AllowParentheses value indicates that the numeric value in the string can be enclosed within a single set of parentheses. The parentheses are evaluated in such a way that a negative number is returned instead of a positive number. The NumberStyles.AllowLeadingWhite value indicates that all white-space characters in front of the number should be ignored during parsing. The attributes of NumberStyles are set by using the bitwise inclusive OR (|) of the field flags. If you use the bitwise AND (&), you will reset the field flags instead of setting them. Using NumberStyles.AllowLeadingSign and NumberStyles.AllowTrailing sign instead of NumberStyles.AllowParentheses is incorrect because the NumberStyles.AllowLeadingSign value indicates that the number can be preceded by a sign, such as a - sign. In this case there is no leading sign in the source string. The NumberStyles.AllowTrailingSign value indicates that the string can have a sign following the number. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) References : NumberStyles Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/4twfbc26(en-US,VS.80).aspx NumberFormatInfo Class MSDN Link: http://msdn2.microsoft.com/en-us/library/2xdwt6xx(en-US,VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-015

____________________________________________________________________________________________________________________ You are creating the client part of a client/server application. The application must pass data over an unsecured network. You must verify the server's identity and protect the confidentiality of the data. Company policy requires that communications over an unsecured network use Transport Layer Security (TLS) and mutual certificate authentication. You have instantiated an object named secureStream of type SslStream and an X509CertificateCollection named ccert. You need to write code to allow the client to negotiate authentication with the server. What code should you use? 1. secureStream.AuthenticateAsServer("myserver", ccert, SslProtocols.None, false); 2. secureStream.AuthenticateAsServer("myserver", ccert, SslProtocols.Ssl3, true); 3. secureStream.AuthenticateAsClient("myserver", ccert, SslProtocols.Tls, true); 4. secureStream.AuthenticateAsClient("myserver", ccert, SslProtocols.Default, false); Explanation : You should use the code: secureStream.AuthenticateAsClient("myserver", ccert, SslProtocols.Tls, true); The AuthenticateAsClient method is called by the client application to negotiate authentication with the server. The Tls member of the SslProtocols enumeration specifies that only Transport Layer Security (TLS) should be supported. You should not use the AuthenticateAsServer method. The AuthenticateAsServer method is called on the server. You should not specify SslProtocols.None. Doing so allows any Secure Sockets Layer (SSL) protocol to be negotiated. You should not specify SslProtocols.Ssl3. Doing so causes only SSL 3.0 to be supported. You should not specify SslProtocols.Default. Doing so causes both SSL 3.0 and TLS to be supported. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement a custom authentication scheme by using the System.Security.Authentication classes. (Refer System.Security.Authentication namespace) References : SslProtocols Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.authentication.sslprotocols(vs.80).aspx SslStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.net.security.sslstream(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-120

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code in your application (line numbers are for reference only): 01: FileSecurity fs = File.GetAccessControl(@"c:\root\config.crn"); 02: string ownerName = String.Empty; 03: Console.WriteLine("Owner name: {0}", ownerName); You need to write additional code before line 03 that allows you to print a user-friendly owner name of the file C:\root\config.crn. Which code segment should you use? 1. NTAccount acc = (NTAccount) fs.GetOwner(typeof(NTAccount)); ownerName = acc.Value; <Correct> 2. SecurityIdentifier sid = (SecurityIdentifier) fs.GetOwner(typeof(SecurityIdentifier)); ownerName = sid.Value; 3. GenericPrincipal acc = (GenericPrincipal) fs. GetOwner (typeof(GenericPrincipal)); ownerName = acc.Identity.Name; 4. WindowsPrincipal acc = (WindowsPrincipal) fs. GetOwner (typeof(WindowsPrincipal)); ownerName = acc.Identity.Name; Explanation : The GetOwner method of the FileSecurity class gets the owner associated with the given file. The Value property of the NTAccount class represents a user-friendly owner name. Therefore, you should use the following code segment: NTAccount acc = (NTAccount) fs.GetOwner(typeof(NTAccount)); ownerName = acc.Value; The Value property of the SecurityIdentifier class provides a long string containing the security identifier corresponding to a Windows account. Therefore, you should not use the following code segment: SecurityIdentifier sid = (SecurityIdentifier) fs.GetOwner(typeof(SecurityIdentifier)); ownerName = sid.Value; The GetOwner method returns an Identity object, not a Principal object. Therefore, you cannot use either of the following blocks of code: WindowsPrincipal acc = (WindowsPrincipal) fs. GetOwner (typeof(WindowsPrincipal)); ownerName = acc.Identity.Name; GenericPrincipal acc = (GenericPrincipal) fs. GetOwner (typeof(GenericPrincipal)); ownerName = acc.Identity.Name; Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement access control by using the System.Security.AccessControl classes. References : SecurityIdentifier Class MSDN

Link: http://msdn2.microsoft.com/en-us/library/system.security.principal.securityidentifier(vs.80).aspx ObjectSecurity.GetOwner Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.objectsecurity.getowner(vs. 80).aspx NTAccount Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.principal.ntaccount(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-041

____________________________________________________________________________________________________________________ You are creating a class named FileWatcher that will watch several different paths for a new file. When a new file is created, it will raise the FileArrived event. The path of the new file will be passed as part of the event. What code would you use to declare the delegate for the event? 1. public class FileEventArgs : EventArgs { private string m_Path; public string Path; { get{return m_Path;} set{m_Path = value;} } } public event EventHandler FileArrivedEvent; 2. public class FileEventArgs { private string m_Path; public string Path; { get{return m_Path;} set{m_Path = value;} } } public delegate void FileArrivedEvent; 3. public class FileEventArgs { private string m_Path; public string Path; { get{return m_Path;} set{m_Path = value;} } } public event EventHandler FileArrivedEvent(object sender, FileEventArgs e); 4. public class FileEventArgs : EventArgs { private string m_Path; public string Path; { get{return m_Path;} set{m_Path = value;} } } public delegate void FileArrivedEvent(object sender, FileEventArgs e); <Correct> Explanation : You should declare the delegate for the event by using the following code: public class FileEventArgs : EventArgs { private string m_Path;

public string Path; { get{return m_Path;} set{m_Path = value;} } } public delegate void FileArrivedEvent(object sender, FileEventArgs e); The FileEventArgs class is used to pass the file path information when the event is raised. It should inherit from EventArgs. You declare an event's signature using the delegate keyword. When you define a delegate, you must include the arguments it will expect. You should not declare the delegate for the event by using the following code: public event EventHandler FileArrivedEvent(object sender, FileEventArgs e); The event keyword is used to declare a method that will be raised when you do not need to pass event-specific data to the event. For example, if you did not need to pass custom event arguments to the FileArrivedEvent, you could use the event keyword to declare the FileArrived event as follows: public event EventHandler FileArrivedEvent; Objective: Developing applications that use system types and collections Sub Objective(s): Control interactions between .NET Framework application components by using events and delegates. (Refer System namespace) How to: Implement Events in Your Class MSDN Link: http://msdn2.microsoft.com/en-us/library/5z57dxz2(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-110

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code in your application: [ComVisible(false)] public class WhsProcess { [ComVisible(false)] public void GetState() { // Additional code goes here } public string ChangeCase(string s) { return s.ToUpper(); } [ComVisible(true)] private int Increment(int i) { return i++; } protected void UpdateState() { // Additional code goes here } } [ComVisible(true)] public class VarProcess : WhsProcess { public void PrintState() { // Additional code here } } You compile the code and use the Type Library Exporter tool to generate a type library. You need to use the type library in a Component Object Model (COM) application. In the list on the right, select the methods of the VarProcess class that will be visible in the COM application. Place your selections in the list on the left by clicking the items in the list on the right and clicking the arrow button. You may not need to use all of the items from the list on the right. Explanation : The ComVisible attribute controls the visibility of a class or its members to a COM application. By default all public classes and their members are visible to COM. You can change the visibility of all the members of a class by setting the ComVisible attribute at the class level. Any inherited classes do not automatically inherit the ComVisible attribute. So if you have set the ComVisible attribute to False for a base class, its public members will default to COM visibility in the derived class. You must explicitly mark any public members that you do not want exposed to COM applications in a derived class. In this scenario, the PrintState and the ChangeCase methods will be visible to the COM applications. The GetState method is explicitly marked with a ComVisible attribute set to False so it will not be visible to the COM applications in the base class or its derived classes. The private and protected members are never visible to COM even after applying the ComVisible attribute set to True.

Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Expose COM components to the .NET Framework and .NET Framework components to COM. (Refer System.Runtime.InteropServices namespace) ComVisibleAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.comvisibleattribute(vs.80) .aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-006

____________________________________________________________________________________________________________________ You have deployed an application that uses a dependent assembly named TaxCalc. It was written to work with version 1.1.3.6 of TaxCalc, but has been tested successfully through version 2.1.1.0. The user updates the TaxCalc assembly to version 2.1.1.2 and your application no longer runs. Several other applications on the computer use TaxCalc. The other applications on the computer can run with the new version of TaxCalc. You need to ensure that your application works with a supported version of TaxCalc that is installed on the computer. Your solution should allow other applications to continue to use the latest version of TaxCalc. What should you do? 1. Add the following to the application configuration file: <dependentAssembly> <assemblyIdentity type="win32" processorArchitecture="x86" name="TaxCalc" publicKeyToken="12345abcde12345bcdef12345abcde" oldVersion="1.1.3.6-2.1.1.2" newVersion="2.1.1.0" /> </dependentAssembly> 2. Add the following to the application configuration file: <dependentAssembly> <assemblyIdentity type="win32" processorArchitecture="x86" name="TaxCalc" publicKeyToken="12345abcde12345bcdef12345abcde" /> <bindingRedirect oldVersion="2.1.1.2" newVersion="2.1.1.0" /> </dependentAssembly> <Correct> 3. Add the following to the publisher configuration file: <dependentAssembly> <assemblyIdentity type="win32" processorArchitecture="x86" name="TaxCalc" publicKeyToken="12345abcde12345bcdef12345abcde" oldVersion="2.1.1.2" newVersion="1.1.3.6-2.1.1.0" /> </dependentAssembly> 4. Add the following to the publisher configuration file for the TaxCalc assembly: <dependentAssembly> <assemblyIdentity type="win32" processorArchitecture="x86" name="TaxCalc" publicKeyToken="12345abcde12345bcdef12345abcde" /> <bindingRedirect oldVersion="2.1.1.2" newVersion="2.1.1.0" /> </dependentAssembly> Explanation : You should add the following to the application configuration file: <dependentAssembly> <assemblyIdentity type="win32" processorArchitecture="x86" name="TaxCalc" publicKeyToken="12345abcde12345bcdef12345abcde" /> <bindingRedirect oldVersion="2.1.1.2" newVersion="2.1.1.0" /> </dependentAssembly> You use a bindingRedirect to cause an application to load another version of an assembly in place of a specific version. You need to place the element in the application configuration file so that only the specific application is affected. In this case, you want to redirect attempts to load the most recent (unsupported) version of the TaxCalc assembly to the earlier supported version. You should not make the change to the publisher configuration file for TaxCalc. Doing so will affect all applications that use the shared assembly. You should not add the oldVersion and newVersion attributes to the dependentAssembly element.

These attributes should be specified using the bindingRedirect element. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Create a custom Microsoft Windows Installer for .NET Framework components by using the System.Configuration.Install namespace, and configure .NET Framework applications by using configuration files, environment variables, and the .NET Framework Configuration tool (Mscorcfg.msc). How To Build and Service Isolated Applications and Side-by-Side Assemblies for Windows XP MSDN Link: http://msdn2.microsoft.com/en-us/library/ms997620.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-032

____________________________________________________________________________________________________________________ You are developing a Windows Forms application by using the .NET Framework. This application will be used by people in several countries. The application needs to fully support customization of the user interface based on the user's preferences. The customization should include language, currency formats, and date and time formats. You need to write code that compares the name of two customers. The customer names are stored in variables named name1 and name2 respectively.The comparison must be culture-sensitive based on the user's language and regional settings, but case insensitive. Which code segment should you use? 1. String.Compare(name1, name2, false, CultureInfo.InvariantCulture); 2. String.Compare(name1, name2, false, CultureInfo.InstalledUICulture) 3. String.Compare(name1, name2, true, CultureInfo.CurrentCulture); 4. name1.CompareTo(name2) 5. String.Equals(name1, name2) Explanation : You should call the Compare method using the following syntax: String.Compare(name1, name2, true) The default behavior of the String.Compare method is to perform case-sensitive comparisons using the rules of the current culture. To perform a case-insensitive comparison, you should pass true as the third argument. You should not use the following code because it will perform a comparison that is sensitive to culture: String.Compare(name1, name2, false, CultureInfo.InvariantCulture) You should not use the CompareTo method because it performs a case-sensitive and culture-sensitive comparison. You should not use the Equals method because it performs a case-sensitive, culture insensitive comparison. You should not use the following code because it will perform a comparison based on the machine settings, not the user preferences: String.Compare(name1, name2, false, CultureInfo.InstalledUICulture) Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) References : String.Compare method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.string.compare(vs.80).aspx Performing Culture-Insensitive String Comparisons MSDN Link: http://msdn2.microsoft.com/en-us/library/885e1sy1(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-141

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You need to control user access to the directory c:\docs. You must make sure that the Windows user DOMAIN\ProdUser is granted read rights to the c:\docs directory and all of its subdirectories, including the nested directories. The user DOMAIN\ProdUser must not be able to read the contents of any files in these directories. You write the following code in your application (line numbers are for reference only): 01: DirectorySecurity dirSec = Directory.GetAccessControl(@"c:\docs"); 02: dirSec.AddAccessRule(fsaRule); 03: Directory.SetAccessControl(@"c:\docs", dirSec); What additional code must you insert before line 02 to control access for the user DOMAIN\ProdUser? 1. FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); 2. FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); 3. FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); <Correct> 4. FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); Explanation : You should insert the following code segment before line 02: FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); The FileSystemRights.Read value specifies that read-only access needs to be granted. The ContainerInherit inheritance flag requests access for the directory and all of its subdirectories, including the nested directories. The PropogationFlags.None value does not change the default propagation of the access control entries to all the child directories. Inserting the following code is incorrect because the InheritanceFlags.ObjectInherit value affects the access control entries for files rather than directories: FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); Inserting the following code is incorrect because the InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit value affects the access control entries for files as well as directories:

FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); Inserting the following code is incorrect because the PropagationFlags.InheritOnly value allows access to the child directory and any subdirectory nested within the child directory but restricts access to the parent directory (c:\docs): FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement access control by using the System.Security.AccessControl classes. FileSystemAccessRule Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.filesystemaccessrule(vs.80) .aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-028

____________________________________________________________________________________________________________________ You are developing a Windows forms application by using the .NET Framework. This application will be used by regional offices in various countries. You need to customize the application so that the language, calendar, and cultural conventions are changed based on the user's operating system settings. You need to identify the .NET Framework class that you should use for this requirement. Which class should you select? 1. CultureInfo <Correct> 2. RegionInfo 3. DateTimeFormatInfo 4. CharUnicodeInfo 5. TextInfo Explanation : You should use the CultureInfo class to customize the applications settings based on the users locale. The CultureInfo class contains a CurrentCulture property, which you can use to determine how numbers and dates should be formatted and the appropriate sort order for strings based on the geographical region settings. It also includes a CurrentUICulture object that identifies the language and, optionally, the region. RegionInfo is not the correct answer because the RegionInfo class does not allow you to obtain the users regional information preferences or language information. CharUnicodeInfo is not the correct answer because this class only retrieves information about a Unicode character. It does not represent a user's preferences. DateTimeFormatInfo is not the correct answer because the DateTimeFormatInfo class only defines how DateTime values are formatted and displayed, depending on the culture. TextInfo is not the correct answer because this class only affects behavior such as text casing, depending on the culture. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) Using the CultureInfo Class MSDN Link: http://msdn2.microsoft.com/en-us/library/87k6sx8t(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-003

____________________________________________________________________________________________________________________ You are writing code to compare two Byte arrays. You need to determine which bits contain a 1 in both arrays. What code should you use? 1. Byte[] ba1 = {20, 30, 40, 50}; Byte[] ba2 = {25, 35, 45, 55}; BitArray bits1 = new BitArray(4); BitArray bits2 = new BitArray(4); bits1.SetAll(ba1); bits2.SetAll(ba2); BitArray result; int i; result = bits1.Or(bits2); for(i=0; i< result.Count; i++) { if (result[i] == true) { Console.WriteLine(i); } } 2. Byte[] ba1 = {20, 30, 40, 50}; Byte[] ba2 = {25, 35, 45, 55}; BitArray bits1 = new BitArray(ba1); BitArray bits2 = new BitArray(ba2); BitArray result; int i; result = bits1.Or(bits2); for(i=0; i< result.Count; i++) { if (result[i] == true) { Console.WriteLine(i); } } 3. Byte[] ba1 = {20, 30, 40, 50}; Byte[] ba2 = {25, 35, 45, 55}; BitArray bits1 = new BitArray(ba1); BitArray bits2 = new BitArray(ba2); BitArray result; int i; result = bits1.And(bits2); for(i=0; i< result.Count; i++) { if (result[i] == true) { Console.WriteLine(i); } } <Correct> 4. Byte[] ba1 = {20, 30, 40, 50}; Byte[] ba2 = {25, 35, 45, 55}; BitArray bits1 = new BitArray(4); BitArray bits2 = new BitArray(4); bits1.SetAll(ba1); bits2.SetAll(ba2); BitArray result; int i; result = bits1.And(bits2); for(i=0; i< result.Count; i++) { if (result[i] == true)

{ Console.WriteLine(i); } } Explanation : You should use the code: Byte[] ba1 = {20, 30, 40, 50}; Byte[] ba2 = {25, 35, 45, 55}; BitArray bits1 = new BitArray(ba1); BitArray bits2 = new BitArray(ba2); BitArray result; int i; result = bits1.And(bits2); for(i=0; i< result.Count; i++) { if (result[i] == true) { Console.WriteLine(i); } } The BitArray collection stores a list of Boolean values. One constructor accepts an array of Byte values and converts the Byte values to an array of Boolean values that represent the setting for each bit in the byte. For example, a Byte value of 20 would be converted to: False, False True, False, True. The And method of the BitArray collection performs a bitwise And operation and returns the result. In a bitwise And operation, only the bits set to true in both BitArray collections will be set to true in the result. You should not use the code: Byte[] ba1 = {20, 30, 40, 50}; Byte[] ba2 = {25, 35, 45, 55}; BitArray bits1 = new BitArray(ba1); BitArray bits2 = new BitArray(ba2); BitArray result; int i; result = bits1.Or(bits2); for(i=0; i< result.Count; i++) { if (result[i] == true) { Console.WriteLine(i); } } The Or method sets the bits to true if they are true in either or both BitArray collection. You should not use the code: Byte[] ba1 = {20, 30, 40, 50}; Byte[] ba2 = {25, 35, 45, 55}; BitArray bits1 = new BitArray(4); BitArray bits2 = new BitArray(4); bits1.SetAll(ba1); bits2.SetAll(ba2); BitArray result; int i; result = bits1.And(bits2); for(i=0; i< result.Count; i++) { if (result[i] == true) { Console.WriteLine(i); } } Or Byte[] ba1 = {20, 30, 40, 50}; Byte[] ba2 = {25, 35, 45, 55}; BitArray bits1 = new BitArray(4); BitArray bits2 = new BitArray(4); bits1.SetAll(ba1); bits2.SetAll(ba2); BitArray result; int i;

result = bits1.Or(bits2); for(i=0; i< result.Count; i++) { if (result[i] == true) { Console.WriteLine(i); } } The SetAll method is used to set all values in a BitArray to the same Boolean value. It cannot be used to set the values in a BitArray to the values in an array of type Byte. Also, the constructor that accepts an argument of type Integer, creates a BitArray with that number of elements (in this case 4). To store 4 bytes, a BitArray must have 32 elements because there are 8 bits in a byte. Objective: Developing applications that use system types and collections Sub Objective(s): Manage a group of associated data in a .NET Framework application by using collections (Refer System.Collections namespace) BitArray Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.bitarray(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-014

____________________________________________________________________________________________________________________ You are writing an application. You need to ensure that both successful and failed attempts to modify, delete, or change permissions on the cc.dat file are logged to the Security log. These events should be logged whenever a member of the Executives group or Managers group attempts the action. You need to write code to meet the requirements. Your code should replace any audit entries for the Executives or Managers groups. What code should you use? 1. string filename = "cc.dat"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure | AuditFlags.Success); fileSec.AddAuditRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure | AuditFlags.Success); fileSec.AddAuditRule(rule); File.SetAccessControl(filename, fileSec); 2. string filename = "cc.dat"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAuditRule rule; rule = new FileSystemAuditRule("MyDomain\\Executives", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure); fileSec.AddAuditRule(rule); rule = new FileSystemAuditRule("MyDomain\\Executives", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Success); fileSec.SetAuditRule(rule); rule = new FileSystemAuditRule("MyDomain\\Managers", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure); fileSec.AddAuditRule(rule); rule = new FileSystemAuditRule("MyDomain\\Managers", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Success); fileSec.SetAuditRule(rule); File.SetAccessControl(filename, fileSec); 3. string filename = "cc.dat"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAuditRule rule; rule = new FileSystemAuditRule("MyDomain\\Executives", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure | AuditFlags.Success); fileSec.SetAuditRule(rule); rule = new FileSystemAuditRule("MyDomain\\Managers", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure | AuditFlags.Success); fileSec.SetAuditRule(rule); File.SetAccessControl(filename, fileSec); <Correct> 4. string filename = "cc.dat"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Delete & FileSystemRights.TakeOwnership & FileSystemRights.ChangePermissions, AuditFlags.Failure & AuditFlags.Success); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.Delete &

FileSystemRights.TakeOwnership & FileSystemRights.ChangePermissions, AuditFlags.Failure & AuditFlags.Success); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); Explanation : You should use the following code: string filename = "cc.dat"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAuditRule rule; rule = new FileSystemAuditRule("MyDomain\\Executives", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure | AuditFlags.Success); fileSec.SetAuditRule(rule); rule = new FileSystemAuditRule("MyDomain\\Managers", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure | AuditFlags.Success); fileSec.SetAuditRule(rule); File.SetAccessControl(filename, fileSec); You use a FileSystemAuditRule to enable auditing. In this case, you want to audit both failure and success for three types of events, so you need to use the Or operator to join both FileSystemRights and AuditFlags enumeration values. You should use SetAuditRule to replace any existing rule for those groups. You should not use the following code: string filename = "cc.dat"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure | AuditFlags.Success); fileSec.AddAuditRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.Delete | FileSystemRights.TakeOwnership | FileSystemRights.ChangePermissions, AuditFlags.Failure | AuditFlags.Success); fileSec.AddAuditRule(rule); File.SetAccessControl(filename, fileSec); Or string filename = "cc.dat"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Delete & FileSystemRights.TakeOwnership & FileSystemRights.ChangePermissions, AuditFlags.Failure & AuditFlags.Success); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.Delete & FileSystemRights.TakeOwnership & FileSystemRights.ChangePermissions, AuditFlags.Failure & AuditFlags.Success); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); You must use the FileSystemAuditRule class, not the FileSystemAccessRule class to define audit rules. You should not use the following code: string filename = "cc.dat"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Delete & FileSystemRights.TakeOwnership & FileSystemRights.ChangePermissions, AuditFlags.Failure & AuditFlags.Success); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.Delete & FileSystemRights.TakeOwnership & FileSystemRights.ChangePermissions, AuditFlags.Failure & AuditFlags.Success); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); Because SetAuditRule overwrites any existing rule, only Success audits will be made.

Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement access control by using the System.Security.AccessControl classes. References : AuditRule Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.auditrule(vs.80).aspx FileSystemRights Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.filesystemrights(vs.80).aspx FileSecurity Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-085

____________________________________________________________________________________________________________________ You are writing an application that uses the custom class DownloadWatcher. The DownloadWatcher class raises two custom events. The delegates are shown below: public delegate void DownloadComplete(object sender, EventArgs e); public delegate void DownloadProgress(object sender, DownloadProgressEventArgs e); You need to handle these two events in your application. What code should you use? 1. private DownloadWatcher dw = new DownloadWatcher(); void dw_DownloadComplete(object sender, EventArgs e) { //implementation here } void dw_DownloadProgress(object sender, DownloadProgressEventArgs e) { //implementation here } public event dw_DownloadComplete DownloadCompleteEvent; public event dw_DownloadProgress <DownloadProgressEventArgs> DownloadProgressEvent; 2. private DownloadWatcher dw = new DownloadWatcher(); void dw_DownloadComplete(object sender, EventArgs e) { //implementation here } void dw_DownloadProgress(object sender, DownloadProgressEventArgs e) { //implementation here } public event dw_DownloadComplete DownloadCompleteEvent; public event dw_DownloadProgress DownloadProgressEvent; 3. private DownloadWatcher dw = new DownloadWatcher(); void dw_DownloadComplete(object sender, EventArgs e) { //implementation here } void dw_DownloadProgress(object sender, DownloadProgressEventArgs e) { //implementation here } dw_DownloadComplete += dw.DownloadComplete; dw_DownloadProgress += dw.DowloadProgress; 4. private DownloadWatcher dw = new DownloadWatcher(); void dw_DownloadComplete(object sender, EventArgs e) { //implementation here } void dw_DownloadProgress(object sender, DownloadProgressEventArgs e) { //implementation here } dw.DownloadComplete += dw_DownloadComplete; dw.DowloadProgress += dw_DownloadProgress; <Correct> Explanation : You should use the code:

private DownloadWatcher dw = new DownloadWatcher(); void dw_DownloadComplete(object sender, EventArgs e) { //implementation here } void dw_DownloadProgress(object sender, DownloadProgressEventArgs e) { //implementation here } dw.DownloadComplete += dw_DownloadComplete; dw.DowloadProgress += dw_DownloadProgress; To handle an event, you must create a sub procedure that contains the code to handle the event. Next, you must link that sub procedure with the event. You can do this by using the += operator. You must specify the name of the event as the left operand and the sub procedure as the right operand. You should not use the code: private DownloadWatcher dw = new DownloadWatcher(); void dw_DownloadComplete(object sender, EventArgs e) { //implementation here } void dw_DownloadProgress(object sender, DownloadProgressEventArgs e) { //implementation here } public event dw_DownloadComplete DownloadCompleteEvent; public event dw_DownloadProgress DownloadProgressEvent; or private DownloadWatcher dw = new DownloadWatcher(); void dw_DownloadComplete(object sender, EventArgs e) { //implementation here } void dw_DownloadProgress(object sender, DownloadProgressEventArgs e) { //implementation here } public event dw_DownloadComplete DownloadCompleteEvent; public event dw_DownloadProgress <DownloadProgressEventArgs> DownloadProgressEvent; You use the event statement to declare an event within a class, not to associate the event with its handler. You should not use the following code: private DownloadWatcher dw = new DownloadWatcher(); void dw_DownloadComplete(object sender, EventArgs e) { //implementation here } void dw_DownloadProgress(object sender, DownloadProgressEventArgs e) { //implementation here } dw_DownloadComplete += dw.DownloadComplete; dw_DownloadProgress += dw.DowloadProgress; The += operator requires the object and event as the left operand and the name of the subprocedure as the right operand. Objective: Developing applications that use system types and collections Sub Objective(s): Control interactions between .NET Framework application components by using events and delegates. (Refer System namespace) How to: Subscribe to and Unsubscribe from Events (C# Programming Guide) MSDN Link: http://msdn2.microsoft.com/en-us/library/ms366768(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-042

____________________________________________________________________________________________________________________ You are developing a class library by using the .NET Framework. You write the following code: public delegate void NumberDelegate(int number); public class NumberClass { public void TestMethod1(int number) { string output = "Zero"; if (number > 0) output = "Positive"; if (number < 0) output = "Negative"; Console.WriteLine(output); } public void TestMethod2(int number) { string output = String.Empty; if (number > 0) output = "+"; if (number < 0) output = "-"; Console.WriteLine(output); } } You write the following code to test the class: NumberClass num = new NumberClass(); NumberDelegate del1 = new NumberDelegate(num.TestMethod1); NumberDelegate del2 = new NumberDelegate(num.TestMethod2); Delegate.Combine(del2, del1); del1(5); What should you select as the output generated by this code segment? 1. Positive + 2. Positive <Correct> 3. + Positive 4. + Explanation : Two delegate objects can be combined by using the Combine method, but the Combine method does not alter the delegates. Instead, executing Combine returns a new delegate that represents a combination of the two delegates. In the given code, the result of combining operations is not preserved, so it will have no effect on the output. The correct output generated by the program is: Positive Only one line of output will be generated because only one delegate (del1) is invoked. Objective: Developing applications that use system types and collections

Sub Objective(s): Control interactions between .NET Framework application components by using events and delegates. (Refer System namespace) Delegate Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.delegate(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-033

____________________________________________________________________________________________________________________ You are developing a large application by using the .NET Framework. Your application must provide support for culture-specific information such as language, calendar, currency, etc. You need to parse a date and time string generated for a custom culture. To help ensure the success of the parse operation, you designate parse patterns that are likely to succeed. You must prevent write code to parse the date and time string. Your solution must minimize the likelihood that the parsing operation will fail. Which method should you use for parsing the date and time string? 1. TryParseExact method 2. ParseExact method 3. Parse method 4. TryParse method Explanation : If you parse a date and time string generated for a custom culture, you should use the TryParseExact method instead of the TryParse method to ensure that the parse operation will succeed. The TryParseExact method requires you to explicitly designate one or more exact parse patterns that are likely to succeed. The TryParse method attempts to parse a string with several implicit parse patterns, all of which might fail. The Parse and ParseExact methods are incorrect because these methods do not provide error handling. A custom culture date and time string can be complicated and difficult to parse. In case of any errors, the Parse or ParseExact methods are likely to fail. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Enhance the user interface of a .NET Framework application by using the System.Drawing namespace. DateTime.TryParseExact Method MSDN Link: http://msdn2.microsoft.com/en-us/library/k9s47fcc(en-US,VS.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-013

____________________________________________________________________________________________________________________ You create a Windows service application that consists of two services. One service monitors a directory for new orders and the other service replicates a database table with the most up-to-date inventory information. You need to develop a project installer class to install these services. What should you do? (Each correct answer presents part of the solution. Choose two.) 1. Instantiate two ServiceInstaller instances and add them to the project installer class. <Correct> 2. Instantiate two ComponentInstaller instances and add them to the project installer class. 3. Instantiate one ServiceInstaller instance and add it to the project installer class. 4. Instantiate one ComponentInstaller instance and add it to the project installer class. 5. Instantiate one ServiceProcessInstaller instance and add it to the project installer class. <Correct> 6. Instantiate two ServiceProcessInstaller instances and add them to the project installer class. Explanation : The ServiceProcessInstaller class installs an executable containing services. The ServiceInstaller class installs a class that implements a service. When creating a project installer class, you need to instantiate one ServiceProcessInstaller instance per service application, and one ServiceInstaller instance for each service in the application. The ComponentInstaller class specifies an installer that copies properties from a component to use at install time. This class is an abstract class and cannot be instantiated. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Implement, install, and control a service. (Refer System.ServiceProcess namespace) References : ServiceProcessInstaller Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.serviceprocess.serviceprocessinstaller(vs.80).aspx ServiceInstaller Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-078

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following classes as part of your code: public class Book { public string Name; } public class Library { public Book[] Books; } You need to create an object of the Library type and serialize it to disk in a file named books.xml. You write the following code: Book[] books = new Book[3]; books[0] = new Book(); books[0].Name = "Book Name 1"; books[1] = new Book(); books[1].Name = "Book Name 2"; books[2] = new Book(); books[2].Name = "Book Name 3"; Library library = new Library(); library.Books = books; XmlSerializer mySerializer = new XmlSerializer(typeof(Library)); using (StreamWriter myWriter = new StreamWriter("books.xml")) { mySerializer.Serialize(myWriter, library); } What XML output will be generated by this program? 1. <Library> <Books> <Book> <Name>Book Name 1</Name> </Book> <Book> <Name>Book Name 2</Name> </Book> <Book> <Name>Book Name 3</Name> </Book> </Books> </Library> <Correct> 2. <Library> <Books> <Name>Book Name 1</Name> <Name>Book Name 2</Name> <Name>Book Name 3</Name> </Books> </Library> 3. <Library> <Book> <Name>Book Name 1</Name> </Book> <Book>

<Name>Book Name 2</Name> </Book> <Book> <Name>Book Name 3</Name> </Book> </Library> 4. <Library> <Books> <Book Name = "Book Name 1" /> <Book Name = "Book Name 2" /> <Book Name = "Book Name 3" /> </Books> </Library> Explanation : The code uses XML serialization to serialize the library object, which serializes all the public fields to the XML file. The top-level node will be the name of the type (Library) for the library object. The Library type contains a public property named Books, which becomes the child element. The Books field is of the type Book, which becomes the child of the Books element. Finally the Book type contains one public property (Name), which becomes its child element. The correct serialized XML output will be as follows: <Library> <Books> <Book> <Name>Book Name 1</Name> </Book> <Book> <Name>Book Name 2</Name> </Book> <Book> <Name>Book Name 3</Name> </Book> </Books> </Library> To cause the data to be serialized as follows, you would need to precede the Name property with the <XmlAttribute> attribute. <Library> <Books> <Book Name = "Book Name 1" /> <Book Name = "Book Name 2" /> <Book Name = "Book Name 3" /> </Books> </Library> Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Control the serialization of an object into XML format by using the System.Xml.Serialization namespace. References : Introducing XML Serialization MSDN Link: http://msdn2.microsoft.com/en-us/library/182eeyhh(vs.80).aspx Examples of XML Serialization MSDN Link: http://msdn2.microsoft.com/en-us/library/58a18dwa(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-070

____________________________________________________________________________________________________________________ You are developing a text manipulation application by using the .NET Framework. You write the following code in your application: StringBuilder sb = new StringBuilder(":string:"); char[] b = { 'a', 'b', 'c', 'd', 'e', 'f', 'g'}; StringWriter sw = new StringWriter(sb); sw.Write(b, 0, 3); Console.WriteLine(sb); sw.Close(); What output will be generated by this code segment when the application is executed? 1. :stabcdefg 2. abcring: 3. abc:string: 4. :string:abc <Correct>

Explanation : The code segment will generate the following output: :string:abc The specific overload of the Write method takes a character array and reads three characters starting from the index 0 and appends them to the end of the underlying StringBuilder object. The output abc:string: is incorrect because the characters will be appended to the end of the underlying StringBuilder object. The output strings abcring: and : stabcdefg are incorrect because the StringWriter is sequential and it will not go back and overwrite the characters that are already in the underlying StringBuilder object. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Manage .NET Framework application data by using Reader and Writer classes. (Refer System.IO namespace) StringWriter Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.stringwriter(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-137

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write code that creates a default instance of the Rijndael symmetric algorithm class and configures it with a key that is generated from a salted password. You write the following code (line numbers are for reference only): 01: byte[] salt = new byte[16]; 02: Rijndael cryptoRij = Rijndael.Create(); 03: cryptoRij.Key = key; The variable named salt acts as a seed to the key derivation algorithm. You need to insert additional code before line 02 that stores a random number into the salt variable and generates a key using Rfc2898DeriveBytes. Which code segment should you use? 1. RNGCryptoServiceProvider rNum = (RNGCryptoServiceProvider) RNGCryptoServiceProvider.Create(); rNum.GetBytes(salt); Rfc2898DeriveBytes passDerBytes= new Rfc2898DeriveBytes (password, salt); byte[] key = passDerBytes.GetHashCode(); 2. RNGCryptoServiceProvider rNum = (RNGCryptoServiceProvider) RNGCryptoServiceProvider.Create(); rNum.GetBytes(salt); Rfc2898DeriveBytes passDerBytes= new Rfc2898DeriveBytes (password, salt); byte[] key = passDerBytes.GetBytes(16); <Correct> 3. Random rNum = new Random(); rNum.NextBytes(salt); Rfc2898DeriveBytes passDerBytes= new Rfc2898DeriveBytes (password, salt); byte[] key = passDerBytes.GetBytes(16); 4. Random rNum = new Random(); rNum.NextBytes(salt); Rfc2898DeriveBytes passDerBytes= new Rfc2898DeriveBytes (password, salt); byte[] key = passDerBytes.GetHashCode(); Explanation : You should use the following code segment because the RNGCryptoServiceProviderclass generates an unpredictable, and therefore cryptographically valid, sequence of pseudorandom numbers and stores them in an array of type Byte. RNGCryptoServiceProvider rNum = (RNGCryptoServiceProvider) RNGCryptoServiceProvider.Create(); rNum.GetBytes(salt); Rfc2898DeriveBytes passDerBytes= new Rfc2898DeriveBytes (password, salt); byte[] key = passDerBytes.GetBytes(16); The Rfc2898DeriveBytes class can then use that array, in conjunction with a password, to generate an array of bytes that the Rijndael algorithm can use as its key. You retrieve these bytes using the GetBytes function. The Random class creates random numbers, but they are not cryptographically valid because when the same seed is used, the sequence can be predicted. The GetHashCode method of Rfc2898DeriveBytes returns a hash, not an array of bytes. A hash is an integer and cannot be used as the Rijndael key. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features

Sub Objective(s): Encrypt, decrypt, and hash data by using the System.Security.Cryptography classes. (Refer System.Security.Cryptography namespace) References : RNGCryptoServiceProvider Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(vs. 80).aspx Rfc2898Derivebytes Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-039

____________________________________________________________________________________________________________________ You are developing an enterprise application by using the .NET Framework. You create the following variable in your code: DateTime dateValue; You also write code to store local time to the dateValue variable. You need to serialize the value of the dateValue variable. If the DateTime object is serialized in one time zone and deserialized in a different time zone, the local time represented by the resulting DateTime object should be automatically adjusted to the second time zone. Which expression should you use to serialize the value of the dateValue variable? 1. dateValue.ToString("yyyy-MM-ddTHH:mm:ss.fffffff", CultureInfo.InvariantCulture) 2. dateValue.ToBinary() 3. dateValue.Kind 4. dateValue.Ticks Explanation : In the .NET Framework, the DateTime structure has additional information about whether it is Local, Universal, or Unspecified. To preserve this information there are new ToBinary and FromBinary methods. These methods also automatically adjust local times. Using the Ticks property is a simple and fast way to determine the number of 100-nanosecond intervals that have elapsed since January 1, 0001. Using this property is not recommended for local times because the value returned by the Ticks property exists in the context of the computer's local time zone. If the time zone changes or the serialized value is read from a different computer, it could be invalid. Using the following expression is incorrect because it does not preserve all the information such as local time and time zone in the DateTime object: dateValue.ToString("yyyy-MM-ddTHH:mm:ss.fffffff", CultureInfo.InvariantCulture) Using the Kind property is incorrect in this case because the Kind property gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither. The Kind property cannot serialize the value on its own. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) DateTime Structure MSDN Link: http://msdn2.microsoft.com/en-us/library/system.datetime(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-117

____________________________________________________________________________________________________________________ You are developing an application by using the .NET Framework. You write the following code for the ManageTask method (line numbers are for reference only): 01: public void ManageTask(string name1, string role1, 02: string name2, string role2) 03: { 04: PrincipalPermission principalPerm1 = 05: new PrincipalPermission(name1, role1); 06: PrincipalPermission principalPerm2 = 07: new PrincipalPermission(name2, role2); 08: 09: // Additional code 10: } The identity strings name1 and name2 will always be different. You must make sure the current user has permissions associated with at least one of the defined principal permission objects. What code should you write in line 08? 1. principalPerm1. IsInRole(principalPerm2); 2. (principalPerm1.Union(principalPerm2)).Demand(); <Correct> 3. (principalPerm1.Intersect(principalPerm2)).Demand(); 4. principalPerm1.IsSubsetOf(principalPerm2); Explanation : You should use the Union method because this method takes a permission object and returns a permission object that represents all permissions in common for that permission object and the current object. It is incorrect to use the Intersect method because this method intersects identity and roles independent of each other. So if the identities are different, their interaction will be identity="", which is an unauthenticated user. The IsSubsetOf method determines if one PrincipalPermission class is a full subset of another PrincipalPermission class. In this scenario, the identities are different, so this function will always return False. The IsInRole method is a method of the Principal object, not the PrincipalPermission object. It allows you to verify whether the principal is a member of a specific role. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control permissions for resources by using the System.Security.Permission classes. (Refer System.Security.Permission namespace) References : Combining PrincipalPermission Objects MSDN Link: http://msdn2.microsoft.com/en-us/library/103hb3s7(VS.80).aspx How to: Perform Imperative Security Checks MSDN Link: http://msdn2.microsoft.com/en-us/library/dc8ztsad(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-138

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You need to encrypt a data file before transmitting its contents over the Internet. The encryption must prevent any spoofing of the identity of the publisher of the data file. You sign the data by using the publisher's private key. You also encrypt the data by using the receiver's public key. The receiver of the file uses a private key (only known to the receiver) to decrypt the data. The receiver also has access to the publishers public key. The intended recipient must be able to decrypt the encrypted file after it is received through an Internet transmission. The intended recipient must also be able to detect any tampering with the contents of the data file. Which class should you use for encrypting the data file? 1. RSACryptoServiceProvider <Correct> 2. SHA1Managed 3. RijndaelManaged 4. SHA1CryptoServiceProvider Explanation : You should use the RSACryptoServiceProvider class to encrypt the data file. The RSACryptoServiceProvider class implements an asymmetric cryptography algorithm that uses a set of related keys (public key and private key) to encrypt and decrypt data. The data is encrypted by using the receiver's public key. This data can only be decrypted by using the recipient's private key (which is only known to the recipient). In this case, the sender also signs the data by using the publisher's private key. The recipient, who has access to the publisher's public key, can detect any tampering with the file contents. You should not use the RijndaelManaged class in this case. The RijndaelManaged class implements a symmetric cryptography algorithm that uses a single shared secret key for encrypting and decrypting the data. You should not use the SHA1Managed and the SHA1CryptoServiceProvider classes in this case. The SHA1Managed and SHA1CryptoServiceProvider classes implement a hash algorithm that can be used to detect any tampering with the file contents, but they cannot be used to establish the identity of the data file's publisher. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Encrypt, decrypt, and hash data by using the System.Security.Cryptography classes. (Refer System.Security.Cryptography namespace) Cryptography Overview MSDN Link: http://msdn2.microsoft.com/en-us/library/92f9ye3s(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-124

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You need to list the available public types and methods in the HGCorBus assembly. The assembly is strongly named and is installed in the global assembly cache. The assembly with the same identity is also stored at c:\assem\HGCorBus.dll. You need to dynamically load the HGCorBus assembly in your application. You must make sure that the assembly is loaded from c:\assem\HGCorBus.dll rather than the global assembly cache and that the application cannot instantiate the classes in the assembly or execute their methods. Which code statement should you use? 1. Assembly assem = Assembly.LoadFrom(@"c:\assem\HGCorBus.dll"); 2. Assembly assem = Assembly.ReflectionOnlyLoad("HGCorBus"); 3. Assembly assem = Assembly.ReflectionOnlyLoadFrom(@"c:\assem\HGCorBus.dll"); 4. Assembly assem = Assembly.Load("HGCorBus"); 5. Assembly assem = Assembly.LoadFile(@"c:\assem\HGCorBus.dll"); Explanation : The following statement will correctly load the assembly from the c:\assem\HGCorBus.dll folder: Assembly assem = Assembly.ReflectionOnlyLoadFrom(@"c:\assem\HGCorBus.dll"); The Assembly.LoadFrom and Assembly.LoadFile methods can load an assembly from a specific file system path, but the application will be able to instantiate the classes in the assembly and execute the methods. The Assembly.Load and Assembly.ReflectionOnlyLoad methods will attempt to locate the assembly in the Global Assembly Cache (GAC) first. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Implement reflection functionality in a .NET Framework application (refer System.Reflection namespace), and create metadata, Microsoft intermediate language (MSIL), and a PE file by using the System.Reflection.Emit namespace. Assembly Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.reflection.assembly(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-013

____________________________________________________________________________________________________________________ You are writing an application that will use a file named cc.txt. You need to ensure that the file can only be read and modified by members of the Executives group and that only members of the Managers and Executives group can append to the file. Members of the Executives group should not be allowed to delete the file or set permissions on the file. All users belong to exactly one of the following groups: MyDomain\Managers MyDomain\Executives MyDomain\Nonmanagers You need to write code to configure the permissions programmatically. What code should you use? 1. string filename = "cc.txt"; FileSystemSecurity fileSec = new FileSystemSecurity(); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.AppendData, AccessControlType.Allow); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Nonmanagers", FileSystemRights.FullControl, AccessControlType.Deny); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Read | FileSystemRights.Modify, AccessControlType.Allow); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); 2. string filename = "cc.txt"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.AppendData, AccessControlType.Allow); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Nonmanagers", FileSystemRights.FullControl, AccessControlType.Deny); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Read | FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); <Correct> 3. string filename = "cc.txt"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); rule = ew FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Read & FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); 4. string filename = "cc.txt"; FileSystemSecurity fileSec = new FileSystemSecurity(); FileSystemAccessRule rule; rule = new FileSystemAccessRule("MyDomain\\Managers", FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule("MyDomain\\Executives", FileSystemRights.Read &

FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); Explanation : You should use the following code: string filename = "cc.txt"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.AppendData, AccessControlType.Allow); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Nonmanagers", FileSystemRights.FullControl, AccessControlType.Deny); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Read | FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); The FileSecurity class contains access and audit rules for a file. When you create a rule, you must specify the Windows user account (including domain or computer name), the permission or permissions associated with the rule, and whether to Allow or Deny the permission. The requirements state that Executives should be able to both Read and Write to the file. Therefore, you can assign both the Read and Write permission by using the Or operator. The Managers group needs to be able to append data to the file, but not read the file. You can accomplish this goal by assigning them the AppendData permission. Finally, any other user should not be allowed access to the file. To prevent other users from accessing the file by virtue of inherited permissions or accidentally placing the user in the Managers or Executives group, you need to Deny the Nonmanagers group Full Control to the file. You should not use the following code: string filename = "cc.txt"; FileSecurity fileSec = File.GetAccessControl(filename); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); rule = ew FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Read & FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); This code will allow Managers to modify existing data, as well as append to the end of the file. It will also allow Nonmanagers to access the file if they are granted access through inheritance or membership in another group. The code also does not set the Executives permissions correctly. By using the And operator, you are adding an access control entry for Executives, but not granting any permissions. You should not use the following code: string filename = "cc.txt"; FileSystemSecurity fileSec = new FileSystemSecurity(); FileSystemAccessRule rule; rule = new FileSystemAccessRule("MyDomain\\Managers", FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule("MyDomain\\Executives", FileSystemRights.Read & FileSystemRights.Write, AccessControlType.Allow); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); It has the same permission problems as the previous block of code. Also, FileSystemSecurity is the abstract base class for FileSecurity, so it cannot be insantiated. You should not use the following code: string filename = "cc.txt"; FileSystemSecurity fileSec = new FileSystemSecurity(); FileSystemAccessRule rule; rule = new FileSystemAccessRule ("MyDomain\\Managers", FileSystemRights.AppendData, AccessControlType.Allow); fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Nonmanagers", FileSystemRights.FullControl, AccessControlType.Deny);

fileSec.AddAccessRule(rule); rule = new FileSystemAccessRule ("MyDomain\\Executives", FileSystemRights.Read | FileSystemRights.Modify, AccessControlType.Allow); fileSec.AddAccessRule(rule); File.SetAccessControl(filename, fileSec); You should not grant the Modify permission to Executives. The Modify permission allows executives to delete the file. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement access control by using the System.Security.AccessControl classes. References : FileSystemRights Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.filesystemrights(vs.80).aspx FileSecurity Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.filesecurity(vs.80).aspx FileSystemAccessRule Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.filesystemaccessrule(vs.80) .aspx FileSystemSecurity Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.filesystemsecurity(vs.80).a spx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-005

____________________________________________________________________________________________________________________ You are developing a .NET Framework application that will be used to schedule jobs in a manufacturing facility. Your application must process the jobs by using the First-In-First-Out technique. As the job requests arrive, you queue them together by using an object of the Queue class. You need to remove the first request from the beginning of the queue and process it. Which method of the Queue class should you use? 1. RemoveAt 2. Peek 3. Pop 4. Dequeue <Correct>

Explanation : You should use the Dequeue method of the Queue class because the Dequeue method removes and returns the object at the beginning of the queue. The Queue class does not implement a Pop method. The Pop method is implemented by the Stack class and is used to process the top record in the stack. The Queue class does not implement a RemoveAt method because it only supports retrieving methods from the front of the queue. The RemoveAt method is implemented by the SortedList class. Using the Peek method of the Queue class is incorrect because the Peek method returns the object at the beginning of the queue without removing it. Objective: Developing applications that use system types and collections Sub Objective(s): Manage a group of associated data in a .NET Framework application by using collections (Refer System.Collections namespace) Queue Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.queue(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-058

____________________________________________________________________________________________________________________ You are designing a Windows service application by using the .NET Framework. The application contains three different Windows services. You must set only one Windows service to start automatically when the system is restarted. Which class should you use? 1. ServiceBase 2. ServiceInstaller 3. ServiceController 4. ServiceProcessInstaller Explanation : You should use the ServiceInstaller class to accomplish this task. The StartType property of the ServiceInstaller class allows you to specify how and when a service is started. Using the ServiceProcessInstaller class is incorrect because this class has methods that affect all the services in an executable. In this case, changes are only required on one Windows service. Using the ServiceController class is incorrect because although this class allows you to interact with a Windows service and issue commands such as start and stop, it does not allow you to set the start type of a Windows service. Using the ServiceBase class is incorrect because although this class is a base type for all the Windows services, it does not allow you to set the start type for a Windows service. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Implement, install, and control a service. (Refer System.ServiceProcess namespace) ServiceInstaller Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-121

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code: public class Shape { private string shapeName; public Shape(string shapeName) { this.shapeName = shapeName; } public virtual string GetName() { return shapeName; } private void DrawShape() { //Add additional code here } } You compile and register this assembly for COM interoperability. Other developers in your team complain that they cannot create an instance of the Shape class in their COM applications. COM applications must be able to create an instance of the Shape class. What should you do? 1. Add the following ComVisible attribute to the Shape class: [ComVisible(true)] 2. Add the following ComVisible attribute to each method of the Shape class: [ComVisible(true)] 3. Modify the definition of the GetName method as shown below: public string GetName() { return shapeName; } 4. Add the following code to the Shape class: public Shape() { } <Correct> Explanation : Only the classes that have a public default constructor can be instantiated from a COM application. The given code has a parameterized constructor, which is not used by COM. Therefore, you should add the following code to the Shape class: public Shape() { } The class and its public members are already visible to COM applications. The only problem is instantiating the class. Therefore, adding the ComVisibile attribute with its value set as true to either the class or its members will not make any difference. Public members are visible to COM applications by default. You would use the ComVisibleAttribute to prevent a Public member from being seen by a COM application.

Removing the virtual keyword from the definition of the GetName method is not required to make it available to the COM application. Also, the requirement in this case is to be able to instantiate a class. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Expose COM components to the .NET Framework and .NET Framework components to COM. (Refer System.Runtime.InteropServices namespace) Qualifying .NET Types for Interoperation MSDN Link: http://msdn2.microsoft.com/en-us/library/7fcfby2t(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-126

____________________________________________________________________________________________________________________ You are developing a .NET Framework application that sends data over the Internet. You must make sure that the data is not modified or tampered with during transmission. Secrecy of the data transmission is not important. You decide to compute a hash value for the data by using a secret key and then transmit the data along with the hash value. The receiver of the data must be able to detect if either the data or the hash value has been modified. The receiver has access to the secret key that was used for computing the hash value. Your must be able to accept keys of any size and produce a key sequence of 160 bits. What should you do? 1. Use the HMACMD5 class to encode the data prior to its transmission. 2. Use the DESCryptoServiceProvider class to encode the data prior to its transmission. 3. Use the MACTripleDES class to encode the data prior to its transmission. 4. Use the HMACSHA1 class to encode the data prior to its transmission. <Correct>

Explanation : You should use the HMACSHA1 class to encode the data prior to its transmission. The HMACSHA1 class uses the SHA1 hash function to compute a Hash-based Message Authentication Code (HMAC). HMAC can be use to find if a message has been modified during transmission. The SHA1 algorithm accepts a secret key of any size and produces a hash sequence of 160 bits. You should not use the HMACMD5 class to encode the data because the HMACMD5 class uses the MD5 hash function to compute an HMAC and produces a hash sequence of 128 bits. You should not use the MACTripleDES class to encode the data because the MACTripleDES class uses a secret key of length 16 or 24 bytes and produces a hash sequence of 8 bytes. You should not use the DESCryptoServiceProvider class to encode the data because the DESCryptoServiceProvider class encrypts the data in an attempt to maintain its secrecy. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Encrypt, decrypt, and hash data by using the System.Security.Cryptography classes. (Refer System.Security.Cryptography namespace) HMACSHA1 Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.cryptography.hmacsha1(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-008

____________________________________________________________________________________________________________________ You are writing an application that needs to read data from the prices.soap file and store it in a SortedList. The data is stored using the Simple Object Access Protocol (SOAP) format and includes a product ID, which you will use as the key, and the product price. What code should you use? 1. SortedList<string, decimal> prices = new SortedList(); SoapFormatter sf = new SoapFormatter(); FileStream fs = new FileStream("Prices.soap", FileMode.Open); prices = (SortedList) sf.Deserialize(fs); 2. SortedList prices = new SortedList(); SoapFormatter sf = new XmlSerializer(); FileStream fs = new FileStream("Prices.soap", FileMode.Open); prices = (SortedList) sf.Deserialize(fs); 3. SortedList<string, decimal> prices = new SortedList(); SoapFormatter sf = new XmlSerializer(); FileStream fs = new FileStream("Prices.soap", FileMode.Open); prices = (SortedList) sf.Deserialize(fs); 4. SortedList prices = new SortedList(); SoapFormatter sf = new SoapFormatter(); FileStream fs = new FileStream("Prices.soap", FileMode.Open); prices = (SortedList) sf.Deserialize(fs); <Correct> Explanation : You should use the code: SortedList prices = new SortedList(); SoapFormatter sf = new SoapFormatter(); FileStream fs = new FileStream("Prices.soap", FileMode.Open); prices = (SortedList) sf.Deserialize(fs); The SoapFormatter object can be used to serialize and deserialize data in the SOAP format. If you need to serialize multiple objects, you can store them in a collection class. You should not use the following code because you cannot use the SoapFormatter with Generic classes: SortedList<string, decimal> prices = new SortedList(); SoapFormatter sf = new SoapFormatter(); FileStream fs = new FileStream("Prices.soap", FileMode.Open); prices = (SortedList) sf.Deserialize(fs); You should not use the code: SortedList prices = new SortedList(); SoapFormatter xf = new XmlSerializer(); FileStream fs = new FileStream("Prices.soap", FileMode.Open); prices = (SortedList) sf.Deserialize(fs); Although you can use the XmlSerializer to serialize and deserialize XML data, you would need to pass an object of the XmlTypeMapping type to the constructor. Also, you cannot use a SortedList or any other collection with an XmlSerializer. Objective: Implementing serialization and input/output functionality in a .NET Framework application

Sub Objective(s): Implement custom serialization formatting by using the Serialization Formatter classes. SoapFormatter Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.formatters.soap.soapformatte r(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-022

____________________________________________________________________________________________________________________ You are creating a graphics application by using the .NET Framework. You need to draw the string "Banner Text" on a window as shown in the exhibit. The application must support users regardless the size of their desktop monitors. You must write code to draw the string. Which code segment should you use? 1. private void Form1_Paint(object sender, PaintEventArgs e) { using (Font font = new Font(new FontFamily("Arial"), 28, FontStyle.Regular, GraphicsUnit.Pixel)) { Point point1 = new Point(10, 10); TextRenderer.DrawText(e.Graphics, "Banner Text", font, point1, Color.Blue); } } <Correct> 2. private void Form1_Paint(object sender, PaintEventArgs e) { using (Font font = new Font(new FontFamily("Arial"), 28, FontStyle.Regular, GraphicsUnit.Inch)) { Point point1 = new Point(10, 10); TextRenderer.DrawText(e.Graphics, "Banner Text", font, point1, Color.Blue); } } 3. private void Form1_Load(object sender, EventArgs e) { Graphics grfx = this.CreateGraphics(); using (Font font = new Font(new FontFamily("Arial"), 28, FontStyle.Regular, GraphicsUnit.Pixel)) { Point point1 = new Point(10, 10); TextRenderer.DrawText(grfx, "Banner Text", font, point1, Color.Blue); } grfx.Dispose(); } 4. private void Form1_Load(object sender, EventArgs e) { using (Graphics grfx = this.CreateGraphics()) { String drawString = "Banner Text"; Font drawFont = new Font("Arial", 28); SolidBrush drawBrush = new SolidBrush(Color.Blue); PointF drawPoint = new PointF(10.0F, 10.0F); grfx.DrawString(drawString, drawFont, drawBrush, drawPoint); } } Explanation : You must select the following code to draw the text string: private void Form1_Paint(object sender, PaintEventArgs e) { using (Font font = new Font(new FontFamily("Arial"), 28,

FontStyle.Regular, GraphicsUnit.Pixel)) { Point point1 = new Point(10, 10); TextRenderer.DrawText(e.Graphics, "Banner Text", font, point1, Color.Blue); } } This code can be used as an event handler to the Paint event of the Windows form. The event handler for the Paint event receives a parameter of type PaintEventArgs. The following code uses GraphicsUnit.Inch as the measurement unit. This will cause this code to draw very large text that will be impossible to display on smaller monitors: private void Form1_Paint(object sender, PaintEventArgs e) { using (Font font = new Font(new FontFamily("Arial"), 28, FontStyle.Regular, GraphicsUnit.Inch)) { Point point1 = new Point(10, 10); TextRenderer.DrawText(e.Graphics, "Banner Text", font, point1, Color.Blue); } } You should not use the Page_Load method for drawing the string. The Load event is fired too early in the lifecycle of the form. Even if you got the Graphics object, you would likely draw before the window was totally visible, and therefore your drawing would be lost. You should instead use the Paint event to draw strings. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Enhance the user interface of a .NET Framework application by using the System.Drawing namespace. References : GraphicsUnit Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.drawing.graphicsunit(vs.80).aspx Form Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.windows.forms.form(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-004

____________________________________________________________________________________________________________________ You are writing a class library that will be used by several applications and by other class libraries. You need to create an attribute that can be used to identify a class as storing data about a perishable food product, a non-perishable food product, or a non-food product. You need to create the attribute. What code should you use? (Each correct answer presents part of the solution. Choose two.) 1. [AttributeUsage(AttributeTargets.Class)] public class ProductTypeAttribute { public ProductTypeAttribute (ProductType productType) { productCategory = productType; } private ProductType productCategory; [AttributeUsage(AttributeTargets.Property)] public ProductType Category { get{ return productCategory; } set { productCategory = value;} } } 2. [AttributeUsage(AttributeTargets.Class)] public class ProductTypeAttribute : Attribute { public ProductTypeAttribute (ProductType productType) { productCategory = productType; } private ProductType productCategory; public ProductType Category { get{ return productCategory; } set { productCategory = value;} } } <Correct> 3. [AttributeUsage(AttributeTargets.Enum)] public enum ProductType {Perishable, NonperishableFood, NonFood}; 4. public class ProductTypeAttribute : Attribute { public ProductTypeAttribute (ProductType productType) { productCategory = productType; } private ProductType productCategory; [AttributeUsage(AttributeTargets.Property)] public ProductType Category { get{ return productCategory; } set { productCategory = value;} } } 5. public enum ProductType{Perishable, NonperishableFood, NonFood}; <Correct> Explanation : You should use the following code to define the enumeration that will be used to define the type: public enum ProductType{Perishable, NonperishableFood, NonFood};

When you plan to use an enumeration within an attribute, you use the standard syntax for defining an enumeration. You should use the following code to define the ProductTypeAttribute class: [AttributeUsage(AttributeTargets.Class)] public class ProductTypeAttribute : Attribute { public ProductTypeAttribute (ProductType productType) { productCategory = productType; } private ProductType productCategory; public ProductType Category { get{ return productCategory; } set { productCategory = value;} } } When creating a class that will act as an attribute, you should derive the class from Attribute. You should also apply the AttributeUsageAttribute to specify the valid targets for the attribute. Doing so will prevent the attribute from being used incorrectly. You should not use the following code to define the enumeration: [AttributeUsage(AttributeTargets.Enum)] public enum ProductType {Perishable, NonperishableFood, NonFood}; The AttributeUsageAttribute can only target a class. You should not define the ProductTypeAttribute class using the following code: [AttributeUsage(AttributeTargets.Class)] public class ProductTypeAttribute { public ProductTypeAttribute (ProductType productType) { productCategory = productType; } private ProductType productCategory; [AttributeUsage(AttributeTargets.Property)] public ProductType Category { get{ return productCategory; } set { productCategory = value;} } } A property procedure is not a valid target for the AttributeUsageAttribute. Also, the class should inherit from the Attribute class. You should not use the following code to create the attribute: public class ProductTypeAttribute : Attribute { public ProductTypeAttribute (ProductType productType) { productCategory = productType; } private ProductType productCategory; [AttributeUsage(AttributeTargets.Property)] public ProductType Category { get{ return productCategory; } set { productCategory = value;} } } You should specify the valid targets on the class using the AttributeUsageAttribute. A property procedure is not a valid target for the AttributeUsageAttribute class. Objective: Developing applications that use system types and collections Sub Objective(s): Manage data in a .NET Framework application by using .NET Framework 2.0 system types (Refer

System namespace) Attribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.attribute(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-099

____________________________________________________________________________________________________________________ You write the following code in your test program: Stream logFile = File.Create(@"C:\LogFile.txt"); TextWriterTraceListener twtl = new TextWriterTraceListener(logFile); Trace.Listeners.Add(twtl); Trace.WriteLine("Test Message 1"); Debug.WriteLine("Test Message 2"); Trace.Flush(); What output is generated in the C:\LogFile.txt file when you run the test program in debug mode? 1. Test Message 1 Test Message 2

<Correct>

2. The C:\LogFile.txt is empty. 3. Test Message 1 4. Test Message 2 Explanation : The following code in the test program creates a TextWriterTraceListener object that writes output to the C:\LogFile.txt. It then adds the listener object to the Trace object. Stream logFile = File.Create(@"C:\LogFile.txt"); TextWriterTraceListener twtl = new TextWriterTraceListener(logFile); Trace.Listeners.Add(twtl); When you run the program in debug mode, both the Trace and Debug statements are executed and their output is sent to the listener object. The following code when executed produces the output in the C:\LogFile.txt file shown below: Code Trace.WriteLine("Test Message 1"); Debug.WriteLine("Test Message 2"); Output Test Message 1 Test Message 2 Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Debug and trace a .NET Framework application by using the System.Diagnostics namespace References : TraceListener Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.tracelistener(vs.80).aspx TextWriterTraceListener Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.textwritertracelistener(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-002

____________________________________________________________________________________________________________________ You are writing a product inventory application. You need to be able to modify the sale price of an item using a loop. The sale price is a percentage of the Suggested Retail Price (SRP). Product items are stored in an instance of the ProductItem class shown below. Instances of ProductItem are loaded into an ArrayList of named products. public class ProductItem { decimal m_saleprice; decimal m_SRP; //other fields declared here public decimal SalePrice { get { return m_saleprice; } set { m_saleprice = value; } } public decimal SRP { get { return m_SRP; } set { m_SRP = value; } } //rest of implementation here } You need to write code to set the SalePrice property of each ProductItem object to eighty percent of the SRP property. What code should you use? 1. IEnumerator productEnum = products.GetEnumerator(); while (productEnum.MoveNext) { productEnum.Current.SalePrice = productEnum.Current.SRP * .08; } 2. ProductItem productToChange; for(i = 0; i < products.Count; i++) { productToChange = (ProductItem) products[i]; productToChange.SalePrice = productToChange.SRP * 0.8; } <Correct> 3. ProductItem productToChange; IEnumerator productEnum = products.GetEnumerator(); foreach productToChange in productEnum { productToChange.SalePrice = productToChange.SRP * 0.8; } 4. ProductItem productToChange; for(i = 0; i < products.Capacity; i++) { productToChange = (ProductItem) products[i]; productToChange.SalePrice = productToChange.SRP * 0.8; } Explanation : You should use the code: ProductItem productToChange; for(i = 0; i < products.Count; i++) { productToChange = (ProductItem) products[i]; productToChange.SalePrice = productToChange.SRP * 0.8; }

The Count property of the ArrayList returns the number of elements in the collection. Because the ArrayList is a zero-based collection, the last element will be the one at Count-1. You should not use the code: ProductItem productToChange; for(i = 0; i < products.Capacity; i++) { productToChange = (ProductItem) products[i]; productToChange.SalePrice = productToChange.SRP * 0.8; } The Capacity property returns the number of elements the ArrayList can hold. There is no guarantee that the ArrayList is filled to capacity, so an error is likely to occur. You should not use the code: ProductItem productToChange; IEnumerator productEnum = products.GetEnumerator(); foreach productToChange in productEnum { productToChange.SalePrice = productToChange.SRP * 0.8; } You cannot loop through an object of type IEnumerator using a For Each loop. You must loop through an object of type IEnumerator using the MoveNext statement. You should not use the code: IEnumerator productEnum = products.GetEnumerator(); while (productEnum.MoveNext) { productEnum.Current.SalePrice = productEnum.Current.SRP * .08; } The Current property of the ArrayList's GetEnumerator returns a generic object. Therefore, unless you store the object in a variable of type ProductItem or cast the variable to type ProductItem, you cannot access the SalePrice or SRP properties. Objective: Developing applications that use system types and collections Sub Objective(s): Manage a group of associated data in a .NET Framework application by using collections (Refer System.Collections namespace) References : IEnumerator Interface MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.ienumerator(vs.80).aspx ArrayList Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.arraylist(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-043

____________________________________________________________________________________________________________________ You are developing a system utility application by using the .NET Framework 2.0. You need to write code that allows you to examine assemblies that were compiled for other versions of the .NET Framework. You create a new application domain. You need to write code to load assemblies into it from a file path. You do not know the name of the assemblies. You must make sure that the code loaded into this context can be examined but cannot be executed. What should you do? 1. Use the Assembly.ReflectionOnlyLoad method. 2. Use the Assembly.ReflectionOnlyLoadFrom method.<Correct> 3. Use the Assembly.Load method. 4. Use the Assembly.LoadFrom method. Explanation : The reflection-only load context lets you use reflection to gather information about an assembly, including those that were compiled for other versions of the .NET Framework or for other platforms. However, it does not allow you to instantiate classes in the assembly. Because you know the path to the file, but not the assemblys display name, you need to use the Assembly.ReflectionOnlyLoadFrom method. You would use the Assembly.ReflectionOnlyLoad method if you knew the display name of the assembly. The Assembly.Load and Assembly.LoadFrom methods are not correct answers because these methods allow you to execute the code and create objects. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Create a unit of isolation for common language runtime within a .NET Framework application by using application domains. (Refer System namespace) How to: Load Assemblies into the Reflection-Only Context MSDN Link: http://msdn2.microsoft.com/en-us/library/ms172331(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-105

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. The application uses a shared assembly for personalizing the user interface of the application. The same assembly is used by several other applications on the user's machine. Any changes in the user preferences in one application must be carried over to other applications. You need to access the user's preferences for displaying the user interface. What should you do? 1. Use the IsolatedStorageFile.GetUserStoreForAssembly method. 2. Use the IsolatedStorageFile.GetUserStoreForDomain method. 3. Use the IsolatedStorageFile.GetMachineStoreForAssembly method 4. Use the IsolatedStorageFile.GetMachineStoreForDomain method. Explanation : You should use the IsolatedStorageFile.GetUserStoreForAssembly method to read the user's preference. This method retrieves assembly-specific and user-specific data from the isolated storage. If the assembly is shared by other applications, the isolated storage area is shared too. You should not use the IsolatedStorageFile.GetUserStoreForDomain method because this method retrieves isolated storage that is application domain and assembly-specific. Because different applications will run in separate application domains, their storage areas will be isolated from each other. You should not use either the IsolatedStorageFile.GetMachineStoreForDomain or the IsolatedStorageFile.GetMachineStoreForAssembly methods because these methods are machine-scoped rather than user-scoped. That is, they will read the settings that are common to all the users on a machine. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Compress or decompress stream information in a .NET Framework application (Refer System.IO.Compression namespace), and improve the security of application data by using isolated storage. (Refer System.IO.IsolatedStorage namespace) IsolatedStorageFile Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-022

____________________________________________________________________________________________________________________ You are creating an application. You need to draw an ellipse like the one shown in the exhibit on the form. You need to add code to the Paint event procedure to draw the ellipse. What code should you use? 1. Graphics g = e.Graphics; Point[] p = new Point[2]; p[0].X = 0; p[0].Y = 0; p[1].X = 5; p[1].Y = 5; LinearGradientBrush myBrush = new LinearGradientBrush(p[0], p[1], Color.AliceBlue, Color.CadetBlue); Pen myPen = new Pen(myBrush); Rectangle myRect = new Rectangle(0, 0, 100, 150); g.DrawEllipse(myPen, myRect); 2. Graphics g = e.Graphics; Point[] p = new Point[2]; p[0].X = 0; p[0].Y = 0; p[1].X = 5; p[1].Y = 5; TextureBrush myBrush = new TextureBrush(p[0], p[1], Color.AliceBlue, Color.CadetBlue); Pen myPen = new Pen(myBrush); Rectangle myRect = new Rectangle(0, 0, 100, 150); g.DrawEllipse(myPen, myRect); 3. Graphics g = e.Graphics; Point[] p = new Point[2]; p[0].X = 0; p[0].Y = 0; p[1].X = 5; p[1].Y = 5; LinearGradientBrush myBrush = new LinearGradientBrush(p[0], p[1], Color.AliceBlue, Color.CadetBlue); Rectangle myRect = new Rectangle(0, 0, 100, 150); g.FillEllipse(myBrush, myRect); <Correct> 4. Graphics g = e.Graphics; Point[] p = new Point[2]; p[0].X = 0; p[0].Y = 0; p[1].X = 5; p[1].Y = 5; TextureBrush myBrush = new TextureBrush(p[0], p[1], Color.AliceBlue, Color.CadetBlue); Rectangle myRect = new Rectangle(0, 0, 100, 150); g.FillEllipse(myBrush, myRect); Explanation : You should use the following code: Graphics g = e.Graphics; Point[] p = new Point[2]; p[0].X = 0; p[0].Y = 0; p[1].X = 5; p[1].Y = 5;

LinearGradientBrush myBrush = new LinearGradientBrush(p[0], p[1], Color.AliceBlue, Color.CadetBlue); Rectangle myRect = new Rectangle(0, 0, 100, 150); g.FillEllipse(myBrush, myRect); The shape is an ellipse that is striped with a gradient. You can create a filled ellipse by calling the FillEllipse method of a Graphics object and passing a brush and a rectangle. The rectangle defines the bounds of the ellipse. Because you want the ellipse to be filled with a repeating pattern of gradients, you should create a brush of type LinearGradientBrush. You should not use the following code: Graphics g = e.Graphics; Point[] p = new Point[2]; p[0].X = 0; p[0].Y = 0; p[1].X = 5; p[1].Y = 5; TextureBrush myBrush =new TextureBrush(p[0], p[1], Color.AliceBlue, Color.CadetBlue); Rectangle myRect = new Rectangle(0, 0, 100, 150); g.FillEllipse(myBrush, myRect); The TextureBrush class is used to create a brush from a graphics file, such as a .bmp file. It is not instantiated using two points and two colors. You should not use a Pen object and the DrawEllipse method. The DrawEllipse method draws the outline of an ellipse, but does not fill it with a color or gradient. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Enhance the user interface of a .NET Framework application by using the System.Drawing namespace. References : LinearGradientBrush Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.drawing.drawing2d.lineargradientbrush(vs.80).aspx Graphics Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.drawing.graphics(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-004

____________________________________________________________________________________________________________________ You must check the date entered by a user against today's date to determine whether they are the same date. What code should you use? 1. DateTime today = DateTime.Today; IComparable isSame = new IComparable(); bool result; isSame = DateTime.Parse("1/7/2007"); result = isSame.Equals(today); 2. DateTime today = DateTime.Today; IComparable<DateTime> isSame; bool result; isSame = DateTime.Parse("1/7/2007"); result = isSame.Equals(today); 3. DateTime today = DateTime.Today; IEquatable isSame; bool result; isSame = DateTime.Parse("1/7/2007"); result = isSame.Equals(today); 4. DateTime today = DateTime.Today; IEquatable<DateTime> isSame; bool result; isSame = DateTime.Parse("1/7/2007"); result = isSame.Equals(today); <Correct> Explanation : One way to meet the requirement is to use the code: DateTime today = DateTime.Today; IEquatable<DateTime> isSame; bool result; isSame = DateTime.Parse("1/7/2007"); result = isSame.Equals(today); The IEquatable generic interface is implemented by class Object, which is a base for all .NET classes. It has a single method, Equals, which returns a Boolean value indicating whether the values are equal according to the rules defined by the type specified in the declaration of IEquatable. You should not use the code: DateTime today = DateTime.Today; IComparable<DateTime> isSame; bool result; isSame = DateTime.Parse("1/7/2007"); result = isSame.Equals(today); The IComparable generic interface allows for type-safe comparisons for sort operations. It implements a CompareTo method, not an Equals method. You should not use the code: DateTime today = DateTime.Today; IEquatable isSame; bool result; isSame = DateTime.Parse("1/7/2007");

result = isSame.Equals(today); The IEquatable interface is a generic interface and requires a type declaration. You should not use the code: DateTime today = DateTime.Today; IComparable isSame = new IComparable(); bool result; isSame = DateTime.Parse("1/7/2007"); result = isSame.Equals(today); IComparable is an interface, not a class. Therefore, it cannot be instantiated. Objective: Developing applications that use system types and collections Sub Objective(s): Implement .NET Framework interfaces to cause components to comply with standard contracts. (Refer System namespace) IEquatable Generic Interface MSDN Link: http://msdn2.microsoft.com/en-us/library/ms131187(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-115

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. Your application validates its users by using the user names and passwords stored in a Microsoft SQL Server 2005 database. You need to create an object that contains information about the user being validated. This object must contain the user name and authentication type. What should you do? 1. Create a WindowsIdentity object. 2. Create a GenericIdentity object. 3. Create a WindowsPrincipal object. 4. Create a GenericPrincipal object. Explanation : The identity object contains the information such as user name and authentication type for the user being validated. The GenericIdentity object is used for custom login scenarios, such as when the user names and passwords are stored in a SQL Server 2005 database. You should create a WindowsIdentity object only if you want to validate against Windows accounts. WindowsPrincipal and GenericPrincipal objects represent the security context for the executing code. They do not store identity information. They instead depend on the identity objects to provide identity information such as user name and authentication type. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement code access security to improve the security of a .NET Framework application. Refer System.Security namespace) Principal and Identity Objects MSDN Link: http://msdn2.microsoft.com/en-us/library/ftx85f8x(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-056

____________________________________________________________________________________________________________________ You are developing a Windows service application by using the .NET Framework. You need to synchronize execution of some resources across multiple processes. Which class should you use to accomplish this in your application? 1. Interlocked 2. Monitor 3. ReaderWriterLock 4. Mutex <Correct>

Explanation : The Mutex class can be used to synchronize thread execution across multiple processes. Therefore, Mutex is the correct answer in this case. The Monitor, ReaderWriterLock, and Interlocked classes are not the correct answers because they can only be used within a single process. The Monitor class is used to allow only a single thread to access a resource. The ReaderWriterLock class is used to allow multiple threads to read a resource and one thread to write to a resource concurrently. The Interlocked class allows you to perform certain operations on a resource as an atomic operation, meaning that either the entire operation is treated as a unit. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Develop multithreaded .NET Framework applications. (Refer System.Threading namespace) Mutex Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.threading.mutex(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-086

____________________________________________________________________________________________________________________ You are writing an application that will store user-specific configuration settings in a configuration file. You open the file using and retrieve the section using the code: Configuration cfgFile; ConfigurationSection cfgSection; cfgFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming); cfgSection = cfgFile.GetSection("LookAndFeel"); MakeChanges(cfgSection); The MakeChanges subprocedure is a custom procedure that modifies the properties of cfgSection as specified by the user. You need to write code to write the changes to the file. Only the settings that are not the same as the inherited settings should be written. What code should you use? 1. cfgSection.SectionInformation.ForceSave = true; cfgFile.Save(ConfigurationSaveMode.Minimal); <Correct> 2. cfgSection.SectionInformation.ForceSave = false; cfgFile.Save(ConfigurationSaveMode.Modified); 3. cfgSection.SectionInformation.AllowOverride = false; cfgFile.Save(ConfigurationSaveMode.Full); 4. cfgSection.SectionInformation.AllowOverride = true; cfgFile.Save(ConfigurationSaveMode.Modified); Explanation : You should use the following code: cfgSection.SectionInformation.ForceSave = true; cfgFile.Save(ConfigurationSaveMode.Minimal); The ConfigurationSaveMode.Minimal value specifies that only property values that are set to a different value than the inherited value are written to the file. The ForceSave property of the SectionInformation object specifies whether the properties should be written if the section has not been modified (a setting of true). Either a value of true or false will meet the requirements. You should not use the following code: cfgSection.SectionInformation.AllowOverride = true; cfgFile.Save(ConfigurationSaveMode.Modified); The Modified value specifies that only property values that have been modified should be written. This does not meet the requirement. The AllowOverride setting determines whether a configuration file lower in the hierarchy can override the values in the section. The scenario does not state any requirements about the ability of configuration files lower in the hierarchy to override the values. You should not use the code: cfgSection.SectionInformation.AllowOverride = false; cfgFile.Save(ConfigurationSaveMode.Full); The Full value specifies that all properties should be written, even if they are still set to the inherited defaults. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework

application Sub Objective(s): Embed configuration management functionality into a .NET Framework application (Refer System.Configuration namespace) ConfigurationSaveMode Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.configuration.configurationsavemode(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-088

____________________________________________________________________________________________________________________ You are developing a Windows application named Analyzer.exe by using the .NET Framework. This application must monitor the Application event log of the local computer to find if any new events are generated by another application named Notify.exe. Notify.exe runs on the local computer. The name of the local computer is ShipComp. When there is a new event log entry, your application must invoke the applicationLog_EntryWritten method in response. You write the following code in your application to generate notifications for new event log entries: EventLog applicationLog = new EventLog("Application", "."); applicationLog.EntryWritten += new EntryWrittenEventHandler (applicationLog_EntryWritten); private void applicationLog_EntryWritten(object sender, EntryWrittenEventArgs e) { if (e.Entry.Source == "Notify") { 'code to process event } } When you run the application, you find that no notifications are being generated. You need to ensure that you are notified of the new event log entries. What should you do? 1. Set the applicationLog.Source property to "Notify". 2. Set the applicationLog.MachineName property to ShipComp. 3. Set the applicationLog.Log property to Notify.exe. 4. Set the applicationLog.EnableRaisingEvents property to true. <Correct>

Explanation : You should set the EnableRaisingEvents property of the applicationLog object to true. When the EnableRaisingEvents property is set to true, it raises events when new entries are written to the specified event log. If the EnableRaisingEvents property is false, you will not receive notifications when new entries are written to the log. By default, the EnableRaisingEvents property is set to false. You should not set the applicationLog.Source property to "Notify". You must set the Source property when writing an event, not when reading one. The event procedure already has code to check for the source before processing the event. Setting the applicationLog.MachineName property to ShipComp is a redundant operation because the EventLog object is already pointing to the local machine by the virtue of the "." parameter in the constructor. Even if you specify the MachineName property again, you will not get event notification without first setting the EnableRaisingEvents property to true. Setting the applicationLog.Log property to Notify.exe is not correct because the Log property should specify the name of the event log. You are interested in reading the Application event log, and this has already been specified in the constructor of the EventLog object. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Manage an event log by using the System.Diagnostics namespace.

EventLog Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.eventlog(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-082

____________________________________________________________________________________________________________________ You are developing a geographical information system by using the .NET Framework. You create a class named GeoCode. You need to serialize all public and non-public data of the GeoCode class. You must produce the smallest byte stream so that the smallest load is placed on network resources. What should you do? 1. Use the XmlSerializationWriter class. 2. Use the SoapFormatter class. 3. Use the BinaryFormatter class. 4. Use the XmlSerializer class. Explanation : You should use the BinaryFormatter class because it allows you to serialize all public and non-public data. It also produces the most compact byte stream compared to other serialization classes. The SoapFormatter class does allow you to serialize all public and non-public data, but the resultant stream is verbose and will consume more network resources when compared to a stream generated by using BinaryFormatter. The XmlSerializer class only serializes public properties and fields. The XmlSerializationWriter class controls serialization by using the XmlSerializer class, so it also does not meet the requirements. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Implement custom serialization formatting by using the Serialization Formatter classes. BinaryFormatter Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryform atter(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-094

____________________________________________________________________________________________________________________ You are developing a new time management application by using the .NET Framework. The application needs to open a file named TimeManagement.xls as a maximized window using Microsoft Excel. Microsoft Office is installed on all end user computers. File associations have not been modified since the software was installed. You need to create a ProcessStartInfo object to provide file details to open the file. Which code segment should you use? 1. ProcessStartInfo psi = new ProcessStartInfo("c:\docs\TimeManagement.xls", "Excel"); psi.UseShellExecute = true; 2. ProcessStartInfo psi = new ProcessStartInfo("c:\docs\TimeManagement.xls"); psi.WindowStyle = ProcessWindowStyle.Maximized; Process.Start(Excel, psi); 3. ProcessStartInfo psi = new ProcessStartInfo("c:\docs\TimeManagement.xls"); Process proc = new Process(); proc.Start(psi); 4. ProcessStartInfo psi = new ProcessStartInfo("c:\docs\TimeManagement.xls"); psi.WindowStyle = ProcessWindowStyle.Maximized; Process.Start(psi); <Correct> Explanation : The ProcessStartInfo class allows you to specify an application file name with which the process should be started, configure the environment in which it should be started, and specify any command line arguments that need to be passed to the application. You can then pass the instance of the ProcessStartInfo class to the static Start method of the Process class. Therefore, one way to meet the requirements is with the following code: ProcessStartInfo psi = new ProcessStartInfo("c:\docs\TimeManagement.xls"); psi.WindowStyle = ProcessWindowStyle.Maximized; Process.Start(psi); You should not use the following code because the overload of the Start method that accepts a ProcessStartInfo object is a static method, not an instance method. ProcessStartInfo psi = new ProcessStartInfo("c:\docs\TimeManagement.xls"); Process proc = new Process(); proc.Start(psi); The following code will not start the process. Instead, it will configure process information for a file named "TimeManagement.xls" with a command-line argument of "Excel". ProcessStartInfo psi = new ProcessStartInfo("c:\docs\TimeManagement.xls", "Excel"); psi.UseShellExecute = true; You should not use the following code: ProcessStartInfo psi = new ProcessStartInfo("c:\docs\TimeManagement.xls"); psi.WindowStyle = ProcessWindowStyle.Maximized; Process.Start(Excel, psi); There is no overloaded version of the Start method that accepts the name of the application and an object of type ProcessStartInfo. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework

application Sub Objective(s): Manage system processes and monitor the performance of a .NET Framework application by using the diagnostics functionality of the .NET Framework 2.0. (Refer System.Diagnostics namespace) References : ProcessStartInfo Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.processstartinfo(vs.80).aspx Process.Start Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.process.start(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-046

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You need to store a collection of strongly typed objects in your application. The items in the collection are not necessarily in sorted order. You need to be able to retrieve the elements of the collection by specifying an index. What data type should you use to store the objects in your application? 1. Dictionary<TKey,TValue> 2. List<T> 3. Hashtable 4. ArrayList Explanation : You should use the List generic class (List<T>) to store the collection of objects in your application. The List generic class enables you to store strongly typed objects in your application. The List generic type also allows you to access the items in the collection by specifying an index. Using the Dictionary generic class (Dictionary<TKey,TValue>) to store the collection of objects is incorrect because although Dictionary generic class enables you to store strongly typed objects in your application, it does not allow you to access the collection items by using an index. The Dictionary generic class is key-centric because you need to supply a key (not an index) for an item that you want to retrieve. The ArrayList class is a non-generic equivalent of the List<T> class. Although ArrayList allows you to retrieve items in the collection by specifying an index, it does not allow strongly typed access to the objects. Therefore, using ArrayList in this case is incorrect. The HashTable class is a non-generic equivalent of the Dictionary<TKey,TValue> class. It does not allow strongly typed access to the object. It also does not allow the items to be accessed by specifying an index. Therefore, using HashTable in this case is incorrect. Objective: Developing applications that use system types and collections Sub Objective(s): Improve type safety and application performance in a .NET Framework application by using generic collections. (Refer System.Collections.Generic namespace) List Generic Class MSDN Link: http://msdn2.microsoft.com/en-us/library/6sh2ey19(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-024

____________________________________________________________________________________________________________________ You are developing an application that will be used globally. You must be able to represent the characters in the following languages: English, Hebrew, Chinese Traditional, and Tamil. Your application must provide error detection for invalid sequences of characters. Your application must also optimize storage. What should you use to encode the characters in your application? 1. UTF16Encoding class 2. UTF8Encoding class 3. UTF7Encoding class 4. UTF32Encoding class Explanation : You should use the UTF8Encoding class. You should not use the UTF7Encoding class because it does not provide error detection. You should only use UTF7Encoding for compatibility with applications that require it. The UTF8Encoding class can represent characters of all the given languages and offer optimum storage by using a sequence of one to four bytes depending on the requirement. UTF16Encoding represents each character as a sequence of one or two 16-bit integers. The UTF32Encoding class represents each character as a 32-bit integer. You will need to enable error detection by setting the throwOnInvalidBytes parameter to True. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Enhance the text handling capabilities of a .NET Framework application (refer System.Text namespace), and search, modify, and control text within a .NET Framework application by using regular expressions. (Refer System.RegularExpressions namespace) UTF8Encoding Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.text.utf8encoding(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-047

____________________________________________________________________________________________________________________ In your .NET Framework application, you write the following code: List<int> list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); list.Add(4); You need to write code that enables you to retrieve all the even numbers in the list object. What should you do? (Each correct answer presents part of the solution. Choose two.) 1. Add the following code beneath the existing code: List<int> l2 = new List<int>(); l2 = list.Find(FindValues); 2. Add the following code beneath the existing code: List<int> l2 = new List<int>(); l2 = list.TrueForAll(FindValues); 3. Add the following method to the class: public int FindValues(int value) { return value % 2; } 4. Add the following method to the class: public int FindValues(List<int> list, int value) { return list.IndexOf(value); } 5. Add the following code beneath the existing code: List<int> l2 = new List<int>(); l2 = list.FindAll(FindValues); <Correct> 6. Add the following method to the class: public bool FindValues(int value) { if ((value % 2) == 0) return true; else return false; } <Correct> Explanation : In this case, you need to find multiple items that meet a certain criteria in a list. You can accomplish this by using the FindAll method of the List<T> class. The FindAll method accepts a predicate delegate (reference to the method) and then executes the method pointed to by the delegate for each item in the list. The return value of the FindAll method is an object of the List<T> type that contains only the values for which the method pointed to by the delegate returned a value of true. Therefore, to find the even values, you should use the following code:

public bool FindValues(int value) { if ((value % 2) == 0) return true; else return false; } Using the TrueForAll method is incorrect because this method returns a Boolean value that only tells whether all the items in the list match the conditions defined by the method pointed to by the delegate object. Using the Find method is incorrect because it only returns the first occurrence of the matching item in the entire List. In this case, you need to find all occurrences, not just the first occurrence. Using the following methods: public int FindValues(int value) { return value % 2; } and public int FindValues(List<int> list, int value) { return list.IndexOf(value); } is incorrect because the FindValues method must return a Boolean value in order for the FindAll method to determine if an item matches the given criteria. Objective: Developing applications that use system types and collections Sub Objective(s): Improve type safety and application performance in a .NET Framework application by using generic collections. (Refer System.Collections.Generic namespace) References : List Generic Class MSDN Link: http://msdn2.microsoft.com/en-us/library/6sh2ey19(vs.80).aspx List.FindAll Method MSDN Link: http://msdn2.microsoft.com/en-US/library/fh1w7y8z(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-144

____________________________________________________________________________________________________________________ You use the .NET Framework to develop a client-server application. The server part of the application runs on a computer running Microsoft Windows Server 2003. All client computers run Microsoft Windows XP Professional. You need to write code that performs authentication and establishes a secure connection between the server and the client. You must make sure that the Kerberos protocol is used for authentication. You must also make sure that data is encrypted before it is transmitted over the network and decrypted when it reaches the destination. Which code segment should you use? 1. public void NetMethod(X509Certificate serverCertificate, Stream innerStream) { SslStream ss = new SslStream(innerStream); ss.AuthenticateAsServer(serverCertificate, true, SslProtocols.Tls, true); // Additional code } 2. public void NetMethod(X509Certificate serverCertificate, Stream innerStream) { SslStream ss = new SslStream(innerStream); ss.AuthenticateAsServer(serverCertificate, true, SslProtocols.Ssl3, true); // Additional code } 3. public void NetMethod(NetworkCredential credentials, Stream innerStream) { NegotiateStream ns = new NegotiateStream(innerStream); ns.AuthenticateAsServer(credentials, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Impersonation); // Additional code } <Correct> 4. public void NetMethod(NetworkCredential credentials, Stream innerStream) { NegotiateStream ns = new NegotiateStream(innerStream); ns.AuthenticateAsServer(credentials, ProtectionLevel.Sign, TokenImpersonationLevel.Impersonation); // Additional code } Explanation : You should use the following code segment: public void NetMethod(NetworkCredential credentials, Stream innerStream) { NegotiateStream ns = new NegotiateStream(innerStream); ns.AuthenticateAsServer(credentials, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Impersonation); // Additional code }

This code segment uses the NegotiateStream class. The NegotiateStream class uses the Kerberos protocol for authentication if it is supported by both the client and the server. Windows Server 2003 and Windows XP both support the Kerberos protocol. When the value ProtectionLevel.EncryptAndSign is passed as a parameter to the AuthenticateAsServer method, it specifies that data must be encrypted and signed before it is transmitted over the network and decrypted and verified when it reaches the destination. You should not use the following code segment because when the value ProtectionLevel.Sign is passed as a parameter to the AuthenticateAsServer method, it specifies that data should only be signed (rather than both encrypted and signed) before it is transmitted: public void NetMethod(NetworkCredential credentials, Stream innerStream) { NegotiateStream ns = new NegotiateStream(innerStream); ns.AuthenticateAsServer(credentials, ProtectionLevel.Sign, TokenImpersonationLevel.Impersonation); // Additional code } You should not use the following code segment because it uses X509 certificates for authentication rather than the Kerberos protocol: public void NetMethod(X509Certificate serverCertificate, Stream innerStream) { SslStream ss = new SslStream(innerStream); ss.AuthenticateAsServer(serverCertificate, true, SslProtocols.Tls, true); // Additional code } You should not use the following code segment because it uses X509 certificates for authentication rather than the Kerberos protocol: public void NetMethod(X509Certificate serverCertificate, Stream innerStream) { SslStream ss = new SslStream(innerStream); ss.AuthenticateAsServer(serverCertificate, true, SslProtocols.Ssl3, true); // Additional code } Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement a custom authentication scheme by using the System.Security.Authentication classes. (Refer System.Security.Authentication namespace) References : NegotiateStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.net.security.negotiatestream(vs.80).aspx SslStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.net.security.sslstream(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-018

____________________________________________________________________________________________________________________ You need to store a type-safe list of names and e-mail addresses in your .NET Framework application. Only one name can be associated with any e-mail address. This list will be populated all at once from sorted data. You will rarely need to perform insertion or deletion operations on the data. You need to choose a data structure that optimizes memory use and has good performance. What should you do? 1. Use the System.Collections.Generic.SortedDictionary class. 2. Use the System.Collections.Generic.SortedList class. 3. Use the System.Collections.HashTable class. 4. Use the System.Collections.SortedList class. Explanation : You should use the SortedList generic class in this scenario. The SortedList generic class provides type safety and is appropriate for managing data that rarely requires insertions or deletions. Although SortedList and SortedDictionary are very similar in their implementation, you should use SortedList in this case because SortedList uses less memory than SortedDictionary. SortedList is slower than SortedDictionary when performing insertions and deletions on unsorted data. But in this case, insertions and deletions are performed rarely. You should not use the System.Collections.SortedList class because this class is not type-safe. To create a type-safe list, you should use a class from the System.Collections.Generic namespace. You should not use the System.Collections.HashTable class because this class is not type-safe. To create a type-safe list, you should use a class from the System.Collections.Generic namespace. Objective: Developing applications that use system types and collections Sub Objective(s): Manage a group of associated data in a .NET Framework application by using collections (Refer System.Collections namespace) SortedList Generic Class MSDN Link: http://msdn2.microsoft.com/en-us/library/ms132319(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-014

____________________________________________________________________________________________________________________ You are designing an application that needs to connect to and control the behavior of existing services installed on a network server named SRV1. Which properties should you use? (Each correct answer presents part of the solution. Choose two.) 1. ServiceInstaller.DisplayName 2. ServiceController.MachineName 3. ServiceInstaller.ServiceName 4. ServiceController.ServiceName 5. ServiceInstaller.Site 6. ServiceController.Site Explanation : You use the ServiceController class to connect to an existing service and manage its behavior. Before you can manage a service using the ServiceController class, you must set two properties on it to identify the service with which it interacts. The MachineName property identifies the computer, and the ServiceName property identifies the service you want to control. The Site property of the ServiceController or ServiceInstaller class is not a correct answer because the Site property binds a Component to a Container and enables communication between them. It does not provide any way to connect to a specific server or a specific service. The ServiceInstaller.ServiceName property is not a correct answer because this property is used to specify the name of the service at the time of installation. In the scenario, the service is already installed. ServiceInstaller.DisplayName property is not a correct answer because this property is used to specify a friendly name for the service at the time of installation. In the scenario, the service is already installed. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Implement, install, and control a service. (Refer System.ServiceProcess namespace) References : ServiceController Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.serviceprocess.servicecontroller(vs.80).aspx ServiceInstaller Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.serviceprocess.serviceinstaller(vs.80).aspx <Correct> <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-074

____________________________________________________________________________________________________________________ You are developing a banking Windows Forms application by using the .NET Framework. You are working on a function that retrieves the images of canceled checks and displays them on the form. You have access to a method that reads the images from Microsoft SQL Server as a series of bytes. You need to select a class that allows you to transfer the image from SQL Server to the Windows Forms application. Your solution must reduce the need for any temporary buffers and files. Which class should you select? 1. MemoryStream 2. BufferedStream 3. NetworkStream 4. FileStream Explanation : With the given requirements, you should use the MemoryStream class. With MemoryStream, you can read the image data in memory and stream it to a Windows Forms application without creating any temporary buffers or files. Using the FileStream and BufferedStream classes is incorrect because they require the creation of temporary files or buffers. Using the NetworkStream class is incorrect because you do not need to directly establish a network connection with SQL Server database. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Manage byte streams by using Stream classes. (Refer System.IO namespace) MemoryStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.memorystream(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-084

____________________________________________________________________________________________________________________ You are developing an inventory application by using the .NET Framework. You develop the following class: public class Inventory { public event EventHandler Reorder; private int quantity; public void SellOne() { quantity = quantity - 1; if (quantity == 0) OnReorder(new EventArgs()); } } You need to define the OnReorder method to raise the Reorder event. Which code segment should you use? 1. protected virtual void OnReorder(EventArgs e) { Reorder(this, e); } 2. protected virtual void OnReorder(EventArgs e) { if (e == null) Reorder(this, e); } 3. protected virtual void OnReorder(EventArgs e) { if (Reorder != null) Reorder(this, e); } <Correct> 4. protected virtual void OnReorder(EventArgs e) { if (Reorder == null) Reorder(this, e); } Explanation : You should use the following code segment: protected virtual void OnReorder(EventArgs e) { if (Reorder != null) Reorder(this, e); } If no event handlers have been attached to the event Reorder, it will contain a null value. You must check for the null value before you raise the event. Based on the event definition, the event is of the type of EventHandler delegate, which has the following signature: delegate void EventHandler(object sender, EventArgs e);

When you raise the event, you must therefore pass two parameters, the first one of the type Object and second one of the type EventArgs. The following code segment is incorrect because if the one or more delegates have been attached to the event, it will not be null and therefore the event will not be raised. Otherwise, the code will throw a System.NullReferenceException exception. protected virtual void OnReorder(EventArgs e) { if (Reorder == null) Reorder(this, e); } The following code is not correct because before raising the event, you must check if it is a non-null value. If the event is null, the code will throw a System.NullReferenceException exception. protected virtual void OnReorder(EventArgs e) { Reorder(this, e); } The following code is incorrect because you must check whether the Reorder event is null rather than checking if the event argument is null. Having a null event argument is okay, but having a null event will throw a System.NullReferenceException exception. protected virtual void OnReorder(EventArgs e) { if (e == null) Reorder(this, e); } Objective: Developing applications that use system types and collections Sub Objective(s): Control interactions between .NET Framework application components by using events and delegates. (Refer System namespace) How to: Implement Events in Your Class MSDN Link: http://msdn2.microsoft.com/en-us/library/5z57dxz2(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-091

____________________________________________________________________________________________________________________ You are developing a console application by using the .NET Framework. You need to enumerate all disk drives on the local computer and list their drive letters and available free space. You decide to use the functionality in the System.Management namespace to accomplish this task. Which code segment should you use? 1. SelectQuery sq = new SelectQuery("Select * from Win32_LogicalDisk"); ManagementObjectSearcher mos = new ManagementObjectSearcher(sq); foreach (ManagementObject mo in mos.Get()) { Console.WriteLine("Drive {0}, Free Space {1}", mo["Name"], mo["FreeSpace"]); } <Correct> 2. SelectQuery sq = new SelectQuery("Select * from Win32_LogicalDisk"); ManagementObjectSearcher mos = new ManagementObjectSearcher(sq); foreach (ManagementObject mo in mos.Get()) { Console.WriteLine("Drive {0}, Free Space {1}", mo["Description"], mo["FreeSpace"]); } 3. SelectQuery sq = new SelectQuery("Select * from Win32_LogicalDisk"); ManagementObjectSearcher mos = new ManagementObjectSearcher(sq); foreach (ManagementObject mo in mos.Get()) { Console.WriteLine("Drive {0}, Free Space {1}", mo["DeviceID"], mo["NumberOfBlocks"]); } 4. SelectQuery sq = new SelectQuery("Select * from Win32_LogicalDisk"); ManagementObjectSearcher mos = new ManagementObjectSearcher(sq); foreach (ManagementObject mo in mos.Get()) { Console.WriteLine("Drive {0}, Free Space {1}", mo["DeviceID"], mo["NumberOfBlocks"]); } Explanation : You need to use the following code segment to list the drive letters and available free space: SelectQuery sq = new SelectQuery("Select * from Win32_LogicalDisk"); ManagementObjectSearcher mos = new ManagementObjectSearcher(sq); foreach (ManagementObject mo in mos.Get()) { Console.WriteLine("Drive {0}, Free Space {1}", mo["Name"], mo["FreeSpace"]); } Using the Description property of the Win32_LogicalDisk management object is incorrect because it does not return the drive letter. Instead, the Description property returns the description of the object. Using the NumberOfBlocks property is incorrect because it returns the block size of each disk rather than its free space.

Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Embed management information and events into a .NET Framework application. (Refer System.Management namespace) References : ManagementObjectSearcher Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.management.managementobjectsearcher(vs.80).aspx Win32_LogicalDisk MSDN Link: http://msdn2.microsoft.com/en-us/library/aa394173.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-067

____________________________________________________________________________________________________________________ You are developing a resource management utility by using the .NET Framework. You need to monitor for the creation of a file with the .res extension in c:\dir1. When a file with the .res extension is created, you will execute code to read and process its contents. You need to write code that enables you to asynchronously monitor the creation of the .res file. What code should you write? 1. FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"c:\dir1"; watcher.Filter = "*.res"; watcher.WaitForChanged(WatcherChangeTypes.Created); 2. FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"c:\dir1"; watcher.Filter = "*.res"; watcher.EnableRaisingEvents=true; <Correct> 3. FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"c:\dir1"; watcher.NotifyFilter = "*.res"; watcher.EnableRaisingEvents=true; 4. FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Filter = @"c:\dir1\*.res"; watcher.WaitForChanged(WatcherChangeTypes.Created); Explanation : You should first create a FileSystemWatcher object and set its Path and Filter properties. The Path property specifies the path in which to look for the changes. The Filter property specifies the type of files to look at. You should use the following code: FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"c:\dir1"; watcher.Filter = "*.res"; Next, you should enable the FileSystemWatcher to raise events as follows: watcher.EnableRaisingEvents=true The EnableRaisingEvents flag monitors the path for an event that matches the filter and the event type, and then calls the appropriate event handler. You would also need to create an event handler associated with the Created event. You should not use the following code because the Filter property is used only to specify the pattern of the file name. You should not include directory information in the Filter property. FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Filter = @"c:\dir1\*.res"; watcher.WaitForChanged(WatcherChangeTypes.Created); Note that the WaitForChanged method synchronously waits for file system changes that match the given Path and Filter and returns a WaitForChangedResult object that specifies the changes. You should not use the code: watcher.Path = "c:\dir1" watcher.NotifyFilter = "*.res" watcher.EnableRaisingEvents=true

The NotifyFilter property is used to selectively watch for events that change certain file properties, such as the last time the file was opened or a change to security settings. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Access files and folders by using the File System classes. (Refer System.IO namespace) FileSystemWatcher Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.filesystemwatcher(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-143

____________________________________________________________________________________________________________________ You are developing an application by using the .NET Framework. You need to write code to make sure that the Windows user DOMAIN\ProdUser is granted read rights to all the files in the c:\docs directory and its subdirectories, including the nested directories. You should not overwrite any other security settings associated with the c:\docs directory. Which code segment should you choose? 1. DirectorySecurity dirSec = Directory.GetAccessControl(@"c:\docs"); FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); dirSec.SetAccessRule(fsaRule); 2. DirectorySecurity dirSec = Directory.GetAccessControl(@"c:\docs", AccessControlSections.Audit); FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); dirSec.SetAccessRule(fsaRule); 3. DirectorySecurity dirSec = Directory.GetAccessControl(@"c:\docs"); FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); dirSec.AddAccessRule(fsaRule); Directory.SetAccessControl(@"c:\docs", dirSec); <Correct> 4. DirectorySecurity dirSec = Directory.GetAccessControl(@"c:\docs"); FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); dirSec.AddAccessRule(fsaRule); Directory.SetAccessControl(@"c:\docs", dirSec); Explanation : You should use the following code segment: DirectorySecurity dirSec = Directory.GetAccessControl(@"c:\docs"); FileSystemAccessRule fsaRule = new FileSystemAccessRule( new NTAccount(@"DOMAIN\ProdUser"), FileSystemRights.Read, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); dirSec.AddAccessRule(fsaRule); Directory.SetAccessControl(@"c:\docs", dirSec); The Directory.GetAccessControl method retrieves the current access control settings on the c:\docs directory. You then create a new FileSystemAccessRule that specifies that read rights should be available

for only files (by virtue of InheritanceFlags.ObjectInherit) and should be available within the parent directory (c:\docs) and all of its subdirectories, including nested directories (by virtue of PropagationFlags.None). The newly created FileSystemAccessRule object is then added to the access control settings in the dirSec object. Finally, you call the Directory.SetAccessControl method to apply the security settings to the c:\docs directory. You should not use the following code segment because it will retrieve the system access control list (SACL) instead of the discretionary access control list (DACL): DirectorySecurity dirSec = Directory.GetAccessControl(@"c:\docs", AccessControlSections.Audit); You should not use the following code segment because the SetAccessRule method overwrites any existing access control settings by the specified access control settings. In this case, you should not overwrite any other security settings associated with the c:\docs directory. dirSec.SetAccessRule(fsaRule); Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement access control by using the System.Security.AccessControl classes. Safety in Windows: Manage Access to Windows Objects with ACLs and the .NET Framework MSDN Link: http://msdn.microsoft.com/msdnmag/issues/04/11/AccessControlinNET/

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-025

____________________________________________________________________________________________________________________ You are developing a text-processing application by using .NET Framework class libraries. You define the following regular expression for currency values: Regex rx = new Regex(@"^-?\d+(\.\d{2})?$"); You need to write code that finds whether a string in the variable named "test" matches the regular expression or not. Which code segment should you use? 1. if (rx.Equals(test)) { } 2. if (rx.Match(test)) { } 3. if (rx.Matches(test)) { } 4. if (rx.IsMatch(test)) { } <Correct> Explanation : You should use if (rx.IsMatch(test)). The IsMatch method returns True if the regular expression finds a match in the input string. Using the Match method is incorrect because the Match method searches an input string for the first occurrence of a regular expression. If it exists, it returns the result as a Match object. Because this method does not return a Boolean, you cannot use if (rx.Match(test)). Using the Matches method is incorrect because the Matches method searches a string for all occurrences of a regular expression and returns a MatchCollection object that contains all the successful matches as if the Match method was called numerous times. Using the Equals method is incorrect because the Equals method determines whether two Object instances are equal. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Enhance the text handling capabilities of a .NET Framework application (refer System.Text namespace), and search, modify, and control text within a .NET Framework application by using regular expressions. (Refer System.RegularExpressions namespace) Regex Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.text.regularexpressions.regex(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-018

____________________________________________________________________________________________________________________ You are writing an application. You need to examine the assembly named FunnyUI.dll at runtime to determine whether it has any classes that derive from the Rectangle class and, if so, make them available for instantiation by storing their fully-qualified name in an array. What code should you use? 1. Type[] t; Type[] rectangles = new Type[100]; Rectangle rect = new Rectangle(); Type rectType = rect.GetType(); Assembly funnyAssembly = Assembly.LoadFile("C:\\funny\\funnyui.dll"); t = funnyAssembly.GetModules(); int i; int r = 0; for(i=0; i<t.Length; i++) { if(t[i].IsSubclassOf(rectType)) { rectangles[r] = t[i]; r = r+1; } } 2. Type[] t; Type[] rectangles = new Type[100]; Rectangle rect = new Rectangle(); Type rectType = rect.GetType(); Assembly funnyAssembly = Assembly.LoadFile("C:\\funny\\funnyui.dll"); t = funnyAssembly.GetTypes(); int i; int r = 0; for(i=0; i<t.Length; i++) { if(t[i].BaseType == rectType) { rectangles[r] = t[i]; r = r+1; } } 3. Type[] t; Type[] rectangles = new Type[100]; Rectangle rect = new Rectangle(); Type rectType = rect.GetType(); Assembly funnyAssembly = Assembly.LoadFile("C:\\funny\\funnyui.dll"); t = funnyAssembly.GetModules(); int i; int r = 0; for(i=0; i<t.Length; i++) { if(t[i].BaseType == rectType) { rectangles[r] = t[i]; r = r+1; } } 4. Type[] t; Type[] rectangles = new Type[100]; Rectangle rect = new Rectangle(); Type rectType = rect.GetType(); Assembly funnyAssembly = Assembly.LoadFile("C:\\funny\\funnyui.dll"); t = funnyAssembly.GetTypes(); int i;

int r = 0; for(i=0; i<t.Length; i++) { if(t[i].IsSubclassOf(rectType)) { rectangles[r] = t[i]; r = r+1; } } <Correct> Explanation : You should use the following code: Type[] t; Type[] rectangles = new Type[100]; Rectangle rect = new Rectangle(); Type rectType = rect.GetType(); Assembly funnyAssembly = Assembly.LoadFile("C:\\funny\\funnyui.dll"); t = funnyAssembly.GetTypes(); int i; int r = 0; for(i=0; i<t.Length; i++) { if(t[i].IsSubclassOf(rectType)) { rectangles[r] = t[i]; r = r+1; } } The GetTypes method returns an array of Type objects for each type defined in the assembly. A Type can be a class, but might also be an enumeration, a generic class, an interface, or a value data type. The IsSubclassOf method of the Type object checks whether the Type is derived from the type passed to the method. In this case, the Drawing.Rectangle class. You should not use the code: Type[] t; Type[] rectangles = new Type[100]; Rectangle rect = new Rectangle(); Type rectType = rect.GetType(); Assembly funnyAssembly = Assembly.LoadFile("C:\\funny\\funnyui.dll"); t = funnyAssembly.GetModules(); int i; int r = 0; for(i=0; i<t.Length; i++) { if(t[i].IsSubclassOf(rectType)) { rectangles[r] = t[i]; r = r+1; } } The GetModules method returns an array of modules in the assembly. You should not use the code: Type[] t; Type[] rectangles = new Type[100]; Rectangle rect = new Rectangle(); Type rectType = rect.GetType(); Assembly funnyAssembly = Assembly.LoadFile("C:\\funny\\funnyui.dll"); t = funnyAssembly.GetTypes(); int i; int r = 0; for(i=0; i<t.Length; i++) { if(t[i].BaseType == rectType) { rectangles[r] = t[i]; r = r+1; } } The BaseType property returns the immediate base type for the type. So, if the class is derived from BlueRectangle, which in turn derives from Rectangle, the condition will be evaluated as false. While you can write nested loops to drill down through the class hierarchy, doing so

requires more code and is less optimal than calling IsSubclassOf. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Implement reflection functionality in a .NET Framework application (refer System.Reflection namespace), and create metadata, Microsoft intermediate language (MSIL), and a PE file by using the System.Reflection.Emit namespace. References : Type Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.type(vs.80).aspx Assembly Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.reflection.assembly(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-113

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code in your application: public interface IShape { double GetArea(); double GetPerimeter(); } public class Shape : IShape { public Shape() { } public double GetArea() { double area = 0; // Additional code goes here return area; } public double GetPerimeter() { double perimeter = 0; // Additional code goes here return perimeter; } } You must make sure that Component Object Model (COM) clients interact with the members of the Shape class exclusively by using an interface reference. The COM clients must only be able to early-bind to the types in the .NET assembly. You must also make sure that adding or rearranging members to the IShape interface does not cause existing COM clients to fail. What should you do? (Each correct answer presents part of the solution. Choose two.) 1. Apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.AutoDispatch)] 2. Apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.AutoDual)] 3. Apply the following attribute to the IShape interface: [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] 4. Apply the following attribute to the IShape interface: [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] <Correct> 5. Apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.None)] <Correct> Explanation : The ClassInterfaceType.None setting indicates that no class interface is automatically generated for the class. Any functionality of the class in this case must be exposed through the interface that is explicitly implemented by the class. Therefore, you should apply the following attribute to the Shape class:

[ClassInterface(ClassInterfaceType.None)] The InterfaceType attribute indicates how an interface is exposed to COM. The ComInterfaceType.InterfaceIsIUnknown setting of the InterfaceType attribute only supports early-binding. Therefore, you should apply the following attribute to the IShape interface: [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] The default setting for the ClassInterface attribute is ClassInterfaceType.AutoDispatch, which indicates that an interface is automatically generated for the COM client on request at runtime. Therefore, you should not apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.AutoDispatch)] The ClassInterfaceType.AutoDual setting binds to a specific interface layout. This may create problems when the order of members in an interface is changed in later versions. Because it can create versioning problems, the use of ClassInterfaceType.AutoDual setting is discouraged. Therefore, you should not apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.AutoDual)] The default setting of the InterfaceType attribute is ComInterface.InterfaceIsDual, which means that the interface supports both early-binding and late-binding. The ComInterfaceType.InterfaceIsIDispatch setting of the InterfaceType attribute only supports late-binding. Therefore, you should not apply the following attribute to the IShape interface: [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Expose COM components to the .NET Framework and .NET Framework components to COM. (Refer System.Runtime.InteropServices namespace) References : ClassInterfaceAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.classinterfaceattribute(vs .80).aspx InterfaceTypeAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.interfacetypeattribute(vs. 80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-062

____________________________________________________________________________________________________________________ You develop a Windows application by using the .NET Framework. The application makes use of an assembly named MyAssembly. The assembly file MyAssembly.dll is deployed in a folder named bin20 under the application's root directory. The MyAssembly assembly is not strongly named. You must configure the Windows application to specify the location of the MyAssembly assembly. Any settings that you change must not affect other applications installed on the system. What should you do? 1. Modify the machine configuration file and add the following setting to the <assemblyBinding> section for the MyAssembly assembly: <codeBase href="bin20/myAssembly.dll"/> 2. Modify the application configuration file to add the following setting to the <assemblyBinding> section: <probing privatePath="bin20"/> <Correct> 3. Modify the machine configuration file and add the following setting to the <assemblyBinding> section for the MyAssembly assembly: <codeBase href="bin20"/> 4. Modify the application configuration file to add the following setting to the <assemblyBinding> section: <probing privatePath="bin20\MyAssembly.dll"/> Explanation : The MyAssembly assembly is not strongly named. Any configuration to such an assembly must be made at the local level by using the application configuration file. You can use the <probing> element to specify the path where the runtime should search for an assembly. This can be correctly done by using the following setting: <probing privatePath="bin20"/> Specifying the file name as in the following setting is incorrect because you only need to specify the path name, and the runtime automatically loads the file containing the correct assembly from that path: <probing privatePath="bin20\MyAssembly.dll"/> Modifying the machine configuration file is incorrect because you need to ensure that the changes do not affect other applications installed on the computer. The machine.config file is used by all applications on the computer. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Create a custom Microsoft Windows Installer for .NET Framework components by using the System.Configuration.Install namespace, and configure .NET Framework applications by using configuration files, environment variables, and the .NET Framework Configuration tool (Mscorcfg.msc). Specifying an Assembly's Location

MSDN Link: http://msdn2.microsoft.com/en-us/library/4191fzwb.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-072

____________________________________________________________________________________________________________________ You are developing a text processing application by using the .NET Framework. You write the following code as part of this application: TextWriter stringWriter = new StringWriter(); using (TextWriter streamWriter = new StreamWriter("MyFile.txt")) { WriteText(stringWriter); WriteText(streamWriter); } The WriteText method must write the string "Message One" to the writer object that is passed to it. How should you write the WriteText method? 1. private void WriteText(StreamWriter writer) { writer.Write("Message One"); } 2. private void WriteText(TextWriter writer) { writer.Write("Message One"); } <Correct> 3. private void WriteText(BinaryWriter writer) { writer.Write("Message One"); } 4. private void WriteText(StringWriter writer) { writer.Write("Message One"); } Explanation : You should write the WriteText method by passing a TextWriter object to it as shown below: private void WriteText(TextWriter writer) { writer.Write("Message One"); } StreamWriter and StringWriter both are derived from the TextWriter class. By the virtue of polymorphism, the Write method inside the function is automatically invoked on the correct underlying type, StreamWriter or StringWriter. Using StreamWriter or StringWriter instead of TextWriter in the method parameter is incorrect because then it will be only possible to pass either the StreamWriter object or StringWriter object to the method, but not both. Using BinaryWriter instead of TextWriter in the method parameter is incorrect because the BinaryReader is incompatible with both StreamWriter and StringWriter. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Manage .NET Framework application data by using Reader and Writer classes. (Refer System.IO

namespace) TextWriter Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.textwriter(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-129

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. Your program should be able to copy the text of a specified window's title bar. You decide to use the GetWindowText method of the user32.dll unmanaged DLL in your application. The GetWindowText method is declared as follows: int GetWindowText(HWND hWnd, LPTSTR lpString, int nMaxCount); The hWnd parameter is a handle to the window containing the text, lpstring is a pointer to the buffer that will receive the text, and nMaxCount is the maximum number of characters to copy to the buffer. You need to declare the GetWindowText method in your managed application. What code should you use? 1. [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] static extern int GetWindowText(IntPtr hWnd, ref StringBuilder lpString, int nMaxCount); 2. [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] static extern int GetWindowText(IntPtr hWnd, [Out] String lpString, int nMaxCount); 3. [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount); <Correct> 4. [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] static extern int GetWindowText(IntPtr hWnd, ref String lpString, int nMaxCount); Explanation : You should use the following declaration: [DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)] static extern int GetWindowText(IntPtr hWnd, [Out] StringBuilder lpString, int nMaxCount); The lpstring parameter is an output parameter. To allow the function to modify the actual string, you must use the StringBuilder object instead of a string object. Another advantage to using a StringBuilder object is that you can specify a specific length for the string. The [Out] attribute, when applied to the parameters, marshals the data back to the caller from the callee. You should not use a string object because strings in the .NET Framework are immutable. That is, any modifications to a string create a new string. If you use a string object to represent the lpstring parameter, you will get an empty string because the modifications made to the string object will not be preserved. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Call unmanaged DLL functions within a .NET Framework application, and control the marshalling of data in a .NET Framework application. (Refer System.Runtime.InteropServices namespace) References : Directional Attributes MSDN Link: http://msdn2.microsoft.com/en-us/library/77e6taeh(vs.80).aspx

C++ Q&A: Call Unmanaged DLLs from C#, Killing Processes Cleanly MSDN Link: http://msdn.microsoft.com/msdnmag/issues/02/08/CQA

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-060

____________________________________________________________________________________________________________________ You develop a new Windows service application by using the .NET Framework. You need to change the security context in which the service runs. You want the service to run in the context of a non-privileged user on the local computer and present anonymous credentials to any remote server. You must set the Account property of the ServiceProcessInstaller class to specify the service account. What value should you specify for the Account property? 1. ServiceAccount.LocalService 2. ServiceAccount.NetworkService 3. ServiceAccount.LocalSystem 4. ServiceAccount.User Explanation : You should use ServiceAccount.LocalService as the value of the Account property of the ServiceProcessInstaller class. Setting this value runs the service in the context of a non-privileged user on the local computer and presents anonymous credentials to remote servers. You should not use ServiceAccount.User as the value of the Account property of the ServiceProcessInstaller class. Setting this value runs the service in the context of a specified user account. Privileges are defined by the privileges of the user, and network credentials are not anonymous. You should not use ServiceAccount.LocalSystem as the value of the Account property of the ServiceProcessInstaller class. Setting this value runs the service in the context of a user with very high privileges and presents the computer's credentials to remote servers. You should not use ServiceAccount.NetworkService as the value of the Account property of the ServiceProcessInstaller class. Setting this value runs the service in the context of a non-privileged user on the local computer but presents the computer's credentials to remote servers. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Implement, install, and control a service. (Refer System.ServiceProcess namespace) How to: Specify the Security Context for Services MSDN Link: http://msdn2.microsoft.com/en-us/library/0x72fzyf(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-076

____________________________________________________________________________________________________________________ You are designing a Windows application with the .NET Framework. The application reads bytes from several sources. You must optimize your code for performance. You use the BufferedStream class to specify a buffer size and improve the code performance. However, runtime tests reveal that not all code segments are equally benefiting from the use of the BufferedStream class. Which code benefits the most from the use of the BufferedStream class? 1. Stream myStream = new UnmanagedMemoryStream(memBytePtr, message.Length, message.Length, FileAccess.Read); BufferedStream bufStream = new BufferedStream(myStream, streamBufferSize); 2. Stream myStream = new NetworkStream(clientSocket, true); BufferedStream bufStream = new BufferedStream(myStream, streamBufferSize); <Correct> 3. Stream myStream = new FileStream(fileName, FileMode.Open); BufferedStream bufStream = new BufferedStream(myStream, streamBufferSize); 4. Stream myStream = new MemoryStream(10000); BufferedStream bufStream = new BufferedStream(myStream, streamBufferSize); Explanation : The following code will benefit the most from the use of the BufferedStream class: Stream myStream = new NetworkStream(clientSocket, true); BufferedStream bufStream = new BufferedStream(myStream, streamBufferSize); The BufferedStream class uses a buffer of data that can be used to reduce the number of calls that need to be made over the network for read operation. Wrapping a BufferedStream around a FileStream does not provide any additional benefit because the FileStream class itself offers buffering and better default performance. Wrapping a BufferedStream around a MemoryStream or an UnmanagedMemoryStream will not provide any additional benefit because these objects are maintained in memory anyway and do not use any buffers. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Manage byte streams by using Stream classes. (Refer System.IO namespace) BufferedStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.bufferedstream(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-112

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code in your application: public interface IShape { double GetArea(); double GetPerimeter(); } public class Shape : IShape { public Shape() { } public double GetArea() { double area = 0; // Additional code goes here return area; } public double GetPerimeter() { double perimeter = 0; // Additional code goes here return perimeter; } } You must make sure that Component Object Model (COM) clients interact with the members of the Shape class exclusively by using an interface reference. The COM clients must also be able to late-bind or early-bind to the types in the .NET assembly. You must also make sure that adding or rearranging members to the IShape interface does not cause existing COM clients to fail. What should you do? 1. Apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.AutoDispatch)] 2. Apply the following attribute to the IShape interface: [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] 3. Apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.AutoDual)] 4. Apply the following attribute to the IShape interface: [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 5. Apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.None)] <Correct> Explanation : The ClassInterfaceType.None setting indicates that no class interface is automatically generated for the class. Any functionality of the class in this case must be exposed through the interface that is explicitly implemented by the class. Therefore, you should apply the following attribute to the Shape class:

[ClassInterface(ClassInterfaceType.None)] The default setting for the ClassInterface attribute is ClassInterfaceType.AutoDispatch, which indicates that an interface is automatically generated for the COM client on request at runtime (late-bound only). Therefore, you should not apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.AutoDispatch)] The ClassInterfaceType.AutoDual setting binds to a specific interface layout. This may create problems when the order of members in an interface is changed in later versions. Because it can create versioning problems, the use of ClassInterfaceType.AutoDual setting is discouraged. Therefore, you should not apply the following attribute to the Shape class: [ClassInterface(ClassInterfaceType.AutoDual)] The InterfaceType attribute indicates how an interface is exposed to COM. The default setting of this attribute is ComInterface.InterfaceIsDual, which means that the interface supports both early-binding and late-binding. The ComInterfaceType.InterfaceIsIDispatch setting of the InterfaceType attribute only supports late-binding. Therefore, you should not apply the following attribute to the IShape interface: [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] The ComInterfaceType.InterfaceIsIUnknown setting of the InterfaceType attribute only supports early-binding. Therefore, you should not apply the following attribute to the IShape interface: [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Expose COM components to the .NET Framework and .NET Framework components to COM. (Refer System.Runtime.InteropServices namespace) References : ClassInterfaceAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.classinterfaceattribute(vs .80).aspx InterfaceTypeAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.interfacetypeattribute(vs. 80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-150

____________________________________________________________________________________________________________________ You develop a .NET Framework application. The assembly is added to these four code groups at the Enterprise level policy: * All Code code group with a permission set of Everything * Known Code code group with a permission set of Local Intranet * Unknown Code code group with a permission set of Internet * Restricted Code code group with a permission set of Nothing The assembly is not a member of any other code groups. When the assembly is executed, what permissions does the Common Language Runtime (CLR) assign to the assembly? 1. Nothing 2. Internet 3. Local Intranet 4. Everything <Correct> Explanation : The correct answer is Everything. Within a level (Enterprise level in this case) the permission set granted to an assembly is the union of all permission sets of the code groups to which the assembly belongs. The result of the union operation is the most unrestrictive permission, Everything. The intersection of permission sets is only applied across different policy levels. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control code privileges by using System.Security.Policy classes. (Refer System.Security.Policy namespace) Computing the Allowed Permission Set MSDN Link: http://msdn2.microsoft.com/en-us/library/kb207s5y(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-050

____________________________________________________________________________________________________________________ You have developed a class library by using the .NET Framework. The class library contains the following code: class Area { public double ToDouble(IFormatProvider provider) { //Additional code here } } This class is already deployed and is used by the client applications. You now need to extend this class to implement the IConvertible interface. The IConvertible interface also contains a method named ToDouble. You must make sure that any modifications that you make do not affect already installed applications. What should you do? 1. Modify the existing ToDouble method to: double Area.ToDouble(IFormatProvider provider) { } 2. Add the following new method to the class: double IConvertible.ToDouble(IFormatProvider provider) { } <Correct> 3. Modify the existing ToDouble method to: double Area.ToDouble(IFormatProvider provider) { } and add the following new method to the class: double IConvertible.ToDouble(IFormatProvider provider) { } 4. Add the following new method to the class: public double ToDouble(IFormatProvider provider) { } Explanation : You should qualify the new interface method with the name of the interface as shown below: double IConvertible.ToDouble(IFormatProvider provider) { } You should not modify the existing method definition. Qualifying a method by the class name is not allowed. You can only use the interface name for method qualification. Adding the following method definition is incorrect because a method of the same name already exists in the class. You must correctly qualify the method name with the name of the interface: public double ToDouble(IFormatProvider provider) { } You should not modify the existing method and add the following new method to the class: double IConvertible.ToDouble(IFormatProvider provider)

{ } As noted above, you should not modify the existing method definition. Qualifying a method by the class name is not allowed. Objective: Developing applications that use system types and collections Sub Objective(s): Implement .NET Framework interfaces to cause components to comply with standard contracts. (Refer System namespace) Explicit Interface Implementation Sample MSDN Link: http://msdn2.microsoft.com/en-us/library/9c12as0k(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-092

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. You need to create a SelectQuery object in your application that enables you to retrieve the current IP address of the local computer. Which code segment should you use? 1. SelectQuery sq = new SelectQuery ("SELECT IPXAddress FROM Win32_NetworkAdapterConfiguration"); 2. SelectQuery sq = new SelectQuery ("SELECT MacAddress FROM Win32_NetworkAdapter"); 3. SelectQuery sq = new SelectQuery ("SELECT NetworkAddresses FROM Win32_NetworkAdapter"); 4. SelectQuery sq = new SelectQuery ("SELECT IPAddress FROM Win32_NetworkAdapterConfiguration"); <Correct> Explanation : The IP address is a property associated with the network adapter configuration. To get an IP address, you must query the Win32_NetworkAdapterConfiguration object. You should create the SelectObject by using the following code: SelectQuery sq = new SelectQuery ("SELECT IPAddress FROM Win32_NetworkAdapterConfiguration"); Selecting IPXAddress property of the Win32_NetworkAdapterConfiguration object is incorrect because the IPXAddress is used to identify a computer using the Internetworking Packet Exchange (IPX) protocol. The NetworkAddresses property of the Win32_NetworkAdapter object is an unimplemented property that returns null by default. The MACAddress property of the Win32_NetworkAdapter object returns the machine address for a network adapter. This is a unique 48-bit id assigned to the network card by its manufacturer. A Media Access Control (MAC) address is different from an IP address and cannot be changed. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Embed management information and events into a .NET Framework application. (Refer System.Management namespace) References : SelectQuery Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.management.selectquery(vs.80).aspx Win32_NetworkAdapterConfiguration Class MSDN Link: http://msdn2.microsoft.com/en-us/library/aa394217.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-054

____________________________________________________________________________________________________________________ You are developing a Windows service application by using the .NET Framework. You need the application to perform several short tasks that require background processing. You do not want to actively manage threads in your application. You must ensure that security checks are performed during the execution of a task. Which method should you use to start a task in your application? 1. ThreadPool.QueueUserWorkItem <Correct>

2. ThreadPool.UnsafeQueueUserWorkItem 3. Thread.Start 4. Thread.Resume Explanation : In this scenario, you have several short tasks that require background processing. Using the ThreadPool class is ideal in such a situation. Worker threads in a thread pool are managed by the system so there is less overhead involved in managing threads. The ThreadPool.QueueUserWorkItem method queues a task for execution. You should not use the ThreadPool.UnsafeQueueUserWorkItem method because this method skips security checks during execution of the queued task. You should not use a method of the Thread class (Thread.Start and Thread.Resume) in this case because the Thread class is useful for creating foreground threads that are actively managed. For example, the threads created by using Thread.Start require active thread management as compared to the system managed threads in a thread pool. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Develop multithreaded .NET Framework applications. (Refer System.Threading namespace) The Managed Thread Pool MSDN Link: http://msdn2.microsoft.com/en-us/library/0ka9477y(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-006

____________________________________________________________________________________________________________________ You are reviewing code that was written by another developer for a multithreaded .NET Framework application. You notice that the developer placed System.Runtime.CompilerServices.MethodImplAttribute on a method and, in the constructor of MethodImplAttribute, specified the Synchronized value. When should you use this means of synchronization? 1. When a critical section spans an entire method <Correct>

2. Whenever a critical section resides in a private object 3. When you need to lock on an external object 4. Whenever you need to protect a reference type Explanation : You should use this means of synchronization when you are protecting a critical section that spans an entire method. By using this means of synchronization, you will ensure that the current thread holds the lock until the method returns. As a general rule, you should not lock on external objects. When you need to synchronize the use of objects by multiple threads, you should lock only on private or internal objects. You should not use this means of synchronization whenever a critical section resides in a private object, only in those cases in which a critical section spans an entire method. You can use the Monitor class to protect an object for which a critical section does not span an entire method. You should not use this means of synchronization whenever you need to protect a reference type. You can use the Monitor class to protect an object, i.e. a reference type, for which a critical section does not span an entire method. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Develop multithreaded .NET Framework applications. (Refer System.Threading namespace) Monitor Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.threading.monitor(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-095

____________________________________________________________________________________________________________________ You recently developed a shipping system by using the .NET Framework. When you deployed the application, users complained that some of the features in the application were not working correctly. You are now trying to debug the application. You write the following code to get information about all the modules loaded by the application (line numbers are for reference only): 01 Process p = Process.Start(new ProcessStartInfo("PaintShipping.exe")); 02 ProcessModuleCollection pmc = p.Modules; 03 for (int i = 0; i < pmc.Count; i++) 04 { 05 Console.WriteLine(pmc(i).FileName) 06 } When you run the above code, you find that all the modules are not displayed. What should you do to correct the problem? 1. Add the following code before line 03: p.WaitForInputIdle(); <Correct> 2. Add the following code before line 02: p.Refresh(); 3. Change line 02 to read: ProcessModuleCollection pmc = p.GetProcesses(); 4. Add the following code before line 03: p.Refresh(); Explanation : You should always retrieve the modules used by an application when it is completely loaded. You can ensure that an application is loaded and is ready to start by calling the Process object's WaitForInputIdle method. The Refresh method will cause the process object's cached values to refresh but will not help if the application is not fully loaded. Also, calling Refresh on the Process object will not affect the values already stored in the ProcessModuleCollection object. The GetProcesses method is a shared method that returns the processes running on the computer as a single-dimensional array. It does not return a collection of the modules running in the process. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Manage system processes and monitor the performance of a .NET Framework application by using the diagnostics functionality of the .NET Framework 2.0. (Refer System.Diagnostics namespace) Process Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.process(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-017

____________________________________________________________________________________________________________________ You are creating a class that will be used by both managed code and COM applications. You need to ensure that the COM applications can access information about the cause of the error using an HRESULT. You need to write code to define an exception class that will handle a user passing an invalid payment amount to the class. What code should you use? 1. public class InvalidPayException : Exception { public InvalidPayException () { this.HResult = "E_INVALIDPAY"; } } 2. public class InvalidPayException : Exception { public InvalidPayException () { this.InnerException = "E_INVALIDPAY"; } } 3. public enum CustomHResults { E_INVALIDPAY = 8000123; } public class InvalidPayException : Exception { public InvalidPayException () { this.InnerException = (int)CustomHResults.E_INVALIDPAY; } } 4. public enum CustomHResults { E_INVALIDPAY = 8000123; } public class InvalidPayException : Exception { public InvalidPayException () { this.HResult = (int)CustomHResults.E_INVALIDPAY; } } <Correct> Explanation : You should use the following code: public enum CustomHResults { E_INVALIDPAY = 8000123; } public class InvalidPayException : Exception { public InvalidPayException () { this.HResult = (int)CustomHResults.E_INVALIDPAY; } }

COM applications use an HRESULT instead of structured exception handling. To allow them to access the HRESULT, you must set the HResult property of the custom exception object. An HRESULT is a numeric value, so you should define an enumeration containing the HRESULTs for the custom exceptions. You should not use the following code: public enum CustomHResults { E_INVALIDPAY = 8000123; } public class InvalidPayException : Exception { public InvalidPayException () { this.InnerException = (int)CustomHResults.E_INVALIDPAY; } } You should set the HResult property, not the InnerException property. You should not set the HResult property to a value of type String. An HResult is an Integer. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Expose COM components to the .NET Framework and .NET Framework components to COM. (Refer System.Runtime.InteropServices namespace) How to: Map HRESULTs and Exceptions MSDN Link: http://msdn2.microsoft.com/en-us/library/9ztbc5s1(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-012

____________________________________________________________________________________________________________________ You are writing an application that will use a custom database to authenticate users. The application needs to execute a block of code only if a user is a member of the Managers role. The application includes a GetUserName function that prompts the user for a name and a GetUserRoles function that queries the data and returns an array of Strings storing the roles to which the user belongs. You need to write code to obtain the user's identity and determine whether the user should be able to execute the code. What code should you use? 1. Thread.CurrentPrincipal.Identity.Name = GetUserName(); WindowsPrincipal prin = new WindowsPrincipal (Thread.CurrentPrincipal.Identity.Name, GetUserRoles(strUser)); Thread.CurrentPrincipal.Roles = prin; PrincipalPermission pp = New PrincipalPermission( Thread.CurrentPrincipal.Identity.Name, "Managers"); try { pp.Union(); //Execute Code } catch { //handle exception } 2. Thread.CurrentPrincipal.Identity.Name = GetUserName(); GenericPrincipal prin = new GenericPrincipal(Thread.CurrentPrincipal.Identity.Name, GetUserRoles(strUser)); Thread.CurrentPrincipal.Roles = prin; PrincipalPermission pp = New PrincipalPermission( Thread.CurrentPrincipal.Identity.Name, "Managers"); try { pp.Union(); //Execute Code } catch { //handle exception } 3. IIdentity ident = new IIdentity(GetUserName()); IPrincipal prin = new IPrincipal(ident, GetUserRoles(strUser)); Thread.CurrentPrincipal = prin; if(Thread.CurrentPrincipal.IsInRole("Managers")) { //Execute code } 4. GenericIdentity ident = new GenericIdentity(GetUserName()); GenericPrincipal prin = new GenericPrincipal(ident, GetUserRoles(strUser)); Thread.CurrentPrincipal = prin; if(Thread.CurrentPrincipal.IsInRole("Managers")) { //execute code } <Correct> Explanation : You should use the code: GenericIdentity ident = new GenericIdentity(GetUserName()); GenericPrincipal prin = new GenericPrincipal(ident, GetUserRoles(strUser));

Thread.CurrentPrincipal = prin; if(Thread.CurrentPrincipal.IsInRole("Managers")) { //execute code } The GenericIdentity and GenericPrincipal classes allow you to check a user's credentials against a custom database instead of using Windows authentication and roles. You should not use the code: Thread.CurrentPrincipal.Identity.Name = GetUserName(); GenericPrincipal prin = new GenericPrincipal(Thread.CurrentPrincipal.Identity.Name, GetUserRoles(strUser)); Thread.CurrentPrincipal.Roles = prin; PrincipalPermission pp = New PrincipalPermission( Thread.CurrentPrincipal.Identity.Name, "Managers"); try { pp.Union(); //Execute Code } catch { //handle exception } The Name property of the Identity class is a read-only property, which can only be set by an Identity object. You could modify this code to work by calling GetUserName within the GenericPrincipal constructor instead of accessing the CurrentPrincipal object. You should not use the code: Thread.CurrentPrincipal.Identity.Name = GetUserName(); WindowsPrincipal prin = new WindowsPrincipal (Thread.CurrentPrincipal.Identity.Name, GetUserRoles(strUser)); Thread.CurrentPrincipal.Roles = prin; PrincipalPermission pp = New PrincipalPermission( Thread.CurrentPrincipal.Identity.Name, "Managers"); try { pp.Union(); //Execute Code } catch { //handle exception } This code has the same problem as the previous code, plus another. The Union method of the PrincipalPermission object. The Union method is used when comparing the role membership of two principals. You should not use the code: IIdentity ident = new IIdentity(GetUserName()); IPrincipal prin = new IPrincipal(ident, GetUserRoles(strUser)); Thread.CurrentPrincipal = prin; if(Thread.CurrentPrincipal.IsInRole("Managers")) { //Execute code } You cannot instantiate IIdentity or IPrincipal. These are interfaces, not classes. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Access and modify identity information by using the System.Security.Principal classes. (Refer System.Security.Principal namespace) References : GenericIdentity Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.principal.genericidentity(vs.80).aspx

GenericPrincipal Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.principal.genericprincipal(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-089

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. You must make sure that application errors, such as a failure to send an e-mail message, are properly logged to the Windows event log. You only need to write non-localized string messages to the event log. You have already written the code to configure the event source. What code should you use to write an entry in the error log? 1. myEventLog.WriteEntry(String.Join(", ", failedEvent), EventLogEntryType.FailureAudit); 2. EventInstance failedEvent = new EventInstance(1001, 0, EventLogEntryType.FailureAudit); string[] messageStrings = { "Process1", "Value1" }; myEventLog.WriteEvent(failedEvent, messageStrings); 3. myEventLog.WriteEntry(String.Join(", ", failedEvent), EventLogEntryType.Error); <Correct> 4. EventInstance failedEvent = new EventInstance(1001, 0, EventLogEntryType.Error); string[] messageStrings = { "Process1", "Value1" }; myEventLog.WriteEvent(failedEvent, messageStrings); Explanation : You should use the WriteEntry method of the EventLog class to write the event because the WriteEvent method is used to write the localized messages to the event log. Also, to make sure that the messages are logged in the event log as error messages, you should use the EventLogEntryType.Error value as a parameter to the WriteEntry method. The EventLogEntryType.FailureAudit value indicates a failed audit event. Therefore, you should write the following code as part of your application: myEventLog.WriteEntry(String.Join(", ", failedEvent), EventLogEntryType.Error); Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Manage an event log by using the System.Diagnostics namespace. EventLog Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.eventlog(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-026

____________________________________________________________________________________________________________________ You are developing a text-processing application by using .NET Framework class libraries. You need to write code to replace dates that are formatted mm/dd/yy with dates that are formatted dd-mm-yy. The dates that need to be replaced are available in a variable named input. Which code segment should you use? 1. output = Regex.Replace(input, "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b", "${day}-${month}-${year}"); <Correct> 2. output = Regex.Replace(input, "\\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\\b", "${day}-${month}-${year}"); 3. output = Regex.Replace(input, "${day}-${month}-${year}", "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b"); 4. output = Regex.Replace(input, "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b", "^{day}-^{month}-^{year}"); Explanation : You should use the following statement: output = Regex.Replace(input, "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b", "${day}-${month}-${year}"); The first parameter specifies the string to modify. The second parameter specifies the regular expression pattern to match. The third and final parameter is the replacement string. The following statement is incorrect because the regular expression pattern is not properly escaped. The characters \b and \d should be properly escaped as \\b and \\d respectively. output = Regex.Replace(input, "\b(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})\b", "${day}-${month}-${year}"); The following statement is incorrect because the positions of the regular expression match pattern and the replacement strings are interchanged: output = Regex.Replace(input, "${day}-${month}-${year}", "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b"); The following expression is incorrect because the replacement string should be "${day}-${month}-${year}" instead of "^{day}-^{month}-^{year}". For example, ${day} substitutes the last substring matched by a (?<day>) group. output = Regex.Replace(input, "\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b", "^{day}-^{month}-^{year}"); Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application

Sub Objective(s): Enhance the text handling capabilities of a .NET Framework application (refer System.Text namespace), and search, modify, and control text within a .NET Framework application by using regular expressions. (Refer System.RegularExpressions namespace) Regex Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.text.regularexpressions.regex(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-087

____________________________________________________________________________________________________________________ You are writing an application that will allow users to modify some settings that are stored in a configuration file. You need to validate each setting and cancel the change if the new value is invalid using the following code: if (e.SettingName == "WindowWidth" & e.NewValue < 100) { e.Cancel = true; } You need to write code that will allow your application to be notified when a change to a setting occurs and cancel the operation if the new value is invalid. In which event should you place the validation code? 1. SettingsLoaded 2. SettingChanging 3. SettingsSaving 4. PropertyChanged Explanation : You should add the code to the SettingChanging event of the MySettings class. The SettingChanging event occurs before a setting's value is modified. It passes an argument of type SettingChangingEventArgs which allows you to access the setting's name and its new value. It also has a Cancel property that allows you to cancel the change to the setting. You should not add the code to the PropertyChanged event. The PropertyChanged event occurs after the change has already been made. Therefore, you cannot cancel the change. You should not add the code to the SettingsLoaded event. The SettingsLoaded event occurs after the application settings are read. You should not add the code to the SettingsSaving event. The SettingsSaving event occurs before saving the settings to the file. While you can cancel the entire save operation, you cannot obtain information about or cancel individual property settings. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Embed configuration management functionality into a .NET Framework application (Refer System.Configuration namespace) How to: Access Settings Events MSDN Link: http://msdn2.microsoft.com/en-us/library/fzc7d4xb(VS.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-035

____________________________________________________________________________________________________________________ You are developing an application that allows the users to send e-mails. The users should be able to send e-mail containing one or more attachments. You decide to use the .NET Framework Attachment class to create the e-mail attachments within your application. You must specify the content in an attachment by using any of the Attachment class constructors. Which object types can pass to a constructor of the Attachment class? (Each correct answer presents a complete solution. Choose two.) 1. XmlDocument object 2. Image object 3. String object<Correct> 4. SqlDataReader object 5. Stream object <Correct>

Explanation : The Attachment constructors allow you to create attachments from a String or a Stream object. You can optionally pass the type of content to the constructor as well. After you instantiate an Attachment object, you will need to add it to the Attachments collection of the MailMessage object. The Image object is not a correct answer because the Attachment class cannot directly use an Image object. You can instead specify the name of an image, or create a Stream object for the image contents. The XmlDocument object is not a correct answer because the Attachment class cannot directly use an XmlDocument object. You can instead specify the name of an XML file, or create a Stream object for the XML contents. The SqlDataReader object is not a correct answer because the Attachment class cannot directly use a SqlDataReader object. You can save the results in a file and attach the file, or you can serialize the object into a Stream object and pass that object to the Attachment constructor. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery from a .NET Framework application. (Refer System.Net.Mail namespace) Attachment Class MSDN Link: http://msdn2.microsoft.com/en-us/library/e02kz1ak(en-US,VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-052

____________________________________________________________________________________________________________________ You are developing a Windows service application by using the .NET Framework. The application will execute on a multiprocessor system. You are writing code for a class that contains a static integer variable named counter. The value of counter will be incremented or decremented from other classes possibly running in separate threads. You must provide atomic and non-blocking updates for counter. Your solution must provide the best performance. What should you do? 1. Use the Interlocked class. 2. Use the lock keyword. 3. Use the SynchronizationContext class. 4. Use the Overlapped class. Explanation : You should use the Interlocked class in this scenario. The Interlocked class is ideal for situations in which you need to provide atomic and non-blocking updates for a data item. The Interlocked class can be used to increment and decrement the value of a variable by using the Increment and Decrement methods. Using the lock keyword is not correct because it does not provide an atomic operation and it offers performance inferior to the Interlocked class. Using the Overlapped class is not correct because the Overlapped class is used for transferring information to Win32 API functions. Using the SynchronizationContext class is not correct because it does not provide support for atomic operations like the Interlocked class. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Develop multithreaded .NET Framework applications. (Refer System.Threading namespace) Interlocked Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.threading.interlocked(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-131

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code to create a WindowsPrincipal object in your application: WindowsPrincipal prin = new WindowsPrincipal(WindowsIdentity.GetCurrent()); You want to control the access to the application. You need to find whether a user has complete and unrestricted access to the computer. Your application will be localized for use in several countries. Any code that you use must minimize the localization efforts. Which code segment should you use? 1. if (prin.IsInRole(WindowsBuiltInRole.Administrator)) { // Additional Code } <Correct> 2. if (string.CompareOrdinal(prin.Identity.Name, "BUILTIN\\Administrators") == 0) { // Additional Code } 3. if (prin.IsInRole("BUILTIN\\Administrators")) { // Additional Code } 4. if (string.Compare(prin.Identity.Name, "BUILTIN\\Administrators", true) == 0) { // Additional code } Explanation : You should use the following code segment: if (prin.IsInRole(WindowsBuiltInRole.Administrator)) { // Additional Code } This code segment checks the role membership against the values of the WindowsBuiltInRole enumeration. These values are culture independent, and this code does not need to be modified during localization. The following code would work, but because of the use of a hard-coded string, it is difficult to localize: if (prin.IsInRole("BUILTIN\\Administrators")) { // Additional Code } The following code segment is incorrect because the expression prin.Identity.Name gets the name of a Windows user and the name is compared against a role. A hard-coded string again makes the code difficult to localize. if (string.Compare(prin.Identity.Name, "BUILTIN\\Administrators", true) == 0) {

// Additional code } The following code segment is incorrect because the expression prin.Identity.Name gets the name of a Windows user and the name is compared against a role. if (string.CompareOrdinal(prin.Identity.Name, "BUILTIN\\Administrators") == 0) { // Additional Code } Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Access and modify identity information by using the System.Security.Principal classes. (Refer System.Security.Principal namespace) WindowsPrincipal Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.principal.windowsprincipal(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-053

____________________________________________________________________________________________________________________ You are developing a class library application by using the .NET Framework. You are writing a class that will be used to tally online votes. The class might be accessed by multiple threads. You declare the following members: private int m_Option1Total; private int m_Option2Total; public int Option1Total { get { return m_Option1Total; } } public readonly int Option2Total { get { return m_Option2Total; } } You need to create an IncrementOption1 method that increments the value in Option1Total by the value passed as byAmount. If the total has been changed by another thread, the method should try again until it successfully increments the value. Your solution must be threadsafe. Which code segment should you use? 1. public void IncrementOption1(int byAmount) { int previousValue; int newValue; do { previousValue = m_Option1Total; newValue = previousValue + byAmount; } while previousValue != Interlocked.CompareExchange(ref m_Option1Total, newValue, previousValue); } <Correct> 2. public void IncrementOption1(int byAmount) int counter; for (counter=1; counter<=byAmount; counter++) { Interlocked.Increment(m_Option1Total); } } 3. public void IncrementOption1(int byAmount) { Monitor.TryEnter(m_Option1); try { m_Option1 += byAmount; } finally { Monitor.Exit(m_Option1); } } 4. public void IncrementOption1(int byAmount) { int previousValue; int newValue; do { previousValue = m_Option1Total; newValue = previousValue + byAmount;

} while previousValue != Interlocked. Exchange(ref m_Option1Total, newValue); } Explanation : You should use the following code segment: public void IncrementOption1(int byAmount) { int previousValue; int newValue; do { previousValue = m_Option1Total; newValue = previousValue + byAmount; } while previousValue != Interlocked.CompareExchange(ref m_Option1Total, newValue, previousValue); } The CompareExchange method performs two operations, comparison and exchange, as an atomic operation. First it compares the value of the first operand (the value in m_Option1Total) with the third operand (the value in m_Option1Total at the beginning of the loop). If they match, it means that no other thread has modified m_Option1Total, so CompareExchange replaces the value currently in m_Option1Total with newValue. You should not use the following code because the Exchange method always replaces the first operand with the second operand without performing any comparison: public void IncrementOption1(int byAmount) { int previousValue; int newValue; do { previousValue = m_Option1Total; newValue = previousValue + byAmount; } while previousValue != Interlocked. Exchange(ref m_Option1Total, newValue); } You should not use the following code segment because this code segment uses an atomic each time through the loop. Therefore, another thread could call IncrementOption1 between iterations of the loop and make the total wrong. public void IncrementOption1(int byAmount) int counter; for (counter=1; counter<=byAmount; counter++) { Interlocked.Increment(m_Option1Total); } } You should not use the following code segment because the Monitor should be used with reference types, not value types. This code will not be threadsafe. public void IncrementOption1(int byAmount) { Monitor.TryEnter(m_Option1); try { m_Option1 += byAmount; } finally { Monitor.Exit(m_Option1); } } Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Develop multithreaded .NET Framework applications. (Refer System.Threading namespace) References : Interlocked Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.threading.interlocked(vs.80).aspx

Monitors MSDN Link: http://msdn2.microsoft.com/en-us/library/hf5de04k(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-090

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. When a user's attempt to log on to the application fails, you must write an entry to the Windows event log. When looking at the Windows event log viewer, the source of the events must be listed as MyApp. You need to create an event source that can be used to write entries to the event log. Which code segment should you use? 1. EventLog.LogNameFromSourceName("MyApp", "Application"); 2. if(!EventLog.SourceExists("MyApp")) { EventLog.CreateEventSource("MyApp", "Application"); } <Correct> 3. if(!EventLog.SourceExists("MyApp")) { EventLog.CreateEventSource("MyApp", "Security"); } 4. EventLog.LogNameFromSourceName("MyApp", "Security"); Explanation : You should use the following code segment to create an event source associated with the Application event log: if(!EventLog.SourceExists("MyApp")) { EventLog.CreateEventSource("MyApp", "Application"); } You should first check if an event source by the same name already exists and create one only if it does not already exist. Additionally, you should use the Application event log for logging events related to your application. Creating an event source for the Security event log is incorrect because the Security log is read-only and you cannot write entries to it. You should use the CreateEventSource method instead of LogNameFromSourceName method because the LogNameFromSourceName method returns the name of an event log for the given event source name and a computer name. This method does not help you with creating an event source. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Manage an event log by using the System.Diagnostics namespace. EventLog Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.eventlog(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-073

____________________________________________________________________________________________________________________ You are developing a text-processing application by using the .NET Framework. In your code, you have access to an array of bytes named myArray that contains your data. You write code to write the contents of the array to a disk file. After the write operation, you need to display the contents of the stream on the console to make sure that the write operation completed successfully. The code segment to write to the stream is shown below (line numbers are for reference only): 01: using (FileStream fs = new FileStream("MyFile.txt", FileMode.Create)) 02: { 03: for (int i = 0; i < myArray.Length; i++) 04: { 05: fs.WriteByte(myArray[i]); 06: } 07: // Add code here 08: } You need to insert code at line 07 to correctly print the contents of the stream. Which code segment should you use? 1. fs.Postion=1; for (int i = 0; i < fs.Length; i++) { Console.WriteLine(fs.WriteByte()); } 2. fs.Seek(0, SeekOrigin.Begin); for (int i = 0; i < fs.Length; i++) { Console.WriteLine(fs.WriteByte()); } 3. fs.Seek(0, SeekOrigin.Begin); for (int i = 0; i < fs.Length; i++) { Console.WriteLine(fs.ReadByte()); } <Correct> 4. fs.Position = 1; for (int i = 0; i < fs.Length; i++) { Console.WriteLine(fs.ReadByte()); } Explanation : After the write operation is completed, you need to reposition the stream so that you can read the contents again from the beginning. This can be successfully accomplished by using the following statement: fs.Seek(0, SeekOrigin.Begin); The first parameter specifies the offset, and the second parameter specifies the reference point for the seek operation. The Value SeekOrigin.Begin indicates that the reader should be positioned at the beginning of the stream. Now you are ready to write the contents of the stream. To do so, you need a For loop that reads each byte and passes it to the WriteLine procedure. This is accomplished using the code: for (int i = 0; i < fs.Length; i++) {

Console.WriteLine(fs.ReadByte()); } The following code will not meet the requirements: fs.Position = 1; for (int i = 0; i < fs.Length; i++) { Console.WriteLine(fs.ReadByte()); } The position of the first element is position 0, not position 1. You cannot use the WriteByte method to write data to the screen. The WriteByte method writes a byte of data to the file stream. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Manage byte streams by using Stream classes. (Refer System.IO namespace) FileStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.filestream(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-125

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You are using an asymmetric algorithm to encrypt the data. You need to maximize the time it would take to successfully perform a brute force attack on the encryption key. You must find an appropriate key size for your encryption key. Which code segment should you use? 1. int GetKeySize(AsymmetricAlgorithm asym) { KeySizes[] sizes = asym.LegalKeySizes; return sizes.GetLength; } 2. int GetKeySize(AsymmetricAlgorithm asym) { KeySizes[] sizes = asym.LegalKeySizes; return sizes.LongLength; } 3. int GetKeySize(AsymmetricAlgorithm asym) { KeySizes[] sizes = asym.LegalKeySizes; return asym.KeySize; } 4. int GetKeySize(AsymmetricAlgorithm asym) { KeySizes[] sizes = asym.LegalKeySizes; return sizes[sizes.Length-1].MaxSize; } <Correct> Explanation : If you need to maximize the time needed to successfully perform a brute force attack on the encryption key, you must use the largest possible key size. The larger the key size, the more time it will take for someone to break the encryption. You can use the following code segment to find the largest key size supported by the algorithm: int GetKeySize(AsymmetricAlgorithm asym) { KeySizes[] sizes = asym.LegalKeySizes; return sizes[sizes.Length-1].MaxSize; } The KeySizes property of the AsymmetricAlgorithm base class returns an array of key sizes supported by the algorithm. Each key size includes properties that define the minimum size, the maximum size, and the interval between each discrete valid keysize in that range, which is returned by the SkipSize property. For example, the RSACryptoServiceProvider algorithm supports a single range of keys between 384 bytes and 16,384 bytes. The SkipSize is 8 bytes. This means that all keys must be divisible by 8. You should not use the GetLength method because it just gives you the number of available valid key size ranges. You should not use the LongLength property because it returns the number of elements in the KeySizes array.

You should not use the KeySize property of the AsymmetricAlgorithm object because it returns the default key size, which is not always the strongest key size. For example, the RSACryptServiceProvider has a default key size of 1024 bytes. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Encrypt, decrypt, and hash data by using the System.Security.Cryptography classes. (Refer System.Security.Cryptography namespace) AsymmetricAlgorithm Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.cryptography.asymmetricalgorithm(vs.80).a spx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-114

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You create an assembly that implements a custom security object. The assembly resides in the CusPerm.exe file. CusPerm.exe references the classes in the BasePerm.exe assembly. You need to write a script that adds the assembly to the full trust assembly list for the currently logged-on user. The user will never have write access to the machine policy file. Which commands should you include in the script? (Choose all that apply.) 1. caspol -enterprise -addfulltrust BasePerm.exe 2. caspol -enterprise -addfulltrust CusPerm.exe 3. caspol -addfulltrust CusPerm.exe <Correct>

4. caspol -addfulltrust BasePerm.exe <Correct> 5. caspol -machine -addfulltrust CusPerm.exe 6. caspol -machine -addfulltrust BasePerm.exe Explanation : You need to include the following commands in the script file: caspol -addfulltrust CusPerm.exe caspol -addfulltrust BasePerm.exe The Caspol.exe tool allows you to modify the code access security policy at the user level, machine level, and enterprise level. The -addfulltrust option adds an assembly that implements a custom security object to a list of fully trusted assemblies for the specified policy level. The policy level can be -enterprise, -machine, or -user. These levels affect the enterprise-level, machine-level, and user-level security policies. If no policy level is specified, the Caspol.exe checks if the user has write permission to the machine policy file. If so, it uses the machine-level security policy. Otherwise, it uses the user-level security policy. If the assembly references classes in some other assembly, the code access security policy must be applied to that assembly too. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement code access security to improve the security of a .NET Framework application. Refer System.Security namespace) Configuring Security Policy Using the Code Access Security Policy Tool (Caspol.exe) MSDN Link: http://msdn2.microsoft.com/en-us/library/a0ke3k86(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-023

____________________________________________________________________________________________________________________ You are developing a console application that uses .NET Framework text processing libraries. You write the following code to process text: StringBuilder sb = new StringBuilder(5); sb.Append("01234567890123456789"); sb.Length = 10; sb.Append("AB"); Console.WriteLine("Length = {0}", sb.Length); Console.WriteLine("Capacity = {0}", sb.Capacity); You must determine the value of sb.Length and sb.Capacity printed by this code segment. Which values should you select? 1. Length = 12 Capacity = 20 <Correct> 2. Length = 10 Capacity = 5 3. Length = 12 Capacity = 12 4. Length = 10 Capacity = 20 Explanation : The correct answer is: Length = 12 Capacity = 20 The StringBuilder object is first created with a capacity of 5. If needed, the Append method increases the length and capacity of the StringBuilder object. Therefore, the following statement increases the capacity and length of the StringBuilder object to 20: sb.Append("01234567890123456789"); When the following statement is executed, the length of the StringBuilder object is truncated to 10 characters, but the capacity stays at 20: sb.Length = 10; Finally, the following statement increases length of the StringBuilder object by 2 characters to 12: sb.Append("AB"); Capacity stays at 20 because there is still room to grow. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Enhance the text handling capabilities of a .NET Framework application (refer System.Text namespace), and search, modify, and control text within a .NET Framework application by using regular expressions. (Refer System.RegularExpressions namespace)

StringBuilder Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.text.stringbuilder(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-093

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. You need to asynchronously monitor the instantiation of Windows services. You write the following code in your application: WqlEventQuery q = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 5), "TargetInstance isa \"Win32_Service\""); ManagementEventWatcher watcher = new ManagementEventWatcher(); watcher.Query = q; You need to add additional code for the asynchronous monitoring to work. Which code segments should you use? (Each correct answer presents part of the solution. Choose two.) 1. private static void Service_Created (object sender, EventArgs e) { 'code to process event here } 2. watcher.EventArrived += new EventArrivedEventHandler(Service_Created); watcher.Start(); <Correct> 3. watcher.EventArrived += new EventArrivedEventHandler(Service_Created); ManagementBaseObject e = watcher.WaitForNextEvent(); 4. private static void Service_Created (object sender, EventArrivedEventArgs e) { 'code to process event here } <Correct> 5. ManagementBaseObject e = watcher.WaitForNextEvent(); watcher.Stop(); Explanation : You should use the Start method of the ManagementEventWatcher class to asynchronously monitor the creation of Windows services. When a new service is instantiated, the EventArrived event is raised. To receive notifications about creation of processes and take action, you must add an event handler to the EventArrived event. The EventArrived event accepts two parameters, the sender and a parameter of type EventArrivedEventArgs. When you use the WaitForNextEvent method of the ManagementEventWatcher class, you are in fact waiting for the events to occur. This leads to synchronous processing rather than asynchronous processing. You should not create an event procedure that accepts a second parameter of type EventArgs. The signature of the event must match the one that is generated by ManagementEventWatcher. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Embed management information and events into a .NET Framework application. (Refer System.Management namespace)

ManagementEventWatcher Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.management.managementeventwatcher(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-003

____________________________________________________________________________________________________________________ You are creating a class library that will be used by several applications. You need to create a custom exception that will be thrown if an application attempts to retrieve product information using an invalid product number. You need to create the ProductNotFoundException class. From which class should you derive ProductNotFoundException? 1. Exception <Correct>

2. SystemException 3. ArgumentException 4. ApplicationException Explanation : You should derive the class for the custom exception from the Exception class. As a general rule, custom exceptions should be derived from the Exception class. Custom exceptions should not inherit from the ApplicationException base class. You should not create the custom exception by deriving from the SystemException class. The SystemException class is the base class from which exceptions thrown by the .NET Framework derive. You should not create a class that inherits from ArgumentException. You should derive a class from ArgumentException if that exception will only be thrown if an invalid argument is passed. Objective: Developing applications that use system types and collections Sub Objective(s): Manage data in a .NET Framework application by using .NET Framework 2.0 system types (Refer System namespace) References : Exception Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.exception(vs.80).aspx Best Practices for Handling Exceptions MSDN Link: http://msdn2.microsoft.com/en-us/library/seyhszts(VS.80).aspx Creating and Throwing Exceptions (C# Programming Guide) MSDN Link: http://msdn2.microsoft.com/en-us/library/ms173163(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-147

____________________________________________________________________________________________________________________ You are writing an application that needs to run with a very limited set of security permissions, regardless of how security policy is configured on the network and on the individual computers. You need to create a policy level for your application and add the code group named cgSecure. What code should you use? 1. PolicyLevel pl; pl.Type = PolicyLevelType.AppDomain; 2. PolicyLevel pl; pl.CreateAppDomainLevel(); 3. PolicyLevel pl; pl.Type = PolicyLevelType.Enterprise; 4. PolicyLevel pl; pl = PolicyLevel.CreateAppDomainLevel(); Explanation : You should use the code: PolicyLevel pl; pl = PolicyLevel.CreateAppDomainLevel(); You need to create an AppDomain-level policy. An AppDomain-level policy can be more restrictive than the policies higher in the hierarchy, but not less restrictive. You create an AppDomain policy using the CreateAppDomainLevel shared method of the PolicyLevel class. You should not use the code: PolicyLevel pl; pl.CreateAppDomainLevel(); CreateAppDomainLevel is a shared method and cannot be called on an instance of the class. You should not use the code: PolicyLevel pl; pl.Type = PolicyLevelType.AppDomain; The Type property of the PolicyLevel object is read/only. You should not use the code: PolicyLevel pl; pl.Type = PolicyLevelType.Enterprise; The Enterprise policy level is at the top of the hierarchy and is configured at the domain level. You cannot configure it within your application. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control code privileges by using System.Security.Policy classes. (Refer System.Security.Policy namespace) PolicyLevel Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.policy.policylevel(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-132

____________________________________________________________________________________________________________________ You are developing a .NET Framework assembly. You write the following code: public sealed class UtilProc { public void DoWork() { // Additional Code } } This code may be called by a Web application or a Web service. You want to restrict the assemblies that can call the DoWork method. Only assemblies signed with the specified public key should be able to call the DoWork method. What should you do? 1. Apply the following attribute to the class: [GacIdentityPermission (SecurityAction.InheritanceDemand)] 2. Apply the following attribute to the DoWork method: [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey ="10293485920938420892304820840842842020229327925727592")] <Correct> 3. Apply the following attribute to the DoWork method: [GacIdentityPermission (SecurityAction.Demand)] 4. Apply the following attribute to the class: [StrongNameIdentityPermission (SecurityAction.Demand, PublicKey ="10293485920938420892304820840842842020229327925727592")] Explanation : You should apply the StrongNameIdentityPermission attribute to the DoWork method and pass SecurityAction.LinkDemand as a parameter to the attribute. The use of the StrongNamePermission attribute ensures that only the assemblies with a specified public key are able to call the DoWork method. The SecurityAction.LinkDemand value ensures that only the immediate caller is authorized. This means that dynamically generated Web applications or Web service assemblies, which cannot be strong named, can use an intermediate assembly with the specified strong name to invoke the DoWork method. It is incorrect to apply the GacIdentityPermission attribute because it ensures that calling code should originate from the global assembly cache (GAC). Having the calling code originate from the GAC is not a stated requirement in this scenario. It is incorrect to pass SecurityAction.InheritanceDemand as a parameter to the attribute. The SecurityAction.InheritanceDemand value is used to limit the scope of the attribute to only the inheriting classes. This class is sealed, so it cannot be used as a base class. It is incorrect to pass SecurityAction.Demand as a parameter to the attribute. The SecurityAction.Demand value is used to enforce that all code in the call stack is signed using the same public key. It is not possible to sign dynamically generated assemblies for Web applications or Web services with a strong name. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features

Sub Objective(s): Control permissions for resources by using the System.Security.Permission classes. (Refer System.Security.Permission namespace) References : SecurityAction Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.securityaction(vs.80).aspx StrongNameIdentityPermissionAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.strongnameidentitypermissiona ttribute(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-002

____________________________________________________________________________________________________________________ You have developed a class named Reward. You package the class in a .NET Framework assembly named BusObj.dll. After the assembly ships and is being used by client applications, you decide to move the Reward class from the BusObj.dll assembly to the RewardObj.dll assembly. When you ship the updated BusObj.dll and RewardObj.dll assemblies, you must ensure that the client applications will still work without being recompiled. What should you do? 1. Add TypeForwardedToAttribute to the BusObj assembly. <Correct>

2. Add TypeForwardedToAttribute to the RewardObj assembly. 3. Add TypeForwardedToAttribute to the machine.config file. 4. Add TypeForwardedToAttribute to the BusObj.dll's configuration file. Explanation : The TypeForwardedToAttribute allows you to move a type from one assembly into another assembly so that it is not necessary to recompile clients that consume the former assembly. You must add the TypeForwardedToAttribute attribute to the assembly that originally contained the class. The attribute should include the name of the type. You must also modify the original assembly to include a reference to the new assembly and recompile it. Objective: Developing applications that use system types and collections Sub Objective(s): Manage data in a .NET Framework application by using .NET Framework 2.0 system types (Refer System namespace) References : Type Forwarding in the Common Language Runtime MSDN Link: http://msdn2.microsoft.com/en-us/library/ms404275.aspx TypeForwardedToAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.compilerservices.typeforwardedtoattribute( vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-064

____________________________________________________________________________________________________________________ You are developing a .NET Remoting application by using the .NET Framework. The name of your class is MyType and the name of the assembly is MyAssembly. This object will be accessed by using Transmission Control Protocol (TCP) at port 1234. You want to expose MyType as a server-activated object for remote access. You must use a configuration file to register the remote object. Which configuration setting should you use? 1. <configuration> <system.runtime.remoting> <application> <service> <wellknown mode="Singleton" type="MyType, MyAssembly" objectUri="MyType.rem" /> </service> </application> </system.runtime.remoting> </configuration> <Correct> 2. <configuration> <system.runtime.remoting> <application> <service> <activated type="MyType, MyAssembly" /> </service> </application> </system.runtime.remoting> </configuration> 3. <configuration> <system.runtime.remoting> <application> <client url="tcp://localhost:1234/MyType.rem"> <activated type="MyType, MyAssembly"/> </client> </application> </system.runtime.remoting> </configuration> 4. <configuration> <system.runtime.remoting> <application> <client> <wellknown type="MyType, MyAssembly" url="tcp://localhost:1234/MyType.rem" /> </client> </application> </system.runtime.remoting> </configuration> Explanation : You must use the following configuration setting to set up an object for remote access: <configuration> <system.runtime.remoting> <application>

<service> <wellknown mode="Singleton" type="MyType, MyAssembly" objectUri="MyType.rem" /> </service> </application> </system.runtime.remoting> </configuration> The <wellknown> element specifies that the object is a server-activated object. The type attribute specifies the type and the assembly containing the type. Using the following configuration setting is incorrect because using the <activated> element registers the remote object as a client-activated object instead of a server-activated object: <configuration> <system.runtime.remoting> <application> <service> <activated type="MyType, MyAssembly" /> </service> </application> </system.runtime.remoting> </configuration> Using the <client> element in the configuration file is incorrect because the <client> element is used to configure a program that consumes the remote object. In this case, the requirement is to expose an object for remote access. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Create a custom Microsoft Windows Installer for .NET Framework components by using the System.Configuration.Install namespace, and configure .NET Framework applications by using configuration files, environment variables, and the .NET Framework Configuration tool (Mscorcfg.msc). Configuration of Remote Applications MSDN Link: http://msdn2.microsoft.com/en-us/library/b8tysty8.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-104

____________________________________________________________________________________________________________________ You are developing a class library by using the .NET Framework. You create the following classes: public class Book { public string Name; } public class Encyclopedia : Book { public int Volume; } You must be able to serialize the objects of the Encyclopedia class to a disk file. What should you do? 1. Add the [Serializable] attribute to the Book class. Add the [Serializable] attribute to the Encyclopedia class. <Correct> 2. Add the [Serializable] attribute to the Encyclopedia class only. 3. Add the [Serializable] attribute to the Encyclopedia class. Add the [NonSerialized] attribute to the Name field. 4. Add the [Serializable] attribute to the Book class only. Explanation : You should add the Serializable attribute to both the Book and the Encyclopedia classes. The Serializable attribute is not inherited by the derived classes, so if you only mark the Encyclopedia class with the Serlializable attribute, the runtime will throw an exception when trying to serialize the Name field. If you only mark the Book class with the Serlializable attribute, you will only be able to serialize the objects of the Book class. To successfully serialize the Encyclopedia class, you must mark the Encyclopedia class and all the base classes with the Serlializable attribute. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Serialize or deserialize an object or an object graph by using runtime serialization techniques. (Refer System.Runtime.Serialization namespace) SerializableAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.serializableattribute(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-008

____________________________________________________________________________________________________________________ You are developing a .NET Framework application that uses the Stack class. You need to write code that enumerates through the stack. Your code must guarantee thread safety during the enumeration. Which code segment should you use? 1. Stack myStack = new Stack(); Stack syncStack = (Stack) myStack.SyncRoot; foreach (Object item in syncStack) { // additional code for processing. } 2. Stack myStack = new Stack(); lock (Stack.Synchronized(myStack)) { foreach (Object item in myStack) { // additional code for processing. } } 3. Stack myStack = new Stack(); lock (myStack.SyncRoot) { foreach (Object item in myStack) { // additional code for processing. } } <Correct> 4. Stack myStack = new Stack(); Stack syncStack = Stack.Synchronized(myStack); foreach (Object item in syncStack) { // additional code for processing. } Explanation : You should use code similar to the following: Stack myStack = new Stack(); lock (myStack.SyncRoot) { foreach (Object item in myStack) { // additional code for processing. } } Enumerating through a collection is not a thread-safe procedure because while one thread is enumerating, the other threads can modify the collection. To ensure thread safety during enumeration, you should lock the collection during the enumeration. Another option is to use exception handling to catch any exceptions that might occur due to records being pushed onto or popped off the stack during enumeration. Using the Synchronized method will cause the stack to be synchronized for some operations, but not for enumerating the elements in the stack. The following code does not show the correct way to use SyncRoot: Stack syncStack = (Stack) myStack.SyncRoot;

Objective: Developing applications that use system types and collections Sub Objective(s): Manage a group of associated data in a .NET Framework application by using collections (Refer System.Collections namespace) Stack.SyncRoot Property MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.stack.syncroot(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-135

____________________________________________________________________________________________________________________ You are writing a program that access a file on the hard disk. You need to cause a SecurityException to occur if any caller in the stack does not have permission to access the specified file path. What should you do? 1. Call Assert on the CodeAccessPermission class. 2. Call IsGranted on the SecurityManager class. 3. Call CheckExecutionRights on the SecurityManager class. 4. Call Demand on the CodeAccessPermission class. <Correct> Explanation : You should call the Demand method on the CodeAccesPermission class. The Demand method requires that all callers on the stack have the necessary permission to access the protected resource. If one of the callers has insufficient permission, a SecurityException will occur. You should not call the Assert method on the CodeAccessPermission class. The Assert method is used to exempt callers from security policy restrictions. Assert should be used with great care because it can result in a security vulnerability. You should not call CheckExecutionRights on the SecurityManager class. The CheckExecutionRights property is a Boolean property that determines whether code access permission should be checked. You should not call IsGranted on the SecurityManager class. The IsGranted method checks whether the immediate caller is granted permission, but does not check all callers on the stack. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement code access security to improve the security of a .NET Framework application. Refer System.Security namespace) CodeAccessPermission Class MSDN Link: <http://msdn2.microsoft.com/en-us/library/system.security.codeaccesspermission(VS.80).aspx>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-016

____________________________________________________________________________________________________________________ You are writing a server application that will authenticate clients using Secure Sockets Layer (SSL) certificates and encrypt the data. The application uses an SslStream object named secureStream. You need to write code to log the algorithm that was used to encrypt the data and its strength. What code should you use to retrieve the data? 1. HashAlgorithmType algorithm; int strength; algorithm = secureStream.HashAlgorithm; strength = secureStream.HashStrength; 2. SslProtocols algorithm; int strength; algorithm = secureStream.SslProtocol; strength = secureStream.Length; 3. ExchangeAlgorithmType algorithm; int strength; algorithm = secureStream.KeyExchangeAlgorithm; strength = secureStream.KeyExchangeAlgorithm; 4. CipherAlgorithmType algorithm; int strength; algorithm = secureStream.CipherAlgorithm; strength = secureStream.CipherStrength; <Correct> Explanation : You should use the code: CipherAlgorithmType algorithm; int strength; algorithm = secureStream.CipherAlgorithm; strength = secureStream.CipherStrength; The algorithm used for encryption is the CipherAlgorithm. The supported algorithms are defined in the enumeration CipherAlgorithmType. The cipher algorithm negotiated is returned by CipherAlgorithm. The cipher strength is returned by CipherStrength. A hash algorithm is used to create a message digest or hash. They are not used to encrypt data. A key exchange algorithm is used to create and share keys used for symmetric encryption. The SslProtocol property returns a value indicating whether the connection is a Secure Sockets Layer (SSL) 2.0, SSL 3.0, or Transport Layer Security (TLS) connection. These are not the algorithms used for encryption. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement a custom authentication scheme by using the System.Security.Authentication classes. (Refer System.Security.Authentication namespace) System.Security.Authentication Namespace MSDN

Link: http://msdn2.microsoft.com/en-us/library/system.security.authentication(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-079

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following classes as part of your code: public class Book { public string Name; } public class Library { [XmlArray("ID1")] [XmlArrayItem("ID2")] public Book[] Books; } You need to create an object of the Library type and serialize it to disk in a file named books.xml using the following code: Book[] books = new Book[3]; books[0] = new Book(); books[0].Name = "Book Name 1"; books[1] = new Book(); books[1].Name = "Book Name 2"; books[2] = new Book(); books[2].Name = "Book Name 3"; Library library = new Library(); library.Books = books; XmlSerializer mySerializer = new XmlSerializer(typeof(Library)); using (StreamWriter myWriter = new StreamWriter("books.xml")) { mySerializer.Serialize(myWriter, library); } What XML output will be generated by this program? 1. <Library> <Books> <ID2> <Name>Book Name 1</Name> </ID2> <ID2> <Name>Book Name 2</Name> </ID2> <ID2> <Name>Book Name 3</Name> </ID2> </Books> </Library> 2. <Library> <ID1> <ID2> <Name>Book Name 1</Name> </ID2> <ID2> <Name>Book Name 2</Name> </ID2> <ID2> <Name>Book Name 3</Name> </ID2> </ID1>

</Library> <Correct> 3. <Library> <Books> <ID1> <ID2>Book Name 1</ID2> </ID1> <ID1> <ID2>Book Name 2</ID2> </ID1> <ID1> <ID2>Book Name 3</ID2> </ID1> </Books> </Library> 4. <Library> <ID1> <Book> <ID2>Book Name 1</ID2> </Book> <Book> <ID2>Book Name 2</ID2> </Book> <Book> <ID2>Book Name 3</ID2> </Book> </ID1> </Library> Explanation : When you use attributes as shown below, you customize the XML that will be generated as part of the serialization process: public class Library { [XmlArray("ID1")] [XmlArrayItem("ID2")] public Book[] Books; } The XmlArray attribute changes the name of the array element to which it is applied. In this case, it will cause the element <Books> to be replaced with <ID1>. The XmlArrayItem attribute changes the name of the array item. In this case, it will change the <Book> element to <ID2>. As a result of this customization, the correct XML output will be as shown below: <Library> <ID1> <ID2> <Name>Book Name 1</Name> </ID2> <ID2> <Name>Book Name 2</Name> </ID2> <ID2> <Name>Book Name 3</Name> </ID2> </ID1> </Library> Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Control the serialization of an object into XML format by using the System.Xml.Serialization namespace. Controlling XML Serialization Using Attributes MSDN Link: http://msdn2.microsoft.com/en-us/library/2baksw0z(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-063

____________________________________________________________________________________________________________________ You are developing a shared assembly by using the .NET Framework. The shared assembly is called SharedObjects, and it resides in a file named SharedObjects.dll. When compiled, the assembly is physically located in the C:\SharedObjects\Debug directory. You do not want to repeatedly install the shared assembly in the global assembly cache while you develop and debug. When you test your application, you want the .NET Framework to load the assembly from its current physical location. What should you do? (Each correct answer presents part of the solution. Choose two.) 1. Put C:\SharedObjects\Debug in the PATHEXT environment variable. 2. Put C:\SharedObjects\Debug in the DEVPATH environment variable. <Correct> 3. Put c:\SharedObjects\Debug in the PATH environment variable. 4. Add the following code to the machine configuration file: <configuration> <runtime> <developmentMode developerInstallation="true"/> </runtime> </configuration> <Correct> 5. Add the following code in the application configuration file: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath=" c:\SharedObjects\Debug"/> </assemblyBinding> </runtime> </configuration> 6. Add the following code to the machine configuration file: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="SharedObjects" publicKeyToken="12ac3ab67e0a34b5" culture="en-us" /> <codeBase version="2.0.0.0" href="SharedObjects\Debug"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration> Explanation : You should put C:\SharedObjects\Debug in the DEVPATH environment variable and add the following code to the machine configuration file: <configuration> <runtime> <developmentMode developerInstallation="true"/> </runtime> </configuration>

When you use the <developmentMode> element and set the developerInstallation attribute to "true", the .NET Framework searches for shared assemblies in the DEVPATH environment variable. Putting C:\SharedObjects\Debug in the PATH or PATHEXT environment variables is not correct because these environment variables are used by Windows and not by the .NET Framework. Adding the <codeBase> element in the machine configuration file is not correct because this setting is used to specify the base path for locating a private assembly. Adding the <probing> element in the application configuration file is not correct because the <probing> element is only useful for specifying the search path for private assemblies. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Create a custom Microsoft Windows Installer for .NET Framework components by using the System.Configuration.Install namespace, and configure .NET Framework applications by using configuration files, environment variables, and the .NET Framework Configuration tool (Mscorcfg.msc). How to: Locate Assemblies by Using DEVPATH MSDN Link: http://msdn2.microsoft.com/en-us/library/cskzh7h6.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-005

____________________________________________________________________________________________________________________ You are creating an Employee class. You want to implement a Format method that will return the Employee's name in LastName, FirstName format. What class declaration should you use? 1. public class Employee : IFormatProvider { //implementation } 2. public class Employee : IFormattable, IFormatProvider { //implementation } 3. public class Employee : IFormattable { //implementation } 4. public class Employee : ICustomFormatter { //implementation } <Correct> Explanation : You should use the following class declaration: public class Employee : ICustomFormatter { //implementation } The ICustomFormatter defines a Format method, which returns a string representation of the object. To implement the Format method, you must declare the class as implementing the ICustomFormatter interface. You should not use the following class declaration: public class Employee : IFormattable { //implementation } The IFormattable interface defines a ToString method, not a Format method. You should not use the following class declaration: public class Employee : IFormatProvider { //implementation } The IFormatProvider interface defines a GetFormat method, which is used to provide a localized or custom format provider to the Format method. You should not use the following class declaration: public class Employee : IFormattable, IFormatProvider { //implementation } If you inherit from both the IFormattable and IFormatProvider interfaces, you will need to

implement the members of each. However, neither of these interfaces defines a Format method. Objective: Developing applications that use system types and collections Sub Objective(s): Implement .NET Framework interfaces to cause components to comply with standard contracts. (Refer System namespace) ICustomFormatter Interface MSDN Link: http://msdn2.microsoft.com/en-us/library/system.icustomformatter(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-009

____________________________________________________________________________________________________________________ You have created the following class: [Serializable()] public class Manager : Employee { private Employee[] emps; public readonly Employee[] Employees { get{return emps;} } } Instances of the Manager class will be serialized and deserialized to a file using the SoapFormatter. After the class has been deserialized, but before the object graph is returned, the class needs to call a procedure to verify that the employees in the emps array are current employees and remove non-current employees. You need to change the class to support this behavior. What should you do? (Each correct answer presents a complete solution. Choose two.) 1. Implement the IDeserializationCallback interface. <Correct>

2. Create a method and mark it with the OnDeserializingAttribute. 3. Implement the ISoapMessage interface. 4. Implement the IObjectReference interface. 5. Create a method and mark it with the OnDeserializedAttribute. <Correct>

Explanation : You should implement the IDeserializationCallback interface. The IDeserializationCallback interface has a single method: OnDeserialization is called when all objects in the object graph have been fully deserialized. Therefore, you can place the code in the OnDeserialization method. An alternative way to meet the requirement is to implement a method that is marked with the OnDeserializedAttribute. You cannot create a method and mark it with the OnDeserializingAttribute. The OnDeserializingAttribute occurs before deserialization is complete. You should not implement the ISoapMessage interface. The ISoapMessage interface is used to support Simple Object Access Protocol (SOAP) Remote Procedure Calls (RPCs). You should not implement the IObjectReference interface. You would use the IObjectReference interface if you could not resolve a reference to an object until deserialization is complete. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Serialize or deserialize an object or an object graph by using runtime serialization techniques. (Refer System.Runtime.Serialization namespace) References : ISoapMessage Interface MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.formatters.isoapmessage(vs.8 0).aspx IDeserializationCallback Interface

MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.ideserializationcallback(vs. 80).aspx OnDeserializedAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.ondeserializedattribute(vs.8 0).aspx OnDeserializingAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute(vs. 80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-097

____________________________________________________________________________________________________________________ You have developed a Windows application by using the .NET Framework. The application provides a user interface similar to Microsoft Excel and allows users to manage their expenses. You are now writing a wrapper around the expense management application. The wrapper application performs security checks. If the user has sufficient rights, the wrapper application launches the expense management application. If the user does not have sufficient rights, you want to forcefully shut down the expense management application. Which method of the Process class should you use to shut down the application process? 1. Close 2. Dispose 3. CloseMainWindow 4. Kill <Correct> Explanation : You should use the Kill method to forcefully shutdown a process. It forces an immediate termination of the process. You should not use the CloseMainWindow method of the Process object because it requests a termination rather than forcefully shutting down the process. You should not use the Close method because it is called to free resources associated with the application process. You should not call the Dispose method because it is generally used to implement cleaning of unmanaged resources. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Manage system processes and monitor the performance of a .NET Framework application by using the diagnostics functionality of the .NET Framework 2.0. (Refer System.Diagnostics namespace) References : Process Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.process(vs.80).aspx Process.Kill Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.process.kill(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-011

____________________________________________________________________________________________________________________ You are writing an application that will store user preferences. The preferences must roam with the user. Only the application you are writing should be able to access the settings. The settings are stored in a one-thousand element Byte array named settings. You need to write code to save the settings to a file named userpref.dat. What code should you use? 1. IsolatedStorageFile saveLoc = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain | IsolatedStorageScope.User | IsolatedStorageScope.Roaming, null); IsolatedStorageFileStream saveFile = new IsolatedStorageFileStream("userpref.dat", FileMode.Create, saveLoc); saveFile.Write(settings, 0, 1000); <Correct> 2. IsolatedStorageFile saveLoc = IsolatedStorageFile.GetStore(IsolatedStorageScope.Application | IsolatedStorageScope.User | IsolatedStorageScope.Roaming, null); FileStream saveFile = new FileStream(saveLoc.ToString + "\" + "userpref.dat", FileMode.Create); saveFile.Write(settings, 0, 1000); 3. IsolatedStorageFile saveLoc = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorage.Domain | IsolatedStorageScope.Roaming, null); FileStream saveFile = new FileStream("userpref.dat", FileMode.Create, saveLoc); StreamWriter sw = new StreamWriter(saveFile); sw.Flush(); 4. IsolatedStorageFile saveLoc = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User | IsolatedStorageScope.Roaming, null); IsolatedStorageFileStream saveFile = new IsolatedStorageFileStream("userpref.dat", FileMode.Create); Explanation : You should use the following code; IsolatedStorageFile saveLoc = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain | IsolatedStorageScope.User | IsolatedStorageScope.Roaming, null); IsolatedStorageFileStream saveFile = new IsolatedStorageFileStream("userpref.dat", FileMode.Create, saveLoc); saveFile.Write(settings, 0, 1000); The IsolatedStorageFile.GetStore method allows you to retrieve the per-application domain/per-user roaming store when you pass the following IsolatedStorageScope argument of: IsolatedStorageScope.Assembly Or IsolatedStorage.Domain Or IsolatedStorageScope.User Or IsolatedStorageScope.Roaming. You pass the filename, the FileMode, and the reference to the store when you instantiate the IsolatedStorageFileStream object. Now you are ready to write the data to the file. Since the amount of data is small, you can write it with a simple Write operation. You should not use the following code: IsolatedStorageFile saveLoc = IsolatedStorageFile.GetStore(IsolatedStorageScope.Application | IsolatedStorageScope.User | IsolatedStorageScope.Roaming, null); FileStream saveFile = new FileStream(saveLoc.ToString + "\" + "userpref.dat", FileMode.Create); saveFile.Write(settings, 0, 1000); You need to use an IsolatedFileStream object, not a FileStream object to write the data. You should not use the following code: IsolatedStorageFile saveLoc = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User | IsolatedStorageScope.Roaming, null); IsolatedStorageFileStream saveFile = new IsolatedStorageFileStream("userpref.dat",

FileMode.Create); The scope of the IsolatedStorageFile object is wrong. You need the location scoped to the application domain, not to a specific assembly. Also, you need to pass the reference to the IsolatedStorageFile to the IsolatedStorageFileStream constructor to provide linkage. You should not use the code: IsolatedStorageFile saveLoc = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorage.Domain | IsolatedStorageScope.Roaming, null); FileStream saveFile = new FileStream("userpref.dat", FileMode.Create, saveLoc); StreamWriter sw = new StreamWriter(saveFile); sw.Flush(); The scope is wrong because you did not include the User in the scope. Also, although you can write to isolated storage by passing an IsolatedFileStream object to a StreamWriter, you cannot do so by passing a standard FileStream object. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Compress or decompress stream information in a .NET Framework application (Refer System.IO.Compression namespace), and improve the security of application data by using isolated storage. (Refer System.IO.IsolatedStorage namespace) Performing Isolated Storage Tasks MSDN Link: http://msdn2.microsoft.com/en-us/library/8dzkff1s(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-009

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. You need to store 16 different flags that will have Boolean values. Your solution must minimize memory use and maximize performance. What should you use? 1. Hashtable 2. ArrayList 3. BitArray 4. BitVector32 <Correct> Explanation : The BitVector32 structure can be used to efficiently store either a collection of bit flags associated with Boolean values or small integers. A BitVector32 structure is always 32 bits. You would use a BitArray to store a collection of bits that must grow dynamically. A BitArray requires more overhead than a BitVector32. The Hashtable class is used to store key/value pairs. The scenario requires storing only a collection of values, not of keys and values. The ArrayList class has high memory requirements and performance overhead compared to BitVector32. Like a BitArray, the ArrayList can grow to meet program requirements. Objective: Developing applications that use system types and collections Sub Objective(s): Manage data in a .NET Framework application by using specialized collections (Refer System.Collections.Specialized namespace) BitVector32 Structure MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.specialized.bitvector32(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-036

____________________________________________________________________________________________________________________ You are developing a Windows Forms application by using the .NET Framework. This application must provide support for multiple languages and regional differences. You need to define a custom culture based on an existing culture and region. An administrative user will install this custom culture on the end user's computer prior to the application's deployment. Which class should you use to define the custom culture? 1. CultureInfo class 2. RegionInfo class 3. CultureAndRegionInfoBuilder class <Correct> 4. CustomAttributeBuilder class Explanation : You can use the CultureAndRegionInfoBuilder class to create and register a custom culture. The custom culture can be a modification of an existing culture and region or it can be created from scratch. Using CultureInfo class is incorrect because this class can only make use of cultures that are already installed. Once you define a new custom culture by using the CultureAndRegionInfoBuilder class and install it on a computer, it can be used by the CultureInfo class. Using RegionInfo class is incorrect because this class is only used to access the region data for a culture that is already installed. The CustomAttributeBuilder class is used to build custom attributes. Attributes are used to associate declarative information with classes. Attributes cannot be used to create custom cultures. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) CultureAndRegionInfoBuilder Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.globalization.cultureandregioninfobuilder(vs.80).a spx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-001

____________________________________________________________________________________________________________________ You are developing an application with the following code (line numbers are for reference purposes only): 01: int? childCount = -1; 02: childCount = null; You need to insert a statement after line 02 to print the value of the variable childCount. However, if the value of childCount is null, the program must print -1. Which line of code should you insert after line 02? 1. Console.WriteLine("childCount = {0}", childCount.HasValue ? childCount.Value : childCount.GetValueOrDefault()); 2. Console.WriteLine("childCount = {0}", childCount.Value); 3. Console.WriteLine("childCount = {0}", childCount ?? -1); <Correct>

4. Console.WriteLine("childCount = {0}", childCount.GetValueOrDefault()); Explanation : You should use the null coalescing operator ?? to assign a value that will be applied when a nullable type is assigned to a non-nullable type. The expression childCount ?? -1 will return the value of childCount if childCount is not null. If the value of childCount is null, then the default value of -1 will be returned. The GetValueOrDefault method retrieves the value of the current nullable object if it is not null. If the object is null, the method returns the object's default value. The expression childCount.GetValueOrDefault() in the scenario will return 0 because the default value for the integer data type is 0. The HasValue property returns a value indicating whether the current nullable object has a non-null value. Because childCount is assigned null in line 02, childCount.HasValue will evaluate to false and the expression childCount.HasValue? childCount.Value : childCount.GetValueOrDefault() will return the value of the childCount.GetValueOrDefault() expression, which is 0 in this case. The expression childCount.Value will return the current value of the nullable object childCount. Accessing the Value property throws an exception if the HasValue property is false. Objective: Developing applications that use system types and collections Sub Objective(s): Manage data in a .NET Framework application by using .NET Framework 2.0 system types (Refer System namespace) References : Nullable Types (C# Programming Guide) MSDN Link: http://msdn2.microsoft.com/en-us/library/1t3y8s4s.aspx Value Types that Might Not Have a Defined Value MSDN Link: http://msdn2.microsoft.com/en-us/library/ms235245(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-103

____________________________________________________________________________________________________________________ You have developed a class library by using the .NET Framework. In version 1.0 of the assembly, you write the following code: [Serializable] public class ClassLib { public string Item1; } This assembly is deployed and is used by the client application to serialize objects by using the BinaryFormatter or the SoapFormatter class. You decide to release version 2.0 of your class library with the following code: [Serializable] public class ClassLib { public string Item1; public string Item2; } When version 2.0 is deployed, you must be able to correctly deserialize the objects that were serialized by using version 1.0. What should you do? 1. Apply the NonSerialized attribute on Item2: [Serializable] public class ClassLib { public string Item1; [NonSerialized()] public string Item2; } 2. Apply the OptionalField attribute on Item2: [Serializable] public class ClassLib { public string Item1; [OptionalField()] public string Item2; } <Correct> 3. Add the following method to the class and then use this method to deserialize Item2: [OnDeserialized()] internal void OnDeserializedMethod(StreamingContext context) { } 4. Add the following method to the class and then use this method to deserialize Item2: [OnDeserializing()] internal void OnDeserializingMethod(StreamingContext context) { } Explanation : You should apply the OptionalField attribute on Item2:

[Serializable] public class ClassLib { public string Item1; [OptionalField()] public string Item2; } If a field marked with the OptionalField attribute is not found during the deserialization process, the field is skipped without throwing an error. You should not use the NonSerialized attribute in this case because a field marked with this attribute is not serialized. In this case, you need to make sure that you are able to deserialize without the Item2 field. Using the OnDeserializedMethod or the OnDeserializingMethod will not help in this case because these methods are only useful for customizing the deserialization process. If the OptionalField attribute is not applied to Item2, an error will be thrown if the field is not found during deserialization. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Serialize or deserialize an object or an object graph by using runtime serialization techniques. (Refer System.Runtime.Serialization namespace) References : Advanced Serialization: Format Your Way to Success with the .NET Framework Versions 1.1 and 2.0 MSDN Link: http://msdn.microsoft.com/msdnmag/issues/04/10/AdvancedSerialization OptionalFieldAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.optionalfieldattribute(vs.80 ).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-133

____________________________________________________________________________________________________________________ You are developing a .NET Framework assembly. You write the following code: public interface IShape { void Draw(); } public sealed class IrregularShape : IShape { public void Draw() { // Additional code } } You need to permit the Draw method to be able to use serialization services. You decide to use the SecurityPermission attribute. You must make sure that permissions are enforced only for the assemblies that are immediate callers to the assembly containing the code. You must also make sure that the security permissions are never bypassed when the Draw method is called from these immediate callers. What should you do? 1. Apply the following attribute only to the Draw method of the IShape interface: [SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] 2. Apply the following attribute only to the Draw method of the IrregularShape class: [SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] 3. Apply the following attribute only to the Draw method of the IrregularShape class: [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] 4. Apply the following attribute to the Draw method of the IrregularShape class and the Draw method of the IShape interface: [SecurityPermission(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] 5. Apply the following attribute only to the Draw method of the IShape interface: [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] 6. Apply the following attribute to the Draw method of the IrregularShape class and the Draw method of the IShape interface: [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] <Correct> Explanation : You should apply the following attribute to the Draw method of the IrregularShape class and the Draw method of the IShape interface: [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] When you apply the SecurityPermission attribute to the Draw method of the IrregularShape class,

the link demand security check only occurs when the Draw method is directly invoked on the instance of the IrregularShape class as shown below: IrregularShape is = new IrregularShape(); is.Draw(); It is possible for the caller to bypass link demand by using the following code: IShape is = new IrregularShape(); is.Draw(); Therefore, you must apply the SecurityPermission attribute to the Draw method of the IrregularShape class and the Draw method of the IShape interface. Using SecurityAction.InheritanceDemand as a scope for the permission is incorrect because this setting limits the scope to only calls from the inherited classes. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control permissions for resources by using the System.Security.Permission classes. (Refer System.Security.Permission namespace) References : SecurityPermissionAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.securitypermissionattribute(v s.80).aspx SecurityAction Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.securityaction(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-136

____________________________________________________________________________________________________________________ You are writing a method that will need several permissions to the file system. You need to be able to verify that the method and all members on the call stack have the necessary permissions using the following code. try { p.Demand(); } catch { MessageBox.Show("Access denied."); } You need to add code to declare p. What code should you use? 1. CodeAccessPermission p = new CodeAccessPermission(PermissionState.None); 2. FileSecurity p = new FileSecurity(); 3. FileSystemAccessRule p = new FileSystemAccessRule(); 4. PermissionSet p = new PermissionSet(PermissionState.None); Explanation : You should use the following code: PermissionSet p = new PermissionSet(PermissionState.None); The PermissionSet class allows you to add multiple permissions and then verify that the executing code has all of them using the Demand method. You should not use the following code: CodeAccessPermission p = new CodeAccessPermission(PermissionState.None); The CodeAccessPermission is an abstract base class and cannot be instantiated. It acts as a template for definining permissions. You should not use the following code: FileSecurity p = new FileSecurity(); The FileSecurity class is used to configure user and group-based file access by setting Access Control Lists (ACLs) on files. You should not use the following code: FileSystemAccessRule p = new FileSystemAccessRule(); The FileSystemAccessRule class is used to define an Access Control Entry (ACE) to be added to the FileSecurity class. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement code access security to improve the security of a .NET Framework application. Refer System.Security namespace) <Correct>

PermissionSet Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissionset.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-128

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. You need to call the GetComputerName method in the library named kernel32.dll from your application to display the computer name. You write the following code: [DllImport("kernel32.dll")] static extern bool GetComputerName([Out] StringBuilder lpBuffer, ref uint lpnSize); Based on your coding standards, you need to call the method as ComputerName. You also need to make sure that your code can be called on any Windows operating system. How should you modify the DllImport attribute to call the GetComputerName method? 1. [DllImport("kernel32.dll", EntryPoint="ComputerName", CharSet=CharSet.Auto)] static extern bool GetComputerName([Out] StringBuilder lpBuffer, ref uint lpnSize); 2. [DllImport("kernel32.dll", EntryPoint="ComputerName", CharSet=CharSet.Ansi)] static extern bool GetComputerName([Out] StringBuilder lpBuffer, ref uint lpnSize); 3. [DllImport("kernel32.dll", EntryPoint="GetComputerName", CharSet=CharSet.Auto)] static extern bool ComputerName([Out] StringBuilder lpBuffer, ref uint lpnSize); <Correct> 4. [DllImport("kernel32.dll", EntryPoint="GetComputerName", CharSet=CharSet.Unicode)] static extern bool ComputerName([Out] StringBuilder lpBuffer, ref uint lpnSize); Explanation : You should modify the DllImport attribute as shown below: [DllImport("kernel32.dll", EntryPoint="GetComputerName", CharSet=CharSet.Auto)] static extern bool ComputerName([Out] StringBuilder lpBuffer, ref uint lpnSize); You should set the EntryPoint property to "GetComputerName", which is the name of the method to be invoked in kernel32.dll. If you do not set this property, the .NET method name will be used for a DLL entry point. If you set the EntryPoint property to "ComputerName", the code will search for the ComputerName method in kernel32.dll. Instead, the .NET method should be declared as ComputerName. You should set the CharSet property to CharSet.Auto so that the strings can be marshaled automatically based on the operating system. This will also make sure that based on the operating system, the appropriate method in the ANSI (GetComputerNameA) or Unicode (GetComputerNameW) formats will be invoked. If you set CharSet property to CharSet.Ansi, the strings will be marshaled in ANSI format and only the GetComputerNameA method will be invoked. While using ANSI would work on all operating systems because it is an industry standard, the following code will not work because the EntryPoint is defined as ComputerName. [DllImport("kernel32.dll", EntryPoint="ComputerName", CharSet=CharSet.Ansi)] static extern bool GetComputerName([Out] StringBuilder lpBuffer, ref uint lpnSize); Setting the CharSet property to CharSet.Unicode will fail if the target platform uses only the ANSI format. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Call unmanaged DLL functions within a .NET Framework application, and control the marshalling of data in a .NET Framework application. (Refer System.Runtime.InteropServices namespace) References :

Specifying a Character Set MSDN Link: http://msdn2.microsoft.com/en-us/library/7b93s42f(vs.80).aspx Specifying an Entry Point MSDN Link: http://msdn2.microsoft.com/en-us/library/f5xe74x8(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-148

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You need to configure the security policy for an assembly. The location of the assembly is stored in a string variable named codebase. The variable codebase may point to an assembly on the Internet (for example, http://www.measureup.com/bin/process.dll) or to an assembly on the local computer (for example, file:///C:/bin/process.dll). You need to create an Evidence object corresponding to the assembly. Your code will run on different computers and must run independent of the user's local settings. Which code segment should you use? 1. public Evidence GetEvidence (string codebase) { Evidence evd = new Evidence(); evd.AddHost(new Url(codebase)); return evd; } <Correct> 2. public Evidence GetEvidence (string codebase) { Evidence evd = new Evidence(); evd.AddHost(Site.CreateFromUrl(codebase)); return evd; } 3. public Evidence GetEvidence (string codebase) { Evidence evd = new Evidence(); evd.AddAssembly(this.GetType().Module.Assembly.Evidence); return evd; } 4. public Evidence GetEvidence (string codebase) { Evidence evd = new Evidence(); evd.AddHost(Zone.CreateFromUrl(codebase)); return evd; } Explanation : You should use the following code segment to create the Evidence object for the assembly in the codebase variable: public Evidence GetEvidence (string codebase) { Evidence evd = new Evidence(); evd.AddHost(new Url(codebase)); return evd; } The AddHost method adds new evidence based on the specified host. You should use the Url class to provide the URL from which the assembly originates when the given URL may be an HTTP-based URL or a file-based URL. You should not use the following code because the Site.CreateFromUrl method cannot handle file-based URLs for the assembly and will throw an ArgumentException exception: public Evidence GetEvidence (string codebase) {

Evidence evd = new Evidence(); evd.AddHost(Site.CreateFromUrl(codebase)); return evd; } You should not use the following code because the security zone assigned to the assembly by the Zone class depends on Internet Explorer's settings for the user running the code. In this case, your code must run independent of the user's local settings. public Evidence GetEvidence (string codebase) { Evidence evd = new Evidence(); evd.AddHost(Zone.CreateFromUrl(codebase)); return evd; } You should not use the following code because it ignores the given codebase and instead returns an Evidence object for the executing assembly: public Evidence GetEvidence (string codebase) { Evidence evd = new Evidence(); evd.AddAssembly(this.GetType().Module.Assembly.Evidence); return evd; } Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control code privileges by using System.Security.Policy classes. (Refer System.Security.Policy namespace) Evidence Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.policy.evidence(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-059

____________________________________________________________________________________________________________________ You are developing a Windows service application by using the .NET Framework. You write the following installation code for the Windows service: [RunInstallerAttribute(true)] public class MyServiceInstaller : Installer { // add additional code here } You need to install the Windows service and write the values associated with the service in the Windows Registry. What should you do? 1. Use the .NET Services Installation Tool (Regsvcs.exe). 2. Use the Global Assembly Cache Tool (Gacutil.exe). 3. Use the Installer Tool (InstallUtil.exe). <Correct>

4. Use the Assembly Registration Tool (Regasm.exe). Explanation : You should use the Installer Tool (InstallUtil.exe) to install the Windows service. When you execute this utility, it will install the classes in the specified assembly that derive from the Installer class and have the RunInstallerAttribute attribute set to true. The .NET Services Installation Tool (Regsvcs.exe) should not be used in this case because this tool is used for installing classes for Enterprise Services. The Assembly Registration Tool (Regasm.exe) should not be used in this case because this tool registers .NET assemblies so that COM clients can access .NET classes. This is not a requirement in the scenario. The Global Assembly Cache Tool (Gacutil.exe) should not be used in this case because this tool is used for installing and uninstalling assemblies from the global assembly cache. This is not a requirement in the scenario. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Implement, install, and control a service. (Refer System.ServiceProcess namespace) Installer Tool (InstallUtil.exe) MSDN Link: http://msdn2.microsoft.com/en-us/library/50614e95(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-080

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following classes as part of your code: public class Book { public string Name; } public class Encyclopedia : Book { public int Volume; } public class Library { public Book[] Books; } You write the following code to create an object of the Library type in your application and serialize it: Book[] books = new Book[3]; books[0] = new Book(); books[0].Name = "Book Name 1"; books[1] = new Book(); books[1].Name = "Book Name 2"; books[2] = new Encyclopedia(); books[2].Name = "Encyclopedia 1"; ((Encyclopedia)books[2]).Volume = 10; Library library = new Library(); library.Books = books; XmlSerializer mySerializer = new XmlSerializer(typeof(Library)); using (StreamWriter myWriter = new StreamWriter("books.xml")) { mySerializer.Serialize(myWriter, library); } The serialized XML in books.xml must match the XML shown in the exhibit. When you run the application, you get a System.InvalidOperation exception. What should you do to successfully execute the application? 1. Change the definition of the Library class to: public class Library { [XmlArrayItem(Type = typeof(Book)), XmlArrayItem(Type = typeof(Encyclopedia))] public Book[] Books; } <Correct> 2. Change the definition of the Library class to: public class Library { [XmlArrayItem("Book"), XmlArrayItem("Encyclopedia")] public Book[] Books; }

3. Change the definition of the Library class to: public class Library { [XmlArray("Book"), XmlArray("Encyclopedia")] public Book[] Books; } 4. Change the definition of the Library class to: [XmlType("Enclycopedia")] public class Library { public Book[] Books; } Explanation : The application generates a System.InvalidOperation exception at runtime because it does not recognize the derived type named Encyclopedia. You must change the definition of the Library class to the following: public class Library { [XmlArrayItem(Type = typeof(Book)), XmlArrayItem(Type = typeof(Encyclopedia))] public Book[] Books; } The XmlArrayItem attribute specifies that the array items may be either of the type Book or the type Encyclopedia. You must use the Type property of the attribute to specify a type. If you do not specify the Type property, the default property ElementName is used and the name of the element is changed instead of its type. You should not use the XmlType attribute because it only adds additional schema information to the XML file. Adding this attribute will not eliminate the System.InvalidOperation exception. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Control the serialization of an object into XML format by using the System.Xml.Serialization namespace. Controlling XML Serialization Using Attributes MSDN Link: http://msdn2.microsoft.com/en-us/library/2baksw0z(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-098

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. The application configuration file has the following configuration settings: <system.diagnostics> <switches> <add name="BooleanSwitch" value="1" /> <add name="TraceLevelSwitch" value="1" /> </switches> </system.diagnostics> In your code, you create switch objects by using the following statements: BooleanSwitch bs = new BooleanSwitch("BooleanSwitch", "Boolean Switch"); TraceSwitch ts = new TraceSwitch("TraceLevelSwitch", "Trace Switch"); What should be the outcome of executing these statements? (Each correct answer presents part of the solution. Choose two.) 1. The BooleanSwitch switch object is enabled.<Correct> 2. The TraceLevelSwitch switch object's trace level is set to TraceLevel.Info. 3. The TraceLevelSwitch switch object's trace level is set to TraceLevel.Error. <Correct> 4. The TraceLevelSwitch switch object's trace level is set to TraceLevel.Warning. 5. The BooleanSwitch switch object is disabled. Explanation : BooleanSwitch objects are either On or Off. A value of 0 corresponds to Off (disabled), and any nonzero value corresponds to On (enabled). The TraceSwitch class provides five different levels of tracing switches. These levels are defined by the TraceLevel enumeration as Off - 0, Error - 1, Warning - 2, Info - 3, and Verbose 4. A value of 1 will enable the BooleanSwitch object and a value of 1 will set the TraceLevelSwitch object's trace level to TraceLevel.Error. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Debug and trace a .NET Framework application by using the System.Diagnostics namespace How to: Configure Trace Switches MSDN Link: http://msdn2.microsoft.com/en-us/library/t06xyy08(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-029

____________________________________________________________________________________________________________________ You are developing a text processing application by using the .NET Framework. You write the following code to iterate over a collection of strings and populate a ListBox control with the values it contains (line numbers are for reference only). The GetStrings function returns an array of strings. 01: StringCollection myStrCol = new StringCollection(); 02: myStrCol.AddRange(GetStrings()); 03: StringEnumerator myEnumerator = myStrCol.GetEnumerator(); You need to add code to populate the ListBox control. What code should you add? 1. myEnumerator.Reset(); do { lstStrings.items.Add(myEnumerator.Current) } while (myEnumerator.MoveNext()) 2. while (myEnumerator.MoveNext()) lstStrings.Items.Add(myEnumerator.Current); <Correct> 3. do { lstStrings.items.Add(myEnumerator.Current) } while (myEnumerator.MoveNext()) 4. do { lstStrings.items.Add(myEnumerator.Current) myEnumerator.Reset(); } while (myEnumerator.MoveNext()) Explanation : You should add the following code after line 03 to populate the ListBox control: while (myEnumerator.MoveNext()) lstStrings.Items.Add(myEnumerator.Current); When you instantiate the enumerator, the Current property points to a location before the first element. You need to call MoveNext() to set the Current point to the first element. Using the following code is incorrect because you attempt to use Current when it does not point to a valid location: do { lstStrings.items.Add(myEnumerator.Current) } while (myEnumerator.MoveNext()) Using the following code is incorrect because calling the Reset method brings the enumerator back to the position before the first element in the collection: myEnumerator.Reset() do { lstStrings.items.Add(myEnumerator.Current) } while (myEnumerator.MoveNext()) Using the following code is incorrect because each time through the loop the enumerator is

repositioned before the first element: do { lstStrings.items.Add(myEnumerator.Current) myEnumerator.Reset(); } while (myEnumerator.MoveNext()) Objective: Developing applications that use system types and collections Sub Objective(s): Manage data in a .NET Framework application by using specialized collections (Refer System.Collections.Specialized namespace) StringEnumerator Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.specialized.stringenumerator(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-077

____________________________________________________________________________________________________________________ You are developing a remoting application by using the .NET Framework. Your system relies on run-time type validation. You need to deserialize a remote stream by using the BinaryFormatter class in your application. You must configure the BinaryFormatter object to reduce the likelihood of a deserialization attack. What should you do? 1. Set the FilterLevel property to TypeFilterLevel.Low. <Correct> 2. Set the FilterLevel property to TypeFilterLevel.Full. 3. Set the TypeFormat property to FormatterTypeStyle.TypesAlways. 4. Set the TypeFormat property to FormatterTypeStyle.TypesWhenNeeded. Explanation : You should set the FilterLevel property of the BinaryFormatter object to TypeFilterLevel.Low. This setting deserializes only certain types, including the minimum types necessary for remoting, primitive types, and types that support serialization either by implementing the ISerializable interface or because they have the SerializableAttribute attribute, but that do not demand any other rights. The TypeFilterLevel.Low value is also the default setting for the FilterLevel property of the BinaryFormatter class. Setting the FilterLevel property to TypeFilterLevel.Full deserializes all types and therefore does not offer protection against deserialization attacks. The TypeFormat property does not limit the deserialization of types. It just configures how the types are laid out in the deserialization stream. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Implement custom serialization formatting by using the Serialization Formatter classes. References : BinaryFormatter Class MSDN Link: http://msdn2.microsoft.com/system.runtime.serialization.formatters.binary.binaryformatter.aspx Automatic Deserialization in .NET Framework Remoting MSDN Link: http://msdn2.microsoft.com/en-us/library/5dxse167.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-075

____________________________________________________________________________________________________________________ You are developing a data analysis application by using the .NET Framework. When a file is supplied to the program for reading data, you know nothing about the inherent structure of the file. You must read the contents of the file byte-by-byte and then use a custom algorithm to find its format. You need to select a class that allows you to read a file's contents byte-by-byte. Which class should you select? 1. StreamReader 2. BinaryReader 3. StringReader 4. FileStream <Correct> Explanation : The FileStream class is designed for reading a file byte-by-byte. The StreamReader class is useful for reading character data in a particular encoding. This class is not useful for reading any other data, such as an image. The BinaryReader class is useful when you know the binary format for the data to read. For example a file may contain a floating-point value, followed by a string of characters, followed by an integer. Knowledge of internal data storage is useful when using the BinaryReader class. The StringReader class reads text from a string. This class is not useful for reading any other data, such as an image. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Manage byte streams by using Stream classes. (Refer System.IO namespace) FileStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.filestream(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-119

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You must write code that repeatedly performs role-based validations. You need a way to create WindowsPrincipal objects that requires the least amount of overhead on the system. In the list on the right, select the required code segments. Place your selections in the list on the left in the order in which the code statements must be used in the code. Place your selections in the list on the left by clicking the items in the list on the right and clicking the arrow button. You can also use the up and down buttons to rearrange items in the list on the left. You may not need to use all of the items from the list on the right. Explanation : When you must perform role-based authorization repeatedly in your code, using the following code to create a WindowsPrincipal object produces the least overhead: AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); WindowsPrincipal princi = (WindowsPrincipal) Thread.CurrentPrincipal; The SetPrincipalPolicy method sets the active principal policy for the current appdomain to WindowsPrincipal. You should place this code in a procedure that executes only once, such as in the Form_Load event. After this principal policy is set, you can retrieve the principal object by using the Thread.CurrentPrincipal property. For the principal policy to be effective, you must set the principal policy before using the Thread.CurrentPrincipal property. You can also use the following statements to retrieve the WindowsPrincipal object in your code: WindowsIdentity iden = WindowsIdentity.GetCurrent(); WindowsPrincipal princi = new WindowsPrincipal(iden); However, this technique causes additional overhead and should be used only when you create a WindowsPrincipal object for single validations. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Access and modify identity information by using the System.Security.Principal classes. (Refer System.Security.Principal namespace) How to: Create a WindowsPrincipal Object MSDN Link: http://msdn2.microsoft.com/en-us/library/t6547wf1(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-130

____________________________________________________________________________________________________________________ You are developing an application by using the .NET Framework. You must call the GetSystemTime method in kernel32.dll. The method is declared in Win32 API as: void GetSystemTime( LPSYSTEMTIME lpSystemTime // pointer to SYSTEMTIME structure ); The structure SYSTEMTIME is declared in Win32 API as: typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME; You declare the GetSystemTime method in your .NET code as follows: [DllImport("kernel32.dll")] static extern void GetSystemTime(out SystemTime lpSystemTime); How should you declare the SystemTime type in .NET code? 1. [StructLayout(LayoutKind.Sequential)] private struct SystemTime { [MarshalAs(UnmanagedType.U2)] public short Year; [MarshalAs(UnmanagedType.U2)] public short Month; [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; [MarshalAs(UnmanagedType.U2)] public short Day; [MarshalAs(UnmanagedType.U2)] public short Hour; [MarshalAs(UnmanagedType.U2)] public short Minute; [MarshalAs(UnmanagedType.U2)] public short Second; [MarshalAs(UnmanagedType.U2)] public short Milliseconds; } <Correct> 2. [StructLayout(LayoutKind.Sequential)] private struct SystemTime { [MarshalAs(UnmanagedType.I2)] public short Year; [MarshalAs(UnmanagedType.I2)] public short Month; [MarshalAs(UnmanagedType.I2)] public short DayOfWeek; [MarshalAs(UnmanagedType.I2)] public short Day; [MarshalAs(UnmanagedType.I2)] public short Hour; [MarshalAs(UnmanagedType.I2)] public short Minute; [MarshalAs(UnmanagedType.I2)] public short Second; [MarshalAs(UnmanagedType.I2)] public short Milliseconds; } 3. [StructLayout(LayoutKind.Sequential)] private struct SystemTime { [MarshalAs(UnmanagedType.U4)] public int Year; [MarshalAs(UnmanagedType.U4)] public int Month; [MarshalAs(UnmanagedType.U4)] public int DayOfWeek; [MarshalAs(UnmanagedType.U4)] public int Day; [MarshalAs(UnmanagedType.U4)] public int Hour; [MarshalAs(UnmanagedType.U4)] public int Minute; [MarshalAs(UnmanagedType.U4)] public int Second;

[MarshalAs(UnmanagedType.U4)] public int Milliseconds; } 4. [StructLayout(LayoutKind.Sequential)] private struct SystemTime { [MarshalAs(UnmanagedType.I4)] public int Year; [MarshalAs(UnmanagedType.I4)] public int Month; [MarshalAs(UnmanagedType.I4)] public int DayOfWeek; [MarshalAs(UnmanagedType.I4)] public int Day; [MarshalAs(UnmanagedType.I4)] public int Hour; [MarshalAs(UnmanagedType.I4)] public int Minute; [MarshalAs(UnmanagedType.I4)] public int Second; [MarshalAs(UnmanagedType.I4)] public int Milliseconds; } Explanation : The MarshalAs attribute specifies how data should be marshaled between managed code and unmanaged code. This attribute should be used when a particular type can be marshaled to different data types. The WORD data type should be marshaled as UnmanagedType.U2, which is an unsigned 2-byte integer. You should not use UnmanagedType.I2 because it represents a signed integer and will not be able to hold all the values of the WORD data type. You should not use UnmanagedType.U4 and UnmanagedType.I4 because they represent 4-byte unsigned and signed integers respectively. Also, this marshaling will result in invalid output. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Call unmanaged DLL functions within a .NET Framework application, and control the marshalling of data in a .NET Framework application. (Refer System.Runtime.InteropServices namespace) References : Platform Invoke Data Types MSDN Link: http://msdn2.microsoft.com/en-us/library/ac7ay120(vs.80).aspx MarshalAsAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute(vs.80). aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-142

____________________________________________________________________________________________________________________ You are developing an application by using the .NET Framework. You retrieve the file's security settings by using the following code: FileStream file = new FileStream(@"c:\docs\projections.xls", FileMode.Open, FileAccess.ReadWrite) FileSecurity fileSec = file.GetAccessControl(); You need to configure security settings for the file c:\docs\projections.xls. This file should keep the security settings that it inherited from its parent directory. However, any future changes to the security settings of the parent directory must not be applied to the c:\docs\projections.xls file. What method should you call on the fileSec object to configure security settings for the c:\docs\projections.xls file? 1. SetAccessRule 2. SetAuditRule 3. SetAccessRuleProtection 4. SetAuditRuleProtection Explanation : You should call the SetAccessRuleProtection method on the fileSec object to configure its security settings. The SetAccessRuleProtection method allows you to specify whether you want to inherit and preserve the security settings of the parent objects and if you want to protect the current object from any future inheritance of security settings. You should not use the SetAccessRule method because this method is used to explicitly specify the access rule that you want to set for an object. The SetAccessRule method does not help you configure the propagation of security settings from parent objects to child objects. You should not use the SetAuditRule method because this method is used to explicitly set an audit rule for an object. An audit rule does not modify the access control for a file. Instead, an audit rule is used to specify any audit that needs to be performed. For example, an audit rule can specify if a failed attempt to write to a file must be recorded. You should not use the SetAuditRuleProtection method because this method helps you configure the propagation of audit settings from parent objects to child objects. This method does not configure access control settings for an object. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement access control by using the System.Security.AccessControl classes. ObjectSecurity.SetAccessRuleProtection Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.accesscontrol.objectsecurity.setaccessrul eprotection(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-111

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You create a new class named WhsProcess as shown in the exhibit. The class is compiled to a file named WhsProcess.dll. Component Object Model (COM) applications must be able to create instances of this class and invoke methods. COM applications may need to bind the type information at compile time. Which .NET Framework command line tool should you use? 1. Use the Type Library Exporter tool (Tlbexp.exe). 2. Use the Type Library Importer tool (Tlbimp.exe). 3. Use the Assembly Registration tool (Regasm.exe). <Correct> 4. Use the Native Image Generator tool (Ngen.exe). Explanation : COM applications expect to find runtime information about types in the Windows registry. The Assembly Registration tool (Regasm.exe) reads an assembly and creates the entries required by the COM applications. The Assembly Registration tool, when used with its /tlb option, also allows you to generate a COM type library that can be used by the COM applications to bind the type information at compile time. The Type Library Exporter tool (Tlbexp.exe) generates a COM library from an assembly. The generated type library can be used to compile COM applications. In order to successfully run a COM application, the type information must be registered in the Windows registry. The Type Library Importer tool (Tlbimp.exe) is functionally the opposite of Tlbexp.exe. It processes COM type libraries to generate .NET assemblies. The Native Image Generator tool (Ngen.exe) is used to generate a native image for managed code. Doing so reduces the load time for .NET applications. This tool does not convert assemblies for use in COM applications. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Expose COM components to the .NET Framework and .NET Framework components to COM. (Refer System.Runtime.InteropServices namespace) Assembly Registration Tool (Regasm.exe) MSDN Link: http://msdn2.microsoft.com/en-us/library/tzat5yw6(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-027

____________________________________________________________________________________________________________________ You are developing an application by using .NET Framework. You write the following code (line numbers are only for reference): 01: String myStr1 = "player's page"; 02: String myStr2 = "Players Page"; 03: CompareInfo myComp = CultureInfo.InvariantCulture.CompareInfo; 04: int compareResult; 05: // Add code here 06: Console.WriteLine(compareResult); In line 05, you need to compare myStr1 and myStr2 in such a way that the program displays "0" as the output. What code should you enter at line 05? 1. compareResult = myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase & CompareOptions.IgnoreSymbols); 2. compareResult = myComp.Compare(myStr1, myStr2, CompareOptions. .Ordinal & CompareOptions.IgnoreCase); 3. compareResult = myComp.Compare(myStr1, myStr2, CompareOptions.StringSort); 4. compareResult = myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols); <Correct> 5. compareResult = myComp.Compare(myStr1, myStr2, CompareOptions.OrdinalIgnoreCase); Explanation : You should use the following statement at line 05: compareResult = myComp.Compare(myStr1, myStr2, CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols); One overloaded version of the CompareInfo.Compare method compares two strings using the specified CompareOptions value. Options can be either the value Ordinal or OrdinalIgnoreCase used by itself, one of the enumerated values IgnoreCase, IgnoreSymbols, IgnoreNonSpace, IgnoreWidth, IgnoreKanaType, and StringSort, or the bitwise combination of two or more of those values. In this case, if the program outputs 0, it means that both the strings must be evaluated as being equal. This is possible if you ignore case as well as symbols in the given strings. This can be achieved by a bitwise-or combination of CompareOptions.IgnoreCase and CompareOptions.IgnoreSymbols. IgnoreSymbols indicates that the string comparison should ignore symbols characters that are not alphanumeric, including whitespace characters. Using a bitwise-and combination of CompareOptions.IgnoreCase and CompareOptions.IgnoreSymbols is incorrect because using bitwise-and will not turn on the bitwise flags. Using CompareOptions.OrdinalIgnoreCase is not correct because using OrdinalIgnoreCase causes the string to be converted to uppercase before performing an ordinal comparison. This option does not ignore any symbols in the string. Using CompareOptions.Ordinal And CompareOptions.IgnoreCase is not legal. The Ordinal flag can only be used by itself. Using CompareOptions.StringSort is not correct because the StringSort option indicates that the string comparison must use a string sort algorithm in which symbolic characters come before alphanumeric characters. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application

Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) References : CompareInfo.Compare Method (String, String, CompareOptions) MSDN Link: http://msdn2.microsoft.com/en-us/library/0sk4bdtt(vs.80).aspx CompareOptions Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.globalization.compareoptions(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-081

____________________________________________________________________________________________________________________ You create the following class in your .NET Framework application: public class Model { public string Name; } You need to deserialize the data in model.xml in an object of the Model type. The contents of model.xml are shown in the exhibit. When deserializing, if you encounter any unknown elements, the method named Model_Unknown should be executed. How should you write the code for deserialization? 1. private void DeserializeModel(string filename) { XmlSerializer xs = new XmlSerializer(typeof(Model)); xs.UnknownElement += new XmlElementEventHandler(Model_Unknown); using (FileStream fs = new FileStream(filename, FileMode.Open)) { Model myModel = (Model) xs.Deserialize(fs); } } <Correct> 2. private void DeserializeModel(string filename) { XmlSerializer xs = new XmlSerializer(typeof(Model)); xs.UnreferencedObject += new UnreferencedObjectEventHandler(Model_Unknown); using (FileStream fs = new FileStream(filename, FileMode.Open)) { Model myModel = (Model) xs.Deserialize(fs); } } 3. private void DeserializeModel(string filename) { XmlSerializer xs = new XmlSerializer(typeof(Model)); using (FileStream fs = new FileStream(filename, FileMode.Open)) { Model myModel = (Model) xs.Deserialize(fs); } } 4. private void DeserializeModel(string filename) { XmlSerializer xs = new XmlSerializer(typeof(Model)); xs.UnknownAttribute += new XmlAttributeEventHandler(Model_Unknown); using (FileStream fs = new FileStream(filename, FileMode.Open)) { Model myModel = (Model) xs.Deserialize(fs); } } Explanation : You should use the following code for deserialization: private void DeserializeModel(string filename) { XmlSerializer xs = new XmlSerializer(typeof(Model)); xs.UnknownElement += new XmlElementEventHandler(Model_Unknown);

using (FileStream fs = new FileStream(filename, FileMode.Open)) { Model myModel = (Model) xs.Deserialize(fs); } } The UnknownElement event is fired when the XmlSerializer encounters an XML element such as Number, Style, and Size that are not part of the class definition. You must attach the Model_Unknown method to this event by creating a new XmlElementEventHandler delegate object. You should not use the UnknownAttribute event because this event is fired when unknown attribute values are encountered. The XML file in the exhibit has no attributes in the data. You should not use the UnreferencedObject event because this event is fired when the XmlSerializer object encounters a type that is not being used. In this scenario, there are no unused types. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Control the serialization of an object into XML format by using the System.Xml.Serialization namespace. XmlSerializer Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-057

____________________________________________________________________________________________________________________ You are developing a Windows service application by using the .NET Framework. You write the following code in your class: Timer myTimer ; You add the following code to the OnStart method: myTimer = new Timer(statusDelegate, null, 1000, 250); The delegate statusDelegate is already correctly defined in your class. You need to override the OnPause method to prevent the Timer's delegate from being executed. Which code segment should you use? 1. myTimer.Dispose; 2. myTimer.Interval = 0; 3. myTimer.Enabled = False; 4. myTimer.Change(0, Timeout.Infinite); <Correct>

Explanation : You should call the Change method and pass Timeout.Infinite as the second argument. The second argument defines the period that must elapse between each execution of the callback method defined by the delegate. You should not call the Dispose method. The Dispose method releases the resource used by the object. Since you want the object to be able to restart, you should not release its resources. You should not set the Enabled property of myTimer to False. The Enabled property is used with the Timer control defined in System.Windows.Forms. This Timer cannot be used with a Windows service. Instead, you must use the Timer class in the System.Timers namespace. You should not set the Interval property of myTimer to 0. The Interval property is used with the Timer control defined in System.Windows.Forms. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Develop multithreaded .NET Framework applications. (Refer System.Threading namespace) References : Timer Class MSDN Link: http://msdn2.microsoft.com/saba8ksx(vs.80).aspx Timer.Change Method MSDN Link: http://msdn2.microsoft.com/en-us/library/yz1c7148(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-020

____________________________________________________________________________________________________________________ You are writing an application that will store paycheck data using XML serialization. The XML must be formatted as that shown in the exhibit. You are creating the Paycheck class. What code should you use? 1. public class Paycheck { private string m_EmployeeName; private decimal m_grossPay; private decimal m_netPay; private decimal m_tax; private Deductions m_taxDeductions; public Paycheck() { m_taxDeductions = new Deductions(); } [XmlMapping("Payee")] public string EmployeeName { get { return m_EmployeeName;} set { m_EmployeeName = value;} } public decimal GrossPay { get {return m_grossPay;} set {m_grossPay = value;} } [XmlMapping("Deductions")] public Deductions taxDeductions { get { return m_taxDeductions; } set { m_taxDeductions = value; } } public decimal NetPay { get {return m_netPay;} set {m_netPay = value;} } [XmlIncludeAttributes("State", "Federal")] public class Deductions { private decimal m_stateTax; private decimal m_fedTax; [XmlAttribute("State")] public decimal StateTax { get {return m_stateTax;} set {m_stateTax = value;} } [XmlAttribute("Federal")] public decimal FedTax { get {return m_fedTax;} set {m_fedTax = value;} } } } 2. public class Paycheck { private string m_EmployeeName; private decimal m_grossPay; private decimal m_netPay; private decimal m_tax; private Deductions m_taxDeductions;

public Paycheck() { m_taxDeductions = new Deductions(); } [XmlElement("Payee")] public string EmployeeName { get { return m_EmployeeName;} set { m_EmployeeName = value;} } public decimal GrossPay { get {return m_grossPay;} set {m_grossPay = value;} } [XmlElement("Deductions")] public Deductions taxDeductions { get { return m_taxDeductions; } set { m_taxDeductions = value; } } public decimal NetPay { get {return m_netPay;} set {m_netPay = value;} } public class Deductions { private decimal m_stateTax; private decimal m_fedTax; [XmlAttribute("State")] public decimal StateTax { get {return m_stateTax;} set {m_stateTax = value;} } [XmlAttribute("Federal")] public decimal FedTax { get {return m_fedTax;} set {m_fedTax = value;} } } } <Correct> 3. public class Paycheck { private string m_EmployeeName; private decimal m_grossPay; private decimal m_netPay; private Deductions m_taxDeductions; private decimal m_stateTax; private decimal m_fedTax; public Paycheck() { m_taxDeductions = new Deductions(); } [XmlMapping("Payee")] public string EmployeeName { get { return m_EmployeeName;} set { m_EmployeeName = value;} } public decimal GrossPay { get {return m_grossPay;} set {m_grossPay = value;} } [XmlElement("Deductions")] public Deductions tax { get { return m_taxDeductions; } set { m_taxDeductions = value; } } public decimal NetPay { get {return m_netPay;} set {m_netPay = value;} } [XmlAttribute("State")] public decimal StateTax

{ get {return m_stateTax;} set {m_stateTax = value;} } [XmlAttribute("Federal")] public decimal FedTax { get {return m_fedTax;} set {m_fedTax = value;} } } 4. public class Paycheck { private string m_EmployeeName; private decimal m_grossPay; private decimal m_netPay; private Deductions m_taxDeductions; private decimal m_stateTax; private decimal m_fedTax; public Paycheck() { m_taxDeductions = new Deductions(); } [XmlElement("Payee")] public string EmployeeName { get { return m_EmployeeName;} set { m_EmployeeName = value;} } public decimal GrossPay { get {return m_grossPay;} set {m_grossPay = value;} } [XmlElement("Deductions")] public Deductions taxDeductions { get { return m_tax; } set { m_tax = value; } } public decimal NetPay { get {return m_netPay;} set {m_netPay = value;} } [XmlAttribute("State")] public decimal StateTax { get {return m_stateTax;} set {m_stateTax = value;} } [XmlAttribute("Federal")] public decimal FedTax { get {return m_fedTax;} set {m_fedTax = value;} } } Explanation : You should use the following code: public class Paycheck { private string m_EmployeeName; private decimal m_grossPay; private decimal m_netPay; private decimal m_tax; private Deductions m_taxDeductions; public Paycheck() { m_taxDeductions = new Deductions(); } [XmlElement("Payee")] public string EmployeeName { get { return m_EmployeeName;} set { m_EmployeeName = value;} }

public decimal GrossPay { get {return m_grossPay;} set {m_grossPay = value;} } [XmlElement("Deductions")] public Deductions taxDeductions { get { return m_taxDeductions; } set { m_taxDeductions = value; } } public decimal NetPay { get {return m_netPay;} set {m_netPay = value;} } public class Deductions { private decimal m_stateTax; private decimal m_fedTax; [XmlAttribute("State")] public decimal StateTax { get {return m_stateTax;} set {m_stateTax = value;} } [XmlAttribute("Federal")] public decimal FedTax { get {return m_fedTax;} set {m_fedTax = value;} } } } To change the name of the XML element to a different name than the name of the property, use the XmlElement attribute. You need to do this for EmployeeName and Tax. To make the StateTax and FedTax properties attribute of the Deductions element, you need to encase them in a class named Deductions and use the XmlAttribute attribute. You can specify a name to cause the attributes to use the specified name instead of the name of the property. If you do not encase the StateTax and FedTax properties in a class, they will be made attributes of the root element. You should not use the XmlIncludeAttribute attribute. You use this attribute to cause a derived class to be included. You should not use XmlMapping. XmlMapping is a class, not an attribute. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Control the serialization of an object into XML format by using the System.Xml.Serialization namespace. Attributes That Control XML Serialization MSDN Link: http://msdn2.microsoft.com/en-us/library/83y7df3e(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-107

____________________________________________________________________________________________________________________ You are developing a class library by using the .NET Framework. You compress a file using the following code: byte[] buffer = new byte [100]; FillBuffer(ref buffer); using (FileStream fs = new FileStream("customerFile.txt", FileMode.Create, True)) { using (GZipStream cs = new GZipStream(fs, CompressionMode.Compress)) { cs.Write(buffer, 0, buffer.Length); } } You need to write code to uncompress the file and store the result in uBuff. Which code segment should you use? 1. using (GZipStream ds = new GZipStream(fs, CompressionMode.Decompress)) { ds.Read(uBuff, 0, buffer.Length); } 2. using (DeflateStream ds = new DeflateStream(fs, CompressionMode.Decompress)) { ds.Read(uBuff, 0, uBuff.Length); } 3. using (DeflateStream ds = new DeflateStream(fs, CompressionMode.Decompress)) { ds.Read(uBuff, 0, buffer.Length); } 4. using (GZipStream ds = new GZipStream(fs, CompressionMode.Decompress)) { ds.Read(uBuff, 0, uBuff.Length); } <Correct> Explanation : The GZipStream class and the DeflateStream class both allow you to compress and decompress streams. If the compression mode is CompressionMode.Compress, compression is performed. If the compression mode is CompressionMode.Decompress, decompression is performed. If you compress a stream by using the GZipStream class, you must decompress the compressed stream by using the GZipStream class. To decompress a stream, you can either read it one byte at a time using the ReadByte method or read it into a buffer using the Read method. The Read method accepts the name of a buffer, the offset at which to begin the read operation and the length of the buffer. Since you are reading into uBuff, you should use its length as the last argument. Given these facts, the correct code segment for deserializing compressed customer data into a Customer object would be: using (GZipStream ds = new GZipStream(fs, CompressionMode.Decompress)) {

ds.Read(uBuff, 0, uBuff.Length); } Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Compress or decompress stream information in a .NET Framework application (Refer System.IO.Compression namespace), and improve the security of application data by using isolated storage. (Refer System.IO.IsolatedStorage namespace) References : GZipStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.compression.gzipstream(vs.80).aspx DeflateStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.compression.deflatestream(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-116

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. The application allows users to download video files to the local hard drive. The application needs to have permission for file input and output operations in order to execute. If file input and output permissions are not available, your application should not execute. You need to secure this application. What action should you take? 1. Apply the following attribute at the assembly level: [assembly:FileIOPermission(SecurityAction.RequestOptional, Unrestricted = true)] 2. Apply the following attribute at the assembly level: [assembly:FileIOPermission(SecurityAction.RequestMinimum, Unrestricted = true)] <Correct> 3. Apply the following attribute at the class level: [FileIOPermission(SecurityAction.Demand, Unrestricted = true)] 4. Apply the following attribute at the class level: [FileIOPermission(SecurityAction.Assert, Unrestricted = true)] 5. Apply the following attribute at the assembly level: [assembly:FileIOPermission(SecurityAction.RequestRefuse, Unrestricted = true)] Explanation : You should apply the following attribute at the assembly level: [assembly:FileIOPermission(SecurityAction.RequestMinimum, Unrestricted = true)] The SecurityAction.RequestMinimum value requests for the minimum set of permissions that are required by the application to execute. If these permissions are not available, the application will not execute. The SecurityAction.RequestRefuse value specifies the permissions that the application should not be granted. The SecurityAction.RequestOptional value specifies that the requested permissions are optional. The application executes but if the requested permissions are not available when needed, an exception is thrown. In this scenario, the application should not execute at all if the permissions are not available. The security is required at the level of application. Therefore, you should not apply attributes at the class level. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control permissions for resources by using the System.Security.Permission classes. (Refer System.Security.Permission namespace) References : FileIOPermissionAttribute Class MSDN

Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.fileiopermissionattribute(vs. 80).aspx SecurityAction Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.securityaction(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-016

____________________________________________________________________________________________________________________ In your application, you decide to use the CreateDomain method of the AppDomain class to create an application domain. You need to set the following properties for the new application domain: - Root directory - Location of the configuration file - Search path that the Common Language Runtime uses to load the assemblies into the domain You need to pass these property values to the CreateDomain method. What must you pass as a parameter to the CreateDomain method? 1. An AppDomainSetup object <Correct> 2. An AppDomainFactory object 3. An AppDomainIsolatedTask object 4. An AppDomainHelper object Explanation : You should pass an AppDomainSetup object as a parameter to the CreateDomain method. The AppDomainSetup object allows you to specify the root directory, the location of the configuration file, and the search path to load assemblies to the domain. The AppDomainHelper object is not the correct answer because the AppDomainHelper is used by the .NET Framework and should not be called directly. The AppDomainFactory object is used by the .NET Framework to create a new instance of the AppDomain class for a Web application. This object cannot be used directly. The AppDomainIsolatedTask object can be used to create build tasks that can be instantiated in their own application domain. This object cannot be used to specify setup information for an application domain. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Create a unit of isolation for common language runtime within a .NET Framework application by using application domains. (Refer System namespace) AppDomain.CreateDomain Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.appdomain.createdomain(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-106

____________________________________________________________________________________________________________________ You are developing a Windows assembly by using the .NET Framework. The assembly allows users to customize an application's behavior through an Options dialog box. The assembly might be used by multiple application domains and each application domain should store its own settings for each user. You need to retrieve data from the isolated storage area corresponding to the application domain and the currently logged-on user. Which code segment should you use? (Each correct answer presents a complete solution. Choose two.) 1. IsolatedStorageFile store = IsolatedStorageFile.GetStore(IsolatedStorageScope.User, null); 2. IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForDomain(); <Correct> 3. IsolatedStorageFile store = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User | IsolatedStorageScope.Domain, null); <Correct> 4. IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly(); 5. IsolatedStorageFile store = IsolatedStorageFile.GetStore(IsolatedStorageScope.Application, null); Explanation : According to the requirements, you need to retrieve application-specific and user-specific settings from the isolated storage area. Therefore, you should use the following code segment to retrieve the settings from the isolated storage area corresponding to the application domain for the currently logged-on user: IsolatedStorageFile store = IsolatedStorageFile.GetStore(IsolatedStorageScope.Assembly | IsolatedStorageScope.User | IsolatedStorageScope.Domain, null); Here, the first parameter to the GetStore method creates an application domain-specific and a user-specific scope for retrieving information from isolated storage. An alternate way of retrieving the same store is to call the GetUserStoreForDomain method of the IsolatedStorageFile class. If you specify IsolatedStorageScope.Application as a parameter to the GetStore method, you only limit the scope to the current application, not to its users. If you specify IsolatedStorageScope.User as a parameter to the GetStore method, you only limit the scope to the current user, not to the current application domain and its users. The GetUserStoreForAssembly method retrieves an isolated storage area that is isolated by user, but not by application domain. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Compress or decompress stream information in a .NET Framework application (Refer System.IO.Compression namespace), and improve the security of application data by using isolated

storage. (Refer System.IO.IsolatedStorage namespace) Isolated Storage MSDN Link: http://msdn2.microsoft.com/en-us/library/bdts8hk0(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-122

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code to send e-mail from your application (line numbers are for reference only): 01: void SendMessage(MailMessage message, string host) 02: { 03: SmtpClient client = new SmtpClient(host); 04: try 05: { 06: client.Send(message); 07: } 08: catch (SmtpFailedRecipientsException ex) 09: { 10: for (int i = 0; i < ex.InnerExceptions.Length; i++) 11: { 12: 13: } 14: } 15: } The parameter MailMessage represents an e-mail message and the parameter host contains the address of a Simple Mail Transfer Protocol (SMTP) server. Occasionally this code will encounter an SMTP error 450 (mailbox busy). When that happens, an attempt should be made to resend the mail message after five seconds. If any other SMTP error is encountered, an error should be logged in the event log. You decide to add additional code at line 12 to determine whether error 450 occurred. You need to write an expression that allows you to find the specific SMTP error returned by the SMTP server. Which code segment should you use? 1. if(ex.InnerExceptions[i].Message==450) 2. if(ex.InnerExceptions[i].StatusCode==450) <Correct> 3. if(ex.InnerExceptions[i].GetBaseException ==450) 4. if(ex.InnerExceptions[i].Data==450) Explanation : The StatusCode property of the SmtpFailedRecipientException class returns an enumeration of type SmtpStatusCode. This value gets the error code returned by the SMTP server. You should therefore use the following expression: ex.InnerExceptions[i].StatusCode == 450 or use the enumeration: ex.InnerExceptions(i).StatusCode == SmtpStatusCode.MailboxBusy The Message property of the SmtpFailedRecipientException class returns a descriptive message about the error. It does not give you specific information of the error returned by the SMTP server. The Data property of the SmtpFailedRecipientException class returns a set of user-defined values corresponding to the exception. In this scenario, you need a value returned by the server instead of a user-defined value. The GetBaseException method returns the exception that was the originating cause of one or more exceptions. It returns an Exception object, not a status code. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application

Sub Objective(s): Send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery from a .NET Framework application. (Refer System.Net.Mail namespace) SmtpFailedRecipientException Members MSDN Link: http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpfailedrecipientexception_members(vs.8 0).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-019

____________________________________________________________________________________________________________________ You are writing a program that includes the following class: [Serializable()] public class Manager { //Class implementation } You need to customize how the class is deserialized. At minimum, what changes must you make to the code? 1. [Serializable()] public class Manager : ISerializationSurrogate { //Class implementation protected Manager (SerializationInfo info, StreamingContext context) { //implementation } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { //implementation } } 2. [Serializable()] public class Manager : ISerializable { //Class implementation protected Manager (SerializationInfo info, StreamingContext context) { //implementation } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { //implementation } } <Correct> 3. [Serializable()] public class Manager : ISerializable { //Class implementation public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { //implementation } } 4. [Serializable()] public class Manager : ISerializationSurrogate { //Class implementation protected Manager (SerializationInfo info, StreamingContext context) { //implementation } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { //implementation } public virtual void SetObjectData(SerializationInfo info, StreamingContext context) { //implementation } } Explanation :

You should use the following code: [Serializable()] public class Manager : ISerializable { //Class implementation protected Manager (SerializationInfo info, StreamingContext context) { //implementation } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { //implementation } } To provide customized serialization, a class needs to implement the ISerializable interface. Doing so requires that you implement the GetObjectData method, which allows you to manipulate the data in the SerializationInfo object. You must also implement a special constructor, which will be called during deserialization to create the object from the data in SerializationInfo. You should not use the following code: [Serializable()] public class Manager : ISerializable { //Class implementation public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { //implementation } } If you do not implement a constructor that accepts a SerializationInfo object and a StreamingContext object, the object will not be instantiated. You should not implement ISerializationSurrogate. You implement the ISerializationSurrogate interface when you need to create an object that can serialize and deserialize another object. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Serialize or deserialize an object or an object graph by using runtime serialization techniques. (Refer System.Runtime.Serialization namespace) Custom Serialization MSDN Link: http://msdn2.microsoft.com/en-us/library/aa719875(VS.71).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-007

____________________________________________________________________________________________________________________ You are writing an application that reads the Application event log. The application needs to display only the Error events generated by the "MyApp" source. What code should you use? 1. EventLog evtLog = new EventLog("Application", "."); EventLogEntryCollection logEntryCol = evtLog.Entries; int i; for (i=0; i< logEntryCol.Count; i++) { EventLogEntry evtEntry = logEntryCol[i]; if (evtEntry.Source == "MyApp" && evtEntry.EntryType == EventLogEntryType.Error) { Console.WriteLine(evEntry.TimeGenerated + ": " + evtEntry.Message); } } <Correct> 2. EventLog evtLog = EventLog.CreateEventSource("MyApp", Application); EventLogEntryCollection logEntryCol = evnLogEntries; int i; for (i=0; i< logEntryCol.Count; i++) { EventLogEntry evtEntry = logEntryCol[i]; if (evtEntry.EntryType == EventLogEntryType.Error) { Console.WriteLine(evEntry.TimeGenerated + ": " + evtEntry.Message); } } 3. EventLog evtLog = new EventLog("Application", "."); EventLogEntryCollection logEntryCol = evtLog.GetEntries("MyApp"); int i; for (i=0; i< logEntryCol.Count; i++) { EventLogEntry evtEntry = logEntryCol[i]; if (evtEntry.EntryType == EventLogEntryType.Error) { Console.WriteLine(evEntry.TimeGenerated + ": " + evtEntry.Message); } } 4. EventLog evtLog = new EventLog("Application", "MyApp"); EventLogEntryCollection logEntryCol = evtLog.Entries; int i; for (i=0; i< logEntryCol.Count; i++) { EventLogEntry evtEntry = logEntryCol[i]; if (evtEntry.EntryType == EventLogEntryType.Error) { Console.WriteLine(evEntry.TimeGenerated + ": " + evtEntry.Message); } } Explanation : You should use the following code: EventLog evtLog = new EventLog("Application", "."); EventLogEntryCollection logEntryCol = evtLog.Entries; int i; for (i=0; i< logEntryCol.Count; i++) { EventLogEntry evtEntry = logEntryCol[i]; if (evtEntry.Source == "MyApp" && evtEntry.EntryType == EventLogEntryType.Error)

{ Console.WriteLine(evEntry.TimeGenerated + ": " + evtEntry.Message); } } The EventLog constructor takes the name of the log and the name of the machine as arguments. Using a "." as the machine name specifies that the log on the local machine should be used. The Entries property returns an object of type EventLogEntryCollection that contains all the entries in the log. To display information about Error events generated by MyApp, iterate through the collection and check the values of each entry using an If statement. The Source property stores the event's source and the EventType property stores the event type. You should not use the code: EventLog evtLog = EventLog.CreateEventSource("MyApp", Application); EventLogEntryCollection logEntryCol = evnLogEntries; int i; for (i=0; i< logEntryCol.Count; i++) { EventLogEntry evtEntry = logEntryCol[i]; if (evtEntry.EntryType == EventLogEntryType.Error) { Console.WriteLine(evEntry.TimeGenerated + ": " + evtEntry.Message); } } The CreateEventSource method is used when writing events, not when reading events. You should not use the code: EventLog evtLog = new EventLog("Application", "."); EventLogEntryCollection logEntryCol = evtLog.GetEntries("MyApp"); int i; for (i=0; i< logEntryCol.Count; i++) { EventLogEntry evtEntry = logEntryCol[i]; if (evtEntry.EntryType == EventLogEntryType.Error) { Console.WriteLine(evEntry.TimeGenerated + ": " + evtEntry.Message); } } The String argument passed to GetEntries is the name of the computer where the log is stored, not the source. You should not use the code: EventLog evtLog = new EventLog("Application", "MyApp"); EventLogEntryCollection logEntryCol = evtLog.Entries; int i; for (i=0; i< logEntryCol.Count; i++) { EventLogEntry evtEntry = logEntryCol[i]; if (evtEntry.EntryType == EventLogEntryType.Error) { Console.WriteLine(evEntry.TimeGenerated + ": " + evtEntry.Message); } } The second string passed to the EventLog constructor is the name of the computer, not the name of the source. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Manage an event log by using the System.Diagnostics namespace. EventLogEntry Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.diagnostics.eventlogentry.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-100

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following class in your application: [Serializable()] public class MyClass { public string item1; private string item2; [NonSerialized()] public string item3; [OptionalField()] public string item4; public MyClass() { item1 = "10"; item2 = "20"; item3 = "30"; item4 = "40"; } } You create an object of the MyClass type in your application and write the following code to serialize its contents: MyClass myObject = new MyClass(); XmlSerializer mySerializer = new XmlSerializer(typeof(MyClass)); StreamWriter myWriter = new StreamWriter("myFile.xml"); mySerializer.Serialize(myWriter, myObject); myWriter.Close(); What fields of the myObject object will be written to the myFile.xml file? 1. item1 item2 item3 item4 2. item1 item2 item4 3. item1 4. item1 item3 item4 <Correct> Explanation : The XmlSerializer object serializes all the public fields of a class. When the code is executed, it will serialize the following fields in the myFile.xml file: item1 item3 item4 The NonSerialized attribute and the OptionalField attribute are only used for runtime serialization by using the functionality in the System.Runtime.Serialization namespace. Serialization by using the XmlSerializer class is not affected by the use of these attributes. Objective: Implementing serialization and input/output functionality in a .NET Framework application

Sub Objective(s): Control the serialization of an object into XML format by using the System.Xml.Serialization namespace. Introducing XML Serialization MSDN Link: http://msdn2.microsoft.com/en-us/library/182eeyhh(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-145

____________________________________________________________________________________________________________________ You are developing an application by using the .NET Framework. You use the SslStream class to exchange messages between the client and server by using the Secure Sockets Layer (SSL) security protocol. Before transmitting data, you must check if the algorithm used by the stream meets your requirements for data integrity. Which property of the SslStream class should you use? 1. CipherAlgorithm 2. SslProtocol 3. HashAlgorithm <Correct>

4. KeyExchangeAlgorithm Explanation : You should use the HashAlgorithm property. The HashAlgorithm property specifies the message integrity algorithm used by the SslStream class. You should not use the CipherAlgorithm property because this property specifies the algorithm used for ensuring the confidentiality of the message. You should not use the KeyExchangeAlgorithm property because this property specifies the key exchange algorithm used by the SslStream class. You should not use the SslProtocol property because this property specifies the SSL protocol used for authentication. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement a custom authentication scheme by using the System.Security.Authentication classes. (Refer System.Security.Authentication namespace) SslStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.net.security.sslstream(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-065

____________________________________________________________________________________________________________________ You are developing a Windows service application by using the .NET Framework. The application has three distinct Windows services. You create a custom installation class named MyAppInstaller that derives from the Installer class. Within this class you customize installation for each Windows service by using the ServiceInstaller objects and add them to the Installer collection as shown below: Installers.Add(serviceInstaller1); Installers.Add(serviceInstaller2); Installers.Add(serviceInstaller3); The class is compiled and stored in MyAppInstaller.dll. You must programmatically access and install the Windows services in the MyAppInstaller.dll file. Which class should you use? 1. AssemblyInstaller <Correct>

2. ManagedInstallerClass 3. InstallContext 4. ComponentInstaller Explanation : You should use the AssemblyInstaller class in this case because the AssemblyInstaller class can load the available installers in an assembly and install them. You should not use the ComponentInstaller class because the ComponentInstaller class is an abstract class that can be used as a base class when you need to copy properties from a component to an installer. You should not use the ManagedInstallerClass class because the ManagedInstallerClass class is for the .NET Framework's internal use. You should not use this class directly from your code. You should not use the InstallContext class because the InstallContext class by itself cannot help you install the installers in an assembly. The InstallContext class only helps you provide the current information related to installation, which can be used by the installation program to successfully install an application. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Create a custom Microsoft Windows Installer for .NET Framework components by using the System.Configuration.Install namespace, and configure .NET Framework applications by using configuration files, environment variables, and the .NET Framework Configuration tool (Mscorcfg.msc). AssemblyInstaller Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.configuration.install.assemblyinstaller(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-066

____________________________________________________________________________________________________________________ You are developing a resource management utility by using the .NET Framework. You write the following code as part of your program: DirectoryInfo dirInfo = new DirectoryInfo(@"c:\dir1"); dirInfo.MoveTo(@"c:\dir2"); When you run this program, both c:\dir1 and c:\dir2 already exist. The code has the required permissions to work with c:\dir1 and c:\dir2. What would be the outcome of running this code? 1. The directory c:\dir1 will be moved inside c:\dir2 and become c:\dir2\dir1. 2. The code will throw an ArgumentException. 3. The directory c:\dir1 will be renamed to c:\dir2. 4. The code will throw an IOException. <Correct> Explanation : The code will throw an IOException. The DirectoryInfo.MoveTo method throws an IOException if the target directory already exists. The ArgumentException is only thrown when the target directory is an empty string. The directory will not be renamed to c:\dir2. The directory is only renamed if the target directory does not already exist. The directory c:\dir1 will not be moved inside c:\dir2. To accomplish this, you should have specified c:\dir2\dir1 as the target directory name. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Access files and folders by using the File System classes. (Refer System.IO namespace) DirectoryInfo.MoveTo Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.directoryinfo.moveto(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-149

____________________________________________________________________________________________________________________ You are creating a code group that will contain all classes related to an application. The classes are all strong-named and are signed with a certificate that identifies the publisher. You want to create a code group that will not need to be modified if any of the files in the application are updated. What evidence should you use? 1. Site 2. Hash 3. Publisher 4. StrongName Explanation : You should use Publisher as the evidence for the code group. The Publisher class uses the X.509v3 digital signature as evidence for proving the code's identity. The publisher will not change if a file is updated. However, it will help to identify the source of the code as trusted. You should not use a hash. A hash value changes if even one bit of a file changes. Therefore, you would need to modify the code access policy whenever a file was updated. You should not use a StrongName. The StrongName depends on a name, digital signature, and version number. If any one of these change, the policy would need to be updated. You should not use a Site. Using a Site as evidence is appropriate if the code is being downloaded from a specific Web site, but not always from the same Uniform Resource Locator (URL). There is no requirement for downloading code in this scenario. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control code privileges by using System.Security.Policy classes. (Refer System.Security.Policy namespace) Publisher Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.policy.publisher(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-007

____________________________________________________________________________________________________________________ You are developing a graphics application by using the .NET Framework. You write a Point class with two integer fields as shown below: class Point { static int x, y; public Point(int x1, int y1) { x = x1; y = y1; } } You need to write a static method named GetPointPosition that provides read access to the two integer fields in the class. You must permit read access to multiple threads at the same time. Your solution must result in fast response time and high throughput. How should you write the GetPointPosition method? 1. public void GetPointPosition(ref int x1, ref int y1) { Monitor.Enter(this); try { x1 =x; y1 =y; } finally { Monitor.Exit(this); } } 2. static ReaderWriterLock rwlock = new ReaderWriterLock(); public static void GetPointPosition(ref int x1, ref int y1) { rwlock.AcquireReaderLock(Timeout.Infinite); try { x1 = x; y1 = y; } finally { rwlock.ReleaseReaderLock(); } } <Correct> 3. public void GetPointPosition(ref int x1, ref int y1) { lock (this) { x1 =x; y1 =y; } } 4. public void GetPointPosition(ref int x1, ref int y1) { bool lockAcquired; lockAcquired = Monitor.TryEnter(this, 2000); if (lockAcquired)

{ try { x1 = x; y1 = y; } finally { Monitor.Exit(this); } } } Explanation : The ReaderWriterLock class allows you to design a synchronization scheme that employs shared locks together with exclusive locks. This makes it possible to provide access to multiple reader threads at the same time, which effectively reduces the level of blocking. This results in fast response time and high throughput. Other solutions use an exclusive locking scheme that does not consider whether threads are readers or writers. Unfortunately, this is not the best choice in scenarios in which there are many more read operations than write operations. Using monitors in such a scenario can unnecessarily degrade your response times and overall application throughput. Also, you should use Monitor only with reference variables, not with value variables. Therefore, you should consider using the ReaderWriterLock class to assist with your synchronization. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Develop multithreaded .NET Framework applications. (Refer System.Threading namespace) ReaderWriterLock Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.threading.readerwriterlock(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-049

____________________________________________________________________________________________________________________ You are developing a class library by using the .NET Framework. You develop a class that will provide advanced graphical functionality. This class will be used by several client applications. You create several unmanaged objects in the class. You want to provide the developers of the client applications the ability to explicitly release the resources used by your class. What should you do? 1. Invoke the GC.SuppressFinalize method in the class. 2. Invoke the GC.RemoveMemoryPressure method in the class. 3. Implement a destructor for the class. 4. Implement a Dispose method in the class. <Correct>

Explanation : You should implement a Dispose method in the class to allow client application developers to explicitly release the resources used by your class. Within the Dispose method, you can write code to release the resources used by the unmanaged objects. You do not need to provide code to release managed objects because the garbage collector releases them automatically. Implementing a destructor for the class is not a solution because a destructor cannot be explicitly invoked by the developers of the client applications. A class destructor is implicitly invoked by the garbage collector during finalization. Calling the GC.SuppressFinalize method is not the correct solution because when this method is called, the common language runtime does not call the finalizer for the object. Calling GC.RemoveMemoryPressure method is not the correct solution because this method tells the common language runtime that unmanaged memory has been released and does not need to be taken into account when scheduling garbage collection. Objective: Developing applications that use system types and collections Sub Objective(s): Implement .NET Framework interfaces to cause components to comply with standard contracts. (Refer System namespace) IDisposable Interface MSDN Link: http://msdn2.microsoft.com/en-us/library/system.idisposable(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-139

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You create a class named ScrapData. You must configure the ScrapData class and limit its access to only the code originating from a specific Web site, www.measureup.com, and any of its sub-domains, for example first.measureup.com and second.measureup.com. The Web sites will be accessed using the HTTP, HTTPS, and FTP protocols. You need to configure code access permissions for the ScrapData class. Which class should you use? 1. SiteIdentityPermission 2. PublisherIdentityPermission 3. ZoneIdentityPermission 4. UrlIdentityPermission Explanation : You should use the SiteIdentityPermission class to configure code access permissions for callers from a specific Web site. It is incorrect to use the UrlIdentityPermission class because this class is used to configure access permissions for a Uniform Resource Locator (URL). A URL contains the complete path to a resource including the file name, for example: http://www.measureup.com/myfile.html. In this case, you want to configure code access permissions for the full Web site instead of specific files. It is incorrect to use the ZoneIdentityPermission class. The ZoneIdentityPermission class is used to configure permissions for the zone where the code originates. For example, the Local Machine Zone, the Intranet Zone, or the Internet Zone. The Web site in this case belongs to the Internet Zone, but the Internet Zone also contains many other Web sites. It is incorrect to use the PublisherIdentityPermission class. The PublisherIdentityPermission class is used to configure permissions based on the identity of the software publisher. In this case, information about the software publisher identity is not available. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control permissions for resources by using the System.Security.Permission classes. (Refer System.Security.Permission namespace) References : SiteIdentityPermission Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.siteidentitypermission(vs.80) .aspx UrlIdentityPermission Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.urlidentitypermission(vs.80). aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-034

____________________________________________________________________________________________________________________ You are developing an enterprise application based on the .NET Framework. The application allows its users to send e-mail messages. Your application must allow the users to send HTML-based emails. The users should also be able to use the HTML <img> tag to embed images in the HTML document. The images are not externally hosted. Instead, the images must be sent as part of the e-mail message. Which .NET Framework class should you use? 1. AlternateView 2. Attachment 3. LinkedResource <Correct>

4. AttachmentCollection Explanation : You should use the LinkedResource class to embed external resources in an e-mail attachment, such as an image in an HTML attachment. Using the Attachment class is incorrect because the Attachment class only allows you to send files as an attachment. It does not provide any support for embedding images within an HTML document. Using the AlternativeView class is incorrect. Although you can use the AlternateView class to specify copies of an e-mail message in different formats (text, HTML, etc.), the AlternateView class by itself cannot embed images in the HTML document. Using the AttachmentCollection class is incorrect. You use the AttachmentCollection class to access members of the Attachment or AlternateView class. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery from a .NET Framework application. (Refer System.Net.Mail namespace) LinkedResource Class MSDN Link: http://msdn2.microsoft.com/en-us/library/ms144655(en-US,VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-134

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code in your application (line numbers are for reference only): 01: public int ProcCount() 02: { 03: EnvironmentPermission envPerm = new EnvironmentPermission( 04: EnvironmentPermissionAccess.Read, 05: "NUMBER_OF_PROCESSORS"); 06: 07: return Environment.ProcessorCount; 08: } The method ProcCount returns the number of processors on the computer running the code. The implementation of the ProcCount method is completely transparent to the callers of the methods. The assembly containing the ProcCount method has been granted permission to access environment variables. The callers to the code may not have permission to access environment variables. You want classes in other assemblies to successfully call the ProcCount method. You must write additional code on line 06 to override the security check. Any code that you write must not affect the permissions that your code may already have. Which code segment should you use? 1. envPerm.PermitOnly(); 2. encPerm.Deny(); 3. envPerm.Demand(); 4. envPerm.Assert(); <Correct>

Explanation : You should use the following code segment: envPerm.Assert(); The Assert method allows your code (and any code that you call) to perform actions that your code has permission to perform but its callers may not have permission to perform. This means that when you call Assert, the restriction that all callers in the calling chain must have permission to perform the action is ignored. You should not use the Demand method because the Demand method requires that all the code in the chain of method calls must have the permission to perform the specified action. In this case, the callers to the code may not have permission to access environment variables. Calling the Demand method in such a case will cause a SecurityException exception to be thrown. You should not use the Deny method because using the Deny method on a permission P will explicitly cause the permission P to be denied. In this case, you want to make sure that the permission is applied to the code. You should not use the PermitOnly method because using the PermitOnly method on a permission P will be the same as calling Deny on all permissions other than the permission P. One of the requirements in this case is to not affect any other permission that the code may already have. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Implement code access security to improve the security of a .NET Framework application. Refer

System.Security namespace) References : CodeAccessPermission.PermitOnly Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.codeaccesspermission.permitonly(vs.80).aspx Using the Assert Method MSDN Link: http://msdn2.microsoft.com/en-us/library/91wteedy(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-045

____________________________________________________________________________________________________________________ You write the following code in your .NET Framework application: class CustomCollection { private int m_items; public int Items { get{return m_items;} set{m_items = value;} } } You need to enhance the debugging capabilities of your application. You must configure the class in such as a way that the value of the Items property is shown in the Value column when you view an instance of the CustomCollection class in the debugger while you are debugging the application. (See exhibit.) How should you modify class? 1. [DebuggerDisplay(Items)] class CustomCollection { private int m_items; public int Items { get{return m_items;} set{m_items = value;} } } 2. [DebuggerBrowsable(Items)] class CustomCollection { private int m_items; public int Items { get{return m_items;} set{m_items = value;} } } 3. [DebuggerDisplay("Items={Items}")] class CustomCollection { private int m_items; public int Items { get{return m_items;} set{m_items = value;} } } <Correct> 4. class CustomCollection { private int m_items; [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)] public int Items { get{return m_items;} set{m_items = value;} } } Explanation : You should add the following attribute to the class: [DebuggerDisplay("Items={Items}")]

The DebuggerDisplayAttribute accepts a single argument of type String that specifies the text that should display in the Value column of the Autos and Locals windows of the debugger. You can use a set of curly braces ({ }) within the string to cause the string to include the results of an expression, such as calling the Items property. You should not add the following attribute to the class: [DebuggerDisplay(Items)] The DebuggerDisplayAttribute requires a String argument, not an expression that returns an Integer. You should not add the following attribute to the Items property: [DebuggerBrowsable (DebuggerBrowsableState.Collapsed)] The DebuggerBrowsableAttribute determines how a property or field should be shown in the debugger. However, it does not meet the requirements. You should not add the following attribute to the class: [DebuggerBrowsable(Items)] The DebuggerBrowsableAttribute is applied to a property or field, not to a class. Also, it accepts a value of the DebuggerBrowsableState enumeration as its only parameter, not an Integer. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Debug and trace a .NET Framework application by using the System.Diagnostics namespace Enhancing Debugging with the Debugger Display Attributes MSDN Link: http://msdn2.microsoft.com/en-us/library/ms228992(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-101

____________________________________________________________________________________________________________________ You are developing a console application by using the .NET Framework. You create the following class in your program: [Serializable()] public class MyClass { public string item1; private string item2; [NonSerialized()] public string item3; [OptionalField()] public string item4; public MyClass() { item1 = "10"; item2 = "20"; item3 = "30"; item4 = "40"; } [OnSerializing()] internal void OnSerializingMethod(StreamingContext context) { item2 = "25"; } [OnSerialized()] internal void OnSerializedMethod(StreamingContext context) { item2 = "30"; } [OnDeserializing()] internal void OnDeserializingMethod(StreamingContext context) { item3 = "35"; } [OnDeserialized()] internal void OnDeserializedMethod(StreamingContext context) { item4 = "50"; } public void Print() { Console.WriteLine(item1); Console.WriteLine(item2); Console.WriteLine(item3); Console.WriteLine(item4); } } You need to serialize the object to disk and then deserialize and print the object data. You write the following code: MyClass myObject = new MyClass(); Stream stream = File.Open("data.xml", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, myObject); stream.Close(); stream = File.OpenRead("data.xml");

MyClass newObject = (MyClass) formatter.Deserialize(stream); newObject.Print(); What will be the output generated by this code segment? 1. 10 30 35 50 2. 10 30 35 40 3. 10 25 35 50 <Correct> 4. 10 30 30 50 Explanation : The program will print the following output: 10 25 35 50 The various serialization attributes will affect the initial values of the fields of the myObject object. The value of item1 remains unchanged. The value of item2 is affected by both the OnSerializing and OnSerialized attributes. However, the method marked with the OnSerialized attribute is executed after the serialization, so any changes done here are not persisted to the disk. Because item3 is marked with NonSerialized attribute, its value is not persisted to disk. When the object of MyClass is deserialized, the value of item3 is set by the method marked with the OnDeserializing attribute. The value of item4 is set to 50 by the method marked with the OnDeserialized attribute when the deserialization is completed. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Serialize or deserialize an object or an object graph by using runtime serialization techniques. (Refer System.Runtime.Serialization namespace) References : OnSerializedAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.onserializedattribute(vs.80) .aspx OnSerializingAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute(vs.80 ).aspx OnDeserializedAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.ondeserializedattribute(vs.8 0).aspx

OnDeserializingAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute(vs. 80).aspx OptionalFieldAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.optionalfieldattribute(vs.80 ).aspx SerializableAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.serializableattribute(VS.80).aspx NonSerializedAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.nonserializedattribute(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-019

____________________________________________________________________________________________________________________ You need to store a list of names and e-mail addresses in your .NET Framework application. The number of elements in the list is unknown and may vary at runtime. The list will be used for a mail-merge application and does not need to be sorted. You need to choose a data structure that provides the best performance as you work with your data. What should you do? 1. Use OrderedDictionary. 2. Use HashTable. 3. Use ListDictionary. 4. Use HybridDictionary. <Correct>

Explanation : The HybridDictionary class is the best choice when you need to store a collection of key/value pairs, but you do not know the number of elements you need to store in the collection. The HybridDictionary class works like a ListDictionary for collections with ten or fewer elements and like a Hashtable for larger collections. This flexibility means that the class can offer better performance than either the ListDictionary or the Hashtable for a scenario in which the number of elements in the collection varies. The OrderedDictionary class is suited for use when a collection of key/value pairs must be sorted based on the key/index. In this scenario, use of OrderedDictionary class does not provide any advantage. Objective: Developing applications that use system types and collections Sub Objective(s): Manage data in a .NET Framework application by using specialized collections (Refer System.Collections.Specialized namespace) HybridDictionary Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.specialized.hybriddictionary(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-102

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code: [Serializable()] public class Square { double side; [NonSerialized()] public double area; public Square(double side) { this.side = side; area = side * side; } public void Print() { Console.WriteLine(area); } } You also write code to serialize the class to a disk file. When you deserialize the class and print the value of the area field by using the Print method, you find that the value of the area field is printed incorrectly. You need to make sure that the value of the area field is correctly calculated when the class is deserialized from the disk file. What should you do? (Each correct answer presents a complete solution. Choose two.) 1. Modify the class to implement the IDeserializationCallback interface. Add the following method to the class: void IDeserializationCallback.OnDeserialization(object sender) { area = side * side; } <Correct> 2. Add the following method to the class: [OnDeserialized()] internal void OnDeserializedMethod(StreamingContext context) { area = side * side; } <Correct> 3. Add the following method to the class: [OnSerialized()] internal void OnSerializedMethod(StreamingContext context) { area = side * side; } 4. Modify the class to implement the ISerializable interface. Add the following method to the class: void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {

area = side * side; } 5. Add the following method to the class: [OnSerializing()] internal void OnSerializingMethod(StreamingContext context) { area = side * side; } 6. Add the following method to the class: [OnDeserializing()] internal void OnDeserializingMethod(StreamingContext context) { area = side * side; } Explanation : When deserialization occurs, the constructor of the class is not called. Therefore, any calculation that is part of the constructor must be performed by using different techniques. To correctly calculate the value of the area field after deserialization, you can add the following method to the class: [OnDeserialized()] internal void OnDeserializedMethod(StreamingContext context) { area = side * side; } Because of the OnDeserialized attribute, OnDeserializedMethod will be executed after the deserialization is complete and restore the value of the area field. An alternate answer is to modify the class to implement the IDeserializationCallback interface and add the following method to the class: void IDeserializationCallback.OnDeserialization(object sender) { area = side * side; } The IDeserializationCallback.OnDeserialization method is automatically called by the runtime at the time of deserialization to correctly calculate the value of the area field. Adding the OnDeserializing attribute to OnDeserializingMethod is not the correct solution because this method is called before the deserialization begins. At this time, the value of the side field is unknown and therefore the value of the area field cannot be correctly calculated. Adding the OnSerialized attribute or the OnSerializing attribute to OnSerializedMethod and OnSerializingMethod respectively is not going to help because these methods are executed only when the object is serialized to disk and not when it is deserialized back. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Serialize or deserialize an object or an object graph by using runtime serialization techniques. (Refer System.Runtime.Serialization namespace) Advanced Serialization: Format Your Way to Success with the .NET Framework Versions 1.1 and 2.0 MSDN Link: http://msdn.microsoft.com/msdnmag/issues/04/10/AdvancedSerialization

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-140

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You create a class named DataAccess. You must configure the DataAccess class to disallow access to the c:\cfg.dat file. You also want to restrict the access to c:\cfg.dat through a file system path or through a Universal Naming Convention (UNC) path or a mapped drive letter path. You must be able to access all other files on the c: drive of the computer running the program. Which attributes should you add to the class to limit the access to the c:\cfg.dat file? 1. [FileIOPermissionAttribute(SecurityAction.PermitOnly, All = @"C:\")] [FileIOPermissionAttribute(SecurityAction.Deny, All = @"C:\cfg.dat")] <Correct> 2. [FileIOPermissionAttribute(SecurityAction.RequestMinimum, All = @"C:\")] [FileIOPermissionAttribute(SecurityAction.RequestRefuse, All = @"C:\cfg.dat")] 3. [FileIOPermissionAttribute(SecurityAction.PermitOnly, All = @"C:\ ")] [FileIOPermissionAttribute(SecurityAction.RequestRefuse, All = @"C:\cfg.dat")] 4. [FileIOPermissionAttribute(SecurityAction.RequestRefuse, All = @"C:\cfg.dat")] [FileIOPermissionAttribute(SecurityAction.Deny, All = @"C:\cfg.dat")] Explanation : The correct answer is to use the following code statements to configure the DataAccess class: [FileIOPermissionAttribute(SecurityAction.PermitOnly, All = @"C:\")] [FileIOPermissionAttribute(SecurityAction.Deny, All = @"C:\cfg.dat")] The FileIOPermission attribute applies permissions only to the specified pathname. If the file is accessed by using a different path name such as \\Computer1\C$\cfg.dat, or by using a mapped drive such as x:\cfg.dat, the permissions do not apply. You can use a combination of PermitOnly and Deny to deny access to a specific resource as shown in the above code statements. The first line uses SecurityAction.PermitOnly to specify that the file access permissions are only available for path names starting with c:\. This eliminates access through a UNC path or a mapped drive. The second statement uses SecurityAction.Deny to specifically deny permissions to the c:\cfg.dat file. The RequestMinimum and RequestRefuse security actions can be applied only at the assembly level, not at the class level. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control permissions for resources by using the System.Security.Permission classes. (Refer System.Security.Permission namespace) References : FileIOPermissionAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.fileiopermissionattribute(vs. 80).aspx Using the Deny Method MSDN Link: http://msdn2.microsoft.com/en-us/library/hk3b9142(vs.80).aspx

SecurityAction Enumeration MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.permissions.securityaction(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-118

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. Your application contains the following code: byte[] plain; The byte array plain contains the data that must be protected. The length of data stored in the byte array plain is always a multiple of 16. Only the threads running under the current user context must be able to unprotect the data. The unprotected data will be stored in a different byte array. The original contents of the byte array plain must remain unmodified. The application will be executed on computers running Microsoft Windows XP or later operating systems. Which code segment should you use to protect the data? 1. ProtectedData.Protect(plain, null, DataProtectionScope.CurrentUser); 2. ProtectedData.Protect(plain, null, DataProtectionScope.LocalMachine); 3. ProtectedMemory.Protect(plain, MemoryProtectionScope.SameLogon); 4. ProtectedMemory.Protect(plain, MemoryProtectionScope.SameProcess); Explanation : You should use the following code segment to protect the data: ProtectedData.Protect(plain, null, DataProtectionScope.CurrentUser); The ProtectedData.Protect method returns a protected copy of the data in the byte array plain. The contents of the byte array plain remain unaffected. The DataProtectionScope.CurrentUser value specifies that the data is protected under the context of the current user. Only the threads running in the same user context will be able to unprotect the protected data. Using the DataProtectionScope.LocalMachine is incorrect because it allows any process (irrespective of the user context) running on the local computer to be able to unprotect the data. Using the ProtectedMemory.Protect method is incorrect because this method stores the protected data in the original copy of the byte array. This scenario requires that the contents of the byte array plain should remain unaffected. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Encrypt, decrypt, and hash data by using the System.Security.Cryptography classes. (Refer System.Security.Cryptography namespace) References : ProtectedData Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.security.cryptography.protecteddata(vs.80).aspx How to: Use Data Protection MSDN Link: http://msdn2.microsoft.com/en-us/library/ms229741(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-010

____________________________________________________________________________________________________________________ You are developing a .NET Framework application that uses the queue data structure. You need to create a solution that allows you to enumerate a queue's contents. The queue must only accept elements of type double. Which code should you use? 1. Queue q = new Queue(); q.Enqueue(12.5); q.Enqueue(20.6); foreach(double d in q) { //perform processing } 2. Queue q = new Queue(); double d; q.Contains(d.GetType()); q.Enqueue(12.5); q.Enqueue(20.6); foreach(double d in q) { //perform processing } 3. Queue q = new Queue(); double d; q.Contains(d); q.Enqueue(12.5); q.Enqueue(20.6); foreach(double d in q) { //perform processing } 4. Queue <double> q = new Queue<double>(); q.Enqueue(12.5); q.Enqueue(20.6); foreach(double d in q) { //perform processing } <Correct> Explanation : For type safety you should use the generic version of the Queue class. If you use the non-generic Queue class, you will be able to insert objects of any type in the queue. When you use the generic version, you can specify the type in the constructor by enclosing it between triangular brackets < >. The Contains method allows you to determine whether the queue contains a specific element. It is not used to limit the type of element that can be stored in the queue. Objective: Developing applications that use system types and collections Sub Objective(s): Improve type safety and application performance in a .NET Framework application by using generic collections. (Refer System.Collections.Generic namespace) Queue Generic Class MSDN Link: http://msdn2.microsoft.com/en-us/library/7977ey2c(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-123

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You need to use reflection to dynamically invoke a method that is a part of the GraphRep class in the UtilProc namespace. The code for the GraphRep class is stored in UtilProc.dll file. You run ILDASM on the UtilProc.dll file, and the results are shown in the exhibit. You write the following code (line numbers are for reference only): 01: Assembly assm = Assembly.LoadFrom("UtilProc.dll"); 02: Type graphRepType = assm.GetType("UtilProc.GraphRep"); What additional code should you write after line 02 to invoke the Draw method of the GraphRep class? 1. Object obj = Activator.CreateInstance(graphRepType); assm.EntryPoint.Invoke(obj, null); 2. graphRepType.InvokeMember("Draw", BindingFlags.InvokeMethod, null, graphRepType, null); 3. Object obj = Activator.CreateInstance(graphRepType); graphRepType.GetMethod("Draw").Invoke(obj, null); <Correct> 4. Object obj = Activator.CreateInstanceFrom("UtilProc.dll", "UtilProc.GraphRep"); graphRepType.InvokeMember("Draw", BindingFlags.InvokeMethod, null, obj, null); Explanation : You should write the following code for invoking the Draw method: Object obj = Activator.CreateInstance(graphRepType); graphRepType.GetMethod("Draw").Invoke(obj, null); This code creates an instance of the UtilProc.GraphRep type, gets a MethodInfo object through the GetMethod method, and calls the Invoke method of the MethodInfo object. The first parameter of the Invoke method is an instance of the object on which you want to invoke the method. The second parameter is the arguments that you want to pass to the method. The Draw method takes no arguments, so the second parameter is null. You should not use the EntryPoint property to get the MethodInfo object. The given assembly is a DLL file, and it does not have any entry point. The following code segment is incorrect because it will throw a TargetException: Object obj = Activator.CreateInstanceFrom("UtilProc.dll", "UtilProc.GraphRep"); graphRepType.InvokeMember("Draw", BindingFlags.InvokeMethod, null, obj, null); You must create an object instance from the graphRepType for the InvokeMember method to be successful. The following code segment is incorrect because you must create an instance of the UtilProc.GraphRep type before a method can be invoked on the class: graphRepType.InvokeMember("Draw", BindingFlags.InvokeMethod, null, graphRepType, null); Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s):

Implement reflection functionality in a .NET Framework application (refer System.Reflection namespace), and create metadata, Microsoft intermediate language (MSIL), and a PE file by using the System.Reflection.Emit namespace. References : Activator Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.activator(vs.80).aspx Type Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.type(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-030

____________________________________________________________________________________________________________________ You are developing a logging module for a large application by using the .NET Framework. You need to append logging information to a file named application.log. This log file is opened when the application is started and is closed only when the application is closed. However, you append text several times to the file during a session. You must minimize overhead to the logging process to ensure maximum performance. Which code segment should you use to create the log file? 1. FileInfo fi = new FileInfo(@"c:\application.log"); StreamWriter sw = fi.AppendText(); <Correct> 2. StreamWriter sw = File.CreateText(@"c:\application.log"); 3. FileInfo fi = new FileInfo(@"c:\application.log"); FileStream fs = fi.Open(FileMode.Append); 4. StreamWriter sw = File.AppendText(@"c:\application.log"); Explanation : If you are going to reuse an object several times, you should use the instance method of the FileInfo class instead of the corresponding static methods of the File class, because a security check will not always be necessary. This will minimize any overhead and improve the performance of the application. You should use the following code to append data to the log file: FileInfo fi = new FileInfo(@"c:\application.log"); StreamWriter sw = fi.AppendText(); Using the following code is incorrect because you should use FileMode.Append only in conjunction with FileAccess.Write. FileInfo fi = new FileInfo(@"c:\application.log"); FileStream fs = fi.Open(FileMode.Append); Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Access files and folders by using the File System classes. (Refer System.IO namespace) FileInfo Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.fileinfo(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-146

____________________________________________________________________________________________________________________ You develop a .NET Framework application. This application is deployed throughout the company on all workstations. All workstations are networked and are part of a Microsoft Windows domain. Your application requires certain permissions in order to run. As a domain administrator, you configure the enterprise policy to grant the required permissions to the application. This application may be part of more than one code group. You must make sure that your application receives sufficient permissions to run at all times. You must override any policy changes made by end users that lower the permissions required by your application to run. What should you do? 1. Apply the LevelFinal attribute to the application's code group on the user policy level. 2. Apply the LevelFinal attribute to the application's code group on the enterprise policy level. <Correct> 3. Apply the Exclusive attribute to the application's code group on the enterprise policy level. 4. Apply the Exclusive attribute to the application's code group on the user policy level. Explanation : You should apply the LevelFinal attribute to the application's code group on the enterprise level. Policy is applied in the following order: enterprise policy, machine policy, user policy, and application domain policy. If you apply the LevelFinal attribute to the application's code group on the enterprise policy level machine and user-level policy are not applied to code that belongs to that code group. You should not apply the LevelFinal attribute to the application's code group on the user policy level because you do not want the end users to alter the security setting and restrict the application's execution. You should not apply the Exclusive attribute to the application's code group on the enterprise policy level or the user policy level because the runtime never grants more permissions than what is associated with the code group marked with Exclusive attribute. In this case, you want to make sure that permissions are never lowered below what is required for the application to run. Objective: Improving the security of .NET Framework applications by using the .NET Framework 2.0 security features Sub Objective(s): Control code privileges by using System.Security.Policy classes. (Refer System.Security.Policy namespace) References : Security Policy Management MSDN Link: http://msdn2.microsoft.com/en-us/library/c1k0eed6(vs.80).aspx Code Group Attributes MSDN Link: http://msdn2.microsoft.com/en-us/library/3wxtc9hf(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-012

____________________________________________________________________________________________________________________ You are developing a Windows-based geographical mapping application by using the .NET Framework. Each time you load a plug-in, you create a separate application domain. You want to specify a list of directories that are searched for private assemblies. You must include the application's base directory as part of your search. You need to configure an application domain to meet the requirements. What should you do? 1. Use the AppDomain.BaseDirectory property. 2. Use the AppDomain.DynamicDirectory property. 3. Use the AppDomainSetup.PrivateBinPath property. <Correct> 4. Use the AppDomainSetup.PrivateBinPathProbe property. Explanation : The AppDomainSetup.PrivateBinPath property specifies a list of directories under the application base directory that are probed for private assemblies. You must set this property to specify the locations that should be searched for a private assembly. If the AppDomainSetUp.PrivateBinPathProbe property is set to a non-empty value, it excludes ApplicationBase from the search path for the application and searches only PrivateBinPath. If this property is not set, the ApplicationBase path is included when searching for private assemblies. The AppDomain.BaseDirectory property only specifies the base directory for the application domain. It does not specify all the different locations that should be searched for a private assembly. The AppDomain.DynamicDirectory property gets the directory that the assembly resolver uses to probe for dynamically created assemblies. This is a read-only property and cannot be explicitly set. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Create a unit of isolation for common language runtime within a .NET Framework application by using application domains. (Refer System namespace) References : Using Application Domains MSDN Link: http://msdn2.microsoft.com/en-us/library/yb506139(vs.80).aspx AppDomainSetup Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.appdomainsetup(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-031

____________________________________________________________________________________________________________________ You are developing a Windows Forms application by using the .NET Framework. This application will be used by people in several countries. The application needs to fully support customization of the user interface based on the user's preferences. You need to write code that compares the name of two files. The file names are stored in variables named fileName1 and fileName2 respectively. The comparison should be case insensitive and should produce the same result regardless of the user's regional settings. Which code segment should you use? 1. String.Equals(fileName1, fileName2); 2. String.Compare(fileName1, fileName2, true, CultureInfo.InvariantCulture); 3. String.Compare(fileName1, fileName2, false, CultureInfo.CurrentCulture); 4. fileName1.CompareTo(fileName2); Explanation : You should pass CultureInfo.InvariantCulture to the Compare method. The default behavior of the String.Compare method is to perform case-sensitive comparisons using the rules of the current culture. The InvariantCulture setting takes language into account, but not regional differences. For example, the same rules would be used for Great Britain English as for United States English. You should not use the following code because it will perform a comparison that is sensitive to culture: String.Compare(fileName1, fileName2, false, CultureInfo.CurrentCulture); You should not use the CompareTo method because it performs a case-sensitive and culture-sensitive comparison. You should not use the Equals method because it performs a case-sensitive, culture insensitive comparison. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) References : Performing Culture-Insensitive String Comparisons MSDN Link: http://msdn2.microsoft.com/en-us/library/885e1sy1(vs.80).aspx String.Compare method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.string.compare(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-020

____________________________________________________________________________________________________________________ You are creating a Windows application by using the .NET Framework. This application must be capable of manipulating graphic files in GIF, JPG, and PNG formats. You need to choose an appropriate data type to store graphic files. Your solution must require the least amount of code. What should you do? 1. Use the Metafile class. 2. Use the Bitmap class. 3. Use the Icon class. 4. Use the Image class. Explanation : You should use the Bitmap class in this case. The Bitmap class is an implementation of the Image abstract class that is capable of working with several types of image formats, including GIF, JPG, and PNG formats. Using the Image class is incorrect because the Image class is an abstract class, and you must implement the functionality which will require additional programming efforts. Using the Icon class is incorrect because the Icon class only allows you to work with small bitmap images that can be used as Windows icons. Using the Metafile class is incorrect because the Metafile class provides specific functionality for recording a sequence of graphic operations. It does not allow you to manipulate the images in different formats. Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Enhance the user interface of a .NET Framework application by using the System.Drawing namespace. Bitmap Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.drawing.bitmap(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-061

____________________________________________________________________________________________________________________ You are maintaining a Windows application that was written by using the .NET Framework 1.0. You need to configure this application to run by using the .NET Framework 1.1. The target machines will have two versions of the .NET Framework (version 1.1, and 2.0) installed side-by-side. Version 1.0 will not be installed. You must modify the application configuration file to target the .NET Framework 1.1 runtime. What should you write in the application configuration file? 1. <configuration> <startup> <requiredRuntime version="v1.1.4322" /> </startup> </configuration> <Correct> 2. <configuration> <startup> <supportedRuntime version="v1.1.4322"/> </startup> </configuration> 3. <configuration> <startup> <supportedRuntime version="v1.1.432"/> <requiredRuntime version="v1.0.3705"/> </startup> </configuration> 4. <configuration> <startup> <supportedRuntime version="v2.0.50727"/> <supportedRuntime version="v1.1.4322"/> <supportedRuntime version="v1.0.3705"/> </startup> </configuration> Explanation : You should add the following to the configuration section of the application configuration file: <configuration> <startup> <requiredRuntime version="v1.1.4322" /> </startup> </configuration> Applications compiled with .NET Framework 1.0 do not support the <supportedRuntime> element. Instead, you must use the <requiredRuntime> element. You should not add the following to the configuration section of the application configuration file because the application will not look for the <supportedRuntime> element: <configuration> <startup> <supportedRuntime version="v1.1.4322"/> </startup> </configuration> You should not add the following to the configuration section of the application configuration file:

<configuration> <startup> <supportedRuntime version="v1.1.432"/> <requiredRuntime version="v1.0.3705"/> </startup> </configuration> This entry would cause the application to look for .NET Framework v1.0.3705, which is not installed. You should not add the following to the configuration section of the application file: <configuration> <startup> <supportedRuntime version="v2.0.50727"/> <supportedRuntime version="v1.1.4322"/> <supportedRuntime version="v1.0.3705"/> </startup> </configuration> If the application had been compiled with a .NET Framework 1.1 or later, this entry would cause .NET Framework v2.0 to be used because it is the latest supported version listed. Objective: Embedding configuration, diagnostic, management, and installation features into a .NET Framework application Sub Objective(s): Create a custom Microsoft Windows Installer for .NET Framework components by using the System.Configuration.Install namespace, and configure .NET Framework applications by using configuration files, environment variables, and the .NET Framework Configuration tool (Mscorcfg.msc). References : How to: Use an Application Configuration File to Target a .NET Framework Version MSDN Link: http://msdn2.microsoft.com/en-us/library/9w519wzk.aspx requiredRuntime Element MSDN Link: http://msdn2.microsoft.com/en-us/library/a5dzwzc9(VS.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-109

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. You write the following code in your application: public class WhsProcess { [ComVisible(true)] public void GetState() { // Additional code goes here } [ComVisible(false)] public string ChangeCase(string s) { return s.ToUpper(); } [ComVisible(true)] private int Increment(int i) { return i++; } protected void UpdateState() { // Additional code goes here } } You compile the code and use the Type Library Exporter tool to generate a type library. You need to use the type library in a Component Object Model (COM) application. Which answer choice contains the methods of the WhsProcess class that will be visible in the COM application? 1. GetState Increment UpdateState 2. GetState UpdateState 3. GetState 4. GetState Increment Explanation : By default all public type members are visible to COM. You can change the visibility of public members by using the ComVisible attribute. In this scenario, applying the ComVisible attribute with its value set to False will hide the public member ChangeCase from the COM applications. The private and protected members are never visible to COM even after applying the ComVisible attribute set to True. The only member available to the COM client in this scenario is the GetState method. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Expose COM components to the .NET Framework and .NET Framework components to COM. (Refer System.Runtime.InteropServices namespace) <Correct>

ComVisibleAttribute Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.comvisibleattribute(vs.80) .aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-010

____________________________________________________________________________________________________________________ You are writing an application that must read a file that is compressed using the following code: DeflateStream compressedStream = new DeflateStream(fs2, CompressionMode.Compress, false); compressedStream.Write(bArray, 0, 1000); compressedStream.Close(); The uncompressed Byte array was 1000 bytes. The compressed file is 125 bytes. You need to write code to uncompress the data and store it in a Byte array named Grid. What code should you use? 1. fs2 = new fileStream("numbers.dat", FileMode.Open); DeflateStream uncompressed = new DeflateStream(fs2, CompressionMode.Decompress); uncompressed.Read(Grid, 0, 1000); <Correct> 2. fs2 = new fileStream("numbers.dat", FileMode.Open); GZipStream uncompressed = new GZipStream(fs2, CompressionMode.Decompress); uncompressed.Read(Grid, 0, 1000); 3. fs2 = new fileStream("numbers.dat", FileMode.Open); DeflateStream uncompressed = new DeflateStream(fs2, CompressionMode.Decompress); uncompressed.Read(Grid, 0, 125); 4. fs2 = new fileStream("numbers.dat", FileMode.Open); GZipStream uncompressed = new GZipStream(fs2, CompressionMode.Decompress); uncompressed.Read(Grid, 0, 125); Explanation : You should use the following code: fs2 = new fileStream("numbers.dat", FileMode.Open); DeflateStream uncompressed = new DeflateStream(fs2, CompressionMode.Decompress); uncompressed.Read(Grid, 0, 1000); Because the data was compressed using DeflateStream, you must decompress it using DeflateStream. Also, the count argument passed to the Read method should be the size of the uncompressed data, not the size of the compressed data. In this scenario, the original data is 1000 bytes. You should not use the following code: fs2 = new fileStream("numbers.dat", FileMode.Open); DeflateStream uncompressed = new DeflateStream(fs2, CompressionMode.Decompress); uncompressed.Read(Grid, 0, 125); A length of 125 will cause only 125 bytes of uncompressed data to be read. You should not use GZipStream to decompress the data. You must use the same class as was used to compress the data. Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Compress or decompress stream information in a .NET Framework application (Refer System.IO.Compression namespace), and improve the security of application data by using isolated storage. (Refer System.IO.IsolatedStorage namespace)

DeflateStream Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.compression.deflatestream(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-015

____________________________________________________________________________________________________________________ You are developing a new Windows service named FTPReader. The FTPReader class inherits its functionality from the ServiceBase class. The FTPReader service constantly monitors a file folder for a new file. When a file is uploaded, the service adds the data in the file to a SQL Server database. You override the OnStop method in the ScannerSync class and write code to close database connections. You need to implement the monitoring functionality. What should you do? 1. Add a Timer control to the project. Enable the Timer control in the OnStart method. Add code to the Timer control's Tick event to check for and process a new file. 2. Create a procedure named ProcessFile that checks for and processes a new file. Override the OnStart method and the OnContinue method to call the ProcessFile procedure. 3. Launch a thread from OnStart(). In the thread function, instantiate a System.IO.FileSystemWatcher class. Respond to events raised by the class. <Correct> 4. Create a procedure named ProcessFile that checks for and processes a new file. Override the constructor to call the ProcessFile procedure. Explanation : You should launch a thread from OnStart, instantiate a System.IO.FileSystemWatcher class in the thread function, and respond to events raised by the class. You should also shut down that thread in OnStop(), and set and clear a pause flag in OnPause() and OnResume() that the event handler would check before performing processing. You should not add a Timer control to the project. A Timer control is a member of the System.Windows.Forms namespace and is only available to Windows Forms applications. You should not create a procedure named ProcessFile and call it from the OnStart method. The OnStart method executes only when the Windows service is started. It should not call a method that performs the actual monitoring. You should not create a procedure named ProcessFile and call it from the constructor. The constructor for a Windows service is executed immediately before the OnStart method the first time a service is started after the computer reboots. It is not the appropriate location to place code that performs monitoring. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Implement, install, and control a service. (Refer System.ServiceProcess namespace) References : ServiceBase Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.serviceprocess.servicebase(vs.80).aspx The Windows Forms Timer event is not raised in a Windows service Microsoft Help and Support Link: http://support.microsoft.com/kb/820639

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-021

____________________________________________________________________________________________________________________ You are developing a Windows forms application by using the .NET Framework. You need to create two nested rectangles. The outer rectangle must be black and the inner rectangle must be blue, as shown in the exhibit. The Form_Paint method handles the Paint event for the form. You must add code to the Form_Paint event to accomplish this task. Which code segment should you use? 1. private void Form_Paint (object sender, PaintEventArgs e) { System.ComponentModel.TypeConverter rectConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle)); Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50, 50, 200, 200"); e.Graphics.DrawRectangle(Pens.Black, rect); rect.Inflate(-10, -10); e.Graphics.DrawRectangle(Pens.Blue, rect); } <Correct> 2. private void Form_Paint (object sender, PaintEventArgs e) { System.ComponentModel.TypeConverter rectConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle)); Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50, 50, 200, 200"); e.Graphics.DrawRectangle(Pens.Black, rect); Rectangle rect2 = (Rectangle)rectConverter.ConvertFromString("40, 40, 200, 200"); e.Graphics.DrawRectangle(Pens.Blue, rect2); } 3. private void Form_Paint (object sender, PaintEventArgs e) { System.ComponentModel.TypeConverter rectConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle)); Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50, 50, 200, 200"); e.Graphics.DrawRectangle(Pens.Black, rect); rect.Inflate(10, 10); e.Graphics.DrawRectangle(Pens.Blue, rect); } 4. private void Form_Paint (object sender, PaintEventArgs e) { System.ComponentModel.TypeConverter rectConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle)); Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50, 50, 200, 200"); e.Graphics.DrawRectangle(Pens.Black, rect); Rectangle rect2 = (Rectangle)rectConverter.ConvertFromString("40, 40, 190, 190"); e.Graphics.DrawRectangle(Pens.Blue, rect2); } Explanation : To accomplish this task, your code should do the following: * First draw the rectangle by using a black pen. * Inflate the same rectangle by a negative amount to create a smaller inner rectangle. * Draw the inner rectangle by using a blue pen. This can be correctly done by using the following code:

private void Form_Paint (object sender, PaintEventArgs e) { System.ComponentModel.TypeConverter rectConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle)); Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50, 50, 200, 200"); e.Graphics.DrawRectangle(Pens.Black, rect); rect.Inflate(-10, -10); e.Graphics.DrawRectangle(Pens.Blue, rect); } If you use the following code, you create the blue rectangle as the outer and black rectangle as inner rectangle, which is opposite of what is required: private void Form_Paint (object sender, PaintEventArgs e) { System.ComponentModel.TypeConverter rectConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle)); Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50, 50, 200, 200"); e.Graphics.DrawRectangle(Pens.Black, rect); rect.Inflate(10, 10); e.Graphics.DrawRectangle(Pens.Blue, rect); } If you use the following code, you end up creating two overlapping rectangles: private void Form_Paint (object sender, PaintEventArgs e) { System.ComponentModel.TypeConverter rectConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle)); Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50, 50, 200, 200"); e.Graphics.DrawRectangle(Pens.Black, rect); Rectangle rect2 = (Rectangle)rectConverter.ConvertFromString("40, 40, 190, 190"); e.Graphics.DrawRectangle(Pens.Blue, rect2); } If you use the following code, you also end up creating two overlapping rectangles: private void Form_Paint (object sender, PaintEventArgs e) { System.ComponentModel.TypeConverter rectConverter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(Rectangle)); Rectangle rect = (Rectangle)rectConverter.ConvertFromString("50, 50, 200, 200"); e.Graphics.DrawRectangle(Pens.Black, rect); Rectangle rect2 = (Rectangle)rectConverter.ConvertFromString("40, 40, 200, 200"); e.Graphics.DrawRectangle(Pens.Blue, rect2); } Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Enhance the user interface of a .NET Framework application by using the System.Drawing namespace. References : Rectangle.Inflate Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.drawing.rectangle.inflate(vs.80).aspx Rectangle Structure MSDN Link: http://msdn2.microsoft.com/en-us/library/system.drawing.rectangle(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-055

____________________________________________________________________________________________________________________ You are developing a Windows application by using the .NET Framework. You need to create a foreground thread to draw lines in your application. When you start the thread, you must also provide a data value that specifies the number of lines to be drawn. What should you do? (Each correct answer presents part of the solution. Choose two.) 1. Call the ThreadPool.QueueUserWorkItem method. 2. Create a ThreadStart delegate. 3. Create a ParameterizedThreadStart delegate. 4. Create a WaitCallBack delegate. 5. Call the Thread.Start method. <Correct> <Correct>

Explanation : You should create a ParameterizedThreadStart delegate and then use the Thread.Start method to start the thread. The Thread.Start method allows you to create actively managed foreground threads. A parameterized ThreadStart delegate allows you to pass data when starting a thread. You should not use the ThreadPool.QueueUserWorkItem method because this method is used to create system managed background threads. You should not use a ThreadStart delegate because you need to pass parameters when starting the thread. You should not use WaitCallBack delegate because this delegate specifies the method that needs to be executed in a background thread that is part of a thread pool. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Develop multithreaded .NET Framework applications. (Refer System.Threading namespace) ParameterizedThreadStart Delegate MSDN Link: http://msdn2.microsoft.com/en-us/library/system.threading.parameterizedthreadstart(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-127

____________________________________________________________________________________________________________________ You are trying to port a portion of an old Human Resource Management application to the .NET Framework. This old application is written in unmanaged Windows code and does not have any COM interfaces. The .NET application makes calls to an existing unmanaged library named Performance.dll. You need to make a call to the GetPerformanceScore method of the Performance.dll library. What should you do? 1. Use the Type Library Importer tool (tlbimp.exe). 2. Use the Assembly Registration tool (regasm.exe). 3. Use the Type Library Exporter tool (tlbexp.exe). 4. Declare the method using the DllImportAttribute attribute. 5. Declare the method using the MarshalAsAttribute attribute. Explanation : The Platform Invoke feature allows .NET managed code to call methods in unmanaged libraries. You need to declare the unmanaged method in the managed code using the extern and static keywords, along with the DllImport attribute, which specifies the unmanaged library and other settings required to make a call to the unmanaged method. You should not use the Assembly Registration tool (regasm.exe) because the unmanaged DLL is not in COM. COM applications expect to find runtime information about types in the Windows registry. The Assembly Registration tool (regasm.exe) reads an assembly and creates the entries required by COM applications. You should not use the Type Library Exporter tool (tlbexp.exe) because the .NET managed code needs to call the unmanaged code and also because the unmanaged DLL is not in COM. The Type Library Exporter tool (tlbexp.exe) generates a COM library from a .NET assembly. You should not use the Type Library Importer tool (tlbimp.exe) because the unmanaged DLL is not in COM. The Type Library Importer tool (tlbimp.exe) processes only COM type libraries to generate .NET assemblies. You should not use the MarshalAsAttribute attribute. This attribute is used to control how strings are marshaled when passing an argument to unmanaged code. This attribute is not added to a method. It is added to a parameter or return value. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Call unmanaged DLL functions within a .NET Framework application, and control the marshalling of data in a .NET Framework application. (Refer System.Runtime.InteropServices namespace) Consuming Unmanaged DLL Functions MSDN Link: http://msdn2.microsoft.com/en-us/library/26thfadc(vs.80).aspx <Correct>

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-108

____________________________________________________________________________________________________________________ You are developing a .NET Framework application. The application's assembly is named CustomApp and is stored in CustomApp.exe. You use the .NET Framework's Strong Name tool to generate a key pair for CustomApp.exe as shown below: sn.exe -k CustomAppKey You must use the key pair to build CustomApp.exe as a strong named assembly. What should you do? 1. Use the AssemblyKeyNameAttribute class. 2. Use the AssemblyConfigurationAttribute class. 3. Use the AssemblyDelaySignAttribute class. 4. Use the AssemblyKeyFileAttribute class. <Correct>

Explanation : The Strong Name tool allows you to generate and manage keys for strong name signing. The -k switch generates a new key pair and stores it in the specified file (CustomAppKey in this case). You should use the AssemblyKeyFileAttribute class to specify the file containing the key pair. At the time of compilation, the information in the key file is used to generate a strongly typed assembly. You should not use the AssemblyKeyNameAttribute class because this class is used to specify the name of a key container that should be used for strong name signing. In this scenario, you do not have a key container. You should not use the AssemblyConfigurationAttribute class because this attribute is used to specify a build configuration (for example, debug or release) for an assembly. You should not use the AssemblyDelaySignAttribute class because this class is used to specify whether or not delayed signing should be used when assigning a strong name. Delayed signing may simplify building an assembly when only the public key portion of the key pair is available for strong name signing. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Implement reflection functionality in a .NET Framework application (refer System.Reflection namespace), and create metadata, Microsoft intermediate language (MSIL), and a PE file by using the System.Reflection.Emit namespace. References : AssemblyKeyFileAttribute class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.reflection.assemblykeyfileattribute(vs.80).aspx Strong Name Tool (Sn.exe) MSDN Link: http://msdn2.microsoft.com/en-us/library/k5b5tt23(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-037

____________________________________________________________________________________________________________________ You are developing a console application by using the .NET Framework. You write the following code (line numbers are for reference purposes only): 01 NumberFormatInfo myNfi = new NumberFormatInfo(); 02 myNfi.CurrencySymbol = "$"; 03 myNfi.NegativeSign = "-"; 04 myNfi.NumberNegativePattern = 4; 05 myNfi.CurrencyNegativePattern = 4; 06 Int64 myInt = -1234; 07 The code segment must print the following output on the console: (1,234.00$) You need to add code in line 07 to print the desired output. Which code segment should you use? 1. Console.WriteLine(myInt.ToString("D", myNfi)); 2. Console.WriteLine(myInt.ToString("E", myNfi)); 3. Console.WriteLine(myInt.ToString("C", myNfi)); 4. Console.WriteLine(myInt.ToString("F", myNfi)); 5. Console.WriteLine(myInt.ToString("N", myNfi)); Explanation : You should use the following code segment to get the desired output: Console.WriteLine(myInt.ToString("C", myNfi)); Using the format string "C" prints the currency sign as part of the output. Using the format string "D" prints the number in decimal format and generates the following output: -1234 Using the format string "N" prints the number in a numeric format and generates the following output: 1,234.00Using the format string "F" prints the number in a fixed-point format and generates the following output: -1234.00 Using the format string "E" prints the number in scientific (exponential) format and generates the following output: -1.234000E+003 Objective: Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application Sub Objective(s): Format data based on culture information. (Refer System.Globalization namespace) <Correct>

References : Standard Numeric Format Strings MSDN Link: http://msdn2.microsoft.com/en-us/library/dwhawy9k(vs.80).aspx NumberFormatInfo Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.globalization.numberformatinfo(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-044

____________________________________________________________________________________________________________________ You are developing a class library application by using the .NET Framework. You decide to use the AppDomain class to create an application domain. You need to create an instance of a type named TestSpace.TestType. You must configure the new application domain so that it probes for the assembly containing the type in a specified directory. You create an instance of the AppDomainSetup class. Which property should you set to configure the application domain? 1. ApplicationBase <Correct>

2. ActivationArguments 3. CachePath 4. AppDomainInitializerArguments Explanation : When you create an application domain by calling the CreateDomain method of the AppDomain class, you can pass an instance of an AppDomainSetup object to define configuration information for the application domain. One important property is the ApplicationBase property, which defines the root directory for the application. The Common Language Runtime will use this root directory as the starting point for probing for an assembly that matches a request for a type. Using the ActivationArguments property is incorrect because this property is used to configure the properties used for manifest activation. Using the AppDomainInitializerArguments property is incorrect because this property defines the arguments that are passed to the callback method that executes when the application domain is initialized. Using the CachePath property is incorrect because this property gets or sets the name of the directory to which the assembly files will be shadow copied. An assembly that supports shadow copy can be updated while it is running because the executable is loaded from the shadow copy, not from the original assembly file. Objective: Implementing service processes, threading, and application domains in a .NET Framework application Sub Objective(s): Create a unit of isolation for common language runtime within a .NET Framework application by using application domains. (Refer System namespace) How to: Configure an Application Domain MSDN Link: http://msdn2.microsoft.com/en-US/library/c8hk0245.aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-001

____________________________________________________________________________________________________________________ You are writing an application that allows users to query product inventory information. The information is stored in the Product class defined below: public class Product { private string m_Name; private int m_InStock; private decimal m_Price; private string m_ProductID; public string ProductName { get { return m_Name;} set {m_Name = value;} } public string ProductID { get { return m_ProductID;} set { m_ProductID = value;} } public int InStock { get { return m_InStock;} set { m_ InStock = value;} } public decimal Price { get { return m_Price;} set { m_ Price = value;} } } The application needs to allow users to efficiently retrieve a specific product by product ID. It also must display the names of all the products, sorted by product ID, using the following code: int i; string sName; for (i = 0; i < products.Count; i++) { Product p = (Product) products.GetByIndex(i); sName = p.ProductName; } You need to choose the best collection class to use to store the product data. Which class should you use? 1. HashTable 2. List 3. Dictionary 4. SortedList <Correct>

Explanation : You should use the SortedList class. The SortedList class allows you to retrieve a value by index using the GetByIndex method. It also allows you to retrieve a value by key. In this case, you

would use the product ID as the key. You should not use the Dictionary class. The Dictionary class is used to store a type-safe collection of keys and values. However, it does not store the list in a sorted order. It allows you to retrieve a value by a key, but does not implement a GetByIndex property. You should not use the HashTable class. The HashTable class is like a Dictionary class, except it is not type-safe. You should not use the List class. The List class is a type-safe class, but it stores only values. It does not store key/value pairs. Objective: Developing applications that use system types and collections Sub Objective(s): Manage a group of associated data in a .NET Framework application by using collections (Refer System.Collections namespace) SortedList Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.collections.sortedlist(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : rrMS_70-536-C-021

____________________________________________________________________________________________________________________ You have loaded an assembly dynamically using the Assembly.LoadFromFile method. You have stored a reference to the class you are planning to use in a variable named myClass. Now you need to execute the method of the class named Draw. The Draw method does not require any parameters. What code should you use? 1. MethodInfo m = myClass.GetMethod("Draw"); m.Invoke(myClass); 2. myClass.Invoke("Draw", null); 3. Type t = myClass.GetType(); MethodInfo m = t.GetMethod("Draw"); m.Invoke(myClass, null); <Correct> 4. Type t = myClass.GetType(); t.Invoke("Draw"); Explanation : You should use the following code: Type t = myClass.GetType(); MethodInfo m = t.GetMethod("Draw"); m.Invoke(myClass, null); You need to retrieve a reference to an object of type MethodInfo. Since you know the name of the method, the best way to do this is to call the GetMethod method on a variable that stores the object's type. Next, you can call Invoke on the MethodInfo object, passing the reference to the class as the first argument. Because there are no parameters to the Draw method, you must pass Nothing as the second argument. You should not use the following code: MethodInfo m = myClass.GetMethod("Draw"); m.Invoke(myClass); You need to call GetMethod on a variable that stores the object's type, not on a reference to the object. The object itself does not implement a GetMethod method. You should not use the following code: myClass.Invoke("Draw", null); The Invoke method is implemented by the MethodInfo class, not by the custom class. You should not use the following code: Type t = myClass.GetType(); t.Invoke("Draw"); The Invoke method is implemented by the MethodInfo class, not by the Type class. Objective: Implementing interoperability, reflection, and mailing functionality in a .NET Framework application Sub Objective(s): Implement reflection functionality in a .NET Framework application (refer System.Reflection namespace), and create metadata, Microsoft intermediate language (MSIL), and a PE file by using the System.Reflection.Emit namespace.

References : MethodInfo Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.reflection.methodinfo(vs.80).aspx Type.GetMethod Method MSDN Link: http://msdn2.microsoft.com/en-us/library/system.type.getmethod(vs.80).aspx

Microsoft (70-536) TS: Microsoft .NET Framework - Application Development Foundation C#


Question ID : akMS_70-536-C-071

____________________________________________________________________________________________________________________ You need to read the contents of MyFile.txt and display them on the console. You write the following code (line numbers are for reference only): 01: using (StreamReader sr = new StreamReader("MyFile.txt")) 02: { 03: 04: } What code should you insert at line 03 to successfully read the contents of MyFile.txt? 1. while (sr.Peek() > -1) { Console.Write((char)sr.Read()); } <Correct> 2. while (sr.Read() > -1) { Console.Write((char)sr.Peek()); } 3. while (sr.Peek() > -1) { Console.Write((char)sr.Peek()); } 4. while (sr.Read() > -1) { Console.Write((char)sr.Read()); } Explanation : You should use the following code to successfully read the contents of MyFile.txt: while (sr.Peek() > -1) { Console.Write((char)sr.Read()); } The Peek method returns the next available character in the stream but does not advance the position of the reader. The Read method returns the next available character in the stream but also advances the position of the stream. Both methods return -1 when they encounter an end of stream. The following code is incorrect because it will not write the first character on the console: while (sr.Read() > -1) { Console.Write((char)sr.Peek()); } The following code is incorrect because the stream does not advance and the code will continuously read the first character of the stream: while (sr.Peek() > -1) { Console.Write((char)sr.Peek()); } The following code is incorrect because it skips one character for each character that it writes on the console:

while (sr.Read() > -1) { Console.Write((char)sr.Read()); } Objective: Implementing serialization and input/output functionality in a .NET Framework application Sub Objective(s): Manage .NET Framework application data by using Reader and Writer classes. (Refer System.IO namespace) StreamReader Class MSDN Link: http://msdn2.microsoft.com/en-us/library/system.io.streamreader(vs.80).aspx

Вам также может понравиться