public override string ToString()
        {


            b = (Busy)base.Tag;
            Binding descbinding = new Binding("Description");
            descbinding.Mode = BindingMode.TwoWay;
            descbinding.Source = b;
            txtdesc.SetBinding(TextBox.TextProperty, descbinding);

            return base.ToString();
        }
Пример #2
0
        private async Task CalculateGymData(FortDataWrapper currentGym)
        {
            // Navigating from game page, so we need to actually load the Gym
            Busy.SetBusy(true, "Loading Gym");
            var response = await GameClient.GetGymDetails(currentGym.Id, currentGym.Latitude, currentGym.Longitude);

            Logger.Write($"Entering {response.Name} [ID = {CurrentGym.Id}]");
            Busy.SetBusy(false);
            switch (response.Result)
            {
            case GetGymDetailsResponse.Types.Result.Unset:
                Logger.Write("Entering Gym Unset", LogLevel.Warning);
                ReturnToGameScreen.Execute();
                break;

            case GetGymDetailsResponse.Types.Result.Success:
                // Success, we play the animation and update inventory
                Logger.Write("Entering Gym success");
                CurrentGym     = new FortDataWrapper(response.GymState.FortData);
                CurrentGymInfo = response;
                await GameClient.UpdateInventory();

                CurrentMembers = GetCurrentMembers(CurrentGymInfo);
                SelectedMember = CurrentMembers.FirstOrDefault();
                Logger.Write(string.Join("\n", CurrentMembers.Select(m => $"player:{m.PlayerName} level:{m.PlayerLevel} pokemon:{m.PokemonId} cp:{m.PokemonCp}")));
                UpdateBindableData();
                break;

            case GetGymDetailsResponse.Types.Result.ErrorNotInRange:
                Logger.Write("Entering Gym out of range");
                var dialog2 = new MessageDialog("Gym is completely out of range");
                await dialog2.ShowAsync();

                ReturnToGameScreen.Execute();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(response.Result), "GetGymDetails result enum had something undefined");
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="parameter">FortData containing the Pokestop that we're visiting</param>
        /// <param name="mode"></param>
        /// <param name="suspensionState"></param>
        /// <returns></returns>
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
                                                      IDictionary <string, object> suspensionState)
        {
            if (suspensionState.Any())
            {
                // Recovering the state
                CurrentPokestopInfo        = new FortDetailsResponse();
                CurrentSearchResponse      = new FortSearchResponse();
                SelectedModifierItem       = new ItemData();
                CurrentAddModifierResponse = new AddFortModifierResponse();
                CurrentPokestop            = JsonConvert.DeserializeObject <FortDataWrapper>((string)suspensionState[nameof(CurrentPokestop)]);
                CurrentPokestopInfo.MergeFrom(ByteString.FromBase64((string)suspensionState[nameof(CurrentPokestop)]).CreateCodedInput());
                CurrentSearchResponse.MergeFrom(ByteString.FromBase64((string)suspensionState[nameof(CurrentSearchResponse)]).CreateCodedInput());
                SelectedModifierItem.MergeFrom(ByteString.FromBase64((string)suspensionState[nameof(SelectedModifierItem)]).CreateCodedInput());
                CurrentAddModifierResponse.MergeFrom(ByteString.FromBase64((string)suspensionState[nameof(CurrentAddModifierResponse)]).CreateCodedInput());
                RaisePropertyChanged(() => CurrentPokestopInfo);
                RaisePropertyChanged(() => CurrentSearchResponse);
                RaisePropertyChanged(() => SelectedModifierItem);
                RaisePropertyChanged(() => CurrentAddModifierResponse);
            }
            else
            {
                // Navigating from game page, so we need to actually load the Pokestop
                Busy.SetBusy(true, "Loading Pokestop");
                CurrentPokestop = (FortDataWrapper)NavigationHelper.NavigationState[nameof(CurrentPokestop)];
                NavigationHelper.NavigationState.Remove(nameof(CurrentPokestop));
                Logger.Info($"Searching {CurrentPokestop.Id}");
                CurrentPokestopInfo =
                    await GameClient.GetFort(CurrentPokestop.Id, CurrentPokestop.Latitude, CurrentPokestop.Longitude);

                Busy.SetBusy(false);
                // If timeout is expired we can go to to pokestop page
                if (CurrentPokestop.CooldownCompleteTimestampMs >= DateTime.UtcNow.ToUnixTime())
                {
                    // Timeout is not expired yet, player can't get items from the fort
                    SearchInCooldown?.Invoke(null, null);
                }
            }
        }
Пример #4
0
        public async Task LoadViewModel(string id)
        {
            try
            {
                Busy.SetBusy(true, "Laddar tråden...");
                Error        = null;
                _requestedId = id;

                if (!id.Contains("#") && !id.StartsWith("p") && !id.StartsWith("sp") && _settings.UseSmartNavigation && !_firstLoadDone)
                {
                    // Så länge vi inte navigerar till ett specifikt citerat inlägg och kör med inställningen smartnavigering
                    // så kollat vi om vi har besökt tråden tidigare. Har vi det hoppar vi till senast besökta sida i den.
                    var lastVisitedPageNumber = await _fileService.GetLastVisitedPageForThread(id.GetCleanId(false));

                    if (lastVisitedPageNumber.HasValue)
                    {
                        id = id.GetCleanId(false).GetCleanIdForPage(lastVisitedPageNumber.Value);
                    }
                }

                ForumThread = await _threadService.GetForumThread(id);

                _firstLoadDone = true;

                // spara ner senaste besökta sida om vi använder smartnavigering
                if (_settings.UseSmartNavigation)
                {
                    await _fileService.SaveLastVisitedPageNumber(id.GetCleanId(false), ForumThread.CurrentPage);
                }
            }
            catch (Exception e)
            {
                Error = e.ToString();
            }
            finally
            {
                Busy.SetBusy(false);
            }
        }
Пример #5
0
        public async Task Save()
        {
            using (var busy = Busy.GetTicket())
            {
                GameResultModel gameResult = null;
                var             added      = false;
                if (LastGameId == null)
                {
                    gameResult = new GameResultModel();
                    added      = true;
                }
                else
                {
                    // gameResult = (await gameRepository.FirstOrDefaultAsync(x => x.Id == this.LastGameId)).ToModel();
                    gameResult = SelectedGame;
                }

                SetGameResult(gameResult);

                if (ArenaSession != null)
                {
                    gameResult.ArenaSession = ArenaSession;
                }

                if (added)
                {
                    await gameManager.AddGame(gameResult);
                }
                else
                {
                    await gameManager.UpdateGame(gameResult);
                }

                events.PublishOnBackgroundThread(new SendNotification("Game successfully saved."));
                LastGameId = gameResult.Id;
                LoadGameResult(gameResult);
            }
        }
Пример #6
0
        /// <summary>
        /// </summary>
        /// <param name="parameter">FortData containing the Gym that we're visiting</param>
        /// <param name="mode"></param>
        /// <param name="suspensionState"></param>
        /// <returns></returns>
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
                                                      IDictionary <string, object> suspensionState)
        {
            if (suspensionState.Any())
            {
                // Recovering the state
                CurrentGym           = JsonConvert.DeserializeObject <FortDataWrapper>((string)suspensionState[nameof(CurrentGym)]);
                CurrentGymInfo       = JsonConvert.DeserializeObject <GetGymDetailsResponse>((string)suspensionState[nameof(CurrentGymInfo)]);
                CurrentEnterResponse = JsonConvert.DeserializeObject <GetGymDetailsResponse>((string)suspensionState[nameof(CurrentEnterResponse)]);
            }
            else
            {
                // Navigating from game page, so we need to actually load the Gym
                Busy.SetBusy(true, "Loading Gym");
                CurrentGym = (FortDataWrapper)NavigationHelper.NavigationState[nameof(CurrentGym)];
                NavigationHelper.NavigationState.Remove(nameof(CurrentGym));
                Logger.Write($"Entering {CurrentGym.Id}");
                CurrentGymInfo =
                    await GameClient.GetGymDetails(CurrentGym.Id, CurrentGym.Latitude, CurrentGym.Longitude);

                Busy.SetBusy(false);
            }
        }
Пример #7
0
        /// <summary>
        ///     Gets player's inventoryDelta
        /// </summary>
        /// <returns></returns>
        public static async Task <LevelUpRewardsResponse> UpdatePlayerStats(bool checkForLevelUp = false)
        {
            InventoryDelta = (await _client.Inventory.GetInventory()).InventoryDelta;

            var tmpStats =
                InventoryDelta.InventoryItems.First(item => item.InventoryItemData.PlayerStats != null)
                .InventoryItemData.PlayerStats;

            if (checkForLevelUp && ((PlayerStats == null) || (PlayerStats != null && PlayerStats.Level != tmpStats.Level)))
            {
                PlayerStats = tmpStats;
                var levelUpResponse = await GetLevelUpRewards(tmpStats.Level);
                await UpdateInventory();

                // Set busy to false because initial loading may have left it going until we had PlayerStats
                Busy.SetBusy(false);
                return(levelUpResponse);
            }
            PlayerStats = tmpStats;
            // Set busy to false because initial loading may have left it going until we had PlayerStats
            Busy.SetBusy(false);
            return(null);
        }
Пример #8
0
 internal void UpdateWorkingStatus(string Message, string SubMessage, ulong?CurrentProgressValue, WPinternalsStatus Status = WPinternalsStatus.Undefined)
 {
     if (SubContextViewModel is BusyViewModel Busy)
     {
         if (Message != null)
         {
             Busy.Message    = Message;
             Busy.SubMessage = SubMessage;
         }
         if ((CurrentProgressValue != null) && (Busy.ProgressUpdater != null))
         {
             try
             {
                 Busy.ProgressUpdater.SetProgress((ulong)CurrentProgressValue);
             }
             catch (Exception Ex)
             {
                 LogFile.LogException(Ex);
             }
         }
         Busy.SetShowRebootHelp(Status == WPinternalsStatus.WaitingForManualReset);
     }
 }
Пример #9
0
        private void OnTimerElapsed(object sender, ElapsedEventArgs args)
        {
            try
            {
                IdleScanAnalysis analysis = new IdleScanAnalysis(this);

                Scan?.Invoke(this, analysis);

                try
                {
                    if (analysis.Busy)
                    {
                        IdleCount = 0;

                        Busy?.Invoke(this, analysis);
                    }
                    else
                    {
                        IdleCount++;

                        Idle?.Invoke(this, analysis);
                    }
                }
                catch (Exception e)
                {
                    EventLog.WriteEntry(e.ToString(), EventLogEntryType.Error, 18);

                    analysis.Error = true;
                }

                Eval?.Invoke(this, analysis);
            }
            catch (Exception e)
            {
                EventLog.WriteEntry(e.ToString(), EventLogEntryType.Error, 19);
            }
        }
Пример #10
0
        public static async Task HandleException(Exception e = null)
        {
            if (e != null && (e.GetType().FullName.Contains("ApiHandledException") || e.Message == "Relogin completed."))
            {
                Debug.WriteLine("[Relogin] ApiHandledException from API handled.");
                Debug.WriteLine("[Relogin] Successfuly ended.");
            }
            else if (e != null && e.GetType().Namespace.Equals("PokemonGo.RocketAPI.Exceptions"))
            {
                await
                new MessageDialog(Resources.CodeResources.GetString("LoginExpired")).ShowAsyncQueue();
                GameClient.DoLogout();
                BootStrapper.Current.NavigationService.Navigate(typeof(MainPage));
            }
            else
            {
                var dialog = new MessageDialog(Resources.CodeResources.GetString("SomethingWentWrongText"));
                dialog.Commands.Add(new UICommand(Resources.CodeResources.GetString("YesText"))
                {
                    Id = 0
                });
                dialog.Commands.Add(new UICommand(Resources.CodeResources.GetString("NoText"))
                {
                    Id = 1
                });
                dialog.DefaultCommandIndex = 0;
                dialog.CancelCommandIndex  = 1;
                var result = await dialog.ShowAsyncQueue();

                if ((int)result.Id == 0)
                {
                    GameClient.DoLogout();
                    BootStrapper.Current.NavigationService.Navigate(typeof(MainPage));
                    Busy.SetBusy(false);
                }
            }
        }
        public async Task PostMessage()
        {
            if (string.IsNullOrWhiteSpace(Subject) || string.IsNullOrWhiteSpace(To) || string.IsNullOrWhiteSpace(Message))
            {
                Messenger.Default.Send <string>("Ej fullständiga uppgifter ifyllda för att kunna skicka", FlashbackConstants.MessengerShowError);
                return;
            }

            try
            {
                MayPost = false;

                Busy.SetBusy(true, "Skickar meddelande...");
                Error = null;

                var result = await _messageService.PostMessage(To, Subject, Message, PostToken);

                if (result)
                {
                    Messenger.Default.Send <string>("Meddelandet är skickat!", FlashbackConstants.MessengerShowInformation);
                }
                else
                {
                    Messenger.Default.Send <string>("Något gick fel vid skickande av meddelande", FlashbackConstants.MessengerShowError);
                }
            }
            catch (Exception e)
            {
                Error = e.Message;
            }
            finally
            {
                Busy.SetBusy(false);
                MayPost = true;
            }
        }
        public async Task LoadViewModel()
        {
            try
            {
                Busy.SetBusy(true, "Laddar...");
                Error = null;

                var result = await _messageService.NewPrivateMessage(Id);

                Id        = result.Id;
                PostToken = result.PostToken;
                Message   = result.Message;
                To        = result.To;
                Subject   = result.Subject;
            }
            catch (Exception e)
            {
                Error = e.ToString();
            }
            finally
            {
                Busy.SetBusy(false);
            }
        }
Пример #13
0
        public async void Search(bool cache)
        {
            try
            {
                using (Busy.GetTicket())
                {
                    if (string.IsNullOrEmpty(SearchText))
                    {
                        Start();
                        return;
                    }

                    Expression <Func <Customer, bool> > predicate = x => x.CompanyName.Contains(SearchText);
                    Func <IQueryable <Customer>, IOrderedQueryable <Customer> > orderBy = q => q.OrderBy(x => x.CompanyName);

                    Customers = new BindableCollection <Customer>(
                        cache ? UnitOfWork.Entities.FindInCache(predicate, orderBy) : await UnitOfWork.Entities.FindAsync(predicate, orderBy));
                }
            }
            catch (Exception e)
            {
                ErrorHandler.Handle(e);
            }
        }
Пример #14
0
        public async void Start()
        {
            try
            {
                using (Busy.GetTicket())
                {
                    Func <IQueryable <Customer>, IOrderedQueryable <Customer> > orderBy = q => q.OrderBy(x => x.CompanyName);

                    if (!string.IsNullOrEmpty(SearchText))
                    {
                        Search(IsRestored);
                    }
                    else
                    {
                        Customers = new BindableCollection <Customer>(
                            IsRestored ? UnitOfWork.Entities.AllInCache(orderBy) : await UnitOfWork.Entities.AllAsync(orderBy));
                    }
                }
            }
            catch (Exception e)
            {
                ErrorHandler.Handle(e);
            }
        }
Пример #15
0
        /// <summary>
        /// Takes the photo.
        /// </summary>
        public void TakePhoto()
        {
            if (_context != null && _cameraDevice != null)
            {
                try
                {
                    Busy?.Invoke(this, true);

                    if (_mediaSoundLoaded)
                    {
                        _mediaSound.Play(MediaActionSoundType.ShutterClick);
                    }

                    // Pick the best JPEG size that can be captures with this CameraDevice
                    var    characteristics = _manager.GetCameraCharacteristics(_cameraDevice.Id);
                    Size[] jpegSizes       = null;
                    if (characteristics != null)
                    {
                        jpegSizes = ((StreamConfigurationMap)characteristics.Get(CameraCharacteristics.ScalerStreamConfigurationMap)).GetOutputSizes((int)ImageFormatType.RawSensor);
                    }
                    int width  = 640;
                    int height = 480;

                    if (jpegSizes != null && jpegSizes.Length > 0)
                    {
                        width  = jpegSizes[0].Width;
                        height = jpegSizes[0].Height;
                    }

                    // We use an ImageReader to get a JPEG from CameraDevice
                    // Here, we create a new ImageReader and prepare its Surface as an output from the camera
                    var reader         = ImageReader.NewInstance(width, height, ImageFormatType.Jpeg, 1);
                    var outputSurfaces = new List <Surface>(2);
                    outputSurfaces.Add(reader.Surface);
                    outputSurfaces.Add(new Surface(_viewSurface));

                    CaptureRequest.Builder captureBuilder = _cameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
                    captureBuilder.AddTarget(reader.Surface);
                    captureBuilder.Set(CaptureRequest.ControlMode, new Integer((int)ControlMode.Auto));

                    // Orientation
                    var windowManager           = _context.GetSystemService(Context.WindowService).JavaCast <IWindowManager>();
                    SurfaceOrientation rotation = windowManager.DefaultDisplay.Rotation;

                    captureBuilder.Set(CaptureRequest.JpegOrientation, new Integer(ORIENTATIONS.Get((int)rotation)));

                    // This listener is called when an image is ready in ImageReader
                    ImageAvailableListener readerListener = new ImageAvailableListener();

                    readerListener.ImageProcessingCompleted += (sender, e) =>
                    {
                        Photo?.Invoke(this, e);
                    };

                    // We create a Handler since we want to handle the resulting JPEG in a background thread
                    HandlerThread thread = new HandlerThread("CameraPicture");
                    thread.Start();
                    Handler backgroundHandler = new Handler(thread.Looper);
                    reader.SetOnImageAvailableListener(readerListener, backgroundHandler);

                    var captureListener = new CameraCaptureListener();

                    captureListener.PhotoComplete += (sender, e) =>
                    {
                        Busy?.Invoke(this, false);
                        StartPreview();
                    };

                    _cameraDevice.CreateCaptureSession(outputSurfaces, new CameraCaptureStateListener()
                    {
                        OnConfiguredAction = (CameraCaptureSession session) =>
                        {
                            try
                            {
                                _previewSession = session;
                                session.Capture(captureBuilder.Build(), captureListener, backgroundHandler);
                            }
                            catch (CameraAccessException ex)
                            {
                                Log.WriteLine(LogPriority.Info, "Capture Session error: ", ex.ToString());
                            }
                        }
                    }, backgroundHandler);
                }
                catch (CameraAccessException error)
                {
                    Log.WriteLine(LogPriority.Error, error.Source, error.Message);
                }
                catch (Java.Lang.Exception error)
                {
                    Log.WriteLine(LogPriority.Error, error.Source, error.Message);
                }
            }
        }
Пример #16
0
        public override void RefreshData()
        {
            if (refreshing)
            {
                return;
            }
            refreshing = true;
            LoadData();
            DeckStats.Clear();
            var newstats = new BindableCollection <IDictionary <Deck, IList <StatModel> > >();

            Task.Run(
                () =>
            {
                using (Busy.GetTicket())
                {
                    foreach (Deck deck in Decks)
                    {
                        if (!String.IsNullOrEmpty(GameMode))
                        {
                            var gameMode = (GameMode)Enum.Parse(typeof(GameMode), GameMode);
                            if (gameMode == Data.GameMode.Arena)
                            {
                                var emptystats = new Dictionary <Deck, IList <StatModel> >();
                                newstats.Add(emptystats);
                                var emptylst = new List <StatModel>();
                                emptystats.Add(deck, emptylst);
                                emptylst.AddRange(Heroes.Select(h => new StatModel()
                                {
                                    Hero = h
                                }));
                                continue;
                            }
                        }

                        var r =
                            gameRepository.Query(
                                x =>
                        {
                            var q     = x.Where(g => g.Deck.Id == deck.Id);
                            q         = q.Where(GetFilterExpression());
                            var group = q
                                        .Where(g => q.Any())
                                        .GroupBy(g => g.OpponentHero.Key)
                                        .Select(
                                g =>
                                new
                            {
                                HeroKey      = g.Key,
                                GlobalTotal  = q.Count(),
                                Total        = g.Count(),
                                TotalCoin    = g.Count(c => !c.GoFirst),
                                TotalNoCoin  = g.Count(c => c.GoFirst),
                                Wins         = g.Count(c => c.Victory),
                                Losses       = g.Count(c => !c.Victory),
                                WinsCoin     = g.Count(c => c.Victory && !c.GoFirst),
                                WinsNoCoin   = g.Count(c => c.Victory && c.GoFirst),
                                LossesCoin   = g.Count(c => !c.Victory && !c.GoFirst),
                                LossesNoCoin = g.Count(c => !c.Victory && c.GoFirst)
                            });
                            return(group.ToList());
                        });
                        if (r.Sum(x => x.GlobalTotal) == 0)
                        {
                            continue;
                        }
                        var stats = new Dictionary <Deck, IList <StatModel> >();
                        newstats.Add(stats);
                        var lst = new List <StatModel>();
                        stats.Add(deck, lst);
                        for (int i = 0; i < Heroes.Count; i++)
                        {
                            var oppHero    = Heroes[i];
                            dynamic result = null;
                            if (oppHero.Key != null)
                            {
                                result = r.FirstOrDefault(x => x.HeroKey == oppHero.Key);
                            }
                            else
                            {
                                result = new
                                {
                                    HeroKey      = String.Empty,
                                    GlobalTotal  = r.Sum(x => x.Total),
                                    Total        = r.Sum(x => x.Total),
                                    TotalCoin    = r.Sum(x => x.TotalCoin),
                                    TotalNoCoin  = r.Sum(x => x.TotalNoCoin),
                                    Wins         = r.Sum(x => x.Wins),
                                    Losses       = r.Sum(x => x.Losses),
                                    WinsCoin     = r.Sum(x => x.WinsCoin),
                                    WinsNoCoin   = r.Sum(x => x.WinsNoCoin),
                                    LossesCoin   = r.Sum(x => x.LossesCoin),
                                    LossesNoCoin = r.Sum(x => x.LossesNoCoin)
                                };
                            }
                            if (result == null)
                            {
                                lst.Add(new StatModel()
                                {
                                    Hero = oppHero
                                });
                            }
                            else
                            {
                                lst.Add(
                                    new StatModel()
                                {
                                    Hero         = oppHero,
                                    TotalGames   = result.Total,
                                    GlobalTotal  = result.GlobalTotal,
                                    Wins         = result.Wins,
                                    Losses       = result.Losses,
                                    WinsCoin     = result.WinsCoin,
                                    WinsNoCoin   = result.WinsNoCoin,
                                    LossesCoin   = result.LossesCoin,
                                    LossesNoCoin = result.LossesNoCoin,
                                    WinRate      = result.Total > 0 ? Math.Round((decimal)result.Wins / result.Total * 100, 0) : 0,
                                    LossRate     = result.Total > 0 ? Math.Round((decimal)result.Losses / result.Total * 100, 0) : 0,
                                    WinRateCoin  =
                                        result.TotalCoin > 0 ? Math.Round((decimal)result.WinsCoin / result.TotalCoin * 100, 0) : 0,
                                    WinRateNoCoin =
                                        result.TotalNoCoin > 0 ? Math.Round((decimal)result.WinsNoCoin / result.TotalNoCoin * 100, 0) : 0,
                                    LossRateCoin =
                                        result.TotalCoin > 0 ? Math.Round((decimal)result.LossesCoin / result.TotalCoin * 100, 0) : 0,
                                    LossRateNoCoin =
                                        result.TotalNoCoin > 0 ? Math.Round((decimal)result.LossesNoCoin / result.TotalNoCoin * 100, 0) : 0
                                });
                            }
                        }
                    }
                    refreshing = false;
                }
            }).ContinueWith(
                t =>
            {
                using (Busy.GetTicket())
                {
                    DeckStats.IsNotifying = false;
                    DeckStats.Clear();
                    DeckStats.AddRange(newstats);
                    DeckStats.IsNotifying = true;
                    DeckStats.Refresh();
                }
            });;
        }
Пример #17
0
 protected void OnBusy(string str)
 {
     Busy?.Invoke(this, str);
 }
Пример #18
0
        private async Task Save()
        {
            using (var bsy = Busy.GetTicket())
            {
                var gameResult = new GameResultModel();
                ArenaSessionModel arenasession = null;
                var newArena = false;
                gameResult.GameMode = GameMode;
                gameResult.Conceded = Conceded;

                if (Deck != null)
                {
                    gameResult.Deck = Deck;
                }

                gameResult.GoFirst      = GoFirst;
                gameResult.Hero         = Hero;
                gameResult.OpponentHero = OpponentHero;
                gameResult.Started      = StartTime;
                gameResult.Stopped      = Stopped;
                gameResult.Turns        = Turns;
                gameResult.Victory      = Victory;
                gameResult.Notes        = Notes;
                gameResult.Server       = BindableServerCollection.Instance.DefaultName;

                if (gameResult.GameMode == GameMode.Arena)
                {
                    var serverName  = gameResult.Server;
                    var latestArena = arenaRepository.Query(a => a.Where(x => x.Server == serverName).OrderByDescending(x => x.StartDate).FirstOrDefault());
                    if (latestArena == null
                        ||
                        latestArena.IsEnded
                        ||
                        (gameResult.Hero != null && latestArena.Hero.Key != gameResult.Hero.Key))
                    {
                        Log.Debug("Creating new arena.");
                        newArena     = true;
                        arenasession = new ArenaSessionModel
                        {
                            Hero      = gameResult.Hero,
                            StartDate = gameResult.Started
                        };
                        try
                        {
                            GlobalLocks.NewArenaLock.Reset();
                            await gameManager.AddArenaSession(arenasession);
                        }
                        finally
                        {
                            GlobalLocks.NewArenaLock.Set();
                        }
                    }
                    else
                    {
                        arenasession = latestArena.ToModel();
                    }
                    gameResult.ArenaSession = arenasession;
                }
                await gameManager.AddGame(gameResult);

                // for webapi
                if (arenasession != null)
                {
                    if (newArena)
                    {
                        events.PublishOnBackgroundThread(new ArenaSessionStarted(arenasession.StartDate, arenasession.Hero.Key, arenasession.Wins, arenasession.Losses));
                    }
                    else
                    {
                        if (arenasession.IsEnded &&
                            arenasession.EndDate.HasValue)
                        {
                            events.PublishOnBackgroundThread(new ArenaSessionEnded(arenasession.StartDate, arenasession.EndDate.Value, arenasession.Hero.Key, arenasession.Wins, arenasession.Losses));
                        }
                    }
                }

                // notifications
                //var wonString = gameResult.Victory ? "You won!" : "You lost!";

                var title = "New game tracked.";
                //var hero = gameResult.Hero != null ? gameResult.Hero.ClassName : String.Empty;
                //var oppHero = gameResult.OpponentHero != null ? gameResult.OpponentHero.ClassName : String.Empty;
                //var msg = string.Format("Hero: {0}, Opponent: {1}, {2}", hero, oppHero, wonString);
                //events.PublishOnBackgroundThread(new SendNotification(String.Format("{0} {1}", title, msg)));

                var vm = IoC.Get <GameResultBalloonViewModel>();
                vm.SetGameResult(gameResult);
                events.PublishOnBackgroundThread(new TrayNotification(title, vm, 10000)
                {
                    BalloonType = BalloonTypes.GameStartEnd
                });

                // reset
                Clear();
                IsOpen = false;
            }
        }
Пример #19
0
        private void LoadMore(bool clearValues = false)
        {
            Application.Current.Dispatcher.BeginInvoke(
                (Action)(async() =>
            {
                if (needRefresh)
                {
                    needRefresh = false;
                    if (loadMoreTicket != null)
                    {
                        return;
                    }
                    loadMoreTicket = Busy.GetTicket();
                    await Task.Run(
                        async() =>
                    {
                        if (clearValues)
                        {
                            arenaSessions.Clear();
                        }
                        var newarenas = new List <ArenaSessionModel>();
                        var result = await arenaRepository.ToListAsync(
                            query =>
                        {
                            query = query.Where(GetFilterExpression());
                            query = AddOrderByExpression(query);
                            return(query.Skip(clearValues ? 0 : arenaSessions.Count)
                                   .Take(50));
                        });
                        totalCount = arenaRepository.Query(x => x.Where(GetFilterExpression()).Count());

                        foreach (var arena in result.ToModel())
                        {
                            newarenas.Add(arena);
                            if (ArenaViewModel.IsOpen
                                &&
                                ArenaViewModel.SelectedArenaSession != null
                                &&
                                SelectedArenaSession != null
                                &&
                                SelectedArenaSession.Id == arena.Id)
                            {
                                SelectedArenaSession = arena;
                            }
                            if (SelectedGame != null
                                &&
                                EditGameViewModel.IsOpen
                                &&
                                EditGameViewModel.SelectedGame != null
                                &&
                                SelectedGame != null)
                            {
                                var hasgame = arena.Games.FirstOrDefault(x => x.Id == SelectedGame.Id);
                                if (hasgame != null)
                                {
                                    SelectedGame = hasgame;
                                }
                            }
                        }

                        arenaSessions.AddRange(newarenas);
                        loadMoreTicket.Dispose();
                        loadMoreTicket = null;

                        // does not work nicely
                        //if (EditGameFlyout.IsOpen && EditGameFlyout.SelectedGame != null)
                        //{
                        //    Handle(new SelectedGameChanged(EditGameFlyout, EditGameFlyout.SelectedGame.Id));
                        //}
                        //else
                        //{
                        //    if (ArenaViewModel.IsOpen && ArenaViewModel.SelectedArenaSession != null)
                        //    {
                        //        var selected = this.arenaSessions.FirstOrDefault(x => x.Id == ArenaViewModel.SelectedArenaSession.Id);
                        //        this.SelectedArenaSession = selected;
                        //    }
                        //}
                    });
                }
            }),
                DispatcherPriority.ContextIdle);
        }
Пример #20
0
        /// <summary>
        ///     Starts the timer to update map objects and the handler to update position
        /// </summary>
        public static async Task InitializeDataUpdate()
        {
            #region Compass management
            SettingsService.Instance.PropertyChanged += (object sender, PropertyChangedEventArgs e) =>
            {
                if (e.PropertyName == nameof(SettingsService.Instance.MapAutomaticOrientationMode))
                {
                    switch (SettingsService.Instance.MapAutomaticOrientationMode)
                    {
                    case MapAutomaticOrientationModes.Compass:
                        _compass = Compass.GetDefault();
                        _compass.ReportInterval  = Math.Max(_compass.MinimumReportInterval, 50);
                        _compass.ReadingChanged += compass_ReadingChanged;
                        break;

                    case MapAutomaticOrientationModes.None:
                    case MapAutomaticOrientationModes.GPS:
                    default:
                        if (_compass != null)
                        {
                            _compass.ReadingChanged -= compass_ReadingChanged;
                            _compass = null;
                        }
                        break;
                    }
                }
            };
            //Trick to trigger the PropertyChanged for MapAutomaticOrientationMode ;)
            SettingsService.Instance.MapAutomaticOrientationMode = SettingsService.Instance.MapAutomaticOrientationMode;
            #endregion
            _geolocator = new Geolocator
            {
                DesiredAccuracy         = PositionAccuracy.High,
                DesiredAccuracyInMeters = 5,
                ReportInterval          = 1000,
                MovementThreshold       = 5
            };

            Busy.SetBusy(true, Resources.CodeResources.GetString("GettingGpsSignalText"));
            Geoposition = Geoposition ?? await _geolocator.GetGeopositionAsync();

            GeopositionUpdated?.Invoke(null, Geoposition);
            _geolocator.PositionChanged += GeolocatorOnPositionChanged;
            // Before starting we need game settings
            GameSetting =
                await
                DataCache.GetAsync(nameof(GameSetting), async() => (await _client.Download.GetSettings()).Settings,
                                   DateTime.Now.AddMonths(1));

            // Update geolocator settings based on server
            _geolocator.MovementThreshold = GameSetting.MapSettings.GetMapObjectsMinDistanceMeters;
            if (_heartbeat == null)
            {
                _heartbeat = new Heartbeat();
            }
            await _heartbeat.StartDispatcher();

            // Update before starting timer
            Busy.SetBusy(true, Resources.CodeResources.GetString("GettingUserDataText"));
            //await UpdateMapObjects();
            await UpdateInventory();
            await UpdateItemTemplates();

            Busy.SetBusy(false);
        }
Пример #21
0
            internal async void ProcessAsync(object sender, EventArgs e)
            {
                try
                {
                    if (!Enabled)
                    {
                        return;
                    }

                    Logger.Debug("{0}光栅触发", scaleOperator.Name);

                    if (IsBusy)
                    {
                        return;
                    }
                    IsBusy = true;
                    Busy?.Invoke(this, new EventArgs());

                    await scaleOperator.SwitchRelayAsync(false);//turn red

                    double        weight = 0;
                    GetWtResponse resp   = null;
                    for (int i = 1; i <= 5; i++)
                    {
                        Logger.Debug("[{0}]请求重量", scaleOperator.Name);
                        resp = await scaleOperator.RestClient.GetWtAsync(scaleOperator.ScaleIP, scaleOperator.InOrOut.ToString());

                        Logger.Debug("[{0}]返回重量{1}", scaleOperator.Name, resp.wt_num);

                        /*GetWtResponse resp = new GetWtResponse()
                         * {
                         *  status = "1",
                         *  tk_no = "辽A 88888888",
                         *  wt_num = "1000.88"
                         * };*/
                        if (resp.status == "0")
                        {
                            //Progress?.Invoke(this, new ProgressEventArgs("请求重量失败"));
                            Logger.Warn("称重失败");
                            await Task.Delay(1000);

                            continue;
                        }
                        var w = Convert.ToDouble(resp.wt_num);
                        if (w > 1000)
                        {
                            Logger.Debug("称重大于1000");
                            weight = w;
                            break;
                        }
                        await Task.Delay(1000);
                    }
                    if (weight < 1000)
                    {
                        Logger.Debug("称重小于1000, 开始抬杆");
                        Logger.Debug("[{0}]请求抬杆", scaleOperator.Name);
                        GatePassResponse gpResp = await scaleOperator.RestClient.GatePassAsync(scaleOperator.ScaleIP, scaleOperator.InOrOut.ToString(), resp.tk_no, resp.wt_num);

                        Logger.Debug("[{0}]返回抬杆", scaleOperator.Name);

                        /*GatePassResponse gpResp = new GatePassResponse()
                         * {
                         *  status = 1
                         * };*/
                        if (gpResp.status == "0")//抬杆失败
                        {
                            //Progress?.Invoke(this, new ProgressEventArgs("抬杆失败"));
                            Logger.Warn("抬杆失败:" + gpResp.reason);
                            //SwitchRelay(false);//no need to call this, it's already red
                        }
                        else if (gpResp.status == "1")
                        {
                            Logger.Info("抬杆成功");
                            //Progress?.Invoke(this, new ProgressEventArgs("抬杆成功"));
                            //SwitchRelay(true);
                        }
                        FakeCar?.Invoke(this, new EventArgs());
                    }
                }
                catch (Exception ex)
                {
                    Error?.Invoke(this, new EventArgs());
                    Logger.Debug("处理前光栅事件发生异常:{0}", ex.Message);
                }
                finally
                {
                    IsBusy = false;
                }
            }
Пример #22
0
        public static async Task HandleException(Exception e = null)
        {
            try
            {
                if (e != null && (e.GetType() == typeof(ApiNonRecoverableException)))
                {
                    Debug.WriteLine($"[Relogin] {nameof(ApiNonRecoverableException)} from API handled.");
                    Debug.WriteLine("[Relogin] Successfuly ended.");
                }
                else if (e != null && e.GetType() == (typeof(AccessTokenExpiredException)))
                {
                    await
                    new MessageDialog(Resources.CodeResources.GetString("LoginExpired")).ShowAsyncQueue();
                    GameClient.DoLogout();
                    BootStrapper.Current.NavigationService.Navigate(typeof(MainPage));
                }
                else if (e != null && e.GetType() == (typeof(AccountLockedException)))
                {
                    await
                    new MessageDialog("Account locked/banned").ShowAsyncQueue();
                    GameClient.DoLogout();
                    BootStrapper.Current.NavigationService.Navigate(typeof(MainPage));
                }
                else
                {
                    bool showDebug = false;
                    try
                    {
                        //get inside try/catch in case exception comes from settings instance (storage access issue, ...)
                        showDebug = SettingsService.Instance.ShowDebugInfoInErrorMessage;
                    }
                    catch { }

                    string message = Resources.CodeResources.GetString("SomethingWentWrongText");
                    if (showDebug)
                    {
                        message += $"\nException";
                        message += $"\n Message:[{e?.Message}]";
                        message += $"\n InnerMessage:[{e?.InnerException?.Message}]";
                        message += $"\n StackTrace:[{e?.StackTrace}]";
                    }

                    var dialog = new MessageDialog(message);
                    dialog.Commands.Add(new UICommand(Resources.CodeResources.GetString("YesText"))
                    {
                        Id = 0
                    });
                    dialog.Commands.Add(new UICommand(Resources.CodeResources.GetString("NoText"))
                    {
                        Id = 1
                    });
                    dialog.DefaultCommandIndex = 0;
                    dialog.CancelCommandIndex  = 1;
                    var result = await dialog.ShowAsyncQueue();

                    if ((int)result.Id == 0)
                    {
                        GameClient.DoLogout();
                        BootStrapper.Current.NavigationService.Navigate(typeof(MainPage));
                        Busy.SetBusy(false);
                    }
                }
            }
            catch (Exception ex)
            {
                HockeyClient.Current.TrackException(ex);
                Application.Current.Exit();
            }
        }
Пример #23
0
 private void OnBusy(object sender, EventArgs e)
 {
     Busy?.Invoke(this, new EventArgs());
     _idleTimer.Stop();
 }
Пример #24
0
        /// <summary>
        /// Encounter logic
        /// </summary>
        /// <returns></returns>
        private async Task HandleEncounter()
        {
            if (CurrentPokemon is MapPokemonWrapper)
            {
                CurrentEncounter = await GameClient.EncounterPokemon(CurrentPokemon.EncounterId, CurrentPokemon.SpawnpointId);

                switch (CurrentEncounter.Status)
                {
                case EncounterResponse.Types.Status.PokemonInventoryFull:
                    await new MessageDialog(string.Format(Resources.CodeResources.GetString("PokemonInventoryFullText"), Resources.Pokemon.GetString($"{CurrentPokemon.PokemonId}"))).ShowAsyncQueue();
                    ReturnToGameScreen.Execute();
                    break;

                case EncounterResponse.Types.Status.EncounterSuccess:
                    break;

                case EncounterResponse.Types.Status.EncounterError:
                case EncounterResponse.Types.Status.EncounterNotFound:
                case EncounterResponse.Types.Status.EncounterClosed:
                    await new MessageDialog(string.Format(Resources.CodeResources.GetString("PokemonEncounterErrorText"), Resources.Pokemon.GetString($"{CurrentPokemon.PokemonId}"))).ShowAsyncQueue();
                    ReturnToGameScreen.Execute();
                    break;

                case EncounterResponse.Types.Status.EncounterNotInRange:
                    await new MessageDialog(string.Format(Resources.CodeResources.GetString("PokemonEncounterNotInRangeText"), Resources.Pokemon.GetString($"{CurrentPokemon.PokemonId}"))).ShowAsyncQueue();
                    ReturnToGameScreen.Execute();
                    break;

                case EncounterResponse.Types.Status.EncounterPokemonFled:
                case EncounterResponse.Types.Status.EncounterAlreadyHappened:
                    await new MessageDialog(Resources.CodeResources.GetString("PokemonRanAwayText")).ShowAsyncQueue();
                    ReturnToGameScreen.Execute();
                    GameClient.CatchablePokemons.Remove((MapPokemonWrapper)CurrentPokemon);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else
            {
                CurrentLureEncounter = await GameClient.EncounterLurePokemon(CurrentPokemon.EncounterId, CurrentPokemon.SpawnpointId);

                CurrentEncounter = new EncounterResponse()
                {
                    Background  = EncounterResponse.Types.Background.Park,
                    WildPokemon = new WildPokemon()
                    {
                        PokemonData = CurrentLureEncounter.PokemonData
                    }
                };
                switch (CurrentLureEncounter.Result)
                {
                case DiskEncounterResponse.Types.Result.PokemonInventoryFull:
                    await new MessageDialog(string.Format(Resources.CodeResources.GetString("PokemonInventoryFullText"), Resources.Pokemon.GetString($"{CurrentPokemon.PokemonId}"))).ShowAsyncQueue();
                    ReturnToGameScreen.Execute();
                    break;

                case DiskEncounterResponse.Types.Result.Success:
                    break;

                case DiskEncounterResponse.Types.Result.Unknown:
                case DiskEncounterResponse.Types.Result.NotAvailable:
                    await new MessageDialog(string.Format(Resources.CodeResources.GetString("PokemonEncounterErrorText"), Resources.Pokemon.GetString($"{CurrentPokemon.PokemonId}"))).ShowAsyncQueue();
                    ReturnToGameScreen.Execute();
                    break;

                case DiskEncounterResponse.Types.Result.NotInRange:
                    await new MessageDialog(string.Format(Resources.CodeResources.GetString("PokemonEncounterNotInRangeText"), Resources.Pokemon.GetString($"{CurrentPokemon.PokemonId}"))).ShowAsyncQueue();
                    ReturnToGameScreen.Execute();
                    break;

                case DiskEncounterResponse.Types.Result.EncounterAlreadyFinished:
                    await new MessageDialog(Resources.CodeResources.GetString("PokemonRanAwayText")).ShowAsyncQueue();
                    ReturnToGameScreen.Execute();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            PokemonExtraData    = GameClient.GetExtraDataForPokemon(CurrentPokemon.PokemonId);
            SelectedCaptureItem = SelectAvailablePokeBall();
            Busy.SetBusy(false);
        }
Пример #25
0
        /// <summary>
        ///     Try install update. If it cant be installed directly, redirect user to page with release
        /// </summary>
        /// <param name="release">release to which update</param>
        /// <returns></returns>
        public static async Task InstallUpdate()
        {
            var browserFallback = true;


            var updateError = "";


            try
            {
                //this needs restricted capability "packageManagement" in appxmanifest
                var packageManager = new PackageManager();

                var dependencies = new List <Uri>();

                var uri = new Uri(VersionInfo.Instance.latest_release.setup_file);

                Busy.SetBusy(true,
                             string.Format(Resources.CodeResources.GetString("UpdateDownloadingText"),
                                           VersionInfo.Instance.latest_release.version));


                //Download dependencies
                foreach (string assetUrl in VersionInfo.Instance.latest_release.dependencies)
                {
                    string url      = assetUrl.Replace("{arch}", Package.Current.Id.Architecture.ToString());
                    var    assetUri = new Uri(url);
                    var    file     = await GetTemporaryUpdateFileAsync(Path.GetFileName(assetUri.LocalPath));
                    await DownloadFile(file, assetUri);

                    dependencies.Add(new Uri(file.Path));
                }


                var destinationFile = await GetTemporaryUpdateFileAsync(Path.GetFileName(uri.LocalPath));
                await DownloadFile(destinationFile, uri);

                Busy.SetBusy(false);
                Busy.SetBusy(true, Resources.CodeResources.GetString("UpdateInstallingText"));

                await packageManager.UpdatePackageAsync(new Uri(destinationFile.Path),
                                                        dependencies,
                                                        DeploymentOptions.ForceApplicationShutdown);

                //in case of error COMException is thrown so we cant get result (?????)
                browserFallback = false;
            }
            catch (Exception exc)
            {
                updateError = exc.HResult.ToString("0x") + " " + exc.Message;
                //lets do fallback to browser
            }
            finally
            {
                //clean all temorary files and dont wait on it
                var t1 = CleanTemporaryUpdateFolderAsync();
                Busy.SetBusy(false);
            }

            if (browserFallback)
            {
                //update failed, show dialog to user
                var dialog =
                    new MessageDialog(string.Format(Resources.CodeResources.GetString("UpdateFailedText"), updateError));

                dialog.Commands.Add(new UICommand(Resources.CodeResources.GetString("YesText"))
                {
                    Id = 0
                });
                dialog.Commands.Add(new UICommand(Resources.CodeResources.GetString("NoText"))
                {
                    Id = 1
                });
                dialog.DefaultCommandIndex = 0;
                dialog.CancelCommandIndex  = 1;

                var result = await dialog.ShowAsyncQueue();

                if ((int)result.Id != 0)
                {
                    return;
                }

                //open appx to download
                await Launcher.LaunchUriAsync(new Uri(VersionInfo.Instance.latest_release.setup_file));
            }
        }
Пример #26
0
 /// <summary>
 /// Notifies the busy.
 /// </summary>
 /// <param name="sender">Sender.</param>
 /// <param name="busy">If set to <c>true</c> busy.</param>
 public void NotifyBusy(object sender, bool busy)
 {
     Busy?.Invoke(this, busy);
 }
Пример #27
0
 private void OnHandShake(string obj)
 {
     Busy.SetBusy(false);
     base.Start();
 }
Пример #28
0
 private void Refresh()
 {
     Busy.Show();
     action.UserList(DeviceID.UUID, OnUserList);
 }
Пример #29
0
 internal override async void Start()
 {
     Busy.SetBusy(true, "waiting for buddy approval");
     await ConnectHub();
 }
Пример #30
0
        public async Task Download()
        {
            using (Busy.GetTicket())
            {
                try
                {
                    UpdateAvailable = false;
                    Downloading     = true;

                    // Updater
                    string updaterFileUrl = UpdateInfo.Updater;
                    if (String.IsNullOrEmpty(UpdateInfo.Updater))
                    {
                        updaterFileUrl = HearthcapUpdaterExe;
                    }

                    if (!updaterFileUrl.StartsWith("http://", StringComparison.Ordinal) &&
                        !updaterFileUrl.StartsWith("https://", StringComparison.Ordinal))
                    {
                        updaterFileUrl = _updateBaseUrl + (!_updateBaseUrl.EndsWith("/", StringComparison.Ordinal) ? "/" : "") + updaterFileUrl;
                    }

                    // File package
                    string filePackageUrl = UpdateInfo.File;
                    if (!filePackageUrl.StartsWith("http://", StringComparison.Ordinal) &&
                        !filePackageUrl.StartsWith("https://", StringComparison.Ordinal))
                    {
                        filePackageUrl = _updateBaseUrl + (!_updateBaseUrl.EndsWith("/", StringComparison.Ordinal) ? "/" : "") + filePackageUrl;
                    }

                    string filename = UpdateInfo.File;
                    filename = filename.Substring(filename.LastIndexOf("/", StringComparison.Ordinal) + 1);

                    var file        = Path.Combine(_tempPath, filename);
                    var updaterFile = Path.Combine(_tempPath, HearthcapUpdaterExe);

                    // Download
                    using (var wcFilePackage = new WebClient {
                        CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)
                    })
                        using (var wcUpdater = new WebClient {
                            CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)
                        })
                        {
                            await Task.WhenAll(
                                wcUpdater.DownloadFileTaskAsync(updaterFileUrl, updaterFile),
                                wcFilePackage.DownloadFileTaskAsync(filePackageUrl, file)
                                );
                        }

                    if (!File.Exists(file) ||
                        !File.Exists(updaterFile))
                    {
                        Error = "Error downloading update. Please try again.";
                        _log.Error("Error downloading update. Please try again (file does not exist).");
                    }
                    else
                    {
                        DownloadReady = true;
                    }
                }
                catch (Exception ex)
                {
                    _log.Error("Error downloading update: " + ex);
                    Error = ex.Message;
                }
                finally
                {
                    Downloading = false;
                }
            }
        }
Пример #31
0
 public virtual TReturn Visit(Busy msg, TData data)
 {
     return(default(TReturn));
 }