Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of WCF data instance by server

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "server-side WCF data instance analysis". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

PublicclassMySyncProvider:KnowledgeSyncProvider,IChangeDataRetriever,INotifyingChangeApplierTarget

{

/ / Thenameofthemetadatastorecustomcolumnthatisusedtosaveatimestampoflastchangeonan

/ / iteminthemetadatastoresowecandochangedetection.

ConststringTIMESTAMP_COLUMNNAME= "timestamp"

/ / Thisisoursampleinmemorydatastorewhichforsimplicty,storessetsofstringname-ProcessChangeBatchpairs

/ / referencedbyidentifiersofthetype'Guid'

MySimpleDataStore_store

/ / UsetheSyncFramework'soptionalmetadatastoretotrackversioninformation

SqlMetadataStore_metadataStore=null;// represents a metadata store implemented by using a lightweight database to store metadata.

ReplicaMetadata_metadata=null;// provides access to replica metadata and item metadata in the metadata store. ReplicaMetadata also provides services for deletion detection and helpers for implementing synchronization provider methods

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

Listfields=newList ()

SyncIdid=ReplicaId

Createoropenthemetadatastore,initializingitwiththeidformatswe'llusetoreferenceouritemsandendpoints

If (! File.Exists (_ replicaMetadataFile))

{

Fields.Add (newFieldSchema (TIMESTAMP_COLUMNNAME,typeof (System.UInt64)

/ / create a metadata store file with the specified name and location, and then return the metadata store object that represents the file.

_ metadataStore=SqlMetadataStore.CreateStore (_ replicaMetadataFile)

/ / create and initialize the copy of the metadata in the metadata store and return a copy metadata object that is used to access the copy metadata.

_ metadata=_metadataStore.InitializeReplicaMetadata (ID format schema of the _ idFormats,// provider

ReplicaId,// the copy ID associated with this metadata

Fields,// a collection of schema information for custom metadata fields for each metadata item. If there is no custom metadata field, it can be referenced for null

Null/*Noindexestocreate*/); / / A list of index schemas that can be used to find items in the metadata store more efficiently. If there is no custom index, it can be a null reference

}

Else

{

_ metadataStore=SqlMetadataStore.OpenStore (_ replicaMetadataFile); / / Open an existing metadata store file and return the metadata store object that represents the file

_ metadata=_metadataStore.GetReplicaMetadata (_ idFormats,_replicaId); / / gets the replica metadata object used to access the replica metadata in the metadata store.

}

}

PrivatevoidCloseMetadataStore ()

{

MetadataStore.Dispose ()

MetadataStore=null

}

/ / Updatethemetadatastorewithchangesthathaveoccuredonthedatastoresincethelasttimeitwasupdated.

PublicvoidUpdateMetadataStoreWithLocalChanges ()

{

SyncVersionnewVersion=newSyncVersion (0gramme 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 (); / / start an explicit transaction on the metadata store

Metadata.CleanupDeletedItems (timespan)

MetadataStore.CommitTransaction (); / / commit explicit transactions that have been initiated against the metadata store

CloseMetadataStore ()

}

# endregionMetadataStoreRelatedMethods

# regionKnowledgeSyncProviderOverrides

/ / BeginSessioniscalledatthebeginningofeachsyncoperation. Doinitializationhere. Forexampleupdate

/ / metadataifitwasnotupdatedastheactualdatawaschanged.

PublicoverridevoidBeginSession (SyncProviderPositionposition,SyncSessionContextsyncSessionContext)

{

BeginSession ()

CurrentSessionContext=syncSessionContext

}

/ / EndSessioniscalledafterthesyncoperationiscompleted. Cleanuphappenshere.

PublicoverridevoidEndSession (SyncSessionContextsyncSessionContext)

{

EndSession ()

}

/ / Simplyaskthemetadatastoretocomputemychangebatchforme,providingthebatchsizeandtheknowledgeoftheotherendpoint!

/ / Theengineisaskingforthelistofchangesthatthedestinationproviderdoesnotknowabout.

/ / SyncKnowledge: represents the knowledge that the copy has about its own item store.

/ / all public static (shared in VisualBasic) members of this type are thread safe. The thread safety of any instance member is not guaranteed.

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

}

/ / specify a batchSize of 10 and the corresponding knowledge

PublicoverridevoidGetSyncBatchParameters (outuintbatchSize,outSyncKnowledgeknowledge)

{

BatchSize=10

Knowledge=_metadata.GetKnowledge ()

}

/ / apply modification

PublicoverridevoidProcessChangeBatch (ConflictResolutionPolicyresolutionPolicy,ChangeBatchsourceChanges

ObjectchangeDataRetriever,SyncCallbackssyncCallback,SyncSessionStatisticssessionStatistics)

{

MetadataStore.BeginTransaction ()

Get all local modifications from the original data store

IEnumerablelocalChanges=_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

IEnumerablelocalChanges=_metadata.GetFullEnumerationLocalVersions (sourceChanges)

Createachangeapplierobjecttomakechangeapplicationeasier (maketheenginecallme

WhenitneedsdataandwhenIshouldsavedata)

NotifyingChangeApplierchangeApplier=newNotifyingChangeApplier (_ idFormats)

ChangeApplier.ApplyFullEnumerationChanges (resolutionPolicy,sourceChanges,changeDataRetrieverasIChangeDataRetriever,localChanges,_metadata.GetKnowledge ()

_ metadata.GetForgottenKnowledge (), this,_currentSessionContext,syncCallback)

MetadataStore.CommitTransaction ()

}

This is the end of the content of "server-side WCF data instance analysis". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report