Export (0) Print
Expand All
8 out of 15 rated this helpful - Rate this topic

Walkthrough: Creating an Occasionally Connected Smart Device Application

Visual Studio 2008

Updated: July 2008

This walkthrough provides step-by-step directions for configuring data synchronization in an occasionally connected smart device application. The sample application adds a customer to the local database cache and synchronizes the changes with a remote database. It also displays customer data on a Windows Form: this enables you to verify that synchronization is successful.

During this walkthrough, you will follow these steps:

  • Create a new Smart Device application.

  • Add a new Window Communication Foundation (WCF) Service Library which serves as a middle tier between the local database cache and the remote database.

    NoteNote:

    The middle tier service library is required because Synchronization Services for ADO.NET (Devices) does not support direct 2-tier synchronization.

  • Add a new Local Database Cache to the project.

  • Configure synchronization settings.

  • Configure and start the WCF service.

  • Add synchronization functionality to your device application.

  • Test the application.

To complete this walkthrough you must:

NoteNote:

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To create a new project on the desktop computer

  1. From the File menu, create a new project that uses either Visual Basic or Visual C#.

    NoteNote:

    The Configure Data Synchronization dialog box is supported in Visual Basic and C# projects. Therefore, make sure to select one of these languages.

  2. Name the solution Walkthrough and the project OCSDeviceApp.

  3. Under Project types, click Smart Device, and then Smart Device Project template.

  4. Click OK.

    The Add New Smart Device Project dialog box will appear. By default, the Windows Mobile 5.0 Pocket PC SDK target operating system, .NET Compact Framework version 3.5, and Device Application template are selected.

  5. Click OK.

    The OCSDeviceApp project is created and added to Solution Explorer.

Creating a WCF Service

Unlike desktop applications, the local SQL Server Compact database cache cannot synchronize directly with the remote SQL Server database for smart device projects. You must create a WCF service library that acts as a middle tier between the two databases. The device application uses services exposed by the WCF service for synchronization.

To add a WCF Service Library to the Solution

  1. From the File menu, point to Add, and then click New Project.

  2. Name the project MiddleTierServiceLibrary.

  3. Click WCF under Project types, followed by the WCF Service Library template.

  4. Click OK.

    The MiddleTierServiceLibrary project is created and added to Solution Explorer.

Adding a Local Database Cache

  • Unlike desktop applications, the Local Database Cache template is not available from the Add New Item dialog box of a smart device project. Instead, you must add a local database cache to the middle tier WCF or Web Service project.

To add a local database cache to a project

  1. Right-click the MiddleTierServiceLibrary project, point to Add, and then click New Item.

  2. Click the Local Database Cache template and type NorthwindCache.sync in the Name box.

  3. Click Add.

    A NorthwindCache.sync file is added to Solution Explorer and the Configure Data Synchronization dialog box appears. NorthwindCache.sync stores synchronization configuration information.

Configuring Synchronization Settings

To create data connections to the server and client databases

  1. Use the Configure Data Synchronization dialog box to create a connection to the Northwind database that you installed as a prerequisite to this walkthrough. This is the remote database external to your smart device application. You may either select an existing Server connection to the SQL Server Northwind database, or, if a connection does not exist, click New to create a new connection to the SQL Server Northwind database.

    NoteNote:

    You may enable SQL Server change tracking, but only after the connection to the remote database server is configured to connect to a SQL Server 2008 database. For more information, see How to: Configure Data Synchronization to Use SQL Server Change Tracking.

  2. Accept the default value of Northwind.sdf (new) for the Client connection. The Configure Data Synchronization dialog box creates a new SQL Server Compact 3.5 database and adds it to your project. For more information about the available data connection options, see How to: Create a Data Connection to the Northwind Database.

    After you select the server connection, the Configure Data Synchronization dialog box queries the remote database on the server for a list of available tables. This dialog box also enables the Add button, but only after the list of available tables is retrieved.

    NoteNote:

    Notice that the OK button is not enabled at the conclusion of this step. This is because no tables have been selected for synchronization. The next section explains how to add tables.

To add and configure tables for local caching

  1. Click Add to open the Configure Tables for Offline Use dialog box.

  2. Select the Customers table.

    NoteNote:

    You can modify the default synchronization behavior for each table that you select in the Configure Tables for Offline Use dialog box. For more information, see How to: Configure Data Synchronization in an Application.

  3. Accept the default column and table values. Click OK. The Configure Data Synchronization dialog box will create tracking columns and a deleted-items table if needed.

    The Customers table is added to the Cached Tables list.

To split synchronization components between the server and client projects

  1. In the Configure Data Synchronization dialog box, click Advanced.

  2. On the Client project location drop down menu, select OCSDeviceApp.

  3. Click OK.

    Components will be divided between the client project and the server project, after data synchronization is configured. Meanwhile, the Generate SQL scripts dialog box appears. By default, it generates scripts that maintain tracking columns and tables for deleted and updated items on the server database.

  4. Click OK.

    The generated SQL scripts are saved in the server project if needed. The Northwind.sdf client database is created in the client project and synchronized with the server database for the first time.

    NoteNote:

    SQL scripts are created only if modifications are required on the server. If the server already has a deleted items table and tracking columns or if you use SQL Server change tracking, no scripts are created.

  5. When the Data Source Configuration Wizard appears, select the Customers table.

  6. Click Finish.

    NorthwindDataSet.xsd is added to the client project and all dialog boxes close.

Now that synchronization is configured, the following items are added to the client project:

Item

Description

Northwind.sdf

  • A local database file that contains data cached from SQL Server.

NorthwindCache.Client.sync

  • An XML file that contains synchronization configuration information. Double-click this file to open the Configure Data Synchronization dialog box.

NorthwindCache.Client.Designer.cs (or .vb)

A code file that contains definitions for client sync provider and the sync agent. Also contains sync tables for the local database. For more information, see Architecture and Classes for Client and Server Synchronization.

NorthwindDataSet.xsd

  • The typed dataset generated by the Data Source Configuration wizard. This dataset contains a Customers table that is populated with data that is stored in the local database.

References\Microsoft.Synchronization.Data

References\Microsoft.Synchronization.Data.SqlServerCe

Required references to Microsoft Synchronization Services for ADO.NET.

The following items are added to the server project:

Item

Description

NorthwindCache.sync

An XML file that contains synchronization configuration information. Double-click this file to open the Configure Data Synchronization dialog box.

NorthwindCache.Designer.cs (or .vb)

Contains definitions for the Server Sync Provider and the Sync Adapter for the server database. For more information, see Architecture and Classes for Client and Server Synchronization.

NorthwindCache.SyncContract.cs (or .vb)

A code file that contains the WCF contract definition and its implementation.

SQLScripts folder

A folder of scripts. The scripts in this folder are used to track database changes on the server. Some of the scripts in this folder create the tracking columns, deleted items table. Other scripts in this folder create triggers that track changes on the server.

NoteNote:

SQL scripts are created only if modifications are required on the server. If the server already has a deleted items table and tracking columns or if you use SQL Server change tracking, no scripts are created.

SQLUndoScripts folder

The scripts in this folder delete the tracking columns, the items table, and any triggers that are used to track and respond to database changes on the server. Use these scripts to undo the changes made by the Configure Data Synchronization dialog box to the database.

NoteNote:

SQL scripts are created only if modifications are required on the server. If the server already has a deleted-items table and tracking columns or if you use SQL Server change tracking, no scripts are created.

References\Microsoft.Synchronization.Data

References\Microsoft.Synchronization.Data.Server

Required references to Microsoft Synchronization Services for ADO.NET.

Configuring and Starting the WCF Service

To configure the WCF service (NorthwindCacheSyncService) that is generated by the Configure Data Synchronization dialog box

  1. In Solution Explorer, double-click NorthwindCache.SyncContract.cs (or .vb) to open the file in the Code Editor.

  2. Add the XmlSerializerFormat() attribute just before the definition INorthwindSyncContract. The Code Editor should display:

  3. In Solution Explorer, double-click App.config.

  4. Make the following XML modifications to the App.config file. These changes configure the project to host the NorthwindCacheSyncService generated by the Configure Data Synchronization dialog box instead of the default service (Service1) that is generated by the WCF project template.

    1. Change <service name="MiddleTierServiceLibrary.Service1" behaviorConfiguration="MiddleTierServiceLibrary.Service1Behavior"> to <service name="MiddleTierServiceLibrary.NorthwindCacheSyncService" behaviorConfiguration="MiddleTierServiceLibrary.NorthwindCacheSyncServiceBehavior">

    2. Change <add baseAddress="http://localhost:8731/Design_Time_Addresses/MiddleTierServiceLibrary/Service1/" /> to <add baseAddress="http://<your computer IP address>:8731/NorthwindCacheSyncService/" />

    3. Change <endpoint address="" binding="wsHttpBinding" contract="MiddleTierServiceLibrary.IService1"> to <endpoint address="" binding="basicHttpBinding" contract="MiddleTierServiceLibrary.INorthwindCacheSyncContract">

      NoteNote:

      wsHttpBinding is not supported on devices.

    4. Change <dns value="localhost"/> to <dns value="<your computer IP address>"/>

    5. Change <behavior name="MiddleTierServiceLibrary.Service1Behavior"> to <behavior name="MiddleTierServiceLibrary.NorthwindCacheSyncServiceBehavior">

  5. Right-click MiddleTierServiceLibrary in Solution Explorer and click Set as StartUp Project.

  6. To start the WCF Service, click Start Without Debugging in the Debug menu.

    The Deploy OCSDeviceApp dialog box appears.

  7. Click Cancel and then Yes to continue.

    NoteNote:

    You are only starting the WCF service: the device emulator is not yet required.

    The WCF Service Host is started (icon appears in notification area) and hosts the service. The WCF Test Client appears and enables you to test the service.

    NoteNote:

    Make sure that the port is accessible and not blocked by a firewall.

Coding Synchronization Features in Your Smart Device Application

The previous steps configured your data synchronization options. In addition, you must add synchronization functionality to your smart device application.

Adding a Web reference from the project to the WCF service

  1. In Solution Explorer, right-click OCSDeviceApp, and then click Add Web Reference.

    The Add Web Reference dialog box appears.

  2. Type the address of the NorthwindCacheSyncService, such as http://IP Address:8731/NorthwindCacheSyncService/, in the URL box, and then click Go.

    NoteNote:

    Insure that there are no firewalls blocking port 8731 on the computer.

    Once the NorthwindCacheSyncService Web service is found, the Add Reference button is enabled.

    NoteNote:

    The service address may be found in the App.config file.

  3. Name the Web reference NorthwindCacheWebRef, and then click Add Reference.

    NorthwindCacheWebRef appears under Web References in Solution Explorer. Visual Studio generates the file Reference.cs: however, you will not be able to see this file in Solution Explorer.

  4. Perform the following steps to open and modify Reference.cs:

    1. Double-click NorthwindCacheWebRef to open it in Object Browser.

    2. Expand the node OCSDeviceApp.NorthwindCacheWebRef.

    3. Right-click NorthwindCacheSyncService and click Go To Definition.

      Reference.cs is opened in the Code Editor.

    4. Add the following code after the last using or imports statement:

      Imports Microsoft.Synchronization
      Imports Microsoft.Synchronization.Data
      

      Or, in C#:

      using Microsoft.Synchronization;
      using Microsoft.Synchronization.Data;
      
    5. Remove all classes and enumerations in the file except for NorthwindCacheSyncService.

      NoteNote:

      The removed types are already defined in the newly imported Microsoft.Synchronization and Microsoft.Synchronization.Data namespaces.

To create a data-bound form that is used to view data and initiate synchronization

  1. In Solution Explorer, double-click Form1 to open it in the Visual Studio designer.

  2. Drag the Customers node from the Data Sources window onto Form1.

  3. In Form1, click the left menu item and type Synchronize Now. Set its Name property to SynchronizeMenuItem.

    NoteNote:

    The user will ultimately click Synchronize Now to start the synchronization process.

  4. Double-click the Synchronize Now menu to create a menu-click event handler and open the form in the Code Editor.

  5. Add code that will start the synchronization process and refill the Customers table in the dataset. The code in the event handler should resemble the following:

    Cursor.Current = Cursors.WaitCursor;
    
    // The WCF Service
    NorthwindCacheWebRef.NorthwindCacheSyncService webSvcProxy = new 
        OCSDeviceApp.NorthwindCacheWebRef.NorthwindCacheSyncService();
    
    // The Remote Server Provider Proxy
    Microsoft.Synchronization.Data.ServerSyncProviderProxy serverProvider = new 
        Microsoft.Synchronization.Data.ServerSyncProviderProxy(webSvcProxy);
    
    // The Sync Agent
    NorthwindCacheSyncAgent syncAgent = new NorthwindCacheSyncAgent();
    syncAgent.RemoteProvider = serverProvider;
    syncAgent.Customers.SyncDirection = Microsoft.Synchronization.Data.SyncDirection.Bidirectional;
    
    // Synchronize the databases
    Microsoft.Synchronization.Data.SyncStatistics stats = syncAgent.Synchronize();
    
    // Reload the DataSet/Datagrid from the local database
    customersTableAdapter.Fill(northwindDataSet.Customers);
    
    // Show synchronization statistics
    MessageBox.Show("Changes Downloaded: " + stats.TotalChangesDownloaded.ToString() +
        "\r\n" + "Changes Uploaded: " + stats.TotalChangesUploaded.ToString());
    
    Cursor.Current = Cursors.Default;
    

The DataGridView displays the Customers table from the local database cache (the Northwind.sdf database located in the project).

To add a customer to the local Northwind database

  1. In Solution Explorer, Double-click Form1 to open it in the designer.

  2. Click the menu item that is located on the right side of the form and type Insert Row. Set the menu item's Name property to InsertRowMenuItem.

  3. Double-click the Insert Row button to create a menu-click event handler and open the form in the Code Editor.

  4. Add code to connect to (and insert a row in) the local SQL Server Compact database.

    System.Data.SqlServerCe.SqlCeConnection conn = new System.Data.SqlServerCe.SqlCeConnection(
        ("Data Source=" + (System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), "Northwind.sdf") + ";Max Database Size=2047")));
    try
    {
        // Connect to the local database
        conn.Open();
        System.Data.SqlServerCe.SqlCeCommand cmd = conn.CreateCommand();
    
        // Insert a row
        cmd.CommandText = "INSERT INTO Customers ([CustomerID], [CompanyName]) Values('NEWRW', 'Northwind Traders')";
        cmd.ExecuteNonQuery();
    }
    
    finally
    {
        conn.Close();
    }
    
    // Reload the DataSet/Datagrid from the local database
    customersTableAdapter.Fill(northwindDataSet.Customers);
    

    InsertRowMenuItem inserts a new row in the Customers table in the local database.

    NoteNote:

    Later, when you test the application, you can verify that the new row appears in the remote database following synchronization.

Before you can test the application, you must connect and cradle the target device emulator so that it can connect to the NorthwindCacheSyncService service.

To test the application

  1. From the Tools menu, click Device Emulator Manager (DEM).

    The DEM window appears with a list of available emulators.

  2. Right-click USA Windows Mobile 5.0 Pocket PC R2 Emulator (the target device for OCSWalkthrough) and click Connect.

    The Pocket PC - WM 5.0 Device Emulator appears.

  3. In the DEM window, right-click the connected device and click Cradle.

    Windows Mobile Device Center (Windows Vista) or ActiveSync connects to the cradled device emulator. If Windows Mobile Device Center or ActiveSync offers to set up the device, click Connect without setting up your device (Windows Vista) or Cancel.

    NoteNote:

    The connection to WMDC or ActiveSync enables the emulator to access NorthwindCacheSyncService, which runs on the desktop computer. In order for the device emulator to connect, the connection settings in WMDC or ActiveSync must be configured to allow for DMA connections.

  4. Right-click OCSDeviceApp in Solution Explorer and click Set as StartUp Project.

  5. Press F5 to debug.

  6. Go back to the form in the Pocket PC - WM 5.0 Device Emulator and click Insert Row. The local database and remote database are no longer synchronized. However, a new row should be visible in the Datagrid.

  7. Click Synchronize Now.

    The local (desktop) database and remote (device) database should both have the new row.

  8. On the desktop computer, use Server Explorer/Database Explorer (or another database management tool) to connect to the remote server database and verify that the new record exists.

    1. In Server Explorer/Database Explorer, locate the Customers table on the remote database server (not the connection to Northwind.sdf).

    2. Right-click the Customers table and click Show Table Data.

    3. Verify that the new row exists.

    4. Right-click the new row and click Delete. The databases will again be unsynchronized.

  9. Go back to the form in Device Emulator and click Synchronize Now.

  10. Verify that the modifications to the remote database are synchronized to the local database and displayed in the grid.

  11. Close the form. (Stop debugging.)

Tasks

How to: Configure Data Synchronization in an Application

Concepts

Occasionally Connected Applications Overview

Date

History

Reason

July 2008

Added topic.

SP1 feature change.

February 2009

Revised code sample.

Customer feedback.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.