Пример #1
0
        /// <summary>
        /// Gets a list of contribution visibility options (aka Sharing Preferences). The traditional results are "Microsoft Only", "MVP Community" and "Everyone"
        /// </summary>
        /// <param name="forceRefresh">The result is cached in a backing list by default which prevents unnecessary fetches. If you want the cache refreshed, set this to true</param>
        /// <returns>A list of available visibilities</returns>
        public async Task <IReadOnlyList <Visibility> > GetVisibilitiesAsync(bool forceRefresh = false)
        {
            if (_visibilitiesCachedResult?.Count == 0 && !forceRefresh)
            {
                // Return the cached result by default.
                return(_visibilitiesCachedResult);
            }

            try
            {
                using (var response = await _client.GetAsync("contributions/sharingpreferences"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        var deserializedResult = JsonConvert.DeserializeObject <IReadOnlyList <Visibility> >(json);

                        // Update the cached result.
                        _visibilitiesCachedResult = new List <Visibility>(deserializedResult);

                        return(_visibilitiesCachedResult);
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                            IsTokenRefreshNeeded = true
                        });
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                            IsBadRequest = true, Message = "Bad Request Error - If this continues to happen, please open a GitHub issue so we can fix this immediately (go to the About page for a direct link)."
                        });
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"GetVisibilitiesAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetVisibilitiesAsync Exception: {e}");
            }

            return(null);
        }
Пример #2
0
        public async Task <ClientResponse> ConnectAsync()
        {
            Console.WriteLine("Connecting to {0}", _chatHubUrl);

            _connection = SetupConnection()
                          .Build();

            _connection.Closed += e =>
            {
                Console.WriteLine("Connection closed...");
                Disconnected?.Invoke();
                return(Task.CompletedTask);
            };

            try
            {
                await _connection.StartAsync().ConfigureAwait(false);

                Console.WriteLine("Connected to {0}", _chatHubUrl);

                var client = await _connection.InvokeAsync <ClientResponse>(ServerMethods.AddClientAsync);

                SubscribeToEvents();

                return(client);
            }
            catch (HttpRequestException e) when(e.Message.Contains(_authorizationErrorStatusCode))
            {
                // Workaround for HttpRequestException without StatusCode
                // https://github.com/dotnet/corefx/issues/24253

                AccessTokenExpired?.Invoke();
                throw;
            }
        }
Пример #3
0
        /// <summary>
        /// Get the profile picture of the currently signed in MVP
        /// </summary>
        /// <returns>JPG image byte array</returns>
        public async Task <byte[]> GetProfileImageAsync()
        {
            try
            {
                // the result is Detected mime type: image/jpeg; charset=binary
                using (var response = await _client.GetAsync("https://mvpapi.azure-api.net/mvp/api/profile/photo"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var base64String = await response.Content.ReadAsStringAsync();

                        try
                        {
                            if (string.IsNullOrEmpty(base64String))
                            {
                                return(null);
                            }

                            base64String = base64String.TrimStart('"').TrimEnd('"');

                            return(Convert.FromBase64String(base64String));
                        }
                        catch (Exception e)
                        {
                            await e.LogExceptionAsync();

                            Debug.WriteLine($"GetProfileImageAsync Image Conversion Exception: {e}");
                        }
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new EventArgs());
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new EventArgs());
                }

                Debug.WriteLine($"GetProfileImageAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetProfileImageAsync Exception: {e}");
            }

            return(null);
        }
Пример #4
0
        /// <summary>
        /// Submits the MVP's answers for award consideration questions.
        /// WARNING - THIS CAN ONLY BE DONE ONCE PER AWARD PERIOD, THE ANSWERS CANNOT BE CHANGED AFTER SUBMISSION.
        /// </summary>
        /// <returns>If the submission was successful</returns>
        public async Task <bool> SubmitAwardConsiderationAnswerAsync()
        {
            try
            {
                var    serializedContribution = JsonConvert.SerializeObject(string.Empty);
                byte[] byteData = Encoding.UTF8.GetBytes(serializedContribution);

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    using (var response = await _client.PostAsync("awardconsideration/SubmitAnswers?", content))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            return(true);
                        }

                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                                IsTokenRefreshNeeded = true
                            });
                        }
                        else if (response.StatusCode == HttpStatusCode.BadRequest)
                        {
                            var message = await response.Content.ReadAsStringAsync();

                            RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                                IsBadRequest = true, Message = message
                            });
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true, Message = e.Message
                    });
                }

                Debug.WriteLine($"SubmitContributionAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"SubmitContributionAsync Exception: {e}");
            }

            return(false);
        }
Пример #5
0
        /// <summary>
        /// Delete contribution
        /// </summary>
        /// <param name="contribution">Item to delete</param>
        /// <returns>Success or failure</returns>
        public async Task <bool?> DeleteContributionAsync(Contribution contribution)
        {
            if (contribution == null)
            {
                throw new NullReferenceException("The contribution parameter was null.");
            }

            try
            {
                using (var response = await _client.DeleteAsync($"contributions?id={contribution.ContributionId}"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        return(true);
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                            IsTokenRefreshNeeded = true
                        });
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        var message = await response.Content.ReadAsStringAsync();

                        RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                            IsBadRequest = true, Message = message
                        });
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"UpdateContributionAsync HttpRequestException: {e}");
                return(null);
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetProfileAsync Exception: {e}");
                return(null);
            }

            return(null);
        }
Пример #6
0
        public async Task <bool> DeleteOnlineIdentityAsync(OnlineIdentity onlineIdentity)
        {
            if (onlineIdentity == null)
            {
                throw new NullReferenceException("The OnlineIdentity parameter was null.");
            }

            try
            {
                using (var response = await _client.DeleteAsync($"onlineidentities?id={onlineIdentity.PrivateSiteId}"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        return(true);
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                            IsTokenRefreshNeeded = true
                        });
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        var message = await response.Content.ReadAsStringAsync();

                        RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                            IsBadRequest = true, Message = message
                        });
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"SubmitOnlineIdentitiesAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"SubmitOnlineIdentitiesAsync Exception: {e}");
            }

            return(false);
        }
Пример #7
0
        /// <summary>
        /// Updates an existing contribution, identified by the contribution ID
        /// </summary>
        /// <param name="contribution">Contribution to be updated</param>
        /// <returns>Bool to denote update success or failure</returns>
        public async Task <bool?> UpdateContributionAsync(ContributionsModel contribution)
        {
            if (contribution == null)
            {
                throw new NullReferenceException("The contribution parameter was null.");
            }

            try
            {
                // Request body
                var    serializedContribution = JsonConvert.SerializeObject(contribution);
                byte[] byteData = Encoding.UTF8.GetBytes(serializedContribution);

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    using (var response = await _client.PutAsync("https://mvpapi.azure-api.net/mvp/api/contributions", content))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            return(true);
                        }
                        else
                        {
                            if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                            {
                                AccessTokenExpired?.Invoke(this, new EventArgs());
                            }
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new EventArgs());
                }

                Debug.WriteLine($"UpdateContributionAsync HttpRequestException: {e}");
                return(null);
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetProfileAsync Exception: {e}");
            }

            return(null);
        }
 static ApiClientTokenProvider()
 {
     RefreshHostUri();
     _timer = new Timer(delegate
     {
         remainSeconds--;
         if (AccessToken != null && remainSeconds <= 0)
         {
             _timer.Change(Timeout.Infinite, Timeout.Infinite);
             AccessTokenExpired?.Invoke(null, null);
         }
     }, null, Timeout.Infinite, Timeout.Infinite);
 }
Пример #9
0
        /// <summary>
        /// Returns the profile data of the currently signed in MVP
        /// </summary>
        /// <returns>The MVP's profile information</returns>
        public async Task <Profile> GetProfileAsync()
        {
            try
            {
                using (var response = await _client.GetAsync("profile"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        return(JsonConvert.DeserializeObject <Profile>(json));
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                            IsTokenRefreshNeeded = true
                        });
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        var message = await response.Content.ReadAsStringAsync();

                        RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                            IsBadRequest = true, Message = message
                        });
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"GetProfileAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetProfileAsync Exception: {e}");
            }

            return(null);
        }
Пример #10
0
        /// <summary>
        /// Delete contribution
        /// </summary>
        /// <param name="contribution">Item to delete</param>
        /// <returns>Success or failure</returns>
        public async Task <bool?> DeleteContributionAsync(ContributionsModel contribution)
        {
            if (contribution == null)
            {
                throw new NullReferenceException("The contribution parameter was null.");
            }

            try
            {
                using (var response = await _client.DeleteAsync($"https://mvpapi.azure-api.net/mvp/api/contributions?id={contribution.ContributionId}"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        return(true);
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new EventArgs());
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new EventArgs());
                }

                Debug.WriteLine($"UpdateContributionAsync HttpRequestException: {e}");
                return(null);
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetProfileAsync Exception: {e}");
                return(null);
            }

            return(null);
        }
Пример #11
0
        /// <summary>
        /// Gets the MVPs activities, depending on the offset (page) and the limit (number of items per-page)
        /// </summary>
        /// <param name="offset">page to return</param>
        /// <param name="limit">number of items for the page</param>
        /// <returns></returns>
        public async Task <ContributionViewModel> GetContributionsAsync(int?offset, int limit)
        {
            if (offset == null)
            {
                offset = 0;
            }

            try
            {
                using (var response = await _client.GetAsync($"https://mvpapi.azure-api.net/mvp/api/contributions/{offset}/{limit}"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        return(JsonConvert.DeserializeObject <ContributionViewModel>(json));
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new EventArgs());
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new EventArgs());
                }

                Debug.WriteLine($"GetContributionsAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetContributionsAsync Exception: {e}");
            }

            return(null);
        }
Пример #12
0
        // TODO MVP API doesn't yet have support for submitting a new Online Identity
        //public async Task<OnlineIdentity> SubmitOnlineIdentityAsync(OnlineIdentityViewModel onlineIdentity)
        //{
        //    if (onlineIdentity == null)
        //        throw new NullReferenceException("The OnlineIdentity parameter was null.");

        //    try
        //    {
        //        var serializedOnlineIdentity = JsonConvert.SerializeObject(onlineIdentity);
        //        byte[] byteData = Encoding.UTF8.GetBytes(serializedOnlineIdentity);

        //        using (var content = new ByteArrayContent(byteData))
        //        {
        //            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        //            using (var response = await _client.PostAsync("https://mvpapi.azure-api.net/mvp/api/onlineidentities?", content))
        //            {
        //                if (response.IsSuccessStatusCode)
        //                {
        //                    var json = await response.Content.ReadAsStringAsync();
        //                    Debug.WriteLine($"OnlineIdentity Save JSON: {json}");

        //                    var result = JsonConvert.DeserializeObject<OnlineIdentity>(json);
        //                    Debug.WriteLine($"OnlineIdentity Save Result: ID {result.PrivateSiteId}");

        //                    return result;
        //                }
        //                else
        //                {
        //                    if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
        //                    {
        //                        AccessTokenExpired?.Invoke(this, new EventArgs());
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    catch (HttpRequestException e)
        //    {
        //        await e.LogExceptionAsync();

        //        if (e.Message.Contains("500"))
        //        {
        //            RequestErrorOccurred?.Invoke(this, new EventArgs());
        //        }

        //        Debug.WriteLine($"SubmitOnlineIdentitiesAsync HttpRequestException: {e}");
        //    }
        //    catch (Exception e)
        //    {
        //        await e.LogExceptionAsync();

        //        Debug.WriteLine($"SubmitOnlineIdentitiesAsync Exception: {e}");
        //    }

        //    return null;
        //}

        public async Task <bool> DeleteOnlineIdentityAsync(OnlineIdentityViewModel onlineIdentity)
        {
            if (onlineIdentity == null)
            {
                throw new NullReferenceException("The OnlineIdentity parameter was null.");
            }

            try
            {
                using (var response = await _client.DeleteAsync($"https://mvpapi.azure-api.net/mvp/api/onlineidentities?id={onlineIdentity.PrivateSiteId}"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        return(true);
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new EventArgs());
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new EventArgs());
                }

                Debug.WriteLine($"SubmitOnlineIdentitiesAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"SubmitOnlineIdentitiesAsync Exception: {e}");
            }

            return(false);
        }
Пример #13
0
        public async Task <IReadOnlyList <OnlineIdentityViewModel> > GetOnlineIdentitiesAsync()
        {
            try
            {
                using (var response = await _client.GetAsync("https://mvpapi.azure-api.net/mvp/api/onlineidentities"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        return(JsonConvert.DeserializeObject <IReadOnlyList <OnlineIdentityViewModel> >(json));
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new EventArgs());
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new EventArgs());
                }

                Debug.WriteLine($"GetOnlineIdentitiesAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetOnlineIdentitiesAsync Exception: {e}");
            }

            return(null);
        }
Пример #14
0
        private async Task SendAndHandleExceptionsAsync(string methodName, BaseRequest request)
        {
            var tcs       = new TaskCompletionSource <bool>();
            var requestId = Guid.NewGuid().ToString();

            CreateExceptionSubscription(requestId, tcs);
            CreateValidationFailedSubscription(requestId, tcs);

            IDisposable successSubscription = null;

            successSubscription = _connection.On <string>(ClientEvents.RequestSuccess, id =>
            {
                if (id == requestId)
                {
                    successSubscription.Dispose();
                    tcs.SetResult(true);
                }
            });

            var signalRRequest = new SignalRRequest <BaseRequest>()
            {
                Request   = request,
                RequestId = requestId
            };

            try
            {
                await _connection.InvokeAsync(methodName, signalRRequest).ConfigureAwait(false);

                await tcs.Task.ConfigureAwait(false);
            }
            catch (HttpRequestException e) when(e.Message.Contains(_authorizationErrorStatusCode))
            {
                // Workaround for HttpRequestException without StatusCode
                // https://github.com/dotnet/corefx/issues/24253

                AccessTokenExpired?.Invoke();
            }
        }
Пример #15
0
        /// <summary>
        /// Gets the MVPs activities, depending on the offset (page) and the limit (number of items per-page)
        /// </summary>
        /// <param name="offset">page to return</param>
        /// <param name="limit">number of items for the page</param>
        /// <param name="forceRefresh">The result is cached in a backing list by default which prevents unnecessary fetches. If you want the cache refreshed, set this to true</param>
        /// <returns>A list of the MVP's contributions</returns>
        public async Task <ContributionList> GetContributionsAsync(int?offset, int limit, bool forceRefresh = false)
        {
            if (_contributionsCachedResult != null && !forceRefresh)
            {
                // Return the cached result by default.
                return(_contributionsCachedResult);
            }

            if (offset == null)
            {
                offset = 0;
            }

            try
            {
                using (var response = await _client.GetAsync($"contributions/{offset}/{limit}"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        var deserializedResult = JsonConvert.DeserializeObject <ContributionList>(json);

                        // Update the cached result.
                        _contributionsCachedResult = deserializedResult;

                        return(_contributionsCachedResult);
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                            IsTokenRefreshNeeded = true
                        });
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        var message = await response.Content.ReadAsStringAsync();

                        RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                            IsBadRequest = true, Message = message
                        });
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"GetContributionsAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetContributionsAsync Exception: {e}");
            }

            return(null);
        }
Пример #16
0
        /// <summary>
        /// Saves an OnlineIdentity
        /// </summary>
        /// <param name="onlineIdentity"></param>
        /// <returns></returns>
        public async Task <OnlineIdentity> SubmitOnlineIdentityAsync(OnlineIdentity onlineIdentity)
        {
            if (onlineIdentity == null)
            {
                throw new NullReferenceException("The OnlineIdentity parameter was null.");
            }

            try
            {
                var    serializedOnlineIdentity = JsonConvert.SerializeObject(onlineIdentity);
                byte[] byteData = Encoding.UTF8.GetBytes(serializedOnlineIdentity);

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    using (var response = await _client.PostAsync("onlineidentities?", content))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            var json = await response.Content.ReadAsStringAsync();

                            Debug.WriteLine($"OnlineIdentity Save JSON: {json}");

                            var result = JsonConvert.DeserializeObject <OnlineIdentity>(json);
                            Debug.WriteLine($"OnlineIdentity Save Result: ID {result.PrivateSiteId}");

                            return(result);
                        }

                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                                IsTokenRefreshNeeded = true
                            });
                        }
                        else if (response.StatusCode == HttpStatusCode.BadRequest)
                        {
                            var message = await response.Content.ReadAsStringAsync();

                            RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                                IsBadRequest = true, Message = message
                            });
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"SubmitOnlineIdentitiesAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"SubmitOnlineIdentitiesAsync Exception: {e}");
            }

            return(null);
        }
Пример #17
0
        /// <summary>
        /// Returns a list of the MVP's OnlineIdentities (social media accounts and other identities)
        /// </summary>
        /// <param name="forceRefresh">The result is cached in a backing list by default which prevents unnecessary fetches. If you want the cache refreshed, set this to true</param>
        /// <returns></returns>
        public async Task <IReadOnlyList <OnlineIdentity> > GetOnlineIdentitiesAsync(bool forceRefresh = false)
        {
            if (_contributionTypesCachedResult?.Count == 0 && !forceRefresh)
            {
                // Return the cached result by default.
                return(_onlineIdentitiesCachedResult);
            }

            try
            {
                using (var response = await _client.GetAsync("onlineidentities"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        var deserializedResult = JsonConvert.DeserializeObject <IReadOnlyList <OnlineIdentity> >(json);

                        // Update the cached result.
                        _onlineIdentitiesCachedResult = new List <OnlineIdentity>(deserializedResult);

                        return(_onlineIdentitiesCachedResult);
                    }

                    if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                            IsTokenRefreshNeeded = true
                        });
                    }
                    else if (response.StatusCode == HttpStatusCode.BadRequest)
                    {
                        var message = await response.Content.ReadAsStringAsync();

                        RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                            IsBadRequest = true, Message = message
                        });
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"GetOnlineIdentitiesAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetOnlineIdentitiesAsync Exception: {e}");
            }

            return(null);
        }
Пример #18
0
 void HandleAccessTokenExpired()
 {
     AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
         IsTokenRefreshNeeded = true
     });
 }
Пример #19
0
        /// <summary>
        /// Saves the MVP's answers to the Aware Consideration questions.
        /// IMPORTANT NOTE:
        /// This does NOT submit them for review by the MVP award team, it is intended to be used to save the answers.
        /// To submit the questions, call SubmitAwardConsiderationAnswerAsync after saving the answers.
        /// </summary>
        /// <param name="answers"></param>
        /// <returns></returns>
        public async Task <List <AwardConsiderationAnswer> > SaveAwardConsiderationAnswerAsync(IEnumerable <AwardConsiderationAnswer> answers)
        {
            if (answers == null)
            {
                throw new NullReferenceException("The contribution parameter was null.");
            }

            try
            {
                var    serializedContribution = JsonConvert.SerializeObject(answers);
                byte[] byteData = Encoding.UTF8.GetBytes(serializedContribution);

                using (var content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    using (var response = await _client.PostAsync("awardconsideration/saveanswers?", content))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            var json = await response.Content.ReadAsStringAsync();

                            return(JsonConvert.DeserializeObject <List <AwardConsiderationAnswer> >(json));
                        }

                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                                IsTokenRefreshNeeded = true
                            });
                        }
                        else if (response.StatusCode == HttpStatusCode.BadRequest)
                        {
                            var message = await response.Content.ReadAsStringAsync();

                            RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                                IsBadRequest = true, Message = message
                            });
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"SubmitContributionAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"SubmitContributionAsync Exception: {e}");
            }

            return(null);
        }
Пример #20
0
 protected virtual void OnAccessTokenExpired(EventArgs e) => AccessTokenExpired?.Invoke(this, e);
Пример #21
0
        /// <summary>
        /// Downloads and saves the image file to LocalFolder
        /// </summary>
        /// <returns>File path</returns>
        public async Task <string> DownloadAndSaveProfileImage()
        {
            try
            {
                // the result is Detected mime type: image/jpeg; charset=binary
                using (var response = await _client.GetAsync("profile/photo"))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var base64String = await response.Content.ReadAsStringAsync();

                        try
                        {
                            if (string.IsNullOrEmpty(base64String))
                            {
                                return(null);
                            }

                            base64String = base64String.TrimStart('"').TrimEnd('"');

                            // determine file type
                            var data = base64String.Substring(0, 5);

                            var fileExtension = string.Empty;

                            switch (data.ToUpper())
                            {
                            case "IVBOR":
                                fileExtension = "png";
                                break;

                            case "/9J/4":
                                fileExtension = "jpg";
                                break;
                            }

                            var imgBytes = Convert.FromBase64String(base64String);

                            // TODO: Fix storing the image.
                            // var filePath = StorageHelpers.Instance.SaveImage(imgBytes, $"ProfilePicture.{fileExtension}");
                            // return filePath;
                        }
                        catch (Exception e)
                        {
                            await e.LogExceptionAsync();

                            Debug.WriteLine($"DownloadAndSaveProfileImage Exception: {e}");
                        }
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden)
                        {
                            AccessTokenExpired?.Invoke(this, new ApiServiceEventArgs {
                                IsTokenRefreshNeeded = true
                            });
                        }
                        else if (response.StatusCode == HttpStatusCode.BadRequest)
                        {
                            var message = await response.Content.ReadAsStringAsync();

                            RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                                IsBadRequest = true, Message = message
                            });
                        }
                    }
                }
            }
            catch (HttpRequestException e)
            {
                await e.LogExceptionAsync();

                if (e.Message.Contains("500"))
                {
                    RequestErrorOccurred?.Invoke(this, new ApiServiceEventArgs {
                        IsServerError = true
                    });
                }

                Debug.WriteLine($"GetProfileImageAsync HttpRequestException: {e}");
            }
            catch (Exception e)
            {
                await e.LogExceptionAsync();

                Debug.WriteLine($"GetProfileImageAsync Exception: {e}");
            }

            return(null);
        }