gaoxiang

专注于.NET技术

博客园 首页 新随笔 联系 订阅 管理

Smart Client Offline Application Block

 

Patterns and Practices home

Development Using the Offline Application Block

 

Microsoft Corporation

February 2004

Summary: Chapter 3 details the process for building and using the block. The chapter also presents QuickStarts to help you understand the steps that are needed to implement your own offline solution.

Contents

Installing the Offline Application Block

QuickStarts for the Offline Application Block

Using the Offline Application Block

Developing Your Own Provider

Summary

More Information

Now that you understand the design of the Offline Application Block, you are ready to develop solutions using the block. To develop applications that use the Offline Application Block, you need to:

  • Understand how to build (compile) the block.
  • Review the QuickStarts to learn how to use the block.

This chapter shows how you can develop solutions using the Offline Application Block and the providers associated with the different subsystems that ship with the block. The chapter also discusses design considerations and how to develop your own providers. The chapter uses a connection-detection provider (supplied with the application block) as a reference example.

Installing the Offline Application Block

Before you install the Offline Application Block, it is important to review the software requirements and the folder structure in which the block builds.

Software Requirements

To work with the Offline Application Block, you must ensure that your system meets the following minimum software requirements:

  • Microsoft® Windows® XP operating system
  • Microsoft .NET Framework version 1.1
  • Microsoft Visual Studio® .NET 2003 development system (Enterprise Architect, Enterprise Developer, or .NET Professional edition)

Additionally, you may need to install Microsoft Internet Information Services (IIS), depending on the purpose of your application or whether you plan to install the InsuranceClaimsService Web service for running the InsuranceClaimsQuickStart\InsuranceClaimsClient on the same computer.

The block has built-in providers for the Queue Storage. These providers use:

In addition to other providers, the block has built-in providers for the cache.

Note   Please refer to the "Setting up Desktop Engine and MSMQ" section at the end of the chapter for configuration details of the corresponding Queue and Cache providers.

Building the Offline Application Block

Before you can use the Offline Application Block, you must build the solution and then add references to a few of the assemblies.

To build the Offline Application Block

  1. Open the Offline.sln solution (found in the <installation location>\Offline\ folder) in Visual Studio .NET 2003. Alternatively, you can access the Offline Application Block as follows: click Start, click All Programs, click Microsoft Application Blocks for .NET, click Offline, and then click Offline Application Block.
  2. Build the solution to generate the following assemblies:
    • Microsoft.ApplicationBlocks.SmartClient.Offline.dll
    • Microsoft.ApplicationBlocks.SmartClient.Offline.Providers.dll
    • MemoryMappedFileStream.dll
    • Microsoft.ApplicationBlocks.Cache.dll
    • Microsoft.ApplicationBlocks.Common.dll
    • Microsoft.ApplicationBlocks.Data.dll
    • Microsoft.ApplicationBlocks.ExceptionManagement.dll
    • Microsoft.ApplicationBlocks.ExceptionManagement.Interfaces.dll

To use the Offline Application Block in your applications, you need to add a reference to Common, Offline Providers, and Offline assemblies. If you are using Visual C#, add the using directive in the file where you want to access the block code. If you are using Visual Basic .NET, add the Imports directive in the file where you want to access the block code. For example, if you write a new service agent in Visual C#, add the following using directive to the file to access the block code:

...
using Microsoft.ApplicationBlocks.SmartClient.Offline;
...

The corresponding Imports directive for use in Visual Basic is:

...
Imports Microsoft.ApplicationBlocks.SmartClient.Offline
...

Offline Application Block Folder Structure

When you install the Offline Application Block, the installation package creates the following folder structure:

<Install Location>
+---Offline
+---Caching
:   +---src
:       +---cs
:           +---Cache
:           :   +---DataProtectionImplementations
:           :   +---ExpirationsImplementations
:           :   +---ScavengingImplementations
:           :   +---StorageImplementations
:           +---MemoryMappedFile
+---Common
:   +---src
:       +---cs
:           +---Common
:           :   +---Crypto
:           :   :   +---doc
:           :   +---doc
:           +---Version
+---DAAB
:   +---src
:       +---cs
:           +---Microsoft.ApplicationBlocks.Data
+---Database
:   +---Cache
:   +---Queue
+---Docs
+---EMAB
:   +---src
:       +---cs
:           +---Microsoft.ApplicationBlocks.ExceptionManagement
:           +---Microsoft.ApplicationBlocks.ExceptionManagement.Interfaces
+---QuickStarts
:   +---src
:   :   +---cs
:   :   :   +---ConnectionManagementQuickStart
:   :   :   +---DownloadQuickStart
:   :   :   +---InsuranceClaimsQuickStart
:   :   :   :   +---Database
:   :   :   :   +---InsuranceClaimsClient
:   :   :   :   +---InsuranceClaimsService
:   :   :   +---UploadQuickStart
:   :   +---vb
:   :       +---ConnectionManagementQuickStart
:   :       +---DownloadQuickStart
:   :       +---InsuranceClaimsQuickStart
:   :       :   +---Database
:   :       :   +---InsuranceClaimsClient
:   :       :   +---InsuranceClaimsService
:   :       +---UploadQuickStart
:   +---Utility
:       +---ValidationKeyGeneration
+---src
+---cs
+---Offline
:   +---Builders
:   +---ConnectionManagement
:   +---DataLoadingManagement
:   +---Executor
:   +---QueueManagement
:   +---ReferenceDataManagement
:   +---ServiceAgentManagement
+---Offline Providers
:   +---CacheStorageProviders
:   +---ConnectionDetectionStrategies
:   +---QueueStorageProviders
+---Versioning

Each QuickStart solution builds in its respective subfolder. Table 3.1 describes the folders that the installation package creates when you install the Offline Application Block.

Table 3.1: Folders That the Offline Application Block Installation Package Creates

Folder Description
<installation location> The folder where the Offline Application Block is installed. The default installation folder is: C:\Program Files\Microsoft Application Blocks for .NET\SmartClient Offline Application Block\
Bin Stores all of the binaries generated when the source code is built for the block. This folder contains the Debug or Release folder, which in turn contains the binaries.
Docs Contains the documentation associated with the block, including the compiled help (.chm) file.
Database Contains the database scripts that are required to set up the Desktop Engine database used by the Desktop Engine queue and cache storage provider.
QuickStarts Contains all of the QuickStarts. There are versions of each QuickStart for the Microsoft Visual C#® development tool and the Microsoft Visual Basic® .NET development system. The QuickStarts are self-contained and have an associated solution file. When you build a QuickStart, a bin folder is created under the QuickStart folder. The bin folder contains a Debug or Release folder that contains the binaries. There is a separate bin folder for each Quickstart.
Src Contains the source code for the Offline Application Block. The src folder contains the following folders:
Offline–Contains code that is central to the Offline Application Block.
Providers–Contains the source code that is specific to the providers supplied with the block.

QuickStarts for the Offline Application Block

To add offline capability to an application, begin by reviewing the four QuickStarts that are included with the block:

  • Connection Management QuickStart illustrates how to use the Connection State Management subsystem components of the block to detect whether the application is online or offline and to force the system offline or online.
  • Download QuickStart illustrates how to download reference data, thus allowing the user to continue to use the application even when it goes offline. This QuickStart uses an OnlineProxy class to retrieve the data from a dummy service (a local method call is used for illustration purposes) and store it in the Reference Data Cache by using the Reference Data Management subsystem.
  • Upload QuickStart illustrates how to upload the data on the server after the user of the application has updated some information on the client. This QuickStart illustrates the use of the Message Data Management subsystem of the block. The queue is used to store the messages before they are processed.
  • Insurance Claims QuickStart illustrates an end-to-end application using a Web service. It is the most advanced of the QuickStarts and illustrates how to use the block in an application interacting with a Web service. The scripts that are included with this QuickStart create and delete the virtual directory in IIS. The QuickStart has a smart client application using all of the subsystems of the block: Service Agent Management, Connection State Management, Message Data Management, and Reference Data Management. It also demonstrates basic error handling for the exceptions raised from the block.

You can use these QuickStarts to gain a better understanding of the Offline Application Block, to develop new providers, or to modify existing providers. For example, you may want to develop several providers for connection detection capability and only enable the provider you want in the configuration file.

Important   The QuickStarts are intended to aid you in understanding the block; they are not production-ready code samples.

The following paragraphs discuss each of the QuickStarts in the context of the tasks that a developer would want to perform in an application.

Managing the Connected State of the Application

The Connection Management QuickStart illustrates how to use the Connection State Management subsystem components of the block to detect whether the application is online or offline and to force state changes in the application.

The QuickStart has a single screen with two buttons—Go Offline and Go Online—which allow the user to change the state of the application to online or offline. The screen also has a label to show the connected state of the application.

When the QuickStart is running, the block starts polling the connection in the background to automatically detect connection state changes. If the connection state is subsequently forced offline, polling stops immediately. The QuickStart registers for the ConnectionStateChangedEvent of the ConnectionManager class. Registration for this event allows the QuickStart to react to the changes in the connected state. When the connected state changes, the event is raised and the connection state label on the screen changes to reflect the application connection state.

To build the Connection Management QuickStart

  1. Open the ConnectionManagementQuickStart.sln solution (found in the <installation location>\Offline\QuickStarts\src\<language>\ConnectionManagementQuickStart\ folder) in Visual Studio .NET 2003. Alternatively, you can access the Connection Management QuickStart as follows: click Start, click All Programs, click Microsoft Application Blocks for .NET, click Offline, click QuickStart Samples (C#) / (VB), and then click Connection Management QuickStart.
  2. Build the solution. This generates the ConnectionManagementQuickstart.exe assembly in the bin\<build configuration> folder in the <installation location>\Offline\QuickStarts\src\<language>\ConnectionManagementQuickStart\ folder.

To start the QuickStart, double-click ConnectionManagerQuickStart.exe.

Connection Management QuickStart Files

The QuickStart files build in the <installation location>\Offline\QuickStarts\src\<language>\ConnectionManagementQuickStart\ folder. Table 3.2 describes the files that are relevant to this discussion of the Connection Management QuickStart.

Table 3.2: Connection Management QuickStart Files

File Description
App.config Specifies the configuration information for the application.
ConnectionManagementForm.cs \ .vb Corresponds to the view (UI) of the application.
ConnectionManagementQuickStart.sln Solution file for the Connection Management QuickStart.
Controller.cs \ .vb Manages the UI interactions with the connection manager and service agents. It also registers for a connection state changed event and responds to the change by propagating the changes to the associated view.

Details

The QuickStart uses the default connection detection provider (strategy) that ships with the block. The default connection detection provider uses the InternetGetConnectedState method of the WinInet dynamic-link library (DLL) to detect connection state changes. For example, if you remove the network cable from a computer that is connected to the network while running the sample, the connection state displays the change to offline mode.

The providers for detecting the connection are specified in the application configuration file. For more information about specifying the providers in the configuration file, see Chapter 4, "Offline Application Block Configuration and Security Considerations."

Data in Transition: Downloading

The Download QuickStart illustrates how to download the reference data that allows the user of the application to continue to use the application even when the application goes offline.

The QuickStart has a single screen with a Download button and a grid to display the results. When the user clicks the Download button, the data downloads (it is read from the XML file locally) and appears in the grid.

To build the Download QuickStart

  1. Open the DownloadQuickStart.sln solution (found in the <installation location>\Offline\QuickStarts\src\<language>\DownloadQuickStart\ folder) in Visual Studio .NET 2003. Alternatively, you can access the Download Quick Start as follows: click Start, click All Programs, click Microsoft Application Blocks for .NET, click Offline, click Quick Start Samples (C#) / (VB), and then click Download Quick Start.
  2. Build the solution. This generates the DownloadQuickstart.exe assembly in the bin\<build configuration> folder in the <installation location>\Offline\QuickStarts\src\<language>\DownloadQuickStart\ folder.

To start the QuickStart, double-click DownloadQuickStart.exe.

Download QuickStart Files

The QuickStart files build in the <installation location>\Offline\QuickStarts\src\<language>\DownloadQuickStart\ folder. Table 3.3 describes the files that are relevant to this discussion of the Download QuickStart.

Table 3.3: Download QuickStart Files

File Description
App.config Specifies the configuration information for the application.
DownloadQuickStartForm.cs \ .vb Corresponds to the view (UI) of the application.
DownloadQuickStart.sln Solution file for the Download QuickStart.
Controller.cs \ .vb Manages the UI interaction with the connection manager and service agents. It registers for a connection state change event, creates and registers with the DownloadDataServiceAgent, it Initiates the download, and it updates the view with results when the data is available.
DownloadDataServiceAgent.cs \ .vb Populates the necessary context information for the OnlineProxy and service agent used for downloading the work items. It Initiates download of the work item by calling DataLoaderManager and returns the results to the controller.
OnlineProxy.cs \ .vb Interacts with the remote service; in this case, it is a local file for downloading the data.
DataSimulator.xml Store for the dummy data that is used by the online proxy to return the data.

Details

This QuickStart uses a service agent—DownloadDataServiceAgent—to initiate the download. DownloadDataServiceAgent is responsible for creating the correct ReferenceDataDefinition using the necessary context information, such as using OnlineProxyContext for creating the OnlineProxy class to retrieve the data from a dummy service (a local method call is used for illustration purposes) and ServiceAgentContext for returning the results back to the controller. The service agent calls the DataLoaderManager to initiate the download of the reference data with the correct ReferenceDataDefinition value.

The OnlineProxy is responsible for retrieving the data and then storing it in the Reference Data Cache by using the Reference Data Management subsystem.

By default, the QuickStart uses InMemoryQueueStorageProvider for caching the data. The providers for caching are specified in the application configuration file. For details about how to specify the providers in the configuration file refer to Chapter 4, "Offline Application Block Configuration and Security Considerations."

Data in Transition: Uploading

The Upload QuickStart illustrates how to upload the data to the server after the user of the application has modified it. This QuickStart illustrates the use of the Message Data Management subsystem of the block.

The QuickStart has a basic form with a few fields, a Save button, and a Cancel button. When the QuickStart is started, it reads a local XML file containing the data and displays the data in the form. When the user modifies the data and clicks the Save button, the data is saved to the XML file locally. This simulates using all of the components that are required when communicating with a remote service.

To build the Upload QuickStart

  1. Open the UploadQuickStart.sln solution (found in the <installation location>\Offline\QuickStarts\src\<language>\UploadQuickStart\ folder) in Visual Studio .NET 2003. Alternatively, you can access the Upload Quick Start as follows: click Start, click All Programs, click Microsoft Application Blocks for .NET, click Offline, click Quick Start Samples (C#) / (VB), and then click Upload Quick Start.
  2. Build the solution. This generates the UploadQuickstart.exe assembly in the bin\<build configuration> folder in the <installation location>\Offline\QuickStarts\src\<language>\UploadQuickStart\ folder.

To start the QuickStart, double-click UploadQuickStart.exe.

Upload QuickStart Files

The QuickStart files build in the <installation location>\Offline\QuickStarts\src\<language>\UploadQuickStart\ folder. Table 3.4 describes the files that are relevant to this discussion of the Upload QuickStart.

Table 3.4: Upload QuickStart Files

File Description
App.config Specifies the configuration information for the application.
UploadQuickStartForm.cs \ .vb Corresponds to the view (UI) of the application.
UploadQuickStart.sln Solution file for the Upload QuickStart.
Controller.cs \ .vb Manages the UI interaction with the connection manager and service agents. It registers for a connection state changed event, it creates and registers with the UploadDataServiceAgent, and it initiates upload.
UploadDataServiceAgent.cs \ .vb Creates Payload and populates the necessary context information for the OnlineProxy and service agent used for uploading the work items. It Initiates the upload of work item information by calling the QueueManager, and returns the results to the controller (if required).
OnlineProxy.cs \ .vb Interacts with the remote service. In this case, it is a local file for uploading the data.
DataSimulator.xml Store for the dummy data that is used by online proxy.

Details

This QuickStart illustrates how the Message Data Management subsystem functions. When the QuickStart is started, it reads the data from the local XML file and displays the data in the form. When, after modifying the data, the user clicks the Save button, the controller calls the UpdateWorkItem method of UploadDataServiceAgent object.

The UploadDataServiceAgent object creates the Payload object that is required for processing the request and providing the necessary context information, such as the OnlineProxyContext and ServiceAgentContext objects.

After creating the payload, the UploadDataServiceAgent object stores the payload in the queue. The Executor object picks up the payload from the queue and then calls the OnlineProxy object to process the request.

The OnlineProxy object updates the data in the local XML file. It could also communicate this information to a service. It uses the ServiceAgentContext object to return the result to the controller.

By default, the QuickStart uses InMemoryQueueStorageProvider for queuing the message. The providers for queuing are specified in the application configuration file. For more information about how to specify the providers in the configuration file, refer to Chapter 4, "Offline Application Block Configuration and Security Considerations."

Comprehensive End-to-End Solution

The Insurance Claims QuickStart brings together all of the concepts that were discussed earlier in this chapter and in Chapter 2. This QuickStart illustrates an end-to-end application using a Web service running on the server (or also the local computer) that provides the business capabilities.

Note   By default, when the QuickStart solution is installed, the Web service project and script that creates a virtual directory is included. This script creates the Web service on the same computer. As an alternative approach and to simulate more realistic conditions, you can create a Web service on a different computer. To do this, you must make the appropriate changes to the solution file as well as change the Web references.

There are two parts to this QuickStart: the Insurance Claims Client (smart client application) and the Insurance Claims Service (Web service).

The client corresponds to the smart client application and has the ability to work in an offline mode. The Web service exposes the business capabilities as Web methods.

The user interface consists of a single screen that brings together each of the user interfaces that were exposed in the previous QuickStarts. There are buttons on the screen to force the application online or offline, download work items, and then save the work items that get uploaded when the application is online. This QuickStart uses all of the subsystems of the Offline Application Block.

Before you can build the QuickStart, you must create the Web service and the database that the Web service uses.

To create the Insurance Claims Web service and the database that it uses

  1. To create the Web service, run the CreateInsuranceClaimsServiceVDir.vbs script, which is located in the <installation location>\Offline\QuickStarts\src\<language>\InsuranceClaimsQuickStart\ folder. Alternatively, you can run the script as follows: click Start, click All Programs, click Microsoft Application Blocks for .NET, click Offline, click Quick Start Samples (C#) / (VB), and then click Install Insurance Claims Service.
  2. To create the database, you must have MSDE 2000 installed on your computer. For instructions on how to obtain and install MSDE 2000, see "Software Requirements" earlier in this chapter.
  3. To create the database, run the CreateWebServiceDB.cmd script, which is located in the <installation location>\Offline\QuickStarts\src\<language>\InsuranceClaimsQuickStart\Database\ folder. Before running the script, you must change the instance name of your MSDE 2000 installation in the CreateWebServiceDB.cmd script. Also, if MSDE 2000 is not installed in the default location, you must modify the location where the InsuranceClaims.sql script creates the database files.

Note that you must perform the previous steps on the computer that has the Web service installed.

Important   By default, MSDE uses Windows authentication for its logon mode. The Web service runs under the default user named ASPNET, which has to be given permissions and configured before you can effectively use MSDE. For instructions on how to give permissions and configure the account, see the .NET Framework SDK QuickStart Configuration Details documentation. By default, this documentation is located at: <drive:\>Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Samples\Setup\html\ConfigDetails.htm on the computer running Visual Studio .NET.
However, if you want to change the authentication from Windows mode to mixed mode authentication, you must change the LoginMode hexadecimal value from 1 to 2 for the following registry key: My Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\VSDOTNET\MSSQLServer.

After you create the Web service and the database, use the following steps to build the QuickStart.

To build the Insurance Claims QuickStart

  1. Open the InsuranceClaimsQuickStart.sln solution (found in the <installation location>\Offline\QuickStarts\src<language>\InsuranceClaimsQuickStart\ folder) in Visual Studio .NET 2003. Alternatively, you can access the Offline Application Block as follows: click Start, click All Programs, click Microsoft Application Blocks for .NET, click Offline, click Quick Start Samples (C#) / (VB), and then click Insurance Claims Quick Start.
  2. Build the solution. This generates:
    • InsuranceClaimsClient.exe assembly in the bin\<build configuration> folder in the <installation location>\Offline\QuickStarts\src\<language>\InsuranceClaimsQuickStart\InsuranceClaimsClient\ folder.
    • InsuranceClaimsService.dll under the bin folder located in <installation location>\Offline\QuickStart\src\<language>\InsuranceClaimsQuickStart\InsuranceClaimsService folder.
  3. Change the datasource name in the Web service configuration file to point to the correct datasource.

To start the QuickStart, double-click InsuranceClaimsQuickStart.exe.

Insurance Claims QuickStart Files

The QuickStart solution builds in the <installation location>\Offline\QuickStarts\src\<language>\ InsuranceClaimsQuickStart\InsuranceClaimsClient\ folder. Tables 3.4 and 3.5 describe the files that are relevant to this discussion of the Insurance Claims QuickStart.

Table 3.4: Insurance Claims QuickStart Client Files

File Description
App.config Specifies the configuration information for the application.
InsuranceClaimsQuickStartForm.cs \ .vb Corresponds to the view (UI) of the application.
Controller.cs \ .vb Manages the UI interaction with the Connection Manager and service agents. It registers for a connection state change event and responds to the change by propagating the changes to the associated view. Creates InsuranceCliamsClientServiceAgent and registers with it to initiate download and upload of the work items.
InsuranceClaimsClientServiceAgent.cs \ .vb Initiates download and upload of the work item information. It creates Payload and populates it with the necessary context information about the Online Proxy and service agent used for downloading or uploading the work items, and it returns the results to the controller.
OnlineProxy.cs \ .vb It is responsible for downloading and uploading the data by communicating with the Web service.

Table 3.5: Insurance Claims Service Web Service Files

File Description
Web.config Specifies the location of the database that the Web service uses.
InsuranceClaims.asmx,cs \ .vb Exposes Web methods to be used by the client application.

Details

For information about how specific actions are performed, refer to the details of the previous QuickStarts. For example, the details in the previous QuickStarts described the components involved in downloading the work items or uploading the work items.

The only difference between the previous QuickStarts and this one is the behavior of the OnlineProxy class. To keep the QuickStarts at a basic level, the OnlineProxy class in the previous QuickStarts retrieved or updated data locally. In this case, the QuickStart interacts with a Web service and demonstrates an end-to-end scenario of an application using the Offline Application Block.

Using the Offline Application Block

Before using the Offline Application Block, you should evaluate the existing providers and determine whether you want to use them or create new ones.

Evaluating Providers Based on Application Requirements

When you want to add offline capabilities to an application, you must identify the requirements of that application with respect to the following providers:

  • Connection Detection Provider–The Offline Block provides the WinInetDetectStrategy for connection management. You should evaluate whether this meets the application requirements or whether you need to develop a custom provider. For example, you may require a custom provider to determine whether a particular Web service is available.
  • Cache Storage Provider–The Cache Block provides MSDE, In-Memory, Memory-Mapped Files, Isolated Storage, and SQL Server as storage providers. You should evaluate if any of these providers fit within your application architecture. If not, you need to create a custom provider. For example, you may require caching data to a different database engine.
  • Queue Storage Provider–The Offline Block provides MSDE, In-Memory, Isolated Storage, and Message Queuing as queue storage providers. You should evaluate if any of these providers fit your application architecture. If not, you need to create a custom provider. For example, you may require that data be queued to another queue storage provider.

Encrpytion Provider–The Common Block provides the Data Protection API as its encryption provider. You should evaluate if this provider fits within your application architecture based on your organization's security requirements. If not, you need to create a customer provider.

For information about using providers in an application or developing your own custom providers, see "Developing Your Own Provider," later in this chapter.

Tasks That Use the Offline Block

In the design phase, your organization determined the business requirements that the Offline Application Block would fulfill. Some of these requirements involved the user interface (UI) and the User Interface Controller (UIC). These user interfaces are dependent on the business requirements set forth by your organization and determine the interaction between the online/offline operation and the user. A discussion of the UIC and user interface process (UIP) is out of scope for this guide.

The following list walks you through common tasks that you might perform while building an application with offline capability.

To get started

  1. Depending on the application you are developing, implement the required application service agents. Make sure that the application service agents derive from the ServiceAgent base class.
  2. Implement the OnlineProxy component (usually one for each application service agent, but not necessarily), which acts as the application's interface with the Web service or any other data store used for storing and retrieving information. This component contains the application-specific code for accessing the Web service.
    Note   For more information, you can view the Insurance Claims QuickStart Visual C# or Visual Basic code located in the <installation location>\Offline\QuickStarts\src\<language>\InsuranceClaimsQuickStart\InsuranceClaimsClient folder.

To begin accessing offline functionality

  1. Create a block builder instance from the OfflineBlockBuilder class by calling the OfflineBlockBuilder.Instance property. You can use this OfflineBlockBuilder class to build and access all components of the block. The OfflineBlockBuilder instance is normally obtained in the constructor of the UIC as shown in the following code.

    [C#]

    ...
        private OfflineBlockBuilder offlineBlockBuilderInstance;
        offlineBlockBuilderInstance = OfflineBlockBuilder.Instance;
        ...
        

    [Visual Basic]

    ...
        Private OfflineBlockBuilder offlineBlockBuilderInstance
        offlineBlockBuilderInstance = OfflineBlockBuilder.Instance
        ...
        
  2. Register with the Connection Manager component for online/offline changed state events, as shown in the following code.

    [C#]

    ...
        offlineBlockBuilderInstance.ConnectionManager.ConnectionState ChangedEvent += new ConnectionStateChangedEventHandler(ConnectionManager
        ConnectionStateChangedEvent);
        ...
        

    [Visual Basic]

    ...
        offlineBlockBuilderInstance AddHandler offlineBlockBuilderInstance.ConnectionManager.ConnectionStateChangedEvent, AddressOf ConnectionManagerConnectionStateChangedEvent
        ...
        
  3. Create an instance of Application Service Agent for the offline client.
  4. Register the controller with the Application Service Agent for various events. These events notify the end user about the changes that happen in the background.
  5. Register the controller with the FailsafeServiceAgent, for handling errors in case the original Application Service Agent is not available.

    [C#]

    ...
        FailsafeServiceAgent refFailSafeServiceAgent = offlineBlockBuilderInstance.FailsafeServiceAgent;
        refFailSafeServiceAgent.ErrorEvent += new MethodExecutionFailureReportEventHandler(
        FailSafeServiceAgentErrorEvent);
        ...
        

    [Visual Basic]

    ...
        Dim refFailSafeServiceAgent As FailsafeServiceAgent = offlineBlockBuilderInstance.FailsafeServiceAgent
        AddHandler refFailSafeServiceAgent.ErrorEvent, AddressOf FailSafeServiceAgentErrorEvent
        ...
        
  6. Call the Start method of the OfflineBlockBuilder object to start the Connection Manager. This component polls connection status and sends events to the Service Agent when the connection state changes.

    [C#]

    ...
        offlineBlockBuilderInstance.Start() ;
        ...
        

    [Visual Basic]

    ...
        offlineBlockBuilderInstance = OfflineBlockBuilder.Start
        ...
        
  7. Use the GoOffline method of the ConnectionManager component if you want to force the Application to work in offline mode, as shown in the following code.

    [C#]

    ...
        offlineBlockBuilderInstance.ConnectionManager.GoOffline() ;
        ...
        

    [Visual Basic]

    ...
        offlineBlockBuilderInstance.ConnectionManager.GoOffline()
        ...
        
  8. Use the GoOnline method of the ConnectionManager component if you want to bring the application back online, as shown in the following code.

    [C#]

    ...
        offlineBlockBuilderInstance.ConnectionManager.GoOnline() ;
        ...
        

    [Visual Basic]

    ...
        offlineBlockBuilderInstance.ConnectionManager.GoOnline()
        ...
        

To load data in the client data store by using the DataLoaderManager in Application Service Agent

  1. Create an OnlineProxyContext object, which is used by the Executor to invoke the method on the OnlineProxy class.
  2. Create a ServiceAgentContext object, which is used by ServiceAgentManager to invoke the callback method of the Application Service Agent when the data is available.
  3. Create a ReferenceDataDefinition object using the OnlineProxyContext and ServiceAgentContext.
  4. Call the LoadData method of the DataLoaderManager object to enqueue the data download request.

The following code illustrates the previous steps:

[C#]

...
string onlineProxyAssemblyName = "InsuranceClaimsClient";
string onlineProxyClassName = "Microsoft.ApplicationBlocks.SmartClient.Offline.QuickStarts.OnlineProxy";
string onlineProxyMethodName ="GetWorkItems";
string specificServiceAgentMethodTobeInvoked = "DataAvailableCallBack";
const int absoluteExpirationTime = 600;
string cacheKey = "SmartClient";
OnlineProxyContext onlineProxyMethodContext =
new OnlineProxyContext(onlineProxyAssemblyName,
onlineProxyClassName, onlineProxyMethodName);
ServiceAgentContext specificServiceAgentContext = new
ServiceAgentContext(specificServiceAgentMethodTobeInvoked);
ReferenceDataDefinition refDataDefination = new
ReferenceDataDefinition(cacheKey, absoluteExpirationTime,
onlineProxyMethodContext);
offlineBlockBuilderInstance.DataLoaderManager.LoadData(this.Guid,
specificServiceAgentContext, refDataDefination);
...

[Visual Basic]

...
Dim onlineProxyAssemblyName As String = "InsuranceClaimsClient"
Dim onlineProxyClassName As String =
"Microsoft.ApplicationBlocks.SmartClient.Offline.QuickStarts.OnlineProxy"
Dim onlineProxyMethodName As String = "GetWorkItems"
Dim specificServiceAgentMethodTobeInvoked As String =
"DataAvailableCallBack"
Const absoluteExpirationTime As Integer = 600
Dim cacheKey As String = "SmartClient"
Dim onlineProxyMethodContext As New
OnlineProxyContext(onlineProxyAssemblyName, onlineProxyClassName,
onlineProxyMethodName)
Dim specificServiceAgentContext As New
ServiceAgentContext(specificServiceAgentMethodTobeInvoked)
Dim refDataDefination As New ReferenceDataDefinition(cacheKey,
absoluteExpirationTime, onlineProxyMethodContext)
offlineBlockBuilderInstance.DataLoaderManager.LoadData(Me.Guid,
specificServiceAgentContext, refDataDefination)
...

To enqueue data by using QueueManager in Application Service Agent

  1. Create an OnlineProxyContext for the method in the OnlineProxy to be invoked for downloading or uploading the data.
  2. Create a ServiceAgentContext object to invoke the callback method in the Application Service Agent when the data is available or updated.
  3. Create a new Payload object by using the OnlineProxyContext and ServiceAgentContext methods.
  4. Call the Enqueue method of the PayloadConsumer object to enqueue the data update request.

The following code illustrates the previous steps:

[C#]

...
string onlineProxyAssemblyName = "InsuranceClaimsClient";
string onlineProxyClassName = "Microsoft.ApplicationBlocks.SmartClient.Offline.QuickStarts.OnlineProxy";
string onlineProxyMethodName ="UpdateWorkItem";
string specificServiceAgentMethodTobeInvoked = "DataUpdatedCallBack";
OnlineProxyContext onlineProxyMethodContext = new
OnlineProxyContext(onlineProxyAssemblyName, onlineProxyClassName,
onlineProxyMethodName);
ServiceAgentContext specificServiceAgentContext = new
ServiceAgentContext(specificServiceAgentMethodTobeInvoked);
Payload messageToEnqueue = new
Payload(onlineProxyMethodContext,this.Guid,
specificServiceAgentContext, changedAppData);
offlineBlockBuilderInstance.PayloadConsumer.Enqueue(messageToEnqueue);
...

[Visual Basic]

...
Dim onlineProxyAssemblyName As String = "InsuranceClaimsClient"
Dim onlineProxyClassName As String = "Microsoft.ApplicationBlocks.SmartClient.Offline.QuickStarts.OnlineProxy"
Dim onlineProxyMethodName As String = "UpdateWorkItem"
Dim specificServiceAgentMethodToInvoke As String = "DataUpdatedCallBack"
Dim onlineProxyMethodContext As New OnlineProxyContext(onlineProxyAssemblyName, onlineProxyClassName, onlineProxyMethodName)
Dim specificServiceAgentContext As New ServiceAgentContext(specificServiceAgentMethodToInvoke)
Dim messageToEnqueue As New Payload(onlineProxyMethodContext, _
Me.Guid, specificServiceAgentContext, _
changedAppData)
offlineBlockBuilderInstance.PayloadConsumer.Enqueue(messageToEnqueue)

Developing Your Own Provider

Thus far, the focus of this chapter has been how to use the Offline Application Block in your application without modification. A key aspect of the design is that you can extend the block with your own providers. These considerations are applicable to any provider that you create.

To develop your own provider

  1. Create a provider class that implements the appropriate interface for the subsystem:
    • Connection Detection Provider–Implement IConnectionDetectionStrategy and IProvider interfaces.
    • Queue Storage Provider–Implement the IQueueStorageProvider interface and IProvider interface.
    • Cache Storage Provider–Implement the ICacheStorage provider interface.
  2. Set the configuration settings for custom provider. There are separate configuration sections for the providers for each subsystem. The general rule is to specify common properties of the providers in the section as attributes, and custom properties as elements.

The WinInetDetectionStrategy provider illustrates how the previous design considerations manifest a connection detection provider that the Connection Management subsystem uses for connection detection.

The WinInetDetectionStrategy provider implements the IConnectionDetectionStrategy and IProvider interfaces. The configuration settings for these providers are defined in the ConnectionManagerProviders section as a provider element with the name attribute set to winINetDetectionStrategy. The common properties are specified as attributes and the custom property pollingInterval is specified as a sub-element of the provider element. The ConnectionManagerConfigurator class reads the configuration information, and creates an instance of this provider.

Setting Up MSDE and MSMQ

Before using MSDE and MSMQ providers through the Quickstarts or any custom application, you need to set up MSDE and MSMQ accordingly.

MSDE Setup

Before using the MSDE provider for cache or queue, you must configure MSDE to work properly on the client computer. For more information, refer to <drive:\ >Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Samples\Setup\html\ConfigDetails.htm.

To configure the MSDE provider for caching, you must create the required tables and stored procedures that the cache block uses.

To create the tables and procedures

  1. Locate the CreateCache.cmd script in the <installation location>\Offline\Database\Cache folder.
  2. Open the CreateCache.cmd file, and change the server name to point to the correct server.
  3. Run the CreateCache.cmd script.

When using the MSDE provider for queuing, you must create the required database that is used by the Message Data Management subsystem.

To create the database

  1. Locate the CreateQueueDB.cmd script in the <installation location>\Offline\Database\Queue folder.
  2. Open the CreateQueueDB.cmd script, and change the server name to point to the correct server.
  3. If MSDE is installed on a different drive than C:, you must change the path in the QueueDatabase.sql file to the correct path for your MSDE installation.
  4. Run the CreateQueueDB.cmd script.
Note   To enable the MSDE provider for either the cache or the Queue, go to the App.config file and, in the respective configuration sections, change ConnectionString so that it points to the correct Data Source.

Message Queuing

Before using the MSMQ provider for the queue, you must configure Message Queuing on your local computer. For more information, refer to Microsoft Message Queuing (MSMQ) Center (http://www.microsoft.com/windows2000/technologies/communications/msmq/default.asp)

The Offline Application Block creates the queue if one is not present. We recommend that you manually create the queue before using the Message Queuing provider. This gives you flexibility to configure Message Queuing according to your organizational security requirements. The following procedure explains how to create the queue manually.

To create a private queue manually

  1. Right-click MyComputer, and then click Manage.
  2. In Computer Management, expand the Message Queuing folder.
  3. In the console tree, right-click the Private Queues folder.
  4. Point to New, and then click Private Queue.
  5. In Name, type a name for the new queue, and click OK.

    - or -

    To create a queue to accept transactional messages, type a name, select the Transactional check box, and then click OK.

  6. Expand Private Queues.
  7. Right-click the newly created queue and select Properties.
  8. Add general and security configuration for the queue, such as security policy or permissions, and then click OK.
Note   You cannot create queues in the Outgoing Queues or System Queues folders. These queues are created automatically.
The queue name specified in Step 5 should be added to the application's configuration file, replacing the name that is currently there.

For more information on deployment requirements and considerations, see Chapter 4.

Summary

The Offline Application Block provides you with a flexible design and infrastructure that you can use to add offline capabilities to your applications. In many cases, you will use the supplied providers for the subsystems. In other cases, you will customize these providers or create your own providers. The QuickStarts supplied with the Offline Application Block give you a useful starting point for understanding how to use the block.

More Information

For more information about MSDE, see Distributing the SQL Server Desktop Engine.

For more information about SQL Server, see. SQL Server.

For more information about Message Queuing, see Message Queuing (MSMQ).

For more information about DPAPI, see Windows Data Protection.

Start | Previous | Next

posted on 2006-04-08 17:32  S孤单一吻S  阅读(849)  评论(0)    收藏  举报