Chapter . Answers to Chapter Exercises

A1:

The .NET Framework Redistributable is required by a client to run a .NET application and is available as a free download on the Internet.

A2:

Managed code is produced by a compiler that meets the Common Type System (CTS) requirements that are necessary before code produced by it can be run by the Common Language Runtime (CLR). Unmanaged code does not meet the CTS standard. The Windows API and COM objects are examples of unmanaged code.

A3:

The Common Type System defines the types and their members that must be used by compilers that create code to run on the Common Language Runtime. The Common Language Specification provides stricter requirements that ensure interoperability between languages.

A4:

All .NET compilers generate an Intermediate Language (IL) code. Since IL is compatible, irrespective of its source, the CLR doesn't care which compiler produces it.

A5:

The Global Assembly Cache (GAC) holds shared assemblies—assemblies that can be used by more than one application. Assemblies in the GAC have a digital signature that uniquely identifies them, even if they have the same file name.

A6:

A strong name consists of an assembly name, a version, a culture setting, and a public key token that is required by a client to use the assembly.

A7:

A namespace usually identifies a group of types that provide related services. An assembly may contain one or more namespaces. Also, a namespace may contain types in more than one assembly.

A8:

CLR—Common Language Runtime

FCL—Framework Class Library

GAC—Global Assembly Cache

IL—Intermediate Language (also, CIL or MSIL)

A1:

A C# program must have an entry point defined by the static Main() method. It accepts a string array args as input.

A2:

// is used for single line comments; /* */ is used to enclose multi-line comments; and /// is used to create XML comments that can be exported to a text file.

A3:

A primitive refers to a simple value type such as an int or byte.

A4:

true

A5:

A do loop is evaluated at the end of the iteration and thus must execute at least once.

A6:

A break statement causes control to exit the enclosing loop immediately; a continue statement continues the same loop by skipping to the beginning of the loop.

A7:

a does not compile because an int cannot be converted to a char. c does not compile because a string cannot be converted to a char.

A8:

Each time concatenation occurs, a new string is created in memory. For a large number of concatenations, this wastes memory and also degrades performance. The StringBuilder class can be used as an alternative—but only where there are many concatenations. Otherwise, it will not outperform concatenation.

A9:

All classes inherit from System.Object. In addition, value types inherit from System.ValueType.

A10:

7

A1:

A sealed class cannot be inherited. A sealed class is used primarily when the class contains static members. Note that a struct is implicitly sealed.

A2:

A class can inherit from one class explicitly and inherits from System.Object implicitly. It can inherit from any number of interfaces.

A3:

  1. ShowName is static and cannot be referenced from a class instance.

  2. ShowName.ShowMe("My Name is Ishmael");
    

A4:

An abstract class may contain both abstract and non-abstract methods.

A5:

new is used to replace (not override) an inherited method with one of the same name.

A6:

(a) x=60 y=40. x is passed by reference; y by value.

A7:

Include a method that performs the same operation as the operator overloading.

A8:

A class cannot be instantiated if it is abstract or if it has a private constructor.

A9:

Example event handler:

private void PrintSale(object sender, SaleEvArgs e)
{
   decimal prc=  (decimal)e.saleprice;
   DateTime dt = (DateTime)e.date;
   int itemNum = (int)e.itemnum;
   // Now print the values
}

A10:

(a) Compilation error indicating that keyword new is required on Child.amethod(int, string) because it hides the inherited method. If new is used, the code prints “Base Constructor”.

A1:

The advantages of a class factory pattern are that it can control the number of objects created, encapsulates the logic required to create an object, and makes it easier to add new products by isolating the code in the factory.

A2:

Custom exceptions should inherit from the ApplicationException class. Three constructors should be included: a parameterless one, a constructor accepting a string parameter, and a constructor that accepts a string and Exception object parameter.

A3:

System.Object.Equals bases equality on objects having the same memory location.

A4:

A class must implement the IEnumerable and IEnumerator interfaces to support the foreach statement.

A5:

Generics permit a collection to be type-safe. This means the collection class is restricted to holding and processing objects of one type. Non-generic collections can hold any mixture of objects and require casting to detect their type.

A6:

The IDisposable interface is a convenient way to notify a client that an object's Dispose method should be called. The client only needs to check for the existence of the interface.

A7:

  1. false
    
  2. true
    
  3. false
    
  4. true
    

The Clone method creates a copy of an object at a new address.

A8:

Objects with a Finalize method implemented are placed in a special queue so that Finalize can be executed before Garbage Collection occurs. This delays the actual Garbage Collection by one cycle.

A1:

CultureInfo represents information about a culture. Here is an example of its use:

CultureInfo ci = new CultureInfo("de-AT");  // German-Austria

A2:

CultureInfo() with no parameters and Thread.CurrentThread.CurrentCulture return objects with current culture.

A3:

  1. 2

  2. 3

  3. 1

A4:

Use the instance method when the expression is used repeatedly, because, unlike the static approach, it does not have to recompile the expression each time.

A5:

Equals() is used to check the memory location. If different, a character-by-character comparison is performed.

A6:

  1. 2

  2. 1

  3. 3

A7:

a. FileInfo is not created from a FileStream.

A8:

a

A9:

  1. true
    
  2. true
    
  3. false
    
  4. false
    

A1:

System.Windows.Forms.Form is the required base class for a Windows application.

A2:

Docking attaches a control to an edge of its container; anchoring places a control in a fixed position relative to the edge(s) of a container. As the container is resized, the control remains a fixed distance from the edges.

A3:

x and y yield the coordinates. The Button property is set to a MouseButtons enumeration value.

A4:

The Form.TransparencyKey permits part of a form to appear transparent. Any part of the Form have the color assigned to this property becomes transparent. For example, to set the red portion of myForm to red, set the TransparencyKey as follows:

myForm.TransparencyKey = Color.Red;

A5:

A modal form maintains focus until it is closed. A modeless form allows the parent form to regain focus.

A6:

The owned form is always on top, and closing or minimizing the parent also closes or minimizes the owned form.

A7:

Minimize and Maximize properties are set to false; the HelpButton property is set to true.

A8:

A MouseOver displays information associated with a control's ToolTip. Help text is enabled by pressing F1 or selecting the Help button and clicking a control to show context-sensitive Help.

A9:

Have the original event handler in the base Form call a virtual method to deal with the event. The inheriting Form then overrides the virtual method.

A1:

Only one radio button in a group may be selected at a time. A GroupBox provides a way to group radio buttons logically.

A2:

SizeMode = PictureBoxSizeMode.StretchImage

A3:

To display selected fields of an object in a ListBox, override the object's ToString() method to display the desired fields.

A4:

The SelectedIndexChanged event is fired. Use the SelectedIndex to get the index of the selected item, or SelectedItem to get the object selected.

A5:

Set View property to View.Details.

A6:

The Tag property can be used to store objects.

A7:

DragEnter and DragDrop must be supported by a destination control for drag and drop to work.

A8:

Assign Browsable, Category, and Description attributes.

A9:

The ResourceManager class is used to access resources. Its GetString(name) method returns the value associated with a name in the text file.

A1:

The Graphics object encapsulates the drawing surface and is used to draw; the ClipRectangle represents the area that needs to be redrawn.

A2:

Control.Invalidate().

A3:

C

A4:

b fails because Brush is an abstract class.

A5:

b is more transparent because its alpha value (200) is less than the value (255) of color a.

A6:

100%. The image is scaled to fit the rectangle.

A7:

Here is one solution:

Graphics g = panel1.CreateGraphics();
g.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath gp = new GraphicsPath();
gp.AddLine(10, 170, 30, 170);
gp.AddLine(16, 100, 100, 100);
gp.AddLine(100, 100, 190, 180);
gp.AddLine(40, 50, 50, 20);
gp.StartFigure();
gp.AddLine(50, 20, 145, 100);
gp.StartFigure();
gp.AddArc(65, 10, 120, 180, 180, 80);
gp.StartFigure();
gp.AddArc(65, 5, 120, 100, 200, 70);
g.DrawPath(new Pen(Color.Black, 2), gp);

A8:

D

A1:

Typeface

A2:

Point is the default measurement for a font. It is 1/72nd of an inch.

A3:

Graphics.DrawString method is used. It is passed a StringFormat object that has its Alignment property set to StringAlignment.Far.

A4:

The third column begins at x coordinate of 310 (usually in 1/100ths of an inch). The tab numbers are cumulative.

A5:

The BeginPrint event is fired when PrintDocument.Print is executed.

A6:

The PrintPageEventArgs parameter has a MarginBounds property that represents the margins.

A7:

To preview a document on the screen, you must create a PrintPreviewDialog object, set its Document property to the PrintDocument, and then call ShowDialog to display the preview:

PrintPreviewDialog prvDialog = new PrintPreviewDialog();
PrvDialog.Document = pd;
PrvDialog.ShowDialog();  // Show preview

A1:

Use its static Create method to create an instance.

A2:

XmlReaderSettings defines how an XmlReader processes the input stream. It can specify node types to be ignored and a schema to be used for validation.

A3:

An XPathDocument is used for reading only.

A4:

  1. Two movies nodes are retrieved: Raging Bull and Taxi Driver.

  2. One movies node is retrieved: Taxi Driver.

  3. One movies node is retrieved: Raging Bull.

  4. Two movie_Title nodes are retrieved: Raging Bull and Taxi Driver.

A5:

Two validation techniques were discussed in this chapter. One approach is to use the XmlReader class directly by setting the Schemas and XsdValidate properties to enable validation. The other approach is to use the XmlValidatingReader class.

A1:

A .NET data provider must supply a connection, command, DataReader, and DataAdapter object to provide access to its data source.

A2:

b is the correct choice. a and c are invalid statements.

A3:

ExecuteNonQuery() executes a command but does not return a resultset.

ExecuteReader() returns a resultset in response to a query.

ExecuteScalar() returns a single value—or null—if the query generates no value.

A4:

The DataReader remains connected to a data source and returns data in a forward, read-only cursor. A DataAdapter is a bridge between a data source and an internal data store. It typically loads data from a data source into a DataSet. It can also update the data source.

A5:

A DataSet object contains one or more DataTables.

A6:

Rejected and Changed are not valid DataRowState values. Detached, Unchanged, and Modified are the other values.

A7:

A DataSet schema can be created (without loading actual XML data) by

DataInferXmlSchema(xml file); 

A1:

  1. False

  2. True

  3. True

  4. False

  5. False

  6. False

  7. True

  8. False

  9. True

A2:

Simple binding occurs on a control that displays a single value; complex binding associates a control with a collection of data in a data source. In one-way data binding, the control is bound to the source for read-only purposes. Changes to the control's value are not reflected in the data source. Two-way binding permits the data source to be updated by changing the control's value(s).

A3:

The properties on a custom data source that expose the bound data must be writable, so the object can be updated.

A4:

DataGridView.SelectionMode =
  DataGridViewSelectionMode.FullRowSelect;

A5:

A ListBox cannot be included in a DataGridView cell. Other controls that can be included are a Link, CheckBox, and Image.

A6:

To freeze a column, set the column's Frozen property to true. The column and all to its left remain visible during scrolling.

dgv.Columns[1].Frozen=true;

A1:

False. An asynchronous delegate may have a return value.

A2:

ia is an IAsyncResult object returned by BeginInvoke that is later passed to EndInvoke

p1 is a string parameter defined in the delegate's signature.

p2 is an optional callback method.

p3 is a value that can be passed to the callback method when the thread ends.

A3:

Thread Local Storage (TLS) holds state information about a thread. This is required when a thread is swapped out before completion.

A4:

The default number of threads in a thread pool is 25.

A5:

ThreadStart and ParameterizedThreadStart delegates are used to create a thread. The latter permits parameters to be passed to a thread.

A6:

lock (this) { } expands into an identical construct.

A7:

a. The message is never printed because the semaphore is created with zero initial threads, and then goes into a wait state.

A8:

b. It prints "Primary Thread" followed by "Worker Thread". The mutex in the main thread is created with ownership. The spawned thread's mutex must wait for the original one to finish before its thread continues processing.

A9:

There are many solutions. Here is one based on not grabbing a chopstick until both are available:

using System;
using System.Threading;
class Stick {
  //Sticks available are designated as true
  bool[] chopStick = {true, true, true, true, true}; 
  // Attempt to pick up left and right chopstick
  public void GetSticks(int left, int right) 
  {
    lock (this) 
    {
      // Release lock and wait until both chopsticks are free
      while (!chopStick[left] && !chopStick[right]) 
         Monitor.Wait(this);
      chopStick[right] = false; chopStick[left] = false;
    }
  }

  // Put chopsticks down
  public void FreeSticks(int left, int right) 
  {
    lock(this) 
    {
      chopStick[right] = true; 
      chopStick[left]  = true;
      // Signal threads in queue that chopsticks are available
      Monitor.PulseAll(this);
    }
  }
}
class Philosopher 
{
  int n;             // Philosopher number 
  int eatDelay;  
  int thinkDelay;
  int left, right;  
  Stick chopSticks;
  public Philosopher (int n, int thinkTime,int eatTime, 
                      Stick sticks) 
  {
    this.n = n;
    this.eatDelay   = eatTime;
    this.thinkDelay = thinkTime;
    this.chopSticks = sticks;
    // Fifth philosopher has chopstick 1 on left
    left = n == 5 ? 1 : n+1;  
    right = n;
    new Thread(new ThreadStart(Run)).Start();
  }
  
  public void Run() 
  {
    while(true)
    {
      try
      {
        // Philosopher thinks for random amount of time
        Thread.Sleep(thinkDelay);
        chopSticks.GetSticks(left-1, right-1);
        Console.WriteLine("Philosopher {0} is eating for 
                        [1} ms ",n, eatDelay);
        Thread.Sleep(eatDelay);
        chopSticks.FreeSticks(left-1, right-1);   
      } catch { return; }
    }
  }
}    // End of class Philosopher

public class Diners 
{
  public static void Main() 
  {
    Stick sticks = new Stick();
    // Create thread for each philosopher
    // Eat time is random
    Random r = new Random(DateTime.Now.Millisecond);
    new Philosopher(1, 100, r.Next(500), sticks);
    new Philosopher(2, 200, r.Next(500), sticks);
    new Philosopher(3, 300, r.Next(500), sticks);
    new Philosopher(4, 400, r.Next(500), sticks);
    new Philosopher(5, 500, r.Next(500), sticks);
  }
}

A1:

  1. True. A process may contain multiple AppDomains.

  2. True. An AppDomain may contain multiple assemblies.

  3. True. An AppDomain may contain .dll and .exe files.

  4. True. An AppDomain can be unloaded from a process.

A2:

Three activation modes: client activation, server activation (single call), and server activation (singleton). HTTP or TCP can be used with all.

A3:

Single call server activation creates a new object on each call; single call singleton creates an object on the first call only. The object is then used for other calls.

A4:

CurrentLeaseTime—Amount of time until object is available for Garbage Collection.

InitialLeaseTime—Initial lifetime of a lease.

RenewalOnCallTime—Amount that CurrentLeaseTime is increased on called object.

A5:

Set the LeaseManagerPoolTime in a configuration file to specify how frequently the lease manager checks for expirations.

A6:

Client-activated and server-activated singleton use leases.

A7:

c. A server-activated singleton object is created when the first call is made to the host object.

A8:

Channel registration indicates the type of protocol to be used—usually TCP or HTTP—in the remoting and the port number to be used. Type registration specifies the available remote object and the activation mode type.

A9:

An interface or SoapSuds is used to prevent having to place a full assembly on the remoting client's machine. The assembly provides metadata, but can also expose proprietary code. An interface provides only the metadata a client requires. SoapSuds extracts the metadata and places it in a file that is deployed on the client's machine.

A1:

  1. False. Only a strongly named assembly may be placed in the GAC—but it does not have to be there.

  2. False. The compiler does not automatically check the GAC for references.

  3. True. The CLR checks the GAC for assembly references.

  4. True. A client must have a valid public key token to use an assembly in the GAC.

A2:

A Permission attribute should be added to the assembly, specifying the permission(s) required by the assembly.

A3:

A strong name consists of a simple name, version number, culture info, and public key token.

A4:

Assign version: [assembly: AssemblyVersion("1.1.0.1")]

Assign culture:  [assembly: AssemblyCulture("fr-CA")]

The default build number is the number of days since 1/1/2000; the default revision number is the number of seconds past midnight divided by 2.

A5:

The IStackWalk interface defines the Assert, Deny, and PermitOnly methods to modify a stack walk. Assert stops the walk; Deny specifies permissions that cause the walk to fail; and PermitOnly specifies the only permissions that do not cause the stack walk to fail..

A6:

Delayed signing refers to using a public key to create a digital signature, as opposed to using the private key. When the final assembly is ready, the private key replaces the public key for encryption. This reduces the need to expose the private key during development.

A7:

A predefined permission is an individual permission class provided by .NET. A named permission set is a predefined set of permission objects. A security zone classifies where an assembly originates: Internet, Intranet, MyComputer, NoZone, Trusted, Untrusted.

A8:

  1. True.

  2. True.

  3. False. <Binding Redirect /> is used to redirect CLR to newer version.

  4. False.

A9:

Add to the configuration:

<binding Redirect OldVersion="1.0.0.0" 
             NewVersion="2.0.0.0" />

A1:

GET and PUT are used to transfer data from a client to a server. PUT is default for ASP.NET.

A2:

  1. True.

  2. True.

  3. False. ASP.NET returns HTML, therefore a client does not require the .NET runtime.

  4. True.

  5. True.

A3:

The ListItem class contains a collection for List controls.

A4:

If the TextBox.AutoPostBack property is set to true, the event handler is called immediately on the server; otherwise, it waits until the next round trip to the server occurs.

A5:

The .Master property allows access to the MasterPage object.

A6:

The DataSource property must be set to the data source, and DataBind must be executed to load the data into the control.

A7:

  1. False. You cannot bind directly to a DataAdapter.

  2. True. A control can bind to a DataReader.

  3. False. It is populated when DataBind is executed.

  4. True. A DataSet or data source control can bind to a control.

A8:

Use a validating control to manage input to a text box.

A9:

The @Register directive is required to specify a custom control.

A10:

The HtmlTextWriter class emits HTML that renders a control.

A11:

The controls in a composite control render themselves and offer the standard properties to work with.

A1:

False. A web.config file is not required.

A2:

pageOutput in the web.config file specifies whether the trace log is appended to the Web page for display on the client's browser. If set to false, the output can be viewed in the trace.axd file in the application's root.

A3:

  1. Windows, Forms, and Microsoft Passport authentication are offered by .NET.

  2. Authentication is specified using the <authentication> element of the web.config file.

  3. Authentication verifies that a user is who he says he is; authorization determines what actions the user may perform or what resources he may access.

  4. The Page.User property provides information about a user.

A4:

Out-of-Process Session management supports storing state information on a server on process on another server.

A5:

<%@ OutputCache Duration="180"  VaryByParam="*"
                                VaryByCustom="Browser"
%>

A6:

A data cache is read-only versus read/write for application state data. However, a data cache is much more flexible: An expiration can be assigned to it, and it can be tied to other objects, causing the cache data to be removed if the objects' value changes.

A7:

ASP.NET periodically invokes a resource scavenging process that removes less important data from a data cache. Importance is determined by priority. Thus, setting a high priority reduces the chance of the data cache being removed.

A8:

As a request or response passes through the HTTP pipeline, an Application object fires a series of events that may be handled by an HTTP module or in the global.asax file.

A1:

System.Web.Services.WebService

A2:

WebService attribute is applied to a class providing a Web Service. It describes the Web Service. WebService directive identifies a file as containing a Web Service.

A3:

Use the Web Service attribute to specify a namespace to uniquely identify a service.

A4:

The Invoke method is used for a synchronous call; BeginInvoke is used for asynchronous.

A5:

Use the Timeout property on the Web Service object to set the timeout in milliseconds.

A6:

The <Service> element contains the target URL for a Web Service.

A7:

A Web method requires the SoapHeader attribute to access the SOAP header info.

A8:

BeginInvoke with polling using the IsCompleted property to check for a response. BeginInvoke with EndInvoke to retrieve results. Call <web service name>Async and implement event handler to process response.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset