public

A generic type Request helper class for Windows Azure Mobile Services

  • Download Gist
MobileServiceRequestHelper.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
public class MobileServiceRequestHelper<T> where T : class
{
private string tableEndpoint;
private string applicationKey;
private HttpClient client;
public MobileServiceRequestHelper(string tableName)
{
tableEndpoint = ConfigurationManager.AppSettings["TableEndpoint"] + tableName ;
applicationKey = ConfigurationManager.AppSettings["X-ZUMO-APPLICATION"];
client = new HttpClient();
client.DefaultRequestHeaders.Add("X-ZUMO-APPLICATION", applicationKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public IEnumerable<T> GetAll()
{
var result = client.GetStringAsync(tableEndpoint).Result;
var data = JsonConvert.DeserializeObject<IEnumerable<T>>(result);
return data;
}
public T Get(int id)
{
var result = client.GetStringAsync(tableEndpoint + "?$filter=Id eq " + id).Result;
var data = JsonConvert.DeserializeObject<IEnumerable<T>>(result);
return data.FirstOrDefault();
}
public bool Post(T requestData)
{
var obj = JsonConvert.SerializeObject(requestData, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
var request = new HttpRequestMessage(HttpMethod.Post, tableEndpoint);
request.Content = new StringContent(obj, Encoding.UTF8, "application/json");
var data = client.SendAsync(request).Result;
if (data.IsSuccessStatusCode)
return true;
else
throw new HttpResponseException(data.StatusCode);
}
public bool Put(T requestData, int id)
{
var request = new HttpRequestMessage(new HttpMethod("PATCH"), tableEndpoint + id);
var obj = JsonConvert.SerializeObject(requestData);
request.Content = new StringContent(obj, Encoding.UTF8, "application/json");
var data = client.SendAsync(request).Result;
if (data.IsSuccessStatusCode)
return true;
else
throw new HttpResponseException(data.StatusCode);
}
public void Delete(int id)
{
var request = new HttpRequestMessage(HttpMethod.Delete, tableEndpoint + id.ToString());
var data = client.SendAsync(request).Result;
if (!data.IsSuccessStatusCode)
throw new HttpResponseException(data.StatusCode);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.