using ADSUtileriasService.Helpers;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ADSUtileriasService.Conexion.SIG
{
public class BaseSIG
{
public string domainApi;
string authorization
{
get
{
return ADSUtileriasService.Helpers.GlobalVars._authorization;
}
}
public DateTime GetTokenExpirationValue
{
get
{
if (authorization == "")
{
return DateTime.MinValue;
}
else
{
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(authorization);
var tokenS = handler.ReadToken(authorization) as JwtSecurityToken;
return tokenS.ValidTo;
}
}
}
protected string RouteController = "";
public BaseSIG(string domainApi)
{
if (string.IsNullOrEmpty(domainApi))
{
domainApi = Helpers.GlobalVars.UrlApi;
}
this.domainApi = domainApi;
}
protected string GetRoutbyclass { get { string classname = this.GetType().Name; return classname.Substring(0, classname.Length - 3); } }
private string GetRoute(string path) { return string.Format("api/{0}/{1}", (string.IsNullOrEmpty(RouteController) ? GetRoutbyclass : RouteController), path); }
///
/// Obtiene datos from SIg.
///
/// Clase genérica en donde se obtiene la información del SqlDataReader.
/// ruta sin domino ejemplo "/api/usuarios/login".
/// request object.
/// Lista de objetos.
public async Task getDataAsync(string path, object requestobject, Helpers.requestMethod reqmet = Helpers.requestMethod.POST, bool needauthorization = true) where T : class, new()
{
T objreturn = null;
using (HttpClient client = new HttpClient())
{
// Setting Base address.
client.BaseAddress = new Uri(domainApi);
// Setting content type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
/* Vaalido autorizacion */
if (needauthorization)
{
if (GetTokenExpirationValue < DateTime.UtcNow.AddMinutes(-3))
{
try
{
HttpResponseMessage authresponse = new HttpResponseMessage();
//var objauth = new ADSNetLibrary. SIGAPI.Models.Sistema.RequestLogin() { UserName = "jcaudillo", Password = "45makako45", CveEmpresa = 119 };
var objauth = new ADSNetLibrary.SIGAPI.Models.Sistema.RequestLogin() { UserName = GlobalVars.UserName, Password = GlobalVars.Password, CveEmpresa = GlobalVars.CveEmpresa.ToEntero() };
authresponse = await client.PostAsync("api/Usuario/Login", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(objauth), Encoding.UTF8, "application/json"));
if (authresponse.IsSuccessStatusCode)
{
string jsondata = await authresponse.Content.ReadAsStringAsync();
Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore };
var retorno = Newtonsoft.Json.JsonConvert.DeserializeObject>(jsondata, settings);
if (retorno.IsSuccess)
{
ADSUtileriasService.Helpers.GlobalVars._authorization = retorno.Result.AccessToken;
}
}
}
catch (Exception e)
{
string strerror = string.Format("{0}autologin{0}Excepción :{1}{0}", "\r\n", e);
Mod.GuardaLog(strerror, LogsNames.SigLog);
}
}
}
}
using (HttpClient client = new HttpClient())
{
// Setting Base address.
client.BaseAddress = new Uri(domainApi);
// Setting content type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Setting Authorization.
if (needauthorization) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorization); }
HttpResponseMessage response = new HttpResponseMessage();
var strjsonreq = Newtonsoft.Json.JsonConvert.SerializeObject(requestobject);
StringContent content = new StringContent(strjsonreq, Encoding.UTF8, "application/json");
string route = GetRoute(path);
try
{
switch (reqmet)
{
case Helpers.requestMethod.POST:
response = await client.PostAsync(route, content);
break;
case Helpers.requestMethod.GET:
response = await client.GetAsync(route);
break;
}
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore
};
objreturn = Newtonsoft.Json.JsonConvert.DeserializeObject(jsondata, settings);
}
else
{
string strerror = string.Format("{0}{1}{0}StatusCode:{2}{0}{3}{0}{4}", "\r\n", route, response.StatusCode, response.RequestMessage, strjsonreq);
}
}
catch (Exception e)
{
string strerror = string.Format("{0}{1}{0}Excepción :{2}{0}{3}", "\r\n", route, e, strjsonreq);
Mod.GuardaLog(strerror, LogsNames.SigLog);
}
}
return objreturn;
}
///
/// Obtiene datos from SIg.
///
/// Clase genérica en donde se obtiene la información del SqlDataReader.
/// ruta sin domino ejemplo "/api/usuarios/login".
/// request object.
/// Lista de objetos.
public T getData(string path, object requestobject, Helpers.requestMethod reqmet = Helpers.requestMethod.POST) where T : class, new()
{
return AsyncHelper.RunSync(() => getDataAsync(path, requestobject, reqmet));
}
}
internal static class AsyncHelper
{
private static readonly TaskFactory _myTaskFactory = new
TaskFactory(CancellationToken.None,
TaskCreationOptions.None,
TaskContinuationOptions.None,
TaskScheduler.Default);
public static TResult RunSync(Func> func)
{
return AsyncHelper._myTaskFactory
.StartNew>(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
public static void RunSync(Func func)
{
AsyncHelper._myTaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
}
}
}