Commit inicial Ventas Productivo

This commit is contained in:
JORGE LUIS CAUDILLO ESPARZA
2019-08-14 16:40:54 -07:00
commit c35cf91883
13328 changed files with 3711549 additions and 0 deletions

247
Ashx/CargaEventos.ashx Normal file
View File

@@ -0,0 +1,247 @@
<%@ WebHandler Language="VB" Class="CargaEventos" %>
Option Explicit On
Option Strict On
Imports System
Imports System.Web
Imports System.Collections
Imports System.Collections.Generic
Imports System.Web.SessionState
Imports System.Data
Imports Extensiones
Public Class CargaEventos : Implements IHttpHandler, IRequiresSessionState
Public Property events As List(Of CalendarEvent)
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Dim CveUsuario = -1
Dim CveEmpresa = -1
Dim FI As Date
Dim FF As Date
If context.Request("U").ToEntero > 0 Then
CveUsuario = context.Request("U").ToEntero
CveEmpresa = context.Request("E").ToEntero
FI = context.Request("start").ToDate
FF = context.Request("end").ToDate
End If
If Not GetEventos(CveUsuario, CveEmpresa, FI, FF) Then
'Convierte el objeto de Eventos en JSON
Dim oSerializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer
Dim sJSON As String = oSerializer.Serialize(events)
context.Response.Write(sJSON)
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Private Function GetEventos(CveUsuario As Integer, CveEmpresa As Integer, pFI As Date, pFF As Date) As Boolean
Dim ObjEventos As New ClsOIEventos
Dim ErrorEventos = False
If ObjEventos.GetEventos(-1, -1, -1, "-1", "-1", -1, CveUsuario, CveUsuario, -1, -1, -1, "-1", -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, CveUsuario, CveUsuario, CveUsuario, CveEmpresa, pFI, pFF) Then
If ObjEventos.DtResultados.Rows.Count > 0 Then
events = New List(Of CalendarEvent)
Try
For Each dr As DataRow In ObjEventos.DtResultados.Rows
Dim cevent As CalendarEvent = New CalendarEvent()
cevent.id = dr("CveEvento").ToString.ToEntero
cevent.title = dr("Asunto").ToString
cevent.description = dr("Descripcion").ToString
cevent.start = String.Format("{0:s}", dr("FechaInicio").ToString.ToDateTime)
cevent.end = String.Format("{0:s}", dr("FechaFin").ToString.ToDateTime)
cevent.allDay = False
cevent.CveEventoEstatus = dr("CveEventoEstatus").ToString.ToEntero
cevent.cveagendatipo = dr("CveAgendaTipo").ToString
cevent.prioridad = dr("CvePrioridad").ToString.ToEntero
cevent.backgroundColor = dr("BackGroundColor").ToString
cevent.recurrenciatipo = dr("RecurrenciaTipo").ToString.ToEntero
cevent.frecuencia = dr("Frecuencia").ToString.ToEntero
cevent.diassemana = dr("DiasSemana").ToString
cevent.dia = dr("Dia").ToString.ToEntero
cevent.mes = dr("Mes").ToString.ToEntero
cevent.recurrenciafin = dr("RecurrenciaFin").ToString
cevent.CveProspecto = dr("CveProspecto").ToString.ToEntero
cevent.Prospecto = dr("Prospecto").ToString
cevent.CveTipoEvento = dr("Prospecto").ToString.ToEntero
'11/05/2018 - Evento Gasto Recurrente
cevent.CveTipoEvento = dr("CveTipoEvento").ToString.ToEntero
If cevent.CveTipoEvento = 10 Then
cevent.Importe = dr("Importe").ToString.ToDouble
End If
If cevent.CveEventoEstatus.ToString.ToEntero = 3 Then
cevent.backgroundColor = "#1BBC9B"
End If
'VERIFICAMOS SI TIENE O NO RECURRENCIA
If Not cevent.recurrenciatipo > 0 Then
'AGREGAMOS CUANDO NO ES RECURRENTE
Dim tFecha As DateTime = DateAdd(DateInterval.Month, -6, Date.Now)
'SI LA FECHA DEL EVENTO ES MENOR DE 6 MESES DE LA FECHA ACTUAL NO LO AGREGA
If dr("FechaFin").ToString.ToDateTime > tFecha Or dr("FechaInicio").ToString.ToDateTime > tFecha Then
events.Add(cevent)
End If
Else
'EMPIEZA METODO PARA AGREGAR CUANDO SI ES RECURRENTE
Dim FinRecurrencia = cevent.recurrenciafin.ToEntero
Dim FI As DateTime, FF As DateTime, FT As DateTime
Dim DiasSemana = cevent.diassemana.Split(","c)
FI = cevent.start.ToDateTime
FF = cevent.end.ToDateTime
'OBTENEMOS LA FECHA TERMINO (FT) DE LA RECURRENCIA
Select Case FinRecurrencia
Case -1
FT = DateAdd(DateInterval.Year, 2, dr("FechaInicio").ToString.ToDateTime)
Case 0
FT = dr("RecurrenciaFin").ToString.ToDate
Case Is > 0
FinRecurrencia -= 1
Select Case cevent.recurrenciatipo
Case 1
FT = DateAdd(DateInterval.Hour, FinRecurrencia * cevent.frecuencia, dr("FechaInicio").ToString.ToDateTime)
Case 2
FT = DateAdd(DateInterval.Day, FinRecurrencia * cevent.frecuencia, dr("FechaInicio").ToString.ToDateTime)
Case 3
FT = DateAdd(DateInterval.WeekOfYear, FinRecurrencia * cevent.frecuencia, dr("FechaInicio").ToString.ToDateTime)
FT = DateAdd(DateInterval.Day, (7 - Weekday(FT)).ToString.ToDouble, FT)
Case 4
FT = DateAdd(DateInterval.Month, FinRecurrencia * cevent.frecuencia, dr("FechaInicio").ToString.ToDateTime)
Case 5
FT = DateAdd(DateInterval.Year, FinRecurrencia * cevent.frecuencia, dr("FechaInicio").ToString.ToDateTime)
End Select
End Select
'SI ES TIPO SEMANAL Y DIASSEMANA TIENE VALORES CHECKEA ESTOS VALORES
Do
If DiasSemana.Length > 0 AndAlso DiasSemana(0) <> "" Then
For Each drDias As String In DiasSemana
Dim FIT = FI, FFT = FF
FIT = DateAdd(DateInterval.Day, (drDias.ToEntero - Weekday(FI)).ToString.ToDouble, FI)
FFT = DateAdd(DateInterval.Day, (drDias.ToEntero - Weekday(FF)).ToString.ToDouble, FF)
cevent = New CalendarEvent()
cevent.id = dr("CveEvento").ToString.ToEntero
cevent.title = dr("Asunto").ToString
cevent.description = dr("Descripcion").ToString
cevent.start = String.Format("{0:s}", FIT)
cevent.end = String.Format("{0:s}", FFT)
cevent.allDay = False
cevent.CveEventoEstatus = dr("CveEventoEstatus").ToString.ToEntero
cevent.cveagendatipo = dr("CveAgendaTipo").ToString
cevent.prioridad = dr("CvePrioridad").ToString.ToEntero
cevent.backgroundColor = dr("BackGroundColor").ToString
cevent.recurrenciatipo = dr("RecurrenciaTipo").ToString.ToEntero
cevent.frecuencia = dr("Frecuencia").ToString.ToEntero
cevent.diassemana = dr("DiasSemana").ToString
cevent.dia = dr("Dia").ToString.ToEntero
cevent.mes = dr("Mes").ToString.ToEntero
cevent.recurrenciafin = dr("RecurrenciaFin").ToString
cevent.CveProspecto = dr("CveProspecto").ToString.ToEntero
cevent.Prospecto = dr("Prospecto").ToString
'11/05/2018 - Evento Gasto Recurrente
cevent.CveTipoEvento = dr("CveTipoEvento").ToString.ToEntero
If cevent.CveTipoEvento = 10 Then
cevent.Importe = dr("Importe").ToString.ToDouble
End If
If cevent.CveEventoEstatus.ToString.ToEntero = 3 Then
cevent.backgroundColor = "#1BBC9B"
End If
'SI LA FECHA DEL EVENTO ES MENOR DE 6 MESES DE LA FECHA ACTUAL Y/0 SI LA FECHA INICIAL DE LA RECURRENCIA ES MENOR A LA FECHA QUE SE CREO EL EVENTO NO LO AGREGA
If FIT > DateAdd(DateInterval.Month, -6, Date.Now) And FIT >= dr("FechaInicio").ToString.ToDateTime Then
events.Add(cevent)
End If
Next
Else
cevent = New CalendarEvent()
cevent.id = dr("CveEvento").ToString.ToEntero
cevent.title = dr("Asunto").ToString
cevent.description = dr("Descripcion").ToString
cevent.start = String.Format("{0:s}", FI)
cevent.end = String.Format("{0:s}", FF)
cevent.allDay = False
cevent.CveEventoEstatus = dr("CveEventoEstatus").ToString.ToEntero
cevent.cveagendatipo = dr("CveAgendaTipo").ToString
cevent.prioridad = dr("CvePrioridad").ToString.ToEntero
cevent.backgroundColor = dr("BackGroundColor").ToString
cevent.recurrenciatipo = dr("RecurrenciaTipo").ToString.ToEntero
cevent.frecuencia = dr("Frecuencia").ToString.ToEntero
cevent.diassemana = dr("DiasSemana").ToString
cevent.dia = dr("Dia").ToString.ToEntero
cevent.mes = dr("Mes").ToString.ToEntero
cevent.recurrenciafin = dr("RecurrenciaFin").ToString
cevent.CveProspecto = dr("CveProspecto").ToString.ToEntero
cevent.Prospecto = dr("Prospecto").ToString
'11/05/2018 - Evento Gasto Recurrente
cevent.CveTipoEvento = dr("CveTipoEvento").ToString.ToEntero
If cevent.CveTipoEvento = 10 Then
cevent.Importe = dr("Importe").ToString.ToDouble
End If
If cevent.CveEventoEstatus.ToString.ToEntero = 3 Then
cevent.backgroundColor = "#1BBC9B"
End If
'SI LA FECHA DEL EVENTO ES MENOR DE 6 MESES DE LA FECHA ACTUAL NO LO AGREGA
If FI > DateAdd(DateInterval.Month, -6, Date.Now) Then
events.Add(cevent)
End If
End If
Select Case cevent.recurrenciatipo
Case 1
FI = DateAdd(DateInterval.Hour, cevent.frecuencia, FI)
FF = DateAdd(DateInterval.Hour, cevent.frecuencia, FF)
Case 2
FI = DateAdd(DateInterval.Day, cevent.frecuencia, FI)
FF = DateAdd(DateInterval.Day, cevent.frecuencia, FF)
Case 3
FI = DateAdd(DateInterval.WeekOfYear, cevent.frecuencia, FI)
FF = DateAdd(DateInterval.WeekOfYear, cevent.frecuencia, FF)
Case 4
FI = DateAdd(DateInterval.Month, cevent.frecuencia, FI)
FF = DateAdd(DateInterval.Month, cevent.frecuencia, FF)
Case 5
FI = DateAdd(DateInterval.Year, cevent.frecuencia, FI)
FF = DateAdd(DateInterval.Year, cevent.frecuencia, FF)
End Select
Loop Until FI > FT
End If
Next
Catch ex As Exception
GuardaLog(ex.ToString())
End Try
End If
End If
ObjEventos.Dispose()
Return ErrorEventos
End Function
End Class

141
Ashx/MHRedes.ashx Normal file
View File

@@ -0,0 +1,141 @@
<%@ WebHandler Language="VB" Class="MobileHandler" %>
Imports System.Web
Imports System.Data
Imports Extensiones
Imports System.Text
Public Class MobileHandler : Implements IHttpHandler
Private Property Contexto As HttpContext
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Contexto = context
If context.Request("Opcion") IsNot Nothing Then
Dim Opcion As String = context.Request("Opcion")
Select Case Opcion
Case "ValidaUsuario"
ValidaUsuario()
Case "Simpatizantes"
If IfNull(Contexto.Request("Agrupador"), "0") <> "0" Then
RepSimpatizantes(IfNull(Contexto.Request("Agrupador"), "0").ToString.ToEntero, 41)
End If
Case "Metas"
If IfNull(Contexto.Request("Agrupador"), "0") <> "0" Then
RepMetas(IfNull(Contexto.Request("Agrupador"), "0").ToString.ToEntero, 41)
End If
Case "Actividades"
If IfNull(Contexto.Request("Agrupador"), "0") <> "0" Then
RepActividadesRecientes(41)
End If
End Select
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Private Sub ValidaUsuario()
Dim ObjUsuario As New ClsSisUsuarios
Dim User As Usuario
Dim IP As String
IP = clsUtilerias.GetIP4Address 'Request.ServerVariables("REMOTE_ADDR").ToString()
If IP = "::1" Then
IP = "127.0.0.1"
End If
Dim Json As New StringBuilder
User = ObjUsuario.ValidaUsuario(Contexto.Request("Usuario"), Contexto.Request("Password"), IMEI)
If User IsNot Nothing Then
Dim Token As String = String.Format("{0}*{1}*{2}", Now.ToString, IP, User.CveUsuario)
Token = Encripta(Token)
json.AppendFormat("{{ ""CveUsuario"" : ""{0}"", ""Nombre"" : ""{1}"", ""Token"" : ""{2}"" }} ", User.CveUsuario, User.Nombre, Token)
Else
json.Append("{ ""CveUsuario"" : ""-1"", ""Nombre"" : ""No valido"" } ")
End If
Contexto.Response.Write(json.ToString)
End Sub
Private Sub RepActividadesRecientes(CveEmpresa As Integer)
Dim Json As String = ""
Dim Ind As New ClsProspectos
If Ind.GetProspectosSupervisor(CveEmpresa) Then
Json = DataTableToJSON(Ind.DtResultados)
End If
Ind.Dispose()
Contexto.Response.Write(Json)
End Sub
Private Sub RepSimpatizantes(Agrupador As Integer, CveEmpresa As Integer)
Dim Json As String = ""
Dim Ind As New ClsProspectos
If Ind.GetProspectosAgrupados2(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, Agrupador, CveEmpresa) Then
Dim yValues As New ArrayList
Dim xValues As New ArrayList
'cuando es por edades, ordena por la claverango
Dim dt As DataTable = Ind.DtResultados.FiltraParametros("CveAgrupador > 0", If(Agrupador = 9, "CveRangoEdad", "Total Desc"))
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
Json = DataTableToJSON(Ind.DtResultados)
End If
End If
Ind.Dispose()
Contexto.Response.Write(Json)
End Sub
Private Sub RepMetas(Opcion As Integer, CveEmpresa As Integer)
Dim ObjProspectos As New ClsProspectos
Dim dt As DataTable
Dim Json As String = ""
If ObjProspectos.GetProspectosAgrupadosMetas(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, CveEmpresa) Then
dt = ObjProspectos.DtResultados
If Opcion = 1 Then
dt = dt.FiltraParametros("CveCoordinador > 0 AND CveAgrupador IS NULL")
Else
dt = dt.FiltraParametros("CveSupervisor > 0 AND CveCoordinador IS NULL")
End If
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
Json = DataTableToJSON(dt)
End If
End If
ObjProspectos.Dispose()
Contexto.Response.Write(Json)
End Sub
End Class

72
Ashx/SIGCRM.ashx Normal file
View File

@@ -0,0 +1,72 @@
<%@ WebHandler Language="VB" Class="SIGCRM" %>
Imports System
Imports System.Web
Imports System.Data
Imports Newtonsoft.Json
Imports Extensiones
Imports System.IO
Public Class SIGCRM : Implements IHttpHandler, IRequiresSessionState
#Region "P R O P I E D A D E S"
ReadOnly Property UsuarioActual(ByVal context As HttpContext) As Usuario
Get
UsuarioActual = DirectCast(context.Session("UsuarioSIG"), Usuario)
End Get
End Property
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Private Function Parametros(Cadena As String) As Hashtable
Dim P1() As String = Cadena.Split("&"c)
Dim Tmp As String
Dim P2() As String
Dim URLParametros As New Hashtable
For Each Tmp In P1
P2 = Tmp.Replace("%26%", "&").Split("="c)
URLParametros.Add(P2(0).ToString.ToUpper, P2(1))
Next
Return URLParametros
End Function
#End Region
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Try
Select Case context.Request("metodo")
Case "getimgacercamiento"
GetImgAcercamiento(context)
End Select
Catch ex As Exception
ex.GuardaLog(ex.Message)
End Try
End Sub
Private Sub GetImgAcercamiento(ByVal context As HttpContext)
Dim params As String = Decripta(context.Request("r").ToString)
Dim Parametros = Me.Parametros(params)
Dim Archivo As String = Parametros("ARCHIVO").ToString()
Dim CveAcercamiento As Integer = Parametros("CVEACERCAMIENTO").ToString().ToEntero()
Dim Extension As String = Path.GetExtension(Archivo).Replace(".", "")
Dim Usuario As Usuario = UsuarioActual(context)
If Not IsNothing(Usuario) Then
Dim Url = String.Format("{0}\Empresas\{1}\Acercamientos\{2}\Imagenes\{3}", AppDomain.CurrentDomain.BaseDirectory, Usuario.CveEmpresa, CveAcercamiento, Archivo)
If File.Exists(Url) Then
context.Response.ContentType = String.Format("image/{0}", Extension)
context.Response.Flush()
context.Response.WriteFile(Url)
context.Response.End()
End If
End If
End Sub
End Class

3756
Ashx/SIGFacturacion.ashx Normal file

File diff suppressed because it is too large Load Diff

378
Ashx/SIGFreightVerify.ashx Normal file
View File

@@ -0,0 +1,378 @@
<%@ 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;
ClsSisUsuarios ObjUsuarios = new ClsSisUsuarios();
if (ObjUsuarios.GetUsuarios(1727))
{
if (ObjUsuarios.DtResultados.Rows.Count > 0)
{
var Usuario = ObjUsuarios.DtResultados.Rows[0]["Usuario"].ToString();
var Contrasenia = ObjUsuarios.DtResultados.Rows[0]["Contraseña"].ToString();
UsuarioActual = ObjUsuarios.ValidaUsuario(Usuario, Contrasenia, ModExtensiones.IMEI, 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);
}
}
}

218
Ashx/SIGGPS.ashx Normal file
View File

@@ -0,0 +1,218 @@
<%@ WebHandler Language="VB" Class="SIGGPS" %>
Option Explicit On
Option Strict On
Imports System
Imports System.Web
Imports System.Data
Imports Newtonsoft.Json.Linq
Imports Extensiones
Imports System.IO
Public Class SIGGPS : Implements IHttpHandler, IRequiresSessionState
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Try
If context.Request("metodo") IsNot Nothing Then
Select Case context.Request("metodo")
Case "getimginstalacion"
GetImgInstalacion(context)
End Select
ElseIf context.Request.InputStream IsNot Nothing Then
Using reader As New StreamReader(context.Request.InputStream)
Dim json = reader.ReadToEnd
Dim JsonRequest As JObject = JObject.Parse(json)
If JsonRequest IsNot Nothing Then
Select Case JsonRequest("Metodo").ToString
Case "UpdateNotificacion"
UpdateNotificacion(context, JsonRequest)
Case "RastreoContinuoAF"
RastreoContinuoAF(context, JsonRequest)
End Select
End If
End Using
End If
Catch ex As Exception
ex.GuardaLog(ex.Message)
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
ReadOnly Property UsuarioActual(ByVal context As HttpContext) As Usuario
Get
UsuarioActual = DirectCast(context.Session("UsuarioSIG"), Usuario)
End Get
End Property
Private Function Parametros(Cadena As String) As Hashtable
Dim P1() As String = Cadena.Split("&"c)
Dim Tmp As String
Dim P2() As String
Dim URLParametros As New Hashtable
For Each Tmp In P1
P2 = Tmp.Replace("%26%", "&").Split("="c)
URLParametros.Add(P2(0).ToString.ToUpper, P2(1))
Next
Return URLParametros
End Function
Private Sub GetImgInstalacion(ByVal context As HttpContext)
Dim params As String = Decripta(context.Request("r").ToString)
Dim Parametros = Me.Parametros(params)
Dim Archivo As String = Parametros("ARCHIVO").ToString()
Dim CveDispositivo As Integer = Parametros("CVEDISPOSITIVO").ToString().ToEntero()
Dim Extension As String = Path.GetExtension(Archivo).Replace(".", "")
Dim Usuario As Usuario = UsuarioActual(context)
If Not IsNothing(Usuario) Then
Dim Url = String.Format("{0}\Empresas\{1}\Dispositivos\{2}\Imagenes\{3}", AppDomain.CurrentDomain.BaseDirectory, Usuario.CveEmpresa, CveDispositivo, Archivo)
If File.Exists(Url) Then
context.Response.ContentType = String.Format("image/{0}", Extension)
context.Response.Flush()
context.Response.WriteFile(Url)
context.Response.End()
End If
End If
End Sub
Private Sub UpdateNotificacion(ByVal context As HttpContext, ByVal Json As JObject)
Dim CveBitacora As Integer = Json("Params")("CveBitacora").ToEntero
Dim CveUsuario As Integer = Json("Params")("Cve").ToEntero
Dim Notificaciones As New StringBuilder
Dim countNotificaciones = 0
If CveUsuario > 0 Then
Using ObjNoti As New ClsSisNotificaciones
If CveBitacora > 0 Then
ObjNoti.UpdateNotificacionesCampanaNotifico(CveBitacora, 1)
End If
ObjNoti.GetNotificacionesCampanaPendientes(CveUsuario)
For Each row As DataRow In ObjNoti.DtResultados.Rows
countNotificaciones += row("NumNotificaciones").ToString.ToEntero
Dim TipoMensaje = If(row("TipoMensaje").ToString = "EMG", $"Hay {row("NumNotificaciones")} notificaciones de Emergencia", $"Hay {row("NumNotificaciones")} notificaciones de Alerta")
Dim Icono = If(row("TipoMensaje").ToString = "EMG", "fa fa-exclamation-triangle", "fa fa-bullhorn")
Dim Tipo = If(row("TipoMensaje").ToString = "EMG", "danger", "warning")
Notificaciones.Append(ItemNotificaciones(TipoMensaje, "Hoy", Icono, Tipo, $"/GPS/Notificaciones.aspx?Tipo={row("TipoMensaje")}"))
Next
End Using
End If
Dim Retorno As New JObject(
New JProperty("Titulo", $"({countNotificaciones}) SIG GPS"),
New JProperty("NumNotificaciones", countNotificaciones),
New JProperty("CssClass", If(countNotificaciones > 0, "badge-danger", "badge-default")),
New JProperty("Html", Notificaciones.ToString())
)
context.Response.Write(Retorno.ToString())
End Sub
Private Sub RastreoContinuoAF(ByVal context As HttpContext, ByVal Json As JObject)
Dim CveDispositivo As Integer = Json("Params")("CveDispositivo").ToEntero
Dim CveCliente As Integer = Json("Params")("CveCliente").ToEntero
Dim FechaCliente As DateTime = Json("Params")("FechaCliente").ToDateTime
Dim PoscionesAnteriores As JArray = JArray.Parse(Json("Params")("Posiciones").ToString())
Dim CoordActual As JObject = Nothing
Dim SBJS As New StringBuilder
Dim ObjGPS As New ClsGPS
Try
Dim Fecha = "", Vehiculo = "", Icono = "", Info As String = ""
If ObjGPS.UltimaPosicionEquipoGet(String.Format("{0};", CveDispositivo), CveCliente) Then
If ObjGPS.DtResultados.Rows.Count > 0 Then
For Each Row As DataRow In ObjGPS.DtResultados.Rows
CoordActual = JObject.Parse(SQLToGmapsJArray(Row("Posicion").ToString, "POINT")(0).ToString())
Fecha = Row("FechaTrama").ToString
Vehiculo = Row("Vehiculo").ToString
Info = InfoWindowCombustible(String.Format(" Vehículo: {0}", Vehiculo), "", CveDispositivo, Row, False)
Dim Diferencia As Long = DateDiff(DateInterval.Minute, Fecha.ToDateTime(), FechaCliente)
If Diferencia >= 30 AndAlso Diferencia < 120 Then
Icono = "/Imagenes/rsz_11rsz_car_disconnected.png"
ElseIf Diferencia >= 120 Then
Icono = "/Imagenes/rsz_11rsz_car_disable.png"
Else
If Row("SPD").ToString.ToDouble > 1 Then
Icono = String.Format("/Imagenes/{0}green.png", Row("Icono").ToString)
Else
Icono = String.Format("/Imagenes/{0}.png", Row("Icono").ToString)
End If
End If
PoscionesAnteriores.Add(CoordActual)
SBJS.AppendFormat("creaPolylineRastreo({0},'#4B77BE','{1}',{2},'{3}','{4}',{5}, 1); DeleteMarkersRastreo();", PoscionesAnteriores.ToString(), Info, CoordActual.ToString(), Vehiculo, Icono, CveDispositivo)
Next
End If
End If
Catch ex As Exception
GuardaLog(ex.ToString())
Finally
ObjGPS.Dispose()
End Try
Dim Retorno As New JObject(
New JProperty("CoordActual", CoordActual),
New JProperty("JS", SBJS.ToString())
)
context.Response.Write(Retorno.ToString())
End Sub
Public Function InfoWindowCombustible(Header As String, ExtraBody As String, CveDispositivo As Integer, row As DataRow, Optional PermisoComandos As Boolean = True) As String
Dim SBuilder As New StringBuilder
SBuilder.Clear()
SBuilder.Append($"<div>")
SBuilder.Append($"<div><h5><b>{Header}</b></h5></div>")
SBuilder.Append($"<div><table>")
Try
SBuilder.Append($"<tr><td>Fecha : {row("FechaTrama")} </td></tr>")
SBuilder.Append($"<tr><td>Conductor : {row("Conductor").ToString}</td></tr>")
If row.Table.Columns.Contains("Combustible") Then
SBuilder.Append($"<tr><td>Combustible : {IfNull(row("Combustible"), "NO DISPONIBLE", $"{row("Combustible").ToString.FormatoNumero} lts").ToString}</td></tr>")
End If
If row("SPD").ToString <> "-1" Then
SBuilder.Append($"<tr><td>Velocidad : {row("SPD").ToString} KM/H </td></tr>")
End If
If ExtraBody <> "" AndAlso ExtraBody <> "-1" Then
SBuilder.Append(ExtraBody)
End If
'If PermisoComandos Then
'SBuilder.Append($"<tr><td><a href=""javascript:;"" onclick=""CargaComandos(\'{row("Vehiculo").ToString}\',{CveDispositivo});"">Comandos</a></td></tr>")
SBuilder.AppendFormat("<tr><td><a target=\'_blank\' href=\'https://www.google.com/maps/search/{0},{1}/\'>Ver en google maps</a></td></tr>", row("Lat").ToString, row("Lng").ToString)
'End If
Catch ex As Exception
End Try
SBuilder.Append($"</table></div><div></div></div>")
Return SBuilder.ToString
End Function
Private Function SQLToGmapsJArray(CoordsSQL As String, Tipo As String) As JArray
Dim CoordsPoligono As String = CoordsSQL.Replace($"{Tipo}", "").Replace(")", "").Replace("(", "")
Dim CoordsPuntos() As String = CoordsPoligono.Split(","c)
Dim Json As New JArray(From coord In CoordsPuntos
Let c = coord.Trim.Split(" "c)
Select New JObject(
New JProperty("lat", c(1).ToDouble),
New JProperty("lng", c(0).ToDouble)
)
)
Return Json
End Function
End Class

607
Ashx/SIGWeb.ashx Normal file
View File

@@ -0,0 +1,607 @@
<%@ WebHandler Language="VB" Class="SIGWeb" %>
Imports System
Imports System.Web
Imports System.Data
Imports Newtonsoft.Json
Imports Extensiones
Imports System.IO
Public Class SIGWeb : Implements IHttpHandler, IRequiresSessionState
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Try
Select Case context.Request("metodo")
Case "getps"
GETPS(context)
Case "getps2"
GETPS(context, "PSCodigoClasificacion")
Case "getpsalmacen"
getpsalmacen(context)
Case "Uploadfile"
uploadfile(context)
Case "Downfile"
Downfile(context)
Case "GetImg"
GetImg(context)
Case "getpssat"
GETPSSAT(context)
Case "getpsusados"
GETPSUSADOS(context)
Case "getumsat"
GETUMSAT(context)
Case "getcliente"
GetClientes(context)
Case "getproveedores"
GetProveedores(context)
Case "getfraccionarancelaria"
GetFraccionArancelaria(context)
Case "GetUser"
GetUser(context)
End Select
Catch ex As Exception
ex.GuardaLog(ex.Message)
End Try
End Sub
Private Sub GetUser(ByVal context As HttpContext)
Dim usuario As String = context.Request("usuario").ToString()
Dim CveUsuario As Integer = -1
Dim objs As New ClsSisUsuarios
objs.GetWSusuarios(usuario)
If objs.DtResultados.Rows.Count > 0 Then
CveUsuario = objs.DtResultados.Rows(0)("CveUsuario").ToString().ToEntero()
End If
objs.Dispose()
If CveUsuario > 0 Then
CveUsuario = 1
End If
context.Response.Write(CveUsuario.ToString())
context.Response.StatusCode = 200
End Sub
Private Sub GetImg(ByVal context As HttpContext)
Dim Url As String = Decripta(context.Request("r").ToString)
Dim usuario As Usuario = UsuarioActual(context)
If Not IsNothing(usuario) Then
Url = String.Format("{0}Empresas\{1}\{2}", AppDomain.CurrentDomain.BaseDirectory, usuario.CveEmpresa, Url)
Dim FileInfo As FileInfo = New FileInfo(Url)
If FileInfo.Exists Then
context.Response.ContentType = "image/png"
context.Response.Flush()
context.Response.WriteFile(FileInfo.FullName)
context.Response.End()
End If
End If
End Sub
#Region "File"
Private Sub Downfile(ByVal context As HttpContext)
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = String.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings("FolderPath"), "/Temp")
savepath = context.Server.MapPath(tempPath)
Dim nombre As String = String.Format("{0}\{1}", savepath, context.Request("nombre"))
File.Delete(nombre)
context.Response.StatusCode = 200
End Sub
Private Sub uploadfile(ByVal context As HttpContext)
Dim postedFile As HttpPostedFile
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = String.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings("FolderPath"), "/Temp")
savepath = context.Server.MapPath(tempPath)
Dim filename As String
Dim tick As String
tick = (DateTime.Now.Ticks + 1).ToString()
If Not Directory.Exists(savepath) Then
Directory.CreateDirectory(savepath)
End If
If context.Request.Files.Count = 0 Then
Dim copyFile As String = context.Request("File")
Dim Cve As String = context.Request("Cve")
If copyFile <> "" Then
Dim ext As Integer = copyFile.IndexOf(","c) + 1
Dim extncion As String = copyFile.Substring(5, ext - 5)
If extncion.Contains("image/") Then extncion = extncion.Replace("image/", "").Replace(";base64,", "")
'Dim extncion As String =
filename = String.Format("{0}-{1}.{2}", tick, Cve, extncion)
Dim msf As New MemoryStream(Convert.FromBase64String(copyFile.Substring(ext)))
Dim stem As Stream = New FileStream(String.Format("{0}\{1}", savepath, filename), FileMode.Create)
msf.WriteTo(stem)
msf.Close()
stem.Close()
End If
Else
postedFile = context.Request.Files(0)
filename = String.Format("{0}-{1}", tick, postedFile.FileName)
postedFile.SaveAs((savepath & "\") + filename)
End If
context.Response.Write(tick)
context.Response.StatusCode = 200
End Sub
#End Region
#Region "Get Cliente"
Private Function GetClientes(ByVal context As HttpContext) As String
Dim retorno As String = ""
Dim DtRetorno As DataTable = Nothing
Dim usuario As Usuario = UsuarioActual(context)
Dim CveEmpresa As String
If IsNothing(usuario) Then
context.Response.Write("")
Else
CveEmpresa = usuario.CveEmpresa
Dim Name = IfNull(context.Request("Name"), "-1").ToString
Dim dt As DataTable = DirectCast(context.Application("GlobalDTCliente"), DataTable).FiltraParametros($"CveEmpresa = {CveEmpresa}")
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
DtRetorno = dt.FiltraParametros($"NombreComercial like '%{Name}%'")
End If
End If
If DtRetorno IsNot Nothing AndAlso DtRetorno.Rows.Count > 0 Then
DtRetorno.Columns("CveCliente").ColumnName = "id"
DtRetorno.Columns("NombreComercial").ColumnName = "text"
retorno = JsonConvert.SerializeObject(DtRetorno).ToString
context.Response.Write(retorno)
Else
context.Response.Write("[]")
End If
Return retorno
End Function
#End Region
#Region "Get Proveedor"
Private Function GetProveedores(ByVal context As HttpContext) As String
Dim retorno As String = ""
Dim DtRetorno As DataTable = Nothing
Dim usuario As Usuario = UsuarioActual(context)
Dim CveEmpresa As String
If IsNothing(usuario) Then
context.Response.Write("")
Else
CveEmpresa = usuario.CveEmpresa
Dim Name = IfNull(context.Request("Name"), "-1").ToString
Dim dt As DataTable = DirectCast(context.Application("GlobalDTCompProveedores"), DataTable).FiltraParametros($"CveEmpresa = {CveEmpresa}")
If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
DtRetorno = dt.FiltraParametros($"RazonSocial like '%{Name}%'")
End If
End If
If DtRetorno IsNot Nothing AndAlso DtRetorno.Rows.Count > 0 Then
DtRetorno.Columns("CveProveedor").ColumnName = "id"
DtRetorno.Columns("RazonSocial").ColumnName = "text"
retorno = JsonConvert.SerializeObject(DtRetorno).ToString
context.Response.Write(retorno)
Else
context.Response.Write("[]")
End If
Return retorno
End Function
#End Region
#Region " GET PS "
Private Function getpsalmacen(ByVal context As HttpContext) As String
Dim usuario As Usuario = UsuarioActual(context)
Dim CveEmpresa As String
Dim retorno As String = ""
Dim DtPSRetorno As DataTable = Nothing
If IsNothing(usuario) Then
context.Response.Write("")
Else
CveEmpresa = usuario.CveEmpresa
DtPSRetorno = New DataTable
DtPSRetorno.Columns.Add(New DataColumn("id", System.Type.GetType("System.Int32")))
DtPSRetorno.Columns.Add(New DataColumn("existencia", System.Type.GetType("System.Int32")))
DtPSRetorno.Columns.Add(New DataColumn("almacen", System.Type.GetType("System.String")))
Dim CvePS = IfNull(context.Request("cveps"), "0").ToString.ToEntero
Dim objInv As New ClsInventarios
If objInv.GetExistenciasProducto(CvePS, -1, CveEmpresa, -1, FechaMovto:=DateTime.Today.AddDays(1).ToString("yyyy/MM/dd HH:mm")) Then
' limpio los almacenes donde no tiene ningun producto existencia
For i = objInv.DtResultados.Columns.Count - 1 To 1 Step -1
If Not objInv.DtResultados.Columns(i).ColumnName.Contiene("CveAlmacen", "Almacen", "Existencia") Then
objInv.DtResultados.Columns.RemoveAt(i)
End If
Next
DtPSRetorno = objInv.DtResultados.FiltraParametros("CveAlmacen > 0 and Existencia > 0")
End If
objInv.Dispose()
End If
If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then
DtPSRetorno.Columns("CveAlmacen").ColumnName = "id"
DtPSRetorno.Columns("Almacen").ColumnName = "almacen"
DtPSRetorno.Columns("Existencia").ColumnName = "existencia"
retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString
context.Response.Write(retorno)
Else
context.Response.Write("[]")
End If
Return retorno
End Function
Private Function GETPS(ByVal context As HttpContext, Optional PSCodigoDescripcion As String = "PSCodigo") As String
Dim retorno As String = ""
Dim DtPSRetorno As DataTable = Nothing
'NOTA:
' EN EL WHERE DE LINQ NO SE DEBE USAS EL OPERADOR 'AND' SABE PORQUE FUNCIONA DIFERENTE SE DEBE USAR 'ANDALSO',
' EJEMPLO UNA CONDICION AND DE DOS CAMPOS ARROJA CERO RESULTADOS PERO SI SE PONE ESTAS DOS CONDICIONES POR SEPARADO ARROJA DATOS
Dim usuario As Usuario = UsuarioActual(context)
Dim CveEmpresa As String
If IsNothing(usuario) Then
context.Response.Write("")
Else
CveEmpresa = usuario.CveEmpresa
Dim FuePorXml = IfNull(context.Request("FuePorXml"), "-1").ToString.ToEntero
Dim Name = IfNull(context.Request("Name"), "-1").ToString
Dim CveClasificacion = IfNull(context.Request("CveClasificacion"), "-1").ToString.ToEntero
Dim CveSubFamilia = IfNull(context.Request("CveSubFamilia"), "-1").ToString.ToEntero
Dim CveClasificacionPresupuesto = IfNull(context.Request("CveClasificacionPresupuesto"), "-1").ToString.ToEntero
Dim Pagina = IfNull(context.Request("Pagina"), "-1").ToString
Dim Estatus = IfNull(context.Request("Estatus"), "1").ToString
Dim CveSucursal = IfNull(context.Request("cvesucursal"), "-1").ToString.ToEntero
Dim CveSubProyecto = IfNull(context.Request("cvesubproyecto"), "-1").ToString.ToEntero
Dim UsoClasificacion = IfNull(context.Request("usoclasificacion"), "-1").ToString.ToEntero
Dim AplicaParaVenta = IfNull(context.Request("aplicaparaventa"), "-1").ToString.ToEntero
Dim UsaGlobal As Boolean = True
'verifica existencias
If Pagina.Contiene("ventas/ventas", "oc/oc", "inv/traspaso") AndAlso CveEmpresa.Contiene(72, 80, 119, 140) Then
UsaGlobal = False
Dim objInv As New ClsInventarios
If objInv.GetExistenciasProductosLike(Name, CveClasificacion, CveSubProyecto, Estatus.ToEntero, AplicaParaVenta, CveEmpresa) Then
' limpio los almacenes donde no tiene ningun producto existencia
For i = objInv.DtResultados.Columns.Count - 1 To 1 Step -1
If Not objInv.DtResultados.Columns(i).ColumnName.Contiene("CvePS", "PSCodigo", "PSCodigoClasificacion") AndAlso objInv.DtResultados.SUM(String.Format("[{0}]", objInv.DtResultados.Columns(i).ColumnName)) = 0 Then
objInv.DtResultados.Columns.RemoveAt(i)
End If
Next
DtPSRetorno = objInv.DtResultados
End If
objInv.Dispose()
End If
If UsaGlobal Then
Dim DTPS = DirectCast(context.Application("GlobalDTPSSimplificado"), EnumerableRowCollection(Of DataRow))
If DTPS IsNot Nothing Then
'APLICACION DE FILTROS
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveEmpresa) = CveEmpresa))
If Estatus = 1 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveEstado) = 1))
ElseIf Estatus = -1 Then
End If
'If FuePorXml >= 0 Then
' DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!FuePorXML) = FuePorXml))
'End If
If Name <> "-1" Then
If PSCodigoDescripcion = "PSCodigo" Then
DTPS = DTPS.Where((Function(a) a!PSCodigo.ToString.ToLower Like ("*" + Name.ToLower + "*")))
Else
DTPS = DTPS.Where((Function(a) a!PSCodigoClasificacion.ToString.ToLower Like ("*" + Name.ToLower + "*")))
End If
End If
If CveClasificacion > 0 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacion) = CveClasificacion))
ElseIf CveClasificacion = -1 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacion) >= 0))
End If
If AplicaParaVenta > 0 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!AplicaParaVenta) = 1))
End If
'If CveSubFamilia > 0 Then
' DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveSubFamilia) = CveSubFamilia))
' 'ElseIf CveSubFamilia = -1 Then
' 'DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveSubFamilia) > 0))
'End If
If CveClasificacionPresupuesto > 0 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacionPresupuesto) = CveClasificacionPresupuesto))
End If
If UsoClasificacion > 0 Then DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!UsoClasificacion) = UsoClasificacion))
If Pagina <> "-1" Then
If Pagina = "Compras" Then
DTPS = DTPS.Where((Function(a) a!CveTipoPS = 1 AndAlso a!CveEstado = 1))
ElseIf Pagina = "Compras2" Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveTipoPS) = 1 AndAlso (Convert.ToInt32(a!CveEstado) = 1 OrElse Convert.ToInt32(a!CveEstado) = 2)))
ElseIf Pagina = "Inventarios" Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveTipoPS) = 2))
End If
End If
'Try, generado para cuando el resultado no tiene valores(The source contains no DataRows.), no detenga la ejecucion, no se le puso un count previo, porque el costo se duplica, al preguntar y luego ordenar y convertir a datatable
Try
DtPSRetorno = New DataView(DTPS.OrderBy(Function(a) a!PSCodigo).CopyToDataTable).ToTable(True, {"CvePS", "PSCodigo", "PSCodigoClasificacion"})
Catch ex As Exception
DtPSRetorno = Nothing
End Try
End If
End If
If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then
DtPSRetorno.Columns("CvePS").ColumnName = "id"
DtPSRetorno.Columns(PSCodigoDescripcion).ColumnName = "text"
If PSCodigoDescripcion = "PSCodigo" Then
DtPSRetorno.Columns().Remove("PSCodigoClasificacion")
Else
DtPSRetorno.Columns().Remove("PSCodigo")
End If
retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString
context.Response.Write(retorno)
Else
context.Response.Write("[]")
End If
End If
Return retorno
End Function
#End Region
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
#Region "Funciones"
Public Function GetJson(ByVal dt As DataTable) As String
Dim serializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
Return serializer.Serialize(rows)
End Function
ReadOnly Property UsuarioActual(ByVal context As HttpContext) As Usuario
Get
UsuarioActual = DirectCast(context.Session("UsuarioSIG"), Usuario)
End Get
End Property
#End Region
#Region " GET PS SAT "
Private Function GETPSSAT(ByVal context As HttpContext) As String
Dim retorno As String = ""
Dim DTPS = DirectCast(context.Application("GlobalDTPSATPS"), EnumerableRowCollection(Of DataRow))
Dim DtPSRetorno As DataTable
Dim Name = IfNull(context.Request("Name"), "-1").ToString
If Name <> "-1" Then
DTPS = DTPS.Where((Function(a) a!SATClaveProductoServicio.ToString.ToLower Like ($"*{Name.ToLower}*")))
End If
DtPSRetorno = New DataView(DTPS.OrderBy(Function(a) a!SATClavePS).CopyToDataTable).ToTable(True, {"CveSATPS", "SATClaveProductoServicio"})
If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then
DtPSRetorno.Columns("CveSATPS").ColumnName = "id"
DtPSRetorno.Columns("SATClaveProductoServicio").ColumnName = "text"
retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString
context.Response.Write(retorno)
Else
context.Response.Write("[]")
End If
DtPSRetorno.Dispose()
Return retorno
End Function
#End Region
#Region " GET UM SAT "
Private Function GETUMSAT(ByVal context As HttpContext) As String
Dim retorno As String = ""
Dim DTUM = DirectCast(context.Application("GlobalDTPSATUM"), EnumerableRowCollection(Of DataRow))
Dim DtPSRetorno As DataTable
Dim Name = IfNull(context.Request("Name"), "-1").ToString
If Name <> "-1" Then
DTUM = DTUM.Where((Function(a) a!ClaveNombre.ToString.ToLower Like ("*" + Name.ToLower + "*")))
End If
DtPSRetorno = New DataView(DTUM.OrderBy(Function(a) a!Nombre).CopyToDataTable).ToTable(True, {"CveSATUnidadMedida", "ClaveNombre"})
If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then
DtPSRetorno.Columns("CveSATUnidadMedida").ColumnName = "id"
DtPSRetorno.Columns("ClaveNombre").ColumnName = "text"
retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString
context.Response.Write(retorno)
Else
context.Response.Write("[]")
End If
Return retorno
End Function
#End Region
#Region " GET FRACCION ARANCELARIA "
Private Function GetFraccionArancelaria(ByVal context As HttpContext) As String
Dim retorno As String = ""
Dim DT = DirectCast(context.Application("GlobalDTFraccionArancelaria"), EnumerableRowCollection(Of DataRow))
Dim DtRetorno As DataTable
Dim Name = IfNull(context.Request("Name"), "-1").ToString
If Name <> "-1" Then
DT = DT.Where((Function(a) a!ClaveSATFraccionArancelariaDescripcion.ToString.ToLower Like ($"*{Name.ToLower}*")))
End If
DtRetorno = New DataView(DT.OrderBy(Function(a) a!ClaveSATFraccionArancelaria).CopyToDataTable).ToTable(True, {"CveFraccionArancelaria", "ClaveSATFraccionArancelariaDescripcion"})
If DtRetorno IsNot Nothing AndAlso DtRetorno.Rows.Count > 0 Then
DtRetorno.Columns("CveFraccionArancelaria").ColumnName = "id"
DtRetorno.Columns("ClaveSATFraccionArancelariaDescripcion").ColumnName = "text"
retorno = JsonConvert.SerializeObject(DtRetorno).ToString
context.Response.Write(retorno)
Else
context.Response.Write("[]")
End If
DtRetorno.Dispose()
Return retorno
End Function
#End Region
#Region "USADOS"
Private Function GETPSUSADOS(ByVal context As HttpContext) As String
Dim retorno As String = ""
Dim DtPSRetorno As DataTable = Nothing
Dim usuario As Usuario = UsuarioActual(context)
Dim CveEmpresa As String
If IsNothing(usuario) Then
context.Response.Write("")
Else
CveEmpresa = usuario.CveEmpresa
Dim FuePorXml = IfNull(context.Request("FuePorXml"), "-1").ToString.ToEntero
Dim Name = IfNull(context.Request("Name"), "-1").ToString
Dim CveClasificacion = IfNull(context.Request("CveClasificacion"), "-1").ToString.ToEntero
Dim CveSubFamilia = IfNull(context.Request("CveSubFamilia"), "-1").ToString.ToEntero
Dim CveClasificacionPresupuesto = IfNull(context.Request("CveClasificacionPresupuesto"), "-1").ToString.ToEntero
Dim Pagina = IfNull(context.Request("Pagina"), "-1").ToString
Dim Estatus = IfNull(context.Request("Estatus"), "1").ToString
Dim CveSucursal = IfNull(context.Request("cvesucursal"), "-1").ToString.ToEntero
Dim CveSubProyecto = IfNull(context.Request("cvesubproyecto"), "-1").ToString.ToEntero
Dim UsoClasificacion = IfNull(context.Request("usoclasificacion"), "-1").ToString.ToEntero
Dim UsaGlobal As Boolean = True
If UsaGlobal Then
Dim DTPS = DirectCast(context.Application("GlobalDTPSSimplificado"), EnumerableRowCollection(Of DataRow))
If DTPS IsNot Nothing Then
'APLICACION DE FILTROS
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveEmpresa) = CveEmpresa))
If Estatus = 1 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveEstado) = 1))
ElseIf Estatus = -1 Then
End If
If Name <> "-1" Then
DTPS = DTPS.Where((Function(a) a!PSCodigo.ToString.ToLower Like ("*" + Name.ToLower + "*")))
End If
If CveClasificacion > 0 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacion) = CveClasificacion))
ElseIf CveClasificacion = -1 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacion) >= 0))
End If
If CveClasificacionPresupuesto > 0 Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveClasificacionPresupuesto) = CveClasificacionPresupuesto))
End If
If UsoClasificacion > 0 Then DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!UsoClasificacion) = UsoClasificacion))
If Pagina <> "-1" Then
If Pagina = "Compras" Then
DTPS = DTPS.Where((Function(a) a!CveTipoPS = 1 AndAlso a!CveEstado = 1))
ElseIf Pagina = "Compras2" Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveTipoPS) = 1 AndAlso (Convert.ToInt32(a!CveEstado) = 1 OrElse Convert.ToInt32(a!CveEstado) = 2)))
ElseIf Pagina = "Inventarios" Then
DTPS = DTPS.Where((Function(a) Convert.ToInt32(a!CveTipoPS) = 2))
End If
End If
Try
DtPSRetorno = New DataView(DTPS.OrderBy(Function(a) a!PSCodigo).CopyToDataTable).ToTable(True, {"CvePS", "PSCodigo", "CveTamaño"})
DtPSRetorno = DtPSRetorno.FiltraParametros("CveTamaño > 0")
Catch ex As Exception
DtPSRetorno = Nothing
End Try
End If
End If
If DtPSRetorno IsNot Nothing AndAlso DtPSRetorno.Rows.Count > 0 Then
DtPSRetorno.Columns("CvePS").ColumnName = "id"
DtPSRetorno.Columns("PSCodigo").ColumnName = "text"
retorno = JsonConvert.SerializeObject(DtPSRetorno).ToString
context.Response.Write(retorno)
Else
context.Response.Write("[]")
End If
End If
Return retorno
End Function
#End Region
End Class

1
Ashx/SIGWeb.aspx Normal file
View File

@@ -0,0 +1 @@
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="SIGWeb.aspx.vb" Inherits="Ashx_SIGWeb" %>

42
Ashx/SIGWeb.aspx.vb Normal file
View File

@@ -0,0 +1,42 @@
Option Explicit On
Option Strict On
Imports Extensiones
Imports System.Data
Imports Newtonsoft.Json
Partial Class Ashx_SIGWeb
Inherits System.Web.UI.Page
ReadOnly Property UsuarioActual() As Usuario
Get
UsuarioActual = DirectCast(Session("UsuarioSIG"), Usuario)
End Get
End Property
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim retorno As String = ""
Dim DTPS = DirectCast(Application("GlobalDTProductosServicios"), DataTable)
If DTPS IsNot Nothing Then
Dim usuario As Usuario = UsuarioActual
Dim CveEmpresa As String
If IsNothing(usuario) Then
Context.Response.Write("")
Else
CveEmpresa = usuario.CveEmpresa.ToString
DTPS = DTPS.FiltraParametros(String.Format("CveEmpresa={0} AND PSCodigo LIKE '%{1}%'", CveEmpresa, Request("Name")), "PS", {"CvePS", "PS"})
If DTPS.Rows.Count > 0 Then
DTPS.Columns("CvePS").ColumnName = "id"
DTPS.Columns("PS").ColumnName = "text"
retorno = JsonConvert.SerializeObject(DTPS).ToString
Context.Response.Write(retorno)
Else
Context.Response.Write("[]")
End If
End If
End If
End Sub
End Class

View File

@@ -0,0 +1,193 @@
<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="SigFoxDecodeExample.aspx.vb" Inherits="Ashx_SigFoxDecodeExample" %>
<asp:Content ID="Content1" ContentPlaceHolderID="CP" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Css" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="E" Runat="Server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="HB" Runat="Server">
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="H" Runat="Server">
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="HA" Runat="Server">
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="C" Runat="Server">
</asp:Content>
<asp:Content ID="Content8" ContentPlaceHolderID="JS" Runat="Server">
<script type="text/javascript">
//e.g. parseSigFox('10b67dcc0006efda3d9816c2')
//In an attempt to make the code clearer, I will not be using ArrayBuffer
function hex2Bytes(val) {
if (!val) {
return [];
}
val = val.trim();
if (val.startsWith('0x')) {
val = val.substring(2); //get rid of starting '0x'
}
var numBytes = val.length / 2;
var bytes = [];
for (var i = 0; i < numBytes; i++) {
bytes.push(parseInt(val.substring(i * 2, (i * 2) + 2), 16));
}
return bytes;
}
function parseLittleEndianInt32(buffer, offset) {
return (buffer[offset + 3] << 24) +
(buffer[offset + 2] << 16) +
(buffer[offset + 1] << 8) +
(buffer[offset]);
}
function parseLittleEndianInt16(buffer, offset) {
return (buffer[offset + 1] << 8) +
(buffer[offset]);
}
function parseLittleEndianInt16Bits(buffer, offset, bitOffset, bitLength) {
var temp = parseLittleEndianInt16(buffer, offset);
temp = temp >> bitOffset;
var mask = 0xffff >> (16 - bitLength);
return temp & mask;
}
//e.g. 10b67dcc0006efda3d9816c2
function parseSigFox(data) {
var buffer = hex2Bytes(data);
if (!buffer) {
return null;
}
var recordType = buffer[0] & 0x0f;
switch (recordType) {
case 0: //positional data
return parsePositionalData(buffer);
case 1: //downlink ACK
return parseDownlinkAck(buffer);
case 2: //device data
return parseDeviceStats(buffer);
case 3: //extended positional data
return parseExtendedData(buffer);
default:
return null;
}
}
function parsePositionalData(buffer) {
var flags = buffer[0] & 0xF0;
var inTrip = (flags & 0x10) > 0;
var lastFixFailed = (flags & 0x20) > 0;
var latitudeRaw = parseLittleEndianInt32(buffer, 1);
var longitudeRaw = parseLittleEndianInt32(buffer, 5);
var headingRaw = buffer[9];
var speedRaw = buffer[10];
var batteryRaw = buffer[11];
return {
MessageType: 0,
InTrip: inTrip,
LastFixFailed: lastFixFailed,
Latitude: latitudeRaw * 1e-7,
Longitude: longitudeRaw * 1e-7,
Heading: headingRaw * 2,
SpeedKmH: speedRaw,
BatteryVoltage: (batteryRaw * 25) / 1000.0
};
}
function parseDownlinkAck(buffer) {
var flags = buffer[0] & 0xF0;
var downlinkAccepted = (flags & 0x10) > 0;
var firmwareMajor = buffer[2];
var firmwareMinor = buffer[3];
var data = [];
for (var i = 0; i < 8; i++) {
data.push(i + 4);
}
return {
MessageType: 1,
DownlinkAccepted: downlinkAccepted,
FirmwareVersion: firmwareMajor + '.' + firmwareMinor,
DownlinkData: data
};
}
function parseDeviceStats(buffer) {
var uptimeWeeks = parseLittleEndianInt16Bits(buffer, 0, 4, 9/*bits*/);
var txCountRaw = parseLittleEndianInt16Bits(buffer, 1, 5, 11 /*bits*/);
var rxCountRaw = buffer[3];
var tripCountRaw = parseLittleEndianInt16Bits(buffer, 4, 0, 13 /*bits*/);
var gpsSuccessRaw = parseLittleEndianInt16Bits(buffer, 5, 5, 10 /*bits*/);
var gpsFailuresRaw = parseLittleEndianInt16Bits(buffer, 6, 7, 8 /*bits*/);
var averageFixTime = parseLittleEndianInt16Bits(buffer, 7, 7, 9/*bits*/);
var averageFailTime = parseLittleEndianInt16Bits(buffer, 9, 0, 9/*bits*/);
var averageFreshenTime = parseLittleEndianInt16Bits(buffer, 10, 1, 8/*bits*/);
var wakeupsPerTrip = buffer[11] >> 1;
return {
MessageType: 2,
UptimeWeeks: uptimeWeeks,
TxCount: txCountRaw * 32,
RxCount: rxCountRaw * 32,
TripCount: tripCountRaw,
GpsSuccessCount: gpsSuccessRaw * 32,
GpsFailureCount: gpsFailuresRaw * 32,
AverageFixTimeSeconds: averageFixTime,
AverageFailTimeSeconds: averageFailTime,
AverageFreshenTimeSeconds: averageFreshenTime,
WakeUpsPerTrip: wakeupsPerTrip
};
}
function parseExtendedData(buffer) {
var headingRaw = buffer[0] >> 4;
var latitudeRaw = buffer[1] + buffer[2] * 256 + buffer[3] * 65536;
if (latitudeRaw >= 0x800000) // 2^23
latitudeRaw -= 0x1000000; // 2^24
var longitudeRaw = buffer[4] + buffer[5] * 256 + buffer[6] * 65536;
if (longitudeRaw >= 0x800000) // 2^23
longitudeRaw -= 0x1000000; // 2^24
var posAccRaw = buffer[7];
var batteryRaw = buffer[8];
var speedRaw = buffer[9] & 0x3F;
var inTrip = (buffer[9] & 0x40) > 0;
var lastFixFailed = (buffer[9] & 0x80) > 0;
return {
MessageType: 3,
Heading: headingRaw * 22.5,
Latitude: (latitudeRaw * 256) / 1e7,
Longitude: (longitudeRaw * 256) / 1e7,
PosAccM: posAccRaw * 1,
BatteryVoltage: (batteryRaw * 25) / 1000.0,
SpeedKmH: speedRaw * 2.5,
InTrip: inTrip,
LastFixFailed: lastFixFailed
};
}
</script>
</asp:Content>

View File

@@ -0,0 +1,11 @@
Imports System.Collections
Partial Class Ashx_SigFoxDecodeExample
Inherits System.Web.UI.Page
Public Sub Page_Load() Handles Me.Load
Dim ObjNotificaciones As New ClsSisNotificaciones
ObjNotificaciones.ObtenerNotificaciones()
ObjNotificaciones.Dispose()
End Sub
End Class

249
Ashx/TareasProgramadas.ashx Normal file
View File

@@ -0,0 +1,249 @@
<%@ WebHandler Language="VB" Class="TareasProgramadas" %>
Imports System
Imports System.Web
Imports System.Data
Imports Newtonsoft.Json
Imports Extensiones
Imports System.IO
Public Class TareasProgramadas : Implements IHttpHandler
Private currentcontext As HttpContext
Private URLParametros As New Hashtable
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
currentcontext = context
'timbrarNominab()
Dim retorno As String = "no se encontro la variable"
Try
URLParametros = Parametros(context.Request("var"))
Dim metodo As String = URLParametros("metodo")
Select Case metodo
Case "TimbrarNomina"
retorno = "Error Timbrado Nomina"
retorno = timbrarNomina()
retorno = ""
End Select
Catch ex As Exception
ex.GuardaLog(ex.ToString())
End Try
context.Response.Write(retorno)
End Sub
Public Sub timbrarNominab()
Dim cveEmpresa As String = "5"
Dim Dv As New DataView(DirectCast(currentcontext.Application("GlobalDTUsuarios"), DataTable), $"CveUsuario = 100 AND CveEmpresa ={cveEmpresa}", "", DataViewRowState.CurrentRows)
Dim GlobalDTUsuarios As DataTable = Dv.ToTable
Dv.Dispose()
Dim usuario As Usuario = Nothing
'Dim UsuarioAsignaciones As Usuario
If GlobalDTUsuarios.Rows.Count > 0 Then
Dim dtrow As DataRow = GlobalDTUsuarios.Rows(0)
Dim ObjUsuario As New ClsSisUsuarios
usuario = ObjUsuario.ValidaUsuario(dtrow("Usuario"), dtrow("Contraseña"), IMEI, cveEmpresa)
ObjUsuario.Dispose()
Dim ObjEmpresa As New ClsSisEmpresas()
If ObjEmpresa.GetEmpresas(cveEmpresa, "-1", "-1", "-1", "-1") Then
If ObjEmpresa.GetEmpresasFuncionalidades(cveEmpresa) Then
Dim dttmp As Data.DataTable = ObjEmpresa.DtResultados
Dim EmpresasFuncionalidades As New HybridDictionary
For Each Row As Data.DataRow In dttmp.Rows
EmpresasFuncionalidades.Add(Convert.ToInt32(Row("CveFuncionalidad")), Row("Valor").ToString)
Next
ObjEmpresa.Empresa.SetFuncionalidades(EmpresasFuncionalidades)
End If
usuario.Empresa = ObjEmpresa.Empresa
usuario.CveEmpresa = ObjEmpresa.Empresa.CveEmpresa
ADSSession.ADSSessionConfig.SessionManager(ADSSession.OpcionSession.CambiarEmpresa, Nothing, ObjEmpresa.Empresa.CveEmpresa)
Else
End If
ObjEmpresa.Dispose()
Dim StrErrores As New StringBuilder
Dim Msg As String = String.Empty
Dim CvePeriodo As Integer
Dim CveNomina As Integer
Dim CvePersonal As Integer
Dim SerieFolio As String
Dim DtNominas As New DataTable
Dim objnom As New ClsNominas
objnom.GetNom_porTimbrar(usuario.CveEmpresa)
DtNominas = objnom.DtResultados
'DtNominas = New DataTable
Dim noCiclos As Integer = 0
Dim noTotal As Integer = DtNominas.Rows.Count
Dim lognom As New LogicNominas
For Each Row As DataRow In DtNominas.Rows
'If noCiclos < 4 Then
noCiclos = noCiclos + 1
CveNomina = Row("CveNomina").ToString().ToEntero()
CvePersonal = Row("CvePersonal").ToString().ToEntero()
SerieFolio = Row("SerieFolio").ToString()
CvePeriodo = Row("CvePeriodo").ToString.ToEntero
If CveNomina > 0 Then
Msg = lognom.TimbrarNomina(CveNomina, CvePersonal, CvePeriodo, usuario)
If Msg.Trim <> String.Empty Then StrErrores.Append(Msg & "<br />")
End If
'Else
' Exit For
'End If
Next
GC.Collect()
StrErrores.ToString().GuardaLog()
If StrErrores.ToString().Length > 0 And CvePeriodo > 0 Then
Dim ObjPeriodo As New ClsNominas()
ObjPeriodo.CambiaEstatusPeriodo(CvePeriodo, enumNominasEstatus.Timbrada, usuario.CveUsuario, usuario.CveEmpresa)
ObjPeriodo.Dispose()
'EnvioMasivoCorreo()
'Dim temp As String = DdlPeriodo.SelectedValue
'CargaPeriodos()
'BtnEmitir.Visible = False
'DdlPeriodo.SelectedValue = temp
End If
End If
End Sub
Private Function GetUsuario(CveEmpresa As Integer, Optional CveUsuario As Integer = -1, Optional username As String = "", Optional pass As String = "") As Usuario
Dim usuario As Usuario = Nothing
#Region "Valido que los campos usuario contraseña no sean nulos"
If IsNothing(username) Then
username = ""
End If
If IsNothing(pass) Then
pass = ""
End If
#End Region
#Region "Si el CveUsuario es mayor que cero asigno el username y pass la de la CveUsuario"
If CveUsuario > 0 Then
Using Dv As New DataView(DirectCast(currentcontext.Application("GlobalDTUsuarios"), DataTable), $"CveUsuario = 100 AND CveEmpresa ={CveEmpresa}", "", DataViewRowState.CurrentRows)
Using GlobalDTUsuarios As DataTable = Dv.ToTable()
If GlobalDTUsuarios.Rows.Count > 0 Then
Dim dtrow As DataRow = GlobalDTUsuarios.Rows(0)
username = dtrow("Usuario")
pass = dtrow("Contraseña")
End If
End Using
End Using
End If
#End Region
#Region "obtengo el usuario con el username y la pass"
Using ObjUsuario As New ClsSisUsuarios()
usuario = ObjUsuario.ValidaUsuario(username, pass, IMEI, CveEmpresa)
End Using
#End Region
#Region "Asigno la empresa al usuario"
If Not IsNothing(usuario) Then
Using ObjEmpresa As New ClsSisEmpresas()
If ObjEmpresa.GetEmpresas(CveEmpresa, "-1", "-1", "-1", "-1") Then
If ObjEmpresa.GetEmpresasFuncionalidades(CveEmpresa) Then
Dim dttmp As Data.DataTable = ObjEmpresa.DtResultados
Dim EmpresasFuncionalidades As New HybridDictionary
For Each Row As Data.DataRow In dttmp.Rows
EmpresasFuncionalidades.Add(Convert.ToInt32(Row("CveFuncionalidad")), Row("Valor").ToString)
Next
ObjEmpresa.Empresa.SetFuncionalidades(EmpresasFuncionalidades)
End If
usuario.Empresa = ObjEmpresa.Empresa
usuario.CveEmpresa = ObjEmpresa.Empresa.CveEmpresa
Else
End If
End Using
End If
#End Region
Return usuario
End Function
Public Function timbrarNomina() As String
Dim retorno As String = ""
Dim cveEmpresa As String = URLParametros("CveEmpresa").ToString().ToEntero()
Dim CvePeriodo As Integer = URLParametros("CvePeriodo").ToString().ToEntero()
Dim CveNomina As Integer = URLParametros("CveNomina").ToString().ToEntero()
Dim CvePersonal As Integer = URLParametros("CvePersonal").ToString().ToEntero()
Dim usuario As Usuario = GetUsuario(cveEmpresa, 100)
If Not IsNothing(usuario) Then
Dim StrErrores As New StringBuilder
Dim Msg As String = String.Empty
Dim lognom As New LogicNominas
If CveNomina > 0 Then
Msg = lognom.TimbrarNomina(CveNomina, CvePersonal, CvePeriodo, usuario)
If Msg.Trim() <> String.Empty Then StrErrores.Append(Msg)
retorno = Msg.Trim()
Else
retorno = "Nomina invalida periodo timbrar"
End If
'Using ObjPeriodo As New ClsNominas()
' If StrErrores.ToString().Length > 0 Then
' ObjPeriodo.CambiaEstatusPeriodo(CvePeriodo, enumNominasEstatus.ErrorEnTimbrado, usuario.CveUsuario, usuario.CveEmpresa)
' Else
' ObjPeriodo.CambiaEstatusPeriodo(CvePeriodo, enumNominasEstatus.Timbrada, usuario.CveUsuario, usuario.CveEmpresa)
' End If
'End Using
Else
retorno = "No se encontro el usuario"
Me.GuardaLog(String.Format("Error Timbrado Nomina CveEmpresa:{0} ", usuario.CveEmpresa))
End If
Return retorno
End Function
Private Function Parametros(Cadena As String) As Hashtable
Cadena = Decripta(Cadena)
Dim P1() As String = Cadena.Split("&"c)
Dim Tmp As String
Dim P2() As String
Dim URLParametros As New Hashtable
For Each Tmp In P1
P2 = Tmp.Replace("%26%", "&").Split("="c)
URLParametros.Add(P2(0).ToString(), P2(1))
Next
Return URLParametros
End Function
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class