Last active
January 2, 2018 11:14
-
-
Save aliozgur/222c8e5333a126a523d1 to your computer and use it in GitHub Desktop.
Xamarin.Forms : ModernHttpClient wrapper for API calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using ModernHttpClient; | |
using System.Net.Http; | |
using System.Collections.Generic; | |
using System.Threading; | |
using System.Text; | |
namespace MyNamespace | |
{ | |
public class BaseApiResult | |
{ | |
public bool Success | |
{ | |
get; | |
internal set; | |
} | |
public bool Cancelled | |
{ | |
get; | |
internal set; | |
} | |
public string Error | |
{ | |
get; | |
internal set; | |
} | |
} | |
public class ApiContentResult:BaseApiResult | |
{ | |
public string Content | |
{ | |
get; | |
internal set; | |
} | |
} | |
public class ApiResult<T>: BaseApiResult | |
{ | |
public T Data | |
{ | |
get; | |
set; | |
} | |
} | |
public class ApiClient | |
{ | |
public Dictionary<string,string> QueryStringValues | |
{ | |
get; | |
set; | |
} | |
public ApiClient() | |
{ | |
QueryStringValues = new Dictionary<string,string>(); | |
} | |
private async Task<ApiContentResult> SendAsync(string baseUrl, object content, HttpMethod method, CancellationToken cancellationToken, bool api = true) | |
{ | |
ApiContentResult result = new ApiContentResult(); | |
using (var handler = new NativeMessageHandler()) | |
{ | |
using (HttpClient client = new HttpClient(handler)) | |
{ | |
var qs = ApiUtils.PrepareQueryString(QueryStringValues); | |
var url = String.Format("{0}{1}", baseUrl, String.IsNullOrEmpty(qs) ? String.Empty : "?" + qs); | |
var request = api ? ApiUtils.CreateWebApiRequestMessage(url, content, method) : ApiUtils.CreateWebRequestMessage(url, content, method);; | |
try | |
{ | |
using (var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false)) | |
{ | |
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); | |
result.Content = responseContent; | |
result.Success = IsResponseCodeValid(response); | |
} | |
} | |
catch (OperationCanceledException) | |
{ | |
result.Cancelled = true; | |
result.Success = false; | |
result.Error = "Request cancelled by the user"; | |
} | |
catch (AggregateException agex) | |
{ | |
StringBuilder sb = new StringBuilder(); | |
foreach (var x in agex.InnerExceptions) | |
{ | |
sb.AppendLine(x.Message); | |
} | |
result.Error = sb.ToString(); | |
result.Success = false; | |
} | |
catch (Exception ex) | |
{ | |
result.Success = false; | |
result.Error = ex.Message.Contains("NameResolutionFailure") ? "Check your server address and internet connection".Localize(K.NameResolutionError) : ex.Message; | |
} | |
} | |
} | |
return result; | |
} | |
private bool IsResponseCodeValid(HttpResponseMessage response) | |
{ | |
var statusCode = (int)response.StatusCode; | |
return statusCode >= 200; | |
// var statusCode = response.StatusCode; | |
// return statusCode == System.Net.HttpStatusCode.OK || statusCode == System.Net.HttpStatusCode.Accepted | |
// || statusCode == System.Net.HttpStatusCode.Created | |
// || statusCode == System.Net.HttpStatusCode.NoContent | |
// || statusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation | |
// || statusCode == System.Net.HttpStatusCode.PartialContent; | |
} | |
public async Task<ApiContentResult> GetAsync(string baseUrl, CancellationToken cancellationToken, bool api = true) | |
{ | |
return await SendAsync(baseUrl, null, HttpMethod.Get, cancellationToken, api).ConfigureAwait(false); | |
} | |
public async Task<ApiContentResult> DeleteAsync(string baseUrl, object content, CancellationToken cancellationToken, bool api = true) | |
{ | |
return await SendAsync(baseUrl, content, HttpMethod.Delete, cancellationToken, api).ConfigureAwait(false); | |
} | |
public async Task<ApiContentResult> DeleteAsync(string baseUrl, CancellationToken cancellationToken, bool api = true) | |
{ | |
return await DeleteAsync(baseUrl, null, cancellationToken, api).ConfigureAwait(false); | |
} | |
public async Task<ApiContentResult> PutAsync(string baseUrl, object content, CancellationToken cancellationToken, bool api = true) | |
{ | |
return await SendAsync(baseUrl, content, HttpMethod.Put, cancellationToken, api).ConfigureAwait(false); | |
} | |
public async Task<ApiContentResult> PostAsync(string baseUrl, object content, CancellationToken cancellationToken, bool api = true) | |
{ | |
return await SendAsync(baseUrl, content, HttpMethod.Post, cancellationToken, api).ConfigureAwait(false); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net.Http; | |
using Newtonsoft.Json; | |
using System.Net.Http.Headers; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using Newtonsoft.Json.Serialization; | |
using System.Net; | |
namespace MyNamespace | |
{ | |
public class ApiUtils | |
{ | |
public static HttpRequestMessage CreateWebApiRequestMessage(string url, object payload, HttpMethod method) | |
{ | |
if (String.IsNullOrWhiteSpace(UserSession.AuthToken.ApiUrl)) | |
return null; | |
HttpRequestMessage result = new HttpRequestMessage(); | |
result.Headers.Add("Accept", "application/json"); | |
result.Method = method; | |
result.Headers.Authorization = new AuthenticationHeaderValue("Bearer", UserSession.AuthToken.AccsessToken); | |
result.Content = payload != null | |
? new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json") | |
: null; | |
result.RequestUri = new Uri(UserSession.AuthToken.ApiUrl + url); | |
return result; | |
} | |
public static HttpRequestMessage CreateWebRequestMessage(string url, object payload, HttpMethod method) | |
{ | |
if (String.IsNullOrWhiteSpace(UserSession.AuthToken.ApiUrl)) | |
return null; | |
HttpRequestMessage result = new HttpRequestMessage(); | |
result.Headers.Add("Accept", "application/json"); | |
result.Method = method; | |
result.Headers.Authorization = new AuthenticationHeaderValue("Bearer", UserSession.AuthToken.AccsessToken); | |
result.Content = payload != null | |
? new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json") | |
: null; | |
result.RequestUri = new Uri(UserSession.AuthToken.BaseUrl + url); | |
return result; | |
} | |
public static string PrepareQueryString(Dictionary<string,string> values) | |
{ | |
if (values == null || values.Count == 0) | |
return String.Empty; | |
var pairs = values.Select(x => x.Key + "=" + WebUtility.UrlEncode(x.Value)); | |
return String.Join("&", pairs); | |
} | |
public static string PrepareQueryString(Dictionary<string,object> values) | |
{ | |
if (values == null || values.Count == 0) | |
return String.Empty; | |
var pairs = values.Select(x => x.Key + "=" + (x.Value != null? WebUtility.UrlEncode(x.Value.ToString()): String.Empty)); | |
return String.Join("&", pairs); | |
} | |
public static PmsApiResponseWithData<PagedResult<T>> StringToApiResponseWithPagedResult<T>(string content) where T : class | |
{ | |
var settings = new JsonSerializerSettings(){ ContractResolver = new CamelCasePropertyNamesContractResolver() }; | |
var responseData = JsonConvert.DeserializeObject<PmsApiResponseWithData<PagedResult<T>> >(content, settings); | |
return responseData; | |
} | |
public static PagedResult<T> StringToPagedApiResult<T>(string content) where T : class | |
{ | |
var apiResponse = StringToApiResponseWithPagedResult<T>(content); | |
return apiResponse.Data; | |
} | |
public static PmsApiResponse StringToApiResponse(string content) | |
{ | |
var settings = new JsonSerializerSettings(){ ContractResolver = new CamelCasePropertyNamesContractResolver() }; | |
var responseData = JsonConvert.DeserializeObject<PmsApiResponse>(content, settings); | |
return responseData; | |
} | |
public static PmsApiResponseWithData<T> StringToApiResponseWithData<T>(string content) | |
{ | |
var settings = new JsonSerializerSettings(){ ContractResolver = new CamelCasePropertyNamesContractResolver() }; | |
var responseData = JsonConvert.DeserializeObject<PmsApiResponseWithData<T>>(content, settings); | |
return responseData; | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
using System.Threading; | |
namespace MyNamespace | |
{ | |
public class AlarmDefService | |
{ | |
public string LastError | |
{ | |
get; | |
set; | |
} | |
public AlarmDefService() | |
{ | |
} | |
public async Task<PagedResult<AlarmDefinitionDetailDto>> GetAllAsync(CancellationToken cancellationToken) | |
{ | |
LastError = String.Empty; | |
var baseUrl = "alarm"; | |
ApiClient client = new ApiClient(); | |
var responseResult = await client.GetAsync(baseUrl, cancellationToken).ConfigureAwait(false); | |
if (responseResult.Success && !String.IsNullOrWhiteSpace(responseResult.Content)) | |
{ | |
var result = ApiUtils.StringToApiResponseWithPagedResult<AlarmDefinitionDetailDto>(responseResult.Content); | |
return result == null? null: result.Data; | |
} | |
else | |
{ | |
LastError = responseResult.Cancelled ? String.Empty : responseResult.Error; | |
return null; | |
} | |
} | |
public async Task<bool> Add(NewAlarmDefinitionDto alarm, CancellationToken cancellationToken) | |
{ | |
LastError = String.Empty; | |
var baseUrl = "alarm"; | |
ApiClient client = new ApiClient(); | |
var responseResult = await client.PostAsync(baseUrl, alarm, cancellationToken).ConfigureAwait(false); | |
if (responseResult.Success && !String.IsNullOrWhiteSpace(responseResult.Content)) | |
{ | |
var result = ApiUtils.StringToApiResponseWithData<int>(responseResult.Content); | |
return result.Success; | |
} | |
else | |
{ | |
LastError = responseResult.Cancelled ? String.Empty : responseResult.Error; | |
return false; | |
} | |
} | |
public async Task<bool> Save(PatchAlarmDefinitionDto alarm, CancellationToken cancellationToken) | |
{ | |
LastError = String.Empty; | |
var baseUrl = "alarm/{0}".Fmt(alarm.Id); | |
ApiClient client = new ApiClient(); | |
var responseResult = await client.PostAsync(baseUrl, alarm, cancellationToken).ConfigureAwait(false); | |
if (responseResult.Success && !String.IsNullOrWhiteSpace(responseResult.Content)) | |
{ | |
var result = ApiUtils.StringToApiResponseWithData<int>(responseResult.Content); | |
return result.Success; | |
} | |
else | |
{ | |
LastError = responseResult.Cancelled ? String.Empty : responseResult.Error; | |
return false; | |
} | |
} | |
public async Task<bool> Delete(int id, CancellationToken cancellationToken) | |
{ | |
LastError = String.Empty; | |
var baseUrl = "alarm/{0}".Fmt(id); | |
ApiClient client = new ApiClient(); | |
var responseResult = await client.DeleteAsync(baseUrl, cancellationToken).ConfigureAwait(false); | |
if (responseResult.Success && !String.IsNullOrWhiteSpace(responseResult.Content)) | |
{ | |
var result = ApiUtils.StringToApiResponse(responseResult.Content); | |
return result.Success; | |
} | |
else | |
{ | |
LastError = responseResult.Cancelled ? String.Empty : responseResult.Error; | |
return false; | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment