/// <summary> /// This is the method that is used for post device regiatration login. /// It will automatically try to login three time before returning /// </summary> /// <param name="phone">The phone number of the individual logging in</param> /// <param name="pin">The associated pin</param> /// <param name="filterFlags">Flags to help ignore some API errors</param> /// <returns>Null if login failed or on success a DsrProfile object containing details of user who's logged in</returns> public async Task <LoginResponse> Login(string phone, string pin, ErrorFilterFlags filterFlags) { for (int i = 0; i < this.MaxOnlineTries; i++) { LoginResponse response = await this.Login(phone, pin, false, filterFlags); if (response.Code == LoginResponseCode.Success || response.Code == LoginResponseCode.Unauthorized) { if (response.Code == LoginResponseCode.Success) { this.Logger.Debug(string.Format("Online login succeeded at attempt {0}", i)); } else { this.Logger.Debug(string.Format("Wrong credentials at attempt {0}", i)); } return(response); } this.Logger.Debug(string.Format("Online login failed at attempt {0}", i)); } this.Logger.Debug(string.Format("Online login failed after {0} attempts", this.MaxOnlineTries)); return(new LoginResponse() { Code = LoginResponseCode.Unknown }); }
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()); }
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>()); }
public ErrorDescriber(Type exceptionType, Type uiNotifierType, ErrorFilterFlags filterFlag) { this.ExceptionType = exceptionType; this.UiNotifierType = uiNotifierType; this.FilterFlag = filterFlag; }
internal static void ExceptionOccured <TResult>(object sender, Exception exception, uint httpStatusCode, ErrorFilterFlags filterFlags, Func <Action <object>, Task <TResult> > retryAction = null, Action <object> successCallback = null, string errorCode = "") where TResult : class { Logger.Initialize(sender.GetType().FullName); Logger.Error(exception); if ((filterFlags & ErrorFilterFlags.DisableErrorHandling) == ErrorFilterFlags.DisableErrorHandling) { return; } if (_errorOccuredCallback == null) { return; } exception = GetExceptionOverridden(exception, httpStatusCode); ErrorDescriber desc = _knownErrors.FirstOrDefault(item => item.ExceptionType == exception.GetType()); ErrorDescriber errorDescription = desc ?? new ErrorDescriber(exception.GetType(), typeof(Dialog), ErrorFilterFlags.EnableErrorHandling); if ((filterFlags & errorDescription.FilterFlag) == errorDescription.FilterFlag) { return; } errorDescription.ErrorCode = errorCode; errorDescription.HttpStatusCode = httpStatusCode; if (retryAction != null) { if (successCallback != null) { errorDescription.SuccessCallback = successCallback; errorDescription.RetryAction = async x => { var result = await retryAction(successCallback); successCallback(result); }; } } _errorOccuredCallback(errorDescription); }
public async Task <bool> ShowOverlayIfPhoneNumberDuplicate(string phone, string nationalId = null) { ErrorFilterFlags flag = ErrorFilterFlags.DisableErrorHandling; Person person; SalesApp.Core.BL.Models.People.Customer customer = await new CustomersController().GetPersonIfExists(phone, nationalId, filterFlags: flag, checkDuplicate: false); SalesApp.Core.BL.Models.People.Prospect prospect = null; if (customer == null) { prospect = await new ProspectsController().GetPersonIfExists(phone, filterFlags: flag, checkDuplicate: false); person = JsonConvert.DeserializeObject <Person>(JsonConvert.SerializeObject(prospect)); } else { if (customer.PersonType == PersonTypeEnum.Prospect) { prospect = JsonConvert.DeserializeObject <SalesApp.Core.BL.Models.People.Prospect>( JsonConvert.SerializeObject(customer)); } else { string urlParam = customer.Phone + "&foradditionalproduct=true"; CustomerStatus customerStatus = await new CustomerStatusApi().GetAsync(urlParam); if (customerStatus != null) { customer.AccountStatus = customerStatus.AccountStatus; } } person = JsonConvert.DeserializeObject <Person>(JsonConvert.SerializeObject(customer)); } if (person == null) { return(false); } this._fragmentInfo = new FragmentInfo(); this._fragmentInfo.SetArgument(FragmentInfo.ResourceIdBundleKey, Resource.Layout.fragment_unified_existing_person); this._fragmentInfo.ViewCreated += (sender, args) => { ViewsHelper <Person> viewsHelper = new ViewsHelper <Person>(Activity as ActivityBase, _fragmentInfo.InflatedView); viewsHelper.BindEvent ( BindableEvents.OnClick , Resource.Id.linEditCustomer , linEditCustomer => { WizardActivity.HideOverlay(true); }); viewsHelper.BindEvent( BindableEvents.OnClick, Resource.Id.linAddProduct, linAddProduct => { // if doing prospect registration, do conversion to customer if (WizardActivity.WizardType == WizardTypes.ProspectRegistration) { // do conversion to customer if (person.PersonType == PersonTypeEnum.Prospect) { ProspectSearchResult psr = JsonConvert.DeserializeObject <ProspectSearchResult>(JsonConvert.SerializeObject(prospect)); Dictionary <string, object> bundledItems = new Dictionary <string, object>(); bundledItems.Add(KeyProspectIdBundled, psr); WizardLauncher.Launch(Activity, WizardTypes.CustomerRegistration, WizardActivity.StartPoint, bundledItems); } else { // posible additional product if (customer != null) { WizardActivity.HideOverlay(true); IsAdditionalProduct = true; WizardActivity.IsProspectConversion = true; CustomerSearchResult csr = JsonConvert.DeserializeObject <CustomerSearchResult>(JsonConvert.SerializeObject(customer)); Dictionary <string, object> bundledItems = new Dictionary <string, object>(); bundledItems.Add(KeyCustomerIdBundled, csr); WizardLauncher.Launch(Activity, WizardTypes.CustomerRegistration, WizardActivity.StartPoint, bundledItems); } } } else { // customer registration if (person.PersonType == PersonTypeEnum.Prospect) { // auto fill the details FillFromExistingRecord(prospect); WizardActivity.IsProspectConversion = true; } else { // auto fill the details FillFromExistingRecord(customer); } WizardActivity.HideOverlay(true); IsAdditionalProduct = true; // though this may be cheating ;) WizardActivity.GoNext(); } }); viewsHelper.Write(Resource.Id.tvPersonName, person.FullName); viewsHelper.Write(Resource.Id.tvPhone, person.Phone); viewsHelper.WriteBoundViews(customer); if (customer != null && customer.AccountStatus != null && !customer.AccountStatus.Equals("Active")) { ShowConversionButton(_fragmentInfo.InflatedView, ViewStates.Gone); ShowPersonStatus(_fragmentInfo.InflatedView); } if (person.PersonType == PersonTypeEnum.Prospect) { // show conversion button ShowConversionButton(_fragmentInfo.InflatedView, ViewStates.Visible); } }; WizardActivity.ShowOverlay(_fragmentInfo, false); return(true); }
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); }
public async Task <CustomerDetailsResponse> GetCustomerDetails(string customerParams, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling) { Log.Verbose("Get details of a customer."); ServerResponse <CustomerDetailsResponse> response = null; try { response = await MakeGetCallAsync <CustomerDetailsResponse>(customerParams, filterFlags : filterFlags); } catch (Exception e) { Log.Verbose("Error during API call."); Log.Error(e); return(new CustomerDetailsResponse() { Successful = false, Status = ServiceReturnStatus.NoInternet, }); } Log.Verbose("API call done."); if (response == null || response.StatusCode != HttpStatusCode.OK || string.IsNullOrEmpty(response.RawResponse)) { Log.Verbose("API call not successfull"); return(new CustomerDetailsResponse() { Successful = false, Status = ServiceReturnStatus.NoInternet, }); } Log.Verbose(response.RawResponse); // try getting the object from JSON CustomerDetailsResponse result = null; try { result = response.GetObject(); } catch (Exception e) { Log.Verbose("Error try getting the object from JSON."); Log.Error(e); return(new CustomerDetailsResponse() { Successful = false, Status = ServiceReturnStatus.ParseError }); } // got a proper result, return it if (result != null) { result.Successful = true; if (result.CustomerFound) { if (result.Surname != null) { result.Surname = result.Surname.Trim(); } if (result.OtherNames != null) { result.OtherNames = result.OtherNames.Trim(); } } return(result); } return(new CustomerDetailsResponse() { Successful = false, CustomerFound = false }); }
/// <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"); } }
public async virtual Task <TServerResponse> GetAsync(string queryString, ErrorFilterFlags flags = ErrorFilterFlags.EnableErrorHandling) { var result = await GetRawServerReponseAsync(queryString, flags); return(result.GetObject()); }
/// <summary> /// Attempts to perform an online login /// </summary> /// <param name="phone">The phone number of the individual logging in</param> /// <param name="pin">The associated pin</param> /// <param name="isFirstTime">Flag for whether it is the first time the individual is log</param> /// <param name="filterFlags">Flags to help ignore some API errors</param> /// <returns>Null if login failed or on success a DsrProfile object containing details of user who's logged in</returns> public async Task <LoginResponse> Login(string phone, string pin, bool isFirstTime, ErrorFilterFlags filterFlags) { try { if (pin == null) { return(new LoginResponse { Code = LoginResponseCode.WrongParameters }); } if (phone == null) { return(new LoginResponse { Code = LoginResponseCode.WrongParameters }); } IHashing hashing = Resolver.Instance.Get <IHashing>(); string hash = hashing.HashPassword(phone, pin); string credentials = string.Format("{0}:{1}", phone, hash); byte[] bytes = hashing.GetBytes(credentials); string base64 = Convert.ToBase64String(bytes); this.RemoveHeader("Authorization"); this.AddHeader("Authorization", " Basic " + base64); ServerResponse <LoginResponse> response = await PostObjectAsync <LoginResponse, LoginDto>( new LoginDto { Hash = hash, IsFirstLogin = isFirstTime, DeviceInformation = Resolver.Instance.Get <IInformation>() }, null, filterFlags); this.Logger.Debug("Call to login api completed"); if (response == null) { this.Logger.Debug("Response is null"); return(new LoginResponse() { Code = LoginResponseCode.HttpError }); } if (response.StatusCode == HttpStatusCode.Unauthorized) { this.Logger.Debug("HttpStatusCode.Unauthorized"); return(new LoginResponse() { Code = LoginResponseCode.Unauthorized }); } if (!response.IsSuccessStatus) { this.Logger.Debug("IsSuccessStatus = false"); return(new LoginResponse() { Code = LoginResponseCode.HttpError }); } this.Logger.Debug("Persisting user hash"); Resolver.Instance.Get <ISalesAppSession>().UserHash = base64; this.Logger.Debug("deserializing response text to object"); LoginResponse loginResponse = response.GetObject(); if (loginResponse.Permissions == null || !loginResponse.Permissions.Any()) { this.Logger.Debug("Looks like we don't yet support permissions. Lets fake some."); var vals = Enum.GetNames(typeof(Permissions)); loginResponse.Permissions = new List <Permission>(); foreach (string value in vals) { this.Logger.Debug(string.Format("Faking permission: {0}", value)); loginResponse.Permissions.Add( new Permission { Name = value, PermissionId = (uint)Enum.Parse(typeof(Permissions), value) }); } } this.Logger.Debug(string.Format("Updating permissions total permissions count {0}", loginResponse.Permissions.Count)); await PermissionsController.Instance.UpdatePermissionsAsync(loginResponse.Permissions); this.Logger.Debug("Login went smoothly... Exiting method and returning result"); loginResponse.Code = LoginResponseCode.Success; return(loginResponse); } catch (Exception ex) { this.Logger.Error(ex); return(new LoginResponse() { Code = LoginResponseCode.Unknown }); } }
public async Task <ServerResponse <List <BL.Product> > > GetAsync(string urlParams = null, ErrorFilterFlags flags = ErrorFilterFlags.EnableErrorHandling) { ServerResponse <List <BL.Product> > serverResponse = await this.MakeGetCallAsync <List <BL.Product> >(urlParams, null, flags); if (serverResponse.IsSuccessStatus) { return(serverResponse); } return(null); }
public async Task <ProductComponentsResponse> GetProductDetails(string productParams, ErrorFilterFlags filterFlags = ErrorFilterFlags.EnableErrorHandling) { Log.Verbose("Get components of a product."); ServerResponse <List <ProductComponent> > response = null; try { response = await MakeGetCallAsync <List <ProductComponent> >(productParams, filterFlags : filterFlags); } catch (Exception e) { Log.Error(e); } Log.Verbose("API call done."); if (response == null) { Log.Verbose("API NOT successfull"); return(new ProductComponentsResponse() { Successful = false, ResponseText = "not_connected", }); } Log.Verbose(response.RawResponse); // try getting the object from JSON List <ProductComponent> components = null; ProductComponentsResponse result = null; try { components = response.GetObject(); result = new ProductComponentsResponse { ProductComponents = components, }; } 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."); return(new ProductComponentsResponse() { Successful = false, }); }
/// <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); }
public async virtual Task <ServerResponse <TServerResponse> > GetRawServerReponseAsync(string queryString, ErrorFilterFlags flags) { Logger.Debug("Making get call for remote service ~".GetFormated(GetType().Name)); Logger.Debug("Get query string is ~".GetFormated(queryString)); string jsonString = ""; try { if (Api == null) { Api = Activator.CreateInstance <TApiClass>(); } ServerResponse <TServerResponse> serverResponse = await this.Api.MakeGetCallAsync <TServerResponse>(queryString, null, flags); if (serverResponse == null) { Logger.Verbose("No results."); } else if (serverResponse.IsSuccessStatus) { jsonString = serverResponse.RawResponse; return(serverResponse); } } catch (JsonReaderException jsonReaderException) { HandleException ( jsonReaderException , "Attempt to parse invalid JSON may have been made." + " JSON: " + jsonString ); } catch (NotConnectedToInternetException notConnectedToInternetException) { HandleException ( notConnectedToInternetException , "Unable to connect internet. Could connection have dropped?" ); } catch (TaskCanceledException taskCanceled) { HandleException(taskCanceled, "Timeout may have occured or task may have been explicitly canceled by user."); } catch (Exception exception) { HandleException(exception, "Exception: " + exception.Message); } return(new ServerResponse <TServerResponse> { IsSuccessStatus = false , RawResponse = JsonConvert.SerializeObject(Activator.CreateInstance <TServerResponse>()) , StatusCode = HttpStatusCode.Ambiguous , RequestException = null }); }
/// <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 }); } }
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); }
/*/// <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 = "{}" }); } }
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." }); }