服務端對WCF數(shù)據(jù)舉例說明
作者:佚名
隨著時代的進步科技的發(fā)展WCF數(shù)據(jù)版本也快速的提升與升級,下面我就對升級前和升級后WCF數(shù)據(jù)做一下自己的解析。希望能夠對大家有幫助
到這里服務端的代碼就全部列舉出來了。當然本文中介紹的是元數(shù)據(jù)同步,而相應的SyncProvider實現(xiàn)是
通過MySimpleSyncProvider.cs文件提供的, #t#
當然為了不讓我的某些錯誤理解影響大家閱讀源碼,這里直接將相應的英文注釋也放在這里?!?SPAN>publicclassMySyncProvider:KnowledgeSyncProvider,IChangeDataRetriever,INotifyingChangeApplierTarget
- {
- //Thenameofthemetadatastorecustomcolumnthatisusedtosaveatimestampoflastchangeonan
- //iteminthemetadatastoresowecandochangedetection.
- conststringTIMESTAMP_COLUMNNAME="timestamp";
- //Thisisoursampleinmemorydatastorewhichforsimplicty,storessetsofstringname-ProcessChangeBatchpairs
- //referencedbyidentifiersofthetype'Guid'
- MySimpleDataStore_store;
- //UsetheSyncFramework'soptionalmetadatastoretotrackversioninformation
- SqlMetadataStore_metadataStore=null;//表示通過使用輕型數(shù)據(jù)庫存儲元數(shù)據(jù)來實現(xiàn)的元數(shù)據(jù)存儲區(qū)。
- ReplicaMetadata_metadata=null;//提供對元數(shù)據(jù)存儲區(qū)中的副本元數(shù)據(jù)和項元數(shù)據(jù)的訪問。ReplicaMetadata還對刪除檢測和用于實現(xiàn)同步提供程序方法的幫助器提供服務
- privatestring_name=null;
- privatestring_folderPath=null;
- privatestring_replicaMetadataFile=null;
- privatestring_replicaIdFile=null;
- //Theprovider'suniqueidentifier
- SyncId_replicaId=null;
- SyncIdFormatGroup_idFormats=null;
- SyncSessionContext_currentSessionContext=null;
- //Constructadatastorebyprovidinganamefortheendpoint(replica)and
- //afiletowhichwe'llpersistthesyncmetadata(file)
- publicMySyncProvider(stringfolderPath,stringname)
- {
- namename=name;
- folderPathfolderPath=folderPath;
- replicaMetadataFile=_folderPath.ToString()+""+_name.ToString()+".Metadata";
- replicaIdFile=_folderPath.ToString()+""+_name.ToString()+".Replicaid";
- SetItemIdFormatandReplicaIdFormatforusingGuidids.
- idFormats=newSyncIdFormatGroup();
- idFormats.ItemIdFormat.IsVariableLength=false;
- idFormats.ItemIdFormat.Length=16;
- idFormats.ReplicaIdFormat.IsVariableLength=false;
- idFormats.ReplicaIdFormat.Length=16;
- }
- publicSyncIdReplicaId
- {
- get
- {
- if(_replicaId==null)
- {
- replicaId=GetReplicaIdFromFile(_replicaIdFile);
- }
- return_replicaId;
- }
- }
- #regionMetadataStoreRelatedMethods
- privatevoidInitializeMetadataStore()
- {
- Valuesforaddingacustomfieldtothemetadatastore
- List<FieldSchema>fields=newList<FieldSchema>();
- SyncIdid=ReplicaId;
- Createoropenthemetadatastore,initializingitwiththeidformatswe'llusetoreferenceouritemsandendpoints
- if(!File.Exists(_replicaMetadataFile))
- {
- fields.Add(newFieldSchema(TIMESTAMP_COLUMNNAME,typeof(System.UInt64)));
- //創(chuàng)建一個具有指定名稱和位置的元數(shù)據(jù)存儲區(qū)文件,然后返回表示該文件的元數(shù)據(jù)存儲區(qū)對象。
- _metadataStore=SqlMetadataStore.CreateStore(_replicaMetadataFile);
- //在元數(shù)據(jù)存儲區(qū)創(chuàng)建和初始化副本的元數(shù)據(jù),并返回一個用于訪問該副本元數(shù)據(jù)的副本元數(shù)據(jù)對象。
- _metadata=_metadataStore.InitializeReplicaMetadata(_idFormats,//提供程序的ID格式架構
- replicaId,//與此元數(shù)據(jù)相關聯(lián)的副本ID
- fields,//每個元數(shù)據(jù)項的自定義元數(shù)據(jù)字段的架構信息集合。如果不存在自定義元數(shù)據(jù)字段,則可為null引用
- null/*Noindexestocreate*/);//可用于更有效地查找元數(shù)據(jù)存儲區(qū)中的項的索引架構列表。如果不存在自定義索引,則可以是null引用
- }
- else
- {
- _metadataStore=SqlMetadataStore.OpenStore(_replicaMetadataFile);//打開現(xiàn)有的元數(shù)據(jù)存儲區(qū)文件,并返回表示該文件的元數(shù)據(jù)存儲區(qū)對象
- _metadata=_metadataStore.GetReplicaMetadata(_idFormats,_replicaId);//獲取用于訪問元數(shù)據(jù)存儲區(qū)中的副本元數(shù)據(jù)的副本元數(shù)據(jù)對象。
- }
- }
- privatevoidCloseMetadataStore()
- {
- metadataStore.Dispose();
- metadataStore=null;
- }
- //Updatethemetadatastorewithchangesthathaveoccuredonthedatastoresincethelasttimeitwasupdated.
- publicvoidUpdateMetadataStoreWithLocalChanges()
- {
- SyncVersionnewVersion=newSyncVersion(0,_metadata.GetNextTickCount());
- metadata.DeleteDetector.MarkAllItemsUnreported();
- foreach(Guididin_store.Ids)
- {
- ItemDatadata=_store.Get(id);
- ItemMetadataitem=null;
- //Lookupanitem'smetadatabyitsID
- item=_metadata.FindItemMetadataById(newSyncId(id));
- if(null==item)
- {
- Newitem,musthavebeencreatedsincethatlasttimethemetadatawasupdated.
- Createtheitemmetadatarequiredforsync(givingitaSyncIDandaversion,definedtobeaDWORDandaULONGLONG
- Forcreates,simplyprovidetherelativereplicaID(0)andthetickcountfortheprovider(everincreasing)
- item=_metadata.CreateItemMetadata(newSyncId(id),newVersion);
- item.ChangeVersion=newVersion;
- SaveItemMetadata(item,data.TimeStamp);
- }
- else
- {
- if(data.TimeStamp>item.GetUInt64Field(TIMESTAMP_COLUMNNAME))//theitemhaschangedsincethelastsyncoperation.
- {
- //ChangedItem,thisitemhaschangedsincethelasttimethemetadatawasupdated.
- //Assignanewversionbysimplystating"who"modifiedthisitem(0=local/me)and"when"(tickcountforthestore)
- item.ChangeVersion=newVersion;
- SaveItemMetadata(item,data.TimeStamp);
- }
- else
- {
- //Unchangeditem,nothinghaschangessojustmarkitaslivesothatthemetadataknowsithasnotbeendeleted.
- _metadata.DeleteDetector.ReportLiveItemById(newSyncId(id));
- }
- }
- }
- Nowgobackthroughtheitemsthatarenolongerinthestoreandmarkthemasdeletedinthemetadata.
- Thissetstheitemasatombstone.
- foreach(ItemMetadataitemin_metadata.DeleteDetector.FindUnreportedItems())
- {
- item.MarkAsDeleted(newVersion);
- SaveItemMetadata(item,0);//settimestampto0fortombstones
- }
- }
- privatevoidSaveItemMetadata(ItemMetadataitem,ulongtimeStamp)
- {
- item.SetCustomField(TIMESTAMP_COLUMNNAME,timeStamp);
- SaveItemMetadata(item);
- }
- privatevoidSaveItemMetadata(ItemMetadataitem)
- {
- metadata.SaveItemMetadata(item);
- }
- //MethodforcleaninguptombstonesolderthanacertainTimeSpan
- publicvoidCleanupTombstones(TimeSpantimespan)
- {
- InitializeMetadataStore();
- metadataStore.BeginTransaction();//對元數(shù)據(jù)存儲區(qū)啟動顯式事務
- metadata.CleanupDeletedItems(timespan);
- metadataStore.CommitTransaction();//提交已對元數(shù)據(jù)存儲區(qū)啟動的顯式事務
- CloseMetadataStore();
- }
- #endregionMetadataStoreRelatedMethods
- #regionKnowledgeSyncProviderOverrides
- //BeginSessioniscalledatthebeginningofeachsyncoperation. Doinitializationhere. Forexampleupdate
- //metadataifitwasnotupdatedastheactualdatawaschanged.
- publicoverridevoidBeginSession(SyncProviderPositionposition,SyncSessionContextsyncSessionContext)
- {
- BeginSession();
- currentSessionContext=syncSessionContext;
- }
- //EndSessioniscalledafterthesyncoperationiscompleted. Cleanuphappenshere.
- publicoverridevoidEndSession(SyncSessionContextsyncSessionContext)
- {
- EndSession();
- }
- //Simplyaskthemetadatastoretocomputemychangebatchforme,providingthebatchsizeandtheknowledgeoftheotherendpoint!
- //Theengineisaskingforthelistofchangesthatthedestinationproviderdoesnotknowabout.
- //SyncKnowledge:表示副本所具有的有關自己項存儲區(qū)的知識。
- //此類型的所有公共靜態(tài)(在VisualBasic中共享)成員都是線程安全的。不保證任何實例成員的線程安全。
- publicoverrideChangeBatchGetChangeBatch(uintbatchSize,SyncKnowledgedestinationKnowledge,outobjectchangeDataRetriever)
- {
- ChangeBatchbatch=_metadata.GetChangeBatch(batchSize,destinationKnowledge);
- changeDataRetriever=this;//thisiswherethetransfermechanism/protocolwouldgo.Foraninmemoryprovider,thisissufficient
- returnbatch;
- }
- //ThisisonlycalledwhentheenginehasdetectedthatthedestinationisoutofdateduetoTombstonecleanup.
- publicoverrideFullEnumerationChangeBatchGetFullEnumerationChangeBatch(uintbatchSize,SyncIdlowerEnumerationBound,SyncKnowledgeknowledgeForDataRetrieval,outobjectchangeDataRetriever)
- {
- FullEnumerationChangeBatchbatch=_metadata.GetFullEnumerationChangeBatch(batchSize,lowerEnumerationBound,knowledgeForDataRetrieval);
- changeDataRetriever=this;//thisiswherethetransfermechanism/protocolwouldgo.Foraninmemoryprovider,thisissufficient
- returnbatch;
- }
- //指定batchSize為10,以及相應的知識
- publicoverridevoidGetSyncBatchParameters(outuintbatchSize,outSyncKnowledgeknowledge)
- {
- batchSize=10;
- knowledge=_metadata.GetKnowledge();
- }
- //應用修改
- publicoverridevoidProcessChangeBatch(ConflictResolutionPolicyresolutionPolicy,ChangeBatchsourceChanges,
- objectchangeDataRetriever,SyncCallbackssyncCallback,SyncSessionStatisticssessionStatistics)
- {
- metadataStore.BeginTransaction();
- 從原數(shù)據(jù)存儲中獲得取得本地所有修改
- IEnumerable<ItemChange>localChanges=_metadata.GetLocalVersions(sourceChanges);
- Createachangeapplierobjecttomakechangeapplicationeasier(maketheenginecallme
- whenitneedsdataandwhenIshouldsavedata)
- NotifyingChangeApplierchangeApplier=newNotifyingChangeApplier(_idFormats);
- changeApplier.ApplyChanges(resolutionPolicy,sourceChanges,changeDataRetrieverasIChangeDataRetriever,localChanges,_metadata.GetKnowledge(),
- _metadata.GetForgottenKnowledge(),this,_currentSessionContext,syncCallback);
- metadataStore.CommitTransaction();
- }
- //Iffullenumerationisneededbecause thisproviderisoutofdateduetotombstonecleanup,thenthismethodwillbecalledbytheengine.
- publicoverridevoidProcessFullEnumerationChangeBatch(ConflictResolutionPolicyresolutionPolicy,FullEnumerationChangeBatchsourceChanges,objectchangeDataRetriever,SyncCallbackssyncCallback,SyncSessionStatisticssessionStatistics)
- {
- metadataStore.BeginTransaction();
- Getallmylocalchangeversionsfromthemetadatastore
- IEnumerable<ItemChange>localChanges=_metadata.GetFullEnumerationLocalVersions(sourceChanges);
- Createachangeapplierobjecttomakechangeapplicationeasier(maketheenginecallme
- whenitneedsdataandwhenIshouldsavedata)
- NotifyingChangeApplierchangeApplier=newNotifyingChangeApplier(_idFormats);
- changeApplier.ApplyFullEnumerationChanges(resolutionPolicy,sourceChanges,changeDataRetrieverasIChangeDataRetriever,localChanges,_metadata.GetKnowledge(),
- _metadata.GetForgottenKnowledge(),this,_currentSessionContext,syncCallback);
- metadataStore.CommitTransaction();
- }
責任編輯:chenqingxiang
來源:
機械工業(yè)出版社