Esempio n. 1
0
        public void LocalRefresh()
        {
            try
            {
                League.LocalRefresh();

                var memberships = Memberships.Select(vm => vm.Membership).ToList();

                var comparer = new MembershipComparer();
                var toRemove = memberships.Except(League.Memberships, comparer).ToList();
                var toAdd    = League.Memberships.Except(memberships, comparer).ToList();

                toRemove.ForEach(m => Memberships.Remove(Memberships.Single(vm => vm.Membership == m)));

                toAdd.ForEach(m => Memberships.Add(new MembershipViewModel {
                    MembershipId = m.Id
                }));

                Memberships.Sort(new MembershipSortComparer());
                Memberships.ToList().ForEach(vm => vm.NotifyPropertiesChanged());

                if (Memberships.Count == 0)
                {
                    Memberships.Add(new MembershipViewModel {
                        EmptyMessage = "This league has no members yet"
                    });
                }
            }
            catch (Exception e)
            {
                InsightsManager.Report(e);
            }
        }
Esempio n. 2
0
        public void LocalRefresh(List <Challenge> challenges)
        {
            try
            {
                var current = Challenges.Select(vm => vm.Challenge).ToList();

                var comparer = new ChallengeComparer();
                var toRemove = current.Except(challenges, comparer).ToList();
                var toAdd    = challenges.Except(current, comparer).ToList();
                toRemove.ForEach(c => Challenges.Remove(Challenges.Single(vm => vm.Challenge == c)));

                var preSort = new List <ChallengeViewModel>();
                toAdd.ForEach(c => preSort.Add(new ChallengeViewModel {
                    Challenge = c
                }));

                preSort.Sort(new ChallengeSortComparer());
                preSort.ForEach(Challenges.Add);

                if (Challenges.Count == 0)
                {
                    Challenges.Add(new ChallengeViewModel()
                    {
                        EmptyMessage = "{0} no challenges for this league".Fmt(Membership.AthleteId == App.CurrentAthlete.Id
                                                        ? "You have" : "{0} has".Fmt(Membership.Athlete.Alias))
                    });
                }
            }
            catch (Exception e)
            {
                InsightsManager.Report(e);
            }
        }
Esempio n. 3
0
        async protected virtual void OnIncomingPayload(NotificationPayload payload)
        {
            string challengeId;

            if (payload.Payload.TryGetValue("challengeId", out challengeId))
            {
                try
                {
                    var vm   = new BaseViewModel();
                    var task = AzureService.Instance.GetChallengeById(challengeId);
                    await vm.RunSafe(task);

                    if (task.IsCompleted && !task.IsFaulted && task.Result != null)
                    {
                        var details = new ChallengeDetailsPage(task.Result);
                        details.AddDoneButton();

                        await App.Current.MainPage.Navigation.PushModalAsync(details.WithinNavigationPage());
                    }
                }
                catch (Exception e)
                {
                    InsightsManager.Report(e);
                    Console.WriteLine(e);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// All tasks are created as unstarted tasks and are processe via a proxy method that will run the task safely
        /// Instead of wrapping every task body in a try/catch, we'll process tasks in RunSafe
        /// RunSafe will start the task within the scope of a try/catch block and notify the app of any exceptions
        /// This can also be used to cancel running tasks when a user navigates away from a page - each VM has a cancellation token
        /// </summary>
        public async Task RunSafe(Task task, bool notifyOnError = true, [CallerMemberName] string caller = "")
        {
            if (!App.IsNetworkRechable)
            {
                MessagingCenter.Send <BaseViewModel, Exception>(this, Messages.ExceptionOccurred, new WebException("Please connect to the Information Super Highway"));
                return;
            }

            Exception exception = null;

            try
            {
                await Task.Run(() =>
                {
                    if (!CancellationToken.IsCancellationRequested)
                    {
                        task.Start();
                        task.Wait();
                    }
                });
            }
            catch (TaskCanceledException)
            {
                Debug.WriteLine("Task Cancelled");
            }
            catch (AggregateException e)
            {
                var ex = e.InnerException;
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }

                exception = ex;
            }
            catch (Exception e)
            {
                exception = e;
            }

            if (exception != null)
            {
                InsightsManager.Report(exception);
                Debug.WriteLine(exception);

                if (notifyOnError)
                {
                    NotifyException(exception);
                }
            }
        }
        /// <summary>
        /// Shows the Google authentication web view so the user can authenticate
        /// </summary>
        async Task ShowGoogleAuthenticationView()
        {
            if (App.AuthToken != null && Settings.Instance.User != null)
            {
                var success = await GetUserProfile();

                if (success)
                {
                    AzureService.Instance.Client.CurrentUser = Settings.Instance.User;
                    return;
                }
            }

            try
            {
                AuthenticationStatus = "Loading...";
                MobileServiceUser user = await _authenticator.DisplayWebView();

                var identity = await AzureService.Instance.Client.InvokeApiAsync("getUserIdentity", null, HttpMethod.Get, null);

                App.AuthToken = identity.Value <string>("accessToken");
                Utility.SetSecured("AuthToken", App.AuthToken, "xamarin.sport", "authentication");

                Settings.Instance.User = user;
                await Settings.Instance.Save();

                if (App.CurrentAthlete != null && App.CurrentAthlete.Id != null)
                {
                    var task = AzureService.Instance.SaveAthlete(App.CurrentAthlete);
                    await RunSafe(task);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("**SPORT AUTHENTICATION ERROR**\n\n" + e.GetBaseException());
                InsightsManager.Report(e);
            }
        }
Esempio n. 6
0
        protected virtual void TrackPage(Dictionary <string, string> metadata)
        {
            var identifier = GetType().Name;

            InsightsManager.Track(identifier, metadata);
        }
        /// <summary>
        /// Attempts to get the user profile from Google. Will use the refresh token if the auth token has expired
        /// </summary>
        async public Task <bool> GetUserProfile()
        {
            //Can't get profile w/out a token
            if (App.AuthToken == null)
            {
                return(false);
            }

            if (AuthUserProfile != null)
            {
                return(true);
            }

            using (new Busy(this))
            {
                AuthenticationStatus = "Getting Google user profile";
                var task = GoogleApiService.Instance.GetUserProfile();
                await RunSafe(task, false);

                if (task.IsFaulted && task.IsCompleted)
                {
                    //Need to get refresh token from Azure somehow
                    //Likely our authtoken has expired
//					AuthenticationStatus = "Refreshing token";
//
//					var refreshTask = GoogleApiService.Instance.GetNewAuthToken(Settings.Instance.RefreshToken);
//					await RunSafe(refreshTask);
//
//					if(refreshTask.IsCompleted && !refreshTask.IsFaulted)
//					{
//						//Success in getting a new auth token - now lets attempt to get the profile again
//						if(!string.IsNullOrWhiteSpace(refreshTask.Result) && App.AuthToken != refreshTask.Result)
//						{
//							//We have a valid token now, let's try this again
//							App.AuthToken = refreshTask.Result;
//							await Settings.Instance.Save();
//							return await GetUserProfile();
//						}
//					}
                }

                if (task.IsCompleted && !task.IsFaulted && task.Result != null)
                {
                    AuthenticationStatus = "Authentication complete";
                    AuthUserProfile      = task.Result;

                    InsightsManager.Identify(AuthUserProfile.Email, new Dictionary <string, string> {
                        {
                            "Name",
                            AuthUserProfile.Name
                        }
                    });

                    Settings.Instance.AuthUserID = AuthUserProfile.Id;
                    await Settings.Instance.Save();
                }
                else
                {
                    AuthenticationStatus = "Unable to authenticate";
                }
            }

            return(AuthUserProfile != null);
        }