Skip to content

Instantly share code, notes, and snippets.

@DorukUlucay
Last active June 4, 2021 15:27
Show Gist options
  • Save DorukUlucay/5e2358883fc8e3d100c4338bd27ef756 to your computer and use it in GitHub Desktop.
Save DorukUlucay/5e2358883fc8e3d100c4338bd27ef756 to your computer and use it in GitHub Desktop.
snipps
void Logit(int step, object ob, string location)
{
if (string.IsNullOrWhiteSpace(location))
location = $"Debug Session {DateTime.Now.Date.ToString("yyyyMMdd")}";
Log.Fatal($"{location}: {step}, {Newtonsoft.Json.JsonConvert.SerializeObject(ob)}");
}
using Newtonsoft.Json;
using NLog;
using RestSharp;
using RestSharp.Authenticators;
public T Execute<T>(string resource, Method method, object body, IAuthenticator authenticator)
=> JsonConvert.DeserializeObject<T>(Execute(resource, method, body, authenticator).Content);
public IRestResponse Execute(string resource, Method method, object body, IAuthenticator authenticator)
{
RestClient restClient = new RestClient();
RestRequest restRequest = new RestRequest(resource, method);
restClient.Authenticator = authenticator;
if (method != Method.GET)
{
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddParameter("application/json", JsonConvert.SerializeObject(body), ParameterType.RequestBody);
}
Logger.Debug(restRequest.ToLogString());
var response = restClient.Execute(restRequest);
Logger.Debug(response.ToLogString());
return response;
}
public static class RestSharpLogExtensions
{
public static string ToLogString(this RestRequest restRequest)
{
var requestlog = new
{
Resource = restRequest.Resource,
Method = restRequest.Method.ToString(),
Body = restRequest.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody)?.Value,
Parameters = restRequest.Parameters.Select(parameter => new
{
name = parameter.Name,
value = parameter.Value,
type = parameter.Type.ToString()
}),
};
return $"Request: {JsonConvert.SerializeObject(requestlog)}";
}
public static string ToLogString(this IRestResponse restResponse)
{
var requestlog = new
{
StatusCode = restResponse.StatusCode,
Content = restResponse.Content,
Headers = restResponse.Headers,
ResponseUri = restResponse.ResponseUri,
ErrorMessage = restResponse.ErrorMessage
};
return $"Response: {JsonConvert.SerializeObject(requestlog)}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment