Created
May 12, 2013 09:17
-
-
Save shijuvar/5562928 to your computer and use it in GitHub Desktop.
A generic type Request helper class for Windows Azure Mobile Services
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
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment