C#

Ace your homework & exams now with Quizwiz!

You are developing a Microsoft Windows Presentation Foundation (WPF) application by using C# and Visual Studio 2015. Your application must be able to display the contents of large, encrypted files. You have this code: (Line numbers are for reference purposes only.) 01 // The data variable is intialized elsewhere 02 private CryptoStream data; 03 private async void button_Click(object sender, RolutedEventArgs args) 04 { 05 06 } You need to complete the code to display the contents of the file in a user interface object named outputText. You should ensure that the application remains responsive. Note that the user interface objects in a WPF applicaiton must be accessed only by the one thread that owns all user interface objects. Which code block completes the method when inserted at line 05?

You should use this code block: var reader = new StreamReader(data); outputText.Text = await reader.ReadToendAsync(); The StreamReader class inherits several asynchronous methods from the TextReader base class. These methods include the Async suffix in the method name. Each asynchronous method returns a Task instance that may be awaited in your code. When you use the await keyword on a Task instance, the compiler constructs an internal state machine that uses the Synchronizationcontext.Current static property to run the remainder of the method on the appropriate thread. In a WPF application, the current SynchronizationContext ensures that the return value of the task is processed on the user-interface(UI) thread.

You use Microsoft .NET Framework 4.5 to create an application. An event handler named DocumentsProcessed handles an event named Processed. You need to unsubscribe the event handler from the Processed event. Which code segment should you use?

You should use this code segment: Processed -= DocumentsProcessed; This code uses the -= operator to remove a subscription to the Processed event. In this scenario, the subscription is an event handler named DocumentsProcessed.

You use Microsoft .NET Framework 4.5 to create an application. This class definition exists: public class Classroom { public string RoomNumber {get; set;} } You write this code to create a Classroom instance: Classroom room = new Classroom(); room.RoomNumber = "100A"; By not altering the Classroom class definition, you must serialize the instance to this XML: <Classroom number="100A"/> You need to write the code to accomplish your goal. Which code segment should you use?

You should use this code segment: XmlAttributeOverrides overrides = new XmlAttributeOverrides(); XmlAttributes roomNumberAttributes = new XmlAttributes(); roomNumberAttributes.XmlAttribute = new XmlAttributeAttribute("number"); overrides.Add(typeof(Classroom),"RoomNumber", roomNumberAttributes); XmlSerializer serializer = new XmlSerializer(typeof(classroom), overrides); MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, room); the XmlAttributeOverrides class allows you to override the default XML serialization. By default, a class and its members are serialized as XML elements. The XmlSerializer class accepts an XmlAttributeOverrides instance that specifies custom serialization attributes. The XmlAttributeOverrides class contains a collection of XmlAttributes instances. The XmlAttributes class represents XML serialization attributes that you can declaratively specify for classes and members. The XmlAttribute property of this class allows you to represent a class member as an XML attribute. In this scenario, this code represents the RoomNumber property as an XML attribute named number: roomNumberAttributes.XmlAttribute = new XmlAttributeAttribute("number"); The code then adds the XmlAttributres instance to the XmlAttributeOverrides instance by calling its Add method.

You use Microsoft .NET Framework 4.5 to create an application. You use the BinaryWriter class to write five strings to a file named Strings.dat. You need to retrieve each string written to the Strings.dat file. Which code segment should you use?

You should use this code segment: using (BinaryReader reader = new BinaryReader(File.OpenRead("Strings.dat"))) { for (int i = 0; i < 5; i++) { string data = reader.ReadString(); } } This code uses the BinaryReader class to read data from a file. The Readstring method reads one string from the file. by calling the method within a loop, you can read all five strings from the file.

You use Microsoft .NET Framework 4.5 to create an application. You deserialize text-based data into a Memorystream instance named memoryStream. You need to obtain the contents of the memoryStream instance. which code segment should you use?

You should use this code segment: using (StreamReader reader = new StreamReader(memoryStream)) { string data = reader.ReadToEnd(); } The StreamReader class allows you to read text-based input from a stream. The constructor accepts a Stream instance that represents the data to read. The ReadToEnd method returns a string that represents the text-based data read from the stream.

You use Microsoft .NET Framework 4.5 to create an application. You create a variable named integers that represents a generic List instance of integers. You need to write each integer on a separate line in a file named integers.txt. Which code segment should you use?

You should use this code segment: using (StreamWriter writer = new StreamWriter("Integers.txt")) { integers.ForEach(i => writer.WriteLine(i)); } This code calls the WriteLine method of the StreamWriter class during each iteration. The WriteLine method writes data to a new line in the underlying stream.

You are writing a C# application for a convenience store by using Visual Studio 2015. The app must return an enum indicating whether the customer is a minor (under age 18), can buy tobacco (at least age 18), or can buy alcohol (at least age 21) based on the customer's age. You create the following enum: enum AgeType { Unknown, Minor, Tobacco, Alcohol } You need to write a function that will return the appropriate value. Which block of code should you write?

You should write the block of code below: AgeType GetType(int age) { AgeType type = AgeType.Unknown; if (age <18) { type = AgeType.Minor; } else if (age <21) { type = AgeType.Tobacco; } else { type = AgeType.Alcohol; } return type; } This code uses an if-else block to test each age condition and returns the correct result based on the customer's age. If the customer is under 18, then Minor is returned. Otherwise, the code checks to see if the customer is under 21, which returns Tobacco. Otherwise the code returns Alcohol because at this point the customer must be 21 or older.

You use Microsoft .NET Framework 4.5 to create an application. You must call a method named ImportData that might throw exceptions of multiple types. If it throws an instance of type SqlException, you must call the LogSqlError method and pass to it the SqlException instance as a parameter. If it throws any other type of exception, you must call the LogError method and pass to it the instance of the exception that was thrown. You need to write code to accomplish your goal. Which code segment should you use?

try { ImportData(); } catch(SqlException ex) { LogSqlError(ex) } catch(Exception ex) { LogError(ex); }

You use Microsoft .NET Framework 4.5 to create a reusable component. You need to create a user-defined exception for your component. Your solution must adhere to Microsoft best practices. From which base calls should you derive your exception class?

You should derive your exception class from Exception. This adheres to Microsoft best practices. The Exception class represents the base type from which all exceptions should be derived.

You use Microsoft .NET Framework 4.5 to create an application. You have three resource files that you want to merge into a single assembly. You need to merge the resource files. Which command should you run?

You should run the Al.exe command. This is the Assembly Linker tool. It allows you to merge manifest or resource files into a single assembly.

You are writing a C# application by using Visual Studio 2015. The application processes long calculations on multiple threads. You write the code below (line numbers added for reference): 01 static WaitHandle[] handles = new WaitHandle[] 02{ 03 new AutoResetEvent(false), 04 new AutoResetEvent(false), 05 new AutoResetEvent(false) 06 }; 07 ThreadPool.QueueUserWorkItem(new WaitCallback(Calculate), wait Handles[0]); 08ThreadPool.QueueUserWorkItem(new WaitCallback(Calculate), waitHandles[1]); 09 10 Summarize(); The calculate function processes the calculations. After all of the calculations are completed, you want the summarize function to run. Which line of code should you write at line 09?

You should use the line of code below: WaitHandle.WaitAll(waitHandles); The WaitAll method instructs the thread management to wait until all of the wait handles in the waitHandles array have completed before moving on the next statement.

You use Microsoft .NET Framework 4.5 to create an application. Your application must store a collection of people in a particular order. If one person is removed from the collection, the collection automatically resizes itself to not leave any gaps. Also, accessing a person from the collection must not remove the person from the collection. You need to choose a collection class. Which class should you use?

You should use the LinkedList class. This collection class implements a doubly linked list. It allows you to quickly determine the immediate sibling items for a specific item in the collection. Removing an item form the collection automatically resizes it so that it does not leave any gaps.

You are writing a C# application by using Visual Studio 2015. You need to write a function that will calculate the numeric sum of two numbers that are stored as strings. Which code should you write?

You should use the block of code below: float SumString(string a, string b) { return float.Parse(a) + float.Parse(b); } This block of code correctly uses the float.Parse method to explicitly convert each string to a float before adding them together. The result will be a float that is the sum of the two numbers.

You are creating a C# application by using Visual Studio 2015. You have created the code below: public class Plant { public virtual void Draw() { DrawPlant(); } } You need to implement a class called Tree that has its own Draw method. When a consumer of Tree calls its Draw method, the Draw method for Plant should also be called. Which code should you write?

You should use the code below: public class Tree: Plant { public override void Draw() { public override void Draw() { DrawTree(); base.Draw(); } } This code properly uses base.Draw to call the Draw method from the Plant class, which is the base class for Tree.

You are developing an application by using C# and Visual Studio 2015. You have a type with this definition (Line numbers are included for reference purposes only.): 01 public struct Point3d 02 { 03 04 public Point3d (double x, double y, double z) 05 { 06 this.X = x; 07 this.Y = y; 08 this.Z = z; 09 } 10 } You need to implement the data members of the struct at Line 03. Which code block should you use?

You should use this code block that declares three fields (or type-level variable): public double X; public double Y; public double Z; When you declare fields in a struct, the compiler automatically adds a default (or parameter-free) constructor that sets all fields to binary zero. When creating a struct in C#, the compiler requires definite assignment. This means that the compiler must be able to analyze the source code and guarantee that all fields have been initialized before any methods (including property setters and getters) may be called. Because the compiler does not require the use of any constructors when using structs, you must be diligent to ensure that these fields are initialized.

You use Microsoft .NET Framework 4.5 to create an application. This class exists: public class Vehicle { public string Make {get; set;} public string Model {get; set;} public int Year {get; set;} public string Vin {get; set;} public static List<Vehicle>GetVehicles() { // Implementation Omitted } } You need to create a query that returns a collection of Vehicle instances where the Make property is set to "Honda". Which code segment should you use?

You should use this code segment: var query = from v in Vehicle.GetVehicles() where v.Make =="Honda" select v; This code uses a LINQ query expression to select Vehicle instances where each instance's Make property is set to "Honda".

You are developing a utility class library by using C# and Microsoft Visual Studio 2015. Your application has performance problems when you use the built-in collection classes in System.Collections.Generic. After thorough analysis, you have decided to implement an Intrusive Linked List. Because this data structure is a pattern that will be used in many classes, you have created the following interface: public interface IIntrusiveList<T> { IIntrusiveList<T>Next { get; set; } IIntrusiveList<T> Previous { get; set; } T Self { get; } } The implementation for common methods such as Add(), Remove(), and Count() can use the same implementation for any class that implements IIntrusiveList<T>. You have decided to implement these three methods as extensions to the IIntrusiveList<T> type. Complete the implementation of the IntrusiveListExtensions class by dragging the keywords on the left to the appropriate location on the right. You may use items more than once, and you do not have to use each item.

An extension method is a static method with a more convenient syntax. For instance, you could write a method that extends the string type to determine a file type based on the file extension: public static StringExtensions { public static bool IsImage(string fileName) { // implementation omitted } } You woudl then invoke this method by using the following method call (assume a variable called fileName of type string ): bool result = StringExtensions.IsImage(fileName); An extension method simplifies the method call to: bool result = fileName.IsImage(); To create an extension method, you must create a static method in a static class. The class name is unimportant, as long as it is accessible and in scope (by adding the namespace to the code file with the using directive). The data type of the first parameter determines the data type to be extended. The other important detail that turns this method from a standard static method to an extension method is the this keyword that prefixes the first parameter: public static StringExtensions { public static bool IsImage(this string fileName) { // implementation omitted } } The compiler automatically annotates the method, the class, and the containing assembly with the ExtensionAttribute. This allows the compiler to assign the value on the left of the dot ( . ) operator to the first parameter of the method. Because the compiler does not require more elaborate design, such as the use of generics or inheritance, ti is not necessary to use specialized keywords such as base or generic type parameters like T.

You are developing a managed Microsoft Windows service by using C# and Microsoft Visual Studio 2015. This service generates and caches large report objects. Other applications on the system access these objects through a named pipe to the service. You want the service to signal other processes when a report is ready to access. Which class should you use?

ManualResetEvent You should use the ManualResetEvent class. This class allows one thread to block all threads that wait on the event until it becomes signaled. If the ManualResetEvent instance is named, any thread in any proces that creates a new, named instance will obtain a reference to the same instance. To create a named ManualResetEvent, call the constructor overload that accepts a Boolean argument and a string argument. The boolean argument should be false to instantiate the event in a non-signaled state. The string should be a unique name that is shared among all processes that should be signaled by the same event instance.

You are developing suite of applicaitons by using C# and Microsoft Visual Studio 2015. These applications share a central web service. End users might open and use any combination of these applications on their system. The web service can only support three simultaneous connections from any one client system. You need to ensure that each client application waits to perform service requests until there are fewer than three pending service operations. Which class should you use?

Semaphore You should use the Semaphore class. The Semaphore class allows you to restrict access to limited resources. When you declare a semaphore, you provide a maximum resource capacity argument and reserved capacity argument. Some overloads to the Semaphore constructor allow you to provide a name. when you pass a name argument, a system-level semaphore is created. Multiple applications that require access to the same limited resource can create Semaphore instances that wrap the same system-level semaphore. When the capacity of the semaphore is depleted, each call to the Semaphore.WaitOne method will block the thread until a different thread releases the resource by calling the Semaphore.Release method.

You are writing a C# application by using Visual Studio 2015. The application opens a data file and reads the first line. You create a custom exception for handling read errors named FileReadException. If a read operation fails, you need to throw a FileReadException. You should ensure that the file is always closed properly. You need to write the code to properly handle an exception during the read operation. Which block of code should you write?

System.IO.StreamReader file = new System.IO.StreamReader("data.txt"); try { file.ReadLine(); } catch (System.IO.IOException e) { throw new FileReadException(); } finally { file.Close(); } This code correctly calls the read operation in a catch block. It then properly catches an IOException error in the catch block and throws the FileReadException. It then correctly closes the file in a finally block, which means that the file will be closed whether the operation succeeds or fails.

You are developing a Microsoft Windows Presentation Foundation (WPF) application by using C# and Microsoft Visual Studio 2015. The standard WPF assembly PresentationFramework.dll defines a class System.windows.Window that you must derive. Your derived class must set the DataContext property, which is defined in the Window base class as a System.Object, to an instance of a class that implements INotifyPropertyChanged. The instance might be passed to the constructor, but if not, it should be instantiated in the consructor. Your class must be able to work with any implementation of INotifyPropertyChanged. Finish the definition for the MainView derived class by dragging the items from the left to the appropriate locaiton on the right. You may use items more than once, and you do not have to use every item.

The final code sample should appear as follows: public class Mainview <T> : System.Windows.Window where T : INotifyPropertyChanged, new() { public MainView() { this.DataContext = new T(); } public MainView(T viewModel) { this.DataContext = viewModel; } } Other constraints available that should not be used in this case: class - requires the type parameter to be a reference type. struct - requires the type parameter to be a value type. <class name> - requires the type parameter to inherit the specified class. <type parameter> - requires one type parameter to inherit a different type parameter. There are several requirements for the MainView class. Some of these requirements could be implemented using several techniques, others require very specific C# techniques to fulfill. The first requirement is that the MainView class derives the System.windows.Window base class. This class provdies the basic functionality for a visual window in WPF. This requirement leads to the following code: public class MainView : System.Windows.Window { } The next requirement is that the MainView constructor must accept an instance of a class that implements the INotifyPropertyChanged system interface in the system.componentModel namespace. This could be implemented by using the following constructor definition: public MainView(INotifyPropertyChanged viewModel) { this.DataContext = viewModel; } However, the next requirement makes the previous code block unaccepatable. The final requirement is that if an instance of a class that implements, INotifyPropertyChanged is not passed as an argument to the constructor, the MainView class must create a new instance. Interface definitions, such as INotifyPropertychanged, cannot specify whether the class has a public constructor. Using generic type definitions satisfies the previous requirement and this requirement. To use a generic type, you must create a type parameter. The type parameter is a custom name that serves as a placeholder for a data type. Conventionally, the type parameter is named T if there is a single type parameter, or prefixed with T if there are more than one type parameters. In the same way that value parameters are declared as a comma-delimited list in parentheses, type parameters are declared as a comma-delimited list in angle brackets immediately following the class (or other reference type) name. The type parameter may be used within the class declaration anywhere a data type is required. When the compiler encounters a generic type used in executable code, it creates a special class that replaces the type parameter with the actual data type used in code. As long as the generic class can use any potential class with the same pattern of code, the executable code can use any data type as the type parameter. In this example, we still have the requirement that the DataContext property must be set to an instance of a class that implements INotifyPropertyChanged. When you use generic types, you may add a where expression to establish a constraint on the type parameters. To guarantee that the class used implements INotifyPropertyChanged, you would add the constraint where T: INotifyPropertyChaneged to the end of the class declaration after inheritance and interface implementaitons have been declared. This changes the class declaration to the following code: public class MainView <T> : System.Windows.Window where T: INotifyPropertyChanged { public MainView(T viewModel) { this.DataContext = viewModel; } } After all o fthese changes, you still need to add a constructor with the following definition to satisfy the still unfulfilled requirement to create a new instance of the type if one is not passed to the constructor: public MainView() { this.Data.Context = new T(0; } This code requires that the data type passed as a type parameter has a public default (or parameter-free) constructor. This is a common requirement when using generic syntax, so a special constraint may be added: new() constraint must be the final constraint in the comma-delimited list.

You are writing a C# application by using Visual Studio 2015. You have created the following function: int CalcArea(int length, int width) { return length * width; } Which three lines of code can properly call the function? (Each correct answer presents a complete solution. Choose three.)

The following lines of code would properly call the function: CalcArea(length: 20, width: 30); CalcArea(width: 30, length: 20); CalcArea(20, width: 30); C# allows the parameters in a function to also be used as named parameters. Because the signature for the CalcArea function is (int lenght, int width), both length and width can be used as named parameters. The advantage of using named parameters is that they can be called in any order. It is also legal to mix a positional parameter with a named parameter as long as the positional parameter is specified first. The function calls above are equivalent to CalcArea(20, 30).

You are developing an application by using C# and Visual Studio 2015. You have these type declarations (Line numbers are included for reference purposes only.): 01 public struct Point2d 02 { 03 public double X { get; set; } 04 public double Y { get; set; } 05 public Point2d(doublex, double y) : this() 06 // remaining logic omitted 07 } 08 public struct Point3d 09 { 10 public static explicit operator Point2d(Point3d value) 11 { return new Point2d(value.X, value.Y); } 12 public static implicit operator Point3d(Point2d value) 13 { return new Point3d(value.X, value.Y, 0d); } 14 public double X { get; set; } 15 public double Y { get; set; } 16 public double Z { get; set; } 17 public Point3d(double x, double y, double z) : this() 18 / remaining logic omitted 19 } Which of these are valid statements? (Choose all that apply.)

These statements are valid statements: Point2d p = (Point2d) new Point3d(1d, 2d, 3d); Point3d p = new Point2d(3d, 2d); Point3d p = (Point3d) new Point2d(3d, 5d); To define a custom conversion, your type must declare the conversion method using a specialized syntax: public static [implicit or explicit] operator [return type]([expression type]<identifier>) The sample code given includes one implicit conversion and one explicit conversion. You can use this code because of the explicit operator that performs a narrowing operation from the more complex Point3d to the simpler Point2d type: Point2d p = (Point2d) new Point3d(1d, 2d, 3d); When you create a custom type, the new type can only be automatically converted to other types through reference conversion (such as converting to a base type), boxing and unboxing conversions (such as converting from a struct to System.Object and back again), wrapping conversions (such as creating a Nullable<T> from a type T), and null type conversions (literally returning a null reference). To extend this behavior, a type may define custom conversions. Custom conversions can be defined in one of two forms. An implicit conversion allows the compiler to assign an expression of one type to variable of another type. This is similar to what is commonly termed a widening conversion, such as assigning a 32-bit signed integer to a 64-bit signed integer. An explicit conversion requires the developer to explicitly add a cast operator to the expression before assigning the value to a variable. This is similar to what is commonly termed a narrowing conversion, such as assigning a long to an int. In the .NET framework, the system only defines widening conversions implicitly, others are explicit only. you can use this code because of the implicit operator that performs a widening operation from the Point2d type to the Point3d type: Point3d p = new Point2d(3d, 2d); You can use this code because of the implicit operator that the compiler allows you to use with an explicit cast: Point3d p = (Point3d) new Point2d(3d, 5d);

You are developing a managed Microsoft Windows service by using C# and Visual Studio 2015. Your service uses the Task Parallel Library (TPL) to transform and save data files. You have this interface declaration: public interface IDatatransformer { DataInfo Transform(DataInfo di, CancellationToken token); void Save(Task<DataInfo>t); } Your implemntation of the IdataTransformer. Transform method accepts a DataInfo instance to describe the data that must be transformed. After successfully transforming the data, this method returns a new DataInfo instance to describe the transformed data that must be saved. A Task that returns this new DataInfo instance should be passed to the Save method to complete the operation. Your service supports graceful shut down. The Transform method supports cancellation. Your code should only call the Save method when the Transform method successfully completes. Which code block correctly implements these requirements?

This code block correctly implements the requirements: var cts = new CancellationTockenSource(); var tasks = new List<Task>(); foreach (DataInfo item in GetDataInfoes()) tasks.Add(Task.Run(() => transformer.Transform(item, cts.Tocke)) .Continuewith(t => Save(t.Result), TaskcontinuationOptions.OnlyOnRanToCompletion); This code passes the Token property of the CancellationTokenSource instance to the Transform method. When you implement the Transform method, you should call the ThrowIfCancellationRequested method of the passed CancellationToken instance. This method will cause the runtime to throw an OperationCancelledException. The status of the task that is cancelled is set to Faulted.

You are developing a scheduling application by using C# and Visual Studio 2015. Your application has this type declaration (Line numbers are included for reference purposes only.): 01 public enum DaysOfWeek : short 02 { 03 None = 0 04 Sunday = 1, 05 Monday =2, 06 Tuesday =4, 07 Wednesday = 8, 08 Thursday = 16, 09 Friday = 32, 10 Saturday = 64 11 } In a single instance of the DaysOfWeek type, the application should be able to store all of the days of the week on which an event is held. Additionally, a call to the ToString() method should result in a comma-delimited list of day names. Finally, calling the static Enum.Parse<DayOfWeek>(...) generic method should be able to convert from a comma-delimited list of day names to an instance of DaysOfWeek. Which code change should you make to Line 01 to allow the DaysOfWeek enumeration to satisfy all of these requirements?

To change the enumeration to support the desired ToString() behavior, you should annotate the enumeration with the Flags attribute: [Flags] public enum DaysOfWeek : short

You are developing an application by using C# and Visual Studio 2015. You are using an unmanaged buffer for image processing. You have this code: (Line numbers are included for reference purposes only.) 01 IntPtr buffer = IntPtr.Zero; 02 int bufferSize = 2073600 * sizeof(int); 03 try 04 { 05 buffer = Marshal.AllocHGlobal(buffersize); 06 07 .. // Use the buffer 08 } 09 finally 10 { 11 if (buffer == IntPtr.Zero) 12 { 13 Marshal.FreeHglobla(buffer); 14 } 15 } You need to inform the Garbage Collector of your unmanaged memory usage so it can determine when to collect memory. Which code fragments should you add to your code? (Each correct answer presents part of the solution. Choose two.)

To correctly inform the Garbage Collector that you have allocated a large amount of unmanaged memory, you should add this line of code to Line 06: GC.AddMemoryPressure(bufferSize); To correctly inform the Garbage Collector that you have freed a large amount of unmanaged memory, you should add this line of code to Line 14: GC.RemoveMemoryPressure(bufferSize);

You are developing a business data library by using C# and Visual Studio 2015. Other developers use this library, and your classes should be built so others can inherit from them. Your classes should follow Don't Repeat Yourself (DRY) principle. Your class fields must always be correctly initialized. You should not add unnecessary methods to the public signature of your classes. You have defined this Employee class (Line numbers are included for reference purposes only.): 01 public class Employee 02 { 03 04 public Employee(string firstName, string lastName) 05 { _firstName = firstName; 06 _lastName = lastName; } 07 // additional details omitted 08 Other developers create classes that could include this Manager class (Line numbers are included for reference purpose only.): 09 public class Manager : Employee 10{ 11 protected Manager() {} 12 public Manager(string firstName, string lastName) 13 : base(fisrtName, lastName) {} 14 // additional details omitted 15 } Which constructor should you add to Line 03 to meet the requirements and complete the Employee class?

To satisfy all requirements, you should add this constructor to Line 03: protected Employee() : this(string.Empty, string.Empty) {} To satisfy the Don't Repeat Yourself (DRY) principle, it is important that all initialization is declared in a single constructor routine. In C#, you can reuse constructor logic by using constructor chaining. The this keyword is used to chain to other constructors in the current class. The base keyword is used to chain to constructors in a base class. The C# compiler automatically chains all non-chained constructors of derived classes to the parameter-free constructor of the base class. If you do not explicitly declare a parameter-free constructor of the base class. If you do not explicitly declare a parameter-free constructor in any class, the compiler generates one for you. A simple solution to maintain the DRY principle is to always include a public or protected default (parameter-free) constructor, even when the class would not otherwise require a default constructor. This constructor would then chain to the constructor with the most parameters, passing default values as the arguments.

You are developing an application by using C# and Visual Studio 2015. You have a class with this definition: public class ExplicitlyDisposable : IDisposable { void IDisposable.Dispose() { System.Diagnostics.Debug.WriteLine("Disposal was called"); } public void DoWork() { // Do some work that might throw an exception } } You need to ensure that Dispose() is called whether the class throws an exception or performs its work successfully. Which code blocks could you use to satisfy this requirement? (Each correct answer presents a complete solution. Choose two.)

When a class implements the IDisposable system interface, it is important to ensure the Dispose() method is called before the object is released to the .NET Garbage Collector. You could use this code to ensure Dispose() is called: var target = new ExplicitlyDisposable(); try { target.DoWork(); //Do other work } finally { if (target != null)((IDisposable)target).Dispose(); } The finally block contains code that executes whether the code in the try block completes successfully or terminates with an exception. It is important to check the object reference for null so the code in the finally block does not throw a NullReferenceException that would hide the original error. This line from the ExplicitlyDisposable class indicates that the Dispose() method is explicitly implemented: void IDisposable.Dispose() This hides the Dispose() method from the compiler unless you first cast the object reference to the IDisposable type. As an alternative, you could also use this code to ensure Dispose() is called: using (var target = new ExplicitlyDisposable()) { target.DoWork(); // Do other work } The using statement is a shortened syntax that ensures the Dispose() method is called when the code block completes sucessfully or with an exception. This statement also ensures that a NullReferenceException is not thrown.

You are developing a business data library by using C# and Visual Studio 2015. You need to implement a PhoneNumber class. The PhoneNumber class must store only the ten digits necessary for North American Numbering Plan (NANP) telephone numbers. Your library must also provide an additional class to format a PhoneNumber instance as (XXX)XXX-XXXX when using the String.Format() static method with any format specifier (such as {0:G}) in the format string. You have already written this code: (Line numbers are included for reference purposes only.) 01 public class PhoneNumber 02 03 { 04 private string_digits; 05 private string Digits { 06 get ( return this._digits;} 07 set { 08 if(value.Length !=10) throw new ArgumentException(); 09 this._digits = value; 10 } 11 12 13 } 14 public class PhoneNumberFormatter 15 16 { 17 18 19 } What should you do to complete the requirements? (Choose all that apply.)

When designing classes, it is desireable to separate the business logic from the presentation logic, which is the Separation of Concerns principle. To create formatting logic separate from your data class, you should implement the IFormatProvider and ICustomFormatter .NET system interfaces. In the sample code, these interfaces should both be implemented in the PhoneNumberFormatter class. The basic process is as follows: 1) Call the String.format() method, providing an instance of any class that implements IFormatProvider. 2) The String.Format() method calls the GetFormat() method of the IFormatProvider instance, passing the Icustomformatter datatype as the argument. 3) If the IFormatProvider instance can provide an instance of the datatype arguments, it returns an instance of that type; otherwise, it returns null. NOTE: The class that implements IFormatProvider is generally the same class that implements ICustomFormatter, so the GetFormat() method includes the line "return this;". 4) the String.Format string, the object to be formatted, and the IFormat Provider instance. 5) The Format() method of the ICustomFormatter() instance returns the string representation of the object to the String.Format() method. This string is incorporated into the larger format string of the call to StringFormat() method.

You are creating a C# application by using Visual Studio 2015. You have created a custom attribute using the code below. [system.AttributeUsage(System.AttributeTargets.Class | system.AttributeTargets.Struct)] public class Documentation: system.Attribute { private string Author; public string Modified; public Documenation(string Author) { this.Author = Author; Modified = dateTime.Now.Tostring(); } } You need to apply the attribute. Which two lines of code could you write? (Each correct answer presents a complete solution. Choose two.)

You could use the following line of code: [Documentation("Jay Adams", Modified = "12/01/2015")] This code correctly uses "Jay Adams" as a positional parameter for the Author member of the Documentation attribute, and "12/01/2015" as a named parameter for the Modified member of the Documentation attribute. Because Author is a private member used in the constructor, it must be used as a positional parameter and cannot be used as a named parameter. Because Modified is a public member that is not listed as a parameter of the constructor, it must be called as a named parameter and cannot be used as a positional parameter. As an alternative, you could use the following line of code: [documentation("Jay Adams")] This code correctly uses "Jay Adams" as a positional parameter for the Author member of the Documentation attribute. A parameter for Modified is not required. Modified is initialized in the constructor.

You are developing a data-processing library by using C# and Microsoft Visual Studio 2015. You must implement a method to find a given value in three-dimensional arrays. You have declared this code: private DataPoint findData(object value, object[, ,] data) { var rank0 = data.GetLength(0); var rank1 = data.GetLength(1); var rank2 = data.GetLength(2); DataPoint result = null } The FindData method should search through the data parameter until it finds the value argument. If the value is found, a new DataPoint instance with the index values for each dimension of the array should be returned. If the value is not found, the method should throw an exception. Your code should return the result immediately upon finding the matching value because it processes very large arrays. Which two code blocks correctly complete the FindData method? (Each correct answer presents a complete solution. Choose two.)

You could use this code block to complete the FindData method: for (int i = 0; i < rank0; i++) for(int j = 0; j < rank1; j++) for(int k = 0; k < rank2; k++) if(data[i,j,k] == value) { result = new DataPoint { R0 = i, R1 = j, R2 = k }; goto EndSearch; } EndSearch: if (result !=null) return rsult; else throw new Exception(); The goto keyword is a convenient way to break out of nested loops. The goto keyword is followed by a label. A label is an identifier that is followed by a colon (:) and then a statement. The goto statement forces execution to immediately jump to the statement that follows the label. Labels must be declared within the scope of a goto. The label may be declared within any block that directly or indirectly contains the goto keyword. The label must be dclared within the same method as the goto keyword. The label must not be declared within a code block that does not directly or indirectly contain the goto keyword. Using goto in this example allows you to centralize the logic that determines when the algorithm is complete. The tradeoff is that many developers are uncomfortable with using goto in their code. Or you could use this code block to complete the FindData method: for (int i = 0; i < rank0 && result == null; i++) for (int j = 0; j < rank1 && result == null; j++) for (int k = 0; k < rank2 && result == null; k++) if (data[ i , j , k ] == value) result = new DataPoint { R0 = i, R1 = j, R2 = k }; if (result !=null) return result; else throw new Exception(); This code block uses a for loop with a compound Boolean expression to control the loop. The middle expression of a for loop may be any Boolean expression. You avoid using goto when you use a com0pound Boolean expression. The tradeoff is that your Boolean expressions become more complex, which can make the logic more difficult to read and modify.

You are developing a service library by using C# and Microsoft Visual Studio 2015. You must implement several service contract interfaces in a single class. These interfaces are already declared: [ServiceContract] public interface DropShipServiceV1 { [OperationContract] StatusCode DropShip(DropShipInfo shipInfo, Product[] products); } [ServiceContract] public interface DropShipServiceV2 { [OperationContact] StatusCode DropShip(DropShipInfo ship Info, Product[] products); } The implementation details for each of these interfaces are different. You must implement both interfaces in a single class. Which code block should you use? (Each correct answer presents a complete solution. Choose two.)

You could use this code block: public class DropShipImplementation : DropShipServiceV1, DropShipServiceV2 { StatusCode DropShipServiceV1.DropShip( DropShipInfo shipInfo, Product[] products) { // implementation omitted} StatusCode DropShipServiceV2.DropShip( DropShipInfo shipInfo, Product[] products) { // implementation omitted} } This code explicitly implements both of the service contract interfaces in the DropShipImplementation class. To explicitly implment an interface, you should declare the implementation methods without access modifiers. The method declaration must include the interface name, followed by the dot operator (.), follwed by the actual method name. You should use explicit implementation when your code requires a different implementation for two or more methods with the same signature declared in different interfaces. You could use this code block: public class DropShipImplementation : DropshipServiceV1, DropShipServiceV2 { StatusCode DropShipServiceV1.DropShip(DropShipInfo shipInfo, Product[] products) { // implementation omitted } public StatusCode DropShip( DropshipInfo shipInfo, Product[] products) { // implementation omitted } } This code explicitly implements the DropShipServiceV1 interface. The DropShipserviceV2 interface is implicitly implemented. Generally, you may implicitly implement as many interfaces in a single class as you require. However, when two or more methods have an identical signature, you must explicitly implement all similar methods except for one.

You are developing a class library by using C# and Visual Studio 2015. Developers who write Component Object Model (COM)-based applications need to use one of the classes in your library. Your library includes this code: [ComVisible(true)] public class PolicyQuoter { public decimal GetAutoQuote(int customerId) { // implementation omitted } public decimal GetLifeQuote(int customerId) { // implementation omited } public decimal GetADDQuote(int customerId) { // implementation omitted} } You need to export only the PolicyQuoter class into a COM Type Library. What should you do? (Choose all that apply.)

You should add this attribute to AssemblyInfo.cs: [assembly: ComVisible(false)] When the Comvisible attribute is applied to an assembly, the boolean argument is treated as the default for all types in the library. in this example, PolicyQuoter is the only class that should be exported to a COM Type Library. By setting Comvisible to false for the whole assembly, only types that are annotated with [Comvisble(true)] are exported. The AssemblyInfo.cs file is the conventional file that contains all attributes that apply to the whole assembly. You should add this attribute to Assembly Info.cs: [assembly: Guid("C358E7BE-7516-473C-BB4C-CC8953DAF437")] To expose types from a .NET assembly as COM interfaces requires that the assembly is uniquely identified with a Globally Unique ID (GUID). The Guid attribute should be applied to the assembly, and optionally to any type that will be visible to COM. If you do not explicitly annotate COM-visible types with the Guid attribute, the export process generates a Guid for you. You should run this command after building the assembly: tlbexp MyAssembly.dll The Type Library Export utility (tlbexp.exe) is installed with Visual Studio 2010 or as part of the Windows Platform SDK. This utility will create a COM Type Library that exposes managed code to COM. In this example, it will create a file named MyAssembly.tlb that can be registered with the Microsoft Windows operating system, and then called by a COM application.

You use Microsoft .NET Framework 4.5 to create application. This code exists: [PrincipalPermission(SecurityAction.Demand, Role="BUILTIN\\Users")] static void SaveData() { } static void Main() { SaveData(); } When the SaveData method is called, an exception of type SecurityException is thrown with the message: Request for principal permission failed. You ensure that the user running the application is a member of the BUILTIN\Users group. You need to solve this problem. What should you do?

You should add this code before the call to SaveData: Appdomain.Currentdomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); The setPrincipalPolicy method of the Appdomain class allows you to specify how the principal associated with the application should be created. A principal is simply a user with a set of roles. By specifying PrincipalPolicy.WindowsPrincipal as the parameter, you instruct the runtime to construct a Windows user with roles that represent the user's groups. This principal is then attached to the current thread. All requests for a specific principal examine the current thread for the attached principal. If you do not call the SetPrincipalPolicy method, the runtime authomatically creates a generic principal o ftype GenericPrincipal with no roles assigned.

You are developing a web service by using C# and Visual Studio 2015. Your service performs data encryption and decryption operations for other applications. After completing each operation, the company-wide logging system must be used to log information about the data that was encrypted and the application that made the request. To make effective use of available parallel processing resources, you have decided to use the Task Parallel Library (TPL). The logging system is encapsulated by a single class, companyLogger. This class uses a series of instance methods to perform the logging operations required by your service. This class is not thread safe. You need to integrate the standard CompanyLogger class with your service. You have decided to make a separate instance available to each thread in your service. Which two statements should you add to make a thread safe CompanyLogger instance available to each thread? (Each correct answer presents part of the solution. Choose two.)

You should add this field to the class: private static ThreadLocal<CompanyLogger> logger; this statement declares a field that is shared by all instances of the service class. This field is declared as the TreadLocal<comapnyLogger>generic type. The ThreadLocal class has a Value property that returns an instance of the CompanyLogger class. Each thread that accesses the Value property receives a unique instance of the CompanyLogger class. Because TPL uses ThreadPool threads, there might be many tasks that operate on any single thread. This implementation of ThreadLocal allows multiple tasks on the same thread to resuse the same CompanyLooger instance. You should also add this initialization to the static constructor of the service class: logger = new ThreadLocal<CompanyLogger>(() => new CompanyLogger()); This statement uses the constructor overload that accepts a Func<CompanyLogger> delegate. This delegate is a factory method that is used by ThreadLocal to initialize the Value property every time a new thread accesses this property. The delegate is only invoked as needed to ensure that the minimum number of instances are created.

You use Microsoft .NET Framework 4.5 to create an application. This code exists to send data over the network (line numbers are included for reference only): 01 TcpClient client = new TcpClient("192.168.1.2", 500); 02 using (NetworkStream networkStream = client.GetStream()) 03 { 04 StreamWriter writer = new StreamWriter(networkStream); 05 writer.Write("Sending Network Data"); 06 } When the code runs, you discover that no data is sent to endpoint 192.168.1.2 You verify that the server is configured to accept incoming TCP connections over port 500. You need to solve this problem. What should you do?

You should add this statement between lines 05 and 06: writer.Flush(); The Flush method of the StreamWriter class causes all buffered data to be written to the underlying stream. In this scenario, the underlying stream is a NetworkStream instance. The problem is that data is being buffered, but not actually sent over the network. Calling the Flush method forces data to be sent over the network.

You use Microsoft .NET Framework 4.5 to create an application. This code exists: private void GenerateImage(Chart chart) { if (chart == null) retunr; using(FileStream stream = File.OpenWrite("Chart.img")) { chart.SaveImage(stream); } } Before you release the application, you need to ensure that the chart instance is never set to a null reference. You want to be notified with a message box if it is. for the release version of the application, the message box should not display, and execution should continue uninterrupted. You need to make changes to the code to accomplish your goal. What should you do?

You should add this statement to the beginning of the method: Debug.Assert(chart !=null); The Assert method of the Debug class tests whether the specified condition is true. If it is false, it halts execution and displays a message box. However, this only happens in a debug configuration. In a release configuration, the Assert method of the Debug class has no effect.

You are creating a C# application by using Visual Studio 2015. You are using the Spy++ tool for debugging your application. You need to ensure that you use the tool correctly. For each of the following statements, select Yes if the statement is true of No if the statement is false.

You should answer No for You must use spy++ x64 if you are using a 64-bit CPU. the 32-bit version of Spy++ can be used to debug on 64-bit CPUs because Visual Studio is a 32-bit product. You would need to use the 64-bit version if the debug output was being redirected to a process running in a 64-bit window. You should answer No to You must keep Visual studio open while you use Spy++. Once Spy++ is started, Visual Studio can be closed. Syp++ can even be started from the command line without ever opening Visual Studio. You should answer Yes to Spy++ allows you to view the status of each thread. One of the core features of Spy++ is the ability to see every thread being used by the application. You should answer Yes to spy++ allows you to view the Windows messages handled by each process. One of the core features of Spy++ is the ability to see all Windows messages sent to each process in the application.

You are creating a C# application by suing Visual Studio 2015. You are writing a function to validate email addresses that are entered in your application. You have found the following regular expression by using a Bing search. ^[a-z0-9](\.?[a-z0-9_-]}{0,}@[a-z0-9]+\.([a-z]{1,6}\.)?[a-z]{2,6}$ You need to ensure that this regular expression will correctly validate an email address. For each of the following statements, select Yes if the statement is true or No if the statement is false.

You should answer No to The dollar sign ($) indicates that the search should start at the beginning of the line of input. The dollar sign ($) in a regular expression indicates that the search should stop at the end of the item, not at the beginning. The caret (^) indicates that the search should start at the beginning. You should answer Yes to You must use RegexOptions.IgnoreCase for this expression to work for upper and lowercase. The current regex statement uses the a-z construct to find text characters. However, this will only find lowercase characters. To insure that uppercase characters are also included, you must use the RegexOptions.IgnoreCase enumeration value. If the regex construct had been a-zA-Z, then this would not be necessary. You should answer No to this regular expression allows numbers in the top-level domain. The expression for the top-level domain is [a-z]{2,6}, which allows tow to six letters between a and z and no numbers. You should answer No to This regular expression allows an underline _ and a period (.) in the part of the email address before the at sign (@). The expression before the at sign (@) is (\.?[a-z0-9_-]){0,}. This allows zero or one periods (.) followed by any number of letters, numbers, underlines (_), and dashes(-). You should answer No to This regular express requires that the top-level domain must have 3 characters. The expression for the top-level domain is [a-z]{2,6}, which allows two to six letters between a and z.

You are creating a C# application by using Visual Studio 2015. Your application creates unmanaged resources. You have started the following method: protected virtual void Dispose(bool disposing) You need to complete the method using the Dispose pattern. For each of the following statements, select Yes if the statement is true or No if the statement is false. If disposing is false, the method has been called from the finalizer. If disposing is false, it is safe to access unmanaged objects. If disposing is true, it is safe for you to dispose of unmanaged objects. This method should be used to centralize disposition of all unmanaged objects.

You should answer Yes for If disposing is false, the method has been called from the finalizer. If the method is called by a finalizer, then disposing is set to false, indicating that the System.Object finalizer invoked the Dispose method, so objects should not be accessed because they might have already been finalized. You cannot control the order in which objects are finalized by the finalizer. You should answer No for If disposing is false, it is safe to access unmanaged object.. If disposing is false, then this method was called by the finalizer and the resource might no longer be allocated. You should answer Yes for If disposing is true, it is safe for you to dispose of unmanaged objects. If disposing is set to true, then this method has been called by the IDisposable.Dispose method and it is now safe to dispose of the unmanaged resource being handled by this class. You should answer Yes for This method should be used to centralize disposition of all unmanaged objects. All disposition of unmanaged objects should occur in a method with this signature. This ensures that unmanaged objects are not released prematurely and that duplicate calls to release the objects are handled correctly.

You use Microsoft .NET Framework 4.5 to create an application. This class exists: public class Claim { public string Number {get; set;} public DateTime date {get; set;} } This code exists to serialize an instance of Claim as XML: claim claim = new Claim{Number="12345", Date=DateTime.Now}; DateContractSerializer serializer = new DataContractSerializer(typeof(Claim)); MemoryStream stream = new Memorystream(); serializer.WriteObject(stream, claim); You must ensure that the claim instance is serialized as XML. What should you do?

You should apply the DataContract attribute to the Claim class and the DataMember attribute to the Number and Date properties. The DataContractSerializer class uses the DataContract attribute or the Serializable attribute to determine whether or not to serialize a class. If you use the Serializable attribute, the DatacontractSerializer class serializes all members that are not marked with the NonSerialized attribute. If you use the DataContract attribute, the DataContractSerializer class serializes all members that are explicitly marked with the DataMember attribute.

You use Microsoft .NET Framework 4.5 to create an application. This class exists: public class Payment { public double Amount; public string CardNumber; public string Payee; } You plan to use the BinaryFormatter class to serialize instances of Payment. You must ensure that the CardNumber field is not serialized. You need to modify the Payment class to ensure that it gets serialized correctly. What should you do?

You should apply the Serializable attribute to the Payment class and the NonSerialized attribute to the CardNumber field. The BinaryFormatter serializes classes that are marked with the Serializable attribute or those that implement ISerializable. The NonSerialized attribute specifies that a field should not be serialized.

You use Microsoft .Net Framework 4.5 to create an application. When you debug the application, you realize that an instance of the Customer class shows the type name of the Customer as the Value in the Watch window. You need to ensure that the Value property in the Watch window shows the Name property of the Customer class during debugging. Which attribute should you apply to the Customer class?

You should apply this attribute to the Customer class: [DebuggerDisplay("{Name}")] This attribute specifies how a type should be displayed in the Watch window of the debugger. Literals between curly braces {} represent expressions. {Name} indicates that the value of the Name property should be displayed fo rthe customer instance.

You use Microsoft .NET Framework 4.5 to create an application. A Microsoft SQL Server 2012 stored procedure is implemented with this statement: SELECT * from dbo.Claim WHERE ClaimType=2 FOR XML AUTO You create a SqlCommand instance to call the stored procedure. You need to call a method of the Sqlcommand instance to process the results returned by the stored procedure. Which method should you call?

You should call the ExecuteXmlReader method. This method allows you to process XML results that are returned from a query. In this scenario, the SQL statement uses the clause FOR XML AUTO. This clause returns a result set as XML data, automatically generating nested elements to represent field names and values.

You use Microsoft .NET Framework 4.5 to create an application. This code exists: PerformanceCounter pc = new PerformanceCounter("Page Hits", "order", false); This code creates a performance counter that monitors the number of hits to an Order page. You need to increase the number of hits by one. Which code segment should you use?

You should call the Increment method. This method increments the value of the performance counter by one.

You use Microsoft .NET Framework 4.5 to create an application. This class exists: public class Group { public int Id {get; set;} public string Name {get; set;} public static IQueryable<Group>GetGroups() { // Implementation Omitted // This code queries a Microsoft SQL Server database for a list of groups } } This code exists: var query = from g in Group.GetGroups() select g.Name; when you run the application, the previous code statement executes, but no queries are sent to the database server. You ensure that data exists and that the GetGroups method is implemented correctly. You need to force execution of the database query. What should you do?

You should call the ToList method of the query variable. The query variable's type is IQueryable<Group>. A LINQ query is converted to a command tree at compile time. At runtime, the command tree is converted to the appropriate data source query and then executed at the data source, but only when the query is requested to be iterated. One way to force execution of a query is to call the ToList method. This forces the LINQ engine to query the underlying data source and return the results as a list. Because of this delayed execution, you can combine multiple LINQ queries together, such as with joins, and the LINQ engine converts the queries to efficiently execute at the data source.

You are developing an application by using C# and Visual Studio 2015. You are implementing INotifyDataErrorInfo in a class that will be used for data binding. You have these classes: (Line numbers are for reference only.) 01 public class Customer 02 { 03 public decimal CreditLimit {get; set;} 04 public decimal Type { get; set; } 05 public IEnumerable GetErrors() 06 { 07 return new CreditLimitValidator(this); 08 } 09 } 10 public class CreditLimitValidator 11 {} You need to complete the CreditLimitValidator class. Which code blocks correctly comoplete the CreditLimitValidator class? (Each correct answer presents part of the solution. Choose all that apply.)

You should change line 10 to read: public class CreditLimitValidator : IEnumerable This implements the System.collections.IEnumerable interface in the CreditLimitValidator class. The IEnumerable interface is used by the foreach loop to faciliate iterating through a forward-only, read-only collection of elements. You should add to the block at line 11: public IEnumerator getEnumerator() { // omitted } The GetEnumerator method is the only method declared in the IEnumerable interface. This method returns an instance of IEnumerator. The IEnumerator interface describes a class that exposes the methods necessary to start, stop, reset, and move progressively through a forward-only, read-only collection. Instances of IEnumerator are used by the compiled code that results from using foreach loop.

You are creating a C# application by using Visual Studio 2015. You have created a custom attribute using the code below: [System.AttributeUsage(System.AttributeTargets.Class | system.AttributeTargets.Struct)] public class Documentation: system.Attribute { private string author; public string Modified; public Documentation(string Author) { this.Author = Author; Modified = DateTime.Now.Tostring(); } } You need to apply the attribute. For each of the following statements, select Yes if the statement is true or No if the statement is false.

You should choose Yes for Author can be used as a positional parameter. Private data members that are included in the constructor of custom attributes are always used as a positional parameter and they cannot be used as named parameters. You should choose No for Modified can be used as a positional parameter. Public data members of a custom attribute are always used as named parameters and cannot be used as positional parameters. You should choose No for Author can be used as a named parameter. Private data members that are included in the constructor of custom attributes are always used as positional parameters and they cannot be used as named parameters. You should choose Yes for Modified can be used as a named parameter. Public data members of a custom attribute are always used as named parameters and cannot be used as positional parameters. You should choose No for Documentation attribute can be applied to a method. The System.AttributeTargets.Class | System.AttributeTargets.Struct usage attributes specify that this attribute can only be applied to a class or struct. To target methods, System.AttributeTargets.method would have to be added to accepatable usage attributes.

You are writing a C# application by using Visual Studio 2015. You need to create a data type to hold only one of three possible categories. The data type should meet the following requirements: * Each category should be a value. * One value must be "Unknown". * One value, "Count", should be equal to the total number of categories, and this value should automatically update if a new category is added. You need to complete the code. Line numbers are included for reference. Which code should you write? Use the drop-down lists to correctly complete the code.

You should choose enum for line 01. An enum is a data structure that allows you to use names as if they were integers. Each name in the enum is assigned an integers, starting with zero, and each additional name is assigned the next higher integer. You should choose Unknown for the first target in line 03. Unknown needs to be the first declaration because it will be set to -1. This will make Palnt = 0, Animal = 1, Mineral =2, and count = 3 (which is the total number of categories). You should choose -1 for the second target in line 03. This sets Unknown to -1 and makes Plant = 0, Animal = 1, Mineral -2, and Count = 3 (which is the total number of categories). You should choose Count for line 07. By placing Count as the last item, and setting Unknown to -1, Count will always be the number of categories, even when you add new categories to the list (as long as they are placed between Unknown and Count).

You are creating a C# application by using Visual Studio 2015. You are designing a class to manage customers and you have written the code below. (Line numbers are included for reference only.) 01 class Customer 02 { 03 string account; 04 bool verified; 05 string Account() 06 { 07 if(Verified) 08 { 09 return account; 10 } 11 return ""; 12 } 13 bool Verified 14 { 15 get { return verified; } 16 set { verified = value; } 17 } 18 } The class must meet the following requirements: * Assemblies external to the file this class is defined in should not be able to access the class or its members. * The member variables can only be accessed by methods in the Customer class. * The Account property can be exposed by any instance of the Customer class and classes that derive form it. * The Verified property can only be accessed from methods in the Customer class or classes that derive from it. Which accessors should you apply to the code? Select each accessor and place it next to the correct code line number.

You should choose internal for line 01. A class prefixed by the internal access modifier can only be accessed from the file the class is defined in. This means that external assemblies and classes defined in other files will not be able to instantiate this class. You should choose private for line 03. A private member variable can only be accessed by methods in the class it is defined in. This means that it will not be exposed to instances of the class, and it will not be accessible from classes that derive from this class. You should choose private for line 04. A private member variable can only be accessed by methods in the class it is defined in. This means that it will not be exposed to instances of the class, and it will not be accessible from classes that derive from this class. You should choose public for line 05. A public variable is exposed to instances of the class it is defined in as well as any classes that derive from this class. This allows programs to have direct access to the Account property. You should choose protected for line 13. A protected variable can be accessed by methods in the class it was defined in or any classes that derive from that class, but it is not exposed to instances of those variables.

You are creating a C# native application by using Visual Studio 2015. You need to debug a crash that is occuring in a third party COM object. What should you do?

You should choose select the Load DLL Exports option in the Debugging General options. This feature scans and exports debug symbols from external files including COM objects. Because this adds overhead, the option is turned off by default.

You are creating a C# application by using Visual Studio 2015. You are implementing performance counters in the code to monitor performance. You need to create a timer that allows you to track the amount of time that has passed since the process started. Which block of code should you write?

You should choose the block of code below: CounterCreationDataCollection counter = new CounterCreationDataCollection(); CounterCreationData data = new CounterCreationData(); data.CounterType = PerformanceCounterType.ElapsedTime; data.CounterName = "Time"; counter.Add(data); This code creates a new CounterCreationDataCollection, which is a container for CounterCreationData objects that define each counter. It then creates a CounterCreationData object, sets the parameters CounterType and CounterName, and then adds it to the container. CounterType is correctly set to the type PeformanceCounterType.ElapsedTime.

You are creating a C# Windows Communication Foundation (WCF) client by using Visual Studio 2015. You need to create and install a self-signed SSL certificate and install it on development computer. Your client will use the certificate to encrypt messages. What should you do? Select the four steps that you should perform. Place your selections in the order in which actions must be completed.

You should choose the following steps in order: * Generate a self-signed root authority certificate and private key file. * Generate a certificate signed by a root authority certificate. * Import the certificate in Trusted Root Certification Authorities. * Configure the clientCertificate setting in the configuration file. First, you must generate a self-signed root authority certificate and use the flags to export a private key file. The private key file is then used as input for the second step, which creates another certificate signed by the root authority certificate you created in the first step. The third step is to import the certificate in Trusted Root Certification Authorities. Finally, to use this certificate in your client application, you must configure the clientCertificate setting in the application's confugration file.

You are creating a C# Windows 8 desktop app by using Virtual Studio 2012. You create a project. You want to enable access to the globalization features in the WinRT API from inside Visual Studio. What should you do? Select the four steps that you should perform. Place your selections in the order in which the action should be performed.

You should choose the following steps in order: * Unload the project. * Set the TargetPlatformVersion in the .csproj file. * Reload the project. * Add a reference to the Windows.winmd. Because you have already opened the project in Visual Studio, you must unload the project before you will be allowed to edit the csproj file. Second, you must set the TargetPlatformVersion in the csproj file. The third step is to reload the project. The fourth step is to add a reference to Windows.winmd. This file will not show up as a choice until you have performed the first three steps in order.

You are creating a C# application by using visual Studio 2015. The application writes random words to a document as part of a process that creates dummy documents of various sizes. You have created the code below. (Line numbers are included for reference only.) 01 public class Docbuilder 02 { 03 List<string> dict; 04 StringBuilder doc; 05 DocBuilder() 06 { 07 initDictionary(); 08 } 09 StringBuilder BuildDoc(ulong words) 10 { 11 int index; 12 doc = new StringBuilder(5000, 40000); 13 Random pick = new Random(); 14 for(ulong i = 0; i < owrds; i++) 15 { 16 17 { 18 index = pick.Next(dict.Count()); 19 doc.Append(dict[index]); 20 } 21 } 22 return doc; 23 } 24 } The InitDictionary function intializes the dict list and fills it with words. You need to protect doc from exceeding the 40,000 characters, while still allowing the string to reach the maximum allowed length. Which line should you add at line 15?

You should choose the line of code below: if(doc.Length + dict[index].Length <= doc.MaxCapacity) The StringBuilder class dynamically allocates memory as necessary to build the string by increasing the capacity until the maximum capacity defined as the second parameter of the constructor is reached. Although the append method can cause the StringBuilder object to grow beyond the defined maximum capacity, this is not desired in this scenario. The Length property indicates the current length of the string builder, and the MaxCapacity property indicates the maximum capacity of the StringBuilder. If the current length plus the length of the new string are less than or equal to the maximum capacity, then it is appropriate to append the new string.

You use Microsoft .NET Framework 4.5 to create an application. You create a performance session and generate the report shown in the graphic exhibit. What can you conclude about the performance of the application?

You should conclude that the CheckUsage, CheckIpAddress, and CheckCredentials methods have performance bottlenecks. Both the Main method and the AuthenticateUser method have the same inclusive sample percentage, which is 75.4. This is the same as the total inclusive sample percentages for CheckUsage, CheckIpAddress, and CheckCredentials. This means that the Main method only calls AuthenticateUser. The authenticateUser method only calls CheckUsage, CheckIpAddress, and CheckCredentials. Therefore, the bottleneck must be in these three methods, or in methods called by these three methods.

You use Microsoft .NET Framework 4.5 to create an application. This configuration exists: <configuration> <system.diagnostics> <switches> <add name="mySwitch" value="1'/> </switches> <sources> <source name="MySource"> <listeners> <add name="messages" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\ServiceLog,xml"/> </listeners> </source> </system.diagnostics> </configuration> this code exists: TraceSwitch switch = new TraceSwitch("mySwitch", null); if (switch.TraceError) Trace.TraceError("Error");if (switch.TraceWarning) Trace.TraceWarning("Warning"); if (switch.TraceInfo) Trace.TraceInfo("Info"); if (switch.TraceVerbose) Trace.TraceVerbose("Verbose"); You need to determine the output of the previous code. In the list on the right, select the messages that will be written to the trace output. Place your selecitons in the list on the left in the order in whcih the messages are written. 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.

You should concolude that only the message Error is written to the trace output. the code uses a trace switch named mySwitch to determine the trace level. When you create a TraceSwitch instance, it checks the configuration for the value of the switch. In this scenario, the switch is set to value 1. This means that only errors are written to the trace output. The code checks the Trace.TraceError property to determine whether to call teh Trace.TraceError method. This property returns true because the switch is set to value 1. If you set the switch to 2, then errrors and warnings are written. If you set the switch to 3, error, warnings, and informational messages are written. If you set the switch to 4, error, warnings, informational messages, and verbose messages are written.1

You use Microsoft .NET Framework 4.5 to create an application. This class exists: [Datacontract] public class Customer { [DataMember] public string Name {get; set;} [DataMember] public Account Account {get; set;} } The Account class is defined in a separate assembly over which you have no control. You write this code: Customer customer = new Customer(); customer.Name = "Jane Doe"; customer.Account = GetAccount(); DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Customer)); MemoryStream stream = new MemoryStream(); json.WriteObject(stream, customer); When the code executes, the properties of the Account class do not get serialized. You need to ensure that properties of the Account class get serialized. What should you do?

You should create a class that implements IDataContractSurrogate and pass an instance of this class to the DataContractJsonSerializer constructor. The IDataContractSurrogate interface allows you to override serialization specified by the DataContract and DataMember attributes. This is necessary if you need to serialize a member whose type is not marked with DataContract and DataMember attributes. In this scenario, the Account class is defined in a separate assembly. When you implement the IDataContractSurrogate interface, you specify a surrogate type that is used during serialization and deserialization. For example, you can define a new class named AccountSurrogate that has all the same members as the Account class. You can mark the members of the AccountSurrogate class with the DataMember attribute. The IDataContractSurrogate interface can use this class when serializing and deserializing Account instances.

You use Microsoft .NET Framework 4.5 to create an application. This configuration exists: <configuration> <system.diagnostics> <switches> ,add name="mySwitch" value="Data Access"/> </switches> </system.diagnostics> </configuration> You need to programmatically obtain the value of the mySwitch switch in code. What should you do?

You should create a custom class that inherits from Switch and examine its Value property. The Switch class is a base class for diagnostic switches. Because the value attribute in this scenario is set to Data Access, you cannot use the existing Switch-derived classes to obtain its value. The existing classes are SourceSwitch, which only understands these values (or their numerical equivalents): Critical, Error, Warning, Information, Verbose, Start, Stop, Suspend, Resume, and Transfer; TraceSwitch, which only understands these values (or their numerical equivalents): Off, Error, Warning, Info, Verbose; and BooleanSwitch, which only understands these values (or their numerical equivalents): False, True.

You use Microsoft .NET Framework 4.5 to create an application for your company. The application must communicate securely with the Department of Motor Vehicles (DMV). The DMV must be sure that data sent from your application was not modified while in transit. You need to secure the data to be sent to the DMV. What should you do?

You should hash the data, encrypt the has with your company's private key, and send the data and the encrypted has to the DMV. to ensure the integrity of data that is transmitted, you should sign the data. This consists of encrypting a hash of data with a private key. Hashing is a one-way algorithm that generates a unique has for the given data. If you encrypt the has with a private key, only a corresponding public key can decrypt the encrypted hash. The DMV can decrypt the encrypted hash with the public key. The DMV can then re-hash the original data that is sent to it, and compare its own hash to the decrypted has. If the two values match, then the DMV can be sure that the data was not modified in transit, because only your company hsould have access to the private key that encrypted the hash.

You are developing a class library by using C# and Microsoft Visual Studio 2015. You need a hierarchy of classes to represent different types of customers. You define a Customer base class to use in applications. Each class that derives Customer needs to implement different details for each type of customer. Applications that use any Customer-derived class should be able to use the methods of the Customer base class to access specialized functionality. Different types of Customer require different maximum credit limits. You need to implement the CreditLimit property. The Customer base class should not permit credit limits greater than 5,000. The PremierCustomer derived class should not permit credit limits greater than 100,000. Finish the class definition by dragging the code samples from the left to the appropriate location on the right. You may use each item more than once, and you do not have to use every item.

You should implement the Customer class hierarchy by using this code: public class Customer { private decimal _creditLimit; public decimal CreditLimit { get { return this._creditLimit;} set { this.OnCreditLimitChanging(value); this._creditLimit = value; } } protected virtual void OnCreditLimitChanging (decimal creditLimit) { if (creditLimit > 5000) throw new ArgumentException(); return; } } public class PremierCustomer : Customer { protected override void OnCreditLimitChanging (decimal creditLimit) { if (creditLimit > 100000) throw new ArgumentException(); return; } } In the Customer base class, you should use this code sample: virtual void OnCreditLimitChanging The virtual keyword tells the .NET runtime that the method declared in the Customer class might be overridden by derived classes. If the derived class declares a method with the exact same name and signature and includes the overrides keyword, the .NET runtime will execute the method from the derived class instead of the base class. This is a key feature of polymorphism. In the PremierCustomer derived class, you should use these code sample: override void OnCreditLimitChanging The override keyword tells the .NET framework that the method declared in the PremierCustomer class should be selected at runtime instead of the method with the same name and signature in the base class. A derived class may only override methods declared in the base class with the virtual keyword.

You use Microsoft .NET Framework 4.5 to create an application. This code exists (line numbers are included for reference only): 01 public async Task ProcessPDFFiles(List<string>files) 0{2 03 foreach (string file in files) 04 { 05 using (StreamReader reader = new StreamReader(file)) 06 { 07 string data = reader.ReadToEnd(); 08 ProcessData(data); 09 } 10 } 11 Console.WriteLine("Processing complete"); 12 } It takes a long time to read each file. You must ensure that the WriteLine method of the Console class is not called until all files are processed. However, the ProcessPdfFiles method must return immediately to its caller while the files are being read and processed. You need to modify the code to accomplish your goal. What should you do?

You should modify line 07 as follows: String data = await reader.ReadToendAsync(); The ReadToendAsync method is an asynchronous version of the ReadToEnd method of the StreamReader class. The await keyword allows a method to execute asynchronously while control returns to the calling code. Control immediately returns to the code that calls the ProcessPdfFiles method. Because the method returns a Task instance, the calling code can use the Task instance to determine when the asynchronous method completes.

You use Microsoft .NET Framework 4.5 to create an application. The application references version 1.0.0.0 of an assembly named DataAccess.dll. You obtain version 3.0.0.0 of the assembly. Both assemblies exist in the global assembly cache (GAC). You need to force the application to use version 3.0.0.0 of the assembly. What should you do?

You should modify the application configuration file as follows: <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1:> <dependentAssembly> <assemblyIdentity name="DataAccess" culture="neutral"/> <bindingRedirect oldVersion="1.0.0.0" newVersion="3.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration> This configuration redirects the application from version 1.0.0.0 of DataAccess.dll to version 3.0.0.0. The assemblyIdentity element specifies the assembly to be redirected. The bindingRedirect element specifies the version to be redirected. The oldVersion attribute specifies the version from which you are redirecting, and the newVersion attribute specifies the version to which you are redirecting.

You are developing an application by using C# and Microsoft Visual Studio 2015. You have programmed the following business entity class: public class Employee : IComparable { public string Firstname {get; set;} public string LastName {get; set;} } You need to implement the IComparable pattern. Wich three tasks should you perform? (Choose three.)

You should perform these tasks: * Override the Equals(...) method. * Override the GetHashcode() method. * Implement the CompareTo(...) method. The IComparable interface is used by the .NET Framework to describe any data type that has instances that can be compared for sorting purposes. For instance, the Array.Sort() static method can sort an array of any data type (system or custom) if the data type implements IComparable. To correctly implement the IComparable interface, you should begin by implementing the CompareTo() method. This is the only method defined in the IComparable interface and is the only required component of the pattern. The CompareTo() method is an instance method that compares the current object to an object passed as the only argument. If the current object (the this reference) should sort before the argument, return -1. If the current object is the same value as the argument, return 0. If the current object should sort after the argument, return 1. In addition to CompareTo() method, a correct implementation of IComparable should (but is not required to) override the Equals(...) method. This method is inherited from the System.Object type, and is present on all classes in the .NET Framework. the responsibility of the Equals(...) method is to return true if the current object and the argument share the same values, regardless of whether they are the same actual object reference. Finally, you should override the GetHashCode() method. The GetHasCode() method is used by the .NET Framework under a variety of circumstances. For instance, if an object is used as a key in a Dictionary instance, the instance calls the GetHashCode() method. The default implementation inherited from System.Object is only valid if two instances of a type are considered equal if and only if the references are equal. In all other cases (such as when overriding Equals()), a custom implementation should be provided.

You use Microsoft .NET Framework 4.5 to create an application. This code exists to encrypt data: string original = GetString(); byte[] key = GetKey(); byte[] iv = GetIV(); byte[] encryptedData = null; using (Rijndael r = Rijndael.Create()) { r.Key = key; r.IV = iv; ICryptoTransform encryptor = r.CreateEncryptor(key, iv); using (MemoryStream ms = new MemoryStream()) { using (Cryptostream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { using (StreamWriter writer = new StreamWriter(cs)) { writer.Write(original); } encryptedData = ms.ToArray(); } } } This code exists to decrypt the data (line numbers are included for reference only): 01 using (Rijndael r = Rijndael.Create()) 02 { 03 ICryptoTransform decryptor = r.CreateDecryptor(); 04 using (MemoryStream ms = new MemoryStream(encryptedData)) 05 { 06 using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) 07 { 08 using (StreamReader reader = new StreamReader(cs)) 09 { 10 string encryptedString = reader.ReadToEnd(); 11 } 12 } 13 } 14 } When you run the previous code, you discover that the encrypted data is not decrypted correctly. You need to solve this problem. What should you do?

You should replace line 03 with this code: ICryptoTransform decryptor = r.CreateDecryptor(key, iv); This code passes the key and initialization vector to the CreateDecryptor method. This is necessary so that the same key and initialization vector that is used to encrypt the data can be used to decrypt the data. The RijndaelManaged class performs symmetric encryption, which uses the same key to encrypt and decrypt data.

You are developing an image-processing application by using C# and Visual Studio 2015. Your application uses a third-party library for performing elaborate transformations to images. The third-party library declares these methods that are used by your application: public byte[] FilterImage(byte[]); public byte[] TransformImage(byte[]); Your application declares this code to load, process, and save each image from a data source: public void ProcessImages(Uri source, Uri destination) { foreach (byte[] image in GetImages9source)) { byte[] buffer = FilterImage(image); buffer = TransformImage(buffer); SaveImage(destination, buffer); } } After profiling your application, you have determined that your application does not use the available parallel processing resources. How should you rewrite the contents of the foreach loop to correctly use available parallel processing resources?

You should rewrite the foreach loop by using this code block: Task.Run(() => FilterImage(Image)) .ContinueWith(t => TransformImage(t.Result)) .ContinueWith(t => SaveImage(destination, t.Result)); The Task.run method creates a single new Task instance for each image returned from the GetImages method. This Task represents a call to the FilterImage method. The ContinueWith method of this Task creates a child task that represents a call to the TransformImage method. This child task is known as a continuation. This child task also includes its own continuation that represents a call to the SaveImage method. The initial Task object does not complete until all child tasks have also completed. When you create new Task instances, the TaskScheduler class is responsible for assigning each Task to a background thread from the ThreadPool. The ThreadPool class uses a hill-climbing algorithm to optimize the number of concurrent threads in use for the current system load. If the hill-climbing algorithm detects that additional threads do not improve throughput, the ThreadPool queues additional tasks until an in-use thread becomes available.

You use Microsoft .NET Framework 4.5 to create a shared assembly. You plan to install the assembly in the global assembly cache (GAC). You need to prepare the assembly to be placed in the GAC. What should you do?

You should run Sn.exe. The Strong Name tool creates a strong name for an assembly, which is required for the assembly to be placed in the GAC. A strong name is a unique name for an assembly. It consists of the assembly name, version, culture, public key, and digital signature.

You use Microsoft .NET Framework 4.5 to create a shared assembly. The assembly is not exposed to COM clients. You need to install the assembly on client computers so that multiple applications can share the assembly. What should you do?

You should run the Gacutil.exe command to place the assembly in the Global Assembly Cache (GAC). this allows multiple applications to share the assembly.

You use Microsoft .NET Framework 4.5 to create a multi-threaded application. You are debugging the application. You set a breakpoint at a method named ImportImage. You need to ensure that the breakpoint is hit only when the thread's name is Thread1. Which two debugger properties allow you to accomplish your goal?

You should set the Breakpoint Filter property. The Filter property allows you to configure the debugger to break only at certain processes and threads. In this Breakpoint filter dialog box, you would specify threadName="Thread1". Alternatively, you can set the Breakpoint Condition property. This property allows you to configure the debugger to break when a certain condition is met. for example, you can configure the debugger to break when a variable is equal to a certain value. In this scenario, you can set the condition to Thread.CurrentThread.Name == "Thread1".

You use Microsoft .NET Framework 4.5 to create an application. You set a breakpoint at the beginning of a method named ProcessRequest. This is the only method in the enclosing class. You need to configure the debugger to break at the breakpoint the fifth time the ProcessRequest method is called. What should you do?

You should set the Hit count property to break when the hit count is five. The Hit Count property tells the debugger when it should break at a breakpoint. By setting it to the number five, you allow it to break only at the fifth time the ProcessRequest method is called.

You are developing an application by using C# and Microsoft visual Studio 2015. You are working on a class that requires many arithmetic calculations. Your application performs arithmetic by using the int type. You have discovered that your calculations return incorrect results when working with very large values for certain parameters. You need the calculations to fail immediately with an exception when the calculation exceeds the maximum value for the int type. What should you do?

You should use a checked statement around the calculations. The checked statement causes the .NET Common Language Runtime (CLR) to perform bounds checking during arithmetic operations contained within the block. bounds checking is a compute-intensive operation that most applications do not require. When bounds checking is enabled, the .NET CLR throws a new OverflowException instance as soon as any arithmetic expression exceeds the minimum or maximum value for the data type. The primitive numeric types expose static, read-only Maxvalue and Minvalue fields. The int type is declared as a 32-bit, signed, two's -complement number. This means that the minimum value is equal to -1*2^31, or -2,147,483,648. The maximum value for an int is 2 ^ 31 - 1, or 2,147,483,647.

You use Microsoft .NET Framework 4.5 to create an application. This class exists: public class Customer { private int customerId; public Customer(int customerId) { this.customerId = customerId; } } You write this code: Customer customer = new Customer(12345); You must serialize the customer instance to this XML: <Customer> <customerId>12345</customerId> </Customer> You plan to apply serialization attributes to the class and its members, but you cannot modify the members. You need to choose a serialization class. Which class should you use?

You should use the DataContractSerializer class. This class allows you to serialize a class and its members as XML elements. With the DataContractSerializer class, you can serialize both public and private properties and fields.

You use Microsoft .NEt Framework 4.5 to create a component. this method exists: public void AddProduct(Product product) { } The Product class contains an ID property that uniquely identifies a product. Another application calls your component to add products to the company's database. Sometimes the application might attempt to add duplicate products. You need to use a collection class that allows you to add a product only once so you cannot add a product to the collection if another product with the same identifier has already been added. If a product is retrieved from the collection, it must not be removed from the collection automatically. You need to choose a collection class. Which class should you use?

You should use the Dictionary class. This class allows you to organize data in a collection by keys. Keys must be unique. In this scenario, the product identifier if unique. Therefore, a Product instance can be stored int he collection only once.

You use Microsoft .NET Framework 4.5 to create an application. Your application receives this data from a Web service: {"ID":"Item1","ProviderParameters":[{"Key":"RateRequestType","value":"Rate"}], "ShipFromAddress": {"Street":"10 M Street Street","city":"Kennesaw","Postalcode":"30144,"State":"GA"}, "ShipToAddress": {"Street":"1 Uptown","City":"Redmond","PostalCode":"98052","State":"WA"}, "Size":{"Height":3,"Length":1,"Unit":0,"width":2},"Weight":{"Unit":0,"Value":5}} You need to ensure that this data can be converted to an appropriate type in your application. Which class should you use?

You should use the JavaScriptSerializer class. This class allows you to serialize and deserialize Java Script Object Notation (JSON) data. JSON is a data format that allows you to represent an object graph as a string literal. Within the literal object graph, each object is enclosed in curly braces {}, and each property-value pair is separated by a colon. For example, this subset of the JSON data represents a ShipFromAddress property that is set to an object instance that has Street, City, PostalCode, and State properties: "ShipFromAddress": {"Street":"10 M Street Street","City":"Kennesaw","Postalcode":"30144","State":"GA"}

You use Microsoft .NET Framework 4.5 to create an application. The application must sort instances of an Employee class in a collection. You must be able to access an Employee instance by its index in the collection. Retrieving an Employee instance must not remove the instance from the collection. You need to choose the collection class. Which class should you use?

You should use the List class. This class allows you to order items in a sizable collection. You can access each item in the collection by its index.

You use Microsoft .NET Framework 4.5 to create an application. The application must send confidential data to a Web service. You plan to use a shared key for encryption and decryption. You need to choose a class for encrypting the data. Which class should you use?

You should use the RijindaelManaged class. This class implements shared-key, or symmetric encryption, which is required in this scenario. With symmetric encryption, both your application and the Web service must know the encryption key that is used.

You use Microsoft .NET Framework 4.5 to create an application. The application must authenticate users by using passwords. You do not want to store the plaintext passwords in the database, but you want to store some type of data in the database to represent the passwords. However, there must be no way for the passwords to be decrypted. You need to choose a class to accomplish your goal. Which class should you use?

You should use the SHA1Managed class. This class uses the Secure Hash Algorithm (SHA) 1 to compute a unique hash of data. Hashing is one way, and it cannot be reversed. If you hash the passwords and store the hashed data in the database, there would be no way for any application to reverse the hashing process to reveal the passwords. When you authenticate the user, you can hash the user's input and compare it to the hashed data in the database. If the two hash values are equal, then the passwords match and the user is authenticated.

You are writing a C# application by using Visual Studio 2015. You are designing a base class that will be inherited by several other classes. The class hierarchy must meet the following requirements: * You need to define some methods in the base class that can be overridden, while other methods cannot be overridden. * You need to define some methods in the base class that do not have an implementation. These classes must be implemented by the classes that inherit from the base class. You write the following code (line numbers are included for reference only): 01 public class Weapons 02 { 03 protected int damage; 04 protected int range; 05 public int CalculateDamage(int modifier) 06 { 07 return damage * modifer; 08 } 09 public bool HasHit(int roll, int threshold); 10 } 11 public class Sword : Weapons 12 { 13 private int size; 14 public int CalculateDamage(int modifier) 15 { 16 return damage * size * modifier; 17 } 18 public bool HasHit(int roll, int threshold) 19 { 20 return roll * size < threshold; 21 } 22 } You need to choose the correct access modifier for each method. Which access modifier should you use for each method? Place the correct access modifier next to each of the line numbers. A modifier may be used once, more than once, or not at all.

You should use the abstract modifier on line 01. The abstract modifier is used to define a class that contains abstract methods. An abstract method is a method that does not contain an implementation and must be overriden and implemented by any class that inherits the abstract class. You should use the virtual modifier on line 05. The virtual modifier is used to indicate that a method in a base class can be overriden in a class that inherits the base class. The method that overrides the virtual method must be preceded by the override modifier. Because the calculateDamage method also appears in the Sword class, it must be declared as virtual in the Weapon class. You should use the abstract modifier on line 09. The abstract modifier is used to define a method that contains has no implementation. Abstract methods can only be defined in an abstract class. Any class that inherits the base class must override the method and provide an implementation for it. The method that overrides the virtual method must be preceded by the override modifier. An abstract method is automatically treated as a virtual method. Because the HasHit method does not contain an implementation, it should be declared as abstract to force the Sword class to provide an implementation. You should use the override modifier on line 14 and line 18. The override modifier indicates that a method in the current class is overriding a method that was declared as abstract or virtual in the parent class. both CalculateDamage and HasHit in the Sword class override the respective methods in the Weapons class.

You are writing a C# application by using Visual Studio 2015. The application creates an audit log of transactions. You need to ensure that the block of code to write to the log file can only be accessed by a single thread at one time. Which block of code should you write?

You should use the block of code below: public class Log<T> { private List<T> list = new List<T>(); public void Add<T entry) { Monitor.Enter(list); try { list.Add(entry); } finally { Monitor.Exit(list); } } } When you use the Monitor class to lock code, you must ensure that the monitor explicitly exists both when the code works and when there is an error. Therefore, the block of code to be locked must be placed in a try block just after the Monitor.Enter call. Then, placing the Monitor.Exit call in the finally block ensures that it is called whether an exception is thrown or not.

You are writing a C# application by using Visual Studio 2015. The application processes payments. You want to check the balance before the payment is taken from the account. You need to ensure that the block of code to check the balance can only be accessed by a single thread at one time. Which block of code should you write?

You should use the block of code below: public class Pay { private float balance; private Object L = new Object(); public void Payment(float amount) { lock (l) { if(amount < balance) { balance -= amount; } } } } This code properly creates the lock as a private object and then uses the lock on the block of code that needs to have exclusive access.

You are writing a C# application by using Visual Studio 2015. You are simulating a game of rock/paper/scissors. In each round, each player chooses rock, paper, or scissors. You want to count the number of times each move has been picked by the player. You define the following enum: enum CategoryIndex { Rock, Paper, Scissors, } You define the following array: int[] categories = { 0, 0, 0 }; Which block of code should you write?

You should use the block of code below: void AddCategories(CategoryIndex ci) { categories[(int)ci]++; } This block of code correctly casts CategoryIndex, an enum, to be an integer, so that it can be used as an index for the categories array. Because C# is a strongly typed language, you must explicitly cast an enum to the integer data type to use it as an integer.

You are creating a C# application by using Visual Studio 2015. You need to consume JSON data. You have created the following code: public class Vendor { public string Company {get; set;} public string State {get; set;} } You need to create a Vendor object from JSON data. Which code should you write?

You should use the code below: Vendor CreateVendor(string json) { DataContractJsonSerializer js = new DatacontractJsonSerializer(typeof(Vendor)); MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); Vendor vendor = (Vendor)js.ReadObject(stream); return vendor; } This code correctly creates the DataContractJsonSerializer with the Vendor class. It then creates a MemoryStream to store the deserialized data and stores the resulting data into a Vendor object.

You are creating C# application by using Visual Studio 2015. You need to write a function that removes a substring from another string. The function must return true if the substring was removed. Otherwise, it must return false. Which block of code should you write?

You should use the code below: bool RemoveString(string source, string search) { bool replaced = false; int position = source.IndexOf(search); if(position >= 0) { source.Remove(position, search.Length); replaced = true; } return replaced; } This code correctly uses the IndexOf method to return the position of the search screen within the source string. If search is not found, the method will return a -1. If the search is found, then position will always be greater than or equal to zero. You can then use this position and the Remove method to remove the string starting at position, and for the length of the search string.

You are creating a C# application by using Visual Studio 2015. You are creating an application that handles orders. You must create an interface that meets the following requirements: * The order id is read-only. * The order amount has read and write access. Which block of code should you write?

You should use the code below: interface IOrder { string Id { get; } float Balance { get; set; } } This code properly defines a get for the Id property. Any class that implements this interface will only be allowed to expose read access to the Id property. Balance has both a get and set. Any class that implements this interface will be able to expose read and write access to the Balance property.

You are developing a class library by using C# and Microsoft Visual Studio 2015. You want to implement a hierarchy of Product classes. These classes are used in other applications. You have declared this Product class: (Line numbers are for reference purposes only.) 01 class Product { 02 Product() 03 { /* constructor implementation omitted */ } 04 } The Product class is the base class for the hierarchy. It should not be possible to directly construct new instances from other applications. It should be possible for other developers to inherit from the Product class. Other classes in your library are responsible for creating new instances of Product and Product-derived classes. Which access modifiers complete the Product class to satisfy these requirements? (Each correct answer presents part of the solution. Choose two.)

You should use the public access modifier at line 01 and the protected internal access modifier at line 02. The public access modifier is required on the Product class declaration because the Product class must be usable in external assemblies. Only two access modifier keywords permit access outside of the declaring assembly: public and protected. The protected keyword does not apply to type declarations, such as classes. The protected internal access modifier is required on the Product constructor. The internal keyword is required to permit other code in the declaring assembly to invoke the constructor. The internal keyword permits access to the declared type or member from any other code declared in the same assembly. The protected keyword is required to permit access to code that inherits from the containing type declaration. Derived classes must have access to at least one constructor in the base class. The C# compiler automatically chains all derived class constructors to the default (parameter-free) constructor.

You use Microsoft .NET Framework 4.5 to create an application for Company A. Company B sends data to Company A through a Web service. You need to verify that the data received by the Web service was not modified in transit, and that it did indeed come from Company B. both companies use public key cryptography. Which key should you use to decrypt the hash of the data?

You should use the public key from Company B. To ensure data integrity, you must verify a digital signature. Company B creates a digital signature by hashing the data, and then encrypting the hash with its private key. It sends the data and the encrypted hash to Company A. Only the corresponding public key can decrypt the hash, which is why you need to use the public key form Company B. When you decrypt the hash, you can rehash the data and compare the two hash values. If they match, you have proof that the data was not modified in transit.

You are developing a data-processing application by using C# and Visual Studio 2015. You need to construct a single string as a comma-delimited list of five-character codes. These codes are stored one-per-row in a database. You have this method stub: public string BuildString(system.Data.DbDataReader reader) { } Which code block should you use to complete the BuildString() method most efficiently?

You should use this code blcok: var retVal = new System.Text.StringBuilder(); while (reader.Read()) retVal.Append(reader.GetString(0) + ","); retVal.Remove(retVal.Length - 2, 1); return retVal.ToString(); This code block uses an instance of the StringBuilder class to assemble the string. The StringBuilder class is designed to efficiently allocate memory for a steadily growing string. Because of the reduced complexity compared to using basic string concatenation, the performance difference in both execution time and memory allocation becomes measurable around 10,000 iterations, and noticeable to a user around 50,000 iterations. Even when your application construct smaller strings in a loop, the reduced memory allocation can help reduce the number of garbage collections.

You are developing an application by using C# and Visual Studio 2015. You have this class definition (Line numbers are provided for reference only.): 01 public class Manager 02 03 { 04 private IList<Employee> _employees = new List<Employee>(); 05 06 } You want to add and retrieve employee objects from the internal collection by using the EmployeeID with index notation. For example, managerInstance[17] would return the Employee instance that has the ID property set to 17. Which code block(s) should you use?

You should use this code block at Line 05 to implement index notation in a custom class: public Employee this[int employeeID] { get { // implementation omitted } set { // implementation omitted } } This syntax appears very similar to a standard property. An indexer includes a get block that accepts arguments of the types and names declared between the square brackets ([ and ]) and returns a value of the type declared before the this keyword. The set blcok accepts arguments of the types and names declared between the square brackets plus a special argument referenced by the value keyword which is of the type declared before the this keyword.

You are developing the checkout process for an online sales application by using C# and Visual Studio 2015. You have created a Units class to contain the information and logic for the different types of units your products might be packaged in, for example, each, box of 10, display box of 24. Among other properties, the Units class has properties to return the user-friendly text for single or plural forms of the unit: public class Units { SingularText {get; set;} PluralText {get; set;} // remaining implementation omitted } Which code block should you use to assemble the user-friendly text of a line item in your order summary?

You should use this code block that uses the ternary operator (?:): lineText = string.format("{0} ({1} x {2})", productName, quantity, quantity > 1 ? unit.PluralText : unit.SingularText); Ther ternary (three-part) operator is an operator that uses two symbols to divide three operands. The first operand is a Boolean expression. The question mark (?) symbol denotes the start of the second operand, the expression if true. The colon (:) symbol denotes the start of the third operand, the expression if false. It is important to recall that the ternary operator is an operator and therefore deals with expressions (scalar values), and note statements (code blocks).

You are developing a C# application using visual Studio 2015. You need to use a logging class with this public declarations: public class Logger { public Logger(TextWriter logDestination) {...} public Log(string message) {...} } You need to store log messages in memory and readable as a string. Which code block correctly implements this requirement?

You should use this code block to provide a Textwriter implementation that stores data as a string in memory: var destination = new StringBuilder(); var writer = new System.IO.StringWriter(destination); var logger = new Logger(writer); The StringBuilder class exposes a ToString() method that concatenates all child strings into a single string object. The StringWriter class uses the Append() method of the StringBuilder argument when writing messages (for instance, when using the WriteLine() method).

You are developing an application by using C# and Microsoft Visual Studio 2015. You are writing a class that needs to track the number of instances created since startup. The application that uses this class uses many multithreading techniques. You have this code: public class CountedClass { private static inti _instances = 0; public static int Instances { get { return _instances;} } public CountedClass90 { } } Which code block should you add to the default constructor to track the number of instances?

You should use this code block: Interlocked.Add(ref _instances, 1); The Interlocked class performs atomic operations on value types. This Add method accepts a reference to an int variable, followed by a value. The Interlocked class obtains an exclusive lock on the variable, adds the second argument to the first, and stores the results in the referenced variable.

You are developing an application by using C# and Visual Studio 2015. Your application must process one long operation for each Employee instance returned from a library method call. You have this code: (Line numbers are for reference purposes only.) 01 private void ProcessEmployees() 02 { 03 IEnumerable<Employee> employees = lib.GetEmployees(); 04 05 } Your application must execute the long operation for each Employee instance. The ProcessEmployees method should wait until all operations have completed. Your application should use all available local computing resources to finish the operations as quickly as possible. The long operations are thread-safe. Which code block inserted at line 04 will correctly satisfy these requirements?

You should use this code block: Parallel.ForEach(employees, (e, state, i) => LongOperation(e)); The Parallel class provides a static ForEach method that creates a separate Task for each element in an IEnumerable collection. The second argument is an Action delegate that is executed once per item in the collection. Each Task is considered an independent work item. The task scheduler will determine at runtime whether to use multiple threads, and if so, how many threads to use. If local system resource availability changes while the Tasks are processing, the task scheduler might choose to change the number of threads to better use the currently available resources. The Parallel.forEach method will block the calling thread until all Tasks have completed.

You are developing a managed Microsoft Windows service by using C# and Visual Studio 2015. Your service uses the Task Parallel Library (TPL) to transform and save data files. Your service includes this code: try { var cts = new CancellationTokenSource(); var tasks = new List<Task>(); foreach (DataInfo item in GetDataInfoes()) tasks.Add(task.Run(() => transformer.transform(item, cts.Token)) .ContinueWith(t => Save(t.Result), TaskContinuationOptions.RanTocompleted); Task.waitall(tasks.ToArray()); } You need to add exception handling to process only task cancellations that occur during task execution. Which catch block should you add?

You should use this code block: catch (AggregateException ex) { var canceled = from e in ex.Flatten().InnerExceptions where e.GetType() == typeof(TaskCanceledException); foreach (var c in canceled) ProcessCancellation(c); } All exceptions that are thrown by tasks are wrapped by the TPL in an AggreagateException. This exception is thrown when you wait on a task or access its result property. You also retrieve an instance when you access a task's Exception property. The AggregateException class exposes an InnerExceptions property to contain the enumerable list of exceptions that were wrapped by TPL. AggregateException also exposes a Flatten method because some of the inner exceptions might also be instances of AggregateException. The general pattern is to first flatten the aggregate exception before processing the individual exceptions.

You are troubleshooting a report-retrieval class written in C# by using Microsoft Visual Studio 2015. The class is supposed to generate report objects, cache the report in memory, and return the cached object from the property's get accessor. Server logs show that, under heavy load, the multithreaded applications that use this class make multiple attempts to generate the report. Reports are computationally expensive to create. Therefore, you need to modify the get accessor to reduce the server load. You have this code: private Report _report public Report currentReport { get { if(_report.IsOld) _report = GetFreshReport(); return _report; } } You need to modify this code to call the GetFreshReport method exactly once to create current report objects. Which code blocks should you use? (each correct answer presents a complete solution. Choose two.)

You should use this code block: private Report _report; private object _locker; public Report CurrentReport { get { if (_report.IsOld) _report = GetFreshReport(); } return _report; } } This code uses the lock statement to restrict access to the first thread to enter the code block. The expression in parentheses is a reference to an object that might be accessed by multiple threads. The contents of the code include any statements that involve a read operation that might lead to a write operation. This statement prevents other threads from preempting the first thread after the read operation but before the write operation. The problem described is known as a race condition. The first thread to read an old report must then generate a new report. However, under heavy load it is possible for other threads to preempt the first thread after it queries the IsOld property but before creating the new report. Each of these threads continue through the if statement and generate a new report. The lock statement permits only a single thread to execute the code within the lock statement. Alternatively, you could use this code block: private Report _report; private object _locker; public Report CurrentReport { get { Monitor.Enter(_locker); try { if (_report.IsOld) _report = GetFreshReport(); } finally { Monitor.Exit(_locker); } } } The Monitor class provides the static Enter and Exit methods to prevent race conditions. The Monitor.Enter method causes the current thread to wait for exclusive access to the object reference passed as the argument. The thread continues executing the remaining code only after exclusive access is granted by the .NET common language runtime (CLR). When the method has completed the operations that require exclusive access to the object, the Monitor.Exit method releases the exclusive lock. The C# compiler rewrites the lock statement to use the Monitor class.

You are developing an application by using C# and Microsoft Visual Studio 2015. Your application needs to log messages generated by several libraries. You do not have access to the source for these libraries. Each message class declares a method called Log that takes zero arguments. You need to write code that logs the message classes from each of three libraries. Which code block should you use? (Each correct answer presents a complete solution. Choose two.)

You should use this code block: public class Logger { public void LogMessage(dynamic message) { /* omitted * / } } The dynamic keyword can be used in declarations where you know that specific properties and methods are present on object that cannot be verified by the compiler. In this example, all of the Message classes support the same method signature. If you had access to the source code, you would extract an interface to represent the common method. In this example, you do not have control over the source. The dynamic keyword allows you to write a single method that can call the common method on these unrelated classes. Or, you could use this code block: public class Logger { public void LogMessage(Library1.MessageClass message) { /* omitted */ } public void LogMessage(Library2.MessageClass message) { /* omitted */ } public void LogMessage(Library3.MessageClass message) { /* omitted */} } You can use overloaded methods to perform similar operations by processing different arguments. The C# compiler allows you to create several methods that share the same name if the count or respective data type of the arguments are unique for each method. In this example, each library declares a unique MessageClass type that does not share a common type, except object, with the MessageClass types from the other libraries. The compiler distinguishes between the methods based on the data type of the passed argument.

You are developing a class library using C# and Visual Studio 2015. Your library must be able to process and log a series of unrelated long-running operations. You have decided to use the Task Parallel Library (TPL). client applications call your library by passing a set of operations to perform. Your library logs and executes all of the operations while ensuring that system resources are most effectively used. It is acceptable to schedule jobs in any order, but your library must log the position of each operation. You have declared this code: public IEnumerable<Task> Execute(System.Action[]jobs) { var tasks = new Task[jobs.Length]; for(int i = 0; i < jobs.Length; i++) { } return tasks; } public void RunJob(Action job, int index) {// implementation omitted } You need to complete the method by inserting code in the for loop. Which code block correctly implements the requirements?

You should use this code block: tasks[i] = new Task((idx) => RunJob(jobs[(int)idx], (int)idx), i); tasks[i].Start(); This code block uses the Task constructor overload that accepts an Action<object> delegate argument followed by an object argument. The second argument to the constructor is passed as the only argument to the Action<object> delegate. The current value of the i variable is captured when the value is boxed and passed to the Task constructor.

You are developing an application by using C# and Visual Studio 2015. You have an array initialization method with this declaration: unsafe private void InitializeArrayOfInts(int* firstElement, int numOfelements) You need to use this method to initialize a new array of integers. Which code block should you use to perform the initialization?

You should use this code block: unsafe private void SomeMethod() { var arrayOfInts = new int[2073600]; fixed(int* firstElement = &arrayOfInts[0]) { InitializeArrayOfInts(firstelement,, arrayOfInts.Length); } } The unsafe keyword in the method declaration indicates to the compiler that the method might include direct memory manipulation. Unsafe operations require special Code Access Security privileges and are not allowed for all applcations. The fixed block indicates to the .NET Common Language Runtime (CLR) that the Garbage Collector is not permitted to move the ArrayOfInts object while the code block excutes. The fixed block initializer statements indicate that the address of (& operator) the first element of the array will be directly referred to by an integer pointer (int* type) named firstElement. The fixed block is required any time unsafe operations are performed against managed objects.

You are developing a media transcoding service by using C# and Microsoft Visual Studio 2015. You have implemented your service by using worker threads to perform the transcoding operations. The main service thread adds custom WorkItem objects to a queue where they await processing by the worker threads. Your worker method should first call a method to determine whether it should continue processing. If the thread should continue, it should then wait for another work item to become available in the queue. Finally, it should process the work item. Which code block should you use?

You should use this code block: while (Shouldcontinue()){ WorkItem item = WaitForNextItem(); ProcessItem(item); } The while statement evaluates a Boolean expression. If the expression evaluates to true, then the code block is executed. After the code block executes, the expression is evaluated again, repeating the process. The while statement is ideal for looping scenarios where the criteria for staying in the loop should be expressed as an arbitrary Boolean expression. If the expression is false when the statement block is first entered, then the rest of the while statement block does not execute.

You are developing a marketing application by using C# and Microsoft Visual Studio 2015. Your application creates mailing lists based on marketing lead data provided by a third party. Some fields might be absent from some of the leads input into your application. The printing service your application uses requires that the Name, AddressLine1, City, PostalCode, and Region fields are included for every mailing address. You have started this Language-Integrated Query (LINQ) expression: var query = from l in GetLeads() where AddressLine !=null && City !=null && PostalCode !=null && Region !=null select new MaillingAddress Your application must create a list of MailingAddress objects to send to the print service. If the Name property is missing, you may use the substitute text "Our Neighbors." Which code block correctly completes the LINQ expression to implement the requirements?

You should use this code block: { Name = l.Name ?? "Our Neighbors", AddressLine1 = l.AddressLine1, AddressLine2 = l.AddressLine2, City = l.city, Region = l.Region, PostalCode = l.PostalCode }; The null-coalesce operator (??) returns the left-hand operand if the operand is not null. If the left-hand operand is null, the operator returns the right-hand operand. This code block uses the correct syntax for declaring property initializers in a new object instantiation.

You are developing a data-processing library by using C# and Visual Studio 2015. Your library must perform compute-intensive operations on large data sets. Your library contains this method definition: (Line numbers are included for reference purposes only.) 01 public DataPoint[] TransformRawData(RawSample[] rawSamples) 02 { 03 04 where DataPoint.IsSampleValid(s) 05 select DataPoint.createFromSample(s); 06 return query.ToArray(); 07 } You need to complete the TransformRawData method to take maximum advantage of available parallel resources. Your library will be deployed to servers with unknown hardware specifications. All static members of the DataPoint class are thread-safe and independent of application state. Which code fragment inserted at line 03 successfully uses available resources?

You should use this code fragment: var query = from s in rawSamples.AsParallel() This fragment uses the AsParallel extension method to begin a Parallel Language-Integrated Query (PLINQ) query. PLINQ queries automatically partition the input set of data to uses all available paralle-processing resources. The PLINQ processor does not guarantee parallel execution of your query. Sometimes the processor detects certain query patterns that indicate the query should be executed serially instead of in parallel. In this code example, using thread-safe, stateless, static methods assures the processor that the query will benefit from parallel execution.

You use Microsoft .NET Framework 4.5 to create an application. The application accesses a Web service that returns data in this format: {"ID":123,"claimtype":2,"ClaimStatus":1} This code exists in your application: [DataContract] public class Claim { public int ID {get; set;} public int ClaimType {get; set;} public int ClaimStatus {get; set;} } You write this code to return data from the Web service: 01 string url = "http://app.measureup.com/GetLastClaim"; 02 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 03 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 04 { 05 Stream stream = response.GetResponseStream() 06 07 } You need to insert code at line 06 to convert the data returned from the Web service to a Claim instance. Which code segment should you use?

You should use this code segment: DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Claim)); Claim claim = (Claim)serializer.ReadObject(stream); The data returned by the Web service is JavaScript Object Notation (JSON) data. By using the DatacontractJsonSerializer class, you can convert that data to a common language runtime (CLR) type. The ReadObject method of that class performs the conversion.

You use Microsoft .NET Framework 4.5 to create an application that runs on Microsoft Windows 7. The application allows users to save credit card numbers to the local computer. The credit card number is stored in a byte array named data. You must generate an encrypted representation of the byte array. Only the user who runs the application when it is encrypted should be able to decrypt the data. The original byte array should not be modified. You need to write code to accomplish your goal. Which code segment should you use?

You should use this code segment: ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser); The ProtectedData class represents a managed implementation of the Data Protection Application Programming Interface (DPAPI). It allows you to encrypt data by suing information from the current user or computer account. Only that user or computer can decrypt the data. The DataProtectionScope.CurrentUser enumeration member indicates that only the current user should be able to decrypt the data. The method returns an encrypted version of the data and does not modify the original data.

You use Microsoft .NET Framework 4.5 to create an application. The application must accept incoming TCP requests over port 500. You need to write code that retrieves a single request as a string. Which code segment should you use?

You should use this code segment: TcpListener listener = new TcpListener(IPAddress.Any, 500); listener.Start(); TcpClient client = listener.AcceptTcpClient(); NetworkStream stream = client.GetStream(); using (StreamReader reader = new StreamReader(stream)) { string message = reader.ReadToend(); } The TcpListener class allows you to listen for incoming TCP requests. The Start method starts the listening process. The AcceptTcpClient method accepts a single connection. The method blocks the current thread until a TCP client connection is established. It returns a TcpClient instance that represents the connected network client. The GetStream method of the Tcpclient class returns a NetworkStream instance that represents the underlying stream that contains the messages sent by the client. You can read data from the NetworkStream instance by calling the ReadToEnd method of the StreamReader class.

You use Microsoft .NET Framework 4.5 to create an application. The application must process this XML data: <Reservation> <Passenger Name="John Doe" FrequentFlyerNumber="12345"/> </Reservation> This method exists: public XElement CreateReservation(string passendgerName, string frequentFlyerNumber) { XElement xml = null; return xml; } You must implement this method to set the Name attribute to the value of passengerName and the FrequentflyerNumber attribute to the value of frequentFlyerNumber. You need to use LINQ to XML to create an instance of XElement that represents the previous XML data. Which code segment should you use?

You should use this code segment: XElement("Reservastion", new XElement("Passenger", new XAttribute("Name", pasengerName), new XAttribute("FrequentFlyerNumber", frequentFlyerNumber) ) ); The Xelement class represents an XML element and its child nodes and attributes. Its two-parameter constructor accepts an XName instance as the first parameter, and a variable number of Object instances as the second parameter. XName can be cast to and from strings. If you specify a string, it becomes the name of the XML element. For the second parameter, you can specify a string to represent the value of the element, another Xelement instance to represent a child element, or an XAttribute instance to represent an XML attribute.

You use Microsoft .NET Framework 4.5 to create an application. This code exists: public async void WriteData(byte[] data, Stream stream) { } You need to write the byte array represented by the data variable to the stream instance. You must write the data asynchronously and return control immediately to the caller of the WriteData method. Which code segment should you use?

You should use this code segment: await stream.writeAsync(data, 0, data.Length); The WriteAsync method of the Stream class writes data to a stream asynchronously. The await operator causes execution to return immediately to the caller of the encapsulating method. Execution resumes within the method where it left after the asynchronous operation completes.

You use Microsoft .NET Framework 4.5 to create an application. This stored procedure is declared in a Microsoft SQL Server 2012 database: CREATE PROCEDURE AddUser @UserName nvarchar(50), @ID int out You create a SqlCommand instance named cmd to represent the stored procedure. You must add parameters to the SqlCommand instance to add a user named JDavis and obtain the ID of that user. You need to write code to accomplish your goal. Which code segment should you use?

You should use this code segment: cmd.Parameters.AddWithValue("@UserName", "JDavis"); SqlParameter param = new SqlParameter("@ID", SqlDbType.Int); param.Direction = ParameterDirection.Output; cmd.Parameters.Add(param); The SqlCommand class contains a Parameters property that returns a collection of SqlParameter instances, which represents parameters to a stored procedure or query. The Addwithvalue method of the SqlParameter class allows you to add a SQL parameter to a stored procedure or query. The first parameter to the method represents the name of the SQL parameter. You must specify the name exactly as it appears in the stored procedure or query. The second parameter to the method represents the SQL parameter's value. By creating a new SqlParameter instance, you can set the Direction property to ParameterDirection.Output. This is necessary because the AddUser method accepts an OUT parameter. The value of this parameter is set after the stored procedure executes.

You use Microsoft .NET Framework 4.5 to create an application that accesses data in a Microsoft SQL Server 2014 database. You write this code. (Line numbers are for reference only.) 01 using(SqlConnection connection = new SqlConnection(connectionString)) 02 { 03 String query = "Update Group Set name='Admin' Where ID=2"; 04 int rowsChanged; 05 06 } You need to execute the query and store the number of rows affected in the rowsChanged variable. What code should you insert at line 05?

You should use this code segment: connection.Open(); SqlCommand command = new Sqlcommand(query, connection); rowsChanged = command.ExecuteNonQuery(); The executeNonQuery method of the SqlCommand class executes a query and returns the number of rows affected by the query.

You use Microsoft .NET Framework 4.5 to create an application. A custom event log named AppCenter exists. You need to write the message Invalid to the custom event log. Which code segment should you use?

You should use this code segment: if(!EventLog.SourceExists("Mysource")) { EventLog.CreateEventSource("MySource", "AppCenter"); } EventLog eventLog = new EventLog("AppCenter"); eventLog.source="MySource"; eventLog.WriteEntry("Invalid"); This code first calls the SourceExists method of the EventLog class to determine whether or not an event source exists. Messages must be associated with event sources. If it does not exist, it calls the CreateEventSource method to create an event source in the AppCenter custom event log. It then creates an EventLog instance, passing to its constructor the name of the custom event log to retrieve. It sets the Source property to the event source, and then call the WriteEntry method to write the message Invalid. The message is written to the AppCenter event log for the source Mysource.

You use Microsoft .NET Framework 4.5 to create an application. The .NET Framework UnhandledException event is defined as follows: public event UnhandledExceptionEventHandler UnhandledException; The .NET Framework UnhandledExceptionEventHandler delegate is defined as follows: public delegate void UnhandledExceptionEventHandler (object sender, UnhandledExceptionEventArgs e); You must create an event handler named HandleApplicationError that handles the UnhandledException event. You need to define the event handler's method signature. Which code segment should you use?

You should use this code segment: private void HandleApplicationError(object sender, UnhandledExceptionEventArgs e) { } The event handler's signature correctly matches the signature of the corresponding delegate. In this scenario, the UnhandledExceptionEventHandler delegate defines two parameters. The type of the first parameter is Object, and the type of the second parameter is UnhandledExceptionEventArgs.

You use Microsoft .NET Framework 4.5 to create an application. You must create a generic class named builder that must only support the Vehicle type or types derived from Vehicle. You need to define the class. Which code segment should you use?

You should use this code segment: public class Builder<T> where T : Vehicle {} This class represents a generic Builder class. The angle bracket identifies the name of the type parameter that is used throughout the class definition. IN this case, the name of the generic type is T. The where keyword identifies a generic constraint. In this scenario, the constraint ensures that other code can only specify Vehicle (or one of its derived classes) as the type argument for T.

You use Microsoft .NET Framework 4.5 to create an application. You must create a class named MappingException to serve as a user-defined exception for your application. Code that throws instances of MappingException must be able to wrap other handled exceptions with your exception. You need to create the MappingException class. Your solution must adhere to Microsoft best practices. Which code segment should you use?

You should use this code segment: public class MappingException : Exception { public MappingException(){} public MappingException(string msg) : base(msg) {} public MappingException9string msg, Exception inner) : base(msg, inner) {} } You must directly or indirectly derive all exceptions from the exception base class. According to Microsoft best practices, you should implement three overloaded constructors. One constructor should accept no parameter. One constructor should accept a String parameter that represents the error message associated with the exception. One constructor should accept a String parameter that represents the error message and an Exception parameter that represents a wrapped exception. The two-parameter overload allows code that throws an instance of MappingException to wrap other handled exceptions with the MappingException instance.

You use Microsoft .NET Framework 4.5 to create an application. You need to declare an event named MouseMove that uses a MouseEventArgs instance as the event argument when the event is raised. You need to declare the event. You must ensure that the event can be raised from within your class only. Which code segment should you use?

You should use this code segment: public event EventHandler<MouseEventArgs>MouseMove; To define an event, you must specify the event keyword. This keyword instructs the compiler that the MouseMove instance represents a multi-cast delegate that can only be invoked from within the class where the event is defined. The EventHandler class represents a delegate that contains two parameters: the type of the first parameter is Object, and the type of the second parameter is EventArgs. By using the generic version of EventHandler, which is defined as EventHandler<T>, you can specify the type that should be used as the second parameter for the delegate that represents the event handler. In this scenario, EventHandler<MouseEventArgs> specifies that the event handler must adhere to this signature: Void SomeEventHandler(object sender, MouseEventArgs e)

You use Microsoft .NET Framework 4.5 to create an application. This method exists: public bool CanAdd(object obj) { } The CanAdd method must return true if the parameter passed to it is an instance of Vehicle or Person. Otherwise it must return false. You need to implement the CanAdd method. Your solution must not throw an exception. Which code segment should you use?

You should use this code segment: return obj is Vehicle || obj is Person; The is keyword allows you to determine whether an object is an instance of a specific type. The || operator represent a conditional OR. This coe segment returns true if the obj instance's type is Vehicle or if it is Person.

You use Microsoft .NET Framework 4.5 to create an application. You must call a method named ProcessData. This method might throw exceptions of different types. If the method throws an exception, you must call a method named LogException, which accepts an Exception instance as a parameter. You must also allow the exception to be propagated up the call stack and preserve the original stack trace. You need to write code to accomplish your goal. Which code segment should you use?

You should use this code segment: try { ProcessData(); } catch (Exception ex) { LogException(ex); throw; } This code handles exceptions of all types by specifying the type Exception as a parameter to the catch statement. It calls the LogException method with an instance of the exception that was handled. The throw statement forwards the original exception up the call stack, preserving the stack trace in the exception details.

You use Microsoft .NET Framework 4.5 to create an application. You are writing code that must call these methods: *Withdraw *Deposit *LogTransaction The methods must meet these transactional requirements: *If the Deposit method throws an exception, changes made by the Withdraw method must be rolled back. *If an exception is thrown by the Log

You should use this code segment: using (TransactionScope scope = new TransactionScope()) { Withdraw(); Deposit(); using (TransactionScope scope2 = new TransactionScope(TransactionScopeOption.Suppress)) { LogTransaction(); } scope.Complete(); } The TransactionScope class allows you to manage implicit transactions, which are those that automatically commit when you call the Complete method, unless an exception is thrown. The transaction rolls back automatically if an exception is thrown. The Suppress TransactionScopeOption allows you to prevent an operation from enlisting in a current transaction. This allows transactional operations to succeed even if the operations within the nested transaction scope fail.

You use Microsoft .NET Framework 4.5 to create an application. You must create a dictionary with two entries. The first entry should use the number 1 as a key and the string Sales as the value. The second entry should use the number 2 as a key and the string Marketing as the value. You need to initialize the dictionary. Which code segment should you use?

You should use this code segment: var dictionary = new Dictionary<int, string>() { {1, "Sales"}, {2, "Marketing"} }; This code creates a dictionary with an integer as its key and string as its value. To create an entry in the dictionary, you must enclose the key and value separated by a comma within the curly braces {}, such as follows: {1, "Sales"}. The entire dictionary must also be enclosed in curly braces.

You use Microsoft .NET Framework 4.5 to create an application. this XML data exists: <Theater> <Movie Title="The Hobbit: An Unexpected Journey" Rating="PG-13" ReleaseDate="1987"/> <Movie Title="The Croods" Rating="PG" ReleaseDate=""/> <Movie Title="Escape from Planet Earth" Rating="PG" ReleaseDate=""/> </Theater> You create an XDocument instance named xDoc that contains the previous XML data. You need to use LINQ to XML to set the ReleaseDate attribute of all Movie elements to 2013 if the ReleaseDate attribute is not set. Which code segment should you use?

You should use this code segment: var movies = from m in xDoc.Descendants("Movie") where m.Attribute("ReleaseDate").Value == "" select m; movies.ToList().ForEach(m=> m.Attribute("ReleaseDate").Value = "2013"); This code uses a LINQ query expression to return all descendant elements named Movie that have an attribute named ReleaseDate set to an empty string. It then calls the ToList method to create a list of XElement instances that represent the found elements. It calls the ForEach method of the returned list to iterate through each element and set the value of the ReleaseDate attribute to 2013.

You use Microsoft .NET Frameowrk 4.5 to create an application. This class exists: public class Publisher { public string Name; } public class Book { public string ISBN {get; set;} public string Title {get; set;} public Publisher Publisher {get; set;} public static List<Book>GetBooks() { // Implementation Omitted } } You need to create a query that returns only the ISBN, title, and publisher's name of all book instances. You must return the publisher's name as a property named Publisher.

You should use this code segment: var query = from b in Book.GetBooks() select new {b.ISBN, b.Title, Publisher=b.Publisher.Name}; this code uses a LINQ query expression to return a collection of anonymous type instances that have ISBN, Title, and Publisher properties. The ISBN and Title properties are set to the corresponding properties of the Book instances. The Publisher property is set to the Name property of the associated Publisher instance.

You use Microsoft .NET Framework 4.5 to create an application. These classes exist: public class Product { public string Name {get; set;} public string ID {get; set;} public double Price {get; set;} } public class ProductList : List<Product> { public static ProductList GetProducts() { // Implementaiton Omitted } } You need to create a query that returns an IEnumberable<string> instance of product names. Which code segment should you use?

You should use this code segment: var query = from p in ProductList.GetProducts() select p.Name; This code segment uses a LINQ query expression syntax to project the Name property from a collection of Product instances. The resulting query would return an IEnuerable<string> instance of product names.

You use Microsoft .NET Framework 4.5 to create an application. public class Result { public double Value; public DateTime Date; public static List<Result> GetResults() { // Implementation Omitted } } You need to create a query to determine the number of Result instances for each distict Date value. Which code segment should you use?

You should use this code segment: var query = from r in Result.GetResults() group r by r.Date into g select new {Date=g.Key, Count=g.Count()}; This code uses a LINQ query expression to gorup data returned by GetResults() by the Date proeprty of the Result class. The group clause allows you to group items in a collection by a key that you provide. The by keyword specifies the key. In this scenario, the key is the Date property. This code returns an anonymous type instance that contains two properties named Date and Count. The Date property represents the value of the distinct key, and the Count property represents the count of the number of items grouped by that key.

You use Microsoft .NET Framework 4.5 to create an application. This class exists: public class Person { public int Age {get; set;} public string Name {get; set;} public static List<Person>GetPeople() { // Implementation Omitted } } You need to call the GetPeople method and sort the list of Person instances by name and then by age. Which code segment should you use?

You should use this code segment: var sortedPeople = Person.GetPeople().OrderBy(p => p.Name).ThenBy(p => p.Age); This code calls the OrderBy method to first order the list by the Name property of each People instance. It then calls the ThenBy method, which allows you to order results by a second key.

You use Microsoft .NET Framework 4.5 to create an application. This class exists (line numbers are included for reference only): public enum Planet { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, PlutoDwarf } 01 public class solarSystem 02 { 03 public static IEnumerable<Planet> PlanetsByDistanceFromsun 04 { 05 get 06 { 07 } 08 } 09 } You must implement the PlanetsByDistanceFromSun property to iterate through the Planet enumeration when it is used in a foreach loop as follows: foreach (Planet p in Universe.PlanetsByDistanceFromSun) { } You need to write code to accomplish your goal. You must ensure that reorganization of the Planet enumeration does not affect the order of the items returned in the foreach loop. What should you do?

You should use this code segment: yield return Planet.Mercury; yield return Planet.Venus; yield return Planet.Earth; yield return Planet.Mars; yield return Planet.Jupiter; yield return Planet.Saturn; yield return Planet.Uranus; yield return Planet.Neptune; yield return Planet.PlutoDwarf; The yield keyword specifies that the current property or method is an iterator. The yield return statement allows you to return one element during each iteration. In this scenario, each yield return statement returns a different Planet enumeration value during each iteration in the foreach loop.

You use Microsoft .NET Framework 4.5 to create an application. You must call a method named RetrieveReport. This method might throw exceptions of different types. Regardless of whether or not RetrieveReport throws an exception, you need to call a method named EndConnection. You need to write the code to accomplish your goal. Which code segment should you use?

You should use this code segment; try { RetrieveReport(); } finally { EndConnection(); } Within a try block, you should place code that might throw an exception. If an exception is thrown and not handled in a catch block, execution resumes up the call stack until a catch block is found that handles the exception. However, code within a finally block always executes before execution resumes up the call stack. By calling the EndConnection method within the finally block, you ensure that it gets called even if RetrieveReport throws an exception.

You use Microsoft .NET Framework 4.5 to create an application. This delegate is defined: public delegate string Combine(string s1, string s2); You must declare an instance of the Combine delegate that uses an anonymous method to concatenate the string instances represented by s1 and s2 and return the concatenated string. You need to declare the delegate instance. Which code segment should you use?

You should use this code statement: Combine combine = delegate(string s1, string s2){return s1 + s2;}; The expression on the right side of the = operator represents an anonymous method. An anonymous method is one that uses the special name delegate. Anonymous methods allow you to assign delegate instances to method bodies without having to explicitly define a method within a class. This is useful if the method will only be called by invocation of the delegate.

You use Microsoft .NET Framework 4.5 to create an application. An event named Processed is declared with the EventHandler delegate. You must subscribe to the Processed event. When the event is raised, you must call a method named ShowCompleted, which accepts no parameters. You need to use a lambda expression to subscribe to and handle the Processed event. Your solution must not prevent other code from also handling the Processed event. Which code segment should you use?

You should use this code statement: Processed +=(sender, e) => ShowCompleted(); This code uses the += operator to add a subscription to the Processed event. In this scenario, the subscription is a lambda expression that represents the event handler. The expression on the left side of the => lambda operator represents the input parameters to the delegate. Just like any method that implements a delegate, you can use any variables that you like, as long as you specify the correct number of parameters. When specifying a single input parameter, you do not need to use parenthesis. However, when specifying more than one input parameter, you must enclose them in parenthesis, separated by commas. The expression on the right side of the => lambda operator represents the method body of the delegate. In this case, the body is simply a call to the ShowCompleted method. Because the body contains only a single code statement, then you do not need to enclose the code within curly braces{}. You also do not need to end the code statement with a semicolon. The semicolon shown is necessary to complete the entire code statement, not the code statement for the expression on the right side of the lambda operator. You also do not need to use the return keyword to return a value from the method. However, had your expression contained multiple code statements, you would have needed to enclose the statements within curly braces {}, end each statement with a semicolon, and add a final statement with the return keyword to return a value from the method.

You are developing a class library by using C# and Microsoft Visual Studio 2015. You are building a class that dynamically generates Comparison methods. These methods are tailored to each entity class by using reflection to discover custom attributes on the entity class. An employee entity class has been completed with this declaration: [Comparable] public class Employee { [CompareBy(3, descending = true)] public int ID { get; set; } [CompareBy(2)] public string FirstName { get; set; } [CompareBy(1)] public string LastName { get; set; } } You need to implement the class that supports the [CompareBy(...)] annotation. Complete the class definition by dragging statement fragments from the left to the appropriate location on the right. You may use items more than once, and you do not have to use each item.

You should use this code: [AttributeUsage(AttributeTargets.Property)] public class CompareByAttribute : Attribute { public CompareByAttribute(int order) { this.order = order; } public bool descending { get; set; } private int order; } To create a custom attribute class to be used for annotating (also called decorating) a class, you should create a class that inherits from the System.Attribute base class. An Attribute-derived class is generally a very simple class whose definition is determined by the intended usage. The bare minimum annotation for any attribute requires square brackets surrounding the class name. Because attribute classes generally include the suffix Attribute in the class name, the compiler permits you to omit the suffix for brevity. Assume your class has this definition: public class compareByAttribute : System.Attribute {} With this definition, the compiler permits this annotation: [CompareBy] Many attributes require positional parameters when using annotation syntax. Positional parameters are always declared as constructor parameters. Your annotation must include arguments for every parameter of one of the accessible constructors. Assume your desired annotation follows: [CompareBy(1)] This annotation implies that the CompareByAttribute class has a constructor that declares a single integer parameter. To implement this attribute, your class might have this definition: public class compareByAttribute : System.Attribute { public CompareByAttribute(int order) { this.order = order; } private int order; } If you want to have optional named arguments when constructing your annotation, your attribute class needs to have a public readable and writeable property with the desired name. For instance, assume you wanted to use this annotation: [CompareBy(1, descending = true)] This desired annotation implies that your attribute should be defined as follows: public class CompareByAttribute :System.Attribute { public CompareByAttribute(int order) { this.order = order; } private int order; public bool descending { get; set; } } There are many other options available when you create an attribute class. One of the most common options is to limit which types of declarations may include your attribute as an annotation. The AttributeUsageAttribute class allows you to combine the bitwise flags in the AttributeTargets enumeration to limit the usage of your attribute. For instance, you can indicate that your attribute may only annotate property declarations by passing the AttributeTargets.Property positional parameter.

You are developing a class library by using C# and Microsoft Visual Studio 2015. You want to implement a Product class. This class is used in many other applications. The Product class should encapsulate all data behind method calls. No other code blocks should have direct access to the storage for these method calls. You have decided to use property declarations to simplify the syntax of these methods. Complete the Product class implementation by dragging the keywords from the left to the appropriate location on the right. You may use items more than once, and you do not have to use each item.

You should use this code: public class Product { private int _id; public int Id { get { return _id;} set ( _id = value; } } private string _firstName; public string FirstName { get { return _firstName;} set { _firstName = value; } } } You can use access modifiers to control which blocks of code may refer to a declaration. The access modifier precedes the declaration that it modifies. You may choose from among these access modifier keywords: public, private, internal, protected, and protected internal. The public keyword is the least restrictive access modifier. This keyword indicates that any code block that can reference the containing code block may refer to the declaration. For example, if a type declaration includes the public keyword, then any code that references the containing assembly may use the type. If a type member declaration includes the public keyword, any code that can access the type may refer to the type member. The private keyword is the most restrictive access modifier. This keyword indicates that the only code that can refer to a private declaration must be within the same containing code block. For example, if a nested type declaration includes the private keyword, then only the containing type declaration may directly refer to it. If a type member includes the private keyword, then only the type that declares the member may refer to the type member. The internal keyword is more restrictive than the public access modifier, but less restrictive than the private access modifier. This keyword indicates that other code within the containing assembly may use the declaration as if it uses the public keyword. However, code outside the containing assembly is restricted as if the declaration uses the private keyword. This is the default access for any declaration that omits access modifier keywords. The protected keyword is a special access modifier that relates to inheritance. This keyword indicates that the declaration should be restricted as if it uses the private keyword. However, any code block that directly, or indirectly, inherits from the containing type can also refer to the declaration. This keyword is not limited by whether the inheriting type is declared in the containing assembly. The protected and internal keywords, when used together, declare the union of the protected and internal access modifiers. This access modifier specifies that the declaration is considered public within the containing assembly. Code that inherits from the containing type may also refer to the declaration, even if the inheriting code is in different assembly.

You are developing a media transcoding library by using C# and Microsoft Visual Studio 2015. You want to declare a class to encapsulate a single work item. Your library requires that the WorkItem class contains properties for MediaType and JobID. These properties should be initialized in the constructor. After initialization, code outside of the library should be unable to change the values of these properties. This version of the library does not require custom validation. You need to begin the WorkItem class declaration and keep the code as simple as possible. Which code block satisfies these requirements?

You should use this code: public class WorkItem { public int JobID { get; internal set; } public string MediaType { get; internal set; } } This code uses auto-implemented properties declared with the public access modifier. This specifies that any code that can access the WorkItem class may also directly reference the properties. However, the set keywords are declared with the internal access modifier. This indicates that only code in the same assembly as the WorkItem class may directly reference the set block.

You use Microsoft .NET Framework 4.5 to create an application. You use the Makecert.exe utility to create a self-signed root authroity certificate. The certificate file is TestCA.cer, and the private key file is TestCA.pvk. You need to create a new certificate with the subject name Test that is signed by your self-signed root authority certificate. Which command should you use?

You should use this command: Makecert.exe -n "CN=Test" -ic TestCA.cer Test.cer The -n switch specifies the subject name of the certificate. You must specify the subject name as CN=subject name. In this case, it is CN=Test. The -ic switch specifies the issuer certificate, which is the certificate authroity that is issuing the certificate. In this scenario, the certificate authority's certificate is the self-signed root authority certificate named TestCA.cer. The final parameter to the command specifies the name of the certificate that is created, which is Test.cer.

You use Microsoft .NET Framework 4.5 to create an application. The application has static references to AssemblyA and AssemblyB. AssemblyA is compiled against .NET Framework 2.0, and AssemblyB is compiled against .NET Framework 4.0. You need to configure the application so that AssemblyA uses .NET Frameowrk 4.0 when the application is run. Which configuration should you use?

You should use this configuration: <configuration> <startup > <supportedRuntime version="v4.0" /> </startup> </configuration> This configuration tells the runtime that the application must use .NET Framework 4.0. This means that all referenced assemblies use .NET Framework 4.0, regardless of the .NET Framework in which they are compiled.

You use Microsoft .NET Framework 2.0 to create an application. During deployment, you discover that the host server contains .NET Framework 1.1 and .NET Framework 4.0. Which configuration should you use?

You should use this configuration: <configuration> <startup> <supportedRuntime version="v2.0.50727" /> <supportedRuntime version="v4.0" /> </startup> </configuration> This forces the application to use either .NET Framework 2.0 or .NET Framework 4.0, whichever is present. Because only .NET Framework 1.1 and .NET Framework 4.0 exist on the host server, this configuration forces the application to use .NET Framework 4.0.

You are developing a product catalog application by using C# and Microsoft Visual Studio 2015. You are programming entity classes. You have declared this class: public partial class Product : INotifyPropertyChanging { public double ListPrice { get { reutrn this._listPrice;} set { if (value !=this._listPrice) { this.OnListPriceChanging(value); this.OnPropertyChanging("ListPrice"); this._listPrice = value; (); } } } public event PropertyChangingEventHandler PropertyChangign; protected virtual void OnPropertyChanging(string propertyName) { var ev = this.PropertyChanging; if (ev != null) this.PropertyChanging(this, new PropertyChangingEventArgs(propertyName)); } } If another developer defines the OnListPriceChanging method in a separate file, you want to call it. If no one defines this method, you want the code to compile successfully. Which declaration should you use to complete the Product class?

You should use this declaration: partial void OnListPriceChanging(double value); The partial keyword on the class declaration causes the compiler to combine the declarations from multiple partial class declarations into a single class if they share the same fully-qualified class anme. Within a partial class block, a partial method declaration causes the compiler to allow a partial class block to refer to methods that have been declared with a return type, name, and signature but without the implementation block. If another partial class block contains the implementations, then the compiler will use it. If no other partial class blocks implement the method, the compiler automatically imeplements an empty, or no-op, method block.

You are developing a class library by using C# and Microsof Visual Studio 2015. You need to develop a hierarchy of classes to represent different kinds of customers. These classes will be used in other applications. You need to declare the Customer class. This class serves as the base class for all Customer classes. You should not be able to create new instances of the Customer class. The Customer-derived classes you declare in this library must not be visible to other assemblies. Other developers derive the Customer class in their own assemblies. Which declaration satisfies these requirements?

You should use this declaration: public abstract class Customer { /* implementation omitted */ } The public access modifier allows all assemblies that take a reference to your library to access the Customer type. The abstract keyword causes the compiler to reject all attempts to create new instances of the Customer class, even in your own code. The only way to create a new instance that uses the Customer type is to use the new keyword with a class that inherits, directly or indirectly, from Customer.

You are developing a class library by using C# and Visual Studio 2015. You need to complete a class to represent employee data. Your application stores employee data in a database. One of the tables that stores employee data includes a DateOfBirth field. Your application must be able to calculate employeees' ages from this field. You have already completed this code: public class Employee { private DateTime _dob; public DateTime DateOfBirth { get ( return _dob; } set { this._dob = value; this.Age = (int)((DateTime.Now - value).TotalDays / 365.25); } } } You need to implement the Age member in the employee class. Because you cannot store the age in the database, the Age member must be read-only. Which declaration correctly implements the Age member?

You should use this declaration: public int Age { get; private set; } This declares a public property of Employee instances named Age. The data type of this property is an integer. When the get and set keywords are followed by semi-colons instead of code blocks, the compiler automatically creates a private backing variable that is returned from the property getter, and stored in the property setter. The compiler allows you to use a different access modifier for either the get or set keywords. In this case, the set keyword is private. This makes the property read-only from the perspective of any code outside of the Employee class declaration. Inside the class block, however, the property may still be assigned. This is used by the set block of the DateOfBirth property.

You are developing a product catalog application by using C# and Visual Studio 2015. You need to develop the data-access components for your application. You need to define an interface that follows these requirements: 1. Provide a read and write property to store an instance of the ObjectContext class. 2. Provide a method to return an IEnumerable<Product> for all products within a category. 3. Provide a method to return a single Product instance identified by a ProductID. Which interface declaration correctly satisfies these requirements?

You should use this interface declaration: public interface IProductAccessService { ObjectContext Context {get;set;} IEnumerable<Product>GetProductsByCategory(int categoryId); Product GetProductByID(int productId); } This declaration correctly declares a read and write property by using the data type, followed by the nam, followed by curly braces ({ and }) containing the token get; to indicate that the property supports read followed by the token set; to indicate the property supports write. This declaration correctly declares two method signatures that match the requirements. Each method declaration is terminated by a semi-colon to indicate that the method definition has been omitted.

You use Microsoft .NET Framework 4.5 to create an application. The .NET Framework Comparison delegate is defined as follows: public delegate int Comparison<in T>(T x, Ty); The method that implements this delegate must return a: *negative number if x is less than y *positive number if x is greater than y *0 if x is equal to y The Sort method of the .NET Framework generic List class is defined as follows: public void Sort<T>(Comparison<T>comparison); This class exists in your application: public class Product { public int ID {get; set;} public string Name {get; set;} public double Price {get; set;} } You declare this generic List instance: List<Product>products = GetProducts(); You must call the Sort method of the products instance to sort the list by the ID property of the Product class. You need to use a lambda expression to accomplish your goal. Which lambda expression should you pass to the Sort method?

You should use this lambda expression: (x,y) => x.ID < y.ID ? -1 : x.ID > y.ID ? 1 : 0 The expression on the left side of the => lambda operator represents the input parameters to the delegate. Just like any method that implements a delegate, you can use any variables that you like, as longs as you specify the correct number of parameters. When specifying a single input parameter, you do not need to use parenthesis. However, when specifying more than one input parameter, you must enclose them in parenthesis, separated by commas. The expression on the right side of the => lambda operator represents the method body of the delegate. If your expression contains only a single code statement, then you do not need to enclose the code within curly braces {}, you do not need to end the code statement with a semicolon, and you do not need to use the return keyword to return a value from the method. However, had your expression contained multiple code statements, you would have needed to enclose the statements within curly braces {}, end each statement with a semicolon, and add a final statement with the return keyword to return a value from the method.

You are developing a class library by using C# and Visual Studio 2015. You need to generate and compile a Comparison<CustomClass> method at runtime. This method compares two instances of CustomClass based on an IEnumerable of PropertyInfo instances. You need to be able to generate and save the source code to this method. You have already used reflection to generate the list of properties by which you can compare two instances of CustomClass: (Line numbers are included for reference purposes only.) 01 public Comparison<customClass>CreateMethod(IEnumerable<PropertyInfo>props) 02 { 03 Comparison<Customclass>comp; 04 05 comp = CompileAndLoadMethod(dynamicMethod); 06 return comp; 07 } Which line of code when inserted at line 04 could be used to generate the Comparison<CustomClass> method, save the C# source code, and compile and load the method?

You should use this line of code at line 04: CodeCompileUnit dynamicMethod = CreateCustomMethod(porps); The CodeCompileUnit class is one of the main classes used by the CodeDOM library. CodeDOM is a code-generation capability built into the .NET Framework Class Library to support runtime generation of source code. You can use the CodeCompileUnit class to create an object model (or code graph) that represents the hierarchy of code blocks found in .NET applications. This object can be converted to source code and compiled by using the CSharpCodeProvider class. Once compiled, the resulting assembly can be loaded into memory using the Reflection API.

You are developing a data transfer library by using C# and Visual Studio 2015. Your application must write a custom binary format to a file. The data to be serialized is contained in an ArrayList of objects of different types. Most of these objects do not share a common base class other than System.Object You have this code: public void SerializeObjects (ArrayList list, BinaryWriter writer) { var serializer = new CustomSerializer { Writer = writer}; forearch (var o in list) serializer.Serialize(o); } You need to write a CustomSerializer class that can serialize each data type to the custom binary format. It will need to use some property getters, adn some method return values for the output, depending on the exact object type. You begin the class definition with this code: public class CustomSerializer { public BinaryWriter Writer { get; set; } public void SerializeClass1 (Class1 object) { // implementation omitted } public void SerializeClass2 (class2 object) { // implementation omitted } // Additional SerializeXXXX methods as needed } You need to define the public Serialize method. Which method definition correctly implements the Serialize method to satisfy the requirements?

You should use this method: public void Serialize(dynamic o) { Serialize(0); } This method uses the dynamic keyword to provide runtime-binding of method calls. The compiler treats the dynamic keyword the same as object when determining the type of input expressions. However, the compiler allows method calls to the object that cannot be verified by static evaluation of the source code. When dynamic expressions are used as parameters to overloaded methods, the compiler does not bind to a specific method. Instead, the compiler uses all available information to determine a candidate list of methods. The .NET Common Language Runtime selects one method from this list when the statement is executed adn the exact data type of the dynamic expression is known. In this example, the serialize method accepts one parameter of any data type. When the code is evaluated statically at compile time, the dynamic keyword on the parameter is treated as a synonym for object. When the dynamic expression o is used in a method call, the compiler does not bind to any particular overload of the private Serialize methods. At runtime, the data type of the o expression is determined, and only then does the runtime select the correct method from the overloads.

You are developing an application by using C# and Visual Studio 2015. You are using .NET Reflection to dynamically load an Assembly and instantiate types discovered within it. You have this code: (Line numbers are for reference purposes only.) 01 var assemblyPath = "C:\someAssembly.dll"; 02 03foreach (Type publicType in assembly.ExportedTypes) 04 InstantiateTypeByUsingReflection(publicType); // Defined elsewhere You need to complete the implementaiton by inserting a statement at line 02. Which statement correctly completes the implementation?

You should use this statement at line 02 to complete the implementation: var assembly = Assembly.LoadFrom(assemblyPath); The static Assembly.LoadFrom method accepts a file path argument and loads the identified assembly into the current AppDomain. You may then use .NET Reflection to discover and instantiate types, and excute methods.

You are developing a file-encryption service by using C# and Visual Studio 2015. The encryption operation is compute-intensive, and you will deploy the service to a system with limited resources. To preserve system responsiveness, you have decided to use exactly two worker threads to execute the encryption operation. You have this service implementation class: (Line numbers are for reference purposes only.) 01 using System.collections; 02 using System.collections.Generic; 03 using System.collections.Concurrent; 04 [ServiceContract] 05 public class ServiceClass { 06 [Operationcontract] 07 public void EncryptData(byte[]data){ 08 q.Add(data); 09 } 10 11 static ServiceClass() { 12 13 new Thread(WorkerMethod).Start(); 14 new Thread(WorkerMethod).Start(); 15 } 16 static WorkerMethod() { 17 foreach (var data in q.GetConsumingEnumerable()) 18 Encrypt(Data); 19 } 20 } Your service should encrypt files according to the order in which they were received. It should minimize blocking on the thread that calls the EncryptData method. You must declare the q static variable at line 10 and instantiate the appropriate class at line 12 to complete the implementation. What should you do?

You should use this statement at line 10: private static BlockingCollection<byte[]> q; And you should use this statement at line 12: q = new Blockingcollection<byte[]>(); The System.Collections.concurrent.BlockingCollection<T> generic class encapsulates one of the other classes from the System.Collections.concurrent namespace that implement the IProducerConsumerCollection<T> generic interface. This class exposes the Add and Take thread-safe methods to allow multiple threads to modify the collection without using additional locking code. This class also exposes the Get ConsumingEnumerable method which atomically removes and then returns the next object in the encapsulated collection. The iterator returned by this mthod automatically blocks the calling thread until the next object is available. The default constructor for the BlockingCollection<T> class causes the instance to automatically use the System.Collections.Concurrent.ConcurrentQueue<T> generic class. This class implements a thread-safe, First-In First-Out (FIFO) queue. This class is specifically designed to support concurrent code patterns where one or more threads are responsible for queuing objects, adn one or more different threads are responsible for dequeuing objects.

You are developing a data-transformation library by using C# and Visual Studio 2015. This library accepts large data streams as input and performs long-running transformation operations on them. You declare these methods to implement the data-transformation process: public void TransformStreams(Stream[] streams) { foreach (var s in streams) } private ovid TransformStream(Stream stream) { // implementation omitted } Your application needs to asynchronously process as many data streams as the system resources allow. Which statement should you use to complete the foreach loop and correctly implement asynchronous processing in your library?

You should use this statement to complete the foreach loop: ThreadPool.QueueUserWorkItem( state => TransformStream((Stream)state), s); The ThreadPool class is used to assign operations to a background thread. The QueueUserWorkItem method queues a delegate to run on the next available ThreadPool thread. The delegate describes a method that accepts a single object argument and has no return value. The ThreadPool class uses a hill-climbing algorithm to add or remove background threads as needed to maximize overall throughput. The overload to QueueUserWorkIteme that accepts an object as the second argument passes the argument to the delegate when the delegate is executed. When the iterator variable s is passed by value to the QueueUserWorkItem method, a copy of the reference to the current object in the iteration is taken. This ensures that whether the delegate is immediately executed or queued for a long time, the correct state object is processed.

You are modifying a C# application by using Microsoft Visual Studio 2015. This application makes database queries in background threads. The background threads perform compute-intensive operations on the results of the queries. You have determined that other threads in your application and in other applications on the system are often starved for processor time. The background threads process results in a loop. You have decided to pause the process after each iteration to execute other threads that are ready to run. You want to pause only if threads are ready on the same logical processor as the background thread that pauses. Which statement should you use?

You should use this statement: Thread.Yield(); This statement uses the static Yield method of the Thread class. This method releases the current thread's time slice only if another thread is ready on the same processor. If there are no waiting threads on the processor, the current thread continues its time slice. If there are waiting threads of any priority on the same processor, the time slice is yielded and the operating system reschedules the current thread according to its priority.

You are writing a C# application by using Visual Studio 2015. The application handles members. You define the following enum: public enum MemberType { Unknown, Member, Staff, Other } You need to write a function that accepts an integer code and returns the following: * MemberType.Member if the code is 10 * MemberType.Staff if the code is 20 * MemberType.Other if the code is any other value which block of code should you write?

You should write the block of code below: MemberType GetType (int code) { MemberType mt = MemberType.Unknown; switch (code) { case 10: mt = MemberType.Member; break; case 20: mt = MemberType.Staff; break; default: mt = MemberType.Other; break; } return mt; } This code uses a switch statement to choose the correct action. It correctly sets the return value based on each code value and then uses default to handle any other values. It also correctly places a break statement after each case so that the code execution will not fall through to the next case.

You are writing a C# application by using Visual Studio 2015. The application opens a file and reads a single line of data. You create a function named LogError for logging any errors. If a read operation fails, you need to call LogError. You should then rethrow the error so that the calling function can handle it. You need to write the code to properly handle an exception during the read operation. Which block of code should you write?

You should write the block of code below: System.IO.StreamReader file = new System.IO.StreamReader("data.txt"); try { file.ReadLine(); } catch(System.IO.IOException e) { LogError(e.Message); throw; } This block of code correctly places the read operation inside a try block. It then places the call to LogError in a catch block and uses the throw statement to rethrow the exception. This will allow the function that called this function (or any function higher up the call stack) to handle the error. Using throw without any arguments preserves the error object as well, so that it will be available to the parent error handler.

You are writing a C# application by using Visual Studio 2015. The application processes vendors. You define the following: string[]venders = {:Acme","Ltd","Corp"}; You need to call the Process function each for each customer in the list. Which code should you write? (each correct answer presents a complete solution. Choose two.)

You should write the block of code below: void iterate() { for(int i = 0; i < vendors.Length; i++) { Process(vendors[i]); } } This code uses a for loop to iterate from the first element in the array (0) to the last element in the array (Length -1) by using the Length property of the array. You can also write the block of code below: void iterate() { for(int i = 0; i < vendors.Count(); i ++) { Process(vendors[i]); } } This code uses a for loop to iterate from the first element in the array (0) to the last element in the array (count() - 1) by using the Count () extension property of the array.

You are writing a C# application by using visual Studio 2015. The application processes customers. You define the following: List<string> customers; You need to call the Process function for each customer in the list. Which code should you write?

You should write the block of code below: void iterate() { foreach (string c in customers) { Process(c); } } This code correctly uses the foreach statement to iterate through a collection. It properly provides the data type of the items in the collection and provides a variable named c to be used for referencing each item in the loop.

You are creating a C# application by using Visual Studio 2015. You are creating a class to handle customer accounts. The class must meet the following requirements: * The member variables, id, and balance can only be accessed by methods inside the class. * A property should be defined to allow instances of the class to read, but not write the id. * A property should be defined to allow instances of the class to read and write the balance. Which block of code should you write?

You should write the code below: public class Account { private int id; private float balance; public int Id { get { return id; } } public float Balance { set { balance = value; } get { return balance; } } } This code properly uses the private access modifier so that the member variables id and balance are only accessible by methods of the Account class. It uses the public access modifier so that the Id and Balance properties can be accessed by instances of the class. Id only has a get, making it read-only. Balance has both a get and set, making it read and write.

You are creating a C# application by using Visual Studio 2015. Your application creates unmanaged resources. You have created the code below. (Line numbers are included for reference only.) 01 public class Unmanaged:IDisposable 02 { 03 04 public Unmanaged() 05 { 06 this.resource = ... // allocate the resource 07 } 08 public void Dispose() 09 { 10 11 12 } 13 protected virtual void Dispose(bool disposing) 14 { 15 if (disposing) 16 { 17 18 } 19 } 20 } You need to complete the code at lines 03, 10, 11, and 17 to properly dispose of the resources. What should you do? Select the line of code. Place your selections in the order in which the lines of code should be written. A solution may be used once, more than once, or not at all.

You should write the following code in order: * private SafeHandle resource; for line 03 * Dispose(true); for line 10 * GC.SuppressFinalize(this); for line 11 * if (resource !=null)resource.Dispose(); for line 17 The code for line 03 declares resource as a safe handle, which provides support for a finalizer to properly handle disposition of the resource and prevent premature disposition. You should add Dispose(true); to line 10 to call the Dispose method at line 13, setting the disposing parameter to true. This code will be executed when Dispose at line 08 is called by the finalizer and it is now appropriate to manually dispose of the resource. GC.SuppressFinalize(this); is required after the call to Dispose at line 10 to tell the garbage collection routines that this resource has already been finalized and disposed and that finalize should not be called on it again. if (resource !=null)resource.Dispose(); is required to manually dispose of the resource. The resource !=null check is required in case the Dispose method is called and the resource is no longer defined.

You are writing a C# application by using Visual Studio 2015. You are creating a custom class to handle error logging. You create the following custom EventArgs class: public class ErrorEventArgs : EventArgs { private string error; public ErrorEventArgs(string e) { error = e; } public string Error { get{return error;} } } You need to declare a delegate that will correctly use the custom event arguments. Which line of code should you use?

You should write the line of code below: public delegate void ErrorEventHandler(object sender, ErrorEventArgs a); This line correctly declares the event handler by using the name of the event (Error) followed by EventHandler. It then sends the two required parameters in the correct order: first an object for the sender, then an ErrorEventArgs object.

You are developing a library by using C# and Microsoft Visual Stduio 2015. Your library handles customer data. Your library requires a Customer class. This class must include a property called name. The value of this property should not be stored when the value is either null or an empty string, except when it is initialized. Applications that use the Customer class should not be able to take a reference to the variable, and they should not be able to bypass the validation logic. Complete the Name property declaration by dragging the code fragments from the list on the left to the appropriate location on the right. You may use items more than once, and you do not have to use each item.

Your code should look like this: public class Customer { private string _name = ""; public string Name { get { return this._name; } set { if (string.IsNullOrempty(value)) throw new ArgumentException(); this._name = value; } } # region implementation omitted #endregion } A property is a class member that encapsulates data by declaring two special methods that are invoked by using variable-assignment and variable-reference syntax. This allows you to centralize validation and dynamic calculation logic. This also prevents other code from taking a reference to your data, because it only obtains a reference to a method instead of a variable. A basic property declaration requires a data type, a property name, a get black if the property is readable, and a set block if the property is writable. For example, the most simple property declaration - an auto-property - is: public class Customer { public string Name { get; set; } } when your property requires custom validation or calculation logic, you should implement the individual get and set blcks. These blocks require a storage location to retrieve and store the data, respectively. You generally use a private variable for storage. The get block is written like a function that accepts no parameters and has a return value of the same type as the property. The set block is written like a function that uses a keyword instead of a named parameter, and does not have a return value. For example, a basic property pattern is: public class Customer { private string _name; public string Name { get { return this._name; } set { this._name = value; } } } It is common for a set block to error-check the value argument before storing it in the variable. The only way to indicate a validation error is to throw an exception because a set block may not return a value. You could use the ArgumentException class to indicate an invalid value. In the example, the value must not be stored if it is null or empty. If you implement this error check and add code to initialize the variable, you create the complete declaration listed above.

You are developing a marketing campaign application by using C# and Microsoft Visual Studio 2015. Your application needs to process customer records retrieved from the database. Your code includes a variable named customers, declared as an array of Customer objects. You need to pass each object to a method called AddToCampaign. This method accepts a Customer argument and does not return a value. Which code block correctly processes each customer object?

foreach (Customer c in customers) AddToCampaign(c); The foreach loop simplifies the process of enumerating a list of objects. The basic syntax is: foreach(<range variable>in<list>) <statement block>; The foreach loop executes your statement block exactly once for every element in the list of objects. The range variable is assigned the current value in the list at the beginning of each iteration of your statement block. If there are no elements in the list, no iterations execute. The list may be any class that implements the System.Collections.IEnumerable interface. This includes the classes in the System.Collections, System.Collections.Generic, and System.collections.ObjectModel namespace. This interface is implemented in a significant number of other .NET framework class Library (FCL) classes.

You are developing an application by using C# 5.0 and Visual Studio 2012. You create a class that includes this code: (Line numbers are included for reference purposes only.) 01 public class MyClass 02 { 03 private Idisposable dependentObject; 04 public MyClass (IDisposable dependency) 05 { 06 this.dependentObject = dependency; 07 ... 08 09 } 10 ... 11 12 } You need to change this code so that the object reference in MyClass does not keep the Garbage Collector from reclaiming the object. What should you do? (Each correct answer presents part of the solution. Choose all that apply.)

to ensure that the object reference in MyClass does not keep the Garbage Collector from reclaiming the object, you should use the WeakReference class. This class exposes a property called Target that contains the object reference. It also exposes a property called Isalive, a Boolean value that is true if the Target property is usable, and false if the object has been collected. If a candidate object is referenced (rooted) only by the Target property of one or more WeakReference objects, the garbage Collector collects the candidate object. To use a WeakReference, you should change Line 03 to read: private WeakReference dependentObject; You should also change Line 06 to read: this.dependentObject = new WeakReference(dependency);


Related study sets

Adjetivos de nacionalidad que terminan en consonante (-l,-n,-s,-z) forman el femenino añadiendo una (-a) al masculino

View Set

Chap 4 Quiz, Volcano's and Igneous Rocks

View Set

Marital Law + Community Property

View Set

New Constitutional Powers - Exam 1 (POLS 3223)

View Set

Introduction to Geometry - Figures

View Set