Skip to content

Instantly share code, notes, and snippets.

@dmannock
Created August 29, 2015 08:48
Show Gist options
  • Select an option

  • Save dmannock/437b8db1be2751d351ec to your computer and use it in GitHub Desktop.

Select an option

Save dmannock/437b8db1be2751d351ec to your computer and use it in GitHub Desktop.
public class ServiceProxy
{
public static TimeSpan Timeout { get; protected set; }
public ServiceProxy()
{
Timeout = TimeSpan.FromSeconds(10);
}
public ServiceProxy(TimeSpan timeout)
{
Timeout = timeout;
}
public async void HandleServiceRequest(Guid id, string name, dynamic data)
{
string responseData = "";
Uri serviceUrl = new Uri("http://127.0.0.1:65535");
try
{
serviceUrl = LookupServiceURL(name);
responseData = await PostJsonAsync(serviceUrl, data);
}
catch (HttpRequestException ex)
{
//send failed here
// new ServiceResponse.Failed {
// ServiceName = name,
// ServiceUri = serviceUrl,
// ErrorMessage = string.Format("Service {0} Request Exception: {1}", name, ex.Message),
// When = DateTime.Now
// };
return;
}
catch (TaskCanceledException ex)
{
//send timeout here
// new ServiceResponse.Timeout {
// Duration = Timeout,
// ServiceName = name,
// ServiceUri = serviceUrl,
// ErrorMessage = string.Format("Request {0} Cancelled Exception: {1}", name, ex.Message),
// When = DateTime.Now
// }
return;
}
catch (Exception ex)
{
//send general failed here
// new ServiceResponse.Failed {
// ServiceName = name,
// ServiceUri = serviceUrl,
// ErrorMessage = string.Format("Service {0} Exception: {1}" + ex.Message, name, ex.Message),
// When = DateTime.Now
// }
return;
}
if (!string.IsNullOrEmpty(responseData))
{
dynamic payload = JsonConvert.DeserializeObject(responseData);
//send success here
// new ServiceResponse.Success {
// Payload = payload,
// ServiceName = name,
// ServiceUri = serviceUrl,
// When = DateTime.Now
}
}
public Uri LookupServiceURL(string serviceName)
{
var serviceNameSettingKey = serviceName;
var value = System.Configuration.ConfigurationManager.AppSettings[serviceNameKey];
var serviceUrl = new Uri(value.TrimEnd('/'));
return serviceUrl;
}
public async Task<string> PostJsonAsync(Uri url, dynamic content)
{
// Create an HttpClient instance
using (var client = new HttpClient())
{
client.Timeout = Timeout;
var postContent = new StringContent(JsonConvert.SerializeObject(content), UTF8Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send a request asynchronously continue when complete
HttpResponseMessage response = await client.PostAsync(url, postContent);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment