Пример #1
0
        /// <summary>
        /// 建立資料夾、檔案
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="sourcelastrecord"></param>
        void CreateFolderAndFile(SyncFolderInfo folder, DateTime?sourcelastrecord, SyncResult result)
        {
            // 新增資料夾
            if (_destination.CreateFolder(folder.Path))
            {
                result.Folder++; // 若實際有增新資料夾,影響的資料夾+1
            }
            foreach (var file in _source.GetFiles(folder.Path))
            {
                // 檢查上次sync時間是否為null或
                // 檔案是否在上次sync後有修改
                if (!sourcelastrecord.HasValue ||
                    file.UpdateDate > sourcelastrecord.Value)
                {
                    result.File++; // 影響的檔案+1

                    // 新增檔案
                    _destination.CreateFile(
                        folder.Path,
                        file.Name,
                        _source.GetFile(file.Path)
                        );
                }
            }

            folder.Folders.ForEach(o =>
            {
                CreateFolderAndFile(o, sourcelastrecord, result);
            });
        }
Пример #2
0
        private async void btnSync_ClickAsync(object sender, EventArgs e)
        {
            CL_Dialog.PleaseWait.Show("Data syncing...\r\nPlease Wait", ParentForm);

            SyncResult result = await DataSync.HandShakeAsync();

            if (result.Successful)
            {
                var resultSync = await DataSync.RunSyncSystem(DataSync.GetSyncSystemList());

                if (resultSync.Successful)
                {
                    string msg = LoginUser.AddSqlUsers();
                    if (msg != null)
                    {
                        GuiCommon.ShowMessage(msg);
                    }
                }

                GuiCommon.ShowMessage(resultSync.DisplayMessage());
            }
            else
            {
                GuiCommon.ShowMessage(result.DisplayMessage());
            }

            CL_Dialog.PleaseWait.Hide();
        }
Пример #3
0
        static SyncResult SyncData()
        {
            SyncResult syncResult = new SyncResult();

            StringBuilder sb = new StringBuilder();

            sb.AppendLine(new string('*', 30) + "同步结果" + new string('*', 30));                                                                                  //64
            sb.AppendLine("* " + String.Format("{0,-29}", new string(' ', 10) + "表名") + " | " + String.Format("{0,-26}", new string(' ', 10) + "影响行数") + " *"); //61

            Assembly assembly = Assembly.GetExecutingAssembly();

            Type[] types = assembly.GetTypes();
            types = types.Where(t => t.FullName.Contains("SyncData.BLL")).ToArray();

            foreach (Type type in types)
            {
                object     obj   = assembly.CreateInstance(type.FullName);
                IBLL.ISync isync = obj as IBLL.ISync;
                if (isync != null)
                {
                    var data = isync.SyncDataBackResult();
                    sb.AppendLine(data.Message);
                }
            }

            sb.AppendLine(new string('*', 68));

            syncResult.flag    = true;
            syncResult.Message = Environment.NewLine + sb.ToString();
            return(syncResult);
        }
Пример #4
0
        public async Task <SyncResult> Synchronise(PlexMediaContainer libraryContainer, bool fullRefresh, string authToken, string plexUri, string machineIdentifier)
        {
            _logger.LogDebug("Started synchronising Movies");

            var syncResult = new SyncResult();

            var localMediaItems = await _plexService.GetMediaItems(Type);

            var localMediaItemsCount = localMediaItems?.Count ?? 0;

            _logger.LogDebug($"Retrieved '{localMediaItemsCount}' existing media items");

            foreach (var remoteMediaItem in libraryContainer.MediaContainer.Metadata)
            {
                _logger.LogDebug($"Processing rating key '{remoteMediaItem.RatingKey}'");

                var ratingKey = Convert.ToInt32(remoteMediaItem.RatingKey);

                var retrievedItem = await _mediaItemProcessor.GetMediaItem(ratingKey, Type, localMediaItems, authToken, plexUri, machineIdentifier, _plexSettings.PlexMediaItemUriFormat);

                _logger.LogDebug($"Finished processing rating key '{remoteMediaItem.RatingKey}'");

                if (retrievedItem == null)
                {
                    continue;
                }

                _mediaItemProcessor.UpdateResult(syncResult, retrievedItem.IsNew, retrievedItem.MediaItem);
            }

            _logger.LogDebug("Finished synchronising Movies");

            return(syncResult);
        }
        public void SyncProjectsOK()
        {
            List <Project> fakeProjects = ProjectUtility.GetFakeSimpleProjects();

            string content = JsonConvert.SerializeObject(fakeProjects.GetRange(0, 2), new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            });

            Mock <HttpWebRequest> mockWebRequest = FakeWebRequest.CreateRequestWithResponse(content, new Dictionary <string, string> {
                { "SyncTimestamp", "stamp1;projectid=3" }
            });

            mockWebRequest.SetupSet(r => r.Method = "GET").Verifiable();

            SyncResult <Project> result = syncService.SyncProjects(null).GetAwaiter().GetResult();

            UriBuilder uriBuilder = new UriBuilder("https://api.aproplan.com/rest/projectsync");

            string expectedUrl = AproplanApiUtility.BuildRestUrl(mockApi.Object.ApiRootUrl, "projectsync", mockApi.Object.ApiVersion, mockApi.Object.RequesterId);

            Assert.AreEqual(expectedUrl, FakeWebRequest.Instance.UriCalled[0].ToString());
            Assert.AreEqual(2, result.Data.Count);
            Assert.AreEqual(fakeProjects[0].Id, result.Data[0].Id);
            Assert.AreEqual(fakeProjects[1].Id, result.Data[1].Id);
            Assert.AreEqual("stamp1;projectid=3", result.ContinuationToken);
            mockWebRequest.Verify();
        }
        public void SendChangedItemsToRemoteReplica_BothParmsHaveChanges_ChangesAggregated()
        {
            IReplica replica   = new Replica("Test");
            var      testItem1 = new TestItem();
            var      testItem2 = new TestItem();

            var requestSender = Mocking.MockAndBind <ISyncRequestSender <TestItem, Guid> >(_container);
            var repository    = Mocking.MockAndBind <IRepository <TestItem, Guid> >(_container);

            Mock.Arrange(() => repository.Find(testItem2.Id)).Returns(testItem2);
            var syncResult = new SyncResult <TestItem, Guid>(_container)
            {
                ChangesRequest = new List <Guid> {
                    testItem2.Id
                }
            };
            var conflictResolutions =
                new ConflictResolutionsToSend <TestItem, Guid> {
                new Resolution <TestItem, Guid>(replica, testItem1)
            };

            var target = new SendingSynchronizer <TestItem, Guid>(_container);

            target.SendChangedItemsToRemoteReplica(syncResult.ChangesRequest, conflictResolutions);

            Mock.Assert(() => requestSender.SendChangedItems(
                            Arg.Matches <IEnumerable <TestItem> >(items => items.Contains(testItem1) && items.Contains(testItem2))));
        }
        public void SyncNotesOK()
        {
            Guid        projectId = Guid.NewGuid();
            List <Note> fakeNotes = NoteUtility.GetFakeSimpleNotes();

            string content = JsonConvert.SerializeObject(fakeNotes.GetRange(0, 2), new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            });

            Mock <HttpWebRequest> mockWebRequest = FakeWebRequest.CreateRequestWithResponse(content, new Dictionary <string, string> {
                { "SyncTimestamp", "stamp1;noteid=3" }
            });

            mockWebRequest.SetupSet(r => r.Method = "GET").Verifiable();

            SyncResult <Note> result = syncService.SyncNotes(projectId, null).GetAwaiter().GetResult();


            string expectedUrl = AproplanApiUtility.BuildRestUrl(mockApi.Object.ApiRootUrl, "notesync", mockApi.Object.ApiVersion, mockApi.Object.RequesterId);

            expectedUrl += "&projectid=" + projectId;
            Assert.AreEqual(expectedUrl, FakeWebRequest.Instance.UriCalled[0].ToString());
            Assert.AreEqual(2, result.Data.Count);
            Assert.AreEqual(fakeNotes[0].Id, result.Data[0].Id);
            Assert.AreEqual(fakeNotes[1].Id, result.Data[1].Id);
            Assert.AreEqual("stamp1;noteid=3", result.ContinuationToken);
            mockWebRequest.Verify();
        }
        public void GetConflictingItems_ChangesHaveNoConflicts_NoConflictsInSyncResult()
        {
            // Create non conflicting items
            Guid id          = Guid.NewGuid();
            var  serverStamp = new Stamp();
            var  clientStamp = serverStamp.Fork();
            var  serverItem  = new TestItem {
                Id = id, Stamp = serverStamp
            };
            var clientItem = new TestItem {
                Id = id, Stamp = clientStamp
            };

            // Arrange server repository to return server item
            var repository = Mocking.MockAndBind <IRepository <TestItem, Guid> >(_container);

            Mock.Arrange(() => repository.Find(id)).Returns(serverItem);

            // Arrange client sync request
            ISyncRequest <Guid> syncRequest = new SyncRequest <TestItem, Guid> {
                new SyncItem <Guid>(clientItem)
            };

            var target = new SyncResult <TestItem, Guid>(_container);

            target.GetConflictingItems(syncRequest);

            Assert.IsFalse(target.ConflictingItems.Contains(serverItem));
        }
Пример #9
0
        protected async Task <SyncResult <T> > SyncAllEntities <T>(String syncStamp, Guid?projectId = null, int?requestedBlockSize = null, String forcedResourceName = null, SyncBatchCallback <T> callback = null) where T : Entity
        {
            SyncResult <T> allResult = new SyncResult <T>()
            {
                Data = new List <T>()
            };
            bool           breakCall = false;
            SyncResult <T> result    = null;
            string         syncToken = syncStamp;

            while ((result == null || result.Data.Count > 0) && !breakCall)
            {
                result = await SyncEntity <T>(syncToken, projectId, requestedBlockSize, forcedResourceName);

                if (result.Data.Count > 0)
                {
                    allResult.Data.AddRange(result.Data);
                    callback?.Invoke(result, ref breakCall);
                }
                allResult.ContinuationToken = result.ContinuationToken;
                syncToken = allResult.ContinuationToken;
                if (string.IsNullOrEmpty(syncToken))
                {
                    break;
                }
            }
            return(allResult);
        }
Пример #10
0
        /// <summary>
        /// Synchronizes the data asynchronously.
        /// </summary>
        /// <param name="storeId">The store ID.</param>
        /// <param name="syncData">The wine Inventory For Syncs.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task <SyncResult> SyncAsync(string storeId, List <Dictionary <string, object> > syncData)
        {
            List <Dictionary <string, object> > chunckData = new List <Dictionary <string, object> >();
            SyncResult syncResult = new SyncResult();

            for (int i = 0; i < syncData.Count; i++)
            {
                chunckData.Add(syncData[i]);
                if (i % ChunkSize == 0)
                {
                    SyncResult chunkSyncResult = await SyncChunckAsync(storeId, chunckData);

                    syncResult += chunkSyncResult;
                    chunckData.Clear();
                }
            }

            if (chunckData.Count > 0)
            {
                SyncResult chunkSyncResult = await SyncChunckAsync(storeId, chunckData);

                syncResult += chunkSyncResult;
            }

            return(syncResult);
        }
Пример #11
0
        public void SyncServicePullFileTest()
        {
            Device             device             = GetFirstDevice();
            FileListingService fileListingService = new FileListingService(device);

            using (ISyncService sync = device.SyncService)
            {
                String    rfile  = "/sdcard/bootanimations/bootanimation-cm.zip";
                FileEntry rentry = fileListingService.FindFileEntry(rfile);

                String     lpath  = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                String     lfile  = Path.Combine(lpath, LinuxPath.GetFileName(rfile));
                FileInfo   lfi    = new FileInfo(lfile);
                SyncResult result = sync.PullFile(rfile, lfile, new FileSyncProgressMonitor());

                Assert.IsTrue(lfi.Exists);
                Assert.IsTrue(ErrorCodeHelper.RESULT_OK == result.Code, ErrorCodeHelper.ErrorCodeToString(result.Code));
                lfi.Delete();

                result = sync.PullFile(rentry, lfile, new FileSyncProgressMonitor());
                Assert.IsTrue(lfi.Exists);
                Assert.IsTrue(ErrorCodeHelper.RESULT_OK == result.Code, ErrorCodeHelper.ErrorCodeToString(result.Code));
                lfi.Delete();
            }
        }
Пример #12
0
        public SyncErrorResultAction HandleError(SyncResult syncResult)
        {
            if ((syncResult != null) && (syncResult.Operation != SyncOperationType.ConfigureSource))
            {
                if (syncResult.Ignorable == Ignorable.Yes)
                {
                    return(SyncErrorResultAction.Ignore);
                }
                switch (syncResult.ResultCode)
                {
                case 0x800700aa:
                    if (syncResult.Item != null)
                    {
                        return(SyncErrorResultAction.Retry);
                    }
                    return(SyncErrorResultAction.Abort);

                case 0x83002113:
                    if (syncResult.Item != null)
                    {
                        return(SyncErrorResultAction.Pause);
                    }
                    return(SyncErrorResultAction.Abort);
                }
                this.RecordSyncError(syncResult);
            }
            return(SyncErrorResultAction.Ignore);
        }
Пример #13
0
        public static void UpdateState(DateTime date, SyncResult syn)
        {
            string sql = string.Format(@"select objectid from ot_user where ServiceState<>'2'  and State= 1
                                    and   parentid not in ({0}) 
                                    and  code not in({1})  and  ModifiedTime< to_date('{2}',
                        'yyyy-mm-dd hh24:mi:ss')", ExceptOrgIDs, ExceptUserCodes, date);

            OThinker.H3.Controllers.AppUtility.Engine.LogWriter.Write("禁用sql:" + sql);
            DataTable dt = OThinker.H3.Controllers.AppUtility.Engine.EngineConfig.CommandFactory.CreateCommand().ExecuteDataTable(sql);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Unit ur  = OThinker.H3.Controllers.AppUtility.Engine.Organization.GetUnit(dt.Rows[i]["objectid"] + string.Empty);
                User old = ur == null ? null : (User)ur;
                if (old != null)
                {
                    //如果是在职状态,且此时Cap中没有这个用户,执行禁用,加上离职时间
                    if (old.ServiceState == UserServiceState.InService)
                    {
                        old.DepartureDate = DateTime.Now;
                    }
                    old.ServiceState = UserServiceState.Dismissed;
                    old.State        = State.Inactive;
                    UpdateUnit(old, "263禁用", syn);
                }
            }
        }
Пример #14
0
        private async void btnSystemStart_ClickAsync(object sender, EventArgs e)
        {
            if (!HasInternetConnection())
            {
                return;
            }

            CL_Dialog.PleaseWait.Show("Data syncing...\r\nPlease Wait", ParentForm);

            SyncResult result = await DataSync.HandShakeAsync();

            if (result.Successful)
            {
                var resultSync = await DataSync.RunSyncSystem(_systemSyncList);

                if (resultSync.Successful)
                {
                    string msg = LoginUser.AddSqlUsers();
                    if (msg != null)
                    {
                        GuiCommon.ShowMessage(msg);
                    }
                }

                GuiCommon.ShowMessage(resultSync.DisplayMessage());
                AfterSync?.Invoke();
            }
            else
            {
                GuiCommon.ShowMessage(result.DisplayMessage());
            }

            CL_Dialog.PleaseWait.Hide();
        }
Пример #15
0
        private void syncOperationCompleted(SyncResult result)
        {
            lock (stateLock)
            {
                IsRunningSync = false;

                if (result is Success)
                {
                    startSyncIfNeeded();
                    if (IsRunningSync == false)
                    {
                        progress.OnNext(SyncProgress.Synced);
                    }
                    return;
                }

                if (result is Error error)
                {
                    processError(error.Exception);
                    return;
                }

                throw new ArgumentException(nameof(result));
            }
        }
Пример #16
0
        static void TestCon()
        {
            BLL.CommonBLL     bll  = new BLL.CommonBLL();
            Func <SyncResult> func = () =>
            {
                SyncResult r = new SyncResult();
                r.flag = bll.TestCon();
                return(r);
            };

            SyncResult result = new SyncResult();

            while (!result.flag)
            {
                result = ShowDynText("正在测试连接", "连接完成", func);
                if (!result.flag)
                {
                    ShowMessage("连接失败,正在重试");
                    Thread.Sleep(2000);
                }
                else
                {
                    ShowMessage("连接成功");
                }
            }
        }
Пример #17
0
        /// <summary>
        /// Will fire if when the Synchronizer finishes executing a autoFetchAll-job.
        /// When event fires, we'll have to refresh the listbox of documents incase some document was deleted/renamed.
        /// </summary>
        /// <param name="result"></param>
        private void SynchronizerAutoFetchAllEntriesFinished(SyncResult result)
        {
            // refresh the listbox with current item titles
            BrowseRefreshEntriesEventHandler refreshListBoxDelegate = RefreshListBoxItemsFromSelectedFolder;

            Invoke(refreshListBoxDelegate, true);
        }
Пример #18
0
        public Document CreateNewDocument(string folderId, string title, string content, bool createDefaultDirectory)
        {
            try
            {
                return(NocsService.CreateNewDocument(folderId, title, content, createDefaultDirectory));
            }
            catch (Exception ex)
            {
                var result = new SyncResult
                {
                    Job = new SyncJob {
                        Title = title, Type = SyncJobType.Save
                    },
                    ContentUpdated = false,
                    Error          = ex.Message,
                    Document       = new Document {
                        Content = content, Title = title
                    }
                };

                // let's notify listeners
                ErrorWhileSyncing(result);
                return(null);
            }
        }
Пример #19
0
        private void syncOperationCompleted(SyncResult result)
        {
            lock (stateLock)
            {
                analyticsService.SyncCompleted.Track();
                syncTimeStopwatch?.Stop();
                syncTimeStopwatch = null;

                IsRunningSync = false;

                if (result is Success)
                {
                    startSyncIfNeeded();
                    if (IsRunningSync == false)
                    {
                        progress.OnNext(SyncProgress.Synced);
                    }
                    return;
                }

                if (result is Error error)
                {
                    processError(error.Exception);
                    return;
                }

                throw new ArgumentException(nameof(result));
            }
        }
Пример #20
0
        protected SyncResult DownloadAllDataForSync(DateTime lastSyncDate)
        {
            var resultBase = DownloadBaseData();

            var standardSyncItems = Task.Run(() => ConnectorLocator.SyncConnector.GetStandardsSyncData(lastSyncDate, 0, int.MaxValue));
            var topicSyncItems    = Task.Run(() => ConnectorLocator.SyncConnector.GetTopicsSyncData(lastSyncDate, 0, int.MaxValue));
            var syncRes           = new SyncResult(resultBase)
            {
                StandardSyncItems = standardSyncItems.Result,
                TopicSyncItems    = topicSyncItems.Result
            };

            var standardIds    = syncRes.StandardSyncItems.Select(x => x.Id);
            var standardLoader = new LoaderBase <Guid, AcademicBenchmarkConnector.Models.Standard>(standardIds);

            syncRes.Standards = standardLoader.Load(id => Task.Run(() => ConnectorLocator.StandardsConnector.GetStandardById(id)).Result);

            var topicIds    = syncRes.TopicSyncItems.Select(x => x.Id);
            var topicLoader = new LoaderBase <Guid, AcademicBenchmarkConnector.Models.Topic>(topicIds);

            syncRes.Topics = topicLoader.Load(id => Task.Run(() => ConnectorLocator.TopicsConnector.GetTopic(id)).Result);

            Log.LogInfo("Downloaded Standard, Topic sync data");
            return(syncRes);
        }
Пример #21
0
 public void TestCallback()
 {
     SyncResult result;
      Boolean called;
      called = false;
      result = new SyncResult(
     ar =>
     {
        Assert.IsNull(ar.AsyncState);
        Assert.IsTrue(ar.CompletedSynchronously);
        Assert.IsTrue(ar.IsCompleted);
        Assert.IsTrue(ar.AsyncWaitHandle.WaitOne(0));
        called = true;
     },
     null
      );
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(called);
      called = false;
      result = new SyncResult(
     ar =>
     {
        Assert.AreEqual(ar.AsyncState, 1);
        Assert.IsTrue(ar.CompletedSynchronously);
        Assert.IsTrue(ar.IsCompleted);
        Assert.IsTrue(ar.AsyncWaitHandle.WaitOne(0));
        called = true;
     },
     1
      );
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(called);
 }
Пример #22
0
 private void RecordSyncError(SyncResult result)
 {
     lock (this.syncErrors)
     {
         this.syncErrors.Add(result);
     }
 }
Пример #23
0
        /// <summary>
        /// 게이트웨이로 데이터동기화의 동기 처리 결과 메시지 전송.
        /// </summary>
        public bool SendResultOfSASProfileUpdate(uint requestEventID, int updateResult)
        {
            bool result = false;

            try
            {
                SyncResult syncResult = SyncResult.Success;
                if (updateResult != 0)
                {
                    syncResult = SyncResult.Fail;
                }

                SYNCProtocolBase protoBase = IEASProtocolManager.CreateProtocolForSYNC(SYNCCmdValue.SyncResult);
                SYNCPrtCmd13     cmd13     = protoBase as SYNCPrtCmd13;
                cmd13.Result     = syncResult;
                cmd13.Identifier = requestEventID;
                byte[] frameData = IEASProtocolManager.MakeFrameForSYNC(cmd13);

                result = this.sessionManager.SendData(frameData);
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("[CommunicationManager] SendResultOfSASProfileUpdate( " + ex.ToString() + " )");
                FileLogManager.GetInstance().WriteLog("[CommunicationManager] SendResultOfSASProfileUpdate( Exception=[" + ex.ToString() + "] )");

                return(false);
            }
            return(result);
        }
Пример #24
0
        void PacketHandler.Run(int credential, string payload)
        {
            Dictionary <int, ClientSession> clientList = EasyGameServer.g_WorldManager.GetClientList();
            List <JoinResult> joinList = new List <JoinResult>();

            foreach (ClientSession client in clientList.Values)
            {
                JoinResult joinResultPay = new JoinResult();
                joinResultPay.m_PlayerID = client.m_PlayerID;
                joinResultPay.m_PosX     = client.m_PosX;
                joinResultPay.m_PosY     = client.m_PosY;
                joinResultPay.m_PosZ     = client.m_PosZ;
                joinResultPay.m_Angle    = client.m_Angle;
                joinResultPay.m_Speed    = client.m_Speed;


                joinList.Add(joinResultPay);
            }

            SyncResult syncResultPay = new SyncResult();

            syncResultPay.m_JoinList = joinList;


            string resultPayload = JsonFx.Json.JsonWriter.Serialize(syncResultPay);

            Console.WriteLine("from:" + credential + "!" + resultPayload);

            string resultPacket = EasyGameServer.g_WorldManager.WrapPacket(PacketTypes.PKT_SC_SYNC, resultPayload);

            Console.WriteLine(":" + resultPacket);
            EasyGameServer.g_WorldManager.SendMessage(credential, resultPacket);
        }
Пример #25
0
        /// <include file='.\ISyncService.xml' path='/SyncService/Push/*'/>
        public static SyncResult Push(this ISyncService syncService, IEnumerable <String> local, FileEntry remote, ISyncProgressMonitor monitor)
        {
            if (monitor == null)
            {
                throw new ArgumentNullException("monitor", "Monitor cannot be null");
            }

            if (!remote.IsDirectory)
            {
                return(new SyncResult(ErrorCodeHelper.RESULT_REMOTE_IS_FILE));
            }

            // make a list of File from the list of String
            List <FileSystemInfo> files = new List <FileSystemInfo>();

            foreach (String path in local)
            {
                files.Add(path.GetFileSystemInfo());
            }

            // get the total count of the bytes to transfer
            long total = syncService.GetTotalLocalFileSize(files);

            monitor.Start(total);
            SyncResult result = syncService.DoPush(files, remote.FullPath, monitor);

            monitor.Stop();

            return(result);
        }
        public IActionResult SyncTenants([FromBody] AssociateDTO dto)
        {
            SyncResult res = molds.SyncTenants(dto.Id1, dto.Id2);

            SubmitResult = new SubmitResult();
            SubmitResult.Data["Sync"] = res;
            return(Respond());
        }
Пример #27
0
    public SyncResult SyncAll(SyncArguments syncArgs)
    {
        var syncResult = new SyncResult();

        // Do lots of other stuff
        // populate syncResult
        return(syncResult);
    }
 public static void Add(SyncResult obj)
 {
     if (_SyncResultList == null)
     {
         Init();
     }
     _SyncResultList.Add(obj);
 }
Пример #29
0
        /// <summary>
        /// Clears items, except the given.
        /// </summary>
        /// <param name="storeId">The store ID.</param>
        /// <param name="syncData">The sync data.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task <SyncResult> SyncClearAsync(string storeId, List <Dictionary <string, object> > syncData)
        {
            SyncResult syncResult = await ClearAsync(storeId);

            syncResult += await SyncAsync(storeId, syncData);

            return(syncResult);
        }
Пример #30
0
        /// <summary>
        /// Log the results to the console and keep track of the number of directories and files that require synchronisation
        /// </summary>
        /// <param name="result"></param>
        private static void LogResult(SyncResult result)
        {
            if (result.Item == SyncResult.ItemType.Trace)
            {
                Console.WriteLine(result.Message);
            }
            else if (result.Item == SyncResult.ItemType.File)
            {
                if (result.Reason == SyncResult.ReasonType.OnlyIn)
                {
                    Console.WriteLine(string.Format("'{0}' only in '{1}'", result.Message, result.Container));
                    FilesMissing++;

                    if (result.Context == SyncResult.ContainerType.Destination)
                    {
                        UnmatchedDestinationFile++;
                    }
                }
                else
                {
                    switch (result.Reason)
                    {
                    case SyncResult.ReasonType.Identical:
                    {
                        Console.WriteLine(string.Format("'{0}' identical", result.Message));
                        break;
                    }

                    case SyncResult.ReasonType.ModifiedTime:
                    {
                        Console.WriteLine(string.Format("'{0}' different modified times", result.Message));
                        FilesChanged++;
                        break;
                    }

                    case SyncResult.ReasonType.Length:
                    {
                        Console.WriteLine(string.Format("'{0}' different lengths", result.Message));
                        FilesChanged++;
                        break;
                    }
                    }
                }
            }
            else
            {
                if (result.Reason == SyncResult.ReasonType.OnlyIn)
                {
                    Console.WriteLine(string.Format("'{0}' only in '{1}'", result.Message, result.Container));
                    DirectoriesMissing++;

                    if (result.Context == SyncResult.ContainerType.Destination)
                    {
                        UnmatchedDestinationDirectory++;
                    }
                }
            }
        }
        /// <summary>
        /// The application entry point.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        static void Main(string[] args)
        {
            // Prepare data
            string login       = "******";
            string password    = "******";
            string apiVersion  = "v001";
            string storeID     = "STORE_ID";
            string baseAddress = "https://integration-test.gettipsi.com";

            List <Dictionary <string, object> > syncData = new List <Dictionary <string, object> >
            {
                new Dictionary <string, object>
                {
                    { TipsiClient.ExternalId, 229445 },
                    { "unit_size", "750ML" },
                    { "price", 34.4 },
                    { "in_stock", 12 },
                    { "barcodes", new [] { 12332323232323 } }
                },
                new Dictionary <string, object>
                {
                    { TipsiClient.ExternalId, 227985 },
                    { "unit_size", "750ML" },
                    { "price", 34.4 },
                    { "in_stock", 12 },
                    { "barcodes", new [] { 1233232323232323 } }
                }
            };

            TipsiClient tipsiClient = new TipsiClient(baseAddress, apiVersion, login, password);

            tipsiClient.LoginAsync().Wait();
            Console.WriteLine("Login is successful!!!");

            // now you can sync
            SyncResult syncResult = tipsiClient.SyncAsync(storeID, syncData).Result;

            PrintSyncResult(syncResult);

            // or
            syncResult = tipsiClient.SyncClearAsync(storeID, syncData).Result;
            PrintSyncResult(syncResult);

            string externalId = "EXTERNAL_ID";

            // Get Product By externalId
            JObject jObject =
                tipsiClient.ProductMatchAsync(
                    storeID,
                    externalId,
                    new Dictionary <string, string>
            {
                { "wine_fields", "id,winery,region" },
                { "inventory_fields", "id,wine" },
                { "winery_fields", "id,name" },
                { "region_fields", "id,name,description,image_url" }
            }).Result;
        }
        public void SyncProgress(SyncResult result)
        {
            Description = string.Format("Progress: {0}/{1}/{2}", result.Length, result.ProcessedRecordsCount, result.ErrorsCount);
            if (result.IsCancelled)
            {
                Description = string.Format("Import job '{0}' processing was canceled.", Job.Name);
            }

            Job.Notifier.Upsert(this);
        }
Пример #33
0
		public EndSyncEventArgs(
			[NotNull] IStatisticsContainer statisticsContainer,
			SyncResult result,
			Exception exception)
		{
			if (statisticsContainer == null)
				throw new ArgumentNullException(nameof(statisticsContainer));

			StatisticsContainer = statisticsContainer;
			Exception = exception;
			Result = result;
		}
Пример #34
0
		public EndSyncEventArgs(
			[NotNull] IStatisticsContainer statisticsContainer,
			SyncResult result,
			Exception exception)
		{
			if (statisticsContainer == null)
				throw new ArgumentNullException("statisticsContainer");

			_statisticsContainer = statisticsContainer;
			_exception = exception;
			_result = result;
		}
Пример #35
0
 public override void OnPerformSync(Account account, Bundle extras, string authority, ContentProviderClient provider, SyncResult syncResult)
 {
     //var feedId = extras.GetLong(KEY_FEED_ID, -1);
     Thread.Sleep(5000);
     /*if (feedId > 0)
     {
         syncFeeds(provider, syncResult, FeedProvider.Columns._ID + "=?", new String[]{ String.valueOf(feedId) });
     }
     else
     {
         syncFeeds(provider, syncResult, null, null);
     }*/
 }
Пример #36
0
 public void TestCompletion()
 {
     SyncResult result;
      result = new SyncResult(null, null);
      Assert.IsTrue(result.CompletedSynchronously);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(0));
      result = new SyncResult(o => { }, null);
      Assert.IsTrue(result.CompletedSynchronously);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(0));
      result = new SyncResult(o => { }, 1);
      Assert.IsTrue(result.CompletedSynchronously);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(0));
 }
Пример #37
0
 private void syncFeed(String feedId, String feedUrl, ContentProviderClient provider, SyncResult syncResult)
 {
     /* try {
         final HttpURLConnection cn = (HttpURLConnection) new URL(feedUrl).openConnection();
         try {
             final RssFeedParser parser = new RssFeedParser(cn.getInputStream());
             try {
                 parser.parse(feedId, provider, syncResult);
             } finally {
                 parser.close();
             }
         } finally {
             cn.disconnect();
         }
     } catch (IOException e) {
         Log.e(SyncAdapter.class.getName(), e.getMessage(), e);
         ++syncResult.stats.numIoExceptions;
     }*/
 }
Пример #38
0
 private ConsoleColor GetColor(SyncResult result)
 {
     ConsoleColor color;
     switch(result)
     {
         case SyncResult.Unchanged:
             color = ConsoleColor.White;
             break;
         case SyncResult.Ignored:
             color = ConsoleColor.White;
             break;
         case SyncResult.Failed:
             color = ConsoleColor.Red;
             break;
         default:
             color = ConsoleColor.Yellow;
             break;
     }
     return color;
 }
Пример #39
0
 private void syncFeeds(ContentProviderClient provider, SyncResult syncResult, String where, String[] whereArgs)
 {
     /*try {
         final Cursor feeds = provider.query(
             FeedProvider.URI, new String[]{
             FeedProvider.Columns._ID,
             FeedProvider.Columns.RSS_LINK
         }, where, whereArgs, null
         );
         try {
             if (feeds.moveToFirst()) {
                 do {
                     syncFeed(feeds.getString(0), feeds.getString(1), provider, syncResult);
                 } while (feeds.moveToNext());
             }
         } finally {
             feeds.close();
         }
     } catch (RemoteException e) {
         Log.e(SyncAdapter.class.getName(), e.getMessage(), e);
         ++syncResult.stats.numIoExceptions;
     }*/
 }
Пример #40
0
 private void RecordSyncError(SyncResult result)
 {
     lock (this.syncErrors)
     {
         this.syncErrors.Add(result);
     }
 }
Пример #41
0
        public SyncErrorResultAction HandleError(SyncResult syncResult)
        {
            if ((syncResult != null) && (syncResult.Operation != SyncOperationType.ConfigureSource))
            {
                if (syncResult.Ignorable == Ignorable.Yes)
                {
                    return SyncErrorResultAction.Ignore;
                }
                switch (syncResult.ResultCode)
                {
                    case 0x800700aa:
                        if (syncResult.Item != null)
                        {
                            return SyncErrorResultAction.Retry;
                        }
                        return SyncErrorResultAction.Abort;

                    case 0x83002113:
                        if (syncResult.Item != null)
                        {
                            return SyncErrorResultAction.Pause;
                        }
                        return SyncErrorResultAction.Abort;
                }
                this.RecordSyncError(syncResult);
            }
            return SyncErrorResultAction.Ignore;
        }
Пример #42
0
 private void OnSyncFinish(ISync Sync, SyncResult SyncResult)
 {
     SyncFinishHandler _eventObj = SyncFinish;
     if (_eventObj != null)
     {
         _eventObj(this, new SyncFinishEventArgs(Sync, SyncResult));
     }
 }
Пример #43
0
 public SyncFinishEventArgs(ISync Sync, SyncResult SyncResult): base(Sync)
 {
     _syncResult = SyncResult;
 }
Пример #44
0
		public EndSyncEventArgs(
			[NotNull] IStatisticsContainer statisticsContainer,
			SyncResult result)
			: this(statisticsContainer, result, null) {}
Пример #45
0
 /// <summary>
 /// Retrieves a message from the session
 /// If no message is available, enqueues a callback
 /// for when a message is submitted on the other end
 /// </summary>
 /// <param name="callback">
 /// Asynchronous callback delegate
 /// </param>
 /// <param name="state">
 /// Asynchronous callback parameter
 /// </param>
 /// <returns>
 /// The asynchronous completion token
 /// </returns>
 public IAsyncResult Dequeue(AsyncCallback callback, Object state)
 {
     IAsyncResult result = null;
      Message message = null;
      lock (this.inputMessageQueue)
      {
     if (this.inputMessageQueue.Any())
        message = this.inputMessageQueue.Dequeue();
     else if (!this.isComplete)
     {
        AsyncResult async = new AsyncResult(callback, state);
        this.inputCallbackQueue.Enqueue(async);
        result = async;
     }
      }
      if (message != null)
     result = new SyncResult(callback, state, message);
      return result;
 }
Пример #46
0
 public void TestState()
 {
     SyncResult result;
      result = new SyncResult(null, null);
      Assert.IsNull(result.AsyncState);
      Assert.IsTrue(result.IsCompleted);
      result = new SyncResult(null, 1);
      Assert.AreEqual(result.AsyncState, 1);
      Assert.IsTrue(result.IsCompleted);
      result = new SyncResult(o => { }, 2);
      Assert.AreEqual(result.AsyncState, 2);
      Assert.IsTrue(result.IsCompleted);
 }
Пример #47
0
 public void TestResult()
 {
     SyncResult result;
      result = new SyncResult(null, null, null);
      Assert.AreEqual(result.GetResult(), null);
      Assert.AreEqual(result.GetResult<String>(), null);
      Assert.IsTrue(result.IsCompleted);
      result = new SyncResult(null, null, "complete");
      Assert.AreEqual(result.GetResult(), "complete");
      Assert.AreEqual(result.GetResult<String>(), "complete");
      try
      {
     result.GetResult<Int32>();
     Assert.Fail("InvalidCastException expected");
      }
      catch (InvalidCastException) { }
      Assert.IsTrue(result.IsCompleted);
 }
Пример #48
0
 public void TestWait()
 {
     SyncResult result = new SyncResult(null, null);
      Assert.IsTrue(result.TryWaitFor(TimeSpan.Zero));
      Assert.IsTrue(result.TryWaitFor(TimeSpan.MaxValue));
      result.WaitFor();
      result.WaitFor(TimeSpan.Zero);
      result.WaitFor(TimeSpan.MaxValue);
 }