Example #1
0
        /*/// <summary>
         * /// Async method that allows you to send arbitrary strings to server
         * /// </summary>
         * /// <param name="value">The arbitrary string to be sent to the server</param>
         * /// <param name="connectedToInternet">Flag for whether an internet connection is present. A <exception cref="NotConnectedToInternetException">NotConnectedToInternetException exception is throw if value is false</exception></param>
         * /// <returns>ServerResponseObjectsBase on success or null on failure</returns>
         * [Obsolete("ServerResponseObjectsBase is an unneeded class and will be removed, as will this method that has a dependancy on it. Use MakeGetCallAsync instead")]
         * protected async Task<ServerResponseObjectsBase> GetStringAsync(string value, bool connectedToInternet)
         * {
         *  string url = string.Format(GetCallsBasePath, value);
         *  var client = DefaultClient;
         *  foreach (KeyValuePair<string, string> headers in extraHeaders)
         *  {
         *      client.DefaultRequestHeaders.Add(headers.Key, headers.Value);
         *  }
         *
         *  HttpResponseMessage responseMsg = null;
         *
         *  try
         *  {
         *      if (!connectedToInternet)
         *      {
         *          throw new NotConnectedToInternetException();
         *      }
         *
         *      responseMsg = await client.GetAsync(await this.AddLocationAndLanguageToApi(url));
         *
         *      string result = responseMsg.Content.ReadAsStringAsync().Result;
         *      if (responseMsg.IsSuccessStatusCode == false)
         *      {
         *          throw new Exception(result);
         *      }
         *
         *      return new ServerResponseObjectsBase
         *      {
         *          RawResponseText = result,
         *          StatusCode = responseMsg.StatusCode,
         *          IsSuccessStatus = responseMsg.IsSuccessStatusCode
         *      };
         *  }
         *  catch (Exception ex)
         *  {
         *      Debug.WriteLine("Call error was " + ex.Message);
         *      return new ServerResponseObjectsBase
         *      {
         *          IsSuccessStatus = false,
         *          RequestException = ex,
         *          StatusCode = responseMsg != null ? responseMsg.StatusCode : HttpStatusCode.ExpectationFailed,
         *          RawResponseText = "{}"
         *      };
         *  }
         * }*/

        /// <summary>
        /// Async method that allows you to send arbitrary JSON string to server
        /// </summary>
        /// <param name="jsonString">The arbitrary JSON string to be sent to the server</param>
        /// <param name="successCallback">The success callback</param>
        /// <param name="filterFlags">Error handling filter flags</param>
        /// <param name="timeOut">Time out in milliseconds</param>
        /// <returns>JSON string on success or null on failure</returns>
        protected async Task <ServerResponseObjectsBase> PostStringAsync(string jsonString, Action <object> successCallback = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            this.Timeout = timeOut;
            HttpResponseMessage responseMsg = null;
            var client = this.DefaultClient;

            foreach (KeyValuePair <string, string> headers in this._extraHeaders)
            {
                client.DefaultRequestHeaders.Add(headers.Key, headers.Value);
            }

            try
            {
                string url = await this.AddLocationAndLanguageToApi(this.ApiPath);

                responseMsg = await client.PostAsync(url, new StringContent(jsonString, Encoding.UTF8, @"application/json"));

                this.NotifyIfErrorStatusCode((uint)responseMsg.StatusCode);
                string rawResponse = await responseMsg.Content.ReadAsStringAsync();

                rawResponse.WriteLine();
                var resp = new ServerResponseObjectsBase
                {
                    RawResponseText = await responseMsg.Content.ReadAsStringAsync(),
                    StatusCode      = responseMsg.StatusCode,
                    IsSuccessStatus = responseMsg.IsSuccessStatusCode
                };

                if (!filterFlags.HasFlag(ErrorFilterFlags.AllowEmptyResponses))
                {
                    this.NotifyIfEmptyResponse(resp.RawResponseText, null);
                }

                if (successCallback != null)
                {
                    successCallback(resp);
                }

                return(resp);
            }
            catch (Exception ex)
            {
                ApiErrorHandler.ExceptionOccured(
                    this,
                    ex,
                    responseMsg != null ? (uint)responseMsg.StatusCode : 0,
                    filterFlags,
                    async x => await this.PostStringAsync(jsonString, successCallback),
                    successCallback);

                return(new ServerResponseObjectsBase
                {
                    IsSuccessStatus = false,
                    RequestException = ex,
                    StatusCode = responseMsg != null ? responseMsg.StatusCode : HttpStatusCode.ExpectationFailed,
                    RawResponseText = "{}"
                });
            }
        }
Example #2
0
        /// <summary>
        /// Makes get calls to the server.
        /// </summary>
        /// <typeparam name="TR">The expected return type</typeparam>
        /// <param name="value">Additional query parameters</param>
        /// <param name="successCallback">A method to be called on success</param>
        /// <param name="filterFlags">The API error filter flags</param>
        /// <param name="timeOut">Timeout in seconds</param>
        /// <returns>Server response that provides information on success/failure of the call and also encapsulates the returned object</returns>
        /// <exception cref="NotConnectedToInternetException">Throws an NotConnectedToInternetException if not connected to the internet when an API call is made</exception>
        /// <exception cref="Exception">Throw a System.Exception for any other error that occurs during processing</exception>
        public virtual async Task <ServerResponse <TR> > MakeGetCallAsync <TR>(string value, Action <object> successCallback = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            this.Timeout = timeOut;

            string url = string.Format(this.GetCallsBasePath, value);

            Logger.Verbose("Url " + url);

            var client = this.DefaultClient;

            foreach (KeyValuePair <string, string> headers in this._extraHeaders)
            {
                client.DefaultRequestHeaders.Add(headers.Key, headers.Value);
            }

            HttpResponseMessage responseMsg = null;

            try
            {
                if (!Resolver.Instance.Get <IConnectivityService>().HasConnection())
                {
                    throw new NotConnectedToInternetException();
                }

                responseMsg = await client.GetAsync(await this.AddLocationAndLanguageToApi(url));

                this.NotifyIfErrorStatusCode((uint)responseMsg.StatusCode);
                var result = await this.GetServerResponsePackaged <TR>(responseMsg);

                if (filterFlags == ErrorFilterFlags.Ignore204)
                {
                    filterFlags = ErrorFilterFlags.AllowEmptyResponses;
                }

                if (!filterFlags.HasFlag(ErrorFilterFlags.AllowEmptyResponses))
                {
                    this.NotifyIfEmptyResponse(result.RawResponse, result.GetObject());
                }

                if (successCallback != null)
                {
                    successCallback(result);
                }

                return(result);
            }
            catch (Exception ex)
            {
                ApiErrorHandler.ExceptionOccured(
                    this,
                    ex,
                    responseMsg != null ? (uint)responseMsg.StatusCode : 0,
                    filterFlags,
                    async x => await this.MakeGetCallAsync <TR>(value, successCallback, filterFlags),
                    successCallback);

                return(new ServerResponse <TR>()
                {
                    IsSuccessStatus = false,
                    RequestException = ex,
                    Status = ServiceReturnStatus.ServerError
                });
            }
        }
Example #3
0
        /// <summary>
        /// Method to send specific JSON String to the server and wait for a response
        /// </summary>
        /// <typeparam name="TR">Response type</typeparam>
        /// <param name="jsonString">JSON payload</param>
        /// <param name="successCallback">Success callback</param>
        /// <param name="filterFlags">Error handling flags</param>
        /// <param name="timeOut">Timeout in seconds</param>
        /// <returns>The server response</returns>
        public async Task <ServerResponse <TR> > PostJsonAsync <TR>(string jsonString, Action <object> successCallback = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            this.Timeout = timeOut;
            HttpResponseMessage responseMsg = null;

            this.Logger.Debug("Passed Json is as below");
            this.Logger.Debug(jsonString);
            try
            {
                // add all extra headers, if any
                HttpClient httpClient = this.DefaultClient;

                foreach (KeyValuePair <string, string> headers in this._extraHeaders)
                {
                    httpClient.DefaultRequestHeaders.Add(headers.Key, headers.Value);
                }

                string url = await this.AddLocationAndLanguageToApi(this.ApiPath);

                StringContent content = new StringContent(jsonString, Encoding.UTF8, @"application/json");

                // check internet connection
                if (!Resolver.Instance.Get <IConnectivityService>().HasConnection())
                {
                    throw new NotConnectedToInternetException();
                }

                responseMsg = await httpClient.PostAsync(url, content);

                this.NotifyIfErrorStatusCode((uint)responseMsg.StatusCode);

                var resp = new ServerResponse <TR>
                {
                    RawResponse     = await responseMsg.Content.ReadAsStringAsync(),
                    StatusCode      = responseMsg.StatusCode,
                    IsSuccessStatus = responseMsg.IsSuccessStatusCode
                };

                if (!filterFlags.HasFlag(ErrorFilterFlags.AllowEmptyResponses))
                {
                    this.NotifyIfEmptyResponse(resp.RawResponse, resp.GetObject());
                }

                if (successCallback != null)
                {
                    successCallback(resp);
                }

                return(resp);
            }
            catch (Exception ex)
            {
                ApiErrorHandler.ExceptionOccured(
                    this,
                    ex,
                    responseMsg != null ? (uint)responseMsg.StatusCode : 0,
                    filterFlags,
                    async x => await PostJsonAsync <TR>(jsonString, successCallback),
                    successCallback);

                return(new ServerResponse <TR>
                {
                    IsSuccessStatus = false,
                    RequestException = ex,
                    StatusCode =
                        responseMsg != null ? responseMsg.StatusCode : HttpStatusCode.ExpectationFailed,
                    RawResponse = "{}"
                });
            }
            finally
            {
                this.Logger.Debug("Exiting PostJsonAsync");
            }
        }
Example #4
0
        public virtual async Task <T> PostObjectAsync <T>(object obj, Action <object> successCallback = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal) where T : ServerResponseObjectsBase
        {
            ServerResponseObjectsBase response = await this.PostStringAsync(JsonConvert.SerializeObject(this.GetPostableData(obj), Formatting.Indented), successCallback, filterFlags, timeOut);

            if (response == null)
            {
                return(default(T));
            }

            return(response.GetResponseObject <T>());
        }
Example #5
0
        /// <summary>
        /// Async method that allows you to send an object TP to the server and receive an object TR in response.
        /// </summary>
        /// <typeparam name="TR">The type of object returned by the API</typeparam>
        /// <typeparam name="TP">The type of object being passed to the API</typeparam>
        /// <param name="obj">The object to be serialized and sent to the server</param>
        /// <param name="successCallback">Method to be called on success</param>
        /// <param name="filterFlags">The error filter flags</param>
        /// <param name="timeOut">Timeout in seconds</param>
        /// <returns>An object of <typeparamref name="TR"/> on successful communication with the server or default(TR) on failure</returns>
        public virtual async Task <ServerResponse <TR> > PostObjectAsync <TR, TP>(TP obj, Action <object> successCallback = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
            where TR : class
        {
            this.Timeout = timeOut;
            this.Logger.Debug(string.Format("Passed object is null = {0}", obj == null));

            ServerResponse <TR> response = await this.PostJsonAsync <TR>(JsonConvert.SerializeObject(obj, Formatting.Indented), successCallback, filterFlags, timeOut);

            this.Logger.Debug(string.Format("Response is null = {0}", response == null));
            return(response);
        }
Example #6
0
        public async Task <CustomerRegistrationResponse> RegisterCustomer(Customer customer, ApiTimeoutEnum timeOut)
        {
            // register custom error handler for 500 error, we want to show toast and continue
            var errorDescriber500 = new ErrorDescriber(
                typeof(HttpResponse500Exception),
                typeof(BackgroundNotifier),
                ErrorFilterFlags.Ignore500Family);

            ApiErrorHandler.RegisterExpectedError(this, errorDescriber500);

            Log.Verbose("Register Customer.");
            ServerResponse <CustomerRegistrationResponse> response =
                await this.PostObjectAsync <CustomerRegistrationResponse, Customer>(customer, timeOut : timeOut);

            Log.Verbose("API call done.");
            if (response == null)
            {
                Log.Verbose("API NOT successfull");

                return(new CustomerRegistrationResponse()
                {
                    Customer = null,
                    RequestId = customer.RequestId,
                    Successful = false,
                    ResponseText = null
                });
            }

            Log.Verbose("API result: " + response.IsSuccessStatus);
            Log.Verbose(response.RawResponse);

            // try getting the object from JSON
            CustomerRegistrationResponse result = null;

            try
            {
                result = response.GetObject();
            }
            catch (Exception e)
            {
                Log.Error(e);
            }

            // got a proper result, return it
            if (result != null)
            {
                result.Successful = true;
                return(result);
            }

            Log.Verbose("Could not parse response.");

            // 500 error occured, special case
            if (response.RequestException.GetType().IsAssignableFrom(typeof(HttpResponse500Exception)))
            {
                return(new CustomerRegistrationResponse
                {
                    Customer = null,
                    RequestId = customer.RequestId,
                    Successful = false,
                    ResponseText = "HttpResponse500Exception"
                });
            }

            // if exception was thrown, return the exception as text
            if (response.RequestException != null)
            {
                return(new CustomerRegistrationResponse
                {
                    Customer = null,
                    RequestId = customer.RequestId,
                    Successful = false,
                    ResponseText = response.RequestException.ToString()
                });
            }

            // unknown error returned
            return(new CustomerRegistrationResponse
            {
                Customer = null,
                RequestId = customer.RequestId,
                Successful = false,
                ResponseText = "Unknown Error."
            });
        }
Example #7
0
        public async Task <T> GetPersonIfExists(string phone, string nationalId = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, bool checkDuplicate = false, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            T person = await this.GetByPhoneNumberAsync(phone, checkDuplicate);

            if (person != null)
            {
                return(person);
            }

            if (!Resolver.Instance.Get <IConnectivityService>().HasConnection())
            {
                return(null);
            }

            person = await this.SearchPersonOnlineAsync(phone, nationalId, filterFlags, timeOut);

            return(person);
        }
Example #8
0
        public async Task <T> SearchPersonOnlineAsync(string phone, string nationalId = null, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            string urlParams = string.Format("?phoneNumber={0}", phone);

            if (!string.IsNullOrEmpty(nationalId))
            {
                urlParams += string.Format("&idNumber={0}", nationalId);
            }

            T person = await new PeopleApis <T>("persons/search").Search(urlParams, filterFlags, timeOut);

            return(person);
        }
Example #9
0
        public async Task <T> Search(string searchParams, ErrorFilterFlags filterFlags, ApiTimeoutEnum timeOut = ApiTimeoutEnum.Normal)
        {
            ServerResponse <T> response = await this.MakeGetCallAsync <T>(searchParams, null, filterFlags, timeOut);

            if (response == null || !response.IsSuccessStatus)
            {
                return(null);
            }

            return(response.GetObject());
        }
Example #10
0
        public async Task <SwapComponentResponse> SwapComponent(SwapComponentRequest request, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling, ApiTimeoutEnum timeout = ApiTimeoutEnum.Long)
        {
            Log.Verbose("Swapping component.");
            ServerResponse <SwapComponentResponse> response = null;

            try
            {
                response = await PostObjectAsync <SwapComponentResponse, SwapComponentRequest>(request, filterFlags : filterFlags, timeOut : timeout);
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(new SwapComponentResponse()
                {
                    Success = false,
                    Status = ServiceReturnStatus.NoInternet,
                    Message = "A connection error has occurred. Check your internet settings."
                });
            }

            Log.Verbose("API call done.");

            if (response == null)
            {
                Log.Verbose("API NOT successfull");
                return(new SwapComponentResponse()
                {
                    Success = false,
                    Status = ServiceReturnStatus.NoInternet,
                    Message = "A connection error has occurred. Check your internet settings."
                });
            }

            Log.Verbose("API result:");
            Log.Verbose(response.RawResponse);

            // try getting the object from JSON
            SwapComponentResponse result = null;

            try
            {
                result = response.GetObject();
            }
            catch (Exception e)
            {
                Log.Error(e);
                return(new SwapComponentResponse()
                {
                    Success = false,
                    Status = ServiceReturnStatus.ParseError,
                    Message = "An error has occurred when getting the server response."
                });
            }

            // got a proper result, return it
            if (result != null)
            {
                return(result);
            }

            Log.Verbose("Could not parse response.");

            return(new SwapComponentResponse()
            {
                Success = false,
                Status = ServiceReturnStatus.ParseError,
                Message = "An error has occurred when getting the server response."
            });
        }