Beispiel #1
0
        public void SyncFileSystemReplicasOneWay(
            SyncId sourceReplicaId,
            SyncId destinationReplicaId,
            string sourceReplicaRootPath,
            string destinationReplicaRootPath,
            FileSyncScopeFilter filter,
            FileSyncOptions options)
        {
            using (var sourceProvider = createFileSyncProvider(
                sourceReplicaId.GetGuidId(),
                sourceReplicaRootPath,
                filter,
                options))
            using (var destinationProvider = createFileSyncProvider(
                destinationReplicaId.GetGuidId(),
                destinationReplicaRootPath,
                filter,
                options))
            {
                destinationProvider.AppliedChange += destinationProvider_AppliedChange;
                destinationProvider.SkippedChange += destinationProvider_SkippedChange;

                sourceProvider.DetectChanges();
                destinationProvider.DetectChanges();

                synchronizeProviders(destinationProvider, sourceProvider);
            }
        }
Beispiel #2
0
 public void DetectChangesOnFileSystemReplica(
     SyncId replicaId,
     string replicaRootPath,
     FileSyncScopeFilter filter,
     FileSyncOptions options)
 {
     using (var provider = createFileSyncProvider(replicaId.GetGuidId(), replicaRootPath, filter, options))
         provider.DetectChanges();
 }
Beispiel #3
0
 /// <summary>
 /// Создает хранилище метаданных реплики
 /// </summary>
 /// <param name="replicaId">The replica id.</param>
 /// <param name="idFormats">The id formats.</param>
 /// <returns></returns>
 public static SyncMetadataStore CreateStore(SyncId replicaId, int principalId)
 {
     SyncMetadataStore retVal = null;
     ReplicaMetadataAdaptor replica = ReplicaMetadataAdaptor.CreateInstance(replicaId, StaticIdFormats);
     if (replica != null)
     {
         replica.PrincipalId = principalId;
         replica.Save();
     }
     retVal = OpenStore(replicaId);
     return retVal;
 }
Beispiel #4
0
        public static void DetectChangesOnFileSystemReplica(
            SyncId syncid, string replicaRootPath,
            FileSyncScopeFilter filter, FileSyncOptions options,
            DirectoryInfo syncDir,
            string metadataName)
        {
            FileSyncProvider provider = null;

            try
            {
                provider = new FileSyncProvider(
                    syncid.GetGuidId(), replicaRootPath, filter, options, syncDir.FullName, metadataName, syncDir.FullName, null);
                provider.DetectChanges();
            }
            finally
            {
                // Release resources
                if (provider != null)
                    provider.Dispose();
            }
        }
 public static StreamKey FromSyncId <T>(string sourceId, SyncId id) where T : ISyncModel
 {
     return(new StreamKey(sourceId, PersistentKey.GetKey <T>(id)));
 }
Beispiel #6
0
        public static void SyncFileSystemReplicasOneWay(
            SyncId sourceId, SyncId destId,
            string sourceReplicaRootPath, string destinationReplicaRootPath,
            DirectoryInfo syncDir,
            string sourceMetadata, string targetMetadata,
            FileSyncScopeFilter filter, FileSyncOptions options)
        {
            FileSyncProvider sourceProvider = null;
            FileSyncProvider destinationProvider = null;

            try
            {
                sourceProvider = new FileSyncProvider(
                    sourceId.GetGuidId(), sourceReplicaRootPath, filter, options, syncDir.FullName, sourceMetadata, syncDir.FullName,
                    null);
                destinationProvider = new FileSyncProvider(
                    destId.GetGuidId(), destinationReplicaRootPath, filter, options, syncDir.FullName, targetMetadata, syncDir.FullName,
                    null);

                destinationProvider.AppliedChange += OnAppliedChange;
                destinationProvider.SkippedChange += OnSkippedChange;

                SyncOrchestrator agent = new SyncOrchestrator
                {
                    LocalProvider = sourceProvider,
                    RemoteProvider = destinationProvider,
                    Direction = SyncDirectionOrder.Upload
                };
                // Sync source to destination

                //Console.WriteLine("Synchronizing changes to replica: " +
                //   destinationProvider.RootDirectoryPath);
                agent.Synchronize();
            }
            finally
            {
                // Release resources
                if (sourceProvider != null) sourceProvider.Dispose();
                if (destinationProvider != null) destinationProvider.Dispose();
            }
        }
 public BatchRange( BatchRange src ) 
 {
     TableName = src.TableName;
     Start     = src.Start;
     End       = src.End;
 }
Beispiel #8
0
        public void Load()
        {
            string syncFile = Path.Combine(folderPath, "file.sync");

            if (File.Exists(syncFile))
            {
                using (FileStream stream = new FileStream(syncFile, FileMode.Open))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    replicaId = (SyncId)bf.Deserialize(stream);
                    tickCount = (ulong)bf.Deserialize(stream);
                    myKnowledge = (SyncKnowledge)bf.Deserialize(stream);
                    if (myKnowledge.ReplicaId != ReplicaId)
                        throw new Exception("Replica id of loaded knowledge doesn't match replica id provided in constructor.");
                    myForgottenKnowledge = (ForgottenKnowledge)bf.Deserialize(stream);
                    if (myForgottenKnowledge.ReplicaId != ReplicaId)
                        throw new Exception("Replica id of loaded forgotten knowledge doesn't match replica id provided in constructor.");

                    System.Diagnostics.Debug.WriteLine("    ### Loaded For: " + folderPath + "  # Now Load metadatastore");
                    metadataStore.Load(stream);

                    System.Diagnostics.Debug.WriteLine("    ### End load Knowledge ###");
                }
                FindLocalFileChanges(folderPath);
            }
            else
            {
                replicaId = new SyncId(Guid.NewGuid());
                myKnowledge = new SyncKnowledge(IdFormats, ReplicaId, tickCount);
                myForgottenKnowledge = new ForgottenKnowledge(IdFormats, myKnowledge);
            }
        }
 private void PopulateClientScopeNameAndSyncId(SyncBlob incomingBlob)
 {
     _clientScopeName = String.Format("{0}_{1}", _scopeName, incomingBlob.ClientScopeName);
     _clientSyncId = new SyncId(new Guid(incomingBlob.ClientScopeName));
 }
Beispiel #10
0
        /// <summary>
        /// This adds a SyncId as the maximum SyncId for the current table.
        /// </summary>
        /// <param name="tableName"> The name of the table which holds
        /// the SyncId</param>
        /// <param name="maxSyncIdInCurrentTable"> The new end SyncId</param>
        public void AddSyncId( string tableName, SyncId maxSyncIdInCurrentTable )
        {
            Debug.Assert( _inProgressRS != null );

            string currentTableName = _inProgressRS.Last.TableName;

            if( !currentTableName.Equals( tableName ) ) {

                throw new DbSyncException("InteralBatchRangeSetError");
            }

            Debug.Assert( maxSyncIdInCurrentTable > _tableRanges[currentTableName].Start );
            Debug.Assert( maxSyncIdInCurrentTable < _tableRanges[currentTableName].End );
            Debug.Assert( maxSyncIdInCurrentTable > _inProgressRS.Last.End );
            // Set this SyncId as the max in the current range
            _inProgressRS.Last.End = maxSyncIdInCurrentTable;
        }
Beispiel #11
0
 //This is only called when the engine has detected that the destination is out of date due to Tombstone cleanup.
 public override FullEnumerationChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval, out object changeDataRetriever)
 {
     if(!_fullEnumFirstCall)
     {
         _syncItemCount = (uint)_store.Ids.Count;
         _fullEnumFirstCall = true;
     }
     FullEnumerationChangeBatch batch = _metadata.GetFullEnumerationChangeBatch(batchSize, lowerEnumerationBound, knowledgeForDataRetrieval);
     changeDataRetriever = this; //this is where the transfer mechanism/protocol would go. For an in memory provider, this is sufficient
     uint changesCount = 0;
     foreach (ItemChange itemChange in batch)
     {
         changesCount++;
     }
     batch.RemainingSessionWorkEstimate = _syncItemCount;
     batch.BatchWorkEstimate =  batch.IsLastBatch ? changesCount : batchSize;
     _syncItemCount = batch.IsLastBatch ? 0 : _syncItemCount - batchSize;
     return batch;
 }
 public ItemMetadataAdaptor FindItemMetadataById(SyncId globalId)
 {
     return(ItemMetadataAdaptor.FindMetadataItemById(ReplicaId, globalId));
 }
Beispiel #13
0
        /// <summary>
        /// When overridden in a derived class, gets a change batch that contains item metadata for items that have IDs greater than the specified lower bound, as part of a full enumeration.
        /// </summary>
        /// <param name="batchSize">The number of changes to include in the change batch.</param>
        /// <param name="lowerEnumerationBound">The lower bound for item IDs. This method returns changes that have IDs greater than or equal to this ID value.</param>
        /// <param name="knowledgeForDataRetrieval">If an item change is contained in this knowledge object, data for that item already exists on the destination replica.</param>
        /// <param name="changeDataRetriever">Returns an object that can be used to retrieve change data. It can be an <see cref="T:Microsoft.Synchronization.IChangeDataRetriever"/> object or a be provider-specific object.</param>
        /// <returns>
        /// A change batch that contains item metadata for items that have IDs greater than the specified lower bound, as part of a full enumeration.
        /// </returns>
        public override FullEnumerationChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval, out object changeDataRetriever)
        {
            byte[] rawLowerEnumBound            = lowerEnumerationBound.RawId;
            byte[] rawKnowledgeForDataRetrieval = knowledgeForDataRetrieval.Serialize();
            byte[] rawChangeDataRetriever;
            byte[] rawFullEnumerationChangeBatch =
                _syncService.GetFullEnumerationChangeBatch(batchSize,
                                                           rawLowerEnumBound,
                                                           rawKnowledgeForDataRetrieval,
                                                           out rawChangeDataRetriever);
            CachedChangeDataRetriever cachedRetriever =
                SerializerHelper.BinaryDeserialize <CachedChangeDataRetriever>(rawChangeDataRetriever);

            changeDataRetriever = cachedRetriever;
            return(FullEnumerationChangeBatch.Deserialize(IdFormats, rawFullEnumerationChangeBatch));
        }
Beispiel #14
0
 public override int GetHashCode() => SyncId.GetHashCode(StringComparison.InvariantCulture);
Beispiel #15
0
        public void DeleteFile(string folderPath, SyncId itemID, string[] filters)
        {
            SyncDetails sync = new SyncDetails(folderPath, filters);

            sync.DeleteItem(itemID);
        }
        //This is only called when the engine has detected that the destination is out of date due to Tombstone cleanup.
        public override FullEnumerationChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval, out object changeDataRetriever)
        {
            FullEnumerationChangeBatch batch = _metadata.GetFullEnumerationChangeBatch(batchSize, lowerEnumerationBound, knowledgeForDataRetrieval);

            changeDataRetriever = this; //this is where the transfer mechanism/protocol would go. For an in memory provider, this is sufficient
            return(batch);
        }
Beispiel #17
0
 public MarkerGraphicProperty(IMarker marker)
 {
     Id = marker.Id;
 }
        public byte[] GetFullEnumerationChangeBatch(uint batchSize, byte[] lowerEnumerationBoundRaw,
																 byte[] rawKnowledgeForDataRetrieval,
																 out byte[] changeDataRetriever)
        {
            GenericRemoteSyncProvider<EntityObjectHierarchy> provider = GetSessionProvider();
            byte[] retVal = null;
            try
            {
                SyncKnowledge knowledgeForDataRetrieval = SyncKnowledge.Deserialize(provider.IdFormats,
                                                                                    rawKnowledgeForDataRetrieval);
                SyncId lowerEnumerationBound = new SyncId(lowerEnumerationBoundRaw, false);
                object dataRetriever;
                FullEnumerationChangeBatch changeBatch = provider.GetFullEnumerationChangeBatch(batchSize,
                                                                                                lowerEnumerationBound,
                                                                                                knowledgeForDataRetrieval,
                                                                                                out dataRetriever);
                CachedChangeDataRetriever cachedChangeDataRetriever =
                                                new CachedChangeDataRetriever(dataRetriever as IChangeDataRetriever, changeBatch);
                changeDataRetriever = SerializerHelper.BinarySerialize(cachedChangeDataRetriever);
                retVal = changeBatch.Serialize();
            }
            catch (SyncException e)
            {
                throw SoapErrorCreator.RaiseException(HttpContext.Current.Request.Url.ToString(),
                                                  new SyncronizationServiceError(SyncronizationServiceError.eServiceErrorType.SyncFramework, e),
                                                  true);
            }
            catch (Exception e)
            {
                throw SoapErrorCreator.RaiseException(HttpContext.Current.Request.Url.ToString(),
                                                  new SyncronizationServiceError(SyncronizationServiceError.eServiceErrorType.SyncProvider, e),
                                                  true);
            }

            return retVal;
        }
Beispiel #19
0
 public void SaveConstraintConflict(ItemChange conflictingChange, SyncId conflictingItemId, ConstraintConflictReason reason, object conflictingChangeData, SyncKnowledge conflictingChangeKnowledge, bool temporary)
 {
     throw new NotImplementedException();
 }
        private static SyncId GetReplicaIdFromFile(
            string replicaIdFile
            )
        {
            SyncId replicaId;

            if (System.IO.File.Exists(replicaIdFile))
            {
                replicaId = ReadReplicaIdFromFile(replicaIdFile);
            }
            else
            {
                // Create the replica id and save it.
                replicaId = new SyncId(Guid.NewGuid());
                WriteReplicaIdToFile(replicaIdFile, replicaId);
            }

            return replicaId;
        }
Beispiel #21
0
 private SyncId createNewReplicaId(string idFilePath)
 {
     SyncId replicaId;
     using (var idFile = File.Open(
         idFilePath,
         FileMode.OpenOrCreate,
         FileAccess.ReadWrite))
     using (var sw = new StreamWriter(idFile))
     {
         replicaId = new SyncId(Guid.NewGuid());
         sw.WriteLine(replicaId.GetGuidId().ToString("D"));
     }
     return replicaId;
 }
Beispiel #22
0
 private CalendarEventSyncProvider(SyncId replicaId)
 {
     _replicaId = replicaId;
 }
Beispiel #23
0
        private SyncId createReplicaId(string idFilePath)
        {
            SyncId replicaId = null;

            if (File.Exists(idFilePath))
            {
                using (var sr = File.OpenText(idFilePath))
                {
                    var strGuid = sr.ReadLine();
                    if (!string.IsNullOrEmpty(strGuid))
                        replicaId = new SyncId(new Guid(strGuid));
                }
            }
            return replicaId;
        }
Beispiel #24
0
        /// <summary>
        /// Creates syncid plus one. This method matches the method in
        /// ./sync/src/xproc/knowledge/SyncId.cpp -> SyncId::InitializeByIncrement()
        /// </summary>
        /// <param name="idFormat"> 
        /// The item id format information.
        /// </param>
        /// <param name="origId"> 
        /// The SyncId that we want the "plus one" for.
        /// </param>
        static public SyncId IdPlusOne( SyncIdFormat idFormat, SyncId origId )
        {
            Debug.Assert( origId.IsVariableLength == idFormat.IsVariableLength );

            byte[] origBytes = origId.RawId;
            int idSize; 
            byte[] idBytes;

            // first figure out what the length of the new id should
            // be in bytes.
            if (!idFormat.IsVariableLength)
            {
                idSize = origBytes.Length;
            }
            else if (origBytes.Length < idFormat.Length)
            {
                // we'll just append a 0 in this case
                idSize = origBytes.Length + 1;
            }
            else
            {
                // if 0xFF at the end will turn into 0s; we'll want to drop them
                for (idSize = origBytes.Length; 
                     0xFF == origBytes[idSize - 1]; 
                     --idSize);
            }

            idBytes = new byte[idSize];
            Array.Copy(origBytes, 
                       idBytes, 
                       Math.Min( origBytes.Length, idBytes.Length));
            
            if (idFormat.IsVariableLength)
            {
                if (origBytes.Length < idFormat.Length)
                {
                    // just append 0
                    idBytes[idSize - 1] = 0;
                }
                else
                {
                    idBytes[idSize - 1] += 1;
                }
            }
            else 
            {
                // if we are fixed length
                // increment LSB and carry if needed
                for( int cur_index = idSize-1; ;cur_index -= 1 ) 
                {
                    if( idBytes[cur_index] == 0xFF ) 
                    {
                        idBytes[cur_index] = 0;
                    } else {
                        idBytes[cur_index] += 1;
                        break;
                    }
                }
            }
            return new SyncId( idBytes, idFormat.IsVariableLength );
        }
Beispiel #25
0
 /// <summary>
 /// Возвращает признак того что указанная реплика находится в стадии синхронизации
 /// </summary>
 /// <param name="replicaId">The replica id.</param>
 /// <returns></returns>
 public static bool SyncSessionInProcess(SyncId replicaId)
 {
     return(_syncPool.Contains(replicaId));
 }
Beispiel #26
0
 public void DeleteItem(SyncId itemID)
 {
     ItemMetadata item;
     if (metadataStore.TryGetItem(itemID, out item))
     {
         item.IsTombstone = true;
     }
 }
Beispiel #27
0
        public override ReplicaMetadata GetReplicaMetadata(SyncIdFormatGroup idFormats, SyncId replicaId)
        {
            SyncReplicaMetadata retVal = new SyncReplicaMetadata(idFormats, replicaId, _replicaMetaData);

            return retVal;
        }
 public override FullEnumerationChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval, out object changeDataRetriever)
 {
     FullEnumerationChangeBatch batch = _metadataStore.Metadata.GetFullEnumerationChangeBatch(batchSize, lowerEnumerationBound, knowledgeForDataRetrieval);
     changeDataRetriever = _changeApplier;
     return batch;
 }
Beispiel #29
0
 public override void RemoveReplicaMetadata(SyncIdFormatGroup idFormats, SyncId replicaId)
 {
     throw new NotImplementedException();
 }
Beispiel #30
0
 private static SyncId GetSyncId(string syncFilePath)
 {
     Guid guid;
     SyncId replicaId;
     if (!File.Exists(syncFilePath)) //The ID file doesn't exist.
         //Create the file and store the guid which is used to
         //instantiate the instance of the SyncId.
     {
         guid = Guid.NewGuid();
         replicaId = new SyncId(guid);
         FileStream fs = File.Open(syncFilePath, FileMode.Create);
         StreamWriter sw = new StreamWriter(fs);
         sw.WriteLine(guid.ToString());
         sw.Close();
         fs.Close();
     }
     else
     {
         FileStream fs = File.Open(syncFilePath, FileMode.Open);
         StreamReader sr = new StreamReader(fs);
         string guidString = sr.ReadLine();
         guid = new Guid(guidString);
         replicaId = new SyncId(guid);
         sr.Close();
         fs.Close();
     }
     return (replicaId);
 }
 public void DetectChangesOnFileSystemReplica(SyncId replicaId, string replicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options)
 {
     throw new System.NotImplementedException();
 }
Beispiel #32
0
        /// <summary>
        /// Возвращает только кешированные хранилища метаданнх для определенной реплики 
        /// </summary>
        /// <param name="replicaId">The replica id.</param>
        /// <returns></returns>
        public static SyncMetadataStore OpenStore(SyncId replicaId)
        {
            SyncMetadataStore retVal = null;
            try
            {
                lock (_lock)
                {
                    ReplicaMetadataAdaptor replica;
                    if (!_replicaCache.TryGetValue(replicaId, out replica))
                    {
                        replica = ReplicaMetadataAdaptor.CreateInstance(replicaId);
                        if (replica != null)
                        {
                            _replicaCache.Add(replicaId, replica);
                        }
                    }

                    retVal = new SyncMetadataStore(replica);
                }
            }
            catch (ArgumentException)
            {
            }
            return retVal;
        }
Beispiel #33
0
        protected virtual FileSyncProvider GenerateProvider()
        {
            SyncId syncId = new SyncId(Guid.NewGuid());

            return(new FileSyncProvider(syncId.GetGuidId(), ReplicaRootPath, ScopeFilter, SyncOptions));
        }
Beispiel #34
0
        public override ReplicaMetadata InitializeReplicaMetadata(SyncIdFormatGroup idFormats, SyncId replicaId, IEnumerable<FieldSchema> customItemFieldSchemas,
															  IEnumerable<IndexSchema> customIndexedFieldSchemas)
        {
            if (_replicaMetaData == null)
            {
                throw new NullReferenceException("not initialized");
            }

            return GetReplicaMetadata(idFormats, replicaId);
        }
Beispiel #35
0
 /// <inheritdoc />
 public override FullEnumerationChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval, out object changeDataRetriever)
 {
     // anyone know how to implement ???
     throw new NotImplementedException();
 }
Beispiel #36
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public override ChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval, out ForgottenKnowledge forgottenKnowledge, out object changeDataRetriever)
        {
            throw new NotImplementedException();
        }
Beispiel #37
0
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

        public override void ProcessFullEnumerationChangeBatch(ConflictResolutionPolicy resolutionPolicy, SyncId destinationVersionEnumerationRangeLowerBound, SyncId destinationVersionEnumerationRangeUpperBound, ChangeBatch sourceChanges, ForgottenKnowledge sourceForgottenKnowledge, object changeDataRetriever, SyncCallbacks syncCallback, SyncSessionStatistics sessionStatistics)
        {
            throw new NotImplementedException();
        }
 public void SyncFileSystemReplicasOneWay(SyncId sourceReplicaId, SyncId destinationReplicaId, string sourceReplicaRootPath, string destinationReplicaRootPath, FileSyncScopeFilter filter, FileSyncOptions options)
 {
     throw new System.NotImplementedException();
 }
Beispiel #39
0
        public SharedFoldersDialog(FeatureSharedFolders feature, ZPushAccount account, SyncId initial = null)
        {
            this._account       = account;
            this._folders       = feature.Manage(account);
            this._initialSyncId = initial;

            InitializeComponent();

            // TODO: make a specialised class out of this
            this.kTreeFolders.Images = new OutlookImageList(
                "NewFolder",              // Other
                "JunkEmailMarkAsNotJunk", // Inbox
                "GoDrafts",               // Drafts
                "RecycleBin",             // WasteBasket
                "ReceiveMenu",            // SentMail
                "NewFolder",              // Outbox
                "ShowTaskPage",           // Task
                "ShowAppointmentPage",    // Appointment
                "ShowContactPage",        // Contact
                "NewNote",                // Note
                "ShowJournalPage",        // Journal
                "LastModifiedBy"          // Store

                ).Images;

            // Add the email address to the title
            Text = string.Format(Text, account.Account.SmtpAddress);

            // Set up options
            ShowOptions(new KTreeNode[0]);

            // Set up user selector
            gabLookup.GAB = FeatureGAB.FindGABForAccount(account);
        }
        // GetMetadataStore is called by the framework to get an object that can be used to store sync metadata.
        // This provider will use the Sync Framework built in MetadataStore
        public override MetadataStore GetMetadataStore(
            out SyncId replicaId,
            out System.Globalization.CultureInfo culture
            )
        {
            InitializeMetadataStore();

            replicaId = ReplicaId;
            culture = CultureInfo.CurrentCulture;
            return _metadataStore;
        }
Beispiel #41
0
 public void SaveConstraintConflict(
     ItemChange conflictingChange, 
     SyncId conflictingItemId,
     ConstraintConflictReason reason, 
     object conflictingChangeData,
     SyncKnowledge conflictingChangeKnowledge, 
     bool temporary)
 {
     var i = 1;
     // just to implement the interface
 }
        private static void WriteReplicaIdToFile(
            string file,
            SyncId replicaId
            )
        {
            FileStream fs = new FileStream(file, FileMode.Create);

            // Construct a BinaryFormatter and use it to serialize the data to the stream.
            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(fs, replicaId);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to serialize replica id to file. Reason: " + e.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }
        }
Beispiel #43
0
 public override FullEnumerationChangeBatch GetFullEnumerationChangeBatch(uint batchSize, SyncId lowerEnumerationBound, SyncKnowledge knowledgeForDataRetrieval, out object changeDataRetriever)
 {
     throw new NotImplementedException("The method or operation is not implemented.");
 }
        /// <summary>
        /// Get changes for a client using the knowledge that is passed in.
        /// </summary>
        /// <param name="serverBlob">Client knowledge as byte[]</param>
        /// <returns>Response containing the new knowledge and the list of changes.</returns>
        public GetChangesResponse GetChanges(byte[] serverBlob)
        {
            bool isNewClient = false;
            var response = new GetChangesResponse();

            var syncBlob = new SyncBlob();
            byte[] clientKnowledgeBlob = null;

            // If the incoming knowledge blob is null, then we need to initialize a new scope
            // for this request. 
            if (null == serverBlob || 0 == serverBlob.Length)
            {
                // Create a new Guid and use that as the client Id.
                Guid clientId = Guid.NewGuid();

                _clientScopeName = String.Format(CultureInfo.InvariantCulture, "{0}_{1}", _scopeName, clientId);

                _clientSyncId = new SyncId(clientId);

                CreateNewScopeForClient();

                isNewClient = true;

                syncBlob.ClientScopeName = clientId.ToString();
            }
            else
            {
                SyncBlob incomingBlob = SyncBlob.DeSerialize(serverBlob);

                PopulateClientScopeNameAndSyncId(incomingBlob);

                syncBlob.ClientScopeName = incomingBlob.ClientScopeName;

                clientKnowledgeBlob = incomingBlob.ClientKnowledge;

                if (null != incomingBlob.BatchCode && null != incomingBlob.NextBatch)
                {
                    // This is a batched request, so handle it separately.
                    return GetChanges(incomingBlob.ClientKnowledge, incomingBlob.BatchCode.Value, incomingBlob.NextBatch.Value);
                }
            }

            // Intialize a SqlSyncProvider object.
            _sqlSyncProvider = CreateSqlSyncProviderInstance(_clientScopeName, _serverConnectionString, _configuration.SyncObjectSchema);

            var sessionContext = new SyncSessionContext(_sqlSyncProvider.IdFormats, new SyncCallbacks());

            _sqlSyncProvider.BeginSession(SyncProviderPosition.Remote, sessionContext);

            try
            {
                // Get the SyncKnowledge from the blob. If the blob is null, initialize a default SyncKnowledge object.
                SyncKnowledge clientKnowledge = GetSyncKnowledgeFromBlob(clientKnowledgeBlob);

                DbSyncContext dbSyncContext;

                uint changeBatchSize = (_configuration.IsBatchingEnabled)
                                           ? (uint)_configuration.DownloadBatchSizeInKB
                                           : 0;

                RowSorter rowSorter = null;

                do
                {
                    object changeDataRetriever;

                    // Get the next batch.
                    _sqlSyncProvider.GetChangeBatch(changeBatchSize, clientKnowledge,
                                                    out changeDataRetriever);

                    dbSyncContext = (DbSyncContext)changeDataRetriever;

                    // Only initialize the RowSorter, if the data is batched.
                    if (null == rowSorter && _configuration.IsBatchingEnabled)
                    {
                        // Clone the client knowledge.
                        var clonedClientKnowledge = clientKnowledge.Clone();

                        // Combine with the MadeWithKnowledge of the server.
                        clonedClientKnowledge.Combine(dbSyncContext.MadeWithKnowledge);

                        // Use the new knowledge and get and instance of the RowSorter class.
                        rowSorter = GetRowSorter(clonedClientKnowledge);
                    }

                    // Remove version information from the result dataset.
                    RemoveSyncVersionColumns(dbSyncContext.DataSet);

                    // For a new client, we don't want to send tombstones. This will reduce amount of data
                    // transferred and the client doesn't care about tombstones anyways.
                    if (isNewClient)
                    {
                        RemoveTombstoneRowsFromDataSet(dbSyncContext.DataSet);
                    }

                    // Add the dataset to the row sorter. Only use this if batching is enabled.
                    if (_configuration.IsBatchingEnabled)
                    {
                        rowSorter.AddUnsortedDataSet(dbSyncContext.DataSet);

                        // Delete the batch file generated by the provider, since we have read it.
                        // Otherwise we will keep accumulating files which are not needed.
                        if (!String.IsNullOrEmpty(dbSyncContext.BatchFileName) && File.Exists(dbSyncContext.BatchFileName))
                        {
                            File.Delete(dbSyncContext.BatchFileName);
                        }
                    }

                } while (!dbSyncContext.IsLastBatch && dbSyncContext.IsDataBatched);

                List<IOfflineEntity> entities;

                if (_configuration.IsBatchingEnabled)
                {
                    // If batching is enabled.
                    Batch batch = SaveBatchesAndReturnFirstBatch(rowSorter);

                    if (null == batch)
                    {
                        entities = new List<IOfflineEntity>();
                    }
                    else
                    {
                        // Conver to to entities.
                        entities = _converter.ConvertDataSetToEntities(batch.Data);

                        //Only combine the knowledge of this batch.
                        clientKnowledge.Combine(SyncKnowledge.Deserialize(_sqlSyncProvider.IdFormats,
                                                                          batch.LearnedKnowledge));

                        response.IsLastBatch = batch.IsLastBatch;
                        syncBlob.IsLastBatch = batch.IsLastBatch;

                        if (batch.IsLastBatch)
                        {
                            syncBlob.NextBatch = null;
                            syncBlob.BatchCode = null;
                        }
                        else
                        {
                            syncBlob.NextBatch = batch.NextBatch;
                            syncBlob.BatchCode = batch.BatchCode;
                        }
                    }
                }
                else
                {
                    // No batching.
                    response.IsLastBatch = true;

                    entities = _converter.ConvertDataSetToEntities(dbSyncContext.DataSet);

                    // combine the client and the server knowledge.
                    // the server may have an updated knowledge from the last time the client sync'd.
                    clientKnowledge.Combine(dbSyncContext.MadeWithKnowledge);
                }

                // Save data in the response object.
                syncBlob.ClientKnowledge = clientKnowledge.Serialize();

                response.ServerBlob = syncBlob.Serialize();
                response.EntityList = entities;
            }
            finally
            {
                _sqlSyncProvider.EndSession(sessionContext);
            }

            return response;
        }
        async Task <List <Task <AssetEntry <ISyncModel> > > > DownloadMaterial(string sourceId, SyncId materialId, CancellationToken token)
        {
            var tasks = new List <Task <AssetEntry <ISyncModel> > >();

            var materialTask = DownloadSyncModel <SyncMaterial>(sourceId, materialId, token);

            var materialResult = await materialTask;

            tasks.Add(materialTask);
            DownloadTextures(sourceId, (SyncMaterial)materialResult.asset, ref tasks, token);

            return(tasks);
        }