using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using Loyalty.Common.Contracts;
using Loyalty.Common.Exceptions;
using Loyalty.Common.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Loyalty.AdminPortal.Services.Services
{
public class JsonServiceWithHeaders : IUnderstandJson
{
private readonly JsonSerializerSettings settings;
public JsonServiceWithHeaders()
{
settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
}
public T Get<T>(string uri)
{
var request = CreateRequest(uri, "GET");
return PerformRequest<T>(request);
}
public T Get<T>(string uri, object data)
{
var uriWithQuery = string.Format("{0}?{1}", uri, data.ToQueryString());
var request = CreateRequest(uriWithQuery, "GET");
return PerformRequest<T>(request);
}
public T Post<T>(string url)
{
return Post<T>(url, null);
}
public T Post<T>(string url, object data)
{
var request = CreateRequest(url, "POST");
if (data != null)
WriteRequestBody(data, request);
else
request.ContentLength = 0;
return PerformRequest<T>(request);
}
public T Put<T>(string url)
{
return Put<T>(url, null);
}
public T Put<T>(string url, object data)
{
var request = CreateRequest(url, "PUT");
if (data != null)
WriteRequestBody(data, request);
else
request.ContentLength = 0;
return PerformRequest<T>(request);
}
private T PerformRequest<T>(HttpWebRequest request)
{
try
{
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var responseText = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(responseText);
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError && e.Response != null)
{
var response = (HttpWebResponse)e.Response;
if (response.StatusCode == HttpStatusCode.NotFound)
return default(T);
}
var message = "Unknown remote error.";
if (e.Response != null)
{
using (var reader = new StreamReader(e.Response.GetResponseStream()))
message = reader.ReadToEnd();
}
throw new RemoteServerException(message);
}
}
private void WriteRequestBody(object data, HttpWebRequest request)
{
var json = JsonConvert.SerializeObject(data, Formatting.Indented, settings);
var jsonBytes = Encoding.UTF8.GetBytes(json);
var stream = request.GetRequestStream();
stream.Write(jsonBytes, 0, jsonBytes.Length);
stream.Close();
}
private HttpWebRequest CreateRequest(string uri, string method)
{
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = method;
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json, text/javascript, */*; q=0.01";
request.Headers["X-ApiAuth-Username"] = ConfigurationManager.AppSettings["Security.Username"];
return request;
}
}
}
namespace Loyalty.Common.Contracts
{
public interface IUnderstandJson
{
T Get<T>(string uri);
T Get<T>(string uri, object data);
T Post<T>(string uri);
T Post<T>(string uri, object data);
T Put<T>(string uri);
T Put<T>(string uri, object data);
}