Powered By Blogger

19 may 2009

PRUEBATE PARA EL EXAMEN 70-536

PRUEBATE PARA EL EXAMEN 70-536



Questions Exam 70-536 MCTS

Previo a un examen de certificación se necesita poner a prueba los conocimientos sobre Framework .NET 2.0 que sirve parcialmente para el Framework 3.5, razón por la cual presento estas preguntas DE PREPARACION con sus respectivas claves.




1-
You develop a service application named FileService. You deploy the service applicationto multiple servers on your network. You implement the following code segment. (Linenumbers are included for reference only.)01 public :02 void StartService(String^ serverName){0304 ServiceController^ crtl = gcnew05 ServiceController("FileService");06 if (crtl->Status == ServiceControllerStatus::Stopped){}07 }You need to develop a routine that will start FileService if it stops. The routine must startFileService on the server identified by the serverName input parameter.Which two lines of code should you add to the code segment? (Each correct answerpresents part of the solution. Choose two.)


A-Insert the following line of code between lines 03 and 04:crtl.ServiceName =serverName;
B-Insert the following line of code between lines 03 and 04:crtl.MachineName =serverName;
C-Insert the following line of code between lines 03 and 04:crtl.Site.Name =serverName;
D-Insert the following line of code between line 04 and 05:crtl.continue();
E-Insert the following line of code between line 04 and 05:crtl.Start();F- Insert the following line of code between line 04 and 05:crtl.ExecuteCommand(0);


Answer: BE


2-
You need to write a code segment that transfers the first 80 bytes from a stream variablenamed stream1 into a new byte array named byteArray. You also need to ensure that thecode segment assigns the number of bytes that are transferred to an integer variablenamed bytesTransferred. Which code segment should you use?

A-bytesTransferred = stream1.Read(bytesArray,0, 80);
B-for (int i = 0;i <80;i++) {stream1.WriteByte(byteArray[i]);bytesTransferred = i;if (!stream1.CanWrite) {break;}}

C-while (bytesTransferred < 80) {stream1.Seek(1, SeekOrigin.Current);byteArray[bytesTransferred++] =Convert.ToByte(stream1.ReadByte());}

D-stream1.Write(byteArray, 0, 80);bytesTransferred = byteArray.Length;

Answer: A
3-
You use Reflection to obtain information about a method named MyMethod.You need to ascertain whether MyMethod is accessible to a derived class. What shouldyou do?

A-Call the IsAssembly property of the MethodInfo class.B-Call the IsVirtual property of the MethodInfo class.C-Call the IsStatic property of the MethodInfo class.D-Call the IsFamily property of the MethodInfo class.

Answer: D

4-
You need to identify a type that meets the following criteria: ?Is always a number.?Is not greater than 65,535. Which type should you choose?

A-System.UInt16
B-int
C-System.String
D-System.IntPtr

Answer: A

5-
You are developing an application to assist the user in conducting electronic surveys. Thesurvey consists of 25 true-or-false questions. You need to perform the following tasks:Initialize each answer to true.Minimize the amount of memory used by each survey.Which storage option should you choose?

A.BitVector32 answer = new BitVector32(1);B.BitVector32 answer = new BitVector32(-1);
C-BitArray answer = new BitArray (1);D-BitArray answer = new BitArray (-1);

Answer: B

6-
You need to write a code segment that will create a common language runtime (CLR)unit of isolation within an application. Which code segment should you use?

A.AppDomainSetup^ mySetup =AppDomain::CurrentDomain::SetupInformation;mySetup->ShadowCopyFiles = "true";
B.System::Diagnostics::Process^ myProcess;myProcess = gcnew System::Diagnostics::process();
C- C.AppDomain^ domain;domain = AppDomain::CreateDomain("CertKillerDomain")
D.System::ComponentModel::Component^ myComponent;myComponent = gcnew System::ComponentModel::Component();

Answer: C


7-
You are creating a class to compare a specially-formatted string. The default collationcomparisons do not apply. You need to implement the IComparable interface.Which code segment should you use?

A-public class Person : IComparable{public int CompareTo(string other){}}
B-public class Person : IComparable{public int CompareTo(object other){
}}
C-public class Person : IComparable{public bool CompareTo(string other){}}
D-public class Person : IComparable{public bool CompareTo(object other){}}

Answer: A

8-
You need to write a multicast delegate that accepts a DateTime argument and returns aBoolean value. Which code segment should you use?

A-public delegate int PowerDeviceOn(bool, DateTime);
B- public delegate bool PowerDeviceOn(Object, EventArgs);
C- public delegate void PowerDeviceOn(DateTime);
D- public delegate bool PowerDeviceOn(DateTime);

Answer: A


9-
You are developing a class library that will open the network socket connections tocomputers on the network. You will deploy the class library to the global assembly cacheand grant it full trust. You write the following code to ensure usage of the socketconnections.SocketPermission permission =new SocketPermission(PermissionState.Unrestricted);permission.Assert();Some of the applications that use the class library might not have the necessarypermissions to open the network socket connections.You need to cancel the assertion.Which code segment should you use?

A- CodeAccessPermission.RevertAssert();
B- CodeAccessPermission.RevertDeny();
C-Permission.Deny();
D-Permission.PermitDeny();

Answer: A







10-
You are writing a method that returns an ArrayList named al. You need to ensure thatchanges to the ArrayList are performed in a thread-safe manner. Which code segmentshould you use?

A-ArrayList al = new ArrayList();lock (al.SyncRoot){return al;}
B- ArrayList al = new ArrayList();lock (al.SyncRoot.GetType()){return al;}
C- ArrayList al = new ArrayList();Monitor.Enter(al);Monitor.Exit(al);return al;
D- ArrayList al = new ArrayList();ArrayList sync_al = ArrayList.Synchronized(al);return sync_al;

Answer: D

11-
You are working on a debug build of an application.You need to find the line of code that caused an exception to be thrown. Which propertyof the Exception class should you use to achieve this goal?

A- Data
B- Message
C- StackTrace
D- Source

Answer: C

12-
You need to generate a report that lists language codes and region codes.Which code segment should you use?

A- for each (CultureInfo^ culture inCultureInfo::GetCultures(CultureTypes::SpecificCultures)) {// Output the culture information...}
B- CultureInfo^ culture = gcnew CultureInfo("");CultureType^ type = culture->CultureTypes;
// Output the culture information...}
C- for each (CultureInfo^ culture inCultureInfo::GetCultures(CultureTypes::NeutralCultures)) {// Output the culture information...}
D- for each (CultureInfo^ culture inCultureInfo::GetCultures(CultureTypes::ReplacementCultures)) {// Output the culture information...}

Answer: A







13-
You need to serialize an object of type List in a binary format. The object is nameddata.Which code segment should you use?

A- BinaryFormatter^ formatter = gcnew BinaryFormatter();MemoryStream^ stream = gcnew MemoryStream();formatter->Serialize(stream, data);
B- BinaryFormatter^ formatter = gcnew BinaryFormatter();MemoryStream^ stream = gcnew MemoryStream();for (int i = 0;i Count;i++) {formatter->Serialize(stream, data);}
C- BinaryFormatter^ formatter = gcnew BinaryFormatter();byte^ buffer = gcnew array(data->Count);MemoryStream^ stream = gcnew MemoryStream(buffer, true);formatter->Serialize(stream, data);
D- BinaryFormatter^ formatter = gcnew BinaryFormatter();MemoryStream^ stream = gcnew MemoryStream();Capture c(formatter,stream);data->ForEach(gcnew Action(%c,&Capture::Action));

Answer: A

14-

You need to create a method to clear a Queue named q. Which code segment should youuse?

A- for each (Object^ e in q) {q.Dequeue();}
B- for each (Object^ e in q) {q.Enqueue();}
C-q.Clear();

D-q. Dequeue();

Answer: C

15-
You create an application that stores information about your customers who reside invarious regions. You are developing internal utilities for this application.You need to gather regional information about your customers in Canada.Which code segment should you use?

A- For Each objCulture As CultureInfo In_CultureInfo.GetCultures(CultureTypes.SpecificCultures)...Next
B- Dim objCulture As New CultureInfo("CA")
C- Dim objRegion As New RegionInfo("CA")
D- Dim objRegion As New RegionInfo("")If objRegion.Name = "CA" Then...End If



16-

You are creating an undo buffer that stores data modifications. You need to ensure thatthe undo functionality undoes the most recent data modifications first. You also need toensure that the undo buffer permits the storage of strings only. Which code segmentshould you use?

A.Dim undoBuffer As New Stack(Of String)B.Dim undoBuffer As New Stack()C.Dim undoBuffer As New Queue(Of String)D.Dim undoBuffer As New Queue()

Answer: A

17-
You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform. You use a Windwos XP Professional clientcomputer named Certkiller -WS536 as your development computer. You are developing a .NET Framework 2.0 Windows application on Certkiller -WS536 which is used as collateral.
You write the following code in the application:Dim testplain As Byte() The byte array testplain contains the data that needs to be protected and the length of the data stored in the byte array is always a multiple of 16. You want only thethreads running under the current user context to be able to unprotect the data whilst the protected data will be stored in a different byte array. The original contents from the testplain byte array must remain unmodified. You are required to select which code segment to use if the application will be executed on computers running Windows XP Professional.What should you do?

A.Use ProtectedMemory.Protect(testplain, MemoryProtectionScope.SameLogon)B.Use ProtectedMemory.Protect(testplain, Nothing, DataProtectionScope.LocalMachine)C.Use ProtectedMemory.Protect(testplain, MemoryProtectionScope.SameProcess)D.Use ProtectedData.Protect(testplain, Nothing, DataProtectionScope.CurrentUser)

Answer: D

Explanation:The ProtectedData.Protect method is used to return a protected copy of the data in the testplain byte array whilst the content of the byte array remains unaffected making this the correct option to use in the scenario.

18-
You work as the application developer at Certkiller .com. You are developing a .NET Framework 2.0 Windows Service application named TestScannerSync that will be used to constantlymonitor for a scanner to be connected to the computer. The TestScannerSync class inherits its functionality from the ServiceBase class. When you connect a scanner the servicesynchronizes its data with the data in a SQL Server database.You decide to override the OnStop method in the TestScannerSync class and write code to close database connections. are required to identify a place in the code where you can openthe connection to the database.What should you do?


A.The database connection is opened in the constructor of TestScannerSync class
B.The database connection is opened in the OnContinue method of TestScannerSync classC.The database connection is opened in the OnStart method of the TestScannerSync classD.The database connection is opened in the OnPowerEvent method of the TestScannerSync class

Answer: C
Explanation:The constructor for a service class derived from ServcieBase is called the first time you call Start on the service, the OnStart command-handling method is called immediately after theconstructor executes.


19-
You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform. You use a Windwos XP Professional clientcomputer named Certkiller -WS554 as your development computer.You are developing a .NET Framework 2.0 application.
The application will be used globally and must be able to represent characters in the following languages:English, Chinese Traditional, Hebrew and Tamil. Your application is required to provide error detection for invalid sequences of characters whilst your application must also optimize storage.What should you do?

A.Encode the characters in your application using the UTF8Encoding classB.Encode the characters in your application using the UTF7Encoding classC.Encode the characters in your application using the UTF32Encoding classD.Encode the characters in your application using the UTF16Encoding class

Answer: A

Explanation:To successfully enable error detection and make the class instance more secure you should make use of the UTF8Encoding class in the scenario.Incorrect Answers:B: The Encoding class used in this option UTF7Encoding does not provide any error detection and should not be used in the scenario.
C, D: The Encoding classes in these options should not be used in the scenario because the UTF16Encoding class represents each character as a sequence of one to two 16-bit integers and the UTF32Encoding represents each code point as a 32-bit integer.

20-

You work as an application developer at Certkiller .com. A fellow developer named Amy Walsh recently created an assembly that implements a custom permission set. Certkiller .comhas asked you to test this assembly. You start by copying the assembly to a test server named Certkiller -SR15 that has the Microsoft .NET 2.0 Framework installed. You thenlog on to the Certkiller -SR15 as a member of the local Administrators Windows group.
You run the assembly, and receive a security exception. You perform a brief analysis of the security issues involved, and find that the assembly has not been assigned the appropriatepermissions to run.
You need to ensure that this assembly runs.What should you do?

A-Use the permview.exe tool to modify the assembly's granted permissions.B-Use the sn.exe tool to modify the assembly's granted permissions.C-Use the caspol.exe tool to modify the assembly's granted permissions.D-Use the gacutil.exe tool to modify the assembly's granted permissions.

Answer: C
Explanation:The caspol.exe command-line tool allows users to modify security permissions, permission sets, and code groups for an assembly at the machine, user, and enterprise policy levels.Incorrect Answers:A: The permview.exe tool only allows users to view declarative security of an assembly.
B: The sn.exe tool allows developers to create a strong-named asymmetric key pair for strong-named assemblies.D: The gacutil.exe tool allows users to manage the contents of the global assembly and download cache.

21-

You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform. You are developing a .NET Framework 2.0 Web application and are busy creating a Configuration object in your application that inherits settings from the applications' web.config file and machine.config file. You modify several of the Configuration objects settings and want to save the Configuration object to a file named testconf.config. You require only the values that differ fromthe inherited values to be written to the configuration file.What should you do? (Choose two)


A.The Save method on the Configuration object should be called
B.The ConfigurationSaveMode.Full value must be passed as a parameterC.The ConfigurationSaveMode.Modified value must be passed as a parameter
D.The SaveAs method on the Configuration object should be calledE.The ConfigurationSaveMode.Minimal value should be passed as a parameter

Answer: CD

Explanation:When you are required to write configuration settings to a different file the SaveAs method should be called. If you wish to write only values which differ from inherited values theConfigurationSaveMode.Minimal value should be passed as a parameter.

22-

You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform. You are developing a .NET Framework 2.0 application and write the following code in your Bill program:
Dim logFile As Stream = File.Create("C:\BillLogFile.txt") Dim txtl As TextWriterTraceListner = New TextWriterTraceListner(logFile) Trace.Listners.Add(txtl) Trace.WriteLine("Bill Message 1")Debug.WriteLine("Bill Message 2") Trace.Flush() You need to know what output will be generated in the C:\BillLogFIle.txt file when you run the Bill program in debug mode.What should you do?

A.Bill Message 1B.Bill Message 2
C.The C:\BillLogFile.txt file is emptyD.Bill Message 1 Bill Message 2

Answer: D

23-
You work as an application developer at Certkiller .com. You are currently creating an application that requires role-based security. You are planning to utilize a database to store the user accounts and group membership data.You need to ensure that users are able to log on and off. You also need to ensure that the application you have created tracks the user accounts of these users, and restrict or allow access to code based on their group membership. You need to achieve this objective with as little developer effort as possible.
What should you do to implement role-based security?

A.Inherit from the GenericIdentity and GenericPrincipal classes.B.Make use of GenericIdentity and GenericPrincipal objects.C.Implement the IIdentity and IPrincipal interfaces.D.Make use of WindowsIdentity and WindowsPrincipal objects

Answer: B

24-

You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform. You are developing a Windows Service application that consists of two Services. The first service monitors a directory for new orders while the other service replicates a database table with up-to-date information. You are required to develop a project installer class to install these services.
What should you do? (Choose two)

A- One ServiceProcessInstaller instance must be Instantiate and add it to the project installer class
B- Two ServiceInstaller instances must be Instantiate and add them to the project installer class
C- Two ServiceProcessInstaller instances must be Instantiate and add them to the project installer class
D- One ComponentInstaller instance must be Instantiate and add them to the project installer classE-Two ComponentInstaller instances must be Instantiate and add them to the project installer classF-One ServiceInstaller instance must be Instantiate and add them to the project installer class

Answer: AB


25-

You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform.You are developing a .NET Framework 2.0 Windows application that provides a user interface similar to Microsoft Excel and allows users to manage their expenses.
You recently wrote a wrapper around the expense management application which performs security checks. If the users have the sufficient rights the wrapper application launches the expense management application, if no sufficient rights the application should be forced to close. You must decide which method of the Process class to use.What should you do?

A.Use the Kill method.B.Use the Close method.C.Use the Dispose method.D.Use the CloseMainWindows method.

Answer: A

26-

You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform.You are developing a .NET Framework 2.0 application that will be used for publishing its own custom performance counter. You additionally require the value of a performance counter toincrease by 5 and must minimize the amount of code needed to write.What should you do?

A.Use the NextValue method.B.Use the Decrement method.C.Use the Increment method.D.Use the IncrementBy method.

Answer: D

27-

You work as an application developer at Certkiller .com. You are developing a .NET Framework 2.0 application used to store a type-safe list of names and e-mail addresses. The list will bepopulated all at ones from the sorted data which means you well not always need to perform insertion or deletion operations on the data.You are required to choose a data structure that optimizes memory use and has good performance.What should you do?

A.The System.Collections.Generic.SortedList class should be usedB.The System.Collections.HashTable class should be usedC.The System.Collections.Generic.SortedDictionary class should be usedD.The System.Collections.SortedList class should be used

Answer: A


28-

You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform.You are developing a .NET Framework 2.0 geographical information system for the company and create a class named Certkiller Code. You are required to serialize all public and non-publicdata of the Certkiller Code class whilst you ensure that you produce the smallest byte stream so that the smallest load is placed upon network resources.What should you do?

A.The XmlSerializationWriter class should be usedB.The XmlSerializer class should be usedC.The BinaryFormatter class should be usedD.The SoapFormatter class should be used

Answer: C

29-

You work as an application developer at Certkiller .com. Certkiller .com has been contracted to develop an application for the local bank.
You have been given the responsibility of creating this application and need to store each transaction record, which is identified using a complex transaction identifier, in memory. The bank informs you that the total amount of transaction records could reach 200 per day.
To achieve this, you decide to utilize one of the existing collection classes in the .NET 2.0 class library. You need to ensure that you the collection class you select is the most efficient one for storing transaction records.

What should you do?


A-Select the ListDictionary collection class.B-Select the HashTable collection class.C-Select the Queue collection class.D-Select the StringCollection collection class

Answer: B




30-

You work as the application developer at Certkiller .com. Certkiller .com uses Visual Studio.NET 2005 as its application development platform.You are developing a .NET Framework 2.0 time management application that requires opening a file namedBillTimeManagement.als programmatically.
All the client computers are equippedwith Microsoft Office and file associations have not been modified after installation of the software. You are required to create a ProcessStatInfo object to provide file details to open the file.What should you do?


A.Dim psi As ProcessStartInfo = New ProcessStartInfo("BillTimeManagement.xls", "Excel")
B.Dim psi As ProcessStartInfo = New ProcessStartInfo("Excel BillTimeManagement.xls")C.Dim psi As ProcessStartInfo = New ProcessStartInfo("Excel", "BillTimeManagement.xls")D.Dim psi As ProcessStartInfo = New ProcessStartInfo("BillTimeManagement.xls")

Answer: D



31. Why should boxing be avoided? (Choose one.)

A. It adds overhead.
B. Users must have administrative privileges to run the application.
C. It makes code less readable.

32 Structures inherit ToString from System.Object. Why would someone override that method within a structure? (Choose as many correct answer as apply.)

A. To avoid boxing.
B. To return something other than the type name.
C. The compiler requires structures to override the ToString method
D. To avoid run-time errors caused by invalid string conversions.

33. If there is no valid conversion between two types, what should you do when
implementing the IConvertible interface?

A. Delete the ToType member that performs the conversion
B. Throw an InvalidCastException.
C. Throw a new custom exception reporting the error.
D. Leave the member body empty.

34. With strict conversions enabled, which of the following would allow an implicit
conversion? (Choose all that apply.)

A. Int16 to Int32
B. Int32 to Int16
C. Int16 to Double
D. Double to Int16


Respuestas

31. Correct Answer: A

A. Correct: The primary reason to avoid boxing is because it adds overhead.
B. Incorrect: Boxing requires no special privileges.
C. Incorrect: Boxing does not make code less readable.

32. Correct Answers: A and B

A. Correct: Value types are boxed when an abstract method inherited from
System.Object is called. Overriding the method avoids boxing.
B. Correct: By default, the ToString method simply returns the type name,
which is typically not useful for a consuming application.
C. Incorrect: The compiler does not require structures to override the
ToString method.
D. Incorrect: ToString never causes a run-time error; it simply returns the type
name unless overridden.

33. Correct Answer: B

A. Incorrect: You can’t omit a member of an interface and still conform to that
interface.
B. Correct: InvalidCastException is the recommended exception to throw.
C. Incorrect: While you could throw a custom exception, using standard
exception types makes it easier for developers writing code to consume
your type to catch specific exceptions.
D. Incorrect: You must return a value for each conversion member.


34. Correct Answers: A and C

A. Correct: You can convert from Int16 to Int32 because that is considered a
widening conversion. Because Int32 can store any value of Int16, implicit
conversion is allowed.
B. Incorrect: You cannot convert from Int32 to Int16 because that is consid-
ered a narrowing conversion. Because Int16 cannot store any value of Int32,
implicit conversion is not allowed.
C. Correct: You can convert from Int16 to Double because that is considered a
widening conversion. Because Double can store any value of Int16, implicit
conversion is allowed.
D. Incorrect: You cannot convert from Double to Int16 because that is consid-
ered a narrowing conversion. Because Int16 cannot store any value of Dou-
ble, implicit conversion is not allowed.

4 may 2009

Manejo de Eventos TreeView - Ejemplo

EJEMPLO - EVENTOS TREEVIEW

Las listas 7.7 y 7.8 dan un código completo para un ejemplo de página de selección TreeView, como muestra las figuras 1 y 2. Estas figuras también ilustran sus nodos productos usando check boxes. El usuario puede también checkear uno o mas de estos boxes, y entonces clickear el boton comprar.







Figura 1 Ejemplo de manejo de árbol selección de nodos





Figura 2 TreeEventHandling.aspx

Listing 7.7 TreeEventHandling.aspx





Listing 7.8 TreeEventHandling.aspx.cs

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TreeEventHandling : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Fill tree with data
FillTree();
// Let's begin with all the nodes collapsed as well
treeMain.CollapseAll();
}
}
///


/// Helper method to fill tree with data
///

private void FillTree()
{


// Get all the groups and iterate through them
string[] groups = ProductCatalog.GetGroups();
foreach (string grp in groups)
{
// Create the node for the group
TreeNode groupNode = new TreeNode(grp);
// For each group get their subheadings and process them
string[] subheadings =
ProductCatalog.GetSubHeadingsByGroup(grp);
foreach (string sub in subheadings)
{
// Create the node for the subheading
TreeNode subheadingNode = new TreeNode(sub);
// For each subheading, get their products
// and process them
Product[] products =
ProductCatalog.GetProductObjectsBySubHeading(sub);
foreach (Product prod in products)
{
// Create new product tree node
TreeNode productNode = new TreeNode(prod.Name);
// Set the node's value to the product id
productNode.Value = prod.Id.ToString();
// Add product node to its parent
subheadingNode.ChildNodes.Add(productNode);
}

// Add subheading node to its parent
groupNode.ChildNodes.Add(subheadingNode);
}
// Add group node to its parent
treeMain.Nodes.Add(groupNode);
}
}
///
/// Handles the tree node selection event
///

protected void SelectProduct(object sender, EventArgs e)
{
// Get the tree node that was selected
TreeNode node = treeMain.SelectedNode;
// Only process selection if a leaf node selected
if (node.ChildNodes.Count == 0)
{

// Retrieve the product id that we placed in the node
int id = Convert.ToInt32(node.Value);
// From that product id get the product
Product prod = ProductCatalog.GetProductById(id);

// If this is a valid product, display details
if (prod != null)
{
txtId.Text = prod.Id.ToString();
txtIsbn.Text = prod.Isbn;
txtName.Text = prod.Name;
txtPrice.Text = String.Format("{0:c}", prod.Price);
}
}
}
///
/// Handles the purchase button click event
///

protected void btnPurchase_Click(object sender, EventArgs e)
{
// Handle the fact there may be no checked products
if (treeMain.CheckedNodes.Count <= 0)


labChoose.Text =

"You did not choose any products to purchase";

else

{

labChoose.Text = "You have selected the following products:";

double total = 0.0;

bulSelected.Items.Clear();

// Loop through each checked node

foreach (TreeNode node in treeMain.CheckedNodes)

{

// Retrieve the product info about this node int id = Convert.ToInt32(node.Value);

Product prod = ProductCatalog.GetProductById(id);

// If valid product, add it to list

// and add it to running total

if (prod != null)

{

string s = prod.Name;

s += "(" + String.Format("{0:c}", prod.Price) +

")";

ListItem item = new ListItem(s);

bulSelected.Items.Add(item);

total += prod.Price;

}

}

labTotal.Text = "Total purchase price: ";

labTotal.Text += String.Format("{0:c}", total);

}

}

}


Codificacion: Los siete Pilares del desarrollo

CODIGO EN MOVIMIENTO



Por Laura Wingerd y Christopher Seiwald
“BEAUTIFUL CODE” – OREILLY

Al principio en el planeamiento de este libro, el colaborador Greg Wilson pregunto si Beautiful Code fue un apropiado titulo.”Mucho de lo que discutirás es diseño y arquitectura de software, antes que código” nos escribió.

Pero este capitulo es acerca de código, no es acerca de que hace el código, no es acerca que cuan hermoso es esto. En lugar de eso, este capitulo trata del look del código, específicamente, como ciertas características visibles de codificación hacen posible la colaboración.

Esto es lo hermoso del “Código en movimiento”.

Lo que estas leyendo esta tomado mayormente del articulo de Christopher Seiwald’s,
”Los siete Pilares de Buen Código” (http://www.perforce.com/perforce/papers/prettycode.html.).

En Resumen los siete pilares son:

Ø Siendo “bookish” (Formato de libros)

Ø Verse semejante.

Ø Venciendo la anidación.

Ø Desenredando bloques de código

Ø Comentando Bloques de código

Ø Decluterring

Ø Aliarse con un estilo existente.

Mientras estos pueden sonar igual a convenciones de codificación, son más que eso. Ellos son manifestaciones exteriores de las prácticas de desarrollo que siempre producen evolución sobre la comprensión.

En este capitulo, veremos como los siete pilares tienen soportado a una pieza de código que estuvo siendo parte de un sistema de software comercial por 10 años.

Esta pieza de código es DiffMerge, un componente del Sistemas Gestor de Configuración del software Perforce.

DiffMerge trabaja para producir un clásico “Combinador por comparación”, comparando dos versiones de un archivo de texto (“tramo 1” y “tramo 2”) a una versión de referencia (“La base”).


En los archivos ingresados, el resultado salida de líneas interpoladas con placeholders marcan las líneas que están en conflicto.

Si has usado Perforce, has visto DiffMerge para trabajar en el comando p4 resolve y en gráficos Perforce’s .

DiffMerge fue originalmente escrito en 1996. A pesar de su simple objetivo, un combinador de texto, esta función cambio para ser llenado con complejidad.
Siendo una elevación de casos especiales de la idiosincrasia de interfaces de usuario, lenguajes de programación, personalidad de codificaciones y los programadores mismos. (“Eso no es un conflicto”, “si es”, “no es”)
En los años DiffMerge en un convirtió en una parte de desarrollo critico en el software Perforce.


Siendo “bookish”

“Los Siete pilares del buen código” describe guías que nosotros usaremos en Perforce Software. Los siete pilares no son solo guías de codificación a usar, no están aplicadas a todos nuestros proyectos de desarrollo. Nosotros aplicamos estos a componentes tal como DiffMerge donde el mismo código esta probablemente activo en varias versiones soportadas al mismo tiempo y modificadas por varios programadores.
El efecto de los siete pilares es hacer código mas comprensible para los programadores quienes son los que leen esto, en varios de los escenarios en los que ellos mismos buscan leer el mismo.

Por ejemplo, los siete pilares aconsejan ser “bookish.” Los Textos de libros y revistas están compuestas de columnas, usualmente en pocas columnas apretadas en la pagina.

Porque? Porque la estreches reduce el trabajo de ir de atrás a adelante capturadando por nuestros ojos cuando leemos. Leer es fácil cuando nuestros ojos trabajan menos.
Leer también es fácil cuando lo que nosotros tenemos leyendo y lo que estamos próximos a leer están ambos en nuestro rango visual. Investigaciones muestran que como nuestros ojos cambian de foco de palabra a palabra, nuestros cerebros pueden tomar señales desde el circunvecino, desenfocando la forma. Muchos de nuestros cerebros pueden recabar “el preventivo avance” del sentido textual dentro de la periferia visual, lo bueno es que están permitidos a dirigir a nuestros ojos para maximizar la comprensión.


El código no es estrictamente texto, pero para propósitos de legibilidad humana, el mismo principio aplica. Código “Bookish”- esto es, código formateado en libro- como columnas y trozos – es fácil de comprender.
Bookishness es más que una simple conservación en líneas cortas. Esta es la diferencia entre codigo que luce igual a esto:
Y codigo que luce igual a esto:

El segundo de estos códigos pertenece a DiffMerge. Cuando nosotros leemos esto, nuestros cerebros sienten el alcance de la lógica a la mano, y nuestros ojos no tienen que llegar muy lejos de lado a lado para entender.


Verse igualmente Semejante

El Fragmento DiffMerge en la sección previa también ilustra otro principio de escritura para la compresibilidad: código que es observado semejante.

Nosotros vemos esto en todo el código DiffMerge. Por ejemplo:


La demostración precedente como líneas cortas puede crear un patrón visual que hará esto fácil para nuestros cerebros ver un patrón lógico. Nosotros podemos decir en una mirada que tres de las cuatro pruebas en esta declaración While son esencialmente lo mismo.


Aquí esta un ejemplo mas de verse semejante. Esta única ilustración de codificación que deja que nuestras mentes hagan una exitosa operación: “una de estas no es de la misma forma”.


Aun si no conoces acerca del código, esta claramente a la vista, por ejemplo, que readfile y state están establecidos en todos los tres casos, pero solo en el tercer caso esta state establecido incondicionalmente. El programador quien escribió esto esta concentrado para construir una apariencia semejante; aquellos de nosotros que leemos esto después, podemos ver en una mirada donde esta la lógica esencial.


El peligro del código Anidado

Todos enseñamos a usar la Anidación para mostrar la profundidad del anidamiento en los bloques lógicos. La profundidad del anidamiento, más allá, a la derecha de página deberá aparecer el código anidado. Código Formateado así es una muy buena idea, pero no porque esto haga a código alguno fácil de leer.

Si cualquier, código profundamente anidado es difícil de leer. Importante lógica es apiñada fuera de la derecha, sumergiendo casi a insignificantes notas al margen por las capas de codigo if-then else que rodean esto, mientras triviales pruebas aplicadas en bloques exteriores parecen elevados en importancia.
Así mientras la anidación es útil para mostrar donde comienzan y finalizan los bloques, esta no hace para nosotros el código fácil de comprender.


El gran peligro es la animación; el código anidado esfuerza la comprensión humana, claro y simple. Edward Tufte no estaba siendo halagador cuando el escribió que “Algunas veces son tan complejas e intensamente anidada que ello se asemeja a código de computador ”. Steve McConnell advirtió sobre el uso anidado de declaraciones if
- no porque ellos sean ineficioentes o ineficaces, sino porque ellos son difíciles sobre la comprensión humana. El dice :” Para entender el codigo, tu tienes observar el conjunto entero de anidaciones if en tu mente al mismo tiempo”.No sorprende que en investigaciones señalan a las condicionales anidadas como el mas propenso a error de todas las estructuras de programación. Una gran evidencia de esto es “DiffMerge’s”

A lo largo de los marcados DiffMerge’s

Nosotros tenemos un registro de cada cambio, división, y anexión correspondiente a DiifMerge a lo largo de sus 10 años de historia. Y es un interesante record. La Figura 32-3 ofrece una pequeña vista de los cambios a las versiones liberadas de DiffMerge. Esto muestra que DiffMerge comenzó en la línea principal y ha estado siendo versionado hacia más de 20 versiones.
Los cambios a DiffMerge han ocurrido en la Línea Principal, la mayor parte. Pero el grafico muestra una actividad peculiar en algunos de los más recientes releases.

Un grafico de conteo de parches del DifMerge’s por release , ver en la figura 32-4, es aun mas intrigante. Esto muestra que DiffMerge fue raramente parchado después que fuese liberada – hasta el release2004.2 esta. Cuando el subsiguiente – parche release evalúa altamente, solamente para decrecer otra vez en el release 2006.2. Porque están los releases 2004.2 hasta el 2006.1 así, ¿ un acertijo entre parches?



Aquí esta la historia: DiffMerge comenzó como un aprovechable pero simple programa combinador. En esta temprana vida, esta hizo poco para discriminar entre combinaciones actuales conflictivas y no conflictivas, cambios de líneas. En el 2004, nosotros mejoramos DiffMerge para ser atildado respecto a la detección y resolución de conflictos. Como en el release 2004.2, DiffMerge fue por supuesto más capaz, pero este fue un buggy. Nosotros conseguimos reportes de error en el 2004.2 y 2005.1 -
Por lo tanto un gran numero de parches.


Nosotros probamos en limpiar el código para el release el 2005.2, pero la limpieza resulto en un error tan intratable que nosotros tuvimos que restaurar la versión 2005.1 dentro del release 2005.2. Entonces, en el 2006, nosotros reescribimos las partes problemáticas del DiffMerge completo. La reescritura fue bien exitosa, aunque tuvimos un susto en el release 2006.1.Desde entonces, DiffMerge fue muy estable, y el indicador de parches post-release bajaron a cero.

Así, cuanto hicimos mal cuando nosotros reescribimos DiffMerge en el 2004? Nosotros pensamos que esto sucedió cuando dejamos el código convertirse en incomprensible.
Quizás nuestra revisión de código en el tiempo perdió de vista los siete pilares, o quizás nosotros salteamos algunas revisiones enteramente.

En cualquier índice, aunque esta continuado el grafico de regresión, DiffMerge navego dentro de releases llenos de Bugs que no vimos en el grafico.
No tenemos forma para medir cuan legible es el código fuente o cuan bien esta adaptado a los siete pilares.
La Figura 32.5 muestra un número de declaraciones if y sus respectivos niveles de anidamiento (depths) en cada periodo inicial de DiffMerge. En esa época nosotros modificamos y ramificamos DiffMerge para el 2004.2, al parecer, nosotros duplicamos el número de declaraciones if en el código. Y por primera vez, allí estaban ifs anidados a más de tres niveles de profundidad.


Correlación no es causalidad, como se dice, y podrá haber otros factores contribuyentes.
El diseño de la mejora, los casos de prueba, las otras construcciones codificadas -hasta el tamaño del archivo código fuente- algunas o todas de estas podrá contribuir a la alza de las estadísticas de errores. Sin apreciar que conocemos acerca de profundidad de las condicionales anidadas y la comprensibilidad, no es difícil tomar esta deslumbrante correlación para valorar.


Conclusión

Para un programador trabajando sobre código en evolución, hermoso es el código que puede ser modificado con un mínimo de agitación. Tú lees el código, determinas que hace, y cambias esto. Tu éxito depende mucho sobre cuan bien sobreentiendes el código al comienzo mediante tu habilidad para programar. También depende sobre cuan bien tu código es entendido por los próximos programadores que abordaran este; si ustedes nunca llamaron ayuda de fuera, ustedes tuvieron buen termino.


A todos nos debe gustar realmente leer desde la izquierda para decir que el éxito del código en movimiento depende de cuan comprensible es esto para los programadores quienes leerán el código.