22
Now that you’ve read this book, worked through the exercises, Guided Practice Exercises, and Step by Steps, and acquired as much hands-on experience using Visual C# .NET as you could, you are ready for the exam. This chapter is designed to be a “final cram in the parking lot” before you walk into the testing center. You can’t reread the whole book in an hour, but you will be able to read this section in that time. This chapter is organized by objective category, giving you not just a summary, but a review of the most important points from the book. Remember, this is just a review, not a replacement for the actual study material! It’s meant to be a review of concepts and a trigger for you to remember useful bits of information you will need when taking the exam. If you know the information in here and the concepts that stand behind it, chances are good that the exam will be a snap. CREATING USER SERVICES Create a Windows form by using the Windows Forms Designer. Add and set properties on a Windows form. á Properties let you customize the appearance and behavior of a Windows form. á The Windows Forms Designer lets you define a form based on the properties that are available in its base class (which is usually the System.Windows.Forms.Form class). Fast Facts 70-316

Add controls to a Windows form

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Add controls to a Windows form

Now that you’ve read this book, worked through theexercises, Guided Practice Exercises, and Step bySteps, and acquired as much hands-on experienceusing Visual C# .NET as you could, you are readyfor the exam. This chapter is designed to be a“final cram in the parking lot” before you walk intothe testing center. You can’t reread the whole bookin an hour, but you will be able to read this sectionin that time.

This chapter is organized by objective category,giving you not just a summary, but a review of themost important points from the book. Remember,this is just a review, not a replacement for theactual study material! It’s meant to be a review ofconcepts and a trigger for you to remember usefulbits of information you will need when taking theexam. If you know the information in here and theconcepts that stand behind it, chances are goodthat the exam will be a snap.

CREATING USER SERVICES

Create a Windows form byusing the Windows FormsDesigner.

Add and set properties on aWindows form.

á Properties let you customize the appearance andbehavior of a Windows form.

á The Windows Forms Designer lets you define aform based on the properties that are available inits base class (which is usually theSystem.Windows.Forms.Form class).

Fast Facts

70-316

22 0789728230 FFacts 11/21/02 1:21 PM Page 1039

Page 2: Add controls to a Windows form

1040 FAST FACTS

á The Graphics object gives you access to a draw-ing surface that you can use to draw lines, text,curves, and a variety of shapes.

á The ResizeRedraw property, when set to true,instructs the form to redraw itself when it isresized. It’s a good programming practice todesign forms that resize their contents based onthe form’s size. The Resize event of a form canalso be used to program the resizing logic.

á The Graphics class provides a set of Draw() meth-ods that are used to draw shapes such as rectan-gles, ellipses, and curves on a drawing surface.The Graphics class also provides a set of Fill()methods that are used to create solid shapes.

á You can use an object of the Bitmap class tomanipulate objects. The System.Drawing name-space classes can work with a variety of imageformats.

Add controls to a Windows form.

Set properties on controls.á You can add controls to a form in two ways: You

can use the Windows Forms Designer or createthem in code.

á The Windows Forms Designer in the MicrosoftVisual Studio .NET IDE allows you to add con-trols to a form and manipulate them very easily.

á The Visual Studio .NET toolbox provides a vari-erty of controls and components for creatingcommon Windows GUI elements.

á You can set the properties of controls at designtime by using the Properties window or at run-time by accessing them as ControlName.PropertyName in code.

á You can add custom properties to a form.

á Properties let you encapsulate additional logic, inthe form of the get and set accessors. Theseaccessors let you preprocess data before you allowthe programs to store them or read them fromthe field that originally stored the data.

á The get and set accessors allow read and writeaccess, respectively, to a property. If you want tomake a property read-only, you should notinclude a set accessor in its property definition.On the other hand, if you want a write-onlyproperty, you should not include a get accessorin the property definition.

á Attributes let you define the runtime behavior ofa property.

Create a Windows form by usingvisual inheritance.

á With form inheritance, you can create a newform by inheriting it from a base form. Thisallows you to reuse and extend the code thatyou’ve already written.

á The Windows Forms Designer lets you inherit aform visually from an existing form through theInheritance Picker dialog box. You can also visu-ally manipulate inherited properties through theProperties window.

Build graphical interface elementsby using the System.Drawing name-space.

á Windows forms follow a two-dimensional coordi-nate system. A point is an addressable location inthis coordinate system.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1040

Page 3: Add controls to a Windows form

FAST FACTS 1041

á Some of the important properties of controls,such as Anchor, Dock, Enabled, Font, Location,Name, Size, TabIndex, TabStop, and Visible, areshared by most common Windows forms con-trols.

á A dialog box is used to prompt a user for input.A few built-in dialog boxes available, such asColorDialog, FontDialog, OpenFileDialog, andSaveFileDialog. These function just like theWindows operating system’s dialog boxes.

á You can build custom dialog boxes to meet cus-tom requirements. You can create custom dialogboxes by first creating a form and setting a fewproperties of the form to enable the form tobehave like a dialog box.

á Dialog boxes can be of two types: modal andmodeless. You can call the ShowDialog() orShow() methods of the Form class to create modaland modeless dialog boxes, respectively.

á The LinkLabel control is derived from the Labelcontrol. The LinkLabel control allows you to addlinks to a control. The Links property of theLinkLabel control contains a collection of all thelinks referred to by the control.

á The TextBox control can be displayed as an ordi-nary text box, a password text box (where eachcharacter is masked by the character provided inthe PasswordChar property), or a multilinetextbox (if you set its MultiLine property totrue). The RichTextBox control provides richerformatting capabilities than a TextBox control. Itcan also be drawn as a single-line or multilinetext box. By default, the RichTextBox control hasits MultiLine property set to true.

á GroupBox and Panel controls are container con-trols. They can be used to group other controls.The Controls property of these controls containsa collection of their child controls.

á In a group of CheckBox controls, you can checkmultiple check boxes. In a group of RadioButtoncontrols, you can select only a single radio buttonat a time.

á The CheckBox control allows you to set threecheck states (Checked, Unchecked, andIndeterminate), if the ThreeState property is setto true.

á The ComboBox control allows you to select a valuefrom a predefined list of values. You can alsoenter a value in the ComboBox control. TheListBox control only allows you to select a valuefrom the list of values displayed.

á The CheckedListBox control derives from theListBox control and inherits its functionality.However, a CheckedListBox control displays aCheckBox control along with each item in the listof items to be checked. The CheckedListBox con-trol allows only two selection modes: None (noselection) and One (allows multiple selections).

á The DomainUpDown and NumericUpDown controlsallow you to select from a list of defined values bypressing up and down buttons. You can also entervalues in the controls unless their ReadOnlyproperty is set to true.

á The DateTimePicker control allows you to select adate and time, and the MonthCalendar controlallows you to select a date or range of dates. TheSelectionStart, SelectionEnd, andSelectionRange properties return the start date,end date, and range of dates selected.

á The TreeView control is used to display data in ahierarchical collection of nodes. Each node is rep-resented by a TreeNode object. The AfterSelectevent of the TreeView control occurs when a nodeis selected and the SelectedNode property is setwith the new selection.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1041

Page 4: Add controls to a Windows form

1042 FAST FACTS

á Event handlers can be attached to controls eitherby using the Properties window or programmati-cally by adding an event handler object toControlName.EventName by using the += operator.

Instantiate and invoke an ActiveXcontrol.

á You can use the Windows Forms ActiveX ControlImporter to create wrapper classes. These wrapperclasses let you host an ActiveX control on a .NETWindows form.

á You can import an ActiveX control to a VisualStudio .NET project by adding it to the toolbox.

á After they’re imported, ActiveX controls can beused just as native .NET controls are.

á ActiveX controls impose a performance penaltyand have other drawbacks.

Configure control licensing.á The default control licensing structure in the

.NET Framework requires no configuration byeither developer or administrator. If you encounterruntime licensing errors, they are almost certainlycoming from a custom licensing scheme. In such acase, the best course of action is to contact thecontrol vendor directly for assistance.

Create menus and menu items.á There are two types of menus in Windows applica-

tions. The main menu is used to group all the available commands and options in a Windowsapplication. A context menu is used to specify a rel-atively short list of options that apply to a control,depending on the application’s current context.

á The ListView control is used to display items indifferent views—such as List, Details,SmallIcon, and LargeIcon—like the view optionsof Windows Explorer.

á Scrollbars can be associated with controls to pro-vide scrolling functionality.

á The TabControl control provides a user interfacethat can be used to save space as well as to orga-nize a large number of controls. You usually seeTabControl controls used in wizards.

Load controls dynamically.á Adding controls dynamically is a three-step

process:

1. Create a private variable to represent each ofthe controls you want to place on the form.

2. In the form, place code to instantiate eachcontrol and to customize each control, usingits properties, methods, or events.

3. Add each control to the form’s control collection.

á While creating controls programmatically, be sureto add them to their parent container’s Controlscollection.

Write code to handle control eventsand add the code to a control.

á Control programming is event driven. Events arefired when the user interacts with a control. Totake a specific action when an event occurs, youwould write an event handler method and attachit to the event of a control via its delegate.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1042

Page 5: Add controls to a Windows form

FAST FACTS 1043

á You can make keyboard navigation possiblebetween menu items by including keyboardhotkeys in the Text properties of menu items.You can also associate shortcut keys with menus.Pressing a shortcut key directly invokes a com-mand.

Implement navigation for theuser interface (UI).

Configure the order of tabs.á All controls with TabStop properties set to true

appear in the tab order for a form. The order inwhich the Tab key moves the cursor to the con-trols is dictated by the TabOrder properties of thecontrols.

á The Tab Order Wizard provides a convenient wayto set the TabIndex properties of controls toimplement logical keyboard-based navigation inthe form by using the Tab key.

Validate user input.á It is generally a good practice to validate user

input at the time of data entry. Thoroughly vali-dated data results in consistent and correct databeing stored by the application.

á When a user presses a key, three events are gener-ated: KeyDown, KeyPress, and KeyUp, in that order.

á The Validating event is the ideal place for stor-ing the field-level validation logic for a control.

á The CausesValidation property specifies whethervalidation should be performed. If it is set tofalse, the Validating and Validated events aresuppressed.

á The ErrorProvider component in the VisualStudio .NET toolbox is used to show validation-related error messages to the user.

á A control cannot receive the focus and appearsgrayed out if its Enabled property is set to false.

Validate non-Latin user input.á The String.Compare() method compares strings

according to the rules of the CultureInfo objectreferenced by the CurrentCulture property.

á The CultureInfo.CompareInfo object searches forsubstrings according to the comparison rules ofthe current culture.

á The Array.Sort() method sorts the members ofan array by the alphabetical order rules of thecurrent culture.

á The SortKey.Compare() method compares stringsaccording to the rules of the current culture.

Implement error handling in the UI.

Create and implement custom errormessages.

á You can associate custom error messages with theexception classes defined by the CLR to providemore meaningful information to the caller code.The constructor of these classes that accepts theexception message as its parameter can be used topass the custom error message.

á If the existing exception classes do not satisfyyour exception handling requirements, you cancreate new exception classes that can be specificto your application. Custom exceptions should bederived from the ApplicationException class.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1043

Page 6: Add controls to a Windows form

1044 FAST FACTS

á The Framework Class Library (FCL) providestwo main types of exceptions: SystemExceptionand ApplicationException. SystemException rep-resents the exceptions thrown by the CLR, andApplicationException represents the exceptionsthrown by user programs.

á The System.Exception class represents the baseclass for all Common Language Specification(CLS)-compliant exceptions and provides thecommon functionality for exception handling.

á The throw statement is used to raise an exception.

Implement online user assis-tance.

á Visual Studio .NET includes the HTML HelpSDK for the creation of HTML Help files.

á HTML Help files are composed of multipleHTML source files that are compiled into a sin-gle .chm file.

á You can create HTML Help topics with anyHTML authoring tool. HTML Help Workshopprovides a convenient way to organize help pro-jects.

á An HTML Help file can include navigation aidssuch as a table of contents and an index.

á HTML Help 2 is Microsoft’s latest standard forhelp files.

á The Visual Studio Help Integration Kit includesthe tools necessary to build HTML Help 2 files,including Microsoft Help Workshop.

á Custom exceptions should have names that endwith the word Exception and should implementthree constructors (default, Message, Message andException) of their base classes.

á You can use the UnhandledException event of theAppDomain class to manage unhandled exceptions.

á You can use the EventLog class to log events tothe Windows event log.

Create and implement custom errorhandlers.

á A try block consists of code that might raise anexception. A try block cannot exist on its own. Itshould be immediately followed by one or morecatch blocks or a finally block.

á A catch block handles any exception raised bythe code in the try block. The CLR looks for amatching catch block to handle the exception,which is the first catch block with either exactlythe same exception type or any of the exception’sbase classes.

á If multiple catch blocks are associated with a tryblock, then the catch blocks should be arrangedin top-to-bottom order of specific to generalexception types.

á The finally block is used to enclose code thatneeds to be run, regardless of whether the excep-tion is raised.

Raise and handle errors.á An exception occurs when a program encounters

any unexpected problem during normal execu-tion.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1044

Page 7: Add controls to a Windows form

FAST FACTS 1045

á The HelpProvider component is the bridgebetween a .NET Framework Windows applica-tion and an HTML Help file.

á You can use HelpProvider to display topics froma help file, Web pages, or pop-up help strings.

á Pop-up help is appropriate for dialog boxes,where you don’t want the user to switch focus toanother task.

á ToolTips let you provide quick help for individ-ual controls.

Display and update data.

Transform and filter data.á Server Explorer is a powerful tool for working

with SQL Server data.

á You can edit and design SQL Server objectsdirectly within Visual Studio .NET.

á The DataView object offers client-side sorting andfiltering capabilities for data-bound objects.

á Using views on a server can be an efficient way tofilter or transform data.

Bind data to the UI.á Simple data binding refers to connecting a single

entity in the data model to a single property of acontrol on the user interface.

á Any class that implements the IBindingList,ITypedList, or IList interface can deliver data viasimple data binding.

á You can bind to almost any property of any con-trol.

á Complex data binding binds a user interface con-trol to an entire collection of data.

á To use complex data binding with a ListBox con-trol or a ComboBox control, you set the control’sDataSource and DisplayMember properties.

á A ListBox control or a ComboBox control can pullvalues from one data source and place them inanother.

á You can cause a ListBox control or a ComboBoxcontrol to display one value while binding anoth-er by using the DisplayMember and ValueMemberproperties of the control.

á The DataGrid control displays an entire array ofdata in rows and columns. You specify the data todisplay by setting the DataSource property of theDataGrid control.

á The properties of the DataGrid control includemany flexible formatting options.

á In one-way data binding, data from the datamodel is displayed on the form, but changes tothe form do not affect the data model.

á In two-way data binding, data from the datamodel is displayed on the form, and changes tothe form are written back to the database.

á The .NET Framework uses BindingContext andCurrencyManager objects to manage data binding.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1045

Page 8: Add controls to a Windows form

1046 FAST FACTS

á You can generate proxy classes for a Web servicemanually by using the Web Services DescriptionLanguage tool (wsdl.exe).

á You can generate proxy classes for a Web serviceautomatically by setting a Web reference to pointto the Web service.

á You can test and debug a Web service without aclient application by using one of several SOAPproxy tools.

Instantiate and invoke a COM orCOM+ component.

á Using COM or COM+ components from .NETmanaged code requires the creation of an RCW.

á You can create an RCW for a COM componentby using the Type Library Importer or by directlyreferencing the COM component from .NETcode.

á To use COM components that you did not create, you should obtain a Primary InteropAssembly (PIA) from the creator of the compo-nent.

á RCWs impose a performance penalty on COMcode.

Instantiate and invoke a .NET component.

á .NET components are classes that implement theIComponent interface.

á You can add .NET components to the VisualStudio .NET toolbox. They support the VisualStudio .NET interface with drag-and-drop func-tionality and the use of the Properties window.

á You can use events of the CurrencyManager objectto help react to changes in bound data.

á The Data Form Wizard helps you create data-bound forms, both simple and complex, quickly.These forms draw their data from relational data-bases such as SQL Server databases.

Instantiate and invoke a Webservice or component.

Instantiate and invoke a Web service.

á Web services provide you with the means to cre-ate objects and invoke their methods, eventhough your only connection to the server is viathe Internet.

á Communication with Web services occurs viaXML messages transported by HTTP.

á Because they communicate over HTTP, Web ser-vices are typically not blocked by firewalls.

á The Simple Object Access Protocol (SOAP)encapsulates object-oriented messages betweenWeb service clients and servers.

á UDDI is a multivendor standard for discoveringonline resources, including Web services.

á Disco is Microsoft’s standard format for discoverydocuments, which contain information aboutWeb services.

á The Web Services Discovery tool, disco.exe, canretrieve discovery information from a server thatexposes a Web Service.

á The Web Services Description Language (WSDL)lets you retrieve information on the classes andmethods that are supported by a particular Webservice.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1046

Page 9: Add controls to a Windows form

FAST FACTS 1047

á You can instantiate a .NET component by drag-ging it from the toolbox to a form or by declaringa new instance of the component’s class in yourcode.

Call native functions by using plat-form invoke.

á You can use the .NET PInvoke facility to callfunctions from unmanaged libraries, includingthe Windows API.

Implement globalization.

Implement localizability for the UI.á Localization is a three-step process that consists of

globalization (identifying resources), localizability(verifying separation of resources from code), andlocalization (translating resources).

á Many resources may need to be localized, includ-ing user interface text, dates, times, currencyamounts, and calendars.

á Cultures are identified by culture codes. A neutralculture code specifies only a location and cannotbe used for localization. A specific culture codespecifies both a location and a language, and itprovides enough information for localization.

á The CultureInfo object represents a culture inthe .NET Framework.

Convert existing encodings.á Internally, .NET applications use 16-bit Unicode

(UTF-16) as their preferred character encoding.

á The System.Text.Encoding class and its subclassesallow you to convert text from one encoding toanother.

Implement right-to-left and left-to-right mirroring.

á In some languages, the user interface is read fromright to left instead of from left to right.Converting a form for one of these languages isreferred to as mirroring.

á The .NET Framework provides partial supportfor mirroring through the RightToLeft propertyon forms and controls.

Prepare culture-specific formatting.á To iterate through the elements of a string in a

world-ready application, you should use theGetTextElementEnumerator() method of theStringInfo class.

á Searching, sorting, and comparing strings in aworld-ready application requires you to use stan-dard objects and methods rather than clever pro-gramming tricks.

Create, implement, and handleevents.

á Events allow a program to respond to changes inthe code’s environment.

á You can cause custom code to be executed whenan event fires by registering the code with theevent. These pieces of code that respond to anevent are called event handlers.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1047

Page 10: Add controls to a Windows form

1048 FAST FACTS

á When you’re ready to print, you call the Print()method of a PrintDocument object. This raises thePrintPage event, in which you can use theSystem.Drawing methods to construct the print-out.

á If there is more to be printed when you are doneconstructing a page in the PrintPage() method,you should set e.HasMorePages to true to tell theCLR to trigger the event again for another page.

á The PrintDocument class supports the BeginPrint,EndPrint, and QueryPageSettings events.

á The PageSetupDialog component displays a dia-log box that allows the user to set page-relatedprinting properties.

á The PrintPreviewDialog component displays apreview of a document before it is printed.

á The PrintPreviewControl control lets you embeda print preview in a Windows form.

á The PrintDialog component allows the user toset printer-related printing properties.

Implement accessibility features.

á The .NET Framework supports the five basicprinciples of accessible design:

• Flexibility—The user interface should be flexi-bile and customizable, so that users can adjust itto their own individual needs and preferences.

á Event handlers are registered with events throughdelegate objects.

á A delegate object is a type of object that can storea reference to a method that has a specific signa-ture. Events are objects whose type is delegate.

á To create and implement an event, you need totake care of the following steps:

1. Define the EventArgs class that will containthe event-related data. This is required only ifyou want to pass specific event-related infor-mation to the event handlers.

2. Create a delegate object that can store a refer-ence to the event handler.

3. Define the event itself as an object of delegatetype.

4. Define a method that notifies the registeredobjects of the event. Usually this method hasa name such as OnChanged, where Changed isthe event name.

5. Call the method defined in step 4 wheneverthe event occurs.

á You should always use += syntax when attachingan event handler to an event in order to add thedelegate to a list of already existing delegates.Otherwise, all the previously existing delegates arecanceled and receive no notification of the event.

Implement print capability.á Printing in .NET is managed by the

PrintDocument class. The PrintDocument classexposes a Graphics object that you can draw orwrite to with any of the System.Drawing methods.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1048

Page 11: Add controls to a Windows form

FAST FACTS 1049

• Choice of input methods—Different usershave different abilities and preferences when itcomes to using the mouse or keyboard for per-forming tasks. All operations in an applicationshould be accessible to the keyboard, and basicoperations should be available via the mouse aswell. In the future, voice and other types ofinput may also be considered as input methods.

• Choice of output methods—You should notdepend on a single method of output (such assound, color, or text) for important informa-tion.

• Consistency—Your application should beconsistent with the Windows operating sys-tem and other applications in order to mini-mize difficulties related to learning and usingnew interfaces.

• Compatibility with accessibility aids—Windows includes a number of accessibilityaids such as the Magnifier (which can blowup text or graphics to a larger size) and theOnscreen Keyboard (which enables keyboardinput via the mouse). Your application shouldnot circumvent these accessibility aids.

á Control properties that you should set to ensureaccessibility include AccessibleDescription,AccessibleName, AccessibleRole, BackColor,ForeColor, FontSize, BackgroundImage, TabIndex,and Text.

á You can support high-contrast mode by settingthe value of the Boolean SystemInformation.HighContrast property. The SystemEvents.UserPreferenceChanged event is raised wheneverthe HighContrast property changes.

CREATING AND MANAGINGCOMPONENTS AND .NETASSEMBLIES

Create and modify a .NETassembly.

á Assemblies are the basic unit for reuse, version-ing, security, and deployment of components thatare created by using the .NET Framework. Eachassembly includes an assembly manifest thatstores the assembly’s metadata.

á Depending on the number of files that make upan assembly, it is called a single-file or a multifileassembly.

á A private assembly is an assembly that is availableonly to clients in the same directory structure asthe assembly. A shared assembly can be referencedby more than one application and is stored in themachinewide global assembly cache (GAC). Ashared assembly must be assigned a cryptographi-cally strong name.

Create and implement satelliteassemblies.

á Satellite assemblies are assemblies that store culture-specific information for use in localizingan application.

Create resource-only assemblies.á Resource-only assemblies are assemblies that con-

tain just resources and no code. Resource-onlyassemblies may be satellite assemblies, or theymay hold the default resources for all or part ofan application.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1049

Page 12: Add controls to a Windows form

1050 FAST FACTS

Host a Windows control insideMicrosoft Internet Explorer.

á When controls are hosted inside InternetExplorer, they are rendered as object elementsthat do not require any registration, unlikeActiveX objects. The class ID should be assignedthe assembly (.dll) path and the control name tobe hosted, separated with a # (pound sign).

á Controls can be hosted inside Internet Explorer ifthe assemblies exist in the same virtual directorieswhere the Web page resides or in the GAC.

CONSUMING ANDMANIPULATING DATA

Access and manipulate datafrom a Microsoft SQL Serverdatabase by creating and usingad hoc queries and stored procedures.

á Transact-SQL is the Microsoft SQL Server dialectof the ANSI SQL-92 standard query language.

á You can execute T-SQL statements from a varietyof interfaces, including the Visual Studio .NETIDE, osql, SQL Query Analyzer, or custom appli-cations.

á SELECT statements retrieve data from tables in adatabase.

á INSERT statements add new data to tables in adatabase.

Create a Windows control.á The Microsoft .NET Framework allows program-

mers to create reusable code components. Youcan create a Windows component for use onforms by deriving from Component, Control, orUserControl or from any of their derived classes.

á If you want to create a control by assemblingexisting controls and you want to add custom-defined functionality to it, you should choose toinherit from the UserControl class. You shouldcreate a Windows Control Library template tocreate a user control.

á You can drag and drop a custom componentfrom the toolbox to a form’s surface and set itsproperties just as you can with any standardWindows component.

á When you create a control by extending it fromthe Control class, the control does not have anydefault user interface. You need to handle thecontrol’s Paint event to render its user interface.

á When you don’t need any visual representationfor components at runtime, you can extend themfrom the Component class. This class does not haveany user interface to show on a form, but it doesprovide useful properties and events that can beused by its container to customize and control itsbehavior.

Create a Windows control by usingvisual inheritance.

á The technique of inheriting one visual objectfrom another visual object is known as visualinheritance. When you inherit from a control byusing visual inheritance, you inherit all the func-tionality and user interface of the base control.This allows you to reuse code.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1050

Page 13: Add controls to a Windows form

FAST FACTS 1051

á UPDATE statements modify existing data in tablesin a database.

á DELETE statements remove data from tables in adatabase.

á You can create new stored procedures via ServerExplorer and design them directly in VisualStudio .NET.

á To execute a query or stored procedure, you assignthe text of the query or the name of the stored pro-cedure to the CommandText property of a SqlCommandobject. You use the Execute(), ExecuteReader(),ExecuteScalar(), or ExecuteNonQuery() method toexecute the command. The Execute() methodreturns a DataSet object. The ExecuteReader()method returns a SqlDataReader object. TheExecuteScalar() method returns a single value.The ExecuteNonQuery() method does not return aresult.

Access and manipulate datafrom a data store. Data storesinclude relational databases,XML documents, and flat files.Methods include XML tech-niques and ADO.NET.

á The ADO.NET object model includes both database-specific data provider classes and data-base-independent DataSet classes.

á Data providers contain implementations of theConnection, Command, Parameter, DataReader, andDataAdapter objects that are optimized for a par-ticular database product. For example,OleDbConnection, OleDbCommand, OleDbParameter,OleDbDataReader, and OleDbDataAdapter aredesigned to work with any database that supportsOLE DB, whereas the SqlConnection,SqlCommand, SqlParameter, SqlDataReader, andSqlDataAdapter classes are optimized for SQLServer. A separate implementation is optimizedfor Oracle database, too.

á The SqlConnection object represents a connectionto a SQL Server database.

á The SqlCommand object represents a commandthat can be executed.

á The SqlParameter object represents a parameterof a stored procedure.

á The SqlDataReader object provides a fast way toretrieve a resultset from a command.

á The SqlDataAdapter object implements a two-way pipeline between the database and the datamodel.

á The DataSet object represents an entire relationaldatabase in memory. It’s composed of DataTable,DataRelation, DataRow, and DataColumn objects.

á The DataView object provides a filtered row of thedata from a DataTable object.

á You can change data in a DataSet object by treat-ing the items in the DataSet object like any othervariables.

á To persist changes from the data model to theunderlying database, you must call the Update()method of the SqlDataAdapter object.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1051

Page 14: Add controls to a Windows form

1052 FAST FACTS

á The SqlException and SqlError objects provideyou with the means to retrieve SQL Server–specific error information.

á When you’re designing update commands, youcan choose between optimistic concurrency and“last one wins” concurrency.

TESTING AND DEBUGGING

Create a unit test plan.á Testing is the process of executing a program with

the intention of finding errors. You should designan effective test plan to ensure that your applica-tion is free from all detectable defects and errors.

á Unit testing ensures that each unit of an applica-tion functions as desired. It is the lowest level oftesting.

á Integration testing ensures that different units ofan application function as expected by the testplan after they are integrated.

Implement tracing.Add trace listeners and trace switches to an application.

á Listeners are objects that receive trace and debugoutput. By default, there is one listener,DefaultTraceListener, attached to the Trace andDebug classes. This listener displays the messagesin the output window.

á Debug and Trace objects share the same Listenerscollection. Therefore, any Listener object that isadded to the Trace.Listeners collection is alsoadded to the Debug.Listeners collection.

á The UpdateCommand property of theSqlDataAdapter object specifies a SqlCommandobject to be executed for all changed rows.

á The InsertCommand property of theSqlDataAdapter object specifies a SqlCommandobject to be executed for all new rows.

á The DeleteCommand property of theSqlDataAdapter object specifies a SqlCommandobject to be executed for all deleted rows.

á The DataGrid control can provide a convenientway to handle data changes on the user interface.

á To retrieve data from disk files as raw bytes, youuse the FileStream object.

á To retrieve data from disk files in a line-orientedfashion, you use the StreamReader object.

á To retrieve data from disk files that are formattedfor binary storage, you use the BinaryReaderobject.

á To read data from XML files quickly, in a for-ward-only manner, where memory is a constraint,you use XmlTextReader.

á When memory is not a constraint and you wantflexibility in retrieving, inserting, deleting, andupdating data in any direction from XML files,you use XmlDocument. The XmlDocument classimplements the W3C Document Object Model(DOM) Level 1 Core and the Core DOM Level2 standards.

Handle data errors.á Every real-world application should include error

trapping. Data manipulation adds some specialrequirements to error trapping code.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1052

Page 15: Add controls to a Windows form

FAST FACTS 1053

á Trace switches provide a mechanism that allowsyou to change the type of messages traced by aprogram, depending on a value stored in theXML configuration file. You need not recompilethe application for this change to take effect; youjust restart it. You need to implement code to dis-play the messages, depending on the value of theswitch.

Display trace output.á The Trace and Debug classes can be used to dis-

play informative messages in an application whenthe DEBUG and TRACE symbols are defined, respec-tively, at the time of compilation.

á By default, both the TRACE and DEBUG symbols aredefined in the Debug configuration for compila-tion. Only the TRACE symbol is defined for theRelease configuration of compilation.

á Visual C# .NET preprocessing directives allowyou to define symbols in an application, markregions of code, and conditionally skip code forcompilation.

á The Conditional attribute allows you to condi-tionally add or skip a method for compilation,depending on the value of the symbol passed as aparameter to the attribute.

Debug, rework, and resolvedefects in code.

Configure the debugging environ-ment.

á Debugging is the process of finding the causes oferrors in a program, locating the lines of codecausing the errors, and then fixing the errors.

á The three options available during step-by-stepexecution are Step Into, Step Over, and Step Out.

á Breakpoints allow you to mark code that signalsthe debugger to pause execution. After youencounter a breakpoint, you can choose to con-tinue step-by-step execution or resume normalexecution by clicking F5 or the Resume button.

á The various tool windows, such as This, Locals,Autos, Watch, and Call Stack, can be of greathelp in tracking the execution path and the statusof variables in the process of debugging an appli-cation in Visual Studio .NET.

Create and apply debugging codeto components and applications.

á When an exception is thrown by an application,you can either choose to continue execution orbreak into the debugger (to start debugging oper-ations such as step-by-step execution). You cancustomize this behavior for each exception objectby using the Exceptions dialog box.

á You can attach a debugger to a running process(local or remote) with the help of the Processesdialog box.

Provide multicultural test data tocomponents and applications.

á When an application is localized for multiple cul-tures, you should test the application’s executionby using test data from each culture. You shoulduse this test data both with the localized versionof the application and with the default version ofthe application.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1053

Page 16: Add controls to a Windows form

1054 FAST FACTS

á Visual Studio .NET provides four types of deploy-ment templates—Setup Project (for Windows-based applications), Web Setup Project (for Web-based applications), Merge Module Project(for shared components and assemblies), and CabProject (for ActiveX components to be down-loaded over the Internet). It also provides theSetup Wizard, which helps you create installationpackages for any of these deployment projects.

Plan a deployment that uses remov-able media.

á Deployment via removable media is the “lowestcommon denominator” solution and covers themaximum number of users.

á To create a setup project for removable media,you create a setup project, right-click the projectin Solution Explorer, and select Properties fromthe shortcut menu. In the Properties window,change Package Files to In Cabinet File(s). Thisenables the CAB size option. Set the CAB size toCustom, and set the size depending on yourmedia size.

Plan a Web-based deployment.á Web-based deployment reduces the costs of

media, replication, and distribution. It also makesthe management of software updates simple.

á Creating a setup package for Web-based deploy-ment is similar to doing so for network-baseddeployment. After the setup files are created,rather than copy them to a network share, youcopy them to a virtual directory on a Web server.You might also want to password-protect thedeployment Web site so that only authorizedusers are able to download the application.

Execute tests.á To test an application by using debugging fea-

tures such as breakpoints, you should execute theapplication by using the default Debug configura-tion. Debugging features are disabled in thedefault Release configuration.

Resolve errors and rework code.á Whenever the code is modified or a new feature

is added in an application, you should run all theexisting test cases, along with a new set of testcases, to check the new feature. This regressiontesting helps in developing robust applications.

DEPLOYING A WINDOWS-BASED APPLICATION

Plan the deployment of aWindows-based application.

á Although .NET supports XCOPY deployment,XCOPY is not sufficient for advanced deploymentrequirements. For advanced requirements, youshould instead use the Microsoft WindowsInstaller to deploy applications.

á Microsoft Windows Installer 2.0 is the built-ininstallation and configuration service of theWindows operating system. In addition to pro-viding several advanced installation features, italso provides the ability to roll back the installa-tion process, uninstall an application, and repair acomponent or an application.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1054

Page 17: Add controls to a Windows form

FAST FACTS 1055

Plan a network-based deployment.á Network-based installation is useful in a scenario

in which multiple users are sharing a commonnetwork. In such a case, applications can beinstalled via a shared network folder. This kind ofdeployment method is very common in corporateenvironments.

á While creating a setup project for a network-based deployment, you create a single setup pack-age instead of creating multiple CAB files. Afteryou have built the setup project, you copy all thesetup files to a shared folder on the network andpublish the address of the network to the users.

Ensure that the application con-forms to Windows Installer require-ments and Windows Logo Programrequirements.

á Microsoft provides logo programs to ensure thecompatibility of applications with Microsoftoperating systems. The logo programs provideguidelines to developers for writing applicationsthat interoperate properly with Windows, provid-ing greater stability, better maintenance, andimproved management features.

á To earn a logo, an application must meet prede-fined specifications, and an independent lab musttest it to confirm its compliance with the specifi-cation.

á The Certified for Windows logo program certifiescompliance with Windows 2000.

á The Designed for Microsoft Windows XP logoprogram certifies compliance with Windows XP.

á The Windows Installer SDK contains requirementsfor the Windows Installer. If you build WindowsInstaller packages by using Visual Studio .NET,they will automatically meet these requirements.

Create a setup program thatinstalls an application andallows for the application to beuninstalled.

Register components and assem-blies.

á When you include a component in a VisualStudio .NET setup project, the WindowsInstaller automatically handles component andassembly registration.

á For shared components, you should create amerge module rather than a full installation package.

á The System.Configuration.Install.Installerclass works as a base class for all the custominstallers in the .NET Framework.

á The Installer class method Install() is calledwhen an application is installed, and Uninstall()is called when an application is uninstalled. TheCommit() method is executed if the Install()method executes successfully, and the Rollback()method is executed if the Install() method isnot executed successfully.

á If you add predefined installation components(for example, a PerformanceCounter installationcomponent) to a setup project, they are all addedto the ProjectInstaller class. They are actuallyadded to the Installers collection of this class.

á You can add your own custom Installer classesto a project to perform custom actions throughthe Custom Actions Editor during installation,such as compiling the code to its native image orcreating a database on a target computer.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1055

Page 18: Add controls to a Windows form

1056 FAST FACTS

á The Custom Actions Editor allows you to addcustom actions to be performed during the instal-lation process. It allows you to run .dll, .exe,and assembly files. There are four phases whencustom actions can be performed: Install,Commit, Rollback, and Uninstall.

á The Launch Conditions Editor allows you to setconditions to be evaluated when the installationbegins on the target machine. If the conditionsare not met, the installation stops.

Add assemblies to the GlobalAssembly Cache.

á Shared assemblies are used by multiple applica-tions on a machine. They are placed in the GACand enjoy special priviliges, such as file security(because they are placed in the System folder),shared location, and side-by-side versioning.

á Public/private key pairs are generated by usingthe Strong Name tool (sn.exe). These pairs canbe used to digitally sign an assembly.

á You can add a shared assembly to the GAC byusing Windows Explorer, the .NET FrameworkConfiguration tool, the Global Assembly Cachetool, or the Installer tool.

á The best way to add an assembly during deploy-ment is to use using Microsoft Windows Installer.The Microsoft Windows Installer provides assem-bly reference-counting features and managesremoval of the assembly at the time of uninstalla-tion.

á When the Assembly Cache folder in the Systemfolder is viewed in Windows Explorer, it displaysassemblies from the GAC and Native ImageCache.

Perform an install-time compilationof a Windows-based application.

á MSIL can be compiled to native code via theNative Image Generator tool (ngen.exe). Theassemblies that are compiled into machine-specific native code are placed in the NativeImage Cache.

Deploy a Windows-based appli-cation.

Use setup and deployment projects.á The File System Editor provides mapping of a file

system on a target machine. The folders arereferred to by special names that during theinstallation process are converted to represent thefolder as it is named in the file system on the tar-get machine.

á The Registry Editor allows you to specifyRegistry keys, subkeys, and values that are addedto the Registry in the target machine duringinstallation.

á The File Types Editor allows you to register a fileextension with a Windows application.

á The User Interface Editor allows you to cus-tomize the user interface that is provided to theuser during the installation process. Differenttypes of user-interfaces are available for end userinstallation and administrative installation.

á The User Interface Editor and the LaunchConditions Editor for Search Elements providespecial properties (such as Property andButtonProperty) whose values can be evaluated toperform the installation according to the enduser’s choice.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1056

Page 19: Add controls to a Windows form

FAST FACTS 1057

á The CLR first searches the GAC to locate assem-blies before it looks into the files and folderswhere the assemblies are installed. Thus, sharedassemblies placed in the GAC are more efficientbecause the CLR does not look into the <codebase> and <probing> elements of the applic-able configuration files.

á Delay signing allows a shared assembly to beplaced in the GAC by just having the assemblysigned with the public key. This allows the assem-bly to be signed with private key at a later stage,when the development process is complete andthe component or assembly is ready to bedeployed. This process allows developers to workwith shared assemblies as if they were stronglynamed and yet also secure the private key of thesignature from being accessed at different stagesof development.

á Merge modules allow you to create reusable com-ponents that help in deploying shared compo-nents. The merge modules cannot be directlyinstalled. They need to be merged with installerprograms of a Windows application.

Verify security policies for adeployed application.

á Code Access Security allows code to be trusted tovarying degrees, depending on where the codeoriginates, the publisher, the strong name, andthe security zone.

á If AllowPartiallyTrustedCallersAttribute isassociated with a strongly named assembly, evenpartially trusted assemblies are allowed to call it.

á The .NET Framework Configuration tool can beused to configure the runtime security policy foran assembly or a zone.

Launch a remote application (URLremoting).

á URL remoting provides a zero deployment modelfor deploying a Windows application. The codeand configuration files reside on a Web server,and you can execute the application just bypointing to the URL of the .exe file fromInternet Explorer.

á The code downloaded from a URL is cached in acentral location called the download cache. Whena second request is made to the same content, thedownload cache checks the timestamp of therequested assemblies on the server and downloadsthe file from the server only if its timestamp haschanged. Otherwise, it displays the cached copyto the user.

MAINTAINING ANDSUPPORTING A WINDOWS-BASED APPLICATION

Optimize the performance of aWindows-based application.

á You should use the StringBuilder class for stringsthat will be changed during the course of a pro-gram. The StringBuilder class can be changed inplace, unlike the String class, which must bedestroyed and re-created.

á You should use AddRange to add multiple objectsto collections in a single operation.

á You should use native compilation to reducestartup time. Native images load faster thanMSIL code the first time the code is used.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1057

Page 20: Add controls to a Windows form

1058 FAST FACTS

Diagnose and resolve errorsand issues.

á A process is an application that is being executed.Each running process is uniquely identified on acomputer via a process identifier (PID).

á The Process class provides a large set of proper-ties for getting information about runningprocesses on a local or remote machine.

á The event log is a central repository for variousissues that an application may encounter while itis executing. Use of an event log to record suchmessages not only makes the job of the systemadministrator easier but also allows other applica-tions to take appropriate action when an entry iswritten to a log.

á Multiple event sources can write into an eventlog. However, an event source can be used towrite into only one event log.

á By default, events of the Process and EventLogclasses are not enabled. You can set theEnableRaisingEvents property to true in order toinstruct these classes to raise events.

á Performance counters are organized in categoriesthat define specific sets of performance counters.

á The process of reading a performance countervalue is called sampling the performance counter.The process of updating a performance counter value is called publishing a performancecounter.

á You should throw exceptions only when neces-sary. Exceptions are time-consuming and shouldnot be used for normal program flow.

á You should minimize calls to unmanaged codeand use a chunky interface rather than a chattyone. The fewer calls to unmanaged code, thefaster an application will run.

á You should minimize calls across processes.Cross-process calls are slower than in-processcalls.

á You should compile an application by using theRelease configuration. This removes unnecessarydebugging code that can slow down an applica-tion.

á You should avoid scaling images and performingother advanced graphics operations.

á You should use data source–specific managedproviders for data access. These providers (such asthe SqlClient classes) are more efficient than theOleDb classes for their specific databases.

á You should use stored procedures instead of SQLstatements. Stored procedures can be precompiledon the database server for speed of execution.

á You should use the DataReader classes for sequen-tial table reading.

á You should use connection pooling for fasterdatabase connections. Connection pooling avoidsthe time-consuming process of creating a newconnection for each database operation.

á You should avoid using auto-generated com-mands. Such commands are convenient butimpose additional runtime overhead.

á You should avoid distributed transactions.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1058

Page 21: Add controls to a Windows form

FAST FACTS 1059

CONFIGURING AND SECURINGA WINDOWS-BASEDAPPLICATION

Configure a Windows-basedapplication.

á The .NET Framework stores runtime configura-tion information in XML files that can be editedwithout the application being recompiled.

á Dynamic properties enable you to store compo-nent properties in runtime configuration files.

á Machine and application configuration files holdadministrative settings such as information aboutconfigured assemblies and remoting channels.

á The .NET Framework Configuration Editor is aGUI interface for editing runtime configurationfiles.

Configure security for aWindows-based application.

Select and configure authenticationtype. Authentication types includeWindows Authentication, None,forms-based, Microsoft Passport,and custom authentication.

á Windows-based applications use Windowsauthentication to determine role membership.

You can also implement custom authenticationschemes if the Windows user identity is not suffi-cient for your purposes.

Specify the security level for anapplication.

á Permissions control access to resources.

á Code can request the minimum permissions thatit needs to run and the optional permissions thatit would like to have. It can also refuse permis-sions and demand permissions on the part of call-ing code.

á Code access permissions represent access toresources, and identity permissions representthings that the .NET Framework knows aboutcode.

á The .NET Framework supplies both attribute-based declarative security and class-based impera-tive security.

á A code group is a set of assemblies that shares asecurity context.

á A permission set is a set of permissions that canbe granted as a unit.

á The CLR computes actual permissions at run-time based on code group membership and thecalling chain of the code.

Use custom attributes to configuresecurity.

á To implement a custom permission, you mustcreate a class that inherits from theCodeAccessPermission class.

á Custom permissions allow you to create yourown permissions to protect particular resources.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1059

Page 22: Add controls to a Windows form

1060 FAST FACTS

Configure authorization.

Configure role-based authorization.á The .NET Framework supports both authentica-

tion and authorization. Authentication involvesverifying a user’s identity. Authorization involvesgranting rights based on that identity.

á Windows applications constructed with the.NET Framework automatically use Windowsauthentication.

á You can use the IsInRole() method of theWindowsPrincipal object to check for member-ship in Windows groups.

Implement identity management.á The WindowsPrincipal and WindowsIdentity

classes let you check the authentication status ofthe current user.

á The PrincipalPermission class allows you to per-form declarative or imperative role-based securityoperations.

22 0789728230 FFacts 11/21/02 1:21 PM Page 1060