public async Task Sync()
        {
            try
            {
                var response = await RestService.Client.GetAsync("api/EngineTypes/");

                if (!response.IsSuccessStatusCode)
                {
                    SyncFailed?.Invoke(this, EventArgs.Empty);
                    return;
                }

                var result =
                    JsonConvert.DeserializeObject <IEnumerable <EngineTypeViewModel> >(await response.Content.ReadAsStringAsync());

                using (var transaction = DatabaseService.Realm.BeginWrite())
                {
                    DatabaseService.Realm.RemoveAll <EngineType>();

                    foreach (var et in result)
                    {
                        var realmEt = DatabaseService.Realm.CreateObject <EngineType>();
                        realmEt.Id   = et.Id.ToString();
                        realmEt.Name = et.Name;
                    }

                    transaction.Commit();
                }
            }
            catch
            {
                SyncFailed?.Invoke(this, EventArgs.Empty);
            }
        }
Ejemplo n.º 2
0
        public async Task RunNowAsync()
        {
            lock (_LOCK)
            {
                if (IsSyncRunning)
                {
                    return;
                }

                IsSyncRunning = true;
            }

            try
            {
                var lastUpdateTime = await DbService.GetNewestTimeAsync();

                DateTime currentDay = lastUpdateTime == null?DateTime.Now.Date.AddDays(-100) : lastUpdateTime.Value.Date;

                while (currentDay <= DateTime.Now)
                {
                    var items = await DataService.GetExchangeRateAsync(currentDay, lastUpdateTime);

                    if (items.Count > 0)
                    {
                        await DbService.SyncRateItemsAsync(items);

                        SyncUpdated?.Invoke(this, new SyncUpdatedEventArgs {
                            LastUpdate = items.Max(o => o.Time)
                        });
                    }

                    currentDay     = currentDay.AddDays(1);
                    lastUpdateTime = null;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Forex data sync error");

                SyncFailed?.Invoke(this, new SyncFailedEventArgs {
                    Message = ex.Message
                });
            }
            finally
            {
                lock (_LOCK)
                {
                    IsSyncRunning = false;
                }
            }
        }
        private async Task InitPeerInfo(ISynchronizationPeer peer, CancellationToken token)
        {
            Task <Keccak> getHashTask = peer.GetHeadBlockHash();

            if (_logger.IsDebugEnabled)
            {
                _logger.Debug($"Requesting head block info from {peer.NodeId}");
            }

            Task <BigInteger> getNumberTask = peer.GetHeadBlockNumber(token);
            await Task.WhenAll(getHashTask, getNumberTask).ContinueWith(
                t =>
            {
                if (t.IsFaulted)
                {
                    if (_logger.IsErrorEnabled)
                    {
                        if (t.Exception != null && t.Exception.InnerExceptions.Any(x => x is TimeoutException))
                        {
                            _logger.Warn($"InitPeerInfo failed for node: {peer.NodeId}. {t.Exception?.Message}");
                        }
                        else
                        {
                            _logger.Error($"InitPeerInfo failedf or node: {peer.NodeId}.", t.Exception);
                        }
                    }

                    SyncFailed?.Invoke(this, new SyncEventArgs(peer));
                }
                else if (t.IsCanceled)
                {
                    token.ThrowIfCancellationRequested();
                }
            }, token);

            if (_logger.IsDebugEnabled)
            {
                _logger.Info($"Received head block info from {peer.NodeId} with head block numer {getNumberTask.Result}");
            }

            bool addResult = _peers.TryAdd(peer.NodeId, new PeerInfo(peer, getNumberTask.Result)
            {
                NumberReceived = BlockTree.BestSuggested.Number
            });                                                                                                                                        // TODO: cheating now with assumign the consistency of the chains

            if (!addResult)
            {
                _logger.Error($"Adding {nameof(PeerInfo)} failed for {peer.NodeId}");
            }
        }
Ejemplo n.º 4
0
 private void OnSyncFailed()
 {
     SyncFailed?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Если произошла ошибка
 /// </summary>
 public void OnSyncFailed()
 {
     SyncFailed?.Invoke(this, EventArgs.Empty);
 }
        private async Task SyncAsync()
        {
            while (true)
            {
                // TODO: order by total difficulty
                var peers = _peers.Where(x => !x.Value.IsSynced).OrderBy(p => p.Value.NumberAvailable).ToArray();

                if (!peers.Any())
                {
                    if (_logger.IsInfoEnabled)
                    {
                        _logger.Info($"No sync peers availible, finishing sync process, our block #: {BlockTree.BestSuggested.Number}");
                    }
                    return;
                }

                var peerInfo = peers.Last().Value;

                if (BlockTree.BestSuggested.Number >= peerInfo.NumberAvailable)
                {
                    if (_logger.IsInfoEnabled)
                    {
                        _logger.Info($"No more peers with higher block number availible, finishing sync process, our highest block #: {BlockTree.BestSuggested.Number}, highest peer block #: {peerInfo.NumberAvailable}");
                    }
                    return;
                }

                _currentSyncingPeer = peerInfo;
                if (_logger.IsInfoEnabled)
                {
                    _logger.Info($"Starting sync processes with Node: {peerInfo.Peer.NodeId} [{peerInfo.Peer.ClientId}], peer highest block #: {peerInfo.NumberAvailable}, our highest block #: {BlockTree.BestSuggested.Number}");
                }

                _syncCancellationTokenSource = new CancellationTokenSource();

                var currentPeerNodeId = peerInfo?.Peer?.NodeId;

                var syncTask = PeerSyncAsync(_syncCancellationTokenSource.Token, peerInfo);
                await syncTask.ContinueWith(t =>
                {
                    if (t.IsFaulted)
                    {
                        if (_logger.IsErrorEnabled)
                        {
                            if (t.Exception != null && t.Exception.InnerExceptions.Any(x => x is TimeoutException))
                            {
                                _logger.Warn($"Stopping Sync with node: {currentPeerNodeId}. {t.Exception?.Message}");
                            }
                            else
                            {
                                _logger.Error($"Stopping Sync with node: {currentPeerNodeId}. Error in the sync process: {t.Exception?.Message}");
                            }
                        }
                        else if (_logger.IsDebugEnabled)
                        {
                            _logger.Error($"Stopping Sync with node: {currentPeerNodeId}. Error in the sync process", t.Exception);
                        }

                        //TODO check if we should disconnect this node
                        RemovePeer(peerInfo?.Peer);
                        if (_logger.IsInfoEnabled)
                        {
                            _logger.Info($"Sync with Node: {currentPeerNodeId} failed. Removed node from sync peers.");
                        }

                        SyncFailed?.Invoke(this, new SyncEventArgs(peerInfo.Peer));
                    }
                    else if (t.IsCanceled)
                    {
                        RemovePeer(peerInfo?.Peer);
                        if (_logger.IsInfoEnabled)
                        {
                            _logger.Info($"Sync with Node: {currentPeerNodeId} canceled. Removed node from sync peers.");
                        }
                    }
                    else if (t.IsCompleted)
                    {
                        if (_logger.IsInfoEnabled)
                        {
                            _logger.Info($"Sync process finished with nodeId: {currentPeerNodeId}. Best block now is {BlockTree.BestSuggested.Hash} ({BlockTree.BestSuggested.Number})");
                        }
                    }

                    if (_logger.IsInfoEnabled)
                    {
                        _logger.Info($"Finished sync process [{(t.IsFaulted ? "FAULTED" : t.IsCanceled ? "CANCELLED" : t.IsCompleted ? "COMPLETED" : "OTHER" )}] with Node: {peerInfo.Peer.NodeId} [{peerInfo.Peer.ClientId}], peer highest block #: {peerInfo.NumberAvailable}, our highest block #: {BlockTree.BestSuggested.Number}");
                    }
                });
            }
        }
Ejemplo n.º 7
0
        public async Task Sync()
        {
            try
            {
                var response = await RestService.Client.GetAsync("api/Companies/");

                if (!response.IsSuccessStatusCode)
                {
                    SyncFailed?.Invoke(this, EventArgs.Empty);
                    return;
                }

                var result =
                    JsonConvert.DeserializeObject <IEnumerable <CompanyViewModel> >(await response.Content.ReadAsStringAsync()).Select(c => new Company()
                {
                    CloudId  = c.Id.ToString(),
                    Name     = c.Name,
                    Personal = c.Personal
                });

                var existing = await GetCompanies();

                var existingEnumerable = existing as Company[] ?? existing.ToArray();

                var resultEnumerable = result as Company[] ?? result.ToArray();

                foreach (var company in resultEnumerable)
                {
                    var currentCompany = existingEnumerable.FirstOrDefault(c => c.CloudId == company.CloudId);

                    if (currentCompany == null)
                    {
                        using (var transaction = DatabaseService.Realm.BeginWrite())
                        {
                            var newCompany = DatabaseService.Realm.CreateObject <Company>();

                            newCompany.CloudId = company.CloudId;
                            newCompany.Id      = Guid.NewGuid().ToString();

                            newCompany.Name     = company.Name;
                            newCompany.Personal = company.Personal;

                            transaction.Commit();
                        }
                    }
                    else
                    {
                        using (var transaction = DatabaseService.Realm.BeginWrite())
                        {
                            var existingCompany = DatabaseService.Realm.ObjectForPrimaryKey <Company>(currentCompany.Id);

                            existingCompany.Name     = company.Name;
                            existingCompany.Personal = company.Personal;

                            transaction.Commit();
                        }
                    }
                }

                foreach (var company in existingEnumerable)
                {
                    var currentCompany = resultEnumerable.FirstOrDefault(c => c.CloudId == company.CloudId);

                    if (currentCompany != null)
                    {
                        continue;
                    }

                    var existingCompany = await Host.CompanyService.GetCompany(company.Id);

                    DatabaseService.Realm.Remove(existingCompany);
                }
            }
            catch
            {
                SyncFailed?.Invoke(this, EventArgs.Empty);
            }
        }