mcts self paced training kit exam 70-536 microsoft net framework 3.5 application development foundation phần 4 pot

82 387 0
mcts self paced training kit exam 70-536 microsoft net framework 3.5 application development foundation phần 4 pot

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

214 Chapter Review Case Scenarios In the following case scenarios, you apply what you’ve learned about how to implement and apply serialization, as well as how to upgrade applications that make use of serialization You can find answers to these questions in the “Answers” section at the end of this book Case Scenario 1: Choosing a Serialization Technique You are an application developer for City Power & Light For the last year, you and your team have been creating a distributed NET Framework solution to replace the antiquated system that currently accounts for electrical usage and distributes bills to customers You have created components for monitoring electrical usage, and you are at the stage of development when you need to transmit usage information to the billing system Your manager asks you to interview key people and then answer some questions about your design choices Interviews The following is a list of company personnel you interviewed and their statements: “I’ve already got my guy working on this, and he has built methods with NET that accept your Usage objects and add billing information to the database So we just need you to create those objects and send them over the internal network to us.” Billing System Development Manager “All the accounting and billing servers are on the same subnet, so you don’t have to worry about your network traffic going through any firewalls I would like you to try and minimize the bandwidth used—we have millions of accounts, and that subnet is close to being saturated already.” Network Manager Questions Answer the following questions for your manager: Which serialization method will you use? What changes will you need to make to your class to enable serialization? About how many lines of code will you need to write to perform the serialization? Chapter Review 215 Case Scenario 2: Serializing Between Versions You are an application developer working for Humongous Insurance Recently, you have launched version 1.0 of Incident, an application based on an earlier version of the NET Framework that tracks insurance events throughout their life cycle Subsequent to this successful launch, you have begun development of Incident 2.0 Incident 2.0 is based on the latest version of the NET Framework During a planning meeting, your manager asks you questions about how Incident 2.0 will handle the upgrade process during deployment Questions Answer the following questions for your manager: In Incident 1.0, I know you save some user preferences, such as window position, to a file by serializing your Preferences object using BinaryFormatter Now that the application will be based on a newer version of the NET framework, will you be able to deserialize those settings directly in Incident 2.0 if you don’t make any changes to the Preferences class? We have some feature requests that will require you to add more preferences If you add more members to the Preferences class, will you still be able to deserialize settings stored from the previous version? If so, what special accommodations will you need to make? The IT department has requested we switch to using XML-based configuration files so that they can edit them more easily How could you deserialize the existing binary-formatted object, while serializing an XML object? Suggested Practices To help you successfully master the “Implementing serialization and input/output functionality in a NET Framework application” exam objective, complete the following tasks Serialize or Deserialize an Object or an Object Graph by Using Runtime Serialization Techniques For this task, you should complete at least Practices and If you want a better understanding of how serialization can be used in the real world and you have the resources needed to Practice 3, complete it as well 216 Chapter Review Using the last custom class that you created as part of your job, modify it so that it can be serialized Then write an application to serialize and deserialize it using BinaryFormatter Examine the serialized data Then modify the application to use SoapFormatter Examine the serialized data Practice Examine the class that you used in Practice and, if possible, identify a member that does not need to be serialized Modify your class so that the member will not be serialized but will be defined automatically upon deserialization Practice Write a client/server application to transfer an object between two networked computers using serialization and deserialization Practice Control the Serialization of an Object into XML Format by Using the System.Xml.Serialization Namespace For this task, you should complete all three practices to gain experience using XML serialization with real-world classes and schema Write an application that uses XML serialization to serialize and deserialize the last class that you created as part of your job Practice Examine the class that you used in Practice and, if possible, identify a member that does not need to be serialized Use an attribute to modify your class so that the member will not be serialized Practice Find an XML schema on the Internet and create a class that, when serialized, conforms to that XML schema Create the class using two different techniques: manually and with Xsd.exe Practice Implement Custom Serialization Formatting by Using the Serialization Formatter Classes For this task, you should complete at least Practices and If you want in-depth knowledge of the serialization process, complete Practice as well Using the last custom class that you created as part of your job, modify it so that it implements ISerializable and can be successfully serialized and deserialized Examine the members to determine whether you can optimize serialization by omitting calculated values Practice Create a class that provides methods for all four BinaryFormatter serialization events Practice Chapter Review 217 Implement the IFormatter interface to create a custom formatter Use it during serialization and deserialization to understand the formatter’s role in serialization Practice Take a Practice Test The practice tests on this book’s companion CD offer many options For example, you can test yourself on just one exam objective, or you can test yourself on all the 70-536 certification exam content You can set up the test so that it closely simulates the experience of taking a certification exam, or you can set it up in study mode so that you can look at the correct answers and explanations after you answer each question MORE INFO Practice Tests For details about all the practice test options available, see the section ”How to Use the Practice Tests” in the Introduction of this book Chapter Graphics You can use graphics to enhance the user interface of your applications, generate graphical charts and reports, and edit or create images The NET Framework includes tools that allow you to draw lines, shapes, patterns, and text This chapter discusses how to create graphics and images using the classes in the System.Drawing namespace NOTE WPF Graphics NET Framework versions 3.0 and later include Windows Presentation Foundation (WPF), which provides robust graphics capabilities beyond those provided by the System.Drawing namespace However, the 70-536 certification exam covers only the System.Drawing namespace Therefore, for the purpose of this exam, you should disregard the WPF graphics capabilities Exam objectives in this chapter: Enhance the user interface of a NET Framework application by using the Sysem.Drawing namespace Enhance the user interface of a NET Framework application by using brushes, pens, colors, and fonts Enhance the user interface of a NET Framework application by using graphics, images, bitmaps, and icons Enhance the user interface of a NET Framework application by using shapes and sizes Lessons in this chapter: Lesson 1: Drawing Graphics 221 Lesson 2: Working with Images 243 Lesson 3: Formatting Text 250 219 220 Chapter Graphics Before You Begin To complete the lessons in this chapter, you should be familiar with Microsoft Visual Basic or C# and be comfortable with the following tasks: Creating a Windows Forms or WPF application in Microsoft Visual Studio using Visual Basic or C# Adding namespaces and system class library references to a project Writing to files and streams Lesson 1: Drawing Graphics 221 Lesson 1: Drawing Graphics You can use the NET Framework to enhance the user interface by drawing lines, circles, and other shapes With just a couple of lines of code, you can display these graphics on a form or other Windows Forms control After this lesson, you will be able to: Describe the members of the System.Drawing namespace Control the location, size, and color of controls Draw lines, empty shapes, and solid shapes Customize pens and brushes to enhance graphics Estimated lesson time: 60 minutes The System.Drawing Namespace The NET Framework includes the System.Drawing namespace, which enables you to create graphics from scratch or modify existing images With the System.Drawing namespace, you can the following: Add circles, lines, and other shapes to the user interface dynamically Create charts from scratch Edit and resize pictures Change the compression ratios of pictures saved to disk Crop or zoom pictures Add copyright logos or text to pictures This lesson focuses on drawing graphics Lesson covers working with images, and Lesson describes how to format text Table 6-1 lists the most important classes in the System.Drawing namespace, which you can use to build objects used for creating and editing images Of these classes, you use Graphics the most because it provides methods for drawing to the display device The Pen class is used to draw lines and curves, while classes derived from the abstract class Brush are used to fill the interiors of shapes In addition, you should be familiar with the PictureBox class (in the System.Windows.Forms namespace), which you can use in Windows Forms applications to display an image as part of the user interface The System.Drawing namespace includes the structures shown in Table 6-2 222 Chapter Graphics Table 6-1 System.Drawing Classes Class Description Bitmap Encapsulates a GDI+ (Graphical Device Interface) bitmap, which consists of the pixel data for a graphics image and its attributes A Bitmap object is an object used to work with images defined by pixel data This is the class you use when you need to load or save images Brush Classes derived from this abstract base class, described in the section “How to Fill Shapes,” later in this lesson, define objects used to fill the interiors of graphical shapes such as rectangles, ellipses, pies, polygons, and paths Brushes Provides brushes for all the standard colors This class cannot be inherited Use this class to avoid creating an instance of a Brush class ColorConverter Converts colors from one data type to another Access this class through the TypeDescriptor ColorTranslator Translates colors to and from GDI+ Color structures This class cannot be inherited Font Defines a particular format for text, including font face, size, and style attributes This class cannot be inherited FontConverter Converts Font objects from one data type to another Access the FontConverter class through the TypeDescriptor object FontFamily Defines a group of type faces having a similar basic design and certain variations in styles This class cannot be inherited Graphics Encapsulates a GDI+ drawing surface This class cannot be inherited You use this class anytime you need to draw lines, draw shapes, or add graphical text to a control or image Icon Represents a Microsoft Windows icon, which is a small bitmap image used to represent an object Icons can be thought of as transparent bitmaps, although their size is determined by the system Lesson 1: Drawing Graphics Table 6-1 223 System.Drawing Classes Class Description IconConverter Converts an Icon object from one data type to another Access this class through the TypeDescriptor object Image An abstract base class that provides functionality for the Bitmap- and Metafile-descended classes ImageAnimator Animates an image that has time-based frames ImageConverter Converts Image objects from one data type to another Access this class through the TypeDescriptor object ImageFormatConverter Converts colors from one data type to another Access this class through the TypeDescriptor object Pen Defines an object used to draw lines, curves, and arrows This class cannot be inherited Pens Provides pens for all the standard colors This class cannot be inherited Use this class to avoid creating an instance of a Pen class PointConverter Converts a Point object from one data type to another Access this class through the TypeDescriptor object RectangleConverter Converts rectangles from one data type to another Access this class through the TypeDescriptor object Region Describes the interior of a graphics shape composed of rectangles and paths This class cannot be inherited SizeConverter The SizeConverter class is used to convert from one data type to another Access this class through the TypeDescriptor object SolidBrush Defines a brush of a single color Brushes are used to fill graphics shapes, such as rectangles, ellipses, pies, polygons, and paths This class cannot be inherited StringFormat Encapsulates text layout information (such as alignment and line spacing), display manipulations (such as ellipsis insertion and national digit substitution), and OpenType features This class cannot be inherited Lesson 2: Managing Threads 281 catch (ThreadAbortException ex) { Console.WriteLine("DoWork was aborted."); } finally { Console.WriteLine("Use finally to close all open resources."); } Console.WriteLine("DoWork has ended."); } This program outputs the following: DoWork is running on another thread DoWork was aborted Use finally to close all open resources The Main() thread is ending Notice that the DoWork method never outputs “DoWork has ended.” because the thread was aborted while DoWork was executing Thread.Sleep If you were to comment out the DoWorkThread.Abort call, DoWork would finish running IMPORTANT Calling Thread.Suspend You can call Thread.Suspend and Thread.Resume to pause and resume a thread’s execution However, those methods have been deprecated Because Thread.Suspend and Thread.Resume not rely on the cooperation of the thread being controlled, they are highly intrusive and can result in serious application problems like deadlocks (for example, if you suspend a thread that holds a resource that another thread needs) Instead, you should use an instance of Monitor, as described in the section “Synchronizing Access to Resources,” later in this chapter After you create a thread, but before starting a thread, you can set the Thread.Priority property using the ThreadPriority enumeration Thread priority controls how the operating system schedules time to a thread Generally, threads with higher priorities run before threads with lower priorities Therefore, if you create two threads that perform processor-intensive work—one with a priority of Highest and one with a priority of Lowest, the thread with the priority of Highest finishes first From highest to lowest priority, your options are the following: Highest AboveNormal Normal BelowNormal Lowest By default, threads and applications run with Normal priority 282 Chapter Threading Thread State You can check a thread’s state using the Thread.ThreadState property Threads can be in any of the following states: Unstarted The initial state before a thread is started The thread is active and executing, typically as a result of another thread calling Thread.Start Running Stopped The thread has stopped The thread is waiting for another thread to complete Typically this happens after calling Thread.Join on another thread WaitSleepJoin The thread is currently responding to a Thread.Suspend request When you call Thread.Suspend, the Common Language Runtime (CLR) allows the thread to execute until it has reached a safe point before actually suspending the thread A safe point for a thread is a point in its execution at which garbage collection can be performed SuspendRequested Suspended The thread has been suspended because another thread called Thread.Suspend AbortRequested Aborted The thread is currently responding to a Thread.Abort request The thread has been suspended because another thread called Thread Abort Threads are often in more than one state at any given time For example, if a thread is blocked on a Monitor.Wait call and another thread calls Abort on that same thread, the thread is in both the WaitSleepJoin and the AbortRequested state at the same time In that case, as soon as the thread returns from the call to Wait or is interrupted, it receives the ThreadAbortException Passing Data to and from Threads Up to this point, the threading examples called a method without providing any parameters and without retrieving any data from the thread In practice, you almost always need to provide data to a thread (such as providing a print job or data to process) and retrieve the results from the thread To provide data to a thread, create a class with a constructor that accepts one or more parameters and stores the data You create an instance of this class and use that instance when you create your ThreadStart object Lesson 2: Managing Threads 283 To retrieve data from a thread, create a method that accepts the return results as a parameter Then, create a delegate for the method Pass the delegate and the method itself as an additional parameter to your class constructor The following code sample demonstrates this technique The Multiply class constructor accepts the data that will be processed by the new thread The Multiply.ThreadProc method performs the actual processing, which simply involves displaying a text message and multiplying an integer by The ResultCallback method accepts the return value from Multiply.ThreadProc, and ResultDelegate is the delegate for the ResultCallback method: ' VB Sub Main() ' Supply the state information required by the task Dim m As New Multiply("Hello, world!", 13, New ResultDelegate( _ AddressOf ResultCallback)) Dim t As New Thread(New ThreadStart(AddressOf m.ThreadProc)) t.Start() Console.WriteLine("Main thread does some work, then waits.") t.Join() Console.WriteLine("Thread completed.") Console.ReadKey() End Sub ' The callback method must match the signature of the callback delegate Sub ResultCallback(ByVal retValue As Integer) Console.WriteLine("Returned value: {0}", retValue) End Sub Public Class Multiply ' State information used in the task Private greeting As String Private value As Integer ' Delegate used to execute the callback method when the task is ' complete Private callback As ResultDelegate ' The constructor obtains the state information and the callback ' delegate Public Sub New(ByVal _greeting As String, ByVal _value As Integer, _ ByVal _callback As ResultDelegate) greeting = _greeting value = _value callback = _callback End Sub 284 Chapter Threading ' The thread procedure performs the tasks (displaying ' the greeting and multiplying the value by 2) Public Sub ThreadProc() Console.WriteLine(greeting) If (callback Nothing) Then callback(value * 2) End If End Sub End Class ' Delegate that defines the signature for the callback method Delegate Sub ResultDelegate(ByVal value As Integer) // C# class Program { static void Main() { // Supply the state information required by the task Multiply m = new Multiply("Hello, world!", 13, new ResultDelegate(ResultCallback)); Thread t = new Thread(new ThreadStart(m.ThreadProc)); t.Start(); Console.WriteLine("Main thread does some work, then waits."); t.Join(); Console.WriteLine("Thread completed."); Console.ReadKey(); } // The callback method must match the signature of the callback delegate public static void ResultCallback(int retValue) { Console.WriteLine("Returned value: {0}", retValue); } } public class Multiply { // State information used in the task private string greeting; private int value; // Delegate used to execute the callback method when the task is complete private ResultDelegate callback; // The constructor obtains the state information and the callback delegate public Multiply(string _greeting, int _value, ResultDelegate _callback) { greeting = _greeting; value = _value; callback = _callback; } Lesson 2: Managing Threads 285 // The thread procedure performs the tasks (displaying // the greeting and multiplying the value by 2) public void ThreadProc() { Console.WriteLine(greeting); if (callback != null) callback(value * 2); } } // Delegate that defines the signature for the callback method public delegate void ResultDelegate(int value); The previous code sample outputs the following: Main thread does some work, then waits Hello, world! Returned value: 26 Thread completed Synchronizing Access to Resources If an application needs to write to a file, it typically locks the file Locking the file prevents other applications from accessing it If another application needs to access the file, it either must wait for the lock to be released or cancel the action that requires the file Multithreaded applications have similar challenges when accessing shared resources To reduce problems, the NET Framework provides synchronization objects that you can use to coordinate resources shared among multiple threads Resources that require synchronization include the following: System resources (such as communications ports) Resources shared by multiple processes (such as file handles) The resources of a single application domain (such as global, static, and instance fields) accessed by multiple threads Object instances that are accessed by multiple threads To understand what can happen if you don’t synchronize access to resources in a multithreaded application, consider the following Console application The constructor for the Math class accepts two integer values and provides methods to perform calculations using those values However, the calculations take a full second to complete—therefore, the private result variable might be overwritten by other 286 Chapter Threading threads between the time the calculation is performed and the time the result is displayed to the console: ' VB Sub Main() Dim m As New Math(2, 3) Dim t1 As New Thread(New ThreadStart(AddressOf m.Add)) Dim t2 As New Thread(New ThreadStart(AddressOf m.Subtract)) Dim t3 As New Thread(New ThreadStart(AddressOf m.Multiply)) t1.Start() t2.Start() t3.Start() ' Wait for the user to press a key Console.ReadKey() End Sub Class Math Public value1 As Integer Public value2 As Integer Private result As Integer Public Sub New(ByVal _value1 As Integer, ByVal _value2 As Integer) value1 = _value1 value2 = _value2 End Sub Public Sub Add() result = value1 + value2 Thread.Sleep(1000) Console.WriteLine("Add: " + result.ToString) End Sub Public Sub Subtract() result = value1 - value2 Thread.Sleep(1000) Console.WriteLine("Subtract: " + result.ToString) End Sub Public Sub Multiply() result = value1 * value2 Thread.Sleep(1000) Console.WriteLine("Multiply: " + result.ToString) End Sub End Class // C# class Program { static void Main() { Math m = new Math(2, 3); Lesson 2: Managing Threads 287 Thread t1 = new Thread(new ThreadStart(m.Add)); Thread t2 = new Thread(new ThreadStart(m.Subtract)); Thread t3 = new Thread(new ThreadStart(m.Multiply)); t1.Start(); t2.Start(); t3.Start(); // Wait for the user to press a key Console.ReadKey(); } } class Math { public int value1; public int value2; private int result; public Math(int _value1, int _value2) { value1 = _value1; value2 = _value2; } public void Add() { result = value1 + value2; Thread.Sleep(1000); Console.WriteLine("Add: " + result); } public void Subtract() { result = value1 - value2; Thread.Sleep(1000); Console.WriteLine("Subtract: " + result); } public void Multiply() { result = value1 * value2; Thread.Sleep(1000); Console.WriteLine("Multiply: " + result); } } At first glance, you might expect that this Console application should display the following output: Add: Subtract: -1 Multiply: 288 Chapter Threading However, because the Math.Multiply method was called last and the first two threads were in a Sleep state, Math.Multiply overwrote the value of result before Math.Add and Math.Subtract could display the value So, the actual output is as follows: Add: Subtract: Multiply: The sections that follow describe different techniques for synchronizing access to resources Just as the file system uses file locks to prevent different applications from accessing the same file, you can use the Monitor class to lock objects and prevent a specific section of code from running until the object is unlocked Although you can use the Monitor class correctly, it’s much easier to use built-in keywords to call the Monitor.Enter and Monitor.Exit methods In C#, use the keyword lock to specify the object to monitor In Visual Basic, use the keyword SynLock Monitor You can fix the console application in the previous section by using the Monitor class and the lock or SynLock keywords The following code sample updates the Math class from the previous code sample to use locking and allows the Math class to provide accurate results: ' VB Class Math Public value1 As Integer Public value2 As Integer Private result As Integer Public Sub New(ByVal _value1 As Integer, ByVal _value2 As Integer) value1 = _value1 value2 = _value2 End Sub Public Sub Add() SyncLock Me result = value1 + value2 Thread.Sleep(1000) Console.WriteLine("Add: " + result.ToString) End SyncLock End Sub Public Sub Subtract() SyncLock Me result = value1 - value2 Thread.Sleep(1000) Console.WriteLine("Subtract: " + result.ToString) End SyncLock End Sub Lesson 2: Managing Threads Public Sub Multiply() SyncLock Me result = value1 * value2 Thread.Sleep(1000) Console.WriteLine("Multiply: " + result.ToString) End SyncLock End Sub End Class // C# class Math { public int value1; public int value2; private int result; public Math(int _value1, int _value2) { value1 = _value1; value2 = _value2; } public void Add() { lock (this) { result = value1 + value2; Thread.Sleep(1000); Console.WriteLine("Add: " + result); } } public void Subtract() { lock (this) { result = value1 - value2; Thread.Sleep(1000); Console.WriteLine("Subtract: " + result); } } public void Multiply() { lock (this) { result = value1 * value2; Thread.Sleep(1000); Console.WriteLine("Multiply: " + result); } } } 289 290 Chapter Threading The SynLock Me and lock (this) calls allow the code to run only if no other section of code currently has the object locked Therefore, the t2 instance cannot run the Subtract method until the t1 instance has completed running the Add method, preventing the result value from being overwritten Monitor locks reference types (also known as objects), not value types Therefore, while the previous code sample could lock the current instance of the Math class, it couldn’t lock the result integer because result is a value type Using the Monitor class and the SynLock or lock keyword is a straightforward way to prevent two threads from accessing a resource simultaneously However, the Monitor class does not distinguish between read and write locks ReaderWriterLock By providing separate logic for read and write locks, you can improve the efficiency of multithreaded applications in which multiple threads might need to read a value simultaneously Typically, the methods reading the resource need to keep the resource open for an extended period of time for there to be a significant improvement For example, consider an application that used three threads, each of which spent several seconds reading a file from memory, and a fourth thread that occasionally updated the file Using Monitor, only one thread could access the file at a time—if two threads wanted to read the file simultaneously, one would need to wait Using ReaderWriterLock, you could allow the threads to all read the file simultaneously The only time a thread could not read the file is when a thread was writing to the file For example, consider the following Console application, which uses the standard Monitor locks to protect access to the file resource This application takes about nine seconds to run: ' VB Sub Main() Dim m As New MemFile() Dim Dim Dim Dim t1 t2 t3 t4 As As As As New New New New Thread(New Thread(New Thread(New Thread(New ThreadStart(AddressOf ThreadStart(AddressOf ThreadStart(AddressOf ThreadStart(AddressOf t1.Start() t2.Start() t3.Start() t4.Start() End Sub Class MemFile Private file As String = "Hello, world!" m.ReadFile)) m.WriteFile)) m.ReadFile)) m.ReadFile)) Lesson 2: Managing Threads Public Sub ReadFile() SyncLock Me For i As Integer = To Console.WriteLine(file) Thread.Sleep(1000) Next End SyncLock End Sub Public Sub WriteFile() SyncLock Me file += " It's a nice day!" End SyncLock End Sub End Class // C# static void Main(string[] args) { MemFile m = new MemFile(); Thread Thread Thread Thread t1 t2 t3 t4 = = = = new new new new Thread(new Thread(new Thread(new Thread(new ThreadStart(m.ReadFile)); ThreadStart(m.WriteFile)); ThreadStart(m.ReadFile)); ThreadStart(m.ReadFile)); t1.Start(); t2.Start(); t3.Start(); t4.Start(); } class MemFile { string file = "Hello, world!"; public void ReadFile() { lock (this) { for (int i = 1; i

Ngày đăng: 12/08/2014, 20:22

Từ khóa liên quan

Mục lục

  • Chapter 5: Serialization

    • Case Scenarios

      • Case Scenario 1: Choosing a Serialization Technique

      • Questions

      • Case Scenario 2: Serializing Between Versions

      • Questions

      • Suggested Practices

        • Serialize or Deserialize an Object or an Object Graph by Using Runtime Serialization Techniques

        • Control the Serialization of an Object into XML Format by Using the System.Xml.Serialization Namespace

        • Implement Custom Serialization Formatting by Using the Serialization Formatter Classes

        • Take a Practice Test

        • Chapter 6: Graphics

          • Before You Begin

          • Lesson 1: Drawing Graphics

            • The System.Drawing Namespace

            • How to Specify the Location and Size of Controls

            • How to Specify the Color of Controls

              • How to Draw Lines and Shapes

              • How to Customize Pens

              • How to Fill Shapes

              • Lab: Create a Method to Draw a Pie Chart

              • Lesson Summary

              • Lesson Review

              • Lesson 2: Working with Images

                • The Image and Bitmap Classes

                • How to Display Pictures

                • How to Create and Save Pictures

Tài liệu cùng người dùng

Tài liệu liên quan