本篇內容介紹了“服務端對WCF數據實例分析”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
publicclassMySyncProvider:KnowledgeSyncProvider,IChangeDataRetriever,INotifyingChangeApplierTarget
{
//Thenameofthemetadatastorecustomcolumnthatisusedtosaveatimestampoflastchangeonan
//iteminthemetadatastoresowecandochangedetection.
conststringTIMESTAMP_COLUMNNAME="timestamp";
//Thisisoursampleinmemorydatastorewhichforsimplicty,storessetsofstringname-ProcessChangeBatchpairs
//referencedbyidentifiersofthetype'Guid'
MySimpleDataStore_store;
//UsetheSyncFramework'soptionalmetadatastoretotrackversioninformation
SqlMetadataStore_metadataStore=null;//表示通過使用輕型數據庫存儲元數據來實現的元數據存儲區。
ReplicaMetadata_metadata=null;//提供對元數據存儲區中的副本元數據和項元數據的訪問。ReplicaMetadata還對刪除檢測和用于實現同步提供程序方法的幫助器提供服務
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)));
//創建一個具有指定名稱和位置的元數據存儲區文件,然后返回表示該文件的元數據存儲區對象。
_metadataStore=SqlMetadataStore.CreateStore(_replicaMetadataFile);
//在元數據存儲區創建和初始化副本的元數據,并返回一個用于訪問該副本元數據的副本元數據對象。
_metadata=_metadataStore.InitializeReplicaMetadata(_idFormats,//提供程序的ID格式架構
replicaId,//與此元數據相關聯的副本ID
fields,//每個元數據項的自定義元數據字段的架構信息集合。如果不存在自定義元數據字段,則可為null引用
null/*Noindexestocreate*/);//可用于更有效地查找元數據存儲區中的項的索引架構列表。如果不存在自定義索引,則可以是null引用
}
else
{
_metadataStore=SqlMetadataStore.OpenStore(_replicaMetadataFile);//打開現有的元數據存儲區文件,并返回表示該文件的元數據存儲區對象
_metadata=_metadataStore.GetReplicaMetadata(_idFormats,_replicaId);//獲取用于訪問元數據存儲區中的副本元數據的副本元數據對象。
}
}
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();//對元數據存儲區啟動顯式事務
metadata.CleanupDeletedItems(timespan);
metadataStore.CommitTransaction();//提交已對元數據存儲區啟動的顯式事務
CloseMetadataStore();
}
#endregionMetadataStoreRelatedMethods
#regionKnowledgeSyncProviderOverrides
//BeginSessioniscalledatthebeginningofeachsyncoperation. Doinitializationhere. Forexampleupdate
//metadataifitwasnotupdatedastheactualdatawaschanged.
publicoverridevoidBeginSession(SyncProviderPositionposition,SyncSessionContextsyncSessionContext)
{
BeginSession();
currentSessionContext=syncSessionContext;
}
//EndSessioniscalledafterthesyncoperationiscompleted. Cleanuphappenshere.
publicoverridevoidEndSession(SyncSessionContextsyncSessionContext)
{
EndSession();
}
//Simplyaskthemetadatastoretocomputemychangebatchforme,providingthebatchsizeandtheknowledgeoftheotherendpoint!
//Theengineisaskingforthelistofchangesthatthedestinationproviderdoesnotknowabout.
//SyncKnowledge:表示副本所具有的有關自己項存儲區的知識。
//此類型的所有公共靜態(在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();
從原數據存儲中獲得取得本地所有修改
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();
}
“服務端對WCF數據實例分析”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。