CHAPTER

Configuring a Windows Application
In this chapter, you will • Become familiar with configuring a Windows application • Optimize the performance of a Windows application • Configure security • Implement online user assistance • Set globalization properties • Build GUI elements using System.Drawing

24

This is the chapter that will bring together the remaining objectives of the C# Windows exam. In the last chapter, we looked at deploying an application. In this chapter, we will examine the ways of configuring your application. This will include setting application properties that optimize and secure your application. In prior chapters, we have discussed localization and globalization issues in general terms. Here we will look at applying localization to a Windows application. The C# Windows exam also expects you to be conversant in providing online assistance for the user of your application. Towards that goal, we will look at creating ToolTips, adding a help menu, and providing context-sensitive help. The final objective to be covered for the Windows exam involves working with System.Drawing. We will discuss the issues related to building your own graphical elements as they pertain to the exam.

Configuring a Windows Application
You can configure a .NET application by using a number of XML configuration files that specify the configuration elements. The advantage to keeping the configuration data in XML files is that it can be changed as needed. Many hands can take part in the configuration duties—the network administrator may need to set security policies, the application developer may use the files to change settings without recompiling the application, and so forth.

1

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

2
In this section, we will look at the .NET Framework Configuration tool, along with the three types of configuration files: • Machine configuration file computer. Contains the settings that apply to the entire Contains the settings that apply specifically to

• Application configuration file the application. • Security configuration file a security policy.

Contains the permission settings associated with

We will examine these three types of files individually and then look at the configuration tool, which will help you ensure that the files are maintained properly.

Machine Configuration File
The machine configuration file is used to set system-wide configuration options. On a Windows 2000 machine, this file is found at this location: <system drive>:\winnt\ Microsoft.NET\Framework\<version>\CONFIG\Machine.config Figure 24-1 shows an example machine.config file. If you need a refresher on reading XML, refer back to Chapter 8. The configuration files contain elements (logical data structures) that define the configuration information and set its values. Notice in Figure 24-1 that the first element is called <configuration> followed by <configSections> and then the more specific <section name>. These elements define the configuration data to the application. Every .NET-aware machine has the machine.config file in its Windows directory. If you find the file and scroll through its contents, you will find a section starting with the following tag:
<appSettings>

The configuration system starts looking for the application configuration settings in this section. EXAM TIP Using an XCOPY deployment will not copy the machine.config file. Remember that the machine.config file is specific to the host machine, and it would make no sense on another machine. By setting configuration properties within the machine.config file, you will be able to place the configuration data in a single location. However, keep in mind that this file is specific to the computer system or server. The file is not transferred when the application is deployed.

Chapter 24: Configuring a Windows Application

3

PART IV

Figure 24-1

A sample machine.config file

The machine configuration file can specify remoting configurations as well as assembly-binding specifications. EXAM TIP The machine.config file is consulted prior to the application configuration file. This means that the application file will override any settings in the machine.config file.

Application Configuration File
More significant to the Windows application is the application configuration file. This file contains the settings that are particular to the specific application. The CLR will read these settings and apply them to the runtime environment. EXAM TIP The application configuration file must be in the same directory as the application files and is named <application_name>.exe.config (where <application_ name> is the name of the application).

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

4
The application configuration file is read after the machine configuration file. This means that any settings in the application file will override the machine file. However, you may wish to keep common configuration information in a single location. For example, a component that is used by different applications may have its settings in the machine configuration file for easier manageability. EXAM TIP This file is called web.config for an ASP.NET application.

Here’s an example of the kind of data you might want to keep in an application configuration file. Suppose you have a client application that uses a particular shared component. There may be different versions of the component, and you would like your application to use the most current version. By creating an application configuration file, you can easily enter the version number into the file. The following code could be added to the file:
<runtime> <assemblyBinding ….> <dependentAssembly> <assemblyIdentity name="MySharedComponent" … /> <bindingRedirect oldVersion="1.0.0.1" newVersion="1.0.0.2" /> </dependentAssembly> </assemblyBinding> </runtime>

This is a simplistic overview of how you might set the version number of a referenced component. In this XML example, we use the <runtime> tag to set runtime configuration elements. Drilling down through the sub-elements (<assemblyBinding>, <dependentAssembly>), we reach the <bindingRedirect> sub-element that allows us to set the version redirection to version 1.0.0.2. When the application is started, it will be redirected to the new component version. If you are concerned right now about all the XML coding that you will have to do to set these kinds of configuration elements, don’t worry. The .NET Framework includes a tool that will create the files for you. It’s called the .NET Framework Configuration tool and will be covered shortly.

Security Configuration File
In the security configuration file, you can specify data about the permissions that are associated with policy levels for your application. We will be covering this in more detail in the “Securing a Windows Application” section of this chapter.

Chapter 24: Configuring a Windows Application

5
EXAM TIP Microsoft strongly recommends that you use the .NET Framework Configuration tool (Mscorcfg.msc) or the Code Access Security Policy tool (Caspol.exe) to set security data. You know that if Microsoft “strongly” recommends something, you should be very aware of it for an examination. The security configuration files can be found in the following locations: • Enterprise policy configuration file Enterprisesec.config <runtime install path>\Config\

• Machine policy configuration file <runtime install path>\Config\Security.config • User policy configuration file <userprofile path>\Application data\ Microsoft\CLR security config\Security.config

.NET Framework Configuration Tool
The .NET Framework Configuration tool is installed as part of the .NET Framework. It is a graphical interface that allows you to manage and configure assemblies, security policies, and remoting services. It can be used to configure machine and application configuration files. The following configuration tasks can be accomplished by using the .NET Framework Configuration Tool: • Adjust remoting services • Manage and configure assemblies in the Global Assembly Cache • View the current security settings • Increase the assembly trust • Adjust the zone security • Create a deployment package • Reset all policy levels • View and add applications to be configured with the tool • Configure an assembly for an application • View the properties and assembly dependencies for an application PART IV

Running the Configuration Tool
To run the .NET Framework Configuration tool (shown in Figure 24-2), select Start | Programs | Administrative Tools. Under administrative tools, click Microsoft .NET Framework Configuration.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

6

Figure 24-2

The .NET Framework Configuration tool

The tool can also be installed in a Microsoft Management Console as follows: 1. Select Start | Run. 2. Type in the command mmc. This will open a new management console (see Figure 24-3) that you can customize for your purposes. (Note that you can also add the tool to an existing management console.) 3. Select Console | Add/Remove Snap-In from the menus. 4. Click the Add button, and the Add Standalone Snap-In dialog box will be displayed (see the following illustration).

Chapter 24: Configuring a Windows Application

7

PART IV

Figure 24-3

A new Microsoft Management Console

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

8
5. Select the .NET Framework Configuration snap-in, and click Add. Click Close to close the Add Standalone Snap-In dialog box. 6. Click OK, and you will see that the .NET Configuration tool has been added to your management console (see Figure 24-4). 7. Save the management console—select Console | Save As, and choose the location and name of your management console as shown in the following illustration. For this example, place the console on the desktop and name it “.NET tools”. Close the console, and you will see the icon on the desktop

Figure 24-4

Microsoft Management Console with the .NET Framework Configuration tool added

Chapter 24: Configuring a Windows Application

9
labeled “.NET Tools.msc”. You can now access the console by double-clicking on the icon.

EXAM TIP If you are asked the specific location of the .NET Framework Configuration tool, it is found in <winnt>\Microsoft .NET\Framework\ <version number>\mscorcfg.msc (see the following illustration).

PART IV

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

10
Using the Configuration Tool
Now that you know how to run the configuration tool, let’s examine the configuration elements that you can work with. We will examine some of these in more detail as the chapter progresses, but for now, just get comfortable with the tool itself. Open the .NET Framework Configuration tool and click on the Manage the Assembly Cache link. You will see a list of assemblies, as shown in Figure 24-5. All of the assemblies in the Global Assembly Cache are listed on the right side of the display in Figure 24-8 (refer to Chapter 6 for more about the Global Assembly Cache). You can delete assemblies or add assemblies. Let’s look at how to add an assembly to the Global Assembly Cache. We will be using the assembly created in Chapter 6, which includes the Hello.cs and Heja.cs modules. Follow these steps: 1. Right-click on Configured Assemblies in the left panel and select Add. This will start the Configure an Assembly Wizard.

2. At this point, you can either choose to add an assembly that is in the assembly cache or enter the information manually. We have selected the Hello.dll component from Chapter 6. Once you provide the assembly information, you will see the dialog box.

Chapter 24: Configuring a Windows Application

11

PART IV

Figure 24-5

Managing the assembly cache

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

12
3. In the Binding Policy tab, you can specify the binding redirections, which redirect to a different version of the component.

4. In the Codebases tab, you can specify the codebases for specific versions of the assembly.

Chapter 24: Configuring a Windows Application

13
The preceding procedure allows you to work with the assembly configuration. In the coming sections, we will work with the .NET Framework Configuration tool to configure remoting and security. EXAM TIP Working with versioning in .NET is much improved over previous versions. By using these XML configuration files, a developer can use a new version of a component simply by changing the versioning information. The client application never needs to be rebuilt.

XML Configuration Tags
We will now look at some of the important XML tags that can be found in a configuration file. Table 24-1 lists these tags and their purposes. These tags are significant for the Microsoft C# .NET Windows exam. Remember that the configuration files can be created or modified by using the .NET Framework Configuration tool.

Optimizing a Windows Application
In this section, we will examine the various techniques for optimizing your Windows application. There are many different ways to create the final, “shippable” product, keeping in mind that your final goal is to create an executable application that is as small as possible and runs as efficiently as possible. That is the goal of this section. PART IV

Debug vs. Release Versions
The first thing to worry about is whether you are creating a Debug version of your application or a Release version. The Debug version allows a lot of debugging techniques to be built into the application, but when you give your application to the user, it is not necessary to include the debugging code. In order to create a smaller executable without the debugging options, you must change the build type to the Release version.
Tag Purpose

<configuration> <runtime> <assemblyBinding> <dependentAssembly> <assemblyIdentity> <bindingRedirect> <codeBase> Table 24-1

This is the root element. Contains information about the runtime assembly binding. It is a sub-element of <configuration>. Contains information about the location of assemblies and any version redirection. It is a sub-element of <runtime>. Contains information about each assembly. It is a sub-element of <assemblyBinding>. Contains assembly identification information. It is a sub-element of <dependentAssembly>. Contains information that redirects the runtime from one version to another version. It is a sub-element of <dependentAssembly>. Contains the position of a strong named assembly.

XML Tags for Configuration Files

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

14
To change the build type of your solution, right-click on the solution name in Solution Explorer, and you can select the property page for your solution (see the following illustration). You can configure the common properties of the application or the configuration properties.

Under the Common Properties heading, you can set the following: • The startup project Specifies whether this is a single startup project or there are multiple startup projects. • Project dependencies Specifies which projects must be built in which order. • Debug source files Sets the location where the debugger will look for source files when debugging the solution. • Debug symbol files Sets the location where the debugger will look for symbols when debugging the solution. In order to access the configuration properties, click on Configuration Properties in the left panel (see the following illustration). These options will allow you to set how the different versions of the solution will be built. Notice in the illustration that you can set the configuration type for each project. The type can be either Debug or Release. Set this to Release when the application is ready for shipping. This will reduce the size of the released code.

Chapter 24: Configuring a Windows Application

15

PART IV

You can also click the Configuration Manager button to further configure your solution. When you click this button, you will see the window shown in the following illustration. You can use this window to create or edit solution build configurations and project configurations. Any changes that you make here will also be reflected in the Solution Explorer.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

16
Precompiling
In Part I of this book, we talked about the just-in-time (JIT) compile nature of Visual C# .NET. This means that the methods are compiled when they are first used, and this causes a small time lag when the program is first run. A Windows application uses shared libraries to perform certain tasks that call upon the operating system (rendering visual components, and so on), and this can increase the application’s overhead when the application is first started. In order to avoid these limitations, you can precompile your application. The tool that you use to create precompiled versions is the Native Image Generator (ngen.exe). The precompiling can be done during installation or at build time. EXAM TIP In most cases, it makes more sense to run ngen.exe on the destination machine (at installation time) since it will create a precompiled version of the application specific to the local host. This is the syntax of the ngen.exe command:
ngen [options] <assembly path or display name>

The options are listed in Table 24-2. The ngen.exe command creates a native (machine-specific) image from your application and installs it into the native image cache on the host computer. The runtime will automatically try to locate and run the native image each time it runs the assembly. The performance of the application may improve, because a lot of the work that is required to compile methods in a just-in-time implementation will be avoided. NOTE Just because there is a perceived performance boost from precompiling does not mean that every assembly should be precompiled. You can see a big benefit in precompiling Windows applications; however, it may not make sense for a web application. Good developers will do bench-testing on precompiled versus JIT versions of their applications.
Table 24-2 Options for the ngen.exe Command
Option Description

/show /delete /debug /debugopt /prof /? or /help /nologo /silent

Shows existing native images Deletes existing native images Generates an image that can be used under a debugger Generates an image that can be used under a debugger in optimized debugging mode Generates an image that can be used under a profiler Returns the help message Prevents the display of the logo Prevents the display of success messages

Chapter 24: Configuring a Windows Application

17
Other Performance Enhancements
There are a number of other things to consider when it comes to determining how to improve the performance of a Windows application. In this section, we will quickly visit a lot of these methods. However, keep in mind that you must, as a good developer, determine which of these methods will work for your application. Not all optimization techniques will improve the performance of every application—if they did, then all applications would be optimized in the same way, and you wouldn’t need this section of the book. The following are some of the techniques that can be used to optimize a Windows application: • Exception throwing Watch the number of exceptions you throw in your application. Throwing exceptions is very expensive in terms of system resources. Remember that the runtime environment will throw its own exceptions as well— you may not explicitly call for an exception to be thrown, it can happen as a result of the runtime. This does not include exception handling, where you try code blocks with a try … catch block. However, it does include using exception throwing to control program flow. In the following piece of code, the programmer has caused a number of exceptions to be thrown that could easily be handled through the use of flow-control statements (such as break, continue, and the like).
for (int i = 0; i < 100; i++) { try { if (j = i) { throw new System.Exception.WrongValue(); } } catch { } }

PART IV

• Chunky calls Your method calls can be expensive. By making a method perform several related tasks (such as initializing all variables) rather than having many calls to the method, you can improve the overall performance of your application. Keep in mind that your methods may have to be called through remote calls, and several calls to the same method will invoke many transitional calls to the remoting technique (such as marshalling the parameter data to the method). Instead of having five calls to the five different methods, incorporate the common operations into a single method that will involve a single call. • Use value types instead of objects Alright—not all the time, of course! However, there are times when an object is not required, and a value type can handle the problem more efficiently. Keep in mind the overhead required when you create an object. If you must do a lot of boxing and unboxing, though, don’t consider the value type as an option—use an object instead.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

18
• AddRange Rather than adding one item at a time to a collection, use the AddRange() method to add a whole collection of items. Windows Forms controls (or at least most of them) have an AddRange() method that will improve performance when adding multiple items to a collection. • foreach Replacing for loops with foreach loops will significantly improve performance. Instead of having the overhead of a for loop, the foreach acts as an enumerator over many different types. • StringBuilder String manipulation can often be very expensive. Each time a string is modified, a new string is created and the old string must be garbage collected. If you plan to manipulate the string many times, this can become very costly for the performance of your application. Instead use a StringBuilder object to modify the string. Consider the following code:
string myString = "Counting from 1 to 100: "; for (int i=0; i < 100; i++) { myString = myString + i; System.Console.WriteLine (myString); }

This code section causes 100 instances of the string to be created. Instead, use the StringBuilder as follows:
System.Text.StringBuilder s = new System.Test.StringBuilder ("Counting from 1 to 100: "; for (int i=0; i < 100; i++) { System.Console.WriteLine (s.append(i)); }

In this case, there is only 1 object instead of the 100 objects in the first example. • Jagged arrays A jagged array (or an array of arrays) is more efficient than rectangular arrays. The JIT compiler optimizes a jagged array better. • DataReader Use a DataReader instead of a DataSet whenever possible. A DataReader gives you a fast read of the data and doesn’t leave the object’s contents around. The reader is a stream of data instead of an object that holds the state. • Stored procedures Whenever possible, use stored procedures for data manipulation. The request is made from the client, and the processing is done on the server. There is no additional network traffic, and the code does not have to be interpreted or compiled on the client. The preceding list encompasses some of the techniques for optimizing Windows applications. As an exam caution, the most significant startup time-performance improvement can be had by precompiling the application.

Chapter 24: Configuring a Windows Application

19

Securing a Windows Application
Working with the .NET security model allows the developer to protect the application code as well as the data that moves through the application. The security model deals with type safety, code signing, data encryption, access permissions, and role-based security. For the .NET Windows exam, you should become very familiar with code-access security and role-based security. We will cover both of these topics in detail in this section.

Code-Access Security
The code-access security model sets permissions for access to protected resources. The permissions restrict or grant access. The set of permissions are granted through the use of evidence, which is information about an assembly. When an attempt to access protected resources is made, the .NET Framework security system checks to see if the code caller has the necessary permissions.

Evidence
In order to decide which permissions can be granted to an assembly, the security system uses evidence, which is a set of information about the identity and origin of the assembly. Evidence data includes the following: • Assembly’s directory installed. This is the directory into which the application has been PART IV

• Assembly’s publisher This is the signature of the software publisher or the Microsoft Authenticode signer of the code. • Site This is the originator’s site, such as http://www.yoursite.com. It can also be expressed as a UNC (Universal Naming Convention) path, or the folder on a local computer. • Strong name This is the assembly’s strong name, which includes a public key, a name, and a version. The evidence is passed along to the runtime through the trusted application domain or directly from the loader. For example, the digital signature is validated when the code is loaded. Custom evidence can also be included by the creator of the assembly.

Permissions
Certain activities can be performed only if the proper permissions are attached to the call. For example, you might restrict access to reading and writing files on the local file system, or control access to environmental variables based on permissions. Code-access permissions are used to represent the access rights to the resources. Table 24-3 lists some of the built-in code-access classes. You can also create your own custom permission classes.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

20
Class Description

DirectoryServicesPermission DnsPermission EnvironmentPermission EventLogPermission FileIOPermission OleDbPermission PrintingPermission RegistryPermission SocketPermission UIPermission WebPermissions Table 24-3

Directory services Domain Name System Environmental variables Event logs Local files and folders OLE DB databases Printers Registry Connections to other computers (using sockets) Windows and other user-interface elements Access using HTTP

Code-Access Permission Classes

Putting It Together
Every assembly that is loaded is granted a permission set (a group of permissions) based on the policy. The policy is created from evidence, permissions, code groups, and security policies. The evidence is used to put the assembly into a code group. The code group has been assigned permissions that become permissions for the assembly. A union (all permissions from the code group) is assigned to the assembly. An intersection is the combination of union and security policies. Let’s look at the steps involved in granting permissions: 1. Evidence is gathered for the assembly. 2. The assembly is assigned a code group, and it is tested against certain conditions by the runtime. If the assembly meets the conditions, the permission set associated with the code group is granted. The assembly is then considered to be a member of the code group. 3. All code groups are put together to create a union of permissions for the assembly. 4. Steps 1 through 3 are repeating for all security policy levels. These include enterprise, machine, user, and optionally any belonging to the application domain. Enterprise policies are created by the network administrator. Machine policies are specified by the local administrator, and user policies are managed by individual users. 5. The assembly is granted an intersection of permissions that represents all policy levels. EXAM TIP Table 24-4 shows evidence types, permissions, code groups, and security policy levels.

Chapter 24: Configuring a Windows Application

21
Security Piece Type Description

Evidence

Application Directory Hash Publisher Site Strong Name URL Zone FullTrust Everything LocalIntranet Internet Execution Nothing Root Child groups

Permissions

Code group

Security policy levels

Enterprise Machine User Application Domain

Installation directory Cryptographic hash Software publisher’s signature URL, directory, or other location of the software Assembly’s strong name URL of the software Originating zone of the software No limitations All but security verification Enterprise permissions Origin is unknown No access to system resources No permissions Represents all code Made up of group name, membership condition, and permission; examples are Site, Internet, Publisher, etc. Code belonging to the enterprise Code on the computer Code belonging to the user Code in the application domain

PART IV

Table 24-4

Evidence, Permissions, Code Groups, and Security Policy Levels

Here’s a series of steps that provides an example of security at work: 1. An assembly is located locally in the application directory on the computer and has a publisher certificate. 2. The assembly belongs to the Root Code group by default, since its membership criteria is all code. 3. The assembly belongs to a publisher group. 4. The assembly belongs to the application directory, as well. 5. Permissions thus are the combination of the Root, the publisher, and the application directory.

Working with Security Policies
The .NET Framework comes with a Code Access Policy command-line utility you can use to view and configure security policies: caspol.exe.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

22
Using this tool, you can modify the security policy for the machine, the user, or the enterprise policy level. We don’t need to go into great detail for this tool, since you just need to know that it exists for the Microsoft exam; however, it warrants spending a bit of time on its use. To view the security policies for the various levels, you can use the following statement at a command prompt, choosing the appropriate level:
caspol [-enterprise | -machine | -user | -all] –list

Figure 24-6 shows an excerpt from the command output from caspol –machine -list. From the output in Figure 24-6, you can see the different code groups and the reference number or name that you can use to specify them. You will also see the membership condition name and the condition value, along with the name of the permission set associated with it.

Figure 24-6

Output from the caspol command

Chapter 24: Configuring a Windows Application

23
You can use the Code Access Policy tool to add code groups (among other things). To add a new code group, type the following:
caspol –machine –addgroup <parentName> <pset_name> <mship>

For example, suppose you wanted to add a code group that targets code from Internet Explorer trusted sites. You could use the following command:
caspol –addgroup All_Code –zone Trusted LocalIntranet

Before we get too carried away with information not required for the Windows exam, remember that you can configure a lot of the security by using the .NET Framework Configuration tool. Figure 24-7 illustrates the configuration possibilities available using this tool. EXAM TIP For the exam, remember that evidence is the set of information about the identity and origin of an assembly; permissions are the rights to protected resources, and security policies are used to map evidence with the permissions. Security policies include Enterprise, Machine, User, and Application Domain. Also remember that the most restrictive rules are applied. PART IV

Figure 24-7

Using the .NET Framework Configuration tool for configuring security

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

24
Role-Based Security
The second type of security that can be set on an application is role-based security. This involves determining the type of user (or the role that the user plays) and granting permission or denying permission based on that role. For example, you may have an application that requires managers to perform a certain duty. However, clerks may be using the same application but are not permitted to perform the same duty. These restrictions may be as simple as letting a manager change customer details, and letting only a clerk view those details. By implementing role-based security, you can control this. Role-based security is controlled by passing information about the principal (the identity) of the caller on the current thread. This can take the form of a Windows account, or some other form. The application then makes decisions based on the principal and the role to which the user has been assigned. The role is a collection of principals that have the same permissions—for example, all clerks would be one role, all managers would be another role. Note that a principal can be a member of several roles. The manager may also be a member of the clerk role, thereby permitting the manager to view customer details as well as change them. The following program demonstrates the use of principals and role-based security.
using System; using System.Threading; using System.Security.Principal; public class TestRoleBasedSecurity { public static void Main() { AppDomain.CurrentDomain.SetPrincipalPolicy ( PrincipalPolicy.WindowsPrincipal); WindowsPrincipal w = (WindowsPrincipal) Thread.CurrentPrincipal; if (w.IsInRole(WindowsBuiltInRole.Administrator)) { // execute code for Administrators } } }

Notice that the IsInRole() method tests for a built-in Windows role—namely Administrator. This is one of the ways you can use roles. You can also create generic roles using the GenericIdentity and GenericPrincipal classes; however, that is outside of the scope of the Windows exam. For the exam, just be aware of two key elements of role-based security: • Identity This can be as simple as the user’s login name. It could also be a Passport account or a cookie-authenticated user (for an ASP.NET application). • Principal This is the role (or roles) to which the user belongs.

Chapter 24: Configuring a Windows Application

25
EXAM TIP Role-based security can be useful for Windows 2000 accounts, Microsoft Passport, or user directories, to manage access to resources. You may also be tested on your knowledge of the difference between authentication and authorization. These are the basics, in a nutshell: • Authentication is the process of verifying a user’s identity. Examples of processes that will find the user’s identity and then validate them are operating system user names and Microsoft Passport. These are then validated against such mechanisms as Kerberos (Windows 2000 authentication protocol) or NTLM (Windows NT authentication protocol). • Authorization is the process of finding out whether the authenticated user can proceed with an activity. This happens after the authentication process and uses the role to which the user is assigned to determine which resources the user may access.

Providing User Assistance
PART IV There are a few things that can be done to enhance the appearance and the user friendliness of your application. For example, you may give assistance to the user of your application through ToolTips, context-sensitive help, or Help menus. You may also wish to add accessibility features to your application—assistance for vision-, hearing-, or mobility-impaired people. In this section, we will explore these tools.

Providing User Help
Adding help to a Windows application is a necessity. Although you might be very familiar with moving around your forms, the user is not. As a rule, you should try to make your forms as consistent in nature as possible. If you usually put a button in a certain location, try to be sure that it is located there for all related applications. Just as Microsoft does, ensure that your menus are positioned and labeled following Windows standards—File, Edit, View, and so forth. In addition to these techniques, provide assistance to the user with ToolTips, Help menus, and context-sensitive help.

ToolTips
In order to provide assistance through the use of ToolTips, you must add the ToolTip control to each form. Figure 24-8 demonstrates the college application form with an instance of the ToolTip control added to the form.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

26

Figure 24-8

Adding a ToolTip control to the college application form

Once the instance of the control has been added to the form, you can set the ToolTip property of any control on the form. In our example, we have set the property of the Add New Student button to read “This button allows you to add a new student.” (see Figure 24-9).

Chapter 24: Configuring a Windows Application

27

PART IV

Figure 24-9

Setting the ToolTip property

When we execute the application, the user can run the mouse pointer over the button and view the ToolTip (see Figure 24-10).

Context-Sensitive Help
Context-sensitive help occurs when the user presses F1 or clicks the Help button on a form. We will again use our college application as an example and add context-sensitive help to the main form.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

28

Figure 24-10

Using the ToolTip property

The first step is to add an instance of the HelpProvider control to the form as shown in Figure 24-11. Once the HelpProvider control is added to the form, you can set the HelpNamespace property of the HelpProvider control. • If you set the HelpNamespace property, the help will come from the location specified in the property setting when the user presses F1. For example, you could point to a URL or file, and the help will be extracted from there. • If you do not set the HelpNamespace property, the help will be displayed in a small pop-up window beside the control when the user presses F1.

Chapter 24: Configuring a Windows Application

29

PART IV

Figure 24-11

Adding a HelpProvider control to the college application

For this example, leave the HelpNamespace property blank. Now when you click on the button to which you wish to add help, you will see help properties in the Property Explorer (see Figure 24-12). Set the HelpString property to provide the needed assistance. The final step is to set the help properties of the form: 1. Select the form and open the Property Explorer. 2. Find the HelpButton property and set it to True. 3. Set the MaximizeBox and the MinimizeBox properties to False.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

30

Figure 24-12

Setting the help properties

When you run the application now, you will see the Help button (?) in the top right corner (see Figure 24-13). When you click the Help button, it displays a large questionmark symbol. The user can then move the question mark over the desired control (in

Chapter 24: Configuring a Windows Application

31

PART IV

Figure 24-13

The Help button

this example, the Add New Student button) and click the button. The HelpString text will be displayed. EXAM TIP Do not forget to set the MaximizeBox and MinimizeBox to False; otherwise the Help button will not appear.

Linking Help Topics to a Help Menu
The MainMenu control can be used to add menus to your application. Double-click on the MainMenu control in the Toolbox, and the menu will be added to your form. Type in the spaces provided to show the menu items. In the example shown in Figure 24-14, we have added a File and a Help menu to the form. You will then need to add the following code to the form:
private void menuItemx_Click (object sender, System.EventArgs e) { Help.ShowHelp (this, HelpProvider.HelpNamespace); }

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

32

Figure 24-14

Adding menus to a form

The HelpNamespace object identifies the location of the help file. This could be in the form of a URL or a local file.

Adding Accessibility Features
Another way of adding user assistance to your application is to provide accommodation for the accessibility needs of your users. This can include assistance for poor vision, voice input utilities for hand-impaired users, narrators, and many other options. In this section, we will look at adding some of these features to your Windows application. TIP For guidelines on the standards associated with accessibility features, visit Microsoft’s web site: http://www.microsoft.com/enable/. In order be “Certified for Windows”, an accessible application will:

Chapter 24: Configuring a Windows Application

33
• Support Control Panel size, color, font, and input settings. • Support High Contract mode. • Provide documented keyboard access to all features. • Expose location of the keyboard focus visually and programmatically. • Avoid conveying important information by sound alone. These five requirements are verbatim from MSDN and, if followed, mean that your application can add the “Certified for Windows” logo to its packaging. Every control in the Toolbox supports many of the accessibility guidelines, and Table 24-5 illustrates some of these properties. EXAM TIP Use the SystemInformation.HighContrast (which takes a Boolean value) to determine whether the High Contrast mode has been set. If it is True, use the system color scheme for the application. When the HighContrast changes, the UserPreferenceChanged event is raised. Here are some extra tips for making your application more accessible: • The user can resize menu bars, title bars, and the like through the Control Panel. You do not need to code to accommodate for this. • Use the Windows API function FlashWindow to make the title bar flash. This can provide a means of alerting the user to some condition that otherwise would have relied on sound. • Make use of status indicators in the status notification area of the task bar.
Property Description

PART IV

AccessibleDescription AccessibleName AccessibleRole TabIndex Text FontSize Forecolor Backcolor BackgroundImage Table 24-5

Screen readers (specialized programs or devices) will be able to report this property to the disabled user. Screen readers will use this name. Screen readers will understand the use of this element. This is the order in which the controls are tabbed. This will make use of the & to provide alternate methods for accessing the control. The font size should be set to an acceptable level for the form. The property should be set to a default and the user’s preferences will apply. This should be treated in the same way as Forecolor. Using this property can muddle the screen—leave it blank.

Accessibility Properties for Controls

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

34

Localizing a Windows Form
In Chapter 7, we spoke generically about localizing an application. In this section we will apply those concepts to a Windows Form. Two key terms are used here: • Globalization localization. • Localization This is building the functionality of the application without This involves translating the resources. The CultureInfo class contains culture-specific information.

EXAM TIP

The .NET Framework includes the CultureInfo class, which contains specific information for a particular culture. For instance, it would contain information about language, calendars, country or region, date formatting, and currency formatting, to name but a few elements. A unique name exists for each culture—these names can be found in the SDK documentation that comes with the .NET Framework. In our college application, we will localize the text on the Add New Student button and then change the display by changing the locale settings in the Control Panel. Follow these steps to accomplish this: 1. Set the Localizable property of the form to True. 2. Set the needed languages for the form using the Language property. Each language will have its own resource file. 3. With the Language property of the form set to the new language, change the text of the controls. 4. Add any localized text strings by selecting Project | Add New Item | Assembly Resource File from the menus. Add entries into the resource file. 5. Add the necessary using directives:
using System.Globalization; using System.Resources; using System.Threading;

6. Retrieve the locale from the Control Panel settings:
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

EXAM TIP

To set the locale for the application, use the preceding code.

7. Create a resource manage object:
ResourceManager rm = new ResourceManager ("<resource file>", Assembly.GetExecutingAssembly());

Chapter 24: Configuring a Windows Application

35
8. Set the Regional Options of your computer to the new language.

PART IV

9. Run your application under the new regional settings. Notice in Figure 24-15 that the Add New Student button has changed to the French version. EXAM TIP The Localizable property, when set to True, creates a new resource file for each new language that the user adds.

Using System.Drawing
If you want to build your own controls, or draw your own elements on a form, you will need to use the System.Drawing namespace. The namespace contains many classes that will help you draw on a form, such as Color, Point, Rectangle, Icon, Image, Graphics, Pen, StringFormat, and many, many more. We will only deal with the issues that may be pertinent to the Windows exam, since this is a very specific area of study. Keep the following points in mind for the exam: • The Graphics class contains many of the methods that you will use to draw. Some of these methods include: DrawArc, DrawCurve, DrawLine, DrawRectangle, FillRectangle, and RotateTransform, along with many others.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

36
• Create a Graphics object in order to draw lines and shapes or manipulate images. The object represents a GDI+ (Graphical Device Interface) drawing surface and is used to create graphical images.
Graphics g = this.CreateGraphics();

• GDI+ is stateless, which means that a graphics object will not hold its properties. You must always pass the properties to any of the methods (properties like color, pen, brush, and so forth). • Create a new Color object as follows:
Color myColor = Color.FromArgb (127, 182, 145);

• Some of the other namespaces that may be used include the following:
System.Drawing.Drawing2D System.Drawing.Imaging System.Drawing.Printing System.Drawing.Design System.Drawing.Text

Figure 24-15

The form with a localized button

Chapter 24: Configuring a Windows Application

37
The following code segment will produce a small graphic and show you how to manipulate the Graphics object.
// create a new Graphics object Graphics g = this.CreateGraphics(); // display the window this.Show(); // create a pen object with which to draw our rectangle Pen redPen = new Pen (Color.Red, 3); // draw a rectangle g.DrawRectangle (redPen, 100, 100, 100, 100);

The result of the preceding code is shown in the following illustration.

PART IV

Summary
In this chapter, we have dealt with a number of exam topics. Make sure that you feel comfortable with configuring a Windows application and setting security—both role-based and code-access security. You should also know the techniques for optimizing the performance of a Windows application, paying close attention to precompiling as a valuable technique for saving system resources. You may find a little on the exam regarding user assistance in the form of ToolTips, help menu items, and context-sensitive help. Also spend some time on localizing a Windows Form, as you will need to know the classes that retrieve system information from the local computer and determine the locale of the application’s runtime. This completes the fourth part of this book—the Windows exam. By now you should be experienced at creating Windows applications and working with the code that accompanies the graphical interface. Prepare yourself for the exam by going through the questions at the end of each chapter, and then take the practice test on the accompanying CD. That should prepare you for the exam. Of course, there’s nothing like experience—so work with C# as much as you can.

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

38
Test Questions
1. You are responsible for adding localization to an existing Windows Form. What class will determine the locale of the runtime environment? A. ResourceManager B. Localization C. Globalization D. CurrentUICulture 2. Which tool can you use to configure the security settings for an application? A. mscorcfg.msc B. ngen.exe C. caspol.exe D. caspol.msc 3. Which tool can you use to precompile a Windows application? A. mscorcfg.msc B. ngen.exe C. caspol.exe D. caspol.msc 4. Which security file will override the machine configuration file? A. Enterprise configuration B. Application configuration C. Security configuration D. User configuration 5. Which of the following code segments will produce an ellipse on the form? A. Graphics g = new Graphics(); g.DrawEllipse(myPen, 10, 10, 10, 10); B. Graphics g = new Graphics(); g.DrawEllipse (10, 10, 10, 10); C. Graphics g = this.CreateGraphics(); g.DrawEllipse (myPen, 10, 10, 10, 10); D. Graphics g = this.CreateGraphics(); g.DrawEllipse (10, 10, 10, 10); 6. Where would you find the machine.config file on a Windows 2000 machine? A. <system drive>\Program Files\Microsoft .NET\Framework\ CONFIG\ B. <system drive>\Winnt\Microsoft.NET\Framework\<version>\ CONFIG\

Chapter 24: Configuring a Windows Application

39
C. <system drive>\Winnt\CONFIG D. <system drive>\Documents and Settings\Framework\CONFIG 7. Which of the following XML segments will redirect the bindings of a component? A. <runtime> <assemblyBinding > <redirectBinding name="MyComponent" oldVersion="1.0.0.01" newVersion="1.0.0.02" /> </assemblyBinding> </runtime> B. <runtime> <assemblyBinding > <oldVersion="1.0.0.01" newVersion="1.0.0.02" /> </assemblyBinding> </runtime> C. <runtime> <assemblyBinding > <dependentAssembly> <assemblyIdentity name="MyComponent" /> <redirectBinding oldVersion="1.0.0.01" newVersion="1.0.0.02" /> </dependentAssembly> </assemblyBinding> </runtime> D. <runtime> <assemblyBinding > <dependentAssembly> <assemblyIdentity name="MyComponent" /> <bindingRedirect oldVersion="1.0.0.01" newVersion="1.0.0.02" /> </dependentAssembly> </assemblyBinding> </runtime> 8. What is the name and path of an application configuration file if the application name is MyApplication.exe and is found in c:\MyProgs? A. c:\Winnt\Microsoft.NET\Framework\<version>\CONFIG\ MyApplication.exe.config B. c:\MyProgs\MyApplication.config C. c:\MyProgs\MyApplication.exe.config D. c:\Winnt\Microsoft.NET\Framework\<version>\CONFIG\ MyApplication.config

PART IV

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

40
9. What are the three different policy-configuration files? A. Enterprise, Machine, User. B. Enterprise, Machine, Local. C. Enterprise, Security, Local. D. Enterprise, Security, User. 10. Which code segment represents the most efficient way to manipulate a string? A. string s = new string("Hello"); for (int j = 0; j <10; j++) { s = s + NameCollection(j); } B. String s = new String ("Hello"); for (int j = 0; j < 10; j++) { s = s + NameCollection(j); } C. StringBuilder s = new StringBuilder ("Hello"); for (int j = 0; j < 10; j++) { s.append(NameCollection(j)); } D. StringBuffer s = new StringBuffer ("Hello"); for (int j = 0; j < 10; j++) { s.append(NameCollection(j)); } 11. What type of array is the most efficient to work with? A. Rectangular array B. One-dimensional array C. Two-dimensional array D. Jagged array 12. Which code-access class can be used to represent permissions related to network access? A. NetworkPermission B. RemotePermission C. URLPermission D. SocketPermission

Chapter 24: Configuring a Windows Application

41
13. Which of the following represents a union of permissions? A. A collection of code groups. B. A collection of permissions. C. A collection of intersections. D. A collection of evidence. 14. Which code segment would test the validity of a role-based user? A. AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal); if (WindowsBuiltInRole == Administrator) { // do something here } B. AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal); WindowsPrincipal w = (WindowsPrincipal) Thread.CurrentPrincipal; if (w.WindowsBuiltInRole == Administrator) { // do something here } C. AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal); WindowsPrincipal w = (WindowsPrincipal) Thread.CurrentPrincipal; if (w.IsInRole(WindowsBuiltInRole == Administrator)) { // do something here } D. AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal); WindowsPrincipal w = (WindowsPrincipal) Thread.CurrentPrincipal; if (w.IsInRole(WindowsBuiltInRole.Administrator)) { // do something here } 15. What must be done to create a ToolTip on a new Windows control? A. Add a ToolTip control and set the ToolTip property of the new control. B. Set the ToolTip property of the new control. C. Set the Help property of the new control. D. Create a MessageBox that displays when the user clicks the new control.

PART IV

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

42
Test Answers
1. D. 2. A. 3. B. 4. B. 5. D. 6. B. 7. D. 8. C. 9. A. 10. C. 11. D. 12. D. 13. A. 14. D. 15. A.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer: Get 4 months of Scribd and The New York Times for just $1.87 per week!

Master Your Semester with a Special Offer from Scribd & The New York Times