Files
SIG/Ashx/SIGFreightVerify.ashx
2024-06-30 23:19:12 -07:00

377 lines
14 KiB
Plaintext

<%@ WebHandler Language="C#" Class="SIGFreightVerify" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Extensiones;
using System.Collections.Specialized;
using System.IO;
using System.Net.Http;
using System.Text;
using FluentGenerator;
public class SIGFreightVerify : IHttpHandler, IRequiresSessionState
{
//121,183798
private Usuario ValidaUsuarioSistema(int CveEmpresa)
{
Usuario UsuarioActual = null;
string NombreCadena = ClsPaginas.get_GlobalNombreCadenaConexion(141);
ClsSisUsuarioAutenticacion ObjUsuarios = new ClsSisUsuarioAutenticacion(NombreCadena: NombreCadena);
UsuarioActual = ObjUsuarios.GetUsuarioDetalle(1727);
if (UsuarioActual !=null)
{
var Usuario = ObjUsuarios.DtResultados.Rows[0]["Usuario"].ToString();
var Contrasenia = ObjUsuarios.DtResultados.Rows[0]["Contraseña"].ToString();
UsuarioActual = ObjUsuarios.ValidaUsuario(Usuario, Contrasenia, CveEmpresa: CveEmpresa);
UsuarioActual.CveEmpresa = CveEmpresa;
UsuarioActual.CveCliente = 183798;
//CreaObjetoEmpresa(ref UsuarioActual);
CargaZonasHorarias(ref UsuarioActual);
}
ObjUsuarios.Dispose();
return UsuarioActual;
}
private void CreaObjetoEmpresa(ref Usuario UsuarioActual)
{
ClsSisEmpresas ObjEmpresa = new ClsSisEmpresas();
if (ObjEmpresa.GetEmpresas(UsuarioActual.CveEmpresa, "-1", "-1", "-1", "-1"))
{
if (ObjEmpresa.GetEmpresasFuncionalidades(UsuarioActual.CveEmpresa))
{
System.Data.DataTable dttmp = ObjEmpresa.DtResultados;
var EmpresasFuncionalidades = new HybridDictionary();
foreach (System.Data.DataRow Row in dttmp.Rows)
EmpresasFuncionalidades.Add(Convert.ToInt32(Row["CveFuncionalidad"]), Row["Valor"].ToString());
ObjEmpresa.Empresa.SetFuncionalidades(EmpresasFuncionalidades);
}
UsuarioActual.Empresa = ObjEmpresa.Empresa;
}
ObjEmpresa.Dispose();
}
private void CargaZonasHorarias(ref Usuario UsuarioActual)
{
ClsClientes ObjClientes = new ClsClientes();
try
{
if (ObjClientes.GetClientes(UsuarioActual.CveCliente, "-1", "-1", "-1", "-1", "-1", "-1", -1, -1, Estatus: 1))
{
if (ObjClientes.DtResultados.Rows.Count == 1)
UsuarioActual.UTCOffset = ObjClientes.DtResultados.Rows[0]["UTCOffset"].ToString().ToEntero();
}
}
catch (Exception ex)
{
ex.ToString().GuardaLog();
}
finally
{
ObjClientes.Dispose();
}
}
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
try
{
context.Response.ContentType = "text/plain";
IniciarTransmision(context);
}
catch (Exception ex)
{
ex.GuardaLog(ex.Message);
}
}
private void IniciarTransmision(HttpContext context)
{
var UsuarioActual = ValidaUsuarioSistema(121);
DataTable dtShipments = null;
var FVCARRIERID = "";
var SCAC = "";
var UsuarioFV = "";
var ContraseniaFV = "";
var ObjGPS = new ClsGPS();
try
{
if (ObjGPS.GetShipments(UsuarioActual.CveCliente, -1))
{
dtShipments = ObjGPS.DtResultados.FiltraParametros("TransmitirTexto = 'Si'");
}
if (ObjGPS.GetFVConfiguracion(UsuarioActual.CveCliente, -1))
{
if (ObjGPS.DtResultados.Rows.Count == 1)
{
var row = ObjGPS.DtResultados.Rows[0];
FVCARRIERID = row["fvCarrierId"].ToString().Trim();
SCAC = row["scac"].ToString().Trim();
UsuarioFV = row["Usuario"].ToString().Trim();
ContraseniaFV = row["Contrasenia"].ToString().Trim();
}
}
}
catch (Exception ex)
{
this.OnError("Ocurrió un error al obtener la configuración", ex);
}
finally
{
ObjGPS.Dispose();
var array = new JArray();
if (dtShipments != null)
{
foreach (DataRow Row in dtShipments.Rows)
{
var datos = GeneraRequestLO(UsuarioActual, Row["CveShipment"].ToString().ToEntero(), FVCARRIERID, SCAC);
if (datos != null)
{
var retorno = EnviarEventoAPI(UsuarioActual, Row["ShipmentID"].ToString(), Row["Customer"].ToString(), FVCARRIERID, UsuarioFV, ContraseniaFV, datos.ToString());
array.Add(retorno);
}
}
}
context.Response.Write(array);
}
}
protected JObject GeneraRequestLO(Usuario UsuarioActual, int CveShipment, string FVCARRIERID, string SCAC)
{
var route_id = "";
var trailer_number = "";
var trackingAssetId = "";
double lat = 0;
double lon = 0;
var ObjGPS = new ClsGPS();
if (ObjGPS.GetShipmentDetail(CveShipment))
{
if (ObjGPS.DtResultados.Rows.Count == 1)
{
var row = ObjGPS.DtResultados.Rows[0];
lat = row["Lat"].ToString().ToDouble();
lon = row["Lon"].ToString().ToDouble();
route_id = row["RouteID"].ToString();
trailer_number = row["TrailerID"].ToString();
trackingAssetId = row["AssetID"].ToString();
}
}
ObjGPS.Dispose();
var json = new JObject()
{
new JProperty("carrier", new JObject()
{
new JProperty("fvCarrierId", FVCARRIERID),
new JProperty("scac", SCAC)
}),
new JProperty("location",new JObject()
{
new JProperty("latitude", lat),
new JProperty("longitude", lon)
}),
new JProperty("telematics",new JObject()
{
new JProperty("provider", "Direct"),
new JProperty("trackingAssetId", trackingAssetId)
}),
new JProperty("eventDetail",new JObject()
{
new JProperty("event","LO"),
new JProperty("reason","NS"),
new JProperty("eventDate",string.Format("{0}{1}",UsuarioActual.FechaActualCliente.ToString("yyyy-MM-ddThh:mm:ss"),"-0500"))
}),
new JProperty("eventReferences",new JArray() {
new JObject()
{
new JProperty("qualifier", "route_id"),
new JProperty("description", ""),
new JProperty("value",route_id)
},
new JObject()
{
new JProperty("qualifier", "trailer_number"),
new JProperty("description", ""),
new JProperty("value",trailer_number)
}
})
};
return json;
}
private JObject EnviarEventoAPI(Usuario UsuarioActual, string ShipmentID, string Customer, string FVCARRIERID, string UsuarioFV, string ContraseniaFV, string Datos)
{
var retorno = "[]";
var token = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(string.Format("{0}:{1}", UsuarioFV, ContraseniaFV)));
string correlationId = GuidGenerator.GenerateTimeBasedGuid(UsuarioActual.FechaActualCliente).ToString();
HttpClient wc = new HttpClient();
try
{
var fvShipmentId = $"{FVCARRIERID}|{Customer}|{ShipmentID}";
var Url = new Uri("https://api.freightverify.com/ws/rest/v2/tl/shipment/event");
var content = new StringContent(Datos, Encoding.UTF8, "application/json");
wc.DefaultRequestHeaders.Add("Authorization", $"Basic {token}");
wc.DefaultRequestHeaders.Add("WSS-correlationId", correlationId);
wc.DefaultRequestHeaders.Add("X-WSS-fvShipmentId", fvShipmentId);
var response = wc.PostAsync(Url, content).Result;
retorno = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
wc.Dispose();
return JObject.Parse(retorno);
}
}
namespace FluentGenerator
{
public enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}
public static partial class GuidGenerator
{
// number of bytes in guid
public const int ByteArraySize = 16;
// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 0x80;
// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
// indexes within the uuid array for certain boundaries
private const byte TimestampByte = 0;
private const byte GuidClockSequenceByte = 8;
private const byte NodeByte = 10;
// offset to move from 1/1/0001, which is 0-time for .NET, to gregorian 0-time of 10/15/1582
private static readonly DateTimeOffset GregorianCalendarStart = new DateTimeOffset(1582, 10, 15, 0, 0, 0, TimeSpan.Zero);
// random clock sequence and node
public static byte[] DefaultClockSequence { get; set; }
public static byte[] DefaultNode { get; set; }
static GuidGenerator()
{
DefaultClockSequence = new byte[2];
DefaultNode = new byte[6];
var random = new Random();
random.NextBytes(DefaultClockSequence);
random.NextBytes(DefaultNode);
}
public static GuidVersion GetVersion(this Guid guid)
{
byte[] bytes = guid.ToByteArray();
return (GuidVersion)((bytes[VersionByte] & 0xFF) >> VersionByteShift);
}
public static DateTimeOffset GetDateTimeOffset(Guid guid)
{
byte[] bytes = guid.ToByteArray();
// reverse the version
bytes[VersionByte] &= (byte)VersionByteMask;
bytes[VersionByte] |= (byte)((byte)GuidVersion.TimeBased >> VersionByteShift);
byte[] timestampBytes = new byte[8];
Array.Copy(bytes, TimestampByte, timestampBytes, 0, 8);
long timestamp = BitConverter.ToInt64(timestampBytes, 0);
long ticks = timestamp + GregorianCalendarStart.Ticks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
public static DateTime GetDateTime(Guid guid)
{
return GetDateTimeOffset(guid).DateTime;
}
public static DateTime GetLocalDateTime(Guid guid)
{
return GetDateTimeOffset(guid).LocalDateTime;
}
public static DateTime GetUtcDateTime(Guid guid)
{
return GetDateTimeOffset(guid).UtcDateTime;
}
public static Guid GenerateTimeBasedGuid()
{
return GenerateTimeBasedGuid(DateTimeOffset.UtcNow, DefaultClockSequence, DefaultNode);
}
public static Guid GenerateTimeBasedGuid(DateTime dateTime)
{
return GenerateTimeBasedGuid(dateTime, DefaultClockSequence, DefaultNode);
}
public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime)
{
return GenerateTimeBasedGuid(dateTime, DefaultClockSequence, DefaultNode);
}
public static Guid GenerateTimeBasedGuid(DateTime dateTime, byte[] clockSequence, byte[] node)
{
return GenerateTimeBasedGuid(new DateTimeOffset(dateTime), clockSequence, node);
}
public static Guid GenerateTimeBasedGuid(DateTimeOffset dateTime, byte[] clockSequence, byte[] node)
{
if (clockSequence == null)
throw new ArgumentNullException("clockSequence");
if (node == null)
throw new ArgumentNullException("node");
if (clockSequence.Length != 2)
throw new ArgumentOutOfRangeException("clockSequence", "The clockSequence must be 2 bytes.");
if (node.Length != 6)
throw new ArgumentOutOfRangeException("node", "The node must be 6 bytes.");
long ticks = (dateTime - GregorianCalendarStart).Ticks;
byte[] guid = new byte[ByteArraySize];
byte[] timestamp = BitConverter.GetBytes(ticks);
// copy node
Array.Copy(node, 0, guid, NodeByte, Math.Min(6, node.Length));
// copy clock sequence
Array.Copy(clockSequence, 0, guid, GuidClockSequenceByte, Math.Min(2, clockSequence.Length));
// copy timestamp
Array.Copy(timestamp, 0, guid, TimestampByte, Math.Min(8, timestamp.Length));
// set the variant
guid[VariantByte] &= (byte)VariantByteMask;
guid[VariantByte] |= (byte)VariantByteShift;
// set the version
guid[VersionByte] &= (byte)VersionByteMask;
guid[VersionByte] |= (byte)((byte)GuidVersion.TimeBased << VersionByteShift);
return new Guid(guid);
}
}
}