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

Professional Visual Studio 2005 (2006) [eng]

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

Chapter 44

email.Subject = “Sample Email”

email.BodyText = “This email contains sample text to show how easy

email is...”

poom.EmailAccounts(0).Send(email) End Using

End Sub End Class

Status

The Status namespace contains a wealth of information about the status of the device, including static attributes, such as whether there is a camera on the device, and dynamic attributes, such as the ActiveSync status. The following example shows how these two attributes can be queried:

Imports Microsoft.WindowsMobile

Public Class Form1

Private Sub StatusExample(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles

SampleButton.Click

If Status.SystemState.ActiveSyncStatus = _

Status.ActiveSyncStatus.Synchronizing Then _

MsgBox(“Active sync is synchronising now, don’t go away!”)

If Status.SystemState.CameraPresent = True Then _

MsgBox(“There is a camera, why not take a photo”)

End Sub

End Class

Registry entries can also be queried using the RegistryState class in this namespace.

Telephony

The Telephony namespace contains a single class, Phone, which has a single static method called Talk, which can be used to initiate a phone call. An optional parameter, showPrompt, determines whether the user is prompted to proceed with the call or not. In the following code, the user is not prompted before the call is initiated:

Imports Microsoft.WindowsMobile Public Class Form1

Private Sub TelephonyExample(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _

Handles SampleButton.Click

Dim t As New Telephony.Phone t.Talk(“0412413425”, False)

End Sub End Class

Notification Broker

One of the significant improvements in Windows Mobile 5.0 is the Notification Broker, which can be used to notify an application of a particular system event. This may be a change in any of the status states or it may be an incoming SMS or e-mail. The following example shows how you can register your application to intercept an SMS containing a particular string (in this case, “::”). If an incoming SMS is

626

Advanced Device Application Programming

found to contain this string, then the application is notified via the appropriate event handler and given an opportunity to process the SMS, after which the SMS is deleted. The other InterceptionAction is to just notify the application, without deleting the SMS after processing:

Imports Microsoft.WindowsMobile.PocketOutlook

Imports Microsoft.WindowsMobile.PocketOutlook.MessageInterception

Public Class Form1

‘Create the Interceptor

Dim SMSProcessor As New MessageInterceptor( _ InterceptionAction.NotifyAndDelete, True)

Private Sub NotificationExample(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _

Handles SampleButton.Click

‘Define the search condition, in this case must contain :: Dim msgCondition As New MessageCondition() msgCondition.Property = MessageProperty.Body

msgCondition.ComparisonType = MessagePropertyComparisonType.Contains msgCondition.ComparisonValue = “::”

SMSProcessor.MessageCondition = msgCondition

‘Attach an event handler

AddHandler SMSProcessor.MessageReceived, _

AddressOf SMSProcessor_MessageReceived

End Sub

‘Event handler for when a matching SMS is received Private Sub SMSProcessor_MessageReceived _

(ByVal sender As Object, ByVal e As MessageInterceptorEventArgs) Dim theSMS As SmsMessage = CType(e.Message, SmsMessage)

MsgBox(“Message: “ & theSMS.Body) Me.BringToFront()

End Sub

End Class

Note that there is a trick to writing these types of SMS-intercepting applications using the emulators. As mentioned in Chapter 43, some of the emulators have built-in radio stacks, which means that they can simulate sending and receiving SMS. If you want to test the SMS interceptor, you can send an SMS, using Pocket Outlook or another application on the emulator, to the emulator’s built-in test number, which is +1 425 001 0001. The SMS is delayed so that it doesn’t appear immediately, enabling you to navigate back to your application if needed.

Deployment

Deployment of device applications has been a much-debated topic, and numerous white papers have been written about how to package an application for installation. In the past, packaging an application required considerable fiddling within Visual Studio to generate an installer for a mobile application. Although Visual Studio 2005 provides much better support, several steps are still required to deliver an

627

Chapter 44

easy-to-install application. This section looks at how you can use CAB files to install your application, and describes how a desktop MSI installer can really make your application look professional.

CAB Files

The easiest way to deploy your application is via a CAB file, which is essentially a compressed file that contains all the assemblies and resources that your application requires to run. It can also contain registry settings that may need to be applied during installation. To install an application, the CAB file needs to be downloaded to the device before being executed. Executing the CAB file decompresses the contents, installs the application, and performs any installation activities. The final stage is to remove the CAB file from the device. If you use a storage card to deploy a CAB file to multiple devices, it is a good idea to make the card read-only so the CAB file does not get removed.

Visual Studio 2005 has a new project type called a Smart Device CAB Project, which is listed under Setup and Deployment projects in the Add New Project window, shown in Figure 44-13.

Selecting this project type adds a CAB project to your solution. Unlike an installer for the desktop, which has a number of views, the Smart Device CAB Project only has two views, which present a view of the file system and the registry settings. This is shown in the left-hand pane of Figure 44-14, where the primary output for the project DeviceApplication1 has been added to the CAB project, which is achieved by right-clicking on the CAB project and selecting Add Project Output from the context menu.

The File System view can be used to add files and shortcuts on the device itself. Right-clicking on the Target Machine node in the File System view enables you to select Add Special Folder. This includes directories such as Programs, Start menu, and Startup. Right-clicking on one of the folders prompts you to add subfolders, project output, or files. These will be installed on the target machine when the CAB file is installed.

In the Properties window are several properties that can be configured for the CAB file itself. It is, of course, good practice to ensure that the Manufacturer and ProductName reflect the application being deployed.

Figure 44-13

628

Advanced Device Application Programming

Figure 44-14

MSI Installer

The CAB project enables developers to create a CAB file that can be installed on a mobile device. The difficulty lies in getting the CAB file onto the device in the first place. Although as a developer you can easily copy the file to the device via ActiveSync, or even download the CAB file from a web site, unless your application is designed for fellow developers or IT professionals, it is necessary to have an easier mechanism by which the application can be installed.

This can be done using a desktop installer with a custom action to install the CAB using the ActiveSync CEAppMgr application (which can be run from C:\Program Files\Microsoft ActiveSync\ CEAppMgr.exe). The installer works as follows:

1.The end user double-clicks the MSI installer (e.g., MyApplication.msi).

2.The MSI installer copies files to the installation directory.

3.The MSI installer launches a custom installer action.

4.The custom installer action copies the installed files to an application directory used by CEAppMgr.

5.The custom installer action launches CEAppMgr to install CAB files on the device.

6.The Uninstaller: Custom installer action cleans up installed files in the application directory used by CEAppMgr.

The first step in creating this installer is to add a Setup project, which is done the same way as you would create an installer for a desktop application. Select Add New Project from the right-click context menu in Solution Explorer and then select Setup Project from the Setup and Deployment node. This

629

Chapter 44

installer needs to do two things: copy the CAB file onto the desktop and initiate the custom installer action, which will install the CAB file on the device. The easiest way to add the CAB file to the installer is to right-click on the Installer node in the Solution Explorer window and select Add Project Output. In the Add Project Output Group dialog, you then select Build Outputs from the CAB project to add to your installer project. This automatically adds the Build Outputs to the application folder; and because you will be copying the CAB file into the appropriate location with the custom installer action, it doesn’t matter where the files are initially placed.

The next step is to add custom installer actions to copy the installed files to the CEAppMgr application folder and then to run the CEAppMgr, which installs the CAB on the device. To create the custom installer actions, perform the following steps:

1.Create a Class Library project within the existing solution.

2.Remove the default Class1 that is in the solution.

3.Add a new item based on the Installer Class item template.

4.Add event handlers for the BeforeInstall and BeforeUninstall.

5.Add an INI file to Class Library project (for example, DeviceApplication1.ini) and set the Build Action property to Content.

6.Add Class Library primary output and content files to the installer. This can be done by selecting Add Project Outputs from the right-click context menu from the Installer node in Solution Explorer.

7.Wire up custom installer actions to the Setup Project. Select View Custom Actions from the right-click context menu from the Setup Project node in Solution Explorer. Right-click the Custom Actions node and select Add Custom Action. Select the custom installer actions’ class library from within the application folder. This attaches the necessary event handlers to the Windows installer to ensure that the custom installer actions are executed as part of the installation process.

These steps set up the template for the file structure and the custom installer actions. What remains is to fill in the contents for the INI file, which is used by CEAppMgr to install the correct CAB files, and to fill in the event handlers. The INI file needs to define the CAB files that are to be installed on the device for a particular application. The CEAppManager section is required, as it indicates that this is a configuration file for the CEAppMgr application and lists the component to be installed. The component section describes the application and provides a comma-delimited list of CAB files, without spaces, that are to be installed for this application:

[CEAppManager] Version = 1.0 Component = DeviceApp

[DeviceApp]

Description = Sample Device Application CabFiles = SmartDeviceCab1.cab

The BeforeInstall event handler needs to copy the application files from where they are installed by the desktop installer to an application folder that sits within the ActiveSync folder. It then needs to run the CEAppMgr process, passing it the INI file just created. The BeforeUninstall event handler has to

630

Advanced Device Application Programming

clean up the application folder under ActiveSync to ensure that the application is entirely removed. The following code provides a template with which you can include your own installer activities:

Imports System.ComponentModel

Imports System.Configuration.Install

Imports System.IO

Imports Microsoft.Win32

Public Class Actions

Public Sub New()

MyBase.New()

‘This call is required by the Component Designer. InitializeComponent()

‘Add initialization code after the call to InitializeComponent

End Sub

Private Shared Function CEAppMgrApplicationDirectory() As String Dim activeSyncKey As RegistryKey = _

Registry.LocalMachine.OpenSubKey(My.Resources.ActiveSync_Registry_Key) Dim activeSyncPath As String = _ CStr(activeSyncKey.GetValue(My.Resources.CEAppMgr_Install_Dir_Registry_Key)) Dim installPath As String = activeSyncPath + _

My.Resources.Application_Directory

activeSyncKey.Close() Return installPath

End Function

Private Shared Function CEAppMgrExecutable() As String Dim appMgrKey As RegistryKey = _

Registry.LocalMachine.OpenSubKey(My.Resources.CEApp_Mgr_Path) Dim appMgrPath As String = CStr(appMgrKey.GetValue(Nothing)) appMgrKey.Close()

Return appMgrPath End Function

Private Sub ActionBeforeInstall(ByVal sender As Object, _ ByVal e As InstallEventArgs) _

Handles Me.BeforeInstall

Debugger.Break()

‘Copy installation files to the CEAppMgr application directory Dim installPath As String = CEAppMgrApplicationDirectory()

Dim tmpPath As String = (New FileInfo(Me.Context.Parameters.Item _ (My.Resources.Installation_Context_Assembly_Key))).DirectoryName

My.Computer.FileSystem.CopyDirectory(tmpPath, installPath, True)

‘Run CEAppMgr to install the application on the device System.Diagnostics.Process.Start(CEAppMgrExecutable, _

“””” + Path.Combine(installPath, _ My.Resources.Application_Cab_INI_File) + “ “” “)

631

Chapter 44

End Sub

Public Sub ActionBeforeUninstall(ByVal sender As Object, _ ByVal e As InstallEventArgs) _

Handles Me.BeforeUninstall

‘Remove the installation files we manually copied My.Computer.FileSystem.DeleteDirectory(CEAppMgrApplicationDirectory, _

FileIO.DeleteDirectoryOption.DeleteAllContents)

End Sub End Class

This code makes use of a number of resources that are embedded in the Custom Installer Action class library. These constants are provided as shown in Figure 44-15, which illustrates the String resource editor tab of the project properties window.

Figure 44-15

The installer is now ready to be built and deployed to your clients. You can be sure that not only will the application be easy to install, it can also be successfully uninstalled without leaving any traces on the desktop computer. Clearly, in order for the application to be installed on the device, the device needs to be connected to the desktop computer through ActiveSync. However, CEAppMgr can be run at a later stage to install the application on any device attached to the computer via ActiveSync.

OpenNetCF Smar t Devices Framework

Over the past couple of years, a number of Microsoft Most Valuable Professionals (MVPs) have been hard at work writing the OpenNETCF Smart Devices Framework (SDF). Unfortunately, working with version 1.0 of the .NET Compact Framework was a painful process because it lacked so much functionality. The SDF filled most, if not all, of the gaps that mobile developers came up against. It can be downloaded from the OpenNETCF web site at www.opennetcf.org.

Version 2.0 of the .NET Compact Framework has a much richer control library and exposes much of the functionality that was included in the SDF. The team at OpenNETCF will be releasing version 2.0 of the SDF, which again adds functionality that didn’t quite make it into the current version of the .NET Compact Framework.

One of the other frameworks that the team at OpenNETCF has released is a part of some of the most common application blocks. These blocks include the Caching, Exception Management, and Smart Client. Using these blocks can greatly improve the design of the application and reduce the amount of code you have to write to implement similar features. The application blocks can also be downloaded from www.opennetcf.org.

632

Advanced Device Application Programming

Summar y

As you have seen in this chapter, you can build quite complex mobile applications using Visual Studio 2005. The data-binding capabilities, combined with the rich functionality provided in Windows Mobile 5.0, enable you to harness the power of these devices.

Over the next several years, you are going to see a massive growth in mobile technologies as the lines dividing mobile phones, cameras, PDAs, laptops, and tablets begin to fade. Soon you will be writing applications that can reside on a device of any form factor, that will have the capability to record and display data, and can access an arbitrary set of device-specific features, such as taking a photo or making a phone call. With Visual Studio 2005, you are able to start the journey and begin developing for what will become the devices of the future.

633

Part VIII

Build and

Deployment

Chapter 45: Upgrading to Visual Studio 2005

Chapter 46: Build Customization

Chapter 47: Deployment: ClickOnce and Other Methods