Lesson 2: Configuring and Optimizing Your Application

Lesson 2: Configuring and Optimizing Your Application

The .NET Framework provides tools that you can use to configure and optimize your application after it has been deployed. The configuration file allows you to specify location or version information for dependent assemblies and allows you to configure application properties as well. You can use the performance monitor utility to identify bottlenecks in your application and optimize your code for future builds. In this section, you will learn to create and use a configuration file, to configure your application with dynamic properties, and to use the performance monitor to identify bottlenecks in your code.

After this lesson, you will be able to

  • Explain how to create a .config file

  • Describe the basic schema of a .config file

  • Explain how to set dynamic properties in your application

  • Explain how to configure dynamic properties for your application

  • Explain how to use the performance monitor to diagnose bottlenecks in your application

Estimated lesson time: 30 minutes

You can provide a configuration file for your application. A configuration file allows you to configure application properties after the application has been deployed without recompiling your code. The configuration file is an XML file that contains information about how your application should be configured. You learned how to use .config files to configure Trace switches in Chapter 5. You can also use configuration files to configure other aspects of your program.

Creating the Configuration File

A configuration file is simply an XML file with the appropriate tags and an appropriate name. A configuration file for an application will have the name <name>.<extension>.config, where <name> is the name of the application, and <extension> is the extension of the application (such as .exe). Thus, the .config file for an application named myApplication.exe would be myApplication.exe.config. A configuration file must be located in the same folder as the application assembly that it configures.

The content of a configuration file must be configured in the .config file schema. The basic structure of a configuration file is as follows:

<?xml version="1.0" encoding="utf-8" ?> <configuration> <! configured elements go here > </configuration>

Aside from the first element, which specifies the XML version and the encoding, and the top-level <configuration> element, there is no required content for a configuration file. All other elements are optional and can be added or dispensed with as needed.

In Visual Basic .NET, you can create a configuration file for your assembly by choosing Add New Item from the File menu and selecting Application Configuration File. A file with the structure described earlier is added to your application. You can add elements manually to this file, and it will be appropriately named when the application is built.

In Visual C#, you must manually create the .config file by opening a text editor, such as Notepad, and writing the schema displayed previously, adding any desired elements at the same time. You must then save the file as app.config and add the file to your project.

NOTE
In Visual C# .NET 2003, you can add a configuration file to your application by choosing Add New Item from the File menu and selecting Application Configuration File.

The .config File Schema

Although an exhaustive discussion of the .config file schema is beyond the scope of this text, this section introduces the higher-level elements of the .config file schema. You are encouraged to consult the Visual Studio .NET documentation for additional reference material on this schema. Table 9.1 provides an overview of high-level schema elements.

Table 9-1. High-Level .config File Schema Elements

Element

Description

<startup>

Contains only the <requiredRuntime> element, which allows you to specify which common language runtime version to use

<runtime>

Allows you to configure information about assembly binding and the behavior of garbage collection

<system.runtime.remoting>

Contains information about the configuration of channels and remote objects

<system.net>

Contains information for Internet applications

<mscorlib>

Contains the <cryptographySettings> element that allows you to configure how the application uses cryptography

<configSections>

Contains custom configuration settings

<system.diagnostics>

Contains information on the configuration of the Trace and Debug classes for your application

To create a configuration file with Visual Basic .NET

  1. From the Project menu, choose Add New Item. The Add New Item window opens.

  2. In the Add New Item window, choose Application Configuration File. A configuration file is added to your project.

  3. Within the <configuration> element, add schema elements appropriate to the configuration you would like for your application. Consult the Visual Studio .NET documentation for detailed information on all of the available schema elements.

  4. Save your file and build your application.

To create a .config file with Visual C#

  1. From the Project menu, choose Add New Item.

  2. In the Add New Item window, choose Text File. A new text file is added to your project, and the text editor for it opens.

  3. In Solution Explorer, right-click the new text file, and choose Rename. Rename the file App.config. In the text editor, add the following XML:

    <?xml version="1.0" encoding="utf-8" ?> <configuration> </configuration>

    In Solution Explorer, double-click App.config, and choose Yes when asked if you would like to close it. The view reverts to the XML text editor for the App.config file.

Configuring Your Application Using Dynamic Properties

Dynamic properties allow you to configure the startup values of objects in your application. You can map the specific properties of objects to entries in your configuration file and then retrieve them dynamically at run time. Dynamic properties are useful for specifying external resources that might change in the course of an application s lifetime, such as a database connection string. By reading the value of such a property dynamically, you can reconfigure your application without having to recompile and redeploy. Visual Studio .NET allows you to configure dynamic properties using the Properties window at design time, or you can manually add code to retrieve dynamic property values.

Using the Properties Window to Configure Dynamic Properties

You can use the Properties window to set properties of UI elements to be configurable. The Properties window for each control contains an expandable node that allows you to set properties to be read as dynamic properties. Control properties that are likely to be linked to external resources are added to this node by default, or you can add properties by clicking the ellipses next to (Advanced). The DynamicProperties node is shown in Figure 9.2.

figure 9-2 the dynamicproperties node in the properties window.

Figure 9-2. The DynamicProperties node in the Properties window.

In order to read a dynamic property from the .config file, you must supply a key. The key is written to the .config file and corresponds to the appropriate value to return from the .config file. When a key is set for a dynamic property, the key and the value of that property are automatically written to the .config file. The following code example shows the element that is added to the .config file by Visual Studio .NET to make Button1.Text configurable:

<add key="Button1.Text" value="Button1" />

The key value (Button1.Text) is used by the application to retrieve the value (Button1) at run time. Because key values are read by humans, it is a good idea to create the values according to a consistent pattern. The default pattern used by Visual Studio .NET is <control>.<propertyname>, where control is the name of the control and propertyname is the name of the property.

After the program has been deployed, you can configure any dynamic properties by directly editing the configuration file. For example, to change the value of Button1.Text from Button1 to myButton, you would locate the appropriate element in the .config file and change the value represented there. The next time the application starts, the new property value will be read from the configuration file.

To use the Properties window to create a dynamic property

  1. In the designer, select the appropriate control.

  2. In the Properties window, expand the Dynamic Properties node.

  3. If your property is already represented in the Dynamic Properties node, click the ellipses next to the entry for it, select the Map Property to a Key in Configuration File check box, and specify a key for the property. The key and the value for that property are written to the .config file.

  4. If your property is not yet represented in the Dynamic Properties node, click the ellipses to the right of the (Advanced) entry. The Dynamic Properties window appears.

  5. In the Dynamic Properties window, select the properties you want to be configurable, and set a key using the drop-down menu. The keys and the values for the selected properties are written to the .config file.

NOTE
Not all properties are available in the Dynamic Properties window. Because property values are stored as strings, you can only configure properties that are represented as strings or types that can be explicitly converted from a string.

To configure a dynamic property of a deployed application

  1. Using Notepad or another text editor, open the application configuration file.

  2. Locate the node that contains the property value you want to edit.

  3. Change the Value attribute of the node to the appropriate value.

    NOTE
    For properties that are not inherently strings, such as Boolean properties, you must be certain to provide a value that can be parsed to the correct type. For example, when configuring a property with a Boolean data type, you must supply a string that reads either true or false.

  4. Save and close the file. The new property value will be read into the application the next time it is started.

Setting and Retrieving Dynamic Properties Manually

At times, you might want to make properties other than UI properties configurable as well. Consider, for example, a class instantiated at run time. You might want to provide a set of initial properties for that object, but the set of initial properties might vary depending on external factors. You can provide default properties for dynamically created objects in the configuration file and retrieve them dynamically at run time using the AppSettingsReader class.

The AppSettingsReader class is found in the System.Configuration namespace and uses a key to retrieve a value from the configuration file. The main method of this class is the GetValue method. The GetValue method requires a String value for the key, and a Type that indicates the type of object to be retrieved. Even though a Type is specified, the retrieved value is returned as an Object and must be explicitly converted to the correct data type. The following code example demonstrates how to use the AppSettingsReader to set the Text property of a hypothetical Widget object:

Visual Basic .NET

' Creates the AppSettingsReader object Dim myReader As New System.Configuration.AppSettingsReader() ' Creates a new Widget Dim myWidget As New Widget() ' Retrieves the dynamic property. DynamicWidget.Text is the key, ' and it is returned as a String. It is converted from Object to ' String by the CType function. myWidget.Text = CType(myReader.GetValue("DynamicWidget.Text", _ GetType(System.String)), String)

Visual C#

// Creates the AppSettingsReader object System.Configuration.AppSettingsReader myReader = new System.Configuration.AppSettingsReader(); // Creates a new Widget Widget myWidget = new Widget(); // Retrieves the dynamic property. DynamicWidget.Text is the key, // and it is returned as a string. It is converted from object to // string explicitly. myWidget.Text = myReader.GetValue("DynamicWidget.Text", typeof(System.String)).ToString();

If you attempt to use a key not represented in the configuration file, an InvalidOperationException will be thrown.

To read data from the configuration file, you must add the elements at design time. Elements containing the key/data pair should be <add> elements and should be placed as children of the <appSettings> element. The following code example demonstrates how to add an element to the configuration file:

<appSettings> <!-- User application and configured property settings go here.--> <!-- Example: <add key="settingName" value="settingValue"/> --> <add key="Widget.Visible" value="True" /> <add key="Widget.Text" value="I love my Widget!" /> </appSettings>

To retrieve data from the configuration file manually

  1. Create a new instance of System.Configuration.AppSettingsReader.

  2. Use the AppSettingsReader.GetValue method to retrieve the value for the specified key.

  3. Convert the object returned by AppSettingsReader.GetValue to the appropriate data type.

To add data to the configuration file manually

  1. Using Notepad or another text editor, open the application configuration file.

  2. Locate the <appSettings> element. If the <appSettings> element does not exist, add it within the <configuration> element.

  3. Create <add> elements for your data within the <appSettings> element. You must specify a value for the key and value attribute, as shown here:

    <add key="Widget1.Text" value="My Widget">

  4. Save and close the file.

Optimizing Your Application s Performance

Even after an application is built and deployed, development continues. In business settings, applications are constantly fine-tuned to maximize performance or conserve resources. In this section, you will learn guidelines for optimizing your program.

Optimization Begins During Development

Efficient, optimized code is the result of careful planning and good coding practice. By following coding guidelines, you can create applications that have a measure of optimization built in. Some coding guidelines are as follows:

  • Avoid late binding.

    Avoid the use of Object (object) data types whenever possible. Unnecessary conversions are expensive in terms of resources and decrease application performance. Visual Basic .NET users should always code with Option Strict On, which enforces strict typing and reduces unnecessary conversions.

  • Avoid global variables.

    Use local variables and constants whenever possible. Local variables are allocated in a memory region that is easier for code to access. Global variables should be used only for truly global needs. The use of constants for frequently used values can make code more efficient.

  • Be wary of loops.

    Because loops can be the most operation-intensive regions of an application, they merit special attention. Take care to design your loops with the fewest operations possible.

Optimization Is an Iterative Process

The general plan for optimizing your code is as follows:

  1. Measure performance data.

  2. Identify bottlenecks.

  3. Tune your code.

  4. Repeat.

Once bottlenecks in the code have been identified, those areas should be examined to determine whether performance issues can be corrected. After these issues have been addressed, you should measure performance data again to confirm whether the code optimizations that you just implemented had a performance benefit. Assuming success in this regard, your next round of performance monitoring can identify new or less severe bottlenecks, allowing you to further optimize your application.

Measuring Performance

Windows 2000 and Windows XP include a utility named perfmon.exe that can be used to monitor a wide variety of performance-related issues. You can use this utility to view performance data graphically or to write data to log files.

You can also use Trace statements to monitor application execution. Emitted Trace statements can be used to pinpoint your application s execution at run time. Cross-referencing this information with performance data allows you narrow down the location of bottlenecks in your code.

Using the Compiler Optimizations

Enabling optimization with the compiler permits automatic optimizations on your application. Although this step does not take the place of careful coding, you can gain a performance benefit in some cases by applying these optimizations.

You can enable optimizations for your application in the Property Pages. To view the optimizations, right-click your project in Solution Explorer and choose Properties. For Visual Basic .NET, choose optimizations in the Configuration Properties folder. The Optimizations Property Page is displayed, as shown in Figure 9.3.

figure 9-3 the optimizations property page for visual basic .net.

Figure 9-3. The Optimizations Property Page for Visual Basic .NET.

For Visual C#, choose Build in the Configuration Properties folder to access the optimizations drop-down menu, as shown in Figure 9.4.

figure 9-4 the build property page for visual c#.

Figure 9-4. The Build Property Page for Visual C#.

Optimizations are enabled by selecting the check box labeled Enable Optimizations (Visual Basic .NET) or by setting Optimize Code to true (Visual C#). This will cause compiler optimizations to be applied when the application is built. Because compiler optimizations can cause code rearrangements at the intermediate language level, applications can be difficult to debug after optimizations have been applied. Thus, you should use compiler optimizations only on release code.

Lesson Summary

  • The configuration file contains information that allows you to apply different configurations to your application without recompiling. You can configure applications by making changes in the configuration with a text editor, saving, and then restarting the program.

  • Dynamic properties can be useful when they describe external resources that are expected to change in the lifetime of an application. You can configure dynamic applications for UI elements in the designer using the Properties window.

  • You can use the AppSettingsReader to read data from the .config file manually. The AppSettingsReader uses a key to retrieve values stored in <add> elements in the configuration file.

  • You can use the perfmon.exe utility and Trace statements to monitor your application s performance. Use good coding practice and successive rounds of performance monitoring and code tuning to optimize your application.

  • You can enable compiler optimizations by selecting Enable Optimizations (Visual Basic .NET) or by setting Optimize Code to true (Visual C#) on your application s property pages. This should only be done for release builds.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net