Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
 Walkthrough: Creating an Occasional...
Smart Device Development
Walkthrough: Creating an Occasionally Connected Smart Device Application

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.

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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:

Cc488004.alert_note(en-us,VS.90).gifNote:

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#.

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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.

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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.

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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.

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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.

    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. The Northwind.sdf client database is created in the client project and synchronized with the server database for the first time.

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

  6. Click Finish.

  7. 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.

Cc488004.alert_note(en-us,VS.90).gifNote:
SQL scripts are created only if modifications are required on the server. If the server already has a deleted items table and tracking columns, 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.

Cc488004.alert_note(en-us,VS.90).gifNote:
SQL scripts are created only if modifications are required on the server. If the server already has a deleted-items table and tracking columns, 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:

    C#
    [ServiceContractAttribute()]
    [XmlSerializerFormat()]
    public interface INorthwindCacheSyncContract {
    <ServiceContractAttribute()> _
    <XmlSerializerFormat()> _
    Public Interface INorthwindCacheSyncContract
    
  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 name>:8731/NorthwindCacheSyncService/" />

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

      Cc488004.alert_note(en-us,VS.90).gifNote:

      wsHttpBinding is not supported on devices.

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

    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.

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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.

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 in the URL box, and then click Go.

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

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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:

      [C#]

      using Microsoft.Synchronization;
      using Microsoft.Synchronization.Data;
      

      [Visual Basic]

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

      Cc488004.alert_note(en-us,VS.90).gifNote:

      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.

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

Cc488004.alert_note(en-us,VS.90).gifNote:

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

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.

    Visual Basic
    Dim 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()
    
        ' Insert a row
        Dim cmd = conn.CreateCommand()
        cmd.CommandText = "INSERT INTO Customers ([CustomerID], [CompanyName]) Values('NEWRW', 'Northwind Traders')"
        cmd.ExecuteNonQuery()
    
    
    Catch ex As Exception
    Finally
        conn.Close()
    End Try
    
    ' Reload the DataSet/Datagrid from the local database
    CustomersTableAdapter.Fill(Me.NorthwindDataSet.Customers)
    
    
    C#
    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.

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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.

    Cc488004.alert_note(en-us,VS.90).gifNote:

    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.

  8. From the application that is running in Device Emulator, 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.)

Date

History

Reason

July 2008

Added topic.

SP1 feature change.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Code missing on how to initiate Synchronization      NewKiwi   |   Edit   |  

If you read over this Walkthrough it tells you to add a left menu and call it Synchronize, but it never specifies the code to attach to the left menu.

When you click step 7 [Click Synchronize Now] in the Test Application section nothing happens because there is No code behind the button, and so it is not possible to complete this walkthrough.

In addition Step 8 [From the application that is running in Device Emulator, use Server Explorer/Database Explorer ...] is REALLY confusing.

This took me awhile to parse what you meant:

From the development environment that you used to start the Device Emulator (Visual Studio 2008 in this walkthrough), use Server Explorer/Database Explorer or Sql Management Studio or another database management tool, to connect to the Original Northwind database on the development machine (in relation to the OCSDeviceApp on the mobile emulator this is the "remote Data source"

Code Missing for Synchronization      allatthenook   |   Edit   |  

I am also trying to get this walkthrough working, however I am also failing to do this because the code behind the synchronization is missing.
I've tried the following code...


NorthwindCacheSyncAgent syncAgent = new NorthwindCacheSyncAgent();
Microsoft.Synchronization.Data.SyncStatistics syncStats = syncAgent.Synchronize();

However I get the following error message...


System.ArgumentNullException was unhandled
Message="Value can not be null.\r\nParameter name: ServerSyncProvider"

Any help on this would be greatly appreciated.

Flag as ContentBug
Cannot create NorthwindCache.SyncContract.cs      colin158   |   Edit   |  

No matter what I do, after the step "To split synchronization components between the server and client projects", when I check what has been added, according to this walkthrough I should have "NorthwindCache.SyncContract.cs" on the Server side. I do not have this file and cannot proceed any further with the walkthrough - can anyone help me out?

Has anyone successfully completed this walkthrough?

UPDATE: Sorry - an ID10T error I'm afraid - I did not have SP1 installed - installing it enabled the creation of this file!

Tags What's this?: Add a tag
Flag as ContentBug
Walkthrough Completion      robok   |   Edit   |  
There are 2 problems with the Device App in this walkthrough: the missing sync code (as mentioned by NewKiwi and allatthenook), and the missing code to allow bidirectional syncing (without this code the customer insert performed on the device will never be synced to the remote db).

Solution to Problem 1: My C# code for the Sync menu click event looks like this:-

// create SyncAgent with the Web Ref providing the Service proxy...
NorthwindSyncAgent sa = new NorthwindSyncAgent(new NorthwindWebRef.NorthwindSyncService());
// ...then do the sync
sa.Synchronize();

// Reload the DataSet/Datagrid from the local database
this.customersTableAdapter.Fill(this.northwindDataSet.Customers);

[you will need to change the class names I've used to match those used in the walkthrough/your app]

Solution to Problem 2: Replace the existing OnInitialized function in your Sync Agent class with:

private void OnInitialized()
{

// enable bidirectional sync on Customers
// (Possible values are: DownloadOnly (default), Bidrectional, UploadOnly and Snapshot)
this.Customers.SyncDirection =
Microsoft.Synchronization.Data.SyncDirection.Bidirectional;

}

[the sync agent is defined (in the device app) in Northwind.Client.Designer.cs in my solution]


Synchronization Menu Code      Mark Lu MSFT   |   Edit   |  

Guys, I wrote this document. For some reason, the "synchronize now" button code is not showing up on MSDN. I'm working on getting it fixed, but for now, here what you do.

After step 2 in "To create a data-bound form that is used to view data and initiate synchronization". Double click the "synchronize button" to create the button click event a