建议翻译
 
其他人的建议:

progress indicator
没有其他建议。
MSDN Magazine > Home > All Issues > 2009 > MSDN Magazine 四月 2009 >  管理您的数据有效地使用访问 Microsoft 同步 Framework
查看内容:  双语对照查看内容: 双语对照
此为机器翻译内容,社区成员可对其进行编辑。我们十分希望您能单击与以下任一句子关联的“编辑”链接,对翻译进行改进。
Sync Up
Manage Your Data Effectively With The Microsoft Sync Framework
James Yip

This article discusses:
  • Microsoft Sync Framework
  • Synchronization Services
  • Metadata storage
  • Schema synchronization
This article uses the following technologies:
ADO.NET, Microsoft Sync Framework, SQL Server
It's never a trivial task to synchronize data between different data stores. Writing your own logic to perform the synchronization is a time-consuming and costly process. But armed with the Microsoft Sync Framework and its constituent APIs, building synchronization logic becomes much simpler. The Microsoft Sync Framework helps you integrate application data from any data store using any protocol over any network.
Together with the Microsoft Sync Framework, Microsoft released Microsoft Synchronization Services for ADO.NET, Synchronization Services for File Systems, and Synchronization Services for FeedSync, all of which enable developers to perform synchronizations for a specific environment, unlike the Microsoft Sync Framework, which is for building synchronization logic within your application.
These Sync Services provide a set of tools to help you synchronize data between two database sources, synchronize files between machines, and synchronize your application with an RSS or ATOM feed. With the help of these services, you can focus more of your effort on your application logic and less on data synchronization.

Usage Scenarios
The Microsoft Sync Framework is useful in a number of scenarios. Let's take a look at some common ones.
Download only Synchronization In this scenario, the client PC will not have rights to determine what to store and how to keep track of the data stored. An example of this would be RSS Sync. The RSS provider determines how the information is available and how frequently it gets updated. The client determines what content is offered and when.
Offline Data Access Often, you'll need to give some Windows applications offline data access so that the application can continue to run properly if the user is not connected to the network. An example is an inventory application. You would want your remote salespeople to be able to enter sales data on their laptops and then later sync with your database.
Peer-to-Peer Data Collaboration Sometimes you'll issue local copies of your database to increase performance on the client. When there are several such local copies floating around, you'll need to update your back-end data repository appropriately so that all changes are accounted for. One typical example of this is a point-of-sale (POS) application. As sales happen, the POS application in each store records the sales transactions and updates the store's inventory. These updates must be reflected in both the central data store and in all the local copies of the database that other shops are using so that salespersons in each shop know the status of the inventory on hand.
These data access scenarios represent the most common uses for Microsoft Sync Framework. Let's now take a look at how it works to solve these offline data access problems.

Behind the Microsoft Sync Framework
The Microsoft Sync Framework uses a session to carry out data synchronization. Within a session, you define a data source, from which the changes originate, and a destination, to which the changes will be replicated. When the synchronization is triggered by a client, the following happens:
  1. A synchronization session is created.
  2. The Sync Framework checks the destination data to see if there have been changes from any other sources committed since the local copy was downloaded.
  3. Any changes found are sent back to the source to have them applied.
  4. The destination will then request that the source send its changes to the destination store.
  5. The source will send out the changes, and they will be applied to the destination data store.
In order for this to work, both source and destination need to maintain some metadata so they can identify the changes that have happened between synchronizations. There are a number of ways to do this, each of which depends on the type of data we are synchronizing.
Depending on the type of application and synchronization you are trying to implement, you may not need to implement custom change tracking because some data does not include ways for tracking changes. But some data, such as files stored in the file system, already contains create and update metadata. Microsoft Sync Framework supports both one-way synchronization and two-way synchronization. Two-way synchronization is actually implemented as two one-way synchronizations between the source and destination.
Microsoft Sync Framework uses the SyncOrchestrator class to manage the data flow between two data sources. You don't need to extend this class in any way unless you want to add custom application logic during the synchronization session.
The direction of the synchronization is controlled by the Direction property of the SyncOrchestrator class. You can choose whether the specific SyncOrchestrator instance is used for performing an upload or download or both synchronizations.
Providers are used to communicate with source and destination data stores. You need to tell SyncOrchestrator which provider is used before you trigger the synchronization. Once you do trigger it, SyncOrchestrator will call methods in the provider to retrieve changes, save them, and resolve conflicts. Figure 1 illustrates how the synchronization works.
Figure 1 The SyncOrchestrator Object

Synchronization Providers
The Microsoft Sync Framework uses a provider to communicate with both the source and the destination. The provider is responsible for communicating with the data source used to store application data in a manner that is compatible with the associated data store. It is also responsible for detecting changes based on information provided by the other side of the sync session, for applying changes received, and for retrieving changes from the data source.
Developing a provider can require significant time and effort. To implement a synchronization provider, you need to implement the KnowledgeSyncProvider abstract class, the IChangeDataRetriever interface, and the INotifyingChangeApplierTarget interface. Within these classes and interfaces, there are a number of events available for implementing the logic for detecting changes and applying them.
You can implement a proxy provider if there is not a direct connection between the client application and the central data stores. The proxy provider receives commands from and relays those commands to other providers in the synchronization session.
Proxy providers are useful in scenarios such as when a client application communicates with a central data store over the Internet. In this case, you might have the client talking to a proxy through HTTPS and then have the proxy talk to SQL Server. This configuration helps to reduce the exposure of internal servers to the Internet but still allows external users to use Sync Framework to synchronize data.
You implement the proxy provider in the same way you implement any other provider. The only difference between the two is that the proxy provider will not be triggered by the client application directly but by another provider.

Metadata Storage Services in the Sync Framework
In some data sources, you cannot store additional information or implement any kind of change tracking. One good example is the Windows file system. In such a case, Microsoft Sync Framework provides a solution where instead of having the developer build a metadata repository, the Sync Framework provides a lightweight data store called Metadata Storage Services.
Stores you create within Metadata Storage Services can contain two types of data, replica-level data and item-level data. They are used to store information regarding a particular destination (a replica) and an item. Each destination needs a replica ID that uniquely identifies the destination.
ReplicaMetadata, ItemMetadata, and MetadataStore are abstract classes that represent replica metadata, item metadata, and a metadata store. You can manipulate your metadata with the help of these classes.
SqlMetadataStore is the concrete implementation of Metadata Storage Services, which comes with Microsoft Sync Framework to help developers manage metadata at replica level. Unfortunately, the Microsoft Sync Framework does not provide an implementation on the item level for metadata support. Instead, you need to create your own implementation of the ItemMetadata class and create MetadataStore objects if want to store item-level metadata. SqlMetadataStore uses SQL Server to store the metadata in a file you define.
To work with SqlMetadataStore, you either open a saved store using the OpenStore method or create a new one using the CreateStore method. Usually, one store is sufficient for one application. But if you like, you can also maintain multiple stores. To retrieve metadata from a store, you will use the GetReplicaMetadata method.
The following shows how to retrieve items from a SqlMetadataStore:
SyncIdFormatGroup idFormat=new SyncIdFormatGroup();
SyncId syncId=new SyncId(1);
SqlMetadataStore metadataStore=SqlMetadataStore.OpenStore(filePath);
ReplicaMetadata item= metadataStore.GetReplicaMetadata(idFormat,syncId);
When using SqlMetadataStore, you need to specify the schema of the data you'll be storing. You can do so by calling the InitializeReplicaMetadata method of the SqlMetadataStore. This method creates and populates the tables to hold information in the underlying SQL database. For example, the following shows how to populate a metadata store with one field:
SyncIdFormatGroup idFormat=new SyncIdFormatGroup();
SyncId syncId=new SyncId(1);
FieldSchema[] fields=new FieldSchema[1];
IndexSchema[] indexes=new IndexSchema[1];
fields[0]=new FieldSchema("LastSync",typeof(string));
indexes[0]=new IndexSchema("LastSync",false);
SqlMetadataStore metadataStore=SqlMetadataStore.CreateStore(filePath);
ReplicaMetadata item= metadataStore.InitializeReplicaMetadata(  idFormat,syncId, fields,indexes );

Sync Services in Action
Now, let's see how you can add synchronization support to your application using Sync Services for ADO.NET. With the help of SQL Server Compact Edition 3.5, you can create a lightweight data store in local file systems. The good thing about SQL Server Compact Edition is that it works like SQL Server but uses a file as the repository, eliminating the need to modify the application to work with a local data store.
Synchronization Services for ADO.NET supports the synchronization of data and schema between SQL Server databases including SQL Server Compact Edition databases. Here, I will show you how to enable an application that uses a central SQL Server database for offline access via a replica maintained in a SQL Server Compact Edition database.
The first thing to do when you want to implement Synchronization Services for ADO.NET is to decide how to track changes in your data. In Synchronization Services for ADO.NET, you can leverage SQL Server 2008's Integrated Change Tracking or you can use custom tracking by managing change tracking yourself in the application database.
Within SQL Server 2008, tables that are enabled for integrated change tracking will log every data change in a change tracking log table and Sync Services will look at this log to identify all changes since the last synchronization. This keeps the developer from having to change the database schema of an existing application.
But sometimes, as is the case for applications using SQL Server 2005, integrated change tracking may not be available. In such cases, you should consider using custom change tracking. The custom change tracking approach identifies the insertion and update of records in a table with the help of columns and identifies deletions with the help of a tombstone table. To help Sync Services identify rows that have been updated or inserted since the last update, you will need to add four columns—Update Originator, Update Time, Create Originator, and Update Time—to each table that you wish to track. You also need to create a table called a tombstone table to keep a log of all rows that are removed. Within the table, you need at least two pieces of information: the time of deletion and the row's original primary key.
The tombstone table is where Sync Services finds entries that must be removed from the destination store because they have been removed from the source. All of this information helps Sync Services to identify the changes since last synchronization.

Synchronizing Data and Schemas
When implementing synchronization between databases, keeping schemas consistent becomes an issue for most applications. As such, Sync Services for ADO.NET also supports synchronizing database schemas. There is a limitation though. Sync Services will create the table in the client database only the first time it performs the sync unless the developer configures it to recreate it every time it synchronizes.
To configure your providers to use Sync Services for ADO.NET, you need to implement the code in the provider to configure the tables to be synchronized and the direction in which you want the synchronization to run. You can choose to synchronize data from the source to the destination, from the destination to the source, or both. You can place the code to configure the synchronization in the constructor of the provider class. You can also separate tables into groups so that you can have more fine-grained control over the individual tables to be synchronized.
With the destination, most of the time you won't really need to explicitly configure the provider because Sync Services for ADO.NET will automatically create the appropriate schemas and load the data. You simply need to specify the location of the destination database. Sync Services for ADO.NET comes with two providers: one is designed to work with SQL Server and one is designed to work with SQL Server Compact Edition. The only real difference is in the underlying library used to communicate with the database engine; the SQL Server provider uses System.Data.SqlClient while the provider for SQL Server Compact Edition uses System.Data.SqlCeClient.
The provider that is used for communicating with SQL Server is called DbServerSyncProvider while the one designed for SQL Server Compact Edition is SqlCeClientSyncProvider. When you are initializing the provider, you will need a SyncAdapter object, which contains the information about how the provider will communicate with the underlying SQL Server database, and the details about change tracking, such as which column is the change originator column, and whether custom SQL change tracking is used. Another important piece of information defined in the SyncAdapter is the direction of the synchronization. Sync Services for ADO.NET provides the ability for developers to define the direction of the synchronization on a per-table basis. Sync Services for ADO.NET comes with a SyncAdapterBuilder that helps you create the required SyncAdapter object and the SQL statements by supplying information such as table name, name of updater column, create originator column, and so on. Figure 2 illustrates how the adapter builder helps you create a SyncAdapter.
sqlSABuilder = new Microsoft.Synchronization.Data.Server.SqlSyncAdapterBuilder(sqlconn);
sqlSABuilder.TableName = "User";
sqlSABuilder.FilterClause = "username='" +   System.Threading.Thread.CurrentPrincipal.Identity.Name + "' ";
sqlSABuilder.TombstoneTableName = "Deleted_"+ sqlSABuilder.TableName;
sqlSABuilder.SyncDirection =   Microsoft.Synchronization.Data.SyncDirection.Bidirectional;
sqlSABuilder.CreationTrackingColumn = "ct";
sqlSABuilder.UpdateTrackingColumn = "ut";
sqlSABuilder.DeletionTrackingColumn = "dt";
sqlSA = sqlSABuilder.ToSyncAdapter(true, true, true, true);
sqlSA.TableName = "User";
destinationProvider.SyncAdapters.Add(sqlSA);
Having said that, most of the time we just need to add logic for populating SyncAdapters on the source provider. You'll need to do both if you are doing a bi-directional synchronization.
To set up database synchronization, create an instance of the SyncAgent object, which is similar to the SyncOrchestrator object I mentioned earlier but designed to carry out synchronization for Sync Services for ADO.NET. Then assign providers to the RemoteProvider and LocalProvider properties of the object. Next, call the Synchronize method of the SyncAgent, which will trigger the synchronization process and call the respective events and methods that are implemented by the providers. The following illustrates how to configure SyncAgent and start synchronization.
SyncAgent syncAgent=new SyncAgent();
syncAgent.LocalProvider = new SqlCeClientSyncProvider ();
syncAgent.RemoteProvider = new DbServerSyncProvider();
syncAgent.Synchronize();
One point to note about Sync Services for ADO.NET is that it's possible to use it with almost any data source supported by ADO.NET, so you're not limited to SQL Server as the source and/or destination database.
Sync Services for ADO.NET uses the SyncTable object to store information about the tables involved in the synchronization. The following code demonstrates how to populate the SyncTable object and configure it with SyncAgent. You can use the SyncGroup class to aggregate SyncTables into a synchronization group that ADO.NET will process as a whole and ensure consistency for all tables in the group.
SyncGroup lookupSyncGroup=new SyncGroup("LookupTables");
SyncTable syncTable = new SyncTable("Customer");
syncTable.CreationOption = syncTable.DropExistingOrCreateNewTable;
syncTable.SyncDirection = syncTable.Bidirectional;
syncTable.SyncGroup = lookupSyncGroup;
syncAgent.Configuration.SyncTables.Add(syncTable);

Implementing Custom Synchronization
What if you want to implement synchronization using your own logic or you want to implement synchronization for data stores that are not supported by the Microsoft Sync Framework? In this case, you need to create your own provider and implement logic for retrieving data from the underlying data store.
To do this, create a class that derives from the abstract class KnowledgeSyncProvider and override the GetChangeBatch method to retrieve the changes. This method is triggered by the SyncOrchestrator object when you initiate the synchronization process. All detected changes are stored in an object called ChangeBatch, which is passed to the ProcessChangeBatch method of the destination provider. The destination provider will process the ChangeBatch object and use its own logic to apply the changes to the destination data store.
The FilterInfo object is used to communicate filtering information between source and destination providers. The source provider is responsible for populating this object and attaching it to the ChangeBatch object. The destination provider can then use it to apply changes to only an appropriate subset of data. Once the custom provider is implemented, you can use it with SyncOrchestrator. Keep in mind, however, that synchronization providers are not thread-safe, so you need to use cloned providers in new threads if you want to have multiple synchronization running under different threads. To do this, create a new provider object and merge it with the existing one by using the Union method. Then configure SyncOrchestrator to use the newly created provider instead of the original one. Otherwise, the synchronization will fail if there is more than one running synchronization session associated with that provider.
Conflict resolution is always problematic when implementing synchronization logic in applications. The Microsoft Sync Framework will determine if there is a conflict on the item using the following logic.
  1. 1.The destination provider determines whether the destination replica's version information for the item is contained in the source replica's knowledge.
  2. 2.If the destination replica's version is not contained in the source replica's knowledge, the object is said to be in conflict.
If the destination version information is not included in the item itself, the Sync Framework will trigger the TryGetDestinationVersion event of the class that implemented the INotifyingChangeApplierTarget interface for each item. You can then add logic in this event to provide the versioning information to the Sync Framework to aid in conflict resolutions.
public bool TryGetDestinationVersion(ItemChange sourceChange, out   ItemChange destinationVersion)
 {
    ...
 }
Microsoft Sync Framework supports some simple conflict resolution by default. You can configure the conflict resolution policy of the provider and the Sync Framework will perform conflict resolution for you. By default, the Sync Framework supports the following five types of conflict resolution policy.
  • Source wins: the source replica always wins if there is a conflict.
  • Destination wins: the destination replica always wins if there is a conflict.
  • Merge: the changes from both source and destination are merged to form a new version of the item, which is then sent to the destination to be applied.
  • Log: conflicts are ignored and the conflicting item information is sent to the SaveConflict event of the class implementing INotifyingChangeApplierTarget.
  • Defer: completely ignore the conflicts and the destination store will not receive information regarding the conflicts.
All of these conflict resolution policies are applicable at item level but only source wins and destination wins apply to session. Sync policy is specified for the provider by setting the ConflictResolutionPolicy property.
destinationProvider.Configuration.ConflictResolutionPolicy =   ConflictResolutionPolicy.DestinationWins;
You can configure the provider to report the progress of the synchronization instead of using the default configuration. By default, the provider will report progress by calling the ProgressChanged event of the associated SyncCallback objects. You can change this behavior by implementing your own progress reporting. To do this, you need to implement events at the item level using the WorkEstimate event of the ItemChange class, or at the Batch level using the BatchWorkEstimate event of the ChangeBatch class. Then within your provider code, you can call the OnProgressChanged method of the provider to report the change whenever you think that is appropriate.

Wrapping Up
The Microsoft Sync Framework is an application programming framework designed to help build synchronization into applications. While the framework itself includes a number of features and libraries that simplify the development work of building synchronization between different data sources, it does not really perform the synchronization: it relies on developers to provide the logic for detecting and applying changes and resolving conflicts.
Sync Services is a set of libraries created to help address the need for synchronization among some commonly used data stores, such as SQL Server, the file system, and RSS. With Sync Services, you do not need to spend time developing the logic for the synchronization; you simply need to adapt the library for your application. The result is fast, easy synchronization. By adapting Microsoft Sync Framework, you can easily bring support of offline data access and collaboration to your own applications.

James Yip MCT, MCITP, MCPD, PMP, is Managing Consultant of Eventus Limited, a Hong Kong–based technologies consulting company. James works as an architect and project manager. He also teaches MOC classes in both Windows Server Systems Administration and .NET development and works as an SME and TR for MOC courses and authors courseware.

同步设置
管理您的数据有效地使用访问 Microsoft 同步 Framework
James Yip

本文讨论:
  • Microsoft 同步框架
  • 同步服务
  • 元数据存储
  • 架构同步
本文涉及以下技术:
ADO.NET,Microsoft Sync Framework,SQL Server
就永远不会将普通任务 同步不同的数据存储之间的数据。 编写您自己的逻辑进行同步将是一个耗时并且成本的过程。 但有与 Microsoft 同步框架和其构成 API,生成同步逻辑变得更加简单。 Microsoft 同步 Framework 帮助您从任何网络上使用任何协议的任何数据存储的应用程序数据集成。
结合在 Microsoft 同步 Framework 与 Microsoft 发布了 Microsoft 同步服务为 ADO.NET、 文件系统的同步服务和同步服务 FeedSync,所有这些使开发人员可以为特定环境与 Microsoft 同步框架是用于构建应用程序中的同步逻辑不同执行同步操作。
这些同步服务提供一组工具,帮助您同步两个数据库源之间的数据、 机器,间同步的文件和与 RSS 或 ATOM 源同步您的应用程序。 这些服务的借助您可以集中在您的应用程序逻辑上您工作的更多和较少的数据同步。

使用情况
Microsoft 同步 Framework 很有用大量的方案。 让我们一下某些常见的。
下载只同步在这种情况下,客户端计算机将不具有确定如何存储以及如何跟踪的存储的数据的权限。 示例将 RSS 同步。 RSS 提供程序确定如何将信息可用和获取更新频率。 客户端确定提供内容和时间。
脱机数据访问通常,需要授予一些 Windows 应用程序脱机数据访问权限,以便应用程序可以继续正常运行,如果用户没有连接到网络。 示例是库存应用程序。 您可能需要能够在其便携式计算机和与您的数据库的稍后同步输入销售数据在远程销售人员。
对等的数据协作有时会发出数据库提高性能,在客户端上的本地副本。 有几个类本地副本周围浮动时, 需要相应地更新您的后端数据存储库,以便所有更改都考虑的。 这一典型示例是销售点 (POS) 应用程序。 为销售发生,POS 应用程序,每个存储区中的将记录销售交易记录,并更新商店的库存。 在集中的数据存储和其他商店正在使用,以便在每个商店的销售人员另一方面知道库存的状态的数据库的所有本地副本中,必须反映这些更新。
这些数据访问方案的 Microsoft 同步 Framework 表示最常见的用途。 让我们现在看一下原理来解决这些脱机的数据访问问题。

隐藏 Microsoft 同步框架
Microsoft 同步框架使用一个会话执行数据同步。 在的会话中您可以定义从其所做的更改来自数据源和目标复制了更改。 同步被触发由客户端时, 将发生以下:
  1. 创建同步会话。
  2. 同步框架检查目标数据,以查看是否存在已提交因为下载本地副本的其他源中的更改。
  3. 找到的任何更改都将将应用它们发送到源。
  4. 目标然后将请求源到目标存储发送它的更改。
  5. 源将发送更改,和在将应用于目标数据存储。
为了为此源和目标需要维护某些元数据,因此它们可以标识的同步之间发生了更改。 有许多种方法可以这样做,每种取决于我们同步的数据的类型。
根据应用程序和要实现的同步类型,不需要实现自定义的更改跟踪因为某些数据不包含修订的方法。 但某些数据,(如在文件系统中存储的文件已经包含创建和更新元数据。 Microsoft 同步框架支持单向同步和双向同步。 双向同步实际实现为两个源和目标之间的单向同步。
Microsoft 同步框架使用 SyncOrchestrator 类来管理两个数据源之间的数据流。 您不必扩展此类以任何方式,除非您要在同步会话过程中添加自定义应用程序逻辑。
同步的方向由 SyncOrchestrator 类的 Direction 属性控制。 您可以选择特定的 SyncOrchestrator 实例是否用于执行的上载或下载或两个同步。
提供程序用于与源和目标数据存储进行通信。 您需要告诉的 SyncOrchestrator 触发同步之前,可以使用的提供程序。 执行触发该,SyncOrchestrator 将提供程序检索更改,并保存其,解决冲突中调用方法。 图 1 显示了同步的工作原理。
图 1 </a0>-SyncOrchestrator 对象

同步提供程序
Microsoft 同步框架使用提供程序与源和目标的通信。 提供程序负责与数据源用于以兼容与关联的数据存储的方式存储应用程序数据通信。 它负责还检测根据提供的另一端的同步会话的信息的更改、 应用更改接收,以及用于从数据源中检索的更改。
开发一个提供程序可能需要大量的时间和精力。 若要实现同步提供程序,需要实现 KnowledgeSyncProvider 抽象类、 在 IChangeDataRetriever 界面和 INotifyingChangeApplierTarget 接口。 这些类和接口中, 有许多的事件可用于实现检测更改并应用其逻辑。
如果没有客户端应用程序和中心数据存储之间的直接连接,您可以实现代理提供程序。 代理提供程序接收命令,并在同步会话中中继到其他提供商的这些命令。
代理服务器提供程序可用于方案如客户端应用程序通过 Internet 与中心数据存储进行通信的时。 在这种情况下您可能会通过 HTTPS 代理服务器与客户端,然后与 SQL Server 代理服务器。 此配置用于减少内部服务器的暴露程度,到 Internet,但是仍然允许外部用户可以使用同步框架来同步数据。
您在相同的方式实现任何提供程序实现代理提供程序。 两者之间唯一的区别是由客户端应用程序直接但另一个提供程序将不会触发代理提供程序。

同步 Framework 中的元数据存储服务
某些数据源中不能存储的附加信息或实现任何类型的更改跟踪。 一个很好的示例是 Windows 文件系统。 在这种情况下,Microsoft 同步框架提供一个解决方案的位置而不是开发人员生成元数据存储库,同步框架提供一个轻量的数据存储区称为元数据存储服务。
存储在元数据存储服务可以创建包含数据、 副本级别数据和项目级别数据的两种的类型。 它们用于存储有关一个特定的目标 (副本) 和项的信息。 每个目标都需要唯一标识目标的一个副本 ID。
ReplicaMetadata、 ItemMetadata,和 MetadataStore 是表示副本元数据、 项元和元数据存储的抽象类。 您可以操作在元数据,这些类的帮助。
SqlMetadataStore 是元数据存储服务,随 Microsoft 同步 Framework,以帮助管理元数据副本级别的开发人员的具体实现。 遗憾的是,Microsoft 同步框架不实现项目级别上的元数据的支持。 相反,您需要创建自己的实现 ItemMetadata 类的并创建 MetadataStore 对象,如果要存储项目级元数据。 SqlMetadataStore 使用 SQL Server 定义的文件中存储元数据。
若要处理 SqlMetadataStore 您,打开保存的存储区使用 OpenStore 方法或者创建使用 CreateStore 方法新建一个。 通常,一个存储是足以使应用程序。 但如果您愿意您还可以维护多个存储。 从存储区检索元数据,您将使用 GetReplicaMetadata 方法。
下面显示如何从一个 SqlMetadataStore 中检索项:
SyncIdFormatGroup idFormat=new SyncIdFormatGroup();
SyncId syncId=new SyncId(1);
SqlMetadataStore metadataStore=SqlMetadataStore.OpenStore(filePath);
ReplicaMetadata item= metadataStore.GetReplicaMetadata(idFormat,syncId);
使用 SqlMetadataStore 时, 需要指定您将存储的数据的架构。 您可以在通过调用在 SqlMetadataStore InitializeReplicaMetadata 方法执行操作。 此方法创建,并填充表基础的 SQL 数据库中保存的信息。 是例如下面的示例显示如何填充有一个字段的元数据存储:
SyncIdFormatGroup idFormat=new SyncIdFormatGroup();
SyncId syncId=new SyncId(1);
FieldSchema[] fields=new FieldSchema[1];
IndexSchema[] indexes=new IndexSchema[1];
fields[0]=new FieldSchema("LastSync",typeof(string));
indexes[0]=new IndexSchema("LastSync",false);
SqlMetadataStore metadataStore=SqlMetadataStore.CreateStore(filePath);
ReplicaMetadata item= metadataStore.InitializeReplicaMetadata(  idFormat,syncId, fields,indexes );

操作中的同步服务
现在,让我们看看如何将同步支持添加到使用同步服务为 ADO.NET 应用程序。 借助 SQL Server 压缩版本 3.5,则可以在本地文件系统来创建轻型的数据存储区。 SQL Server Compact Edition 在好就是它工作方式与 SQL Server 类似,但为该存储库无需修改应用程序使用本地数据存储使用的文件。
同步服务为 ADO.NET 支持数据和架构包括 SQL Server Compact Edition 数据库的 SQL Server 数据库之间的同步。 此处,我将介绍如何启用脱机访问,通过一个 SQL Server Compact Edition 数据库中维护的副本使用中央的 SQL Server 数据库的应用程序。
要实现同步服务为 ADO.NET 时首先是确定如何跟踪数据中的更改。 同步服务为 ADO.NET,您可以利用 SQL Server 2008 集成的更改跟踪,或者通过管理更改跟踪自己在应用数据库中使用自定义跟踪。
SQL Server 2008 中, 启用了集成的更改跟踪的表将登录修订日志表每次数据更改,并同步服务将查看该日志来标识自上次同步以来的所有更改。 这可以防止开发人员不必更改现有的应用程序的数据库架构。
但有时,是使用 SQL Server 2005 应用程序的情况,集成的更改跟踪可能不可用。 在这样的情况下应考虑使用自定义的更改跟踪。 跟踪方法自定义更改标识插入和更新表中的记录的列的帮助,并标识 Tombstone 表的删除。 为了标识已更新或插入自上次更新的行的同步服务需要添加四个列,更新原始发件人、 更新时间、 创建原始发件人,和更新时间,到想要跟踪的每个表。 还需要创建一个名为逻辑删除表格以保留中删除的所有行的日志表。 表中, 您需要至少两个提供条信息: 删除和行的原始主键的时间。
逻辑删除表是在同步服务查找因为它们已经被删除源中必须从目标存储区删除的项。 所有这些信息有助于确定自上次同步以来的更改的同步服务。

同步数据和架构
实现数据库之间同步时, 则保持一致的架构将成为对于大多数应用程序的一个问题。 在这种情况下,同步服务为 ADO.NET 还支持同步数据库架构。 存在但是限制。 同步服务将在开发人员配置以便每次同步时重新创建它,除非执行同步客户端数据库仅第一个时间创建表。
要配置使用同步服务为 ADO.NET 提供程序,您需要实现提供程序配置为在同步表中的代码和要在其中运行同步的方向。 可以从目标源,或同时同步该的目标数据源。 可以将放置代码以提供程序类的构造函数中配置该同步。 以便您可以使具有更多精细控制各个表进行同步,您可以也将分成组表。
与该的目标大多数情况下您不会真正需要显式配置提供程序,因为同步服务为 ADO.NET 将自动创建适当的架构并加载数据。 只需指定目标数据库的位置。 同步服务为 ADO.NET 附带两个提供程序: 一个设计为使用 SQL Server,而其中一个设计用于 SQL Server Compact Edition。 唯一的真正区别与数据库引擎通信时使用的基础库中 ; SQL Server 提供程序使用 System.Data.SqlClient,而提供程序的 SQL Server Compact Edition 使用 System.Data.SqlCeClient。
用于与 SQL Server 通信的提供程序调用 DbServerSyncProvider SqlCeClientSyncProvider 一个适用于 SQL Server Compact Edition 时。 您初始化提供程序时, 需要一个 SyncAdapter 对象,包含有关如何提供程序与通讯在基础的 SQL Server 数据库以及有关更改跟踪详细信息如哪个列是更改原始发件人列和自定义 SQL 更改是否使用跟踪信息。 在 SyncAdapter 中定义的另一个重要部分是信息的同步的方向。 同步服务为 ADO.NET 能够开发人员可以基于每个表定义同步的方向。 同步服务为 ADO.NET 提供与一个 SyncAdapterBuilder,可帮助您通过提供信息如表 name,更新程序列名称创建必需的 SyncAdapter 对象和 SQL 语句创建原始发件人列等等。 图 2 说明了适配器生成器) 如何帮助您创建一个 SyncAdapter。
sqlSABuilder = new Microsoft.Synchronization.Data.Server.SqlSyncAdapterBuilder(sqlconn);
sqlSABuilder.TableName = "User";
sqlSABuilder.FilterClause = "username='" +   System.Threading.Thread.CurrentPrincipal.Identity.Name + "' ";
sqlSABuilder.TombstoneTableName = "Deleted_"+ sqlSABuilder.TableName;
sqlSABuilder.SyncDirection =   Microsoft.Synchronization.Data.SyncDirection.Bidirectional;
sqlSABuilder.CreationTrackingColumn = "ct";
sqlSABuilder.UpdateTrackingColumn = "ut";
sqlSABuilder.DeletionTrackingColumn = "dt";
sqlSA = sqlSABuilder.ToSyncAdapter(true, true, true, true);
sqlSA.TableName = "User";
destinationProvider.SyncAdapters.Add(sqlSA);
具有称为大部分时间我们只需添加填充 SyncAdapters 源提供程序上的逻辑,。 您需要执行两,如果您正在进行双向同步。
若要设置数据库同步,创建 SyncAgent 对象类似于我前面提到,但为了执行的同步服务为 ADO.NET 同步该 SyncOrchestrator 对象的实例。 然后将提供程序分配给对象的该 RemoteProvider 和 LocalProvider 属性中。 接下来,调用在 SyncAgent 它将触发同步过程并调用相应的事件和提供程序实现的方法的同步方法。 下面说明了如何配置 SyncAgent 和启动同步。
SyncAgent syncAgent=new SyncAgent();
syncAgent.LocalProvider = new SqlCeClientSyncProvider ();
syncAgent.RemoteProvider = new DbServerSyncProvider();
syncAgent.Synchronize();
注意有关同步服务为 ADO.NET 的一个点是就可以将其与支持由 ADO.NET,因此不限于与源和/或目标数据库的 SQL Server 几乎任何数据源。
同步服务为 ADO.NET 使用 SyncTable 对象来存储有关表参与同步的信息。 下面的代码演示如何填充 SyncTable 对象,并使用 SyncAgent 对其进行配置。 可以使用聚合 SyncTables SyncGroup 该类到同步组的 ADO.NET 将作为一个整体处理,并确保组中的所有表的一致性。
SyncGroup lookupSyncGroup=new SyncGroup("LookupTables");
SyncTable syncTable = new SyncTable("Customer");
syncTable.CreationOption = syncTable.DropExistingOrCreateNewTable;
syncTable.SyncDirection = syncTable.Bidirectional;
syncTable.SyncGroup = lookupSyncGroup;
syncAgent.Configuration.SyncTables.Add(syncTable);

实现自定义同步
如果您希望实现使用您自己的逻辑,或者您想实现 Microsoft 同步 Framework 不支持的数据存储进行同步? 在这种情况下,您需要创建自己的提供程序,并实现用于从基础数据存储区检索数据的逻辑。
为此,创建一个从抽象类 KnowledgeSyncProvider 派生类,并重写 GetChangeBatch 方法以检索所做的更改。 启动同步进程时,由 SyncOrchestrator 对象触发此方法。 所有检测到更改存储在一个名为传递给目标提供程序的 ProcessChangeBatch 方法的 ChangeBatch 的对象。 目标提供程序将处理 ChangeBatch 对象,并以应用更改到目标数据存储中使用它自己的逻辑。
FilterInfo 对象用于筛选的信息源和目标提供商之间。 源提供程序负责填充该对象并将其附加到 ChangeBatch 对象。 目标提供程序然后可以使用它将更改应用于只的数据的适当子集。 一旦实现自定义提供程序,可以使用它 SyncOrchestrator。 请记住,但是,同步提供程序不是线程安全,因此您需要在新的线程中使用克隆的提供程序,如果您希望运行不同的线程的多个同步。 为此,创建一个新的提供程序对象,并使用 Union 方法与现有一合并它。 然后配置 SyncOrchestrator 而不是原始使用新创建的提供程序。 否则,同步将失败,如果没有与该提供程序的多个运行同步会话中。
在应用程序中实现同步逻辑时,冲突解决方案始终是有问题。 Microsoft 同步框架将确定该项目,使用下面的逻辑中是否有冲突。
  1. 1.the 目标提供程序确定源副本的知识库中是否包含有项目的目标副本的版本信息。
  2. 2.If 目标副本的版本不包含源副本的知识库,该对象就称为处于冲突。
如果在项目本身未包含目标版本信息,同步框架会触发类实现了 INotifyingChangeApplierTarget 接口,每个项目的 TryGetDestinationVersion 事件。 然后,您可以同步框架来帮助冲突解决方案提供版本控制的信息该事件中添加逻辑。
public bool TryGetDestinationVersion(ItemChange sourceChange, out   ItemChange destinationVersion)
 {
    ...
 }
Microsoft 同步 Framework 在默认情况下支持一些简单的冲突解决方案。 您可以配置提供程序的冲突解析策略,并同步框架将为您执行冲突解决方案。 默认情况下, 同步框架支持以下五种类型的冲突解析策略。
  • 源 wins: 源副本始终获胜如果冲突。
  • 目标 wins: 目标副本始终获胜如果冲突。
  • 合并: 更改源和目标合并以构成该项目然后发送应用于到目标的新版本。
  • 日志: 冲突将被忽略,并冲突的项目信息发送到 SaveConflict 事件的类实现 INotifyingChangeApplierTarget。
  • 推迟: 完全忽略冲突,并且目标存储区不会收到有关冲突的信息。
这些冲突解析策略的所有适用项目级别但仅源 wins,目标 wins 适用于会话。 同步策略由设置 ConflictResolutionPolicy 属性指定提供程序。
destinationProvider.Configuration.ConflictResolutionPolicy =   ConflictResolutionPolicy.DestinationWins;
您可以配置提供程序报告而不是使用默认配置同步的进度。 默认,提供程序将通过调用相关的 SyncCallback 对象的 ProgressChanged 事件报告进度。 可以通过实现您自己的进度报告来更改此行为。 要这样做,您需要执行在使用 WorkEstimate 事件在 ItemChange 类的项目级别或批处理级别使用 ChangeBatch 类的 BatchWorkEstimate 事件的事件。 然后在提供程序代码中,您可以调用提供程序报告更改,只要您认为适合的 OnProgressChanged 方法。

向上覆盖
Microsoft 同步 Framework 是一个应用程序编程框架,用于帮助生成到应用程序的同步。 在 Framework 本身包括了许多功能和简化的生成不同的数据源之间的同步开发工作的库,不真正执行同步: 依赖于开发人员提供逻辑检测并应用更改和解决冲突。
同步服务是一组所要帮助解决将需要一些常用的数据之间的同步存储,如为 SQL Server、 文件系统和 RSS 的库。 与同步服务,不必花费时间开发同步逻辑 ; 您只是需要修改您的应用程序库。 结果是快速,轻松同步。 通过调整 Microsoft 同步 Framework,可轻松地将支持脱机的数据访问和协作到您自己的应用程序。

James Yip MCT、 MCITP、 MCPD PMP,就 Eventus 限制,咨询公司在香港 Kong–based 技术的管理顾问。 James 用作架构师和项目经理。 他还在两个 Windows Server 系统管理和.NET 开发讲解 MOC 类,并作为 SME 和 TR 适合 MOC 课程和作者课件。

Page view tracker