技术开发 频道

SQL Server 2008构建偶尔连接系统

向现有的数据服务添加同步服务操作

1. 在“Solution Explorer”中双击 CustomersCache.Server.SyncContract 文件以将其打开。
2. 将类名从“CustomersCacheSyncService”更改为“Service1”。下面的代码示例演示在更改了类名后应当显示的类声明。(C# 用户还必须更改构造函数的名称。)

public partial class Service1 : object, ICustomersCacheSyncContract
{...

3. 对于 C# 用户:
4. 在 Service1.cs 文件中将 Service1 的类声明更改为一个分部类,以使声明类似于以下内容:

public partial class Service1 : object, ICustomersCacheSyncContract {

private CustomersCacheServerSyncProvider _serverSyncProvider;

public Service1()
{...

5. 在“Build”菜单上单击“Build Solution”。

更新服务引用

由于向现有服务添加了同步操作,因此必须更新 PresentationTier 项目中的服务引用。

1. 在“Solution Explorer”中找到 PresentationTier 项目中的“ServiceReference1”。
2. 右击“ServiceReference1”,再单击“更新服务引用”。

修改用于从本地缓存加载客户数据的窗体

当前表示层中的窗体从数据服务来获取其数据。因此,必须修改代码,以从 SQL Server Compact 3.5 数据库中 Customers 表的本地副本加载数据。Orders 表则仍用从 DataService 返回的数据进行加载。

1. 在代码编辑器中打开 Form1。
2. 用下面的代码替换现有的 Form1_Load 代码:

using (ServiceReference1.Service1Client DataSvc = new ServiceReference1.Service1Client())
{
    LocalNorthwindCustomersTableAdapters.CustomersTableAdapter customersTableAdapter
      
= new LocalNorthwindCustomersTableAdapters.CustomersTableAdapter();
    northwindDataSet.Customers.Merge(customersTableAdapter.GetData());
    northwindDataSet.Orders.Merge(DataSvc.GetOrders());
}

测试应用程序

运行该应用程序。从本地数据库缓存和数据服务检索数据。

1. 按 F5。
2. Customers 表中的数据从本地数据库进行检索,Orders 表中的数据从数据服务进行检索。
3. 关闭窗体。

在本地数据库缓存和远程数据库之间同步数据

现在表示层已设置就绪,可以从正确的源显示表,下一步是添加代码来启动同步。将在窗体中添加一个按钮来启动同步进程。

1. 在设计视图中打开“Form1”。
2. 在窗体上单击 Toolstrip,并在 Toolstrip 中添加一个按钮。
3. 将该按钮命名为“SyncButton”。
4. 双击 SyncButton 以创建一个 SyncButton_Click 事件处理程序。
5. 下面的代码示例用于启动同步进程。将其添加到事件处理程序。

CustomersCacheSyncAgent syncAgent = new CustomersCacheSyncAgent();
using (ServiceReference1.CustomersCacheSyncContractClient syncClient = new ServiceReference1.CustomersCacheSyncContractClient())
{
    syncAgent.RemoteProvider
= new Microsoft.Synchronization.Data.ServerSyncProviderProxy(syncClient);
    Microsoft.Synchronization.Data.SyncStatistics syncStats
= syncAgent.Synchronize();
    northwindDataSet.Customers.Merge(
new LocalNorthwindCustomersTableAdapters.CustomersTableAdapter().GetData());

    
string syncSummary = "Total changes downloaded: " +
    syncStats.TotalChangesDownloaded.ToString()
+ Environment.NewLine +
    
"Last successful synchronization: " +
     syncStats.SyncCompleteTime.ToString();
    MessageBox.Show(syncSummary);
}

6. Customers 表中的数据从本地数据库进行检索,Orders 表中的数据从数据服务进行检索。
7. 关闭窗体。

测试应用程序

1. 按 F5。
2. 运行应用程序时,使用“Server Explorer/Database Connections”(或其他数据库管理工具)连接到远程服务器数据库并修改某些记录。
3. 在“Server Explorer/Database Connections”中,查找远程数据库服务器(不是到 Northwind.sdf 的连接)上的 Customers 表。
4. 右击 Customers 表,然后单击“Show Table Data”。
5. 修改一条或多条记录,然后提交更改。(导航关闭已修改的行。)
6. 返回到窗体,然后单击“SyncButton”。
7. 验证对远程数据库的修改是否已同步到本地数据库并显示在网格中。
8. 关闭窗体。(停止调试。)
 

0
相关文章