Skip to content

Instantly share code, notes, and snippets.

@bjarki
Created February 23, 2012 09:59
Show Gist options
  • Save bjarki/1892035 to your computer and use it in GitHub Desktop.
Save bjarki/1892035 to your computer and use it in GitHub Desktop.
A base for clients that the HttpClient(beta)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using System.Runtime.Serialization.Json;
namespace ElectronicValueCodes.Client
{
public abstract class BaseClient
{
private readonly HttpClient service;
public BaseClient(string url)
: this(new Uri(url))
{ }
public BaseClient(Uri url)
{
MediaTypeFormatter.SkipStreamLimitChecks = true;
service = new HttpClient();
service.MaxResponseContentBufferSize = 196608;
service.BaseAddress = url;
}
public Task<T> Get<T>(string method, int? id = null)
{
if (!method.EndsWith("/"))
method = method + "/";
return service.GetAsync(method + id).ContinueWith((resultTask) =>
{
return resultTask.Result.Content.ReadAsAsync<T>();
}).Unwrap();
}
protected Task<T> Get<T>(int? id = null)
{
var method = Method<T>();
return service.GetAsync(method + "/" + id).ContinueWith((responseTask) =>
{
return responseTask.Result.Content.ReadAsAsync<T>();
}).Unwrap();
}
protected Task<T> Create<T>(T item)
{
var method = Method<T>();
var req = RequestObject(item);
return service.PostAsync(method, req.Content).ContinueWith((reslutTask) =>
{
return reslutTask.Result.Content.ReadAsAsync<T>();
}).Unwrap();
}
protected Task<T> Create<T, Y>(Y item)
{
var req = RequestObject(item);
var method = Method<T>();
return service.PostAsync(method, req.Content).ContinueWith((reslutTask) =>
{
return reslutTask.Result.Content.ReadAsAsync<T>();
}).Unwrap();
}
protected void Update<T>(T item, int id)
{
var method = Method<T>() + "/" + id;
Update<T>(item, method);
}
protected void Update<T>(T item, string method)
{
var req = RequestObject(item);
service.PutAsync(method, req.Content);
}
private HttpRequestMessage<T> RequestObject<T>(T item)
{
var req = new HttpRequestMessage<T>(item);
req.Content.Headers.ContentType = new MediaTypeHeaderValue("text/json");
return req;
}
private string Method<T>()
{
var method = typeof(T).Name;
if (method.EndsWith("s"))
return method;
return method + "s";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment