Files
SIG/GPS/Rastreo.aspx.vb
HECTOR RODRIGUEZ 2a3de0c64d Cambios en reportes
2021-03-17 13:29:19 -07:00

2342 lines
117 KiB
VB.net

Option Strict On
Option Explicit On
Imports System.Data
Imports System.IO
Imports System.Net
Imports System.Net.Http
Imports Extensiones
Imports GemBox.Spreadsheet
Imports Microsoft.Reporting.WebForms
Imports Newtonsoft.Json.Linq
Partial Class GPS_Rastreo
Inherits ClsPaginas
#Region "P R O P I E D A D E S"
Private Property TrazarLineaContinuo As Boolean
Get
Return CType(ViewState("TrazarLineaContinuo"), Boolean)
End Get
Set(value As Boolean)
ViewState("TrazarLineaContinuo") = value
End Set
End Property
Private Property JSCargaSeleccion As String
Get
Return CType(ViewState("JSCargaSeleccion"), String)
End Get
Set(value As String)
ViewState("JSCargaSeleccion") = value
End Set
End Property
Private Property Opcion As String
Get
Return CType(ViewState("Opcion"), String)
End Get
Set(value As String)
ViewState("Opcion") = value
End Set
End Property
Private Property Mensajes As String
Get
Return CType(ViewState("Mensajes"), String)
End Get
Set(value As String)
ViewState("Mensajes") = value
End Set
End Property
Private Property Filtrado As Boolean
Get
Return CType(ViewState("Filtrado"), Boolean)
End Get
Set(value As Boolean)
ViewState("Filtrado") = value
End Set
End Property
Public Property DtDetalle() As Data.DataTable
Get
Return DirectCast(ViewState("DtDetalle"), DataTable)
End Get
Set(ByVal value As Data.DataTable)
ViewState("DtDetalle") = value
End Set
End Property
Private Property DtDatos As DataTable
Get
Return CType(ViewState("DtDatos"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtDatos") = value
End Set
End Property
Private Property FechaI As DateTime
Get
Return CType(ViewState("FechaI"), DateTime)
End Get
Set(value As DateTime)
ViewState("FechaI") = value
End Set
End Property
Private Property FechaF As DateTime
Get
Return CType(ViewState("FechaF"), DateTime)
End Get
Set(value As DateTime)
ViewState("FechaF") = value
End Set
End Property
Private Property DtCoordenadasContinuas As DataTable
Get
Return CType(ViewState("DtCoordenadasContinuas"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtCoordenadasContinuas") = value
End Set
End Property
Private Property DtPosiciones As DataTable
Get
Return CType(ViewState("DtPosiciones"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPosiciones") = value
End Set
End Property
Private Property DtPosicionesW As DataTable
Get
Return CType(ViewState("DtPosicionesW"), DataTable)
End Get
Set(value As DataTable)
ViewState("DtPosicionesW") = value
End Set
End Property
#End Region
Private Property IndiceGV As Integer
Get
Return CType(ViewState("IndiceGV"), Integer)
End Get
Set(value As Integer)
ViewState("IndiceGV") = value
End Set
End Property
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
CargaDispositivos()
CargaEventos()
CargaGrupos()
CargaGruposPI()
CreaTmpDTDetalle()
IndiceGV = 0
End If
End Sub
Private Sub CargaDispositivos()
Dim Dt = GlobalDTDispositivosUsuarios(UsuarioActual.CveCliente, UsuarioActual.CveUsuario).FiltraParametros("Estatus = 1 ")
GvDispositivos.DataSource = Dt
GvDispositivos.DataBind()
DdlEquipoD.DataSource = GlobalDTDispositivos(UsuarioActual.CveCliente)
DdlEquipoD.DataBind()
DdlEquipoD.Items.Insert(0, New ListItem("Seleccione", "-1"))
RegistraScript("$('#C_GvDispositivos_chkSelectAll').click(function () { $("".ChkAllEvt input"").not(this).prop('checked',$(this).is(':checked')); });", "1")
End Sub
Private Sub CargaGruposPI()
Dim ObjGPS As New ClsGPS
If ObjGPS.PuntoDeInteresGrupoGet(-1, 1) Then
GvGrupos.DataSource = ObjGPS.DtResultados
End If
ObjGPS.Dispose()
GvGrupos.DataBind()
UpAgregarPuntoInteres.Update()
End Sub
Private Sub CargaEventos()
Dim GPS As New ClsGPS
If GPS.EventoGet2(-1, -1, 1) Then
GvEventos.DataSource = GPS.DtResultados
Else
GvEventos.DataSource = Nothing
End If
GPS.Dispose()
GvEventos.DataBind()
End Sub
Private Sub CargaGrupos()
Using ObjGPS As New ClsGPS
If ObjGPS.GruposGet(-1, UsuarioActual.CveCliente) Then
DdlGrupo.DataSource = ObjGPS.DtResultados
DdlGrupo.DataBind()
End If
End Using
DdlGrupo.Items.Insert(0, New ListItem("Seleccione", "-1"))
End Sub
Protected Sub CreaTmpDTDetalle()
DtDetalle = New DataTable
Dim pk = DtDetalle.Columns.Add("CveDispositivo", GetType(Integer))
DtDetalle.Columns.Add("NoEconomico", GetType(String))
DtDetalle.Columns.Add("CveDispositivoGeoReferenciaDetalle", GetType(Integer))
DtDetalle.PrimaryKey = New DataColumn() {pk}
GvEquiposDetalle.DataSource = DtDetalle
GvEquiposDetalle.DataBind()
UpAgregar.Update()
End Sub
Protected Sub BtnCosultar_Click(sender As Object, e As EventArgs) Handles BtnRastrear.Click
RegistraScript("DeleteMarkers();", "0")
If Opcion = "KM" Then
ReporteKM()
RegistraScript("FNShowDiv();")
ElseIf Opcion = "Last" OrElse Opcion = "Watch" OrElse Opcion = "TPS" Then
CreaDTPosiciones()
Dim SB As New StringBuilder()
For Each row As GridViewRow In GvDispositivos.Rows
If row.FCCheckBox("chkDis").Checked Then
SB.Append($"{row.DataKey("CveDispositivo")};")
End If
Next
RastrearEquipoNew(SB.ToString, Opcion)
DivGvKM.Visible = False
GVKm.Visible = False
GvBarra.Visible = True
IndiceGV = 0
HdnIndexPage.Value = "0"
If DtPosiciones.Rows.Count > 1000 Then
DvPaginacion.Visible = True
LblRegistros.Text = $"Distribución de datos desde 0 hasta 1,000. Total de registros: {DtPosiciones.Rows.Count.ToString.FormatoNumero}"
Else
DvPaginacion.Visible = False
End If
GvBarra.DataSource = DtPosiciones
GvBarra.DataBind()
If DtPosiciones IsNot Nothing AndAlso DtPosiciones.Rows.Count > 0 Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "")
If Opcion = "TPS" Then
GvBarra.HeaderRow.Cells(4).Text = "No. Pasajeros"
GvBarra.HeaderRow.Cells(4).Style.Add("display", "")
Else
GvBarra.HeaderRow.Cells(4).Style.Add("display", "none !important")
End If
If Opcion = "Last" OrElse Opcion = "Watch" OrElse Opcion = "Idle" OrElse Opcion = "Ralenti" Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "")
GvBarra.HeaderRow.Cells(4).Style.Add("display", "none !important")
ElseIf Opcion = "All" OrElse Opcion = "TPS" Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "")
ElseIf Opcion <> "Eventos" Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "none !important")
GvBarra.HeaderRow.Cells(4).Style.Add("display", "none !important")
End If
End If
Else
CreaDTPosiciones()
For Each row As GridViewRow In GvDispositivos.Rows
If row.FCCheckBox("chkDis").Checked Then
RastrearEquipo(row, Opcion)
End If
Next
If Not String.IsNullOrEmpty(Mensajes) Then
Alert($"No se encontraron resultados en los siguientes vehiculos: {Mensajes}", TipoMensaje.MsgAdvertencia)
Mensajes = ""
End If
DivGvKM.Visible = False
GVKm.Visible = False
GvBarra.Visible = True
IndiceGV = 0
HdnIndexPage.Value = "0"
If DtPosiciones.Rows.Count > 1000 Then
DvPaginacion.Visible = True
LblRegistros.Text = $"Distribución de datos de 0 hasta 1,000. Total de registros: {DtPosiciones.Rows.Count.ToString.FormatoNumero}"
Else
DvPaginacion.Visible = False
End If
GvBarra.DataSource = DtPosiciones
GvBarra.DataBind()
If DtPosiciones.Rows.Count > 0 Then
If Opcion = "Last" OrElse Opcion = "Watch" OrElse Opcion = "Idle" OrElse Opcion = "Ralenti" Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "")
GvBarra.HeaderRow.Cells(4).Style.Add("display", "none !important")
ElseIf Opcion = "All" Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "")
ElseIf Opcion <> "Eventos" Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "none !important")
GvBarra.HeaderRow.Cells(4).Style.Add("display", "none !important")
End If
End If
End If
UPGV.Update()
UPModalBusqueda.Update()
'If Opcion = "Ralenti" OrElse Opcion = "Idle" OrElse Opcion = "All" Then
' ScriptManager.GetCurrent(Me).RegisterAsyncPostBackControl()
' ScriptManager.GetCurrent(Me).RegisterPostBackControl(GvBarra.HeaderRow.FCLinkButton("BtnImprimirEX"))
'Else
' GvBarra.HeaderRow.Cells(6).Style.Add("display", "none !important")
'End If
UPGV.Update()
UPModalBusqueda.Update()
RegistraScript($"$('#HdnOpcion').val('{Opcion}');", "1700")
End Sub
Private Sub ReporteKM()
Dim GPS As New ClsGPS
FechaI = If(txtFechaI.Text.Trim = "", MinFecha, txtFechaI.Text.Trim.ToDate)
FechaF = If(txtFechaF.Text.Trim = "", MaxFecha, txtFechaF.Text.Trim.ToDate)
If GPS.ReporteKMGet(UsuarioActual.CveCliente, FechaI, FechaF, GlobalDTDispositivosUsuarios(UsuarioActual.CveCliente, UsuarioActual.CveUsuario).DefaultView.ToTable(True, "CveDispositivo")) Then
GVKm.DataSource = GPS.DtResultados
DtDatos = GPS.DtResultados
End If
GPS.Dispose()
GvBarra.Visible = False
GVKm.Visible = True
DivGvKM.Visible = True
GVKm.DataBind()
rowImpresionesKM.Visible = True
End Sub
Private Sub RastrearEquipo(GVRow As GridViewRow, Opcion As String)
Dim LastCoord As String = ""
Dim TmpDT As New DataTable
Dim Info = ""
Dim Direccion = ""
Dim SBBody As New StringBuilder
Dim Icono As String = "/Imagenes/rsz_11rsz_car.png"
Dim Fecha, Vehiculo As String
TimmerRefresh.Enabled = False
FechaI = If(txtFechaI.Text.Trim = "", MinFecha, txtFechaI.Text.Trim.ToDate)
FechaF = If(txtFechaF.Text.Trim = "", MaxFecha, txtFechaF.Text.Trim.ToDate)
Dim GPS As New ClsGPS
Try
If Opcion = "Last" Then
If GPS.UltimaPosicionEquipoGet(GVRow.DataKey("CveDispositivo").ToEntero, MinFecha, MaxFecha) Then
If GPS.DtResultados.Rows.Count > 0 Then
Dim Coord As String = GPS.DtResultados.Rows(0)("Posicion").ToString.SQLToGmaps("POINT")
Fecha = GPS.DtResultados.Rows(0)("FechaTrama").ToString
Vehiculo = GPS.DtResultados.Rows(0)("Vehiculo").ToString
Info = InfoWindowCombustible($"Vehículo:{Vehiculo}", "-1", GVRow.DataKey("CveDispositivo").ToString.ToEntero, GPS.DtResultados.Rows(0), UsuarioActual.TienePermisoProceso(200))
If GPS.DtResultados.Rows(0)("SPD").ToString.ToDouble > 1 Then
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {GVRow.DataKey("CveDispositivo").ToString}")}green.png"
Else
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {GVRow.DataKey("CveDispositivo").ToString}")}.png"
End If
RegistraScript($"CreaMarcador({Coord},'{GVRow.DataKey("NombreVehiculo")}', '{Info}', '{Icono}');", GVRow.DataKey("CveDispositivo").ToString)
AddRowPosiciones(Vehiculo, Coord, GPS.DtResultados.Rows(0)("SPD").ToString.ToDouble, Fecha, GVRow.DataKey("CveDispositivo").ToEntero, GPS.DtResultados.Rows(0)("TiempoDetenido").ToString.ToDouble)
Else
Mensajes = Mensajes + $"{GVRow.DataKey("NoEconomico").ToString},"
End If
End If
If ChkTrazarGeocercas.Checked Then
MostrarGeoCercas()
End If
If ChkTrazarGeorutas.Checked Then
MostrarGeoRutas()
End If
If ChkTrazarPuntosInteres.Checked Then
MostrarPuntosDeInteres()
End If
ElseIf Opcion = "All" Then
If ChkTrazarGeocercas.Checked Then
MostrarGeoCercas()
End If
If ChkTrazarGeorutas.Checked Then
MostrarGeoRutas()
End If
If ChkTrazarPuntosInteres.Checked Then
MostrarPuntosDeInteres()
End If
If GPS.GetPosicionEquipo(GVRow.DataKey("CveDispositivo").ToEntero, FechaI, FechaF) Then
If GPS.DtResultados.Rows.Count > 0 Then
Dim StrScriptsMakers As New StringBuilder
Dim StrPolyPath As New StringBuilder
StrPolyPath.Append("[")
Dim POLYPATH As String = "["
TmpDT = GPS.DtResultados
Dim Contador = 0
Dim CveDispositivo = GVRow.DataKey("CveDispositivo").ToString.ToEntero
Dim RowDispositivo As DataRow = GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimero($"CveDispositivo = {CveDispositivo}")
Dim CordenadaAnterior As String = ""
For Each row As DataRow In TmpDT.Rows
Contador += 1
Dim Coord As String = SQLToGmaps(row("Posicion").ToString(), "POINT")
Dim Velocidad As Double = row("SPD").ToString.ToDouble
Fecha = row("FechaTrama").ToString
Vehiculo = row("Vehiculo").ToString
SBBody.Clear()
If Contador = TmpDT.Rows.Count Then
Info = InfoWindowCombustible($" Vehículo: {Vehiculo}", "-1", CveDispositivo, row, UsuarioActual.TienePermisoProceso(200))
If Velocidad > 1 Then
Icono = $"/Imagenes/{RowDispositivo("Icono")}green.png"
Else
Icono = $"/Imagenes/{RowDispositivo("Icono")}.png"
End If
POLYPATH = $"{POLYPATH}{Coord},"
StrPolyPath.AppendFormat("{0}]", Coord)
POLYPATH = $"{POLYPATH.Substring(0, POLYPATH.Length - 1)}]"
RegistraScript($"creaPolyline({StrPolyPath.ToString}, '{RowDispositivo("ColorTrazo")}', '{Info}', {Coord}, '{GVRow.DataKey("NombreVehiculo")}', '{Icono}',{CveDispositivo})", $"A{CveDispositivo}")
AddRowPosiciones(Vehiculo, Coord, Velocidad, Fecha, CveDispositivo, Evento:=row("Evento").ToString, TiempoDetenido:=row("TiempoMuerto").ToString.ToDouble, KMRecorridos:=row("KMRecorridos").ToString.ToDouble, Icono:=Icono)
Else
Info = InfoWindowCombustible($" Vehículo: {Vehiculo}", "-1", CveDispositivo, row, UsuarioActual.TienePermisoProceso(200))
If Velocidad > 1 Then
Icono = $"/Imagenes/{RowDispositivo("Icono")}green.png"
Else
Icono = $"/Imagenes/{RowDispositivo("Icono")}.png"
End If
StrPolyPath.AppendFormat("{0},", Coord)
POLYPATH = $"{POLYPATH}{Coord},"
If TmpDT.Rows.Count < 1500 Then
StrScriptsMakers.Append($"CreaMarcadorHistorico({Coord},'{GVRow.DataKey("NombreVehiculo")}', '{Info}', 0, '{Icono}');")
RegistraScript($"CreaMarcadorHistorico({Coord},'{GVRow.DataKey("NombreVehiculo")}', '{Info}', 0, '{Icono}');", Contador.ToString)
End If
AddRowPosiciones(Vehiculo, Coord, Velocidad, Fecha, CveDispositivo, Evento:=row("Evento").ToString, TiempoDetenido:=row("TiempoMuerto").ToString.ToDouble, Icono:=Icono)
End If
CordenadaAnterior = Coord
Next
RegistraScript($"PreparaDibujadoHistorico();PreparaDibujado(3);")
Else
Mensajes = Mensajes + $"{GVRow.DataKey("NoEconomico").ToString},"
End If
End If
ElseIf Opcion = "Watch" Then
SBBody.Clear()
If GPS.UltimaPosicionEquipoGet(GVRow.DataKey("CveDispositivo").ToEntero, MinFecha, MaxFecha) Then
If GPS.DtResultados.Rows.Count > 0 Then
Dim Coord As String = SQLToGmaps(GPS.DtResultados.Rows(0)("Posicion").ToString, "POINT")
Fecha = GPS.DtResultados.Rows(0)("FechaTrama").ToString
Vehiculo = GPS.DtResultados.Rows(0)("Vehiculo").ToString
Info = InfoWindowCombustible($" Vehículo: {Vehiculo}", "-1", GVRow.DataKey("CveDispositivo").ToString.ToEntero, GPS.DtResultados.Rows(0), UsuarioActual.TienePermisoProceso(200))
Dim Diferencia As Long = DateDiff(DateInterval.Minute, Fecha.ToDateTime(), UsuarioActual.FechaActualCliente)
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 GPS.DtResultados.Rows(0)("SPD").ToString.ToDouble > 1 Then
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {GVRow.DataKey("CveDispositivo").ToString}")}green.png"
Else
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {GVRow.DataKey("CveDispositivo").ToString}")}.png"
End If
End If
If chkTrazarLinea.Checked Then
TrazarLineaContinuo = True
CreaDTCoordenadas()
AddRowCoordenadasContinuas(Coord, GVRow.DataKey("CveDispositivo").ToEntero)
End If
RegistraScript($"CreaMarcador({Coord},'{GVRow.DataKey("NombreVehiculo")}', '{Info}', '{Icono}');", GVRow.DataKey("CveDispositivo").ToString)
AddRowPosiciones(Vehiculo, Coord, GPS.DtResultados.Rows(0)("SPD").ToString.ToDouble, Fecha, GVRow.DataKey("CveDispositivo").ToEntero, GPS.DtResultados(0)("TiempoDetenido").ToString.ToDouble)
Else
Mensajes = Mensajes + $"{GVRow.DataKey("NoEconomico").ToString},"
End If
End If
TimmerRefresh.Enabled = True
ElseIf Opcion = "Idle" Then
Dim StrAlert As New StringBuilder
If GPS.GetTiempoMuerto(GVRow.DataKey("CveDispositivo").ToEntero, txtFechaI.Text.ToDateTime, txtFechaF.Text.ToDateTime, TxtMinutos.Text.ToEntero) AndAlso GPS.DtResultados.Rows.Count > 0 Then
TmpDT = GPS.DtResultados
For Each row As DataRow In TmpDT.Rows
Dim Coord As String = SQLToGmaps(row("Posicion").ToString, "POINT")
Fecha = row("FechaTrama").ToString
Vehiculo = row("Vehiculo").ToString
Info = InfoWindowCombustible($" Vehículo: {Vehiculo}", $"<tr><td> Tiempo Muerto: Mayor a {TxtMinutos.Text} minutos</td></tr>", GVRow.DataKey("CveDispositivo").ToString.ToEntero, row, UsuarioActual.TienePermisoProceso(200))
RegistraScript($"CreaMarcador({Coord},'{GVRow.DataKey("NombreVehiculo")}', '{Info}');", $"{GVRow.DataKey("CveDispositivo").ToString}{row("CvePosicion").ToString}")
AddRowPosiciones(Vehiculo, Coord, "0".ToDouble, Fecha, GVRow.DataKey("CveDispositivo").ToEntero, row("Tiempo").ToString.ToDouble)
Next
Else
Mensajes = Mensajes + $"{GVRow.DataKey("NoEconomico").ToString},"
End If
ElseIf Opcion = "Eventos" Then
Dim Eventos As String = ""
For Each GROW As GridViewRow In GvEventos.Rows
If GROW.FCCheckBox("chkEv").Checked Then
If GPS.EventosPosicionGet(GVRow.DataKey("CveDispositivo").ToEntero, GROW.DataKey("CveEvento").ToEntero, txtFechaI.Text.ToDateTime, txtFechaF.Text.ToDateTime) Then
If GPS.DtResultados.Rows.Count > 0 Then
Dim Coord As String
For Each row As DataRow In GPS.DtResultados.Rows
Vehiculo = row("Vehiculo").ToString
Fecha = row("FechaTrama").ToString
Coord = SQLToGmaps(row("Posicion").ToString, "POINT")
Icono = If(row("Imagen").ToString = "", "/Imagenes/rsz_11rsz_car.png", $"/Imagenes/{row("Imagen").ToString}")
Info = InfoWindowCombustible(row("Evento").ToString, $"<tr><td><a target=\'_blank\' href=\'/GPS/Vehiculos.aspx?CveDispositivo={GVRow.DataKey("CveDispositivo").ToString}\'>Nombre Vehículo: {GVRow.DataKey("NombreVehiculo").ToString}</a></td></tr>", GVRow.DataKey("CveDispositivo").ToString.ToEntero, row, UsuarioActual.TienePermisoProceso(200))
RegistraScript($"CreaMarcador({Coord},'{GVRow.DataKey("NombreVehiculo")}', '{Info}', '{Icono}');", $"{GVRow.DataKey("CveDispositivo").ToString}{row("CveDispositivoEvento").ToString}")
AddRowPosiciones(Vehiculo, Coord, row("SPD").ToString.ToDouble, Fecha, GVRow.DataKey("CveDispositivo").ToEntero)
Next
Else
Eventos = $"{Eventos} {GROW.DataKey("Evento").ToString},"
End If
End If
End If
Next
If Eventos <> "" Then
Alert($"El vehículo con serie: {GVRow.DataKey("SerieVehiculo").ToString}, no cuenta con los siguientes eventos seleccionados: {Eventos.Substring(0, Eventos.Length - 1)}", TipoMensaje.MsgAdvertencia)
End If
ElseIf Opcion = "Speed" Then
If GPS.GetExcesosVelocidad(GVRow.DataKey("CveDispositivo").ToEntero, txtFechaI.Text.ToDateTime, txtFechaF.Text.ToDateTime) Then
TmpDT = GPS.DtResultados
If GPS.DtResultados.Rows.Count > 0 Then
For Each row As DataRow In TmpDT.Rows
Dim Coord As String = SQLToGmaps(row("Posicion").ToString, "POINT")
Fecha = row("FechaTrama").ToString
Vehiculo = row("Vehiculo").ToString
Info = InfoWindowCombustible($"Exceso de velocidad: {row("SPD").ToString} KM/H", $"<tr><td><a target=\'_blank\' href=\'/GPS/Vehiculos.aspx?CveDispositivo={GVRow.DataKey("CveDispositivo").ToString}\'>Nombre Vehículo: {GVRow.DataKey("NombreVehiculo").ToString}</a></td></tr>", GVRow.DataKey("CveDispositivo").ToString.ToEntero, row, UsuarioActual.TienePermisoProceso(200))
RegistraScript($"CreaMarcador({Coord},'{GVRow.DataKey("NombreVehiculo")}', '{Info}', '/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {GVRow.DataKey("CveDispositivo").ToString}")}green.png');", $"{GVRow.DataKey("CveDispositivo").ToString}{row("CveTrama").ToString}")
AddRowPosiciones(Vehiculo, Coord, row("SPD").ToString.ToDouble, Fecha, GVRow.DataKey("CveDispositivo").ToEntero)
Next
Else
Mensajes = Mensajes + $"{GVRow.DataKey("NoEconomico").ToString},"
End If
End If
ElseIf Opcion = "Ralenti" Then
If GPS.GetRalenti(GVRow.DataKey("CveDispositivo").ToEntero, txtFechaI.Text.ToDateTime, txtFechaF.Text.ToDateTime) Then
TmpDT = GPS.DtResultados.FiltraParametros("TiempoDetenido > 0")
Dim count As Integer = 0
If TmpDT.Rows.Count > 0 Then
For Each row As DataRow In TmpDT.Rows
Dim Coord As String = SQLToGmaps(row("Posicion").ToString, "POINT")
Vehiculo = row("Vehiculo").ToString
Fecha = row("FechaTrama").ToString
Info = InfoWindowCombustible($"Ralentí", $"<tr><td><a target=\'_blank\' href=\'/GPS/Vehiculos.aspx?CveDispositivo={GVRow.DataKey("CveDispositivo").ToString}\'>Nombre Vehículo: {Vehiculo}</a></td></tr>", GVRow.DataKey("CveDispositivo").ToString.ToEntero, row, UsuarioActual.TienePermisoProceso(200))
RegistraScript($"CreaMarcador({Coord},'{GVRow.DataKey("NombreVehiculo")}', '{Info}', '/Imagenes/ralenti.png');", $"{GVRow.DataKey("CveDispositivo").ToString}{row("CveDispositivoEvento").ToString}")
AddRowPosiciones(Vehiculo, Coord, "0".ToDouble, Fecha, GVRow.DataKey("CveDispositivo").ToEntero, row("TiempoDetenido").ToString.ToDouble)
count += 1
Next
Else
Mensajes = Mensajes + $"{GVRow.DataKey("NoEconomico").ToString},"
End If
End If
End If
Catch ex As Exception
OnError("Ocurrió un error al rastrear equipo", ex)
End Try
GPS.Dispose()
UpFiltros.Update()
End Sub
Private Sub RastrearEquipoNew(Equipos As String, Opcion As String)
Dim LastCoord As String = ""
Dim TmpDT As New DataTable
Dim Info = ""
Dim Direccion = ""
Dim SBBody As New StringBuilder
Dim Icono As String = "/Imagenes/rsz_11rsz_car.png"
Dim Fecha, Vehiculo As String
DivSeguimiento.Visible = False
TimmerRefresh.Enabled = False
FechaI = If(txtFechaI.Text.Trim = "", MinFecha, txtFechaI.Text.Trim.ToDate)
FechaF = If(txtFechaF.Text.Trim = "", MaxFecha, txtFechaF.Text.Trim.ToDate)
RegistraScript("DeletemarkersParadas();DeletemarkersGeoRastreo();DeleteGeocercas();$('#LnkMostarGeocercas').css('display', 'none');")
Dim GPS As New ClsGPS
Try
If Opcion = "Last" Then
If GPS.UltimaPosicionEquipoGet(Equipos, UsuarioActual.CveCliente) Then
If GPS.DtResultados.Rows.Count > 0 Then
For Each row As DataRow In GPS.DtResultados.Rows
Dim Coord As String = row("Posicion").ToString.SQLToGmaps("POINT")
Fecha = row("FechaTrama").ToString
Vehiculo = row("Vehiculo").ToString
Info = InfoWindowCombustible($"Vehículo:{Vehiculo}", "-1", row("CveDispositivo").ToString.ToEntero, row, UsuarioActual.TienePermisoProceso(200))
If row("SPD").ToString.ToDouble > 1 Then
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {row("CveDispositivo").ToString}")}green.png"
Else
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {row("CveDispositivo").ToString}")}.png"
End If
RegistraScript($"CreaMarcador({Coord},'{row("NombreVehiculo")}', '{Info}', '{Icono}');", row("CveDispositivo").ToString)
AddRowPosiciones(Vehiculo, Coord, row("SPD").ToString.ToDouble, Fecha, row("CveDispositivo").ToString.ToEntero, row("TiempoDetenido").ToString.ToDouble)
Next
If ChkTrazarGeocercas.Checked Then
MostrarGeoCercas()
End If
If ChkTrazarGeorutas.Checked Then
MostrarGeoRutas()
End If
If ChkTrazarPuntosInteres.Checked Then
MostrarPuntosDeInteres()
End If
Else
Alert($"No se encontraron resultados")
End If
End If
ElseIf Opcion = "Watch" Then
DivSeguimiento.Visible = True
SBBody.Clear()
If GPS.UltimaPosicionEquipoGet(Equipos, UsuarioActual.CveCliente) Then
If GPS.DtResultados.Rows.Count > 0 Then
For Each row As DataRow In GPS.DtResultados.Rows
Dim CveDispositivo As Integer = row("CveDispositivo").ToString.ToEntero
Dim Coord As String = SQLToGmaps(row("Posicion").ToString, "POINT")
Dim Velocidad = row("SPD").ToString.ToDouble
Fecha = row("FechaTrama").ToString
Vehiculo = row("Vehiculo").ToString
Info = InfoWindowCombustible($" Vehículo: {Vehiculo}", "-1", CveDispositivo, row, UsuarioActual.TienePermisoProceso(200))
Dim IconoVehiculo = GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {CveDispositivo}")
Dim Diferencia As Long = DateDiff(DateInterval.Minute, Fecha.ToDateTime(), UsuarioActual.FechaActualCliente)
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 Velocidad > 1 Then
Icono = $"/Imagenes/{IconoVehiculo}green.png"
Else
Icono = $"/Imagenes/{IconoVehiculo}.png"
End If
End If
If chkTrazarLinea.Checked Then
TrazarLineaContinuo = True
CreaDTCoordenadas()
AddRowCoordenadasContinuas(Coord, CveDispositivo)
End If
RegistraScript($"CreaMarcador({Coord},'{row("NombreVehiculo")}', '{Info}', '{Icono}');", CveDispositivo.ToString)
AddRowPosiciones(Vehiculo, Coord, row("SPD").ToString.ToDouble, Fecha, row("CveDispositivo").ToString.ToEntero, row("TiempoDetenido").ToString.ToDouble)
Next
If ChkTrazarGeocercas.Checked Then
MostrarGeoCercas()
End If
If ChkTrazarGeorutas.Checked Then
MostrarGeoRutas()
End If
If ChkTrazarPuntosInteres.Checked Then
MostrarPuntosDeInteres()
End If
Else
Alert($"No se encontraron resultados", TipoMensaje.MsgAdvertencia)
End If
End If
TimmerRefresh.Enabled = True
ElseIf Opcion = "TPS" Then
SBBody.Clear()
If GPS.UltimaPosicionPasajerosGet(Equipos, UsuarioActual.CveCliente) Then
If GPS.DtResultados.Rows.Count > 0 Then
Dim DtParadas As DataTable = Nothing
Dim ObjGPSGeo As New ClsGPS
If ObjGPSGeo.GetReferenciaDetalle(-1, -1, -1, UsuarioActual.CveCliente) Then
DtParadas = ObjGPSGeo.DtResultados.FiltraParametros("EsParada = True AND Estatus = 1")
End If
ObjGPSGeo.Dispose()
For Each row As DataRow In GPS.DtResultados.Rows
Dim CveDispositivo = row("CveDispositivo").ToString.ToEntero
Dim Coord As String = SQLToGmaps(row("Posicion").ToString, "POINT")
Dim Velocidad As Double = row("SPD").ToString.ToDouble
Fecha = row("FechaTrama").ToString
Vehiculo = row("Vehiculo").ToString
Info = InfoWindowCombustible($" Vehículo: {Vehiculo}", $" &nbsp;No. Pasajeros: {row("Pasajeros").ToString}", CveDispositivo, row, UsuarioActual.TienePermisoProceso(200))
Dim Diferencia As Long = DateDiff(DateInterval.Minute, Fecha.ToDateTime(), UsuarioActual.FechaActualCliente)
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 Velocidad > 1 Then
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {CveDispositivo}")}green.png"
Else
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {CveDispositivo}")}.png"
End If
End If
If chkTrazarLinea.Checked Then
TrazarLineaContinuo = True
CreaDTCoordenadas()
AddRowCoordenadasContinuas(Coord, CveDispositivo)
End If
RegistraScript($"CreaMarcador({Coord},'{row("NombreVehiculo")}', '{Info}', '{Icono}');", CveDispositivo.ToString)
AddRowPosiciones(Vehiculo, Coord, Velocidad, Fecha, CveDispositivo, row("TiempoDetenido").ToString.ToDouble, Evento:=row("Pasajeros").ToString)
'SI TIENE PARADAS LAS MOSTRAMOS
If DtParadas IsNot Nothing Then
Dim DtParadasDispositivo = DtParadas.FiltraParametros($"CveDispositivo = {CveDispositivo}", "", {"Color", "GeoReferencia", "Coordenadas"})
Dim SbJS As New StringBuilder
SbJS.Append("setTimeout(function(){ DeletemarkersParadas(); ")
For Each Dr As DataRow In DtParadasDispositivo.Rows
Dim CoordsParada = SQLToGmapsJArray(Dr("Coordenadas").ToString, "POLYGON")
SbJS.AppendFormat(" creaPoligonoParada({0},'{1}','{2}'); ", CoordsParada.ToString, Dr("Color").ToString, Dr("GeoReferencia").ToString)
Next
SbJS.Append(" },2000);")
RegistraScript(SbJS.ToString)
End If
Next
TimmerRefresh.Enabled = True
Else
Alert($"No se encontraron resultados", TipoMensaje.MsgAdvertencia)
End If
End If
End If
Catch ex As Exception
OnError("Ocurrió un error al rastrear un equipo", ex)
End Try
GPS.Dispose()
End Sub
Private Sub CargaGeocercas(Dispositivos As String)
Try
Dim DtGeocercas As DataTable = Nothing
Dim ObjGPSGeo As New ClsGPS
If ObjGPSGeo.GetReferenciaDetalle(-1, -1, -1, UsuarioActual.CveCliente) Then
DtGeocercas = ObjGPSGeo.DtResultados.FiltraParametros("EsParada = False AND Tipo='Geocerca' AND Estatus = 1")
End If
ObjGPSGeo.Dispose()
'SI TIENE GEOREFERENCIAS LAS MOSTRAMOS
If DtGeocercas IsNot Nothing Then
Dim DtParadasDispositivo = DtGeocercas.FiltraParametros($"CveDispositivo IN({Dispositivos})", DistinctColumns:={"GeoReferencia", "Coordenadas", "Color"})
GvGeoCercas.DataSource = DtParadasDispositivo
GvGeoCercas.DataBind()
End If
Catch ex As Exception
OnError("Ocurrió un error al consultar las geocercas", ex)
End Try
UpGeoCercas.Update()
End Sub
Private Sub MostrarGeoCercas()
Dim count = 0
Try
RegistraScript($"NuevaConsultaGeoCercas();", count.ToString())
For Each GvRow As GridViewRow In GvGeoCercas.Rows
If GvRow.RowType = DataControlRowType.DataRow Then
If GvRow.FCCheckBox("ChkGeo").Checked Then
count += 1
RegistraScript(String.Format("creaPoligonoGeocerca({0},'{1}','{2}'); ", SQLToGmapsJArray(GvRow.DataKey("Coordenadas"), "POLYGON"), GvRow.DataKey("Color"), GvRow.DataKey("GeoReferencia")), count.ToString())
End If
End If
Next
RegistraScript("VerGeocercas();", (count + 1).ToString())
Catch ex As Exception
OnError("Ocurrió un error al consultar las geocercas", ex)
End Try
End Sub
Private Sub MostrarGeoRutas()
Dim count = 0
RegistraScript($"NuevaConsultaGeoRutas();", count.ToString())
For Each GvRow As GridViewRow In GvGeorutas.Rows
If GvRow.RowType = DataControlRowType.DataRow Then
If GvRow.FCCheckBox("ChkRutas").Checked Then
count += 1
Dim Coord As String = SQLToGmaps(GvRow.DataKey("Coordenadas").ToString, "LINESTRING")
RegistraScript($"creaPolylineRuta({Coord}, '{GvRow.DataKey("Color").ToString}', '{GvRow.DataKey("GeoReferencia")}')", count.ToString())
End If
End If
Next
End Sub
Private Sub MostrarPuntosDeInteres()
RegistraScript($"NuevaConsultaPI();", "0")
For Each GvRow As GridViewRow In GVPuntosInteres.Rows
If GvRow.RowType = DataControlRowType.DataRow Then
If GvRow.FCCheckBox("ChkPI").Checked Then
Dim coords = SQLToGmaps(GvRow.DataKey("Punto"), "POINT")
RegistraScript($"CreaMarcadorPI({coords}, '{GvRow.DataKey("PuntoDeInteres").ToString}')", GvRow.RowIndex.ToString())
End If
End If
Next
End Sub
Protected Sub TimmerRefresh_Tick(sender As Object, e As EventArgs)
DtPosiciones.Rows.Clear()
Dim Info = ""
Dim Icono = ""
Dim Fecha As String
Dim SBBody As New StringBuilder
Dim SB = New StringBuilder()
RegistraScript("DeleteMarkers();")
Dim Vehiculo As String
For Each row As GridViewRow In GvDispositivos.Rows
If row.FCCheckBox("chkDis").Checked Then
SB.Append($"{row.DataKey("CveDispositivo")};")
End If
Next
Dim GPS As New ClsGPS
Try
If Opcion = "TPS" Then
SBBody.Clear()
If GPS.UltimaPosicionPasajerosGet(SB.ToString, UsuarioActual.CveCliente) Then
If GPS.DtResultados.Rows.Count > 0 Then
For Each row As DataRow In GPS.DtResultados.Rows
Dim Coord As String = SQLToGmaps(row("Posicion").ToString, "POINT")
Fecha = row("FechaTrama").ToString
Vehiculo = row("Vehiculo").ToString
Info = InfoWindowCombustible($" Vehículo: {Vehiculo}", $" &nbsp;No. Pasajeros: {row("Pasajeros").ToString}", row("CveDispositivo").ToString.ToEntero, row, UsuarioActual.TienePermisoProceso(200))
Dim Diferencia As Long = DateDiff(DateInterval.Minute, Fecha.ToDateTime(), UsuarioActual.FechaActualCliente)
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 = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {row("CveDispositivo").ToString}")}green.png"
Else
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {row("CveDispositivo").ToString}")}.png"
End If
End If
If chkTrazarLinea.Checked Then
TrazarLineaContinuo = True
CreaDTCoordenadas()
AddRowCoordenadasContinuas(Coord, row("CveDispositivo").ToString.ToEntero)
End If
RegistraScript($"CreaMarcadorWatch({Coord},'{row("NombreVehiculo")}', '{Info}', '{Icono}');", row("CveDispositivo").ToString)
AddRowPosiciones(Vehiculo, Coord, row("SPD").ToString.ToDouble, Fecha, row("CveDispositivo").ToString.ToEntero, row("TiempoDetenido").ToString.ToDouble, Evento:=row("Pasajeros").ToString)
Next
TimmerRefresh.Enabled = True
Else
Alert($"No se encontraron resultados", TipoMensaje.MsgAdvertencia)
End If
End If
Else
If GPS.UltimaPosicionEquipoGet(SB.ToString, UsuarioActual.CveCliente) Then
If GPS.DtResultados.Rows.Count > 0 Then
For Each row As DataRow In GPS.DtResultados.Rows
Dim Coord As String = SQLToGmaps(row("Posicion").ToString, "POINT")
Vehiculo = row("Vehiculo").ToString
Info = InfoWindowCombustible($" Vehículo: {Vehiculo}", "-1", row("CveDispositivo").ToString.ToEntero, row, UsuarioActual.TienePermisoProceso(200))
Fecha = row("FechaTrama").ToString
Dim Diferencia As Long = DateDiff(DateInterval.Minute, Fecha.ToDateTime(), UsuarioActual.FechaActualCliente)
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 = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {row("CveDispositivo").ToString}")}green.png"
Else
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {row("CveDispositivo").ToString}")}.png"
End If
End If
If TrazarLineaContinuo Then
AddRowCoordenadasContinuas(Coord, row("CveDispositivo").ToString.ToEntero)
Dim POLYPATH As String = "["
For Each RCC As DataRow In DtCoordenadasContinuas.FiltraParametros($"CveDispositivo = {row("CveDispositivo").ToString.ToEntero}", DistinctColumns:={"CveDispositivo", "Coord"}).Rows
POLYPATH = $"{POLYPATH}{RCC("Coord").ToString},"
Next
POLYPATH = $"{POLYPATH.Substring(0, POLYPATH.Length - 1)}]"
RegistraScript($"creaPolyline({POLYPATH}, '{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("ColorTrazo", $"CveDispositivo = {row("CveDispositivo").ToString.ToEntero}")}', '{Info}', {Coord}, '{row("NombreVehiculo")}', '{Icono}',{row("CveDispositivo").ToString.ToEntero}, 1)", $"{row("CveDispositivo").ToString}{DtCoordenadasContinuas.Rows.Count}")
Else
RegistraScript($"CreaMarcadorWatch({Coord},'{row("NombreVehiculo")}', '{Info}', '{Icono}');", row("CveDispositivo").ToString)
End If
AddRowPosiciones(Vehiculo, Coord, row("SPD").ToString.ToDouble, row("FechaTrama").ToString, row("CveDispositivo").ToString.ToEntero, row("TiempoDetenido").ToString.ToDouble)
Next
End If
End If
End If
Catch ex As Exception
OnError("Ocurrió un error al rastrear un equipo", ex)
End Try
GPS.Dispose()
If DtPosiciones IsNot Nothing Then
GvBarra.DataSource = DtPosiciones
GvBarra.DataBind()
End If
If GvBarra.HeaderRow IsNot Nothing Then
If Opcion = "Last" OrElse Opcion = "Watch" OrElse Opcion = "Idle" OrElse Opcion = "All" Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "")
GvBarra.HeaderRow.Cells(4).Style.Add("display", "none !important")
ElseIf Opcion = "TPS" Then
GvBarra.HeaderRow.Cells(4).Text = "No. Pasajeros"
GvBarra.HeaderRow.Cells(4).Style.Add("display", "")
GvBarra.HeaderRow.Cells(3).Style.Add("display", "")
ElseIf Opcion <> "Eventos" Then
GvBarra.HeaderRow.Cells(3).Style.Add("display", "none !important")
GvBarra.HeaderRow.Cells(4).Style.Add("display", "none !important")
End If
End If
UPGV.Update()
Dim SbJS As New StringBuilder
SbJS.Append($"setTimeout(function(){{ $('#C_GvBarra').DataTable().search('{HdnTextFilter.Value}').draw(); ")
If ChkSeguimiento.Checked Then
If HdnIndexGvBarra.Value.ToEntero >= 0 Then
SbJS.Append($"$('#row{HdnIndexGvBarra.Value}').click();")
'If Not String.IsNullOrEmpty(JSCargaSeleccion) Then
'End If
End If
End If
SbJS.Append("},2000);")
RegistraScript(SbJS.ToString)
'RegistraScript("CargaPickers();", "ADP")
End Sub
#Region "Herramientas - GPS"
Protected Sub BtnCargaComandos_Click(sender As Object, e As EventArgs) Handles BtnCargaComandos.Click
CargaComandos()
End Sub
Private Sub CargaComandos()
Dim ObjGps As New ClsGPS
If ObjGps.GetComandosModeloDispositivoUsuarios(HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, 1) Then
GvComandos.DataSource = ObjGps.DtResultados
End If
ObjGps.Dispose()
GvComandos.DataBind()
UpBodyTipoEquipo.Update()
'Dim ObjGps As New ClsGPS
'If ObjGps.GetComandosModeloDispositivo(HdnCveDipositivo.Value.ToEntero) AndAlso ObjGps.DtResultados.Rows.Count > 0 Then
' GvComandos.DataSource = ObjGps.DtResultados.FiltraParametros("CveComando In (6, 7, 32, 36, 8, 9)")
'End If
'ObjGps.Dispose()
'GvComandos.DataBind()
'UpBodyTipoEquipo.Update()
End Sub
Private Sub GvComandos_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GvComandos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
'Select Case e.Row.DBCampo("CveComando").ToEntero
' Case 6
' e.Row.Cells(1).Text = "Apagar Motor"
' Case 7
' e.Row.Cells(1).Text = "Encender Motor"
' Case 32
' e.Row.Cells(1).Text = "Reiniciar Dispositivo"
' Case 36
' e.Row.Cells(1).Text = "Telefono de Pánico"
' Case 8
' e.Row.Cells(1).Text = "Abrir Compuerta"
' Case 9
' e.Row.Cells(1).Text = "Cerrar Compuerta"
'End Select
If e.Row.DataKey("RequiereValor").ToEntero = 1 Then
e.Row.FCTextBox("TxtValor").Visible = True
End If
End If
End Sub
Private Sub GvComandos_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles GvComandos.RowCommand
If (e.CommandName = "EnviarComando") Then
Dim ObjHerramientas As New ClsGPSHerramientas
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = GvComandos.Rows(index)
ObjHerramientas.EjecutarComandoGPRS(row.DataKey("CveComando").ToEntero, HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, row.FCTextBox("TxtValor").Text)
ObjHerramientas.Dispose()
End If
End Sub
'Private Sub BtnApagarMotor_Click(sender As Object, e As EventArgs) Handles BtnApagarMotor.Click
' 'Comando 6
' Dim ObjGPSHerramientas As New ClsGPSHerramientas
' ObjGPSHerramientas.EjecutarComandoGPRS(6, HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, "")
' ObjGPSHerramientas.Dispose()
'End Sub
'Private Sub BtnEncenderMotor_Click(sender As Object, e As EventArgs) Handles BtnEncenderMotor.Click
' 'Comando 7
' Dim ObjGPSHerramientas As New ClsGPSHerramientas
' ObjGPSHerramientas.EjecutarComandoGPRS(7, HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, "")
' ObjGPSHerramientas.Dispose()
'End Sub
'Private Sub BtnReinicio_Click(sender As Object, e As EventArgs) Handles BtnReinicio.Click
' 'Comando 32
' Dim ObjGPSHerramientas As New ClsGPSHerramientas
' ObjGPSHerramientas.EjecutarComandoGPRS(32, HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, "")
' ObjGPSHerramientas.Dispose()
'End Sub
'Private Sub BtnTelefonoPanico_Click(sender As Object, e As EventArgs) Handles BtnTelefonoPanico.Click
' 'Comando 36
' Dim ObjGPSHerramientas As New ClsGPSHerramientas
' ObjGPSHerramientas.EjecutarComandoGPRS(36, HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, TxtTelefonoPanico.Text.Trim)
' ObjGPSHerramientas.Dispose()
'End Sub
'Private Sub BtnProbarEncendido_Click(sender As Object, e As EventArgs) Handles BtnProbarEncendido.Click
' 'Comando 8 'Abrir Compuerta
' Dim ObjGPSHerramientas As New ClsGPSHerramientas
' ObjGPSHerramientas.EjecutarComandoGPRS(8, HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, "")
' ObjGPSHerramientas.Dispose()
'End Subah s
'Private Sub BtnInfoDispositivo_Click(sender As Object, e As EventArgs) Handles BtnInfoDispositivo.Click
' 'Comando 9 'Cerrar Compuerta
' Dim ObjGPSHerramientas As New ClsGPSHerramientas
' ObjGPSHerramientas.EjecutarComandoGPRS(9, HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, "")
' ObjGPSHerramientas.Dispose()
'End Sub
'Private Sub BtnAhorroBateria_Click(sender As Object, e As EventArgs) Handles BtnAhorroBateria.Click
' 'Comando 40
' Dim ObjGPSHerramientas As New ClsGPSHerramientas
' ObjGPSHerramientas.EjecutarComandoGPRS(40, HdnCveDipositivo.Value.ToEntero, UsuarioActual.CveUsuario, DdlTipoBateria.SelectedValue)
' ObjGPSHerramientas.Dispose()
'End Sub
#End Region
#Region "DATA TABLES"
Private Sub CreaDTPosiciones()
DtPosiciones = Nothing
Dim dt As New DataTable
dt.Columns.Add("CveDispositivo", Type.GetType("System.Int32"))
dt.Columns.Add("Vehiculo", Type.GetType("System.String"))
dt.Columns.Add("Fecha", Type.GetType("System.String"))
dt.Columns.Add("Evento", Type.GetType("System.String"))
dt.Columns.Add("TiempoDetenido", Type.GetType("System.Double"))
dt.Columns.Add("Velocidad", Type.GetType("System.Double"))
dt.Columns.Add("Posicion", Type.GetType("System.String"))
dt.Columns.Add("KMRecorridos", Type.GetType("System.Double"))
dt.Columns.Add("Icono", Type.GetType("System.String"))
ViewState("DtPosiciones") = dt
End Sub
Private Sub AddRowPosiciones(Vehiculo As String, Posicion As String, Velocidad As Double, Fecha As String, CveDispositivo As Integer, Optional TiempoDetenido As Double = 0, Optional Evento As String = "", Optional KMRecorridos As Double = 0, Optional Icono As String = "/Imagenes/rsz_11rsz_car.png")
Dim dr As DataRow = DtPosiciones.NewRow()
dr("Vehiculo") = Vehiculo
dr("Fecha") = Fecha
dr("TiempoDetenido") = TiempoDetenido
dr("Velocidad") = Velocidad
dr("Posicion") = Posicion
dr("CveDispositivo") = CveDispositivo
dr("Evento") = Evento
dr("KMRecorridos") = KMRecorridos
dr("Icono") = Icono
DtPosiciones.Rows.Add(dr)
End Sub
Private Sub CreaDTCoordenadas()
Dim dt As New DataTable
dt.Columns.Add("CveDispositivo", Type.GetType("System.Int32"))
dt.Columns.Add("Coord", Type.GetType("System.String"))
DtCoordenadasContinuas = dt
End Sub
Private Sub AddRowCoordenadasContinuas(Coord As String, CveDispositivo As Integer)
Dim dr As DataRow = DtCoordenadasContinuas.NewRow()
dr("CveDispositivo") = CveDispositivo
dr("Coord") = Coord
DtCoordenadasContinuas.Rows.Add(dr)
End Sub
#End Region
#Region "Carga Fechas Predeterminadas"
'Protected Sub BtnUltimas2_Click(sender As Object, e As EventArgs) Handles BtnUltimas2.Click
' CargaFechasPredeterminadas("2")
'End Sub
'Protected Sub BtnUltimas8_Click(sender As Object, e As EventArgs) Handles BtnUltimas8.Click
' CargaFechasPredeterminadas("8")
'End Sub
'Protected Sub BtnHoy_Click(sender As Object, e As EventArgs) Handles BtnHoy.Click
' CargaFechasPredeterminadas("24")
'End Sub
'Protected Sub BtnAyer_Click(sender As Object, e As EventArgs) Handles BtnAyer.Click
' CargaFechasPredeterminadas("48")
'End Sub
'Protected Sub BtnSemana_Click(sender As Object, e As EventArgs) Handles BtnSemana.Click
' CargaFechasPredeterminadas("Week")
'End Sub
'Protected Sub BtnMes_Click(sender As Object, e As EventArgs) Handles BtnMes.Click
' CargaFechasPredeterminadas("Month")
'End Sub
<Web.Services.WebMethod()> <Script.Services.ScriptMethodAttribute()>
Public Shared Function WsCalculaFechas(ByVal Opcion As System.String) As System.String
Dim StrFecha As String = "{}"
If Opcion = "2" Then
Dim JsonFecha As New JObject(
New JProperty("FechaI", DateTime.Now.AddHours(-2).ToString("dd/MM/yyyy HH:mm")),
New JProperty("FechaF", DateTime.Now.ToString("dd/MM/yyyy HH:mm"))
)
StrFecha = JsonFecha.ToString
ElseIf Opcion = "8" Then
Dim JsonFecha As New JObject(
New JProperty("FechaI", DateTime.Now.AddHours(-8).ToString("dd/MM/yyyy HH:mm")),
New JProperty("FechaF", DateTime.Now.ToString("dd/MM/yyyy HH:mm"))
)
StrFecha = JsonFecha.ToString
ElseIf Opcion = "24" Then
Dim JsonFecha As New JObject(
New JProperty("FechaI", $"{DateTime.Now.ToString("dd/MM/yyyy")} 0:00"),
New JProperty("FechaF", $"{DateTime.Now.ToString("dd/MM/yyyy")} 23:59")
)
StrFecha = JsonFecha.ToString
ElseIf Opcion = "48" Then
Dim JsonFecha As New JObject(
New JProperty("FechaI", $"{DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy")} 0:00"),
New JProperty("FechaF", $"{DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy")} 23:59")
)
StrFecha = JsonFecha.ToString
ElseIf Opcion = "Week" Then
Dim JsonFecha As New JObject(
New JProperty("FechaI", $"{DateTime.Now.AddDays(-7).ToString("dd/MM/yyyy")} 0:00"),
New JProperty("FechaF", DateTime.Now.ToString("dd/MM/yyyy HH:mm"))
)
StrFecha = JsonFecha.ToString
ElseIf Opcion = "Month" Then
Dim JsonFecha As New JObject(
New JProperty("FechaI", $"{New DateTime(Now.Year, Now.Month, 1).ToString("dd/MM/yyyy")} 0:00"),
New JProperty("FechaF", DateTime.Now.ToString("dd/MM/yyyy HH:mm"))
)
StrFecha = JsonFecha.ToString
End If
Return StrFecha
End Function
'Private Sub CargaFechasPredeterminadas(Opcion As String)
' If Opcion = "2" Then
' txtFechaI.Text = DateTime.Now.AddHours(-2).ToString("dd/MM/yyyy HH:mm")
' txtFechaF.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm")
' ElseIf Opcion = "8" Then
' txtFechaI.Text = DateTime.Now.AddHours(-8).ToString("dd/MM/yyyy HH:mm")
' txtFechaF.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm")
' ElseIf Opcion = "24" Then
' txtFechaI.Text = $"{DateTime.Now.ToString("dd/MM/yyyy")} 0:00"
' txtFechaF.Text = $"{DateTime.Now.ToString("dd/MM/yyyy")} 23:59"
' ElseIf Opcion = "48" Then
' txtFechaI.Text = $"{DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy")} 0:00"
' txtFechaF.Text = $"{DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy")} 23:59"
' ElseIf Opcion = "Week" Then
' txtFechaI.Text = $"{DateTime.Now.AddDays(-7).ToString("dd/MM/yyyy")} 0:00"
' txtFechaF.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm")
' ElseIf Opcion = "Month" Then
' txtFechaI.Text = $"{New DateTime(Now.Year, Now.Month, 1).ToString("dd/MM/yyyy")} 0:00"
' txtFechaF.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm")
' End If
' ' RegistraScript("CargaPickers();")
' upFechas.Update()
'End Sub
#End Region
#Region "Menu"
Protected Sub Btn_Click(sender As Object, e As EventArgs) Handles BtnLast.Click, BtnAll.Click, BtnWatch.Click, BtnRalenti.Click, BtnSpeed.Click, BtnIdle.Click, BtnEv.Click, LnkKM.Click, BtnPasajeros.Click
Dim Btn As LinkButton = CType(sender, LinkButton)
Opcion = Btn.CommandArgument
CargaOpcion(Opcion)
End Sub
Protected Sub CargaOpcion(opcion As String)
TimmerRefresh.Enabled = False
HdnOpcion.Value = opcion
dvTrazo.Visible = False
dvTrazoGeo.Visible = False
dvTrazoRutas.Visible = False
dvTrazoPI.Visible = False
chkTrazarLinea.Checked = False
ChkTrazarGeocercas.Checked = False
ChkTrazarGeorutas.Checked = False
ChkTrazarPuntosInteres.Checked = False
DvPaginacion.Visible = False
rowImpresionesKM.Visible = False
If opcion = "All" Then
dvFechas.Visible = True
txtFechaI.Text = ""
txtFechaF.Text = ""
dvDispositivos.Visible = True
dvTrazo.Visible = False
dvTrazoGeo.Visible = True
dvTrazoRutas.Visible = True
dvTrazoPI.Visible = True
ChkTrazarGeocercas.Visible = True
dvMinutos.Visible = False
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
BtnRastrear.ValidationGroup = "GrpFechas"
dvEventos.Visible = False
myModalLabel2.InnerHtml = "Rastreo Vehícular Histórico"
ElseIf opcion = "Eventos" Then
dvFechas.Visible = True
txtFechaI.Text = ""
dvDispositivos.Visible = True
txtFechaF.Text = ""
dvTrazo.Visible = False
dvTrazoGeo.Visible = False
dvTrazoRutas.Visible = False
dvTrazoPI.Visible = False
dvMinutos.Visible = False
BtnRastrear.ValidationGroup = "GrpFechas"
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
dvEventos.Visible = True
myModalLabel2.InnerHtml = "Rastreo Vehícular por Eventos"
ElseIf opcion = "Speed" Then
dvFechas.Visible = True
txtFechaI.Text = ""
txtFechaF.Text = ""
dvTrazo.Visible = False
dvTrazoGeo.Visible = False
dvTrazoRutas.Visible = False
dvTrazoPI.Visible = False
dvDispositivos.Visible = True
dvMinutos.Visible = False
GvDispositivos.DataSource = GlobalDTDispositivosUsuarios(UsuarioActual.CveCliente, UsuarioActual.CveUsuario).FiltraParametros("Estatus = 1 AND LimiteVelocidad = 1")
GvDispositivos.DataBind()
Filtrado = True
dvEventos.Visible = False
BtnRastrear.ValidationGroup = "GrpFechas"
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
myModalLabel2.InnerHtml = "Rastreo Vehícular de Exceso de velocidad"
ElseIf opcion = "Idle" Then
dvFechas.Visible = True
txtFechaI.Text = ""
txtFechaF.Text = ""
dvDispositivos.Visible = True
dvTrazo.Visible = False
dvTrazoGeo.Visible = False
dvTrazoRutas.Visible = False
dvTrazoPI.Visible = False
dvMinutos.Visible = True
dvEventos.Visible = False
BtnRastrear.ValidationGroup = "GrpFechas"
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
myModalLabel2.InnerHtml = "Rastreo Vehícular por Tiempo Muerto"
ElseIf opcion = "Ralenti" Then
dvFechas.Visible = True
txtFechaI.Text = ""
txtFechaF.Text = ""
dvDispositivos.Visible = True
dvTrazo.Visible = False
dvTrazoGeo.Visible = False
dvTrazoRutas.Visible = False
dvTrazoPI.Visible = False
dvMinutos.Visible = False
dvEventos.Visible = False
BtnRastrear.ValidationGroup = "GrpFechas"
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
myModalLabel2.InnerHtml = "Rastreo Vehícular por Ralentí"
ElseIf opcion = "Last" Then
dvFechas.Visible = False
dvDispositivos.Visible = True
dvTrazo.Visible = False
dvTrazoGeo.Visible = True
dvTrazoRutas.Visible = True
dvTrazoPI.Visible = True
dvMinutos.Visible = False
dvEventos.Visible = False
BtnRastrear.ValidationGroup = "xx"
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
myModalLabel2.InnerHtml = "Última Posición"
ElseIf opcion = "Watch" Then
dvFechas.Visible = False
dvMinutos.Visible = False
dvTrazo.Visible = True
dvTrazoGeo.Visible = True
dvTrazoRutas.Visible = True
dvTrazoPI.Visible = True
dvEventos.Visible = False
BtnRastrear.ValidationGroup = "xx"
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
myModalLabel2.InnerHtml = "Rastreo Continuo"
chkTrazarLinea.Visible = True
ChkTrazarGeocercas.Visible = True
ElseIf opcion = "KM" Then
dvFechas.Visible = True
dvDispositivos.Visible = False
dvMinutos.Visible = False
dvTrazo.Visible = False
dvTrazoGeo.Visible = False
dvTrazoRutas.Visible = False
dvTrazoPI.Visible = False
dvEventos.Visible = False
BtnRastrear.ValidationGroup = "xx"
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
myModalLabel2.InnerHtml = "Reporte de Kilometros Recorridos"
ElseIf opcion = "TPS" Then
dvFechas.Visible = False
dvDispositivos.Visible = True
dvMinutos.Visible = False
dvTrazo.Visible = False
dvTrazoGeo.Visible = False
dvTrazoRutas.Visible = False
dvTrazoPI.Visible = False
DivFechasGVBarra.Visible = False
GvDispositivos.DataSource = GlobalDTDispositivosUsuarios(UsuarioActual.CveCliente, UsuarioActual.CveUsuario).FiltraParametros("CveModelo = 17")
GvDispositivos.DataBind()
Filtrado = True
dvEventos.Visible = False
RegistraScript("$('#dvConsulta').modal();TerminaDibujado();")
myModalLabel2.InnerHtml = "Contador de pasajeros"
End If
If Not dvTrazoGeo.Visible Then
RegistraScript("$('#LnkMostarGeocercas').css('display', 'none');")
End If
If dvTrazoRutas.Visible Then
CargaGeoRutas()
Else
RegistraScript("$('#LnkMostarGeoRutas').css('display', 'none');")
End If
If dvTrazoPI.Visible Then
CargaPI()
Else
RegistraScript("$('#LnkMostarPI').css('display', 'none');")
End If
If opcion <> "Speed" AndAlso opcion <> "TPS" AndAlso Filtrado Then
CargaDispositivos()
Filtrado = False
End If
RegistraScript("$(""#h"").modal('hide');
$(""#ShowDiv3"").css(""line-height"", ""20px"");
open = false;
$(""#ShowDiv3"").html('<i class=""fa fa-angle-up"" aria-hidden=""True""></i>');", "HideDiv")
RegistraScript("$(""input[name^='ctl00$C$GvDispositivos']"").not(this).prop('checked', false);$('#C_GvDispositivos_chkSelectAll').click(function () { $(""input[name^='ctl00$C$GvDispositivos']"").not(this).prop('checked', this.checked); });", "chkGV")
UPConsulta.Update()
End Sub
#End Region
#Region "GVBarra"
Protected Sub GvBarra_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvBarra.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim RowID As String = $"row{e.Row.RowIndex}"
e.Row.Attributes("id") = RowID
Dim IndexGvBarra As Integer = If(String.IsNullOrEmpty(HdnIndexGvBarra.Value), -1, HdnIndexGvBarra.Value.ToEntero)
If Opcion <> "All" Then
If IndexGvBarra >= 0 Then
If e.Row.RowIndex = IndexGvBarra Then
JSCargaSeleccion = $"CargaDatosSeleccionados('{e.Row.RowIndex}', '{e.Row.DBCampo("CveDispositivo").ToString}', {e.Row.DBCampo("Posicion").ToString}, 0);CargaRecSeleccionados({e.Row.RowIndex});GetDireccionesGVClick({e.Row.DBCampo("Posicion").ToString}, {e.Row.RowIndex});"
End If
End If
RegistraScript($"GetDireccionesGV({e.Row.DBCampo("Posicion").ToString}, {e.Row.RowIndex}, 1);", $"{RowID}")
e.Row.Attributes.Add("onClick", $"CargaDatosSeleccionados('{e.Row.RowIndex}', '{e.Row.DBCampo("CveDispositivo").ToString}', {e.Row.DBCampo("Posicion").ToString}, 0);CargaRecSeleccionados({e.Row.RowIndex});GetDireccionesGVClick({e.Row.DBCampo("Posicion").ToString}, {e.Row.RowIndex});")
Else
Dim SBBody = New StringBuilder()
Dim Info As String = ""
Dim Icono As String
SBBody.Append($"<div>")
SBBody.Append($"<div><h5><a target=\'_blank\' href=\'/GPS/Vehiculos.aspx?CveDispositivo={e.Row.DBCampo("CveDispositivo")}\'><b>{e.Row.DBCampo("Vehiculo")}</b></a></h5></div>")
SBBody.Append($"<div><table>")
SBBody.Append($"<tr><td>Fecha : {e.Row.DBCampo("Fecha")} </td></tr>")
SBBody.Append($"<tr><td>Velocidad : {e.Row.DBCampo("Velocidad").ToString}</td></tr>")
If Opcion = "Watch" Then
Dim Diferencia As Long = DateDiff(DateInterval.Minute, e.Row.DBCampo("Fecha").ToDateTime(), UsuarioActual.FechaActualCliente)
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 e.Row.DBCampo("Velocidad").ToString.ToDouble > 1 Then
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {e.Row.DBCampo("CveDispositivo").ToString}")}green.png"
Else
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {e.Row.DBCampo("CveDispositivo").ToString}")}.png"
End If
End If
ElseIf Opcion = "All" Then
Icono = e.Row.DBCampo("Icono").ToString
Else
If e.Row.DBCampo("Velocidad").ToString.ToDouble > 1 Then
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {e.Row.DBCampo("CveDispositivo").ToString}")}green.png"
Else
Icono = $"/Imagenes/{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("Icono", $"CveDispositivo = {e.Row.DBCampo("CveDispositivo").ToString}")}.png"
End If
End If
SBBody.Append($"</table></div><div></div></div>")
Info = SBBody.ToString
e.Row.Attributes.Add("onClick", $"CargaDatosSeleccionados({e.Row.RowIndex}, '{e.Row.DBCampo("CveDispositivo").ToString}', {e.Row.DBCampo("Posicion").ToString}, 2); CreaMarcadorHistorico({e.Row.DBCampo("Posicion").ToString},'{e.Row.DBCampo("Vehiculo")}', '{Info}', 1, '{Icono}', {e.Row.RowIndex}); ")
If IndexGvBarra >= 0 Then
If e.Row.RowIndex = IndexGvBarra Then
JSCargaSeleccion = $"CargaDatosSeleccionados({e.Row.RowIndex}, '{e.Row.DBCampo("CveDispositivo").ToString}', {e.Row.DBCampo("Posicion").ToString}, 2); CreaMarcadorHistorico({e.Row.DBCampo("Posicion").ToString},'{e.Row.DBCampo("Vehiculo")}', '{Info}', 1, '{Icono}', {e.Row.RowIndex}); "
End If
End If
RegistraScript($"GetDireccionesGV({e.Row.DBCampo("Posicion").ToString}, {e.Row.RowIndex}, 0);", $"{RowID}")
End If
If Opcion = "Watch" OrElse Opcion = "Last" OrElse Opcion = "Idle" OrElse Opcion = "Ralenti" Then
e.Row.Cells(3).Text = $"{Decimal.Round(e.Row.DBCampo("TiempoDetenido").ToDecimal / 60, 1).ToString("###,###,##0.##")} Hrs ({e.Row.DBCampo("TiempoDetenido").ToDecimal.ToString("#,##0.##")} minutos)"
e.Row.Cells(4).Style.Add("display", "none")
ElseIf Opcion = "All" Then
e.Row.Cells(3).Text = $"{Decimal.Round(e.Row.DBCampo("TiempoDetenido").ToDecimal / 60, 1).ToString("###,###,##0.##")} Hrs ({e.Row.DBCampo("TiempoDetenido").ToDecimal.ToString("#,##0.##")} minutos)"
ElseIf Opcion = "TPS" Then
e.Row.Cells(3).Text = $"{Decimal.Round(e.Row.DBCampo("TiempoDetenido").ToDecimal / 60, 1).ToString("###,###,##0.##")} Hrs ({e.Row.DBCampo("TiempoDetenido").ToDecimal.ToString("#,##0.##")} minutos)"
Else
e.Row.Cells(3).Style.Add("display", "none")
e.Row.Cells(4).Style.Add("display", "none")
End If
End If
End Sub
Protected Sub GvKm_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GVKm.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim id = $"row{e.Row.RowIndex}"
e.Row.ID = id
If e.Row.DBCampo("Vehiculo").ToString = "" Then
e.Row.CssClass = "Totales"
e.Row.Cells(0).Text = $"Total Kilometros Recorridos: {txtFechaI.Text.ToDateTime.ToShortDateString} - {txtFechaF.Text.ToDateTime.ToShortDateString} "
e.Row.Cells(1).Text = $"{Decimal.Round(DtDatos.SUM("TiempoOperativo", "Vehiculo IS NOT NULL").ToDecimal / 60, 1).ToString("###,###,##0.##")} Hrs ({DtDatos.SUM("TiempoOperativo", "Vehiculo IS NOT NULL").ToDecimal.ToString("#,##0.##")} minutos)"
e.Row.Cells(2).Text = $"{Decimal.Round(DtDatos.SUM("Dist", "Vehiculo IS NOT NULL").ToDecimal, 2).ToString("###,###,##0.00")} KM"
Else
e.Row.Attributes.Add("idgv", e.Row.RowIndex.ToString)
e.Row.Attributes.Add("onClick", $"DeleteMarkers();$('#HdnKM').val({e.Row.DBCampo("CveDispositivo")});doScaledCLickKM('#C_BtnCargaRecorrido',{e.Row.RowIndex});")
' e.Row.Attributes.Add("onClick", $"DeleteMarkers();creaPolyline({SQLToGmaps(e.Row.DBCampo("Recorrido"), "FDFDSFDSFS")}, '{GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("ColorTrazo", $"CveDispositivo = {e.Row.DataKey("CveDispositivo").ToString}")}', '', '', '', '')")
e.Row.Cells(1).Text = $"{Decimal.Round(e.Row.DBCampo("TiempoOperativo").ToDecimal / 60, 1).ToString("###,###,##0.##")} Hrs ({e.Row.DBCampo("TiempoOperativo").ToDecimal.ToString("#,##0.##")} minutos)"
End If
End If
End Sub
#End Region
#Region "GeoReferencias"
Protected Sub BtnCrear_Click(sender As Object, e As EventArgs) Handles BtnAgregarGeoreferencia.Click
Dim GeoRefString As String = ""
Dim ObjGPS As New ClsGPS
ObjGPS.IniciaTransacSQL()
Dim TieneError As Boolean = False
Try
If HdnTipo.Value = "Georuta" Then
GeoRefString = CommandArg.Value
Dim CoordsPuntos() As String = GeoRefString.Split("+"c)
GeoRefString = ""
For Each coordenada As String In CoordsPuntos
If coordenada Is CoordsPuntos.Last Then
Exit For
End If
coordenada = coordenada.Replace("(", "").Replace(")", "")
Dim LatLng() As String = coordenada.Split(","c)
GeoRefString = $"{GeoRefString} {LatLng(1).Trim} {LatLng(0).Trim},"
Next
GeoRefString = GeoRefString.Substring(0, GeoRefString.Length - 1)
GeoRefString = $"LINESTRING({GeoRefString})"
If ObjGPS.GeoReferenciaAdd(TxtNombre.Text, -1, GeoRefString, "Ruta", True, TxtFechaIG.Text.ToDate, TxtFechaFG.Text.ToDate, chkLunes.Checked, chkMartes.Checked, chkMiercoles.Checked, chkJueves.Checked, chkViernes.Checked, chkSabado.Checked, chkDomingo.Checked, MinFecha, MaxFecha, TxtColor.Text, TxtTolerancia.Text.ToEntero, UsuarioActual.CveCliente) Then
For Each Dr As GridViewRow In GvEquiposDetalle.Rows
If Dr.RowType = DataControlRowType.DataRow Then
If Not ObjGPS.AddGeoReferenciaDetalle(ObjGPS.CveGeoReferencia, Dr.DataKey("CveDispositivo").ToString.ToEntero) Then
TieneError = True
Exit For
End If
End If
Next
End If
'RegistraScript("CreaRuta();")
ElseIf HdnTipo.Value = "Geocerca" Then
GeoRefString = $"POLYGON(({GeoCerca.Value} {CommandArg.Value}))"
If ObjGPS.GeoReferenciaAdd(TxtNombre.Text, -1, GeoRefString, "Geocerca", True, TxtFechaIG.Text.ToDate, TxtFechaFG.Text.ToDate, chkLunes.Checked, chkMartes.Checked, chkMiercoles.Checked, chkJueves.Checked, chkViernes.Checked, chkSabado.Checked, chkDomingo.Checked, MinFecha, MaxFecha, TxtColor.Text, TxtTolerancia.Text.ToEntero, UsuarioActual.CveCliente) Then
For Each Dr As GridViewRow In GvEquiposDetalle.Rows
If Dr.RowType = DataControlRowType.DataRow Then
If Not ObjGPS.AddGeoReferenciaDetalle(ObjGPS.CveGeoReferencia, Dr.DataKey("CveDispositivo").ToString.ToEntero) Then
TieneError = True
Exit For
End If
End If
Next
Else
TieneError = True
End If
End If
Catch ex As Exception
OnError("Ocurrió un error al crear la georeferencia", ex)
End Try
If TieneError Then
ObjGPS.RollBack()
Alert("Ocurrió un error al crear la georeferencia", TipoMensaje.MsgError)
Else
ObjGPS.Commit()
Alert("Se agregó correctamente la georeferencia", TipoMensaje.MsgInformacion)
End If
ObjGPS.Dispose()
DtDetalle.Rows.Clear()
GvEquiposDetalle.DataSource = DtDetalle
GvEquiposDetalle.DataBind()
UpAgregarGeo.Update()
Dim SbJS As New StringBuilder
SbJS.Append("$('#LnkMostarGeocercas').css('display', 'block'); setTimeout(function(){ ")
Dim CoordsGeo = SQLToGmapsJArray(GeoRefString, "POLYGON")
SbJS.AppendFormat("Limpieza(); creaPoligonoGeocerca({0},'{1}','{2}'); ", CoordsGeo.ToString, TxtColor.Text, TxtNombre.Text)
SbJS.Append(" VerGeocercas(); VerGeocercas(); },1000);")
GeoRefString = ""
' DdlEquipo.SelectedValue = "-1"
chkLunes.Checked = False
chkMartes.Checked = False
chkMiercoles.Checked = False
chkJueves.Checked = False
chkViernes.Checked = False
chkSabado.Checked = False
chkDomingo.Checked = False
'TxtHoraI.Text = ""
'TxtHoraF.Text = ""
RegistraScript(SbJS.ToString(), "1")
End Sub
Protected Sub LnkAgregarGeoHist_Click(sender As Object, e As EventArgs)
'RegistraScript("Limpieza();")
'GeoRefString = ""
'DdlEquipo.SelectedValue = "-1"
'chkLunes.Checked = False
'chkMartes.Checked = False
'chkMiercoles.Checked = False
'chkJueves.Checked = False
'chkViernes.Checked = False
'chkSabado.Checked = False
'chkDomingo.Checked = False
End Sub
#End Region
#Region "IMPRESIONES"
Public Sub EnviarReporteProgramado(Format As String)
Dim retorno As Byte()
Dim RutaReporte As String = ""
Dim NombreReporte As String = ""
If Opcion = "KM" Then
If GVKm.Rows.Count > 0 Then
RutaReporte = "Empresas/Grales/ReportesProgramados/RPTKmRecorridos.rdlc"
NombreReporte = "ReporteKMRecorridos"
Try
Dim RptParametro As New List(Of ReportParameter)
RptParametro.Add(New ReportParameter("FechaInicio", FechaI.ToString))
RptParametro.Add(New ReportParameter("FechaFin", FechaF.ToString))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New ReportParameter("FechaImpresion", DateTime.Now.ToString))
retorno = StreamPDF(RutaReporte, DtDatos, RptParametro, $"{NombreReporte}{Date.Now.ToShortDateString}", Format, MR:=Nothing, RDSName:="DsOC")
ImprimirbytesPDF(retorno, $"{NombreReporte}{Date.Now.ToShortDateString}", Format)
Catch ex As Exception
GuardaLog(String.Format("Ocurrio un error al generar el reporte RLDC {0}", ex))
End Try
Else
Alert("No se pudo imprimir el pdf, ya que no se ha hecho una consulta, o ésta no arrojó resultados.", TipoMensaje.MsgInformacion)
End If
ElseIf Opcion = "Last" AndAlso Format = "EXCEL" Then
GenerarReporteUltimaPosicionExcel("UltimaPosicion.xlsx")
ElseIf Opcion = "All" Then
If GvBarra.Rows.Count > 0 Then
RutaReporte = "Empresas/Grales/ReportesProgramados/RPTHistorico.rdlc"
NombreReporte = "ReporteHistorico"
Try
ImprimirCrystal(NombreReporte, Format)
Catch ex As Exception
GuardaLog(String.Format("Ocurrio un error al generar el reporte RLDC {0}", ex))
End Try
Else
Alert("No se pudo imprimir el pdf, ya que no se ha hecho una consulta, o ésta no arrojó resultados.", TipoMensaje.MsgInformacion)
End If
ElseIf Opcion = "Speed" Then
RutaReporte = "Empresas/Grales/ReportesProgramados/RPVelocidad.rdlc"
NombreReporte = "ReporteExcesosVelocidad"
Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta))
Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa)
Dim RptParametro As New List(Of ReportParameter)
Dim DtDatos As New DataTable()
DtDatos.Columns.Add("Unidad", GetType(String))
DtDatos.Columns.Add("Fecha", GetType(String))
DtDatos.Columns.Add("Direccion", GetType(String))
DtDatos.Columns.Add("Velocidad", GetType(String))
DtDatos.Columns.Add("Conductor", GetType(String))
Try
RptParametro.Add(New ReportParameter("FechaInicio", FechaI.ToString))
RptParametro.Add(New ReportParameter("FechaFin", FechaF.ToString))
RptParametro.Add(New ReportParameter("MapaURL", ""))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New ReportParameter("FechaImpresion", DateTime.Now.ToString))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New ReportParameter("NombreEmpresa", UsuarioActual.Empresa.Empresa))
If Imagen.Exists Then
RptParametro.Add(New ReportParameter("LogoPath", logouri))
Else
RptParametro.Add(New ReportParameter("LogoPath", ""))
End If
For Each row As GridViewRow In GvBarra.Rows
Dim DrNew = DtDatos.NewRow()
Dim pos = JObject.Parse(row.DataKey("Posicion"))
DrNew("Unidad") = row.Cells(0).Text
DrNew("Fecha") = row.Cells(1).Text
DrNew("Direccion") = If(Not String.IsNullOrEmpty(row.FCHiddenField("HdnDireccionRow").Value), row.FCHiddenField("HdnDireccionRow").Value, CargaDireccion(pos("lat").ToString(), pos("lng").ToString())) 'If(String.IsNullOrEmpty(Direcciones(row.RowIndex)), Direcciones(row.RowIndex), If(row.FCHiddenField("HdnDireccionRow").Value <> "", row.FCHiddenField("HdnDireccionRow").Value, CargaDireccion(pos("lat").ToString(), pos("lng").ToString())))
DrNew("Velocidad") = row.Cells(5).Text
DrNew("Conductor") = "" ' DtPosiciones()
DtDatos.Rows.Add(DrNew)
Next
Catch ex As Exception
GuardaLog(String.Format("Ocurrio un error al generar el reporte RLDC {0}", ex))
End Try
retorno = StreamPDF(RutaReporte, DtDatos, RptParametro, $"{NombreReporte}{Date.Now.ToShortDateString}", Format, MR:=Nothing, RDSName:="DsOC")
ImprimirbytesPDF(retorno, $"{NombreReporte}{Date.Now.ToShortDateString}", Format)
DtDatos.Clear()
Else
If GvBarra.Rows.Count > 0 Then
Select Case Opcion
Case "Idle"
RutaReporte = "Empresas/Grales/ReportesProgramados/RPTiempoMuerto.rdlc"
NombreReporte = "ReporteTiempoMuerto"
Case "Ralenti"
RutaReporte = "Empresas/Grales/ReportesProgramados/RPTRalenti.rdlc"
NombreReporte = "ReporteRalenti"
End Select
Dim RptParametro As New List(Of ReportParameter)
Dim DtDatos As New DataTable()
DtDatos.Columns.Add("Unidad", GetType(String))
DtDatos.Columns.Add("Fecha", GetType(String))
DtDatos.Columns.Add("Direccion", GetType(String))
DtDatos.Columns.Add("TiempoDetenido", GetType(String))
DtDatos.Columns.Add("Conductor", GetType(String))
Try
RptParametro.Add(New ReportParameter("FechaInicio", FechaI.ToString))
RptParametro.Add(New ReportParameter("FechaFin", FechaF.ToString))
RptParametro.Add(New ReportParameter("MapaURL", ""))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New ReportParameter("FechaImpresion", DateTime.Now.ToString))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
If Opcion = "Idle" Then
RptParametro.Add(New ReportParameter("TiempoMuerto", TxtMinutos.Text + " Minutos"))
End If
Dim Direcciones As String() = HdnDirecciones.Value.Split(";"c)
For Each row As GridViewRow In GvBarra.Rows
Dim DrNew = DtDatos.NewRow()
Dim pos = JObject.Parse(row.DataKey("Posicion"))
DrNew("Unidad") = row.Cells(0).Text
DrNew("Fecha") = row.Cells(1).Text
DrNew("Direccion") = If(Not String.IsNullOrEmpty(row.FCHiddenField("HdnDireccionRow").Value), row.FCHiddenField("HdnDireccionRow").Value, CargaDireccion(pos("lat").ToString(), pos("lng").ToString())) 'If(String.IsNullOrEmpty(Direcciones(row.RowIndex)), Direcciones(row.RowIndex), If(row.FCHiddenField("HdnDireccionRow").Value <> "", row.FCHiddenField("HdnDireccionRow").Value, CargaDireccion(pos("lat").ToString(), pos("lng").ToString())))
DrNew("TiempoDetenido") = row.Cells(3).Text
DrNew("Conductor") = "" ' DtPosiciones()
DtDatos.Rows.Add(DrNew)
Next
'Dim ObjMail As New ClsSisMail()
'Dim ObjEmpresa As New ClsSisEmpresas()
'ObjEmpresa.GetEmpresas(1, "-1", "-1", "-1", "-1")
'Dim ResultadoMail As Integer = 0
'Dim LSRutasMail As New List(Of ClsSisMail.ArchivoMail)
'LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.ArchivoBinario = retorno, .NombreArchivo = "ReporteProgramado.pdf"})
'LSRutasMail.Add(New ClsSisMail.ArchivoMail With {.Ruta = Xml}
Catch ex As Exception
GuardaLog(String.Format("Ocurrio un error al generar el reporte RLDC {0}", ex))
End Try
retorno = StreamPDF(RutaReporte, DtDatos, RptParametro, $"{NombreReporte}{Date.Now.ToShortDateString}", Format, MR:=Nothing, RDSName:="DsOC")
ImprimirbytesPDF(retorno, $"{NombreReporte}{Date.Now.ToShortDateString}", Format)
DtDatos.Clear()
Else
Alert("No se pudo imprimir el pdf, ya que no se ha hecho una consulta, o ésta no arrojó resultados.", TipoMensaje.MsgInformacion)
End If
End If
End Sub
Public Function ConsultarDireccionesUP(Dt As DataTable) As JArray
Dim retorno As JArray = Nothing
Dim posicionesArray = New JArray()
For Each Row As DataRow In Dt.Rows
Dim punto = JObject.Parse(Row("Posicion").ToString())
Dim jo = New JObject(
New JProperty("indice", Dt.Rows().IndexOf(Row)),
New JProperty("cveTrama", -1),
New JProperty("lat", punto("lat")),
New JProperty("lon", punto("lng"))
)
posicionesArray.Add(jo)
Next
Dim Base64array = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(posicionesArray.ToString()))
Using wc As New HttpClient()
Try
Dim Url = New Uri(String.Format("{0}nominatim/reverseMultiple.php", ClsPaginas.UrlDirecciones))
Dim FormStuff = String.Format("formato=json&posiciones={0}", Base64array)
Dim content = New StringContent(FormStuff, Encoding.UTF8, "application/x-www-form-urlencoded")
Dim response = wc.PostAsync(Url, content).Result
Dim result = response.Content.ReadAsStringAsync().Result
retorno = JArray.Parse(result)
response.Dispose()
content = Nothing
Url = Nothing
FormStuff = Nothing
Catch ex As Exception
OnError("Ocurrió un error al obtener las direcciones", ex)
End Try
End Using
Return retorno
End Function
Private Sub GenerarReporteUltimaPosicionExcel(FileName As String)
SpreadsheetInfo.SetLicense(ModExtensiones.SerialGemBoxSpreadsheet)
Dim FileExcel As ExcelFile = New ExcelFile
Dim Dt = DtPosiciones.Copy()
Dt.Columns.Add("Direccion", GetType(String))
Dt.Columns.Remove("CveDispositivo")
Dt.Columns.Remove("Evento")
Dt.Columns.Remove("Icono")
Dt.Columns.Remove("KMRecorridos")
Dt.Columns("TiempoDetenido").ColumnName = "Tiempo Detenido (Min)"
Dim Direcciones = ConsultarDireccionesUP(Dt)
Dt.Columns.Remove("Posicion")
For Each Dir As JObject In Direcciones
Dt.Rows(Dir("Indice").ToEntero())("Direccion") = Dir("Direccion").ToString()
Next
Dim item = FileExcel.Worksheets.Add("Última Posición")
item.InsertDataTable(Dt, New InsertDataTableOptions() With
{
.ColumnHeaders = True,
.StartRow = 0,
.StartColumn = 0
})
item.Rows(0).Style.FillPattern.SetPattern(FillPatternStyle.Solid, SpreadsheetColor.FromArgb(75, 119, 190), SpreadsheetColor.FromArgb(255, 255, 255))
item.Rows(0).Style.Font.Color = SpreadsheetColor.FromArgb(255, 255, 255)
Dim columnCount = item.CalculateMaxUsedColumns()
For i = 0 To columnCount
item.Columns(i).AutoFit(1, item.Rows(i), item.Rows(item.Rows.Count - 1))
Next
FileExcel.Save(Me.Response, FileName, SaveOptions.XlsxDefault)
End Sub
Private Function CargaDireccion(ByVal lat As String, ByVal lng As String) As String
Try
Dim DireccionJSON As String = ""
Dim request As WebRequest
Dim js As JObject = Nothing
request = WebRequest.Create(String.Format("{0}nominatim/reverse.php?format=jsonv2&lat={1}&lon={2}", ClsPaginas.UrlDirecciones, lat, lng))
request.Method = "GET"
Dim response As WebResponse = request.GetResponse()
Dim inputstream1 As Stream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(inputstream1)
DireccionJSON = reader.ReadToEnd()
inputstream1.Dispose()
reader.Close()
response.Close()
request = Nothing
js = JObject.Parse(DireccionJSON)
If js IsNot Nothing Then
Return js("display_name").ToString()
Else
Return "Dirección no encontrada"
End If
Catch ex As Exception
Me.GuardaLog(ex.ToString())
End Try
Return "Dirección no encontrada"
End Function
Private Sub ImprimirCrystal(NombreReporte As String, Format As String)
Dim RptParametro As New List(Of CrystalParametro)
Dim Imagen As New System.IO.FileInfo(String.Format("{0}/Logo.png", UsuarioActual.Empresa.Ruta))
Dim logouri = String.Format("{0}://{1}:{2}/Empresas/{3}/Logo.png", Request.Url.Scheme, Request.Url.Host, Request.Url.Port, UsuarioActual.CveEmpresa)
RptParametro.Add(New CrystalParametro("FechaInicio", FechaI.ToString))
RptParametro.Add(New CrystalParametro("FechaFin", FechaF.ToString))
RptParametro.Add(New CrystalParametro("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New CrystalParametro("FechaImpresion", DateTime.Now.ToString))
RptParametro.Add(New CrystalParametro("KMRecorridos", $"{DtPosiciones.SUM("KMRecorridos").ToString} KM"))
RptParametro.Add(New CrystalParametro("NombreEmpresa", UsuarioActual.Empresa.Empresa))
If Imagen.Exists Then
RptParametro.Add(New CrystalParametro("LogoPath", logouri))
Else
RptParametro.Add(New CrystalParametro("LogoPath", ""))
End If
Dim DtDatos As New DataTable()
DtDatos.Columns.Add("Vehiculo", GetType(String))
DtDatos.Columns.Add("Fecha", GetType(String))
DtDatos.Columns.Add("Direccion", GetType(String))
DtDatos.Columns.Add("TiempoDetenido", GetType(String))
DtDatos.Columns.Add("Conductor", GetType(String))
DtDatos.Columns.Add("Velocidad", GetType(String))
DtDatos.Columns.Add("Evento", GetType(String))
DtDatos.Columns.Add("LatLng", GetType(String))
'Dim Direcciones As String() = HdnDirecciones.Value.Split(";"c)
Dim i = 0
Try
Dim Direcciones As JArray = ConsultarDirecciones(DtPosiciones)
For Each row As DataRow In DtPosiciones.Rows
Dim DrNew = DtDatos.NewRow()
DrNew("Vehiculo") = row("Vehiculo")
DrNew("Fecha") = row("Fecha")
DrNew("TiempoDetenido") = row("TiempoDetenido")
DrNew("Evento") = row("Evento")
DrNew("Velocidad") = row("Velocidad")
DrNew("Direccion") = "Dirección no encontrada"
DrNew("LatLng") = row("Posicion").ToString.Replace("{", "").Replace("}", "")
DtDatos.Rows.Add(DrNew)
i = i + 1
Next
For Each Dir As JObject In Direcciones
DtDatos.Rows(Dir("Indice").ToEntero())("Direccion") = Dir("Direccion").ToString()
Next
Catch ex As Exception
GuardaLog(String.Format("Ocurrio un error al generar el reporte RLDC {0}", ex))
End Try
ImprimirbytesPDF(ImprimirPDFCrystal(Server.MapPath("~/Empresas/Grales/ReportesProgramados/RPTHistorico.rpt"), DtDatos, RptParametro, NombreReporte, Format), NombreReporte, Format)
DtDatos.Clear()
End Sub
Private Sub ImprimirRDLC(NombreReporte As String, Format As String, RutaReporte As String)
Dim RptParametro As New List(Of ReportParameter)
RptParametro.Add(New ReportParameter("FechaInicio", FechaI.ToString))
RptParametro.Add(New ReportParameter("FechaFin", FechaF.ToString))
RptParametro.Add(New ReportParameter("MapaURL", ""))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New ReportParameter("FechaImpresion", DateTime.Now.ToShortDateString))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New ReportParameter("KMRecorridos", DtPosiciones.SUM("KMRecorridos").ToString))
Dim DtDatos As New DataTable()
DtDatos.Columns.Add("Vehiculo", GetType(String))
DtDatos.Columns.Add("Fecha", GetType(String))
DtDatos.Columns.Add("Posicion", GetType(String))
DtDatos.Columns.Add("TiempoDetenido", GetType(String))
DtDatos.Columns.Add("Conductor", GetType(String))
DtDatos.Columns.Add("Velocidad", GetType(String))
DtDatos.Columns.Add("Evento", GetType(String))
DtDatos.Columns.Add("LatLng", GetType(String))
Dim Direcciones As String() = HdnDirecciones.Value.Split(";"c)
Dim i = 0
Try
For Each row As DataRow In DtPosiciones.Rows
Dim DrNew = DtDatos.NewRow()
DrNew("Vehiculo") = row("Vehiculo")
DrNew("Fecha") = row("Fecha")
DrNew("TiempoDetenido") = row("TiempoDetenido")
DrNew("Evento") = row("Evento")
DrNew("Velocidad") = row("Velocidad")
If i < Direcciones.Length Then
DrNew("Posicion") = If(String.IsNullOrEmpty(Direcciones(i)), "Dirección no encontrada", Direcciones(i))
Else
DrNew("Posicion") = "Dirección no encontrada"
End If
DrNew("LatLng") = row("Posicion").ToString.Replace("{", "").Replace("}", "")
DtDatos.Rows.Add(DrNew)
i = i + 1
Next
Catch ex As Exception
GuardaLog(String.Format("Ocurrio un error al generar el reporte RLDC {0}", ex))
End Try
ImprimirbytesPDF(StreamPDF(RutaReporte, DtDatos, RptParametro, $"{NombreReporte}_{Date.Now.ToShortDateString}", Format, MR:=Nothing, RDSName:="DsOC"), $"{NombreReporte}{Date.Now.ToShortDateString}", Format)
DtDatos.Clear()
End Sub
Protected Sub btnImprimir_Click(sender As Object, e As EventArgs)
Dim Btn As Button = CType(sender, Button)
Dim Format = Btn.CommandArgument
EnviarReporteProgramado(Format)
End Sub
Protected Sub btnImprimir_ClickKM(sender As Object, e As EventArgs)
Dim Btn As Button = CType(sender, Button)
Dim Format = Btn.CommandArgument
EnviarReporteProgramado(Format)
End Sub
#End Region
Protected Sub BtnCargaRecorrido_Click(sender As Object, e As EventArgs)
Dim ObjGPS As New ClsGPS
Dim Correcto = ObjGPS.RecorridoGet(UsuarioActual.CveCliente, FechaI, FechaF, HdnKM.Value.ToEntero)
Dim Recorrido As String = ""
Dim StrRecorrido As New StringBuilder
StrRecorrido.Append("[")
Dim ColorTrazo As String = ""
If Correcto Then
'For Each Coord As String In ObjGPS.DtResultados.Rows(0)("Recorrido").ToString.Split(",")
' StrRecorrido.AppendFormat("{0},", SQLToGmapsJArray().ToString())
'Next
Recorrido = SQLToGmapsJArray(ObjGPS.DtResultados.Rows(0)("Recorrido").ToString, "FDFDSFDSFS").ToString
Dim color = GlobalDTDispositivos(UsuarioActual.CveCliente).FiltroPrimeroValor("ColorTrazo", $"CveDispositivo = {ObjGPS.DtResultados.Rows(0)("CveDispositivo").ToString}")
ColorTrazo = If(String.IsNullOrEmpty(color), "#3393FF", color)
End If
StrRecorrido.Append("]")
ObjGPS.Dispose()
If Not String.IsNullOrEmpty(Recorrido) Then
RegistraScript($"creaPolyline({Recorrido}, '{ColorTrazo}', '', '', '', '',-1)")
End If
End Sub
Protected Sub BtnFiltrarFechaGV_Click(sender As Object, e As EventArgs)
Dim retorno As Byte()
Dim RutaReporte As String = ""
Dim NombreReporte As String = ""
Dim CveDispositivo As Integer = DtPosiciones.Rows(0)("CveDispositivo").ToString.ToEntero
Dim GrupoMinutos = 30
Dim GrupoHoras = 1
Dim GrupoDias = 1
Dim ObjGPS As New ClsGPS
Dim Correcto = ObjGPS.GetHistorialPasajeros(CveDispositivo, TxtFechaGVI.Text.ToDateTime, TxtFechaGVF.Text.ToDateTime, GrupoMinutos, GrupoHoras, GrupoDias)
Dim DtHistorialPasajeros = ObjGPS.DtResultados.Copy()
ObjGPS.Dispose()
If Correcto Then
Try
RutaReporte = "Empresas/Grales/ReportesProgramados/RPTPasajeros.rdlc"
NombreReporte = "ReportePasajeros"
Dim RptParametro As New List(Of ReportParameter)
RptParametro.Add(New ReportParameter("FechaInicio", TxtFechaGVI.Text.ToString))
RptParametro.Add(New ReportParameter("FechaFin", TxtFechaGVF.Text.ToString))
RptParametro.Add(New ReportParameter("UsuarioImprimio", UsuarioActual.Usuario))
RptParametro.Add(New ReportParameter("FechaImpresion", DateTime.Now.ToShortDateString))
retorno = StreamPDF(RutaReporte, DtHistorialPasajeros, RptParametro, $"{NombreReporte}{Date.Now.ToShortDateString}", "PDF", MR:=Nothing, RDSName:="DsOC")
ImprimirbytesPDF(retorno, $"{NombreReporte}{Date.Now.ToShortDateString}")
Catch ex As Exception
GuardaLog(String.Format("Ocurrio un error al generar el reporte RLDC {0}", ex))
End Try
End If
End Sub
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
Protected Sub LnkAgregarGeoHist_Click1(sender As Object, e As EventArgs)
Dim TieneError As Boolean = False
Dim ObjGPS As New ClsGPS
ObjGPS.IniciaTransacSQL()
Try
'Dim JsonGeoRutas As JArray = JArray.Parse(GeoRutaHistorico.Value)
Dim Geo As JObject = JObject.Parse(GeoRutaHistorico.Value)
If Geo IsNot Nothing Then
Dim CveDispositivo = Geo("ValueEquipo").ToString.ToEntero
Dim Coords As JArray = JArray.Parse(Geo("Cordenadas").ToString)
If Coords.Any Then
Dim GeoRefString As New StringBuilder()
GeoRefString.Append("LINESTRING(")
Dim Index = 0
Dim IndexFinal = Coords.Count - 1
For Each Coord As JObject In Coords
Dim Lat = Coord("lat").ToString
Dim Lng = Coord("lng").ToString
If Index = 0 Then
GeoRefString.AppendFormat("{0} {1},", Lng, Lat)
ElseIf Index = IndexFinal Then
Dim UltimaPos = Geo("UltimaPos")
GeoRefString.AppendFormat("{0} {1})", UltimaPos("lng"), UltimaPos("lat"))
Else
GeoRefString.AppendFormat(" {0} {1},", Lng, Lat)
End If
Index = Index + 1
Next
If ObjGPS.GeoReferenciaAdd(TxtNombreHis.Text, CveDispositivo, GeoRefString.ToString, "Ruta", True, TxtFechaIHis.Text.ToDate, TxtFechaFHis.Text.ToDate, ChkLunesH.Checked, ChkMartesH.Checked, ChkMiercolesH.Checked, ChkJuevesH.Checked, ChkViernesH.Checked, ChkSabadoH.Checked, ChkDomingoH.Checked, MinFecha, MaxFecha, TxtColorH.Text, TxtToleHis.Text.ToEntero, UsuarioActual.CveCliente) Then
If Not ObjGPS.AddGeoReferenciaDetalle(ObjGPS.CveGeoReferencia, CveDispositivo) Then
TieneError = True
End If
Else
TieneError = True
End If
End If
End If
Catch ex As Exception
OnError("Ocurrió un error al crear la georeferencia", ex)
End Try
If TieneError Then
ObjGPS.RollBack()
Alert("Ocurrió un error al crear la Ruta", TipoMensaje.MsgInformacion)
Else
ObjGPS.Commit()
Alert("Se agregó correctamente la Ruta", TipoMensaje.MsgInformacion)
End If
ObjGPS.Dispose()
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><a target=\'_blank\' href=\'/GPS/Vehiculos.aspx?CveDispositivo={CveDispositivo}\'><b>{Header}</b></a></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
#Region "G E O C E R C A S"
Protected Sub GvEquiposDetalle_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
DtDetalle.Rows.RemoveAt(e.RowIndex)
GvEquiposDetalle.DataSource = DtDetalle
GvEquiposDetalle.DataBind()
UpAgregar.Update()
End Sub
Protected Sub LnkAgregarDisp_Click(sender As Object, e As EventArgs)
Dim CveDispositivo As Integer = DdlEquipoD.SelectedValue.ToEntero
If CveDispositivo > 0 Then
Dim NoEconomico As String = DdlEquipoD.SelectedItem.Text
If Not DtDetalle.Select($"CveDispositivo={CveDispositivo}").Any() Then
Dim Dr As DataRow = DtDetalle.NewRow
Dr("CveDispositivo") = CveDispositivo
Dr("NoEconomico") = NoEconomico
Dr("CveDispositivoGeoReferenciaDetalle") = -1
DtDetalle.Rows.Add(Dr)
DtDetalle.AcceptChanges()
Else
Alert($"El dispositivo '{NoEconomico} ya existe en la tabla.'", TipoMensaje.MsgAdvertencia)
End If
GvEquiposDetalle.DataSource = DtDetalle
GvEquiposDetalle.DataBind()
End If
UpAgregar.Update()
End Sub
Protected Sub LnkAgregarGrupo_Click(sender As Object, e As EventArgs)
Dim CveGrupo As Integer = DdlGrupo.SelectedValue.ToEntero
Using ObjGPS As New ClsGPS
If ObjGPS.GruposDetallesGet(CveGrupo) Then
Dim Query = From dr In ObjGPS.DtResultados
Select CveDispositivo = dr("CveDispositivo").ToString.ToEntero, NoEconomico = dr("NoEconomico").ToString, CveDispositivoGeoReferenciaDetalle = -1
Dim dt As DataTable = Query.QueryToDataTable(True)
dt.PrimaryKey = New DataColumn() {dt.Columns(0)}
DtDetalle.Merge(dt, True, MissingSchemaAction.Ignore)
End If
End Using
GvEquiposDetalle.DataSource = DtDetalle
GvEquiposDetalle.DataBind()
UpAgregar.Update()
End Sub
#End Region
Protected Sub btnPagePrev_Click(sender As Object, e As EventArgs)
Dim TotalRegistros As Integer = DtPosiciones.Rows.Count
Dim TotalRowsPage As Integer = GvBarra.PageSize
Dim PrevIndex As Integer = HdnIndexPage.Value.ToEntero - 1
Dim CurrentIndex As Integer = PrevIndex + 1
Dim PrevIndexDT As Integer = (TotalRowsPage) * PrevIndex
Dim CurrentIndexDT As Integer = (TotalRowsPage) * CurrentIndex
HdnIndexPage.Value = PrevIndex.ToString
If Not btnPageNext.Enabled Then
btnPageNext.Enabled = True
End If
If PrevIndexDT <= 0 Then
btnPagePrev.Enabled = False
GvBarra.DataSource = DtPosiciones.FiltraPorIndices(0, CurrentIndexDT)
LblRegistros.Text = $"Distribución de datos desde 0 hasta {CurrentIndexDT.ToString.FormatoNumero(0)}. Total de registros: {DtPosiciones.Rows.Count.ToString.FormatoNumero(0)}"
Else
LblRegistros.Text = $"Distribución de datos desde {PrevIndexDT.ToString.FormatoNumero(0)} hasta {CurrentIndexDT.ToString.FormatoNumero(0)}. Total de registros: {DtPosiciones.Rows.Count.ToString.FormatoNumero(0)}"
GvBarra.DataSource = DtPosiciones.FiltraPorIndices(PrevIndexDT, CurrentIndexDT)
End If
GvBarra.DataBind()
UPGV.Update()
RegistraScript("setTimeout(function(){OpcionesHistorico();},500);")
End Sub
Protected Sub btnPageNext_Click(sender As Object, e As EventArgs)
Dim TotalRegistros As Integer = DtPosiciones.Rows.Count
Dim TotalRowsPage As Integer = GvBarra.PageSize
Dim Index As Integer = HdnIndexPage.Value.ToEntero + 1
Dim NextIndex As Integer = Index + 1
Dim CurrentIndexDT As Integer = (TotalRowsPage) * Index
Dim NextIndexDT As Integer = (TotalRowsPage) * NextIndex
HdnIndexPage.Value = Index.ToString
If Not btnPagePrev.Enabled Then
btnPagePrev.Enabled = True
End If
If NextIndexDT >= TotalRegistros Then
btnPageNext.Enabled = False
GvBarra.DataSource = DtPosiciones.FiltraPorIndices(CurrentIndexDT, TotalRegistros - 1)
LblRegistros.Text = $"Distribución de datos desde {CurrentIndexDT.ToString.FormatoNumero(0)} hasta {DtPosiciones.Rows.Count.ToString.FormatoNumero(0)}. Total de registros: {DtPosiciones.Rows.Count.ToString.FormatoNumero(0)}"
Else
GvBarra.DataSource = DtPosiciones.FiltraPorIndices(CurrentIndexDT, NextIndexDT)
LblRegistros.Text = $"Distribución de datos desde {CurrentIndexDT.ToString.FormatoNumero(0)} hasta {NextIndexDT.ToString.FormatoNumero(0)}. Total de registros: {DtPosiciones.Rows.Count.ToString.FormatoNumero(0)}"
End If
GvBarra.DataBind()
UPGV.Update()
RegistraScript("setTimeout(function(){OpcionesHistorico();},500);")
End Sub
Public Function ConsultarDirecciones(Dt As DataTable) As JArray
Dim retorno As JArray = Nothing
Dim posicionesArray = New JArray(From Row As DataRow In Dt
Let punto = SQLToGmapsJArray(Row("Posicion").ToString(), "POINT")
Select New JObject(
New JProperty("indice", Dt.Rows().IndexOf(Row)),
New JProperty("cveTrama", -1),
New JProperty("lat", punto(0)("lat")),
New JProperty("lon", punto(1)("lat"))
))
Dim Base64array = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(posicionesArray.ToString()))
Using wc As New HttpClient()
Try
Dim Url = New Uri(String.Format("{0}nominatim/reverseMultiple.php", ClsPaginas.UrlDirecciones))
Dim FormStuff = String.Format("formato=json&posiciones={0}", Base64array)
Dim content = New StringContent(FormStuff, Encoding.UTF8, "application/x-www-form-urlencoded")
Dim response = wc.PostAsync(Url, content).Result
Dim result = response.Content.ReadAsStringAsync().Result
retorno = JArray.Parse(result)
response.Dispose()
content = Nothing
Url = Nothing
FormStuff = Nothing
Catch ex As Exception
OnError("Ocurrió un error al obtener las direcciones", ex)
End Try
End Using
Return retorno
End Function
#Region "G E O R E F E R E N C I A S"
Protected Sub ChkTrazarGeocercas_CheckedChanged(sender As Object, e As EventArgs)
If ChkTrazarGeocercas.Checked Then
Dim CountEquipos As Integer = 0
Dim Equipos As New StringBuilder()
For Each row As GridViewRow In GvDispositivos.Rows
If row.FCCheckBox("chkDis").Checked Then
CountEquipos += 1
Equipos.Append($"{row.DataKey("CveDispositivo")};")
End If
Next
If CountEquipos > 0 Then
Dim Dispositivos As String = Equipos.Replace(";", ",").Remove(Equipos.Length - 1, 1).ToString()
CargaGeocercas(Dispositivos)
RegistraScript("$('#DivGeoCercas').modal('show');")
Else
Alert("No hay equipos seleccionados", TipoMensaje.MsgAdvertencia)
End If
End If
End Sub
Protected Sub ChkTrazarGeorutas_CheckedChanged(sender As Object, e As EventArgs)
If ChkTrazarGeorutas.Checked Then
RegistraScript("$('#DivGeoRutas').modal('show');")
End If
End Sub
Protected Sub ChkTrazarPI_CheckedChanged(sender As Object, e As EventArgs)
If ChkTrazarPuntosInteres.Checked Then
RegistraScript("$('#DivMostrarPI').modal('show');")
End If
End Sub
Private Sub CargaGeoRutas()
Dim ObjGPS As New ClsGPS
If ObjGPS.GeoReferenciaGet(-1, 1, "Ruta", UsuarioActual.CveCliente) Then
GvGeorutas.DataSource = ObjGPS.DtResultados
End If
ObjGPS.Dispose()
GvGeorutas.DataBind()
UpGeorutas.Update()
End Sub
Private Sub CargaPI()
Dim ObjGPS As New ClsGPS
If ObjGPS.PuntoDeInteresGet(-1, UsuarioActual.CveCliente, 1, -1) Then
GVPuntosInteres.DataSource = ObjGPS.DtResultados
End If
ObjGPS.Dispose()
GVPuntosInteres.DataBind()
UpMostarPI.Update()
End Sub
#End Region
Protected Sub GvGrupos_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GvGrupos.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes.Add("onClick", $"CargaDatosSeleccionadosPI({e.Row.RowIndex}, '{e.Row.DBCampo("CvePuntoDeInteresGrupo").ToString}');")
End If
End Sub
Protected Sub BtnAgregarPunto_Click(sender As Object, e As EventArgs) Handles BtnAgregarPunto.Click
Dim HuboError = False
Dim ObjGPS As New ClsGPS
ObjGPS.IniciaTransacSQL()
Try
Dim GEOM As String = $"POINT{GeoCerca.Value}"
If Not ObjGPS.PuntoDeInteresAdd(TxtNombrePI.Text, UsuarioActual.CveCliente, GEOM, True, TxtDescripcion.Text, HdnGrupo.Value.ToEntero) Then
HuboError = True
End If
Catch ex As Exception
HuboError = True
OnError("Ocurrió un error al agregar el punto de interés", ex)
End Try
If HuboError Then
ObjGPS.RollBack()
Else
ObjGPS.Commit()
TxtDescripcion.Text = ""
TxtNombre.Text = ""
Alert("El punto de interés se agregó correctamente", TipoMensaje.MsgInformacion)
RegistraScript("$('#DivAgregarPuntoInteres').modal('hide');DeleteMarkersG();", "1")
End If
UpAgregarPuntoInteres.Update()
End Sub
End Class