/// <summary> /// Private constructor /// </summary> /// <param name="smartStore"></param> /// <param name="client"></param> private SyncManager(SmartStore.Store.SmartStore smartStore, IRestClient client) { ApiVersion = ApiVersionStrings.VersionNumber; _smartStore = smartStore; RestClient = client; SyncState.SetupSyncsSoupIfNeeded(smartStore); }
private async Task SyncUp(SyncState sync, Action <SyncState> callback) { if (sync == null) { throw new SmartStoreException("SyncState sync was null"); } var target = (SyncUpTarget)sync.Target; HashSet <string> dirtyRecordIds = GetDirtyRecordIds(sync.SoupName, SmartStore.Store.SmartStore.SoupEntryId); int totalSize = dirtyRecordIds.Count; sync.TotalSize = totalSize; const int i = 0; foreach ( JObject record in dirtyRecordIds.Select( id => _smartStore.Retrieve(sync.SoupName, long.Parse(id))[0].ToObject <JObject>())) { await SyncUpOneRecord(target, sync.SoupName, sync.Options.FieldList, record, sync.MergeMode); int progress = (i + 1) * 100 / totalSize; if (progress < 100) { UpdateSync(sync, SyncState.SyncStatusTypes.Running, progress, callback); } } }
private async Task <bool> SyncDown(SyncState sync, Action <SyncState> callback) { var target = (SyncDownTarget)sync.Target; long maxTimeStamp = sync.MaxTimeStamp; JArray records = await target.StartFetch(this, sync.MaxTimeStamp); int countSaved = 0; int totalSize = target.TotalSize; sync.TotalSize = totalSize; UpdateSync(sync, SyncState.SyncStatusTypes.Running, 0, callback); while (records != null) { SaveRecordsToSmartStore(sync.SoupName, records, sync.MergeMode); countSaved += records.Count; maxTimeStamp = Math.Max(maxTimeStamp, target.GetMaxTimeStamp(records)); if (countSaved < totalSize) { UpdateSync(sync, SyncState.SyncStatusTypes.Running, countSaved * 100 / totalSize, callback); } records = await target.ContinueFetch(this); } sync.MaxTimeStamp = maxTimeStamp; return(true); }
public async void RunSync(SyncState sync, Action <SyncState> callback) { UpdateSync(sync, SyncState.SyncStatusTypes.Running, 0, callback); try { switch (sync.SyncType) { case SyncState.SyncTypes.SyncDown: await SyncDown(sync, callback); break; case SyncState.SyncTypes.SyncUp: await SyncUp(sync, callback); break; } UpdateSync(sync, SyncState.SyncStatusTypes.Done, 100, callback); } catch (Exception) { Debug.WriteLine("SmartSyncManager:runSync, Error during sync: " + sync.Id); UpdateSync(sync, SyncState.SyncStatusTypes.Failed, SyncDownTarget.Unchanged, callback); } }
public SyncState ReSync(long syncId, Action <SyncState> callback) { SyncState sync = SyncState.ById(_smartStore, syncId); if (sync == null) { throw new SmartStoreException("Cannot run ReSync:" + syncId + ": no sync found"); } if (sync.SyncType != SyncState.SyncTypes.SyncDown) { throw new SmartStoreException("Cannot run ReSync:" + syncId + ": wrong type: " + sync.SyncType); } var target = (SyncDownTarget)sync.Target; if (target.QueryType != SyncDownTarget.QueryTypes.Soql) { throw new SmartStoreException("Cannot run ReSync:" + syncId + ": wrong query type: " + target.QueryType); } if (sync.Status != SyncState.SyncStatusTypes.Done) { throw new SmartStoreException("Cannot run ReSync:" + syncId + ": not done: " + sync.Status); } RunSync(sync, callback); return(sync); }
/// <summary> /// Create and run a sync up. /// </summary> /// <param name="target"></param> /// <param name="options"></param> /// <param name="soupName"></param> /// <param name="callback"></param> /// <returns></returns> public SyncState SyncUp(SyncUpTarget target, SyncOptions options, string soupName, Action <SyncState> callback) { SyncState sync = SyncState.CreateSyncUp(_smartStore, target, options, soupName); RunSync(sync, callback); return(sync); }
private void saveTimeWhenReachedSleep(SyncState state) { if (state == Sleep) { lastTimeUsageStorage.SetSuccessfulFullSync(timeService.CurrentDateTime); } }
public SynchronizingItem(ItemInterface item, TaskState task, SyncState state = SyncState.None) { this.Drive = item.GDrive; this.ID = item.ID; this.Task = task; this.State = state; }
public void SetState(string path, SyncState state) { SetSyncInfo(path, new SyncInfo() { State = state }); }
/// <summary> /// Create and run a sync down. /// </summary> /// <param name="target"></param> /// <param name="soupName"></param> /// <param name="callback"></param> /// <param name="options"></param> /// <returns></returns> public SyncState SyncDown(SyncDownTarget target, string soupName, Action <SyncState> callback, SyncOptions options = null) { SyncState sync = SyncState.CreateSyncDown(_smartStore, target, soupName, options); RunSync(sync, callback); return(sync); }
private void ActFinishedCheck(SyncState state) { if (state != SyncState.Failed) { _unfinishedAction = null; } }
public bool Run() { ISyncState currentState = new SyncState(); //execute all actions specified in the sync configuration foreach (var action in m_SyncJob.Actions) { if (!action.IsEnabled) { continue; } //set configuration and state action.State = currentState; m_Logger.Info("Starting Action '{0}'", action.Name); try { //run the action action.Run(); } catch (JobExecutionException ex) { m_Logger.Error("Job did not run successfully: " + ex.Message); return(false); } //update the state currentState = action.State; } return(true); }
public Web3EthApi(IStateReader stateReader, IDeltaResolver deltaResolver, IDeltaCache deltaCache, IDeltaExecutor executor, IStorageProvider storageProvider, IStateProvider stateProvider, ITransactionRepository receipts, ITransactionReceivedEvent transactionReceived, IPeerRepository peerRepository, IMempool <PublicEntryDao> mempoolRepository, IDfsService dfsService, IHashProvider hashProvider, SyncState syncState, IMapperProvider mapperProvider, IPeerSettings peerSettings) { _receipts = receipts; _transactionReceived = transactionReceived ?? throw new ArgumentNullException(nameof(transactionReceived)); HashProvider = hashProvider; _peerId = peerSettings.PeerId; _mempoolRepository = mempoolRepository; PeerRepository = peerRepository; _mapperProvider = mapperProvider; StateReader = stateReader ?? throw new ArgumentNullException(nameof(stateReader)); DeltaResolver = deltaResolver ?? throw new ArgumentNullException(nameof(deltaResolver)); DeltaCache = deltaCache ?? throw new ArgumentNullException(nameof(deltaCache)); Executor = executor ?? throw new ArgumentNullException(nameof(executor)); StorageProvider = storageProvider ?? throw new ArgumentNullException(nameof(storageProvider)); StateProvider = stateProvider ?? throw new ArgumentNullException(nameof(stateProvider)); DfsService = dfsService; SyncState = syncState; }
public void SyncStateChanged (SyncState state) { // TODO: Update tray/applet icon // D-Bus event? // libnotify bubbles when appropriate Logger.Debug ("SilentUI: SyncStateChanged: {0}", state); switch (state) { case SyncState.Connecting: uiDisabled = true; // TODO: Disable all kinds of note editing // -New notes from server should be disabled, too // -Anyway we could skip this when uploading changes? // -Should store original Enabled state GuiUtils.GtkInvokeAndWait (() => { manager.ReadOnly = true; foreach (Note note in new List<Note> (manager.Notes)) { note.Enabled = false; } }); break; case SyncState.Idle: if (uiDisabled) { GuiUtils.GtkInvokeAndWait (() => { manager.ReadOnly = false; foreach (Note note in new List<Note> (manager.Notes)) { note.Enabled = true; } }); uiDisabled = false; } break; default: break; } }
public SyncData(List<TransData> tables) { Tables = tables; MdaId = Tables.First().MdaId; EmployeeId = Tables.First().EmployeeID; State = (SyncState)Tables.First().state; }
public override void Handle(GameSession session, PacketReader packet) { byte function = packet.ReadByte(); // Unknown what this is for session.ServerTick = packet.ReadInt(); session.ClientTick = packet.ReadInt(); byte segments = packet.ReadByte(); if (segments < 1) { return; } SyncState[] syncStates = new SyncState[segments]; for (int i = 0; i < segments; i++) { syncStates[i] = packet.ReadSyncState(); packet.ReadInt(); // ClientTicks packet.ReadInt(); // ServerTicks } PacketWriter syncPacket = SyncStatePacket.UserSync(session.Player.FieldPlayer, syncStates); session.FieldManager.BroadcastPacket(syncPacket, session); UpdatePlayer(session, syncStates); }
/// <summary> /// Create a new instance of the TrensmitUpdateItem class, wrapping this state. /// </summary> /// <param name="synchroniser">The synchroniser I will call to perform this action.</param> /// <param name="state">The sync state on which this action should be performed.</param> public TransmitUpdateAction(Synchroniser <OutlookItemType, SyncStateType> synchroniser, SyncStateType state) : base(1) { state.SetQueued(); this.synchroniser = synchroniser; this.state = state; this.NotifyOnFailure = state.IsManualOverride; MeetingSyncState meeting = state as MeetingSyncState; if (meeting != null) { ILogger log = Globals.ThisAddIn.Log; try { switch (meeting.OutlookItem.MeetingStatus) { case Outlook.OlMeetingStatus.olMeetingCanceled: log.Info($"TransmitUpdateAction: registered meeting {state.Description} cancelled"); break; case Microsoft.Office.Interop.Outlook.OlMeetingStatus.olMeetingReceivedAndCanceled: log.Info($"TransmitUpdateAction: registered meeting {state.Description} received and cancelled"); break; } } catch (COMException comx) { ErrorHandler.Handle($"Possibly-deleted item while trying to transmit update? HResult = {comx.HResult}", comx); } } }
public SynchronizingItem(string id, Drive drive, TaskState task, SyncState state = SyncState.None) { this.Drive = drive; this.ID = id; this.Task = task; this.State = state; }
public static string StateToString(SyncState s) { return s == SyncState.Added ? "added" : s == SyncState.Deleted ? "deleted" : "modified"; }
private void syncOperationCompleted(SyncState operation) { lock (stateLock) { isRunningSync = false; startSyncIfNeeded(); } }
public async Task <SyncState> SyncDownAttachment(AttachmentSyncDownTarget target, string soupName, Action <SyncState> callback, SyncOptions options = null, CancellationToken token = default(CancellationToken)) { SyncState sync = SyncState.CreateSyncAttachment(_smartStore, target, soupName, options); await RunSync(sync, callback, token); return(sync); }
/// <summary> /// Create and run a sync up. /// </summary> /// <param name="target"></param> /// <param name="options"></param> /// <param name="soupName"></param> /// <param name="callback"></param> /// <returns></returns> public async Task <SyncState> SyncUp(SyncUpTarget target, SyncOptions options, string soupName, Action <SyncState> callback, CancellationToken token = default(CancellationToken), Action <string, string> idChangeHandler = default(Action <string, string>)) { SyncState sync = SyncState.CreateSyncUp(_smartStore, target, options, soupName); await RunSync(sync, callback, token, idChangeHandler); return(sync); }
private void startSync(SyncState newState, StateResult entryPoint) { ensureNotSyncing(); syncing = true; stateEntered.OnNext(newState); stateMachine.Start(entryPoint.Transition()); }
public FavouriteDeltaObserver(IDeltaElector deltaElector, SyncState syncState, IPeerRepository peerRepository, IHashProvider hashProvider, ILogger logger) : base(logger) { _deltaElector = deltaElector; _syncState = syncState; _hashProvider = hashProvider; _peerRepository = peerRepository; }
public static SyncState ReadSyncState(this PacketReader packet) { var state = new SyncState(); state.Animation1 = packet.ReadByte(); state.Animation2 = packet.ReadByte(); state.Flag = (SyncStateFlag)packet.ReadByte(); if (state.Flag.HasFlag(SyncStateFlag.Flag1)) { state.Flag1Unknown1 = packet.ReadInt(); state.Flag1Unknown2 = packet.ReadShort(); } state.Coord = packet.Read <CoordS>(); state.Rotation = packet.ReadShort(); // CoordS / 10 (Rotation?) state.Animation3 = packet.ReadByte(); if (state.Animation3 > 127) // if animation < 0 (signed) { state.UnknownFloat1 = packet.Read <float>(); state.UnknownFloat2 = packet.Read <float>(); } state.Speed = packet.Read <CoordS>(); // XYZ Speed? state.Unknown1 = packet.ReadByte(); state.Unknown2 = packet.ReadShort(); // CoordS / 10 state.Unknown3 = packet.ReadShort(); // CoordS / 1000 if (state.Flag.HasFlag(SyncStateFlag.Flag2)) { state.Flag2Unknown1 = packet.Read <CoordF>(); state.Flag2Unknown2 = packet.ReadUnicodeString(); } if (state.Flag.HasFlag(SyncStateFlag.Flag3)) { state.Flag3Unknown1 = packet.ReadInt(); state.Flag3Unknown2 = packet.ReadUnicodeString(); } if (state.Flag.HasFlag(SyncStateFlag.Flag4)) { state.Flag4Unknown = packet.ReadUnicodeString(); // Animation string? } if (state.Flag.HasFlag(SyncStateFlag.Flag5)) { state.Flag5Unknown1 = packet.ReadInt(); state.Flag5Unknown2 = packet.ReadUnicodeString(); } if (state.Flag.HasFlag(SyncStateFlag.Flag6)) { state.Flag6Unknown1 = packet.ReadInt(); state.Flag6Unknown2 = packet.ReadInt(); state.Flag6Unknown3 = packet.ReadByte(); state.Flag6Unknown4 = packet.Read <CoordF>(); state.Flag6Unknown5 = packet.Read <CoordF>(); } state.Unknown4 = packet.ReadInt(); return(state); }
public override void Handle(GameSession session, PacketReader packet) { byte function = packet.ReadByte(); // Unknown what this is for session.ServerTick = packet.ReadInt(); session.ClientTick = packet.ReadInt(); byte segments = packet.ReadByte(); if (segments < 1) { return; } SyncState[] syncStates = new SyncState[segments]; for (int i = 0; i < segments; i++) { syncStates[i] = packet.ReadSyncState(); packet.ReadInt(); // ClientTicks packet.ReadInt(); // ServerTicks } Packet syncPacket = SyncStatePacket.UserSync(session.FieldPlayer, syncStates); session.FieldManager.BroadcastPacket(syncPacket, session); CoordF coord = syncStates[0].Coord.ToFloat(); CoordF closestBlock = Block.ClosestBlock(coord); closestBlock.Z -= Block.BLOCK_SIZE; // Get block under player if (IsCoordSafe(session, syncStates[0].Coord, closestBlock)) { session.Player.SafeBlock = closestBlock; } session.FieldPlayer.Coord = syncStates[0].Coord.ToFloat(); CoordF rotation = new CoordF(); rotation.Z = syncStates[0].Rotation / 10; session.FieldPlayer.Rotation = rotation; if (IsOutOfBounds(session.FieldPlayer.Coord, session.FieldManager.BoundingBox)) { int currentHp = session.Player.Stats[PlayerStatId.Hp].Current; int fallDamage = currentHp * Math.Clamp(currentHp * 4 / 100 - 1, 0, 25) / 100; // TODO: Create accurate damage model CoordF safeBlock = session.Player.SafeBlock; safeBlock.Z += Block.BLOCK_SIZE + 1; // Without this player will spawn inside the block session.Player.ConsumeHp(fallDamage); session.Send(UserMoveByPortalPacket.Move(session, safeBlock, session.Player.Rotation)); session.Send(StatPacket.UpdateStats(session.FieldPlayer, PlayerStatId.Hp)); session.Send(FallDamagePacket.FallDamage(session, fallDamage)); } // not sure if this needs to be synced here session.Player.Animation = syncStates[0].Animation1; }
public override void Handle(GameSession session, PacketReader packet) { byte function = packet.ReadByte(); // Unknown what this is for session.ClientTick = packet.ReadInt(); //ClientTicks packet.ReadInt(); // ServerTicks byte segments = packet.ReadByte(); if (segments < 1) { return; } SyncState[] syncStates = new SyncState[segments]; for (int i = 0; i < segments; i++) { syncStates[i] = packet.ReadSyncState(); packet.ReadInt(); // ClientTicks packet.ReadInt(); // ServerTicks } Packet syncPacket = SyncStatePacket.UserSync(session.FieldPlayer, syncStates); session.FieldManager.BroadcastPacket(syncPacket, session); CoordF coord = syncStates[0].Coord.ToFloat(); CoordF closestBlock = Block.ClosestBlock(coord); closestBlock.Z -= Block.BLOCK_SIZE; // Get block under player if (IsCoordSafe(session, syncStates[0].Coord, closestBlock)) { session.Player.SafeBlock = closestBlock; } session.FieldPlayer.Coord = syncStates[0].Coord.ToFloat(); if (IsOutOfBounds(session.FieldPlayer.Coord, session.FieldManager.BoundingBox)) { CoordF safeBlock = session.Player.SafeBlock; safeBlock.Z += Block.BLOCK_SIZE + 1; // Without this player will spawn inside the block // for some reason if coord is negative player is teleported one block over, which can result player being stuck inside a block if (session.FieldPlayer.Coord.X < 0) { safeBlock.X -= Block.BLOCK_SIZE; } if (session.FieldPlayer.Coord.Y < 0) { safeBlock.Y -= Block.BLOCK_SIZE; } session.Send(UserMoveByPortalPacket.Move(session, safeBlock)); session.Send(FallDamagePacket.FallDamage(session, 150)); // TODO: create a formula to determine HP loss } // not sure if this needs to be synced here session.Player.Animation = syncStates[0].Animation1; }
public JObject SaveStateToSoupForAttTransaction(SyncState state, string transactionItemType, DateTime lastModifiedDate) { if (string.IsNullOrWhiteSpace(transactionItemType)) { throw new SyncException("Expected transactionItemType."); } return(SaveStateToSoup(state, transactionItemType, lastModifiedDate)); }
/// <summary> /// Initializes a new instance of the <see cref="SyncStateEntity"/> class. /// </summary> /// <param name="syncState">They SyncState </param> public SyncStateEntity(SyncState syncState) { EnsureArg.IsNotNull(syncState, nameof(syncState)); PartitionKey = Constants.SyncStatePartitionKey; RowKey = Constants.SyncStateRowKey; SyncedSequence = syncState.SyncedSequence; }
public JObject SaveStateToSoupForDocTransaction(SyncState state, ContentDocument cd) { if (cd == null) { throw new SyncException("ContentDocument is required to save transaction."); } return(SaveStateToSoup(state, cd.Id, cd.LatestPublishedVersionId)); }
/// <summary> /// packet where to put the packet /// </summary> /// <param name="packet"></param> /// <returns></returns> private int GetNextPacket(Packet packet) { // get next packet. bool fetchedPacket = false; while (!EndOfStream && !fetchedPacket) { int result1 = StreamState.packetout(packet); if (result1 == 0) { // no more packets in page. Fetch new page. int result2 = 0; while (!EndOfStream && result2 == 0) { result2 = SyncState.pageout(Page); if (result2 == 0) { FetchData(); } } // return if we have reaced end of file. if ((result2 == 0) && (Page.eos() != 0)) { return(-1); } if (result2 == 0) { // need more data fetching page.. FetchData(); } else if (result2 == -1) { //throw new Exception("syncState.pageout(page) result == -1"); Console.WriteLine("syncState.pageout(page) result == -1"); return(-1); } else { int result3 = StreamState.pagein(Page); } } else if (result1 == -1) { //throw new Exception("streamState.packetout(packet) result == -1"); Console.WriteLine("streamState.packetout(packet) result == -1"); return(-1); } else { fetchedPacket = true; } } return(0); }
public static SyncState GetSyncState(CorrelatedResSyncInfo corelation) { SyncState result = new SyncState(); result.Endpoint = corelation.ResSyncInfo.Endpoint; result.Stamp = corelation.ResSyncInfo.ModifiedStamp; result.Tick = corelation.ResSyncInfo.Tick; return(result); }
public async Task UpdateAsync(SyncState state, CancellationToken cancellationToken = default) { CloudTable table = _client.GetTableReference(Constants.SyncStateTableName); TableEntity entity = new SyncStateEntity(state); TableOperation operation = TableOperation.InsertOrReplace(entity); await table.ExecuteAsync(operation, cancellationToken); }
// 수신. public void ReceiveInputData() { byte[] data = new byte[1400]; // 데이터를 송신합니다. int recvSize = m_transport.Receive(ref data, data.Length); if (recvSize < 0) { // 입력정보를 수신하지 않았으므로 다음 프레임을 처리할 수 없습니다. return; } string str = System.Text.Encoding.UTF8.GetString(data); if (requestData.CompareTo(str.Trim('\0')) == 0) { // 접속 요청 패킷 . return; } // byte 배열을 구조체로 변환합니다. InputData inputData = new InputData(); InputSerializer serializer = new InputSerializer(); serializer.Deserialize(data, ref inputData); // 수신한 입력 정보를 설정합니다. PlayerInfo info = PlayerInfo.GetInstance(); int playerId = info.GetPlayerId(); int opponent = (playerId == 0)? 1 : 0; for (int i = 0; i < inputData.count; ++i) { int frame = inputData.datum[i].frame; //Debug.Log("Set inputdata"+i+"[" + recvFrame + "][" + frame + "]:" + (recvFrame + 1 == frame)); if (recvFrame + 1 == frame) { inputBuffer[opponent].Add(inputData.datum[i]); ++recvFrame; } } //Debug.Log("recvFrame:" + recvFrame); // 접속 종료 플래그를 감시. bit1:접속 종료 응답, bit0: 접속 종료 요구. if ((inputData.flag & 0x03) == 0x03) { // 접속 종료 플래그 수신. suspendSync = 0x03; Debug.Log("Receive SuspendSync."); } if ((inputData.flag & 1) > 0 && (suspendSync & 1) > 0) { suspendSync |= 0x02; Debug.Log("Receive SuspendSync." + inputData.flag); } if (isConnected && suspendSync == 0x03) { // 서로 접속 종료 상태가 되었으므로 상대에게의 접속 종료 플래그를 보내기위한. // 유예기간을 두고 조금 후에 접속종료합니다. ++disconnectCount; if (disconnectCount > 10) { m_transport.Disconnect(); Debug.Log("Disconnect because of suspendSync."); } } // 상태 갱신. if (syncState == SyncState.NotStarted) { syncState = SyncState.WaitSynchronize; } //loopCounter = 0; }
public void StringToStateTest() { SpeedDial target = new SpeedDial(); // TODO: 適切な値に初期化してください string s = string.Empty; // TODO: 適切な値に初期化してください SyncState expected = new SyncState(); // TODO: 適切な値に初期化してください SyncState actual; actual = target.StringToState(s); Assert.AreEqual(expected, actual); Assert.Inconclusive("このテストメソッドの正確性を確認します。"); }
/// <summary> /// Asynchronous method to determine if the user's clock is syncrhonized to BattleClinic time /// </summary> /// <param name="callback"></param> public static void CheckIsSynchronised(TimeSynchronisationCallback callback) { SyncState state = new SyncState(callback); EveClient.HttpWebService.DownloadStringAsync(NetworkConstants.BatlleclinicTimeSynch, SyncDownloadCompleted, state); }
public Sessions() { Messenger.Default.Register<SyncStepFinished>(this, (msg) => { Messenger.Default.Send<SyncStateChanged>(_state |= msg.Content); }); }
public SpawnEvent(SyncState spawnState) { xPos = spawnState.xPos; yPos = spawnState.yPos; xVel = spawnState.xSpeed; yVel = spawnState.ySpeed; }
/// <summary> /// Initialize the Progress /// </summary> /// <param name="tagName">Name of the tag</param> public Progress(string tagName) { State = SyncState.Started; TagName = tagName; }
// // StatusUpdate // // Communicates synchronization status. // // Parameters: // state - A SyncState value. // text - The status description. // progressValue - An integer that indicates the progress value. // maxValue - An integer that indicates the maximum progress value. // internal void StatusUpdate(SyncState state, string text, int progressValue, int maxValue) { //if (syncStatus != null) //{ // syncStatus(state, text, progressValue, maxValue, ref updateWasCanceled); //} }
/// <summary> /// Initializes a new instance of the ActionsViewModel class. /// </summary> public ActionsViewModel() : base("Actions_NextText","Actions_PreviousText","Actions_Title", "Actions_Description") { NextPage = Page.Actions; PreviousPage = Page.ProjectSelection; CanNavigateBack = true; CanNavigateNext = true; updateFromSyncState(); MessengerInstance.Register<ConnectionStateChanged>(this, (msg) => { _cState = msg.Content; }); MessengerInstance.Register<SyncStateChanged>(this, (msg) => { _sState = msg.Content; updateFromSyncState(); }); MessengerInstance.Register<ApplicationClosing>(this, (msg) => { if (msg.WarningOnly) saveAndClose(); }); MessengerInstance.Register<ExecuteAction>(this, (msg) => { if (msg.Content == Enums.Action.CleanDB) executeCleanDB(); }); MessengerInstance.Register<SelectedTaxonLists>(this, (msg) => { if (DefinitionsSvc != null) DefinitionsSvc.TaxaLoaded += new AsyncOperationFinishedHandler(DefinitionsSvc_TaxaLoaded); loadTaxa(msg.Content); }); GetTaxonDefinitions = new RelayCommand( () => { MessengerInstance.Send<CustomDialog>(Dialog.Taxon); }, () => { return requiredConnectionLevel(DEFINITIONS); }); GetPropertyNames = new RelayCommand( () => { if (DefinitionsSvc != null) { IsBusy = true; CurrentOperation = DefinitionsSvc.loadProperties(); } else _Log.Error("DefinitionsService N/A"); }, () => { return requiredConnectionLevel(DEFINITIONS); }); GetPrimaryData = new RelayCommand( () => { MessengerInstance.Send<NavigateToPage>(Page.FieldData); }, () => { return requiredConnectionLevel(REPOSITORY); }); UploadData = new RelayCommand( () => { if (FieldDataSvc != null) { if (ProfileSvc != null) { var projectID = ProfileSvc.ProjectID; var userNo = ProfileSvc.UserNr; IsBusy = true; CurrentOperation = FieldDataSvc.uploadData(userNo, projectID); } else _Log.Error("UserProfileService N/A"); } else _Log.Error("FieldDataService N/A"); }, () => { return requiredConnectionLevel(REPOSITORY); }); CleanDatabase = new RelayCommand( () => { showYesNoBox("Actions_Clean","Actions_ReallyClean_Message",System.Windows.MessageBoxResult.No,(res) => { if(res == System.Windows.MessageBoxResult.Yes) executeCleanDB(); }); }, () => { return requiredConnectionLevel(ConnectionState.ConnectedToSynchronization | ConnectionState.ConnectedToMobileTax | ConnectionState.ConnectedToMobile); }); OpenMaps = new RelayCommand( () => { MessengerInstance.Send<NavigateToPage>(Page.Map); }); }
// 송신. void SendInputData() { PlayerInfo info = PlayerInfo.GetInstance(); int playerId = info.GetPlayerId(); int count = inputBuffer[playerId].Count; InputData inputData = new InputData(); inputData.count = count; inputData.flag = suspendSync; inputData.datum = new MouseData[bufferNum]; //string str1 = "Count :" + count; //Debug.Log(str1); for (int i = 0; i < count; ++i) { inputData.datum[i] = inputBuffer[playerId][i]; //str1 = "Send mouse data => id:" + i + " - " + inputBuffer[playerId][i].frame; //Debug.Log(str1); } // 구조체를 byte 배열로 변환합니다. InputSerializer serializer = new InputSerializer(); bool ret = serializer.Serialize(inputData); if (ret) { byte[] data = serializer.GetSerializedData(); // 데이터를 송신합니다. m_transport.Send(data, data.Length); } // 상태를 갱신. if (syncState == SyncState.NotStarted) { syncState = SyncState.WaitSynchronize; } }
private SyncState _CheckSyncState() { try { if (_syncState != SyncState.Unknown) { return _syncState; } Mutex.Wait(); try { _UpdateProcessCount("_CheckSyncState", 1); try { if (_loadedRootFolderId != RootFolderId) { _loadedRootFolderId = RootFolderId; _loadedLargestChangeId = LargestChangeId; Files.Clear(); FilesByParent.Clear(); _syncState = SyncState.SyncFromWeb; } else if (_loadedLargestChangeId != LargestChangeId) { // used as StartChangeId in SyncChangesFromWeb _largestChangeId = _loadedLargestChangeId; _syncState = SyncState.SyncChangesFromWeb; } else { _syncState = SyncState.SyncedToWeb; } } finally { _UpdateProcessCount("_CheckSyncState", -1); } } finally { Mutex.Release(); } return _syncState; } catch (Exception exception) { Log.Error(exception, false); return _syncState; } }
private bool _LoadFromWeb() { try { if (LoadedFromWeb) { return true; } if (!_LoadFromDisk()) { Log.Error("Cannot load Journal from web - Could not load Journal from disk."); return false; } if (!IsSignedIn) { Log.Error("Cannot load Journal from web - Not signed in."); return false; } if (LoadingFromWeb) { Log.Error("Cannot load Journal from web - Already loading from web."); return false; } Mutex.Wait(); try { _UpdateProcessCount("_LoadFromWeb", 1); _loadingFromWeb = true; try { SyncState syncState = _CheckSyncState(); if (syncState == SyncState.SyncFromWeb) { //if (_SyncFromWeb(RootFolderId, true) == null) //{ // Log.Error("Cannot load Journal from web - Could not sync from web."); // return false; //} } else if (syncState == SyncState.SyncChangesFromWeb) { //if (!_SyncChangesFromWeb()) //{ // Log.Error("Cannot load Journal from web - Could not sync changes from web."); // return false; //} } } finally { _loadingFromWeb = false; _UpdateProcessCount("_LoadFromWeb", -1); } _loadedFromWeb = true; _syncState = SyncState.SyncedToWeb; } finally { Mutex.Release(); } return true; } catch (Exception exception) { Log.Error(exception, false); return false; } }
/// <summary> /// Performs initialization of data structure for a newly created thread /// It sets up the environment for the first method that runs the thread /// </summary> /// <param name="threadID">Thread id, which is the guid of the thread object</param> /// <param name="startingObject">The object from which the thread is started</param> /// <param name="startingMethod">The thread function</param> private void InitializeThread(int threadID, VMValue_object startingObject, CILMethod startingMethod) { this.threadID = threadID; currentMethod = startingMethod; syncState = SyncState.RUNNING; localVariableBlocks.Push(new VMLocalVariableBlock(this, startingMethod)); if(startingObject != null) localVariableBlocks.Peek().AddArgumentFront(startingObject); pc = currentMethod.GetFirstInstruction(); }
public void Update (WidgetParser parser, Stetic.Project stetic) { if (AttrSyncState == SyncState.Unspecified) { InsertToolboxItemAttributes (parser); AttrSyncState = SyncState.On; return; } else if (AttrSyncState == SyncState.Off) return; StringCollection tb_names = new StringCollection (); foreach (var cls in parser.GetToolboxItems().Values) { UpdateClass (parser, stetic, cls, null); tb_names.Add (cls.GetFullName ()); } List<XmlElement> toDelete = new List<XmlElement> (); foreach (XmlElement elem in SelectNodes ("objects/object")) { string name = elem.GetAttribute ("type"); if (!tb_names.Contains (name)) toDelete.Add (elem); } foreach (XmlElement elem in toDelete) elem.ParentNode.RemoveChild (elem); Save (); }
private static void SetState (SyncState newState) { state = newState; if (syncUI != null) { // Notify the event handlers try { syncUI.SyncStateChanged (state); } catch {} } }
//동기화된 입력값을 꺼냅니다. public void DequeueMouseData() { //Debug.Log("DequeueMouseData"); // 양 단말의 데이터가 모였는지 체크합니다. for (int i = 0; i < playerNum; ++i) { if (inputBuffer[i].Count == 0) { return; //입력값이 없을 때는 아무것도 하지 않습니다. } } // 데이터가 모였으므로. for (int i = 0; i < playerNum; ++i) { mouseData[i] = inputBuffer[i][0]; inputBuffer[i].RemoveAt(0); //입력 관리자에게 동기된 데이터로서 전달합니다. m_inputManager.SetInputData(i, mouseData[i]); #if false m_debugWriterSyncData.WriteLine(mouseData[i]); #endif } #if false m_debugWriterSyncData.Flush(); #endif //Debug.Log("DequeueMouseData:isSynchronized"); // 상태 갱신. if (syncState != SyncState.Synchronized) { syncState = SyncState.Synchronized; } isSynchronized = true; }
private bool syncStateSatisfies(SyncState req) { return (_sState & req) == req; }
// // OnFileSyncStatus // // Occurs when new status is available. // // Parameters: // state - A SyncState value. // text - The status description. // progressValue - An integer that indicates the progress value. // maxValue - An integer that indicates the maximum progress value. // cancelUpdate - A ref value that allows the form to tell FileSync to cancel the synchronization. // private void OnFileSyncStatus(SyncState state, string text, int progressValue, int maxValue, ref bool cancelUpdate) { // Allow the Cancel button click to be serviced. Application.DoEvents(); if (progressForm != null) { progressForm.SyncState = state; progressForm.StatusText = text; progressForm.MaxValue = maxValue; progressForm.ProgressValue = progressValue; cancelUpdate = progressForm.Cancel; if (state != SyncState.Updating) { progressForm.SynchronizeCompleted(); } } }
public void SyncStateChanged (SyncState state) { // This event handler will be called by the synchronization thread // so we have to use the delegate here to manipulate the GUI. Gtk.Application.Invoke (delegate { // FIXME: Change these strings to be user-friendly switch (state) { case SyncState.AcquiringLock: ProgressText = Catalog.GetString ("Acquiring sync lock..."); break; case SyncState.CommittingChanges: ProgressText = Catalog.GetString ("Committing changes..."); break; case SyncState.Connecting: Title = Catalog.GetString ("Synchronizing Notes"); HeaderText = Catalog.GetString ("Synchronizing your notes..."); MessageText = Catalog.GetString ("This may take a while, kick back and enjoy!"); model.Clear (); ProgressText = Catalog.GetString ("Connecting to the server..."); progressBar.Fraction = 0; progressBar.Show (); progressLabel.Show (); break; case SyncState.DeleteServerNotes: ProgressText = Catalog.GetString ("Deleting notes off of the server..."); progressBar.Pulse (); break; case SyncState.Downloading: ProgressText = Catalog.GetString ("Downloading new/updated notes..."); progressBar.Pulse (); break; case SyncState.Idle: GLib.Source.Remove (progressBarTimeoutId); progressBarTimeoutId = 0; progressBar.Fraction = 0; progressBar.Hide (); progressLabel.Hide (); closeButton.Sensitive = true; break; case SyncState.Locked: Title = Catalog.GetString ("Server Locked"); HeaderText = Catalog.GetString ("Server is locked"); MessageText = Catalog.GetString ("One of your other computers is currently synchronizing. Please wait 2 minutes and try again."); ProgressText = string.Empty; break; case SyncState.PrepareDownload: ProgressText = Catalog.GetString ("Preparing to download updates from server..."); break; case SyncState.PrepareUpload: ProgressText = Catalog.GetString ("Preparing to upload updates to server..."); break; case SyncState.Uploading: ProgressText = Catalog.GetString ("Uploading notes to server..."); break; case SyncState.Failed: Title = Catalog.GetString ("Synchronization Failed"); HeaderText = Catalog.GetString ("Failed to synchronize"); MessageText = Catalog.GetString ("Could not synchronize notes. Check the details below and try again."); ProgressText = string.Empty; break; case SyncState.Succeeded: int count = 0; count += model.IterNChildren (); Title = Catalog.GetString ("Synchronization Complete"); HeaderText = Catalog.GetString ("Synchronization is complete"); string numNotesUpdated = string.Format (Catalog.GetPluralString ("{0} note updated.", "{0} notes updated.", count), count); MessageText = numNotesUpdated + " " + Catalog.GetString ("Your notes are now up to date."); ProgressText = string.Empty; break; case SyncState.UserCancelled: Title = Catalog.GetString ("Synchronization Canceled"); HeaderText = Catalog.GetString ("Synchronization was canceled"); MessageText = Catalog.GetString ("You canceled the synchronization. You may close the window now."); ProgressText = string.Empty; break; case SyncState.NoConfiguredSyncService: Title = Catalog.GetString ("Synchronization Not Configured"); HeaderText = Catalog.GetString ("Synchronization is not configured"); MessageText = Catalog.GetString ("Please configure synchronization in the preferences dialog."); ProgressText = string.Empty; break; case SyncState.SyncServerCreationFailed: Title = Catalog.GetString ("Synchronization Service Error"); HeaderText = Catalog.GetString ("Service error"); MessageText = Catalog.GetString ("Error connecting to the synchronization service. Please try again."); ProgressText = string.Empty; break; } }); }
private Item _SyncFromData(File file, List<File> children = null) { try { Mutex.Wait(); try { _UpdateProcessCount("_SyncFromFile", 1); Item item = null; try { _RemoveItem(file.Id); item = Files.GetOrAdd(file.Id, new Item()); item.Status = ItemStatus.Pending; _BindToItem(item, file); if (!IsFolder(item.File)) { item.Status = ItemStatus.Cached; } else if (children != null) { foreach (File child in children) { _AddItem(child); } item.Status = ItemStatus.Cached; List<Item> itemChildren = GetChildrenItems(file.Id); _SyncToDiskAsync(item, itemChildren); } } finally { _UpdateProcessCount("_SyncFromFile", -1); } _loadedFromWeb = true; _syncState = SyncState.SyncedToWeb; return item; } finally { Mutex.Release(); } } catch (Exception exception) { Log.Error(exception, false); return null; } }
internal void AddToSync(Entity entity, SyncState syncState) { entity.SyncState |= syncState; _syncList.Add(entity); }
public void resetSync() { Sync = SyncState.None; }