Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Visual Studio 2005 (2006) [eng]

.pdf
Скачиваний:
117
Добавлен:
16.08.2013
Размер:
21.9 Mб
Скачать

Chapter 7

Figure 7-4

Application Framework (VB.NET Only)

Additional application settings are available for VB projects because they can use the Application Framework that is exclusive to VB.NET. This extends the standard event model to provide a series of application events and settings that control the behavior of the application. The Application Framework can be enabled by checking the Enable Application Framework checkbox. The following three checkboxes control the behavior of the Application Framework:

Enable XP visual styles: XP visual styles are a feature that significantly improve the look and feel of Windows XP, as it provides a much smoother interface through the use of rounded buttons and controls that dynamically change color as the mouse passes over them. VB.NET applications enable XP styles by default and can be disabled from the Project Settings dialog, or controlled from within code.

Make single instance application: Most applications support multiple instances running concurrently. However, an application opened more than two or three times may be only run once, with successive executions simply invoking the original application. Such an application could be a document editor, whereby successive executions simply open a different document. This functionality can be easily added by marking the application as a single instance.

Save My.Settings on Shutdown: Selecting the Save My.Settings on Shutdown option will ensure that any changes made to user-scoped settings will be preserved, saving the settings provided prior to the application shutting down. It is also possible to select the authentication mode for the application.

Where an application is marked as a single instance, if a second instance of the application is run, then the request is rerouted to the existing application. If the application is being opened by double-clicking on a document, or via a shortcut whereby command arguments have been provided, it is important for the arguments to be passed through to the existing application. This process is handled by the application events.

86

Projects and Solutions

Five application events are provided to give the developer information about the status of the application. These events can be accessed by clicking the View Application Events button (refer to the bottomright corner of Figure 7-3). The following code snippet shows the contents of ApplicationEvents.vb, which is automatically created when the View Application Events button is pressed:

Namespace My

The following events are available for MyApplication:

Startup: Raised when the application starts, before the startup form is

created.

Shutdown: Raised after all application forms are closed. This event is not

raised if the application terminates abnormally.

UnhandledException: Raised if an unhandled exception is raised.

StartupNextInstance: Raised when launching a single-instance application

‘ and the application is already active.

‘ NetworkAvailabilityChanged: Raised when the network connection is connected ‘ or disconnected.

Partial Friend Class MyApplication

Private Sub MyApplication_StartupNextInstance _ (ByVal sender As Object, _

ByVal e As StartupNextInstanceEventArgs) _ Handles Me.StartupNextInstance

For Each arg As String In e.CommandLine MsgBox(“Command line arguement: “ & arg)

Next End Sub

End Class End Namespace

The Startup and Shutdown events are triggered when an application (only available to Windows Forms applications) is started for the first time and shut down, respectively. The NetworkAvailabilityChanged event is triggered when changes are made to network availability. This event is limited to detecting changes in the connectivity between the PC and the hub. Changes further along, such as between the hub and the rest of the network, will not be triggered.

If an exception is raised by the application that is not handled, an UnhandledException event will be raised. This enables the developer to easily log and handle these exceptions. Lastly, the StartupNext Instance event is raised when an application is marked as single instance and a second instance of the application is launched. The arguments passed into this event handler include a list of command-line arguments so that they can be processed by the existing application.

The Application Framework also gives the developer more control over what happens when the application starts and shuts down. Selecting a form as the splash screen ensures that this form is displayed when you start your application. By default, the splash screen will only remain visible while your application is loading. If your application loads quickly, you may not see the splash screen. A workaround is to handle the application Startup event and set the minimum display time for the splash screen:

Private Sub MyApplication_Startup _

(ByVal sender As Object, ByVal e As StartupEventArgs) _

Handles Me.Startup

My.Application.MinimumSplashScreenDisplayTime = 2000

End Sub

87

Chapter 7

Most applications are built around a main form that remains visible for the duration of the application. An alternative strategy is to have a manager class that manages which forms are visible. This is easily done by changing the shutdown mode for the application to When Last Form Closes.

Compile

The Compile section of the project settings, as shown in Figure 7-5, enables the developer to control how and where the project is built. For example, the output path can be modified so that it points to an alternative location. This might be important if the output is to be used elsewhere in the build process.

Figure 7-5

Within the Advanced Compile Options menu, various attributes can be adjusted, including the compilation constants. The Debug and Trace constants can be enabled here. Alternatively, you can easily define your own constant, which can then be queried. For example, the Debug constant can be queried as follows:

#If Debug Then

MsgBox(“Constant Defined”)

#End If

Some VB.NET-specific properties can also be configured in the Compile pane. Option Explicit determines whether variables that are used in code have to be explicitly defined. Option Strict forces the type of variables to be defined, rather than it being late-bound. Finally, Option Compare determines whether strings are compared using binary or text comparison operators.

The Compile pane also defines a number of different compiler options that can be adjusted to improve the reliability of your code. For example, unused variables may only warrant a warning, whereas a path

88

Projects and Solutions

that doesn’t return a value is more serious and should generate a build error. It is possible to either disable all of these warnings or treat all of them as errors.

VB developers now have the capability to generate XML documentation. Of course, as this will be generated for each build, it is beneficial to disable this option for debug builds. This will speed up the debugging cycle.

The last element of the Compile pane is the Build Events button. Click this button to view commands that can be executed prior to and after the build. Because not all builds are successful, the execution of the post-build event can depend on a successful build.

Debug

The debug tab, shown in Figure 7-6, determines how the application will be executed when run from within Visual Studio 2005.

Figure 7-6

Start Action

When a project is set to start up, this set of radio buttons controls what actually happens when the application is run. Initially, this is set to start the project, which will call the Startup object specified on the Application tab. The other options are to either run an executable or launch a specific web site.

Startup Options

The options that can be specified when running an application are additional command-line arguments (generally used in conjunction with an executable start action) and the initial working directory. You can also specify to start the application on a remote computer. Of course, this is possible only when debugging is enabled on a remote machine.

89

Chapter 7

Enable Debuggers

Debugging can be extended to include unmanaged code and SQL Server. The Visual Studio hosting process can also be enabled here. This process has a number of benefits associated with the performance and functionality of the debugger. The benefits fall into three categories. First, the hosting process acts as a background host for the application you are debugging. In order to debug a managed application, various administrative tasks must be performed, such as creating an AppDomain and associating the debugger, which take time. With the hosting process enabled, these tasks are handled in the background, resulting in a much quicker load time during debugging.

Second, in Visual Studio 2005, it is much easier to create, debug, and deploy applications that run under partial trust. The hosting process is an important tool in this process because it gives you the ability to run and debug an application in partial trust. Without this process, the application would run in full trust mode, preventing you from debugging the application in partial trust mode.

The last benefit that the hosting process provides is design-time evaluation of expressions. This is in effect an optical illusion, as the hosting process is actually running in the background. However, using the Immediate window as you’re writing your code means that you can easily evaluate expressions, call methods, and even hit breakpoints without running up the entire application.

References

The references pane enables the developer to reference classes in other .NET assemblies, projects, and native DLLs. Once the project or DLL has been added to the references list, a class can be accessed either by its full name, including namespace, or the namespace can be imported into a code file so the class can be referenced by just the class name. Figure 7-7 shows the References tab for a project that has a reference to a number of framework assemblies, as well as a reference to a project entitled FirstProject.

Figure 7-7

90

Projects and Solutions

One of the added features of this tab for VB developers is the Unused References button, which performs a search to determine which references can be removed. It is also possible to add a reference path, which will include all assemblies in that location.

Once an assembly has been added to the reference list, any public class contained within that assembly can be referenced within the project. Where a class is embedded in a namespace (which might be a nested hierarchy), referencing a class requires the full class name. Both VB.NET and C# provide a mechanism for importing namespaces so that classes can be referenced directly. The References section allows namespaces to be globally imported for all classes in the project, without them being explicitly imported within the class file.

Resources

In the past, adding resources to a project required a lot of effort because required building a resource file. Project resources now can be added and removed via the Resources tab, shown in Figure 7-8, which illustrates an icon that has been added to this application. Resources can be images, text, icons, files, or any other serializable class.

Figure 7-8

This interface makes working with resource files at design time much easier than it has been in the past. Chapter 10 examines in more detail how resource files can be used to store application constants and internationalize your application.

Settings

Project settings can be of any type and simply reflect a name/value pair whose value can be retrieved at runtime. Previously, settings were only scoped to the application, which meant that they were specified in an app.config file. When the application is compiled this file is renamed according to the executable being generated — for example, SampleApplication.exe.config. Application scoped settings are assigned a value within the Settings tab, as shown in Figure 7-9, which is read-only at runtime.

Figure 7-9

91

Chapter 7

You can also define user-scoped settings. This means that although the default value is specified in the settings tab and will appear in the app.config file, it can be dynamically set at runtime. In addition to providing a rich user interface for defining application settings, Visual Studio 2005 also generates a designer file that gives developers a strongly typed wrapper to access the settings. The following snippet updates the user-scoped CurrentAddress setting. The settings class also generates Reset and Reload methods. Reset is used to restore the initial value of the setting, as found in the app.config file, whereas the Reload method returns the settings to the value stored within the user settings file:

My.Settings.CurrentAddress = “62 Regular Avenue, Smallville”

My.Settings.Save()

The Settings pane also provides a button entitled Synchronize. This removes any user settings that may have been saved by a previous execution of the application, synchronizing the settings to the default values.

Signing

Figure 7-10 shows the Signing tab, which provides developers with the capability to determine how assemblies are signed in preparation for deployment. An assembly can be signed by selecting a key file, as done previously.

Figure 7-10

Visual Studio 2005 supports a new deployment model for applications called ClickOnce. In this model, an application can be published to a web site where a user can click once to download and install the application. Because this model is supposed to support deployment over the Internet, an organization must be able to sign the deployment package. The Signing tab provides an interface for specifying the certificate to use to sign the ClickOnce manifests.

92

Projects and Solutions

Security

Applications deployed using the ClickOnce deployment model may be required to run under limited or partial trust. For example, if a low-privilege user selects a ClickOnce application from a web site across the Internet, the application will need to run with partial trust as defined by the Internet zone. This typically means that the application can’t access the local file system, has limited networking ability, and can’t access other local devices such as printers, databases, and computer ports.

In the past, developers had to build applications that ran under partial trust using an ad hoc trial-and- error. The Security tab, illustrated in Figure 7-11, has a Calculate Permissions buttons that will determine the permissions the application requires to operate correctly.

Figure 7-11

Modifying the permission set that is required for a ClickOnce application may limit who can download, install, and operate the application. For the widest audience, specify that an application should run in partial trust mode with security set to the defaults for the Internet zone. Alternatively, specifying that an application requires full trust will ensure that the application has full access to all local resources, but will necessarily limit the audience to local administrators.

One of the difficulties in building a partial trust application in the past was that it was difficult to debug the application while it was running in partial trust mode. Visual Studio 2005 runs the application using a separate hosting process, which, among other advantages, enables the application to be run in a limited security AppDomain. This closely simulates how a partial trust application would run. This feature can be disabled via the Advanced button on the Security tab.

93

Chapter 7

Publish

The ClickOnce deployment model can be divided into two phases: initially publishing the application and publishing subsequent updates, and the download and installation of both the original application and subsequent revisions. Deploying an existing application using the ClickOnce model can be done using the Publish tab, shown in Figure 7-12.

Figure 7-12

If the install mode for a ClickOnce application is set to be available offline when it is initially downloaded from the web site, it will be installed on the local computer. This will place the application in the Start menu and the Add/Remove Programs list. When the application is run and a connection to the original web site is available, the application will determine whether any updates are available. If there are updates, users will be prompted to determine whether they want the updates to be installed.

Deploying an application using this deployment model is much better than the traditional installer, as it allows the application to be dynamically updated as new versions become available. In an enterprise, this can eliminate the configuration nightmare that typically arises when multiple versions of an application are in use. ClickOnce incorporates features of the Application Updater block put together by the Patterns and Practices group at Microsoft (http://msdn.microsoft.com/practices/).

Code Analysis

Most developers who have ever worked in a team have had to work with an agreed upon set of coding standards. Organizations typically use an existing standard or create their own. Unfortunately, standards are only useful if they can be enforced, and the only way that this can be effectively done is using a tool. In the past this had to be done using an external utility, such as FXCoP. Visual Studio 2005 has the capability to carry out static code analysis from within the IDE. Code analysis incorporates the rules from FXCoP and includes new rules to support the new language enhancements.

94

Projects and Solutions

The Code Analysis tab, shown in Figure 7-13, can be used to enable code analysis as part of the build process. Because this can be quite a time-consuming process, it may be included only in release or test build configurations. Regardless of whether code analysis has been enabled for a project, it can be manually invoked from the Build menu.

Figure 7-13

Not all rules defined in the Code Analysis pane are suitable for all organizations and/or applications. This pane gives the developer control over which rules are applied, and whether they generate a warning or a build error. Unchecking the rule in the Rules column will disable the rule. Double-clicking a cell in the Status column will toggle what happens when a rule fails to be met between a warning and a build error.

Creating a Custom Settings Provider

One of the limitations of storing data using settings is that only two Scope options are available: Application and User. For most scenarios this is sufficient, as settings are normally either static or variable on a per-user basis. However, there are times when an application setting needs to be changed, which can be achieved by creating a settings provider that stores this information in a user agnostic manager. For example, the value could be stored under the All Users folder or in the Local Computer section of the registry.

The current mechanism is also difficult to manage when an application is widely used. Every time an update is made, users’ settings need to be replaced and/or upgraded. An alternative arrangement would see this information centrally recorded. Updating settings could be easily done, as this information can be centrally located. In this case, a settings provider that makes use of a web service to store settings information would be a good solution to this problem.

A settings provider can be created by inheriting from the framework class SettingsProvider and overriding the Get and Set PropertyValue methods. The arguments to these methods specify the context in which the application is running and the list of settings to be accessed. The following code provides an example:

95