/// <summary>
        /// Executes the request without any parsing.
        /// </summary>
        /// <returns>The unparsed.</returns>
        public HttpResponseMessage ExecuteUnparsed()
        {
            var client  = InitializeRestClient();
            var request = BuildRestRequest();

            RequestAuth.Authenticate(request);
            Logger.Log(request);
            var req      = client.SendAsync(request);
            var response = req.Result;

            Logger.Log(response);
            var contentType = response.Headers
                              .Where(x => x.Key.ToLower().Equals("content-type"))
                              .Select(x => x.Value)
                              .SingleOrDefault();

            if (contentType != null && contentType.Any() && !contentType.First().Contains("application/json"))
            {
                var kinveyException = new KinveyException(
                    EnumErrorCategory.ERROR_REQUIREMENT,
                    EnumErrorCode.ERROR_REQUIREMENT_CONTENT_TYPE_HEADER,
                    contentType.FirstOrDefault()
                    )
                {
                    RequestID = HelperMethods.getRequestID(response)
                };
                throw kinveyException;
            }

            lastResponseCode    = response.StatusCode;
            lastResponseMessage = response.StatusCode.ToString();
            lastResponseHeaders = new List <KeyValuePair <string, IEnumerable <string> > >();
            foreach (var header in response.Headers)
            {
                lastResponseHeaders.Add(header);
            }

            try
            {
                response.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                throw new KinveyException(
                          EnumErrorCategory.ERROR_BACKEND,
                          EnumErrorCode.ERROR_JSON_RESPONSE,
                          ex.Message,
                          ex
                          );
            }


            return(response);
        }
        /// <summary>
        /// Executes this request synchronously.
        /// </summary>
        /// <returns> The type of response. </returns>
        public virtual T Execute()
        {
            var response = ExecuteUnparsed();

            // TODO this method must be deleted once everything is async
//			if (OverrideRedirect){
//				var locList = response.Headers.FirstOrDefault(HeaderToCheck => HeaderToCheck.Name.Equals("Location")).Value;
//				return onRedirect((locList as List<string>)[0]);
//			}

            // special case to handle void or empty responses
            if (response.Content == null)
            {
                return(default(T));
            }

            string json = null;

            try
            {
                var task = response.Content.ReadAsStringAsync();
                task.Wait();
                json = task.Result;
                return(JsonConvert.DeserializeObject <T>(json));
            }
            catch (JsonException ex)
            {
                throw new KinveyException(EnumErrorCategory.ERROR_DATASTORE_NETWORK, EnumErrorCode.ERROR_JSON_PARSE,
                                          HelperMethods.GetCustomParsingJsonErrorMessage(json, response.RequestMessage.RequestUri.ToString(), typeof(T).FullName),
                                          null,
                                          ex)
                      {
                          RequestID = HelperMethods.getRequestID(response)
                      };
            }
            catch (ArgumentException ex)
            {
                Logger.Log(ex.Message);
                return(default(T));
            }
            catch (NullReferenceException ex)
            {
                Logger.Log(ex.Message);
                return(default(T));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Executes this request async and parses the result.
        /// </summary>
        /// <returns>The async request.</returns>
        public async Task <KinveyAuthResponse> ExecuteAsync()
        {
            string json = null;
            HttpResponseMessage response = null;

            try
            {
                response = await ExecuteUnparsedAsync().ConfigureAwait(false);

                json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                return(JsonConvert.DeserializeObject <KinveyAuthResponse>(json));
            }
            catch (JsonException ex)
            {
                KinveyException kinveyException = new KinveyException(
                    EnumErrorCategory.ERROR_DATASTORE_NETWORK,
                    EnumErrorCode.ERROR_JSON_PARSE,
                    HelperMethods.GetCustomParsingJsonErrorMessage(json, response?.RequestMessage.RequestUri.ToString(), typeof(KinveyAuthResponse).FullName),
                    null,
                    ex
                    )
                {
                    RequestID = HelperMethods.getRequestID(response)
                };
                throw kinveyException;
            }
            catch (KinveyException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new KinveyException(
                          EnumErrorCategory.ERROR_USER,
                          EnumErrorCode.ERROR_USER_LOGIN_ATTEMPT,
                          "Error deserializing response content.",
                          ex
                          );
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="KinveyException"/> class.
        /// </summary>
        /// <param name="errorCategory">The <see cref="EnumErrorCategory"/>  of the exception.</param>
        /// <param name="errorCode">The <see cref="EnumErrorCode"/>  of the exception.</param>
        /// <param name="response">Http response.</param>
        /// <param name="innerException">Inner exception thrown, if available.</param>
        public KinveyException(EnumErrorCategory errorCategory, EnumErrorCode errorCode, HttpResponseMessage response, Exception innerException)
            : base(innerException.Message, innerException)
        {
            this.errorCategory = errorCategory;
            this.errorCode     = errorCode;

            Tuple <string, string, string> errorInfo = InfoFromErrorCode(errorCategory, errorCode);

            StatusCode = (int)response.StatusCode;

            try
            {
                KinveyJsonError errorJSON = KinveyJsonError.parse(response);
                this.error       = errorJSON.Error ?? errorInfo.Item1;
                this.debug       = errorJSON.Debug ?? errorInfo.Item2;
                this.description = errorJSON.Description ?? errorInfo.Item3;
                this.requestID   = HelperMethods.getRequestID(response);
            }
            catch (Exception) {
                //Catch any exceptions thrown while parsing an unknown responseJSON
            }
        }
        public virtual async Task <T> ExecuteAsync()
        {
            var response = await ExecuteUnparsedAsync();

            if (OverrideRedirect)
            {
                string newLoc = string.Empty;
                foreach (var header in response.Headers)
                {
                    if (header.Key.ToLower().Equals("location"))
                    {
                        newLoc = header.Value.FirstOrDefault();
                        break;
                    }
                }
                //string newlocation = response.Headers.FirstOrDefault(stringToCheck => stringToCheck.ToString().Equals("Location")).ToString();
                return(await onRedirectAsync(newLoc));
            }
            // special case to handle void or empty responses
            if (response.Content == null)
            {
                return(default(T));
            }

            string path = response.RequestMessage.RequestUri.AbsolutePath;

            if (path != null &&
                path.Contains(Constants.STR_PATH_CUSTOM_ENDPOINT) &&
                (((int)response.StatusCode) < 200 || ((int)response.StatusCode) > 302))
            {
                // Seems like only Custom Endpoint/BL would result in having a successful response
                // without having a successful status code.  The BL executed successfully, but did
                // produce a successsful outcome.
                try
                {
                    response.EnsureSuccessStatusCode();
                }
                catch (Exception ex)
                {
                    var ke = new KinveyException(
                        EnumErrorCategory.ERROR_CUSTOM_ENDPOINT,
                        EnumErrorCode.ERROR_CUSTOM_ENDPOINT_ERROR,
                        response,
                        ex
                        );
                    throw ke;
                }
            }

            if (path != null &&
                path.Contains(Constants.STR_PATH_REALTIME_STREAM) &&
                (((int)response.StatusCode) < 200 || ((int)response.StatusCode) > 302))
            {
                // Appears as though there is a stream error.  A stream error could result in having a successful response
                // without having a successful status code, such as a 401.  The request was successful, but the response
                // indicates that there is an issue with what was being requested
                try
                {
                    response.EnsureSuccessStatusCode();
                }
                catch (Exception ex)
                {
                    var ke = new KinveyException(
                        EnumErrorCategory.ERROR_REALTIME,
                        EnumErrorCode.ERROR_REALTIME_ERROR,
                        response,
                        ex
                        );
                    throw ke;
                }
            }

            if (((int)response.StatusCode) < 200 || ((int)response.StatusCode) > 302)
            {
                try
                {
                    response.EnsureSuccessStatusCode();
                }
                catch (Exception ex)
                {
                    var kinveyException = new KinveyException(
                        EnumErrorCategory.ERROR_BACKEND,
                        EnumErrorCode.ERROR_JSON_RESPONSE,
                        response,
                        ex
                        )
                    {
                        RequestID = HelperMethods.getRequestID(response)
                    };
                    throw kinveyException;
                }
            }

            try
            {
                var json = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <T>(json);

                RequestStartTime = HelperMethods.GetRequestStartTime(response);

                return(result);
            }
            catch (JsonException ex)
            {
                KinveyException kinveyException = new KinveyException(
                    EnumErrorCategory.ERROR_DATASTORE_NETWORK,
                    EnumErrorCode.ERROR_JSON_PARSE,
                    ex.Message,
                    ex
                    )
                {
                    RequestID = HelperMethods.getRequestID(response)
                };
                throw kinveyException;
            }
            catch (ArgumentException ex)
            {
                Logger.Log(ex.Message);
                return(default(T));
            }
            catch (NullReferenceException ex)
            {
                Logger.Log(ex.Message);
                return(default(T));
            }
        }
        public async Task <HttpResponseMessage> ExecuteUnparsedAsync()
        {
            var httClient = InitializeRestClient();
            var request   = BuildRestRequest();

            RequestAuth.Authenticate(request);
            Logger.Log(request);
            var response = await httClient.SendAsync(request);

            Logger.Log(response);
            var contentType = response.Headers
                              .Where(x => x.Key.ToLower().Equals("content-type"))
                              .Select(x => x.Value)
                              .FirstOrDefault()?
                              .FirstOrDefault();

            if (contentType != null && !contentType.Contains("application/json"))
            {
                var kinveyException = new KinveyException(
                    EnumErrorCategory.ERROR_REQUIREMENT,
                    EnumErrorCode.ERROR_REQUIREMENT_CONTENT_TYPE_HEADER,
                    contentType
                    )
                {
                    RequestID = HelperMethods.getRequestID(response)
                };
                throw kinveyException;
            }

            lastResponseCode    = response.StatusCode;
            lastResponseMessage = response.StatusCode.ToString();
            lastResponseHeaders = new List <KeyValuePair <string, IEnumerable <string> > >();

            foreach (var header in response.Headers)
            {
                lastResponseHeaders.Add(header);
            }

            if ((int)response.StatusCode == 401)
            {
                ServerError error = null;
                try
                {
                    var json = await response.Content.ReadAsStringAsync();

                    error = JsonConvert.DeserializeObject <ServerError>(json);
                }
                catch (Exception)
                {
                }

                if (error != null && !error.Error.Equals(Constants.STR_ERROR_BACKEND_INSUFFICIENT_CREDENTIALS))
                {
                    // Attempt to get the refresh token
                    Credential cred         = Client.Store.Load(Client.ActiveUser.Id, Client.SSOGroupKey);
                    string     refreshToken = null;
                    string     redirectUri  = null;
                    string     micClientId  = null;

                    if (cred != null)
                    {
                        refreshToken = cred.RefreshToken;
                        redirectUri  = cred.RedirectUri;
                        micClientId  = cred.MICClientID;

                        if (!string.IsNullOrEmpty(refreshToken) && !refreshToken.ToLower().Equals("null"))
                        {
                            if (!hasRetried)
                            {
                                // Attempting retry - set flag to prevent additional attempts
                                hasRetried = true;

                                //use the refresh token for a new access token
                                JObject result = await Client.ActiveUser.UseRefreshToken(refreshToken, redirectUri, micClientId).ExecuteAsync();

                                // log out the current user without removing the user record from the credential store
                                Client.ActiveUser.LogoutSoft();

                                //login with the access token
                                Provider provider = new Provider();
                                provider.kinveyAuth = new MICCredential(result["access_token"].ToString());
                                User u = await User.LoginAsync(new ThirdPartyIdentity(provider), Client);

                                //store the new refresh token
                                Credential currentCred = Client.Store.Load(Client.ActiveUser.Id, Client.SSOGroupKey);
                                currentCred.AccessToken  = result["access_token"].ToString();
                                currentCred.RefreshToken = result.GetValidValue("refresh_token");
                                currentCred.RedirectUri  = redirectUri;
                                Client.Store.Store(Client.ActiveUser.Id, Client.SSOGroupKey, currentCred);

                                // Retry the original request
                                RequestAuth = new KinveyAuthenticator(currentCred.AuthToken);
                                var retryResponse = await ExecuteUnparsedAsync();

                                return(retryResponse);
                            }
                            else
                            {
                                Client.ActiveUser.Logout();
                            }
                        }
                        else
                        {
                            //logout the current user
                            Client.ActiveUser.Logout();
                        }
                    }
                    else
                    {
                        Client.ActiveUser.Logout();
                    }
                }
            }

            try
            {
                response.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                throw new KinveyException(
                          EnumErrorCategory.ERROR_BACKEND,
                          EnumErrorCode.ERROR_JSON_RESPONSE,
                          response,
                          ex
                          );
            }


            return(response);
        }