Created
March 25, 2014 19:11
-
-
Save cerkit/9769016 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Newtonsoft.Json; | |
using RecordKeeper.Portable.Models; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
namespace PortableClient.WebApi.Dal.Services | |
{ | |
public class EntityService<TEntity> where TEntity : EntityBase | |
{ | |
protected static string API_BASE_PATH = "http://localhost:YOUR_PORT_HERE/api/"; | |
public EntityService() { } | |
public static async Task<IEnumerable<TEntity>> Get(string apiPath, ICredentials credentials = null) | |
{ | |
string uri = API_BASE_PATH + apiPath; | |
HttpClientHandler handler = new HttpClientHandler(); | |
if (credentials != null) | |
{ | |
handler.Credentials = credentials; | |
} | |
HttpClient client = new HttpClient(handler); | |
string responseBody = await client.GetStringAsync(uri); | |
List<TEntity> items = ListFromJson(responseBody); | |
return items.AsEnumerable<TEntity>(); | |
} | |
public static async Task<TEntity>Get(string apiPath, string id, ICredentials credentials = null) | |
{ | |
string uri = API_BASE_PATH + apiPath + "/" + id; | |
HttpClientHandler handler = new HttpClientHandler(); | |
if (credentials != null) | |
{ | |
handler.Credentials = credentials; | |
} | |
HttpClient client = new HttpClient(handler); | |
string responseBody = await client.GetStringAsync(uri); | |
TEntity item = FromJson(responseBody); | |
return item; | |
} | |
public static async void Update(string apiPath, TEntity entity, ICredentials credentials = null) | |
{ | |
string uri = API_BASE_PATH + apiPath + "/" + entity.Id; | |
HttpClientHandler handler = new HttpClientHandler(); | |
if (credentials != null) | |
{ | |
handler.Credentials = credentials; | |
} | |
HttpClient client = new HttpClient(handler); | |
// PUT the new entity on the server for an update | |
var responseBody = await client.PutAsJsonAsync<TEntity>(uri, entity); | |
} | |
public static TEntity FromJson(string json) | |
{ | |
TEntity entity; | |
JsonSerializer s = new JsonSerializer(); | |
StringReader sr = new StringReader(json); | |
JsonTextReader r = new JsonTextReader(sr); | |
entity = s.Deserialize<TEntity>(r); | |
return entity; | |
} | |
public static List<TEntity> ListFromJson(string json) | |
{ | |
List<TEntity> entityList; | |
JsonSerializer s = new JsonSerializer(); | |
StringReader sr = new StringReader(json); | |
JsonTextReader r = new JsonTextReader(sr); | |
entityList = s.Deserialize<List<TEntity>>(r); | |
return entityList; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment