public string EditarAgenda(Agenda agenda)
    {
        HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            cliente = cliente.Replace("\0", string.Empty);
            agenda.Cliente = cliente;
            double anti = ReporteAutomaticoBUI.GetAnticipacion(agenda);
            List<DateTime> fechas = ReporteAutomaticoBUI.Fechas(agenda);
            List<FechasAgenda> fechasAgenda = new List<FechasAgenda>();

            foreach (DateTime fecha in fechas)
            {
                FechasAgenda fa = new FechasAgenda();
                fa.AgendaID = -1;
                fa.FechaReporte = fecha;
                fa.Realizada = false;
                fechasAgenda.Add(fa);
            }
            agenda.FechasReporte = fechasAgenda.ToArray();
            bool geocercas = (agenda.DetallesReporte.Geocercas != null && agenda.DetallesReporte.Geocercas.Length > 0) ? true : false;
            bool grupos = (agenda.DetallesReporte.Grupos != null && agenda.DetallesReporte.Grupos.Length > 0) ? true : false;
            string  result = ReporteAutomaticoBUI.ModificarAgenda(agenda.ID.ToString(), agenda, true, true, geocercas, grupos);
            if (!result.Contains("0"))
            {
                return "ok";
            }
            else
                return result;
        }
        else
            return "error404";
    }
 public void Page_Init(object sender, EventArgs e)
 {
     HttpCookie Cookie = Request.Cookies.Get("Usuario");
     Codificador codificador = new Codificador();
     if (Cookie != null && AutentificacionBD.EstadoFactura(codificador.Desencriptar(Cookie.Values.Get("Cliente"))) == -1 && AutentificacionBD.AvisoGlobal() == "" && AutentificacionBD.AvisoPersonal(codificador.Desencriptar(Cookie.Values.Get("UsuarioID"))) == "" && Cookie.Values.Get("Recordar") =="true")
         Response.Redirect("Mapa.aspx");
     anioLegal.InnerHtml = DateTime.Now.Year.ToString();
 }
    public string ReporteViajeEntreGeocercas(List<string> unidades, List<string> geocercas, long fechaInicial, long fechaFinal, string geocercaBase)
    {
        HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            DateTime fInicial = Util.FromUnixMilis(fechaInicial);
            DateTime fFinal = Util.FromUnixMilis(fechaFinal);
            int accion = SistemaRastreoWeb.ReporteNotificacionGeocerca.AccionDentroFuera;
            List<ReporteNotificacionGeocerca> reporte = ReportesBD.ObtenerNotificacionesGeocerca(unidades, geocercas, fInicial, fFinal, accion, cliente);
            List<VehiculoGeocercas> vehiculosConNotificaciones= new List<VehiculoGeocercas>();
            List<ReporteViajesEntreGeocerca> viajes = new List<ReporteViajesEntreGeocerca>();

            //guardar en lista de vehiculos con notificaciones las unidades que tengan notificaciones de geocercas..
            foreach (string unidad in unidades)
            {
                List<ReporteNotificacionGeocerca> seleccionReportes = reporte.Where(x => x.VehiculoID.Equals(unidad)).ToList();
                if (seleccionReportes.Count > 0)
                {
                    //guardar en lista de unidades que si tienen reportes...
                    VehiculoGeocercas notificaciones = new VehiculoGeocercas(unidad, seleccionReportes);
                    vehiculosConNotificaciones.Add(notificaciones);
                }
            }
            //obtener las geocercas que visito la unidad, empezando con una salida, luego encontrando una entrada
            foreach (VehiculoGeocercas vehiculoNotificaciones in vehiculosConNotificaciones)
            {
                bool bViajeExistente = false;
                ReporteViajesEntreGeocerca viaje = new ReporteViajesEntreGeocerca();
                foreach (ReporteNotificacionGeocerca reporteNotificacion in vehiculoNotificaciones.Reportes)
                {
                    if (!bViajeExistente && reporteNotificacion.iAccion == SistemaRastreoWeb.ReporteNotificacionGeocerca.AccionFuera)
                    {
                        viaje.GeocercaSalida = reporteNotificacion.Geocerca;
                        viaje.FechaSalida = reporteNotificacion.Fecha;
                        bViajeExistente = true;
                    }
                    else if (bViajeExistente && reporteNotificacion.iAccion == SistemaRastreoWeb.ReporteNotificacionGeocerca.AccionDentro)
                    {
                        viaje.GeocercaEntrada = reporteNotificacion.Geocerca;
                        viaje.FechaEntrada = reporteNotificacion.Fecha;
                        bViajeExistente = false;
                        viajes.Add(viaje);
                        viaje = new ReporteViajesEntreGeocerca();
                    }
                }
            }
            string json = JsonConvert.SerializeObject(viajes, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            return json;
        }
        else {
            return "error404";
        }
    }
        private void bntBuscar_Click_1(object sender, EventArgs e)
        {
            IPEndPoint remoto = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081);

            cliente.Connect(remoto);
            flujoDatos = cliente.GetStream();
            escritor   = new StreamWriter(flujoDatos);
            lector     = new StreamReader(flujoDatos);

            escritor.WriteLine(2);
            escritor.Flush();

            if (txtBusqueda.Text != "")
            {
                if (controlBusqueda == 1)
                {
                    escritor.WriteLine(1);
                    escritor.Flush();
                }
                else if (controlBusqueda == 2)
                {
                    escritor.WriteLine(2);
                    escritor.Flush();
                }
                escritor.WriteLine(txtBusqueda.Text);
                escritor.Flush();
                try
                {
                    //Se recibe el numero total de personas que se deben recibir en la lista
                    int totalEncontradas = Convert.ToInt32(lector.ReadLine());
                    int aux = 0;
                    while (aux < totalEncontradas)
                    {
                        string  cadena  = lector.ReadLine();
                        Persona persona = new Persona();
                        persona = Codificador.DecodificarPersona(cadena);
                        personas.Add(persona);
                        aux++;
                    }
                    lector.Close();
                    escritor.Close();
                    flujoDatos.Close();
                }
                catch (Exception)
                {
                }
                cliente.Close();
            }
            else
            {
                MessageBox.Show("Debe ingresarse datos en el campo de busqueda", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void btnEnviarDatos_Click(object sender, EventArgs e)
        {
            IPEndPoint remoto = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081);

            cliente.Connect(remoto);
            flujoDatos = cliente.GetStream();
            escritor   = new StreamWriter(flujoDatos);
            lector     = new StreamReader(flujoDatos);

            escritor.WriteLine(4);
            escritor.Flush();

            Persona personaNueva = new Persona();

            personaNueva.IdPersona = contadorPersonas;
            contadorPersonas++;
            personaNueva.Cedula         = txbCedula.Text;
            personaNueva.Nombre         = txbNombre.Text + " " + txbApellido.Text;
            personaNueva.Titulo         = txbTitulo.Text;
            personaNueva.IdTipoPersonal = ((TipoPersonal)cbxTipoContrato.SelectedItem).IdTipoPersonal;
            personaNueva.IdDepartamento = ((Departamento)cbxDepartamento.SelectedItem).IdDepartamento;
            personaNueva.IdEstado       = 1;

            escritor.WriteLine(Codificador.CodificarPersona(personaNueva));
            escritor.Flush();


            try
            {
                validez = lector.ReadLine();
            }
            catch (Exception)
            {
            }
            if (validez == "valido")
            {
                MessageBox.Show("La persona ha sido registrada exitosamente.\n" + "Se encuentra en estado 'SOLICITADO'", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (validez == "existe")
            {
                MessageBox.Show("La persona ya existe en los registros", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("No se ha podido agregar a la persona'", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            lector.Close();
            escritor.Close();
            flujoDatos.Close();
            cliente.Close();
        }
Exemple #6
0
        protected void BtnCadastrar_Click(object sender, EventArgs e)
        {
            try
            {
                // Limpa a mensagem de alerta, caso haja algum texto:
                lblMsg.Text = String.Empty;

                if (!chkTermosUso.Checked)
                {
                    lblMsg.Text = "É necessário aceitar os termos de uso!";
                    return;
                }
                Usuario usuario = new Usuario()
                {
                    Nome  = txtNome.Value.Trim(),
                    Login = txtLogin.Value.Trim(),
                    Email = txtEmail.Value.Trim(),
                    Senha = Codificador.Criptografar(txtSenha.Value)
                };
                UsuarioManager.AddUsuario(usuario);
                usuario = UsuarioManager.GetUsuarioByLogin(txtLogin.Value.Trim());
                Sessao.IniciarSessao(usuario);

                Response.Redirect("Resumo", true);
            }
            catch (Exception ex)
            {
                switch (ex.GetType().Name)
                {
                case "UsuarioNomeException":
                    txtNome.Focus();
                    break;

                case "UsuarioLoginException":
                    txtLogin.Focus();
                    break;

                case "UsuarioEmailException":
                    txtEmail.Focus();
                    break;

                case "UsuarioSenhaException":
                    txtSenha.Focus();
                    break;

                default:
                    throw ex;
                }
                lblMsg.Text = ex.Message;
            }
        }
    protected override void OnInit(EventArgs e)
    {
        HttpCookie cookie = Request.Cookies.Get("Usuario");
        if (cookie == null)
        {
            Response.Redirect("webMobile.aspx");
        }
        else
        {
            string clienteID = new Codificador().Desencriptar(cookie.Values.Get("Cliente")).Replace("\0", string.Empty);
            //Obtener el Nombre del cliente
            string nombre = new Codificador().Desencriptar(cookie.Values.Get("Nombre")).Replace("\0", string.Empty);
            string[] permisos = cookie.Values.Get("Permisos").Split(',');
            List<byte> aPermisosApagado = new List<byte>(new byte[] { 1, 3, 5, 12, 13, 14, 21, 22, 23, 24, 25, 26, 31, 32, 33, 34, 36 });
            List<Vehiculo> vehiculos;

            if (permisos[0] == "7" || permisos[1] == "1" || permisos[1] == "2")
            {
                string usuarioID = new Codificador().Desencriptar(cookie.Values.Get("UsuarioID"));
                vehiculos = AutentificacionBD.VehiculosSubCuenta(usuarioID);
            }
            else
                vehiculos = AutentificacionBD.VehiculosCliente(clienteID);

            string contenido = "";
            foreach (Vehiculo vehiculo in vehiculos)
            {
                string estado = vehiculo.Estado == 0 ? "estadoCero" : string.Empty;
                string ocultar = vehiculo.EstadoLimite == -1 ? "ui-disabled" : string.Empty;
                string clase = "";
                if (estado == "estadoCero" || ocultar == "ocultar")
                    clase = string.Format("class='{0} {1}'", ocultar, estado);
                if (vehiculo.Estado == 0)
                {
                    contenido += string.Format("<li {0} ><a data-rel=\"back\">{1}</a></li>",
                    clase, vehiculo.Descripcion);
                    //contenido += string.Format("<li {0} ><a href='vehiculo{1}' data-rel=\"back\">{3}</a></li>",
                    //clase, vehiculo.Unidad, vehiculo.Limite, vehiculo.Descripcion, vehiculo.Marca, vehiculo.Modelo);
                    //etiquetas += "<tr><td>" + vehiculo.Unidad + "</td><td>" + vehiculo.Etiquetas + "</td></tr>";
                }
                else
                {
                    contenido += string.Format("<li {0} ><a href='vehiculo{1}' data-rel=\"back\">{3}</a></li>",
                    clase, vehiculo.Unidad, vehiculo.Limite, vehiculo.Descripcion, vehiculo.Marca, vehiculo.Modelo);
                    //contenido += string.Format("<tr {0} ><td style=\"text-align: center;\"><input type='checkbox' id='{1}' data-velocidad='{2}'/></td><td>{3}</td><td>{4}</td><td>{5}</td></tr>",
                    //etiquetas += "<tr><td>" + vehiculo.Unidad + "</td><td>" + vehiculo.Etiquetas + "</td></tr>";
                }
            }
            ulUnidades.InnerHtml = contenido;
        }
    }
 public string ConsultarGeocercas()
 {
     HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         cliente = cliente.Replace("\0", string.Empty);
         List<Geocerca> geoList = GeocercasBD.ConsultarGeocercaVisualBD(cliente);
         string json = JsonConvert.SerializeObject(geoList, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
         return json;
     }
     else
         return "error404";
 }
 public string EliminaUnidadesNotificacion(List<long> notificaciones)
 {
     HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
     if (cookie != null && AutentificacionBD.VerificarToken(cookie.Values.Get("Token")))
     {
         string usuario = new Codificador().Desencriptar(cookie.Values.Get("UsuarioID"));
         usuario = usuario.Replace("\0", string.Empty);
         if (NotificacionEventosBUI.EliminaMultiples(notificaciones))
             return "ok";
         else
             return "errorBD";
     }
     return "error404";
 }
 public string ReporteNotificacionGeocerca(List<string> unidades,List<string> geocercas, long fechaInicial, long fechaFinal, int accion)
 {
     HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         DateTime fInicial = Util.FromUnixMilis(fechaInicial);
         DateTime fFinal = Util.FromUnixMilis(fechaFinal);
         List<ReporteNotificacionGeocerca> reporte = ReportesBD.ObtenerNotificacionesGeocerca(unidades, geocercas, fInicial, fFinal, accion,cliente);
         string json = JsonConvert.SerializeObject(reporte, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
         return json;
     }
     else
         return "error404";
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     HttpCookie cookie = Request.Cookies.Get("Usuario");
     if (cookie != null)
     {
         string cliente = cookie.Values.Get("Global");
         if (cliente != null)
         {
             string clienteID = new Codificador().Desencriptar(cookie.Values.Get("Global"));
             clienteID = clienteID.Replace("\0", string.Empty);
             Editbox1.Value = clienteID;//"360369693134316";
             Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "submit()", true);
         }
     }
 }
Exemple #12
0
        private void btnValidarInformacion_Click(object sender, EventArgs e)
        {
            DialogResult opcion = MessageBox.Show("Al hacer esto el proceso estará en estado 'VALIDADO'.\n" +
                                                  "Esto no significa que la persona ha sido contratada aún.\n" +
                                                  "Deberá presionar el botón 'CONTRATAR' para realizar este\n" +
                                                  "proceso, ¿Desea continuar?", "AVISO", MessageBoxButtons.YesNo);

            if (opcion == DialogResult.Yes)
            {
                IPEndPoint remoto = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081);
                cliente.Connect(remoto);
                flujoDatos = cliente.GetStream();
                escritor   = new StreamWriter(flujoDatos);
                lector     = new StreamReader(flujoDatos);

                escritor.WriteLine(3);
                escritor.Flush();

                escritor.WriteLine(2);
                escritor.Flush();

                personaSeleccionada.IdEstado = 3;
                escritor.WriteLine(Codificador.CodificarPersona(personaSeleccionada));
                escritor.Flush();

                try
                {
                    resultado = lector.ReadLine();
                }
                catch (Exception)
                {
                }

                if (resultado == "valido")
                {
                    personaSeleccionada.IdEstado = 3;
                    ActualizarInterfaz();
                }
                else
                {
                    MessageBox.Show("No se ha podido validar los datos", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                lector.Close();
                escritor.Close();
                flujoDatos.Close();
                cliente.Close();
            }
        }
Exemple #13
0
        public async Task <IActionResult> Edit(string nombreCodificador, string email, string token, [Bind("UserId,CodificadorId,FaseId")] UserFaseCodificador userFaseCodificador)
        {
            if (userFaseCodificador.UserId == null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userFaseCodificador);

                    var usuario = new User()
                    {
                        UserId = userFaseCodificador.UserId, Token = token, TokenExpiration = DateTime.Now.AddDays(2)
                    };
                    _context.Attach(usuario);
                    _context.Entry(usuario).Property(x => x.Token).IsModified           = true;
                    _context.Entry(usuario).Property(x => x.TokenExpiration).IsModified = true;

                    var codificador = new Codificador()
                    {
                        CodificadorId = userFaseCodificador.CodificadorId, NombreCodificador = nombreCodificador, Email = email
                    };
                    _context.Attach(codificador);
                    _context.Entry(codificador).Property(x => x.NombreCodificador).IsModified = true;
                    _context.Entry(codificador).Property(x => x.Email).IsModified             = true;

                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserFaseCodificadorExists(userFaseCodificador.UserId) || !UserExists(userFaseCodificador.UserId) || !CodificadorExists(userFaseCodificador.CodificadorId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["FaseId"] = new SelectList(_context.Fase, "FaseId", "NombreFase", userFaseCodificador.FaseId);
            return(View(new Models.UserFaseCodViewModel(userFaseCodificador)));
        }
    public static void updateClientType()
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");

        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string clienteID = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            string query = "SELECT * FROM  Cliente WHERE ClienteID = @idCliente";

            using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
            {
                sqlConnection.Open();
                using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
                {

                    sqlCommand.Parameters.AddWithValue("@idCliente", clienteID);
                    using (SqlDataReader sqlReader = sqlCommand.ExecuteReader())
                    {

                            if (sqlReader.Read())
                            {

                                if ((int)sqlReader["plataforma"] == 2)
                                {
                                    AppID = "ZeekTrans";

                                }
                                else if((int)sqlReader["plataforma"] == 3)
                                {
                                    AppID = "ZeekLight";
                                }
                                else {
                                    AppID = "CMovil";

                                }
                            }
                    }
                }
            }

        }
    }
 public string actualizarGeocerca(Geocerca geocerca)
 {
     HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         cliente = cliente.Replace("\0", string.Empty);
         geocerca.Cliente = cliente;
         if (geocerca.Zona == 0 && geocerca.Puntos.Count > 0) {
             geocerca.Zona = geocerca.Zona = ConversionesGeograficas.GetZoneLatLon(geocerca.Puntos[0].Longitud);
         }
         if (GeocercasBD.ActualizaGeocerca(geocerca))
         {
             return "ok";
         }
         return "errorBD";
     }
     else
         return "error404";
 }
    public string getTipoPlataforma()
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            int tipoPlataforma = AutentificacionBD.getTipoPlataforma(cliente);

            var tipos = new Dictionary<int, string>();
            tipos.Add(0, "error");
            tipos.Add(1, "flotillas");
            tipos.Add(2, "transporte");
            tipos.Add(3, "light");

            string json = JsonConvert.SerializeObject(tipos[tipoPlataforma], Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore, NullValueHandling = NullValueHandling.Ignore });
            return json;
        }
        else
            return "error404";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Obtenemos el Usuario de las cookies del navegador.
        HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");

        // Si la cookie existe y es valida (por medio del token).
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {

            // Solicitamos los datos pasados como parametros.
            string fInicial = Request.QueryString["fInicial"];
            string fFinal = Request.QueryString["fFinal"];
            string aUnidades = Request.QueryString["aUnidades"];
            string zone = Request.QueryString["zona"];

            // Si dichos datos no son nulos o vacios.
            if (!string.IsNullOrEmpty(fInicial) && !string.IsNullOrEmpty(fFinal) && !string.IsNullOrEmpty(aUnidades) && !string.IsNullOrEmpty(zone))
            {
                // Instanciamos las variables con los datos listos para consumir por nuestro codigo.
                Int64 fechaInicial = Int64.Parse(fInicial);
                Int64 fechaFinal = Int64.Parse(fFinal);
                List<string> unidades = aUnidades.Split(',').ToList();
                int zona = Int32.Parse(zone);
                string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
                DateTime fi = Util.FromUnixMilis(fechaInicial);
                DateTime ff = Util.FromUnixMilis(fechaFinal);
                List<string> unidadesSeleccionadas = new List<string>();

                foreach (string unidad in unidades)
                {
                    // En teoria solo deberia venir una unidad, pues ya las separamos en la llamada a esta pagina

                    // Llamamos al webservice para que nos entregue el diccionario con el reporte IFTA de la unidad en el rango de fechas
                    var resultado = mockupService();

                    // Llamamos al metodo que genera las tablas a partir del diccionario
                    diccionarioToHtml(unidad, resultado);
                }
            }
        }
    }
 public string ActualizarPunto(PuntoGrupo punto)
 {
     HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
     if (cookie != null && AutentificacionBD.VerificarToken(cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(cookie.Values.Get("Cliente"));
         cliente = cliente.Replace("\0", string.Empty);
         if (PuntoGrupoBD.ActualizaPunto(punto,cliente))
         {
             return "ok";
         }
         else
         {
             return "errorBD";
         }
     }
     else
     {
         return "error404";
     }
 }
Exemple #19
0
        private void btnBuscar_Click(object sender, EventArgs e)
        {
            if (txtBusqueda.Text != "")
            {
                IPEndPoint remoto = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8081);
                cliente.Connect(remoto);
                flujoDatos = cliente.GetStream();
                escritor   = new StreamWriter(flujoDatos);
                lector     = new StreamReader(flujoDatos);

                escritor.WriteLine(3);
                escritor.Flush();

                Thread.Sleep(200);
                escritor.WriteLine(1);
                escritor.Flush();

                Thread.Sleep(200);
                escritor.WriteLine(txtBusqueda.Text);
                escritor.Flush();

                try
                {
                    personaSeleccionada = Codificador.DecodificarPersona(lector.ReadLine());
                }
                catch (Exception)
                {
                }
                ActualizarInterfaz();
                lector.Close();
                escritor.Close();
                flujoDatos.Close();
                cliente.Close();
            }
            else
            {
                MessageBox.Show("Debe llenar el campo de búsqueda", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
 public string EliminarAgenda(string agendaID)
 {
     HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         cliente = cliente.Replace("\0", string.Empty);
         long token = long.Parse(new Codificador().Desencriptar(Cookie.Values.Get("Token")));
         //eliminar agenda
         int delete = ReporteAutomaticoBUI.EliminarAgenda(agendaID);
         if (delete == 1)
         {
             //eliminado correctamente
             return "ok";
         }
         else
         {
             //error al eliminar
             return "errorBD";
         }
     }
     else
         return "error404";
 }
    public string ConsultaHistoricoTransporteDebug(string unidad, long fechaInicial, long fechaFinal, int zona)
    {
        HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            DateTime fInicial = Util.FromUnixMilis(fechaInicial);
            DateTime fFinal = Util.FromUnixMilis(fechaFinal);
            Historico historico = RastreoEstaticoBD.HistoricoTransporteDebug(cliente, unidad, fInicial, fFinal);
            historico.Descripcion = AutentificacionBD.GetDescripcionUnidad(unidad);

            //enviar json
            string json = JsonConvert.SerializeObject(historico.Ubicaciones, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            return json;
        }
        else
            return "error404";
    }
    public string ConsultaHistoricoTransporte(string unidad, long fechaInicial, long fechaFinal, int zona)
    {
        HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            DateTime fInicial = Util.FromUnixMilis(fechaInicial);
            DateTime fFinal = Util.FromUnixMilis(fechaFinal);
            Historico historico = RastreoEstaticoBD.HistoricoTransporte(cliente, unidad, fInicial, fFinal);
            historico.Descripcion = AutentificacionBD.GetDescripcionUnidad(unidad);

            historico = Historico.CalcularResumenReporte(historico, Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km");
            historico.Ubicaciones = Historico.EliminarSaltosHistorico(historico.Ubicaciones, Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km");

            // Eliminamos los eventos de combustible individuales para posterior agregar los acumulados
            historico.Ubicaciones = historico.Ubicaciones.Where(u => u.Evento != 105 && u.Evento != 106).ToList();
            var eventosCombustibleAgrupados = RastreoEstaticoBD.EventosCombustible(cliente, unidad, fInicial, fFinal);
            eventosCombustibleAgrupados = agruparEventosCombustible(eventosCombustibleAgrupados, "inicios");
            historico.Ubicaciones.AddRange(eventosCombustibleAgrupados);
            // Las ubicaciones tienen su forma de compararse entre ellas y confiamos en que lo haran
            historico.Ubicaciones.Sort();

            historico.Ubicaciones.ForEach(b => b.Fecha = b.Fecha.AddHours(zona));
            //historico.Ubicaciones = historico.Resumidas;
            if (historico.Ubicaciones != null)
                historico.Ubicaciones = historico.Ubicaciones.Where(u => u.Latitud != 0 && u.Longitud != 0).ToList();
            if (Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km" & historico.Ubicaciones != null)
                historico.Ubicaciones.ForEach(b => b.Velocidad = ParseUbicacion.convertirKmhMph(b.Velocidad));
            if (historico.Ubicaciones == null)
                historico.Ubicaciones = new List<Ubicacion>();
            historico.Resumidas = null;

            //Salvar la evidencia del historico
            //RastreoEstaticoBD.SalvarEvidenciaHistorico(cliente, fInicial, fFinal);

            //enviar json
            string json = JsonConvert.SerializeObject(historico, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            return json;
        }
        else
            return "error404";
    }
    public string ConsultaHistorico(string unidad, long fechaInicial, long fechaFinal, int zona)
    {
        HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            cliente = cliente.Replace("\0", string.Empty);
            DateTime fInicial = Util.FromUnixMilis(fechaInicial);
            DateTime fFinal = Util.FromUnixMilis(fechaFinal);
            Historico historico = RastreoEstaticoBD.Historico(cliente, unidad, fInicial, fFinal);
            historico.Descripcion = AutentificacionBD.GetDescripcionUnidad(unidad);

            historico = Historico.CalcularResumenReporte(historico, Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km");
            //se eliminan los saltos
            //historico.Ubicaciones = Historico.EliminarSaltosHistorico(historico.Ubicaciones, Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km");
            historico.Ubicaciones.ForEach(b => b.Fecha = b.Fecha.AddHours(zona));
            //historico.Ubicaciones = historico.Resumidas;
            if (historico.Ubicaciones != null)
                historico.Ubicaciones = historico.Ubicaciones.Where(u => u.Latitud != 0 && u.Longitud != 0).ToList();
            if (Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km" & historico.Ubicaciones != null)
                historico.Ubicaciones.ForEach(b => b.Velocidad = ParseUbicacion.convertirKmhMph(b.Velocidad));
            if (historico.Ubicaciones == null)
                historico.Ubicaciones = new List<Ubicacion>();
            historico.Resumidas = null;

            //Salvar la evidencia del historico
            RastreoEstaticoBD.SalvarEvidenciaHistorico(cliente,fInicial,fFinal);

            //enviar json
            string json = JsonConvert.SerializeObject(historico, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            return json;
        }
        else
            return "error404";
    }
    public string ConsultaExcesos(string unidad, long fechaInicial, long fechaFinal, string velocidad, int zona)
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            cliente = cliente.Replace("\0", string.Empty);
            DateTime fInicial = Util.FromUnixMilis(fechaInicial);
            DateTime fFinal = Util.FromUnixMilis(fechaFinal);
            Historico excesosVelocidad = RastreoEstaticoBD.ExcesosVelocidad(cliente, unidad, fInicial, fFinal, Convert.ToInt32(velocidad));
            excesosVelocidad.Descripcion = AutentificacionBD.GetDescripcionUnidad(unidad);
            if (excesosVelocidad.Ubicaciones.Count > 0)
            {
                excesosVelocidad.Ubicaciones.ForEach(b => b.Fecha = b.Fecha.AddHours(zona));
                excesosVelocidad.FechaInicio = fInicial.ToString("dd/MM/yyyy hh:mm tt");
                excesosVelocidad.FechaFin = fFinal.ToString("dd/MM/yyyy hh:mm tt");
            }
            if (Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km" & excesosVelocidad.Ubicaciones.Count > 0)
                excesosVelocidad.Ubicaciones.ForEach(b => b.Velocidad = ParseUbicacion.convertirKmhMph(b.Velocidad));

            //Salvar la evidencia del historico
            RastreoEstaticoBD.SalvarEvidenciaHistorico(cliente, fInicial, fFinal);

            //Enviar Json
            string json = JsonConvert.SerializeObject(excesosVelocidad, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            return json;
        }
        else
            return "error404";
    }
 public string ConsultaEventosCombustible(string unidad, long fechaInicial, long fechaFinal, int zona)
 {
     List<Ubicacion> ubicaciones = new List<Ubicacion>();
     HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         DateTime fInicial = Util.FromUnixMilis(fechaInicial);
         DateTime fFinal = Util.FromUnixMilis(fechaFinal);
         ubicaciones = RastreoEstaticoBD.EventosCombustible(cliente, unidad, fInicial, fFinal);
         if (ubicaciones.Count > 0)
         {
             ubicaciones.ForEach(b => b.Fecha = b.Fecha.AddHours(zona));
         }
         //ubicaciones = agruparEventosCombustible(ubicaciones, "inicios");
         ubicaciones = ubicaciones.Where(u => Math.Abs(u.MagnitudEventoAcumuladoCombustible) > 2000).ToList();
         string json = JsonConvert.SerializeObject(ubicaciones, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
         return json;
     }
     else
         return "error404";
 }
        private void BtnSalvar_Click(object sender, EventArgs e)
        {
            try
            {
                Usuario usuario = new Usuario
                {
                    IdUsuario = Usuario.IdUsuario,
                    Nome      = txtNome.Text.Trim(),
                    Login     = txtLogin.Text.Trim(),
                    Email     = Usuario.Email,
                    Senha     = Codificador.Criptografar(txtSenha.Text)
                };

                if (usuario.Senha != Usuario.Senha)
                {
                    MessageBox.Show("A senha digitada não corresponde à senha cadastrada.", "Revise o preenchimento da senha", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtSenha.Focus();
                    return;
                }
                if (chkBoxAlterarSenha.Checked)
                {
                    if (!txtConfirmarSenha.Text.Equals(txtNovaSenha.Text))
                    {
                        MessageBox.Show("A nova senha digitada está diferente do campo de validação.", "As senhas digitadas não conferem", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtNovaSenha.Focus();
                        return;
                    }
                    usuario.Senha = Codificador.Criptografar(txtNovaSenha.Text);
                }

                UsuarioManager.EditUsuario(usuario);
                LoginInfo.Usuario = UsuarioManager.GetUsuarioById(usuario.IdUsuario);
                DialogResult      = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                switch (ex.GetType().Name)
                {
                case "UsuarioNomeException":
                    MessageBox.Show(ex.Message, "Revise o preenchimento do nome", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtNome.Focus();
                    break;

                case "UsuarioLoginException":
                    MessageBox.Show(ex.Message, "Revise o preenchimento do login", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtLogin.Focus();
                    break;

                case "UsuarioSenhaException":
                    MessageBox.Show(ex.Message, "Revise o preenchimento da senha", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    if (chkBoxAlterarSenha.Checked)
                    {
                        txtNovaSenha.Focus();
                    }
                    else
                    {
                        txtSenha.Focus();
                    }
                    break;

                default:
                    MessageBox.Show("Erro ao atualizar cadastro. " + Environment.NewLine + ex.Message, "Erro!!! Contate o administrador do sistema.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }
            }
        }
    /// <summary>
    /// Genera un reporte en excel de tipo Histórico
    /// </summary>
    /// <param name="reporte">Contiene la información del reporte a utilizar</param>
    /// <param name="template">Contiene la información del template a utilizar para realizar el reporte</param>
    /// <returns>Arreglo de bytes que contiene el reporte en excel.</returns>
    public static byte[] Historico(ReporteRastreo reporte, MemoryStream template, string metrica, HttpContext contexto)
    {
        using (ExcelPackage xlPackage = new ExcelPackage(new MemoryStream(), template))
        {
            ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];
            int startRow = 10, startColumn = 1; //los declaramos desde aqui por si hay cambios en el template, ajustarlos facilmente
            if (reporte.Ubicaciones.Count > 1)
                worksheet.InsertRow(startRow, reporte.Ubicaciones.Count - 1, startRow);

            worksheet.Cells[3, 5].Value = reporte.Descripcion;
            worksheet.Cells[5, 2].Value = reporte.kmAprox;
            worksheet.Cells[6, 2].Value = reporte.VMaxima;
            worksheet.Cells[7, 2].Value = reporte.VPromedio;
            worksheet.Cells[5, 4].Value = reporte.TMovimiento;
            worksheet.Cells[6, 4].Value = reporte.TMuerto;
            worksheet.Cells[5, 6].Value = reporte.FechaInicial;
            worksheet.Cells[6, 6].Value = reporte.FechaFinal;
            worksheet.Cells[9, 5].Value = metrica;
            int rowActual = startRow;
            string mapa = Resources.Reportes.aspx.Mapa;

            foreach (UbicacionReporte ubicacion in reporte.Ubicaciones)
            {
                int columna = startColumn;
                string link = string.Format("http://maps.google.com/maps?q={0}", ubicacion.Coordenadas);
                worksheet.Cells[rowActual, columna++].Value = ubicacion.Fecha;
                worksheet.Cells[rowActual, columna++].Value = ubicacion.Calle;
                worksheet.Cells[rowActual, columna++].Value = ubicacion.Colonia;
                worksheet.Cells[rowActual, columna++].Value = ubicacion.Ciudad;
                worksheet.Cells[rowActual, columna++].Value = ubicacion.Velocidad;
                worksheet.Cells[rowActual, columna++].Value = ubicacion.Evento;
                worksheet.Cells[rowActual, columna++].Value = ubicacion.Tiempo;
                if (ubicacion.Coordenadas == null)
                    ubicacion.Coordenadas = "";

                HttpCookie cookie = contexto.Request.Cookies.Get("Usuario");
                string nombre = new Codificador().Desencriptar(cookie.Values.Get("Nombre")).Replace("\0", string.Empty);
                if (nombre.Equals("<Marcela Santana> Triversa Telemetria"))
                {
                    worksheet.Cells[rowActual++, columna].Formula = string.Format("HYPERLINK(\"{0}\",\"{1}\")", link, fixCoordinatesString(ubicacion.Coordenadas, 5));
                }
                else
                {
                    worksheet.Cells[rowActual++, columna].Formula = string.Format("HYPERLINK(\"{0}\",\"{1}\")", link, mapa);
                }
            }
            return xlPackage.GetAsByteArray();
        }
    }
 public string CantidadViolacionesExcesoVelocidad()
 {
     string JSON = "";
     int cantidad = 0;
     HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         cantidad = RastreoEstaticoBD.CantidadExcesosVelocidad(cliente, DateTime.Now, DateTime.Now.AddDays(-1), 80);
     }
     JSON = JsonConvert.SerializeObject(cantidad, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
     return JSON;
 }
 public string CantidadUnidadesMovimiento()
 {
     string JSON = "";
     Dictionary<string, int> cantidades = new Dictionary<string, int>();
     cantidades["Movimiento"] = 0;
     cantidades["Detenido"] = 0;
     HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         List<Vehiculo> vehiculos = AutentificacionBD.VehiculosCliente(cliente);
         List<string> unidades = new List<string>();
         foreach (Vehiculo v in vehiculos)
         {
             unidades.Add(v.Unidad);
         }
         cantidades["Movimiento"] = RastreoEstaticoBD.CantidadUnidadesMovimiento(unidades);
         cantidades["Detenido"] = RastreoEstaticoBD.CantidadUnidadesDetenidas(unidades);
     }
     JSON = JsonConvert.SerializeObject(cantidades, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
     return JSON;
 }
 public string CantidadEstadosUnidades()
 {
     string JSON = "";
     Dictionary<string, int> cantidades = new Dictionary<string, int>();
     cantidades["OK"] = 0;
     cantidades["NEUTRAL"] = 0;
     cantidades["FALLANDO"] = 0;
     HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         cantidades["OK"] = RastreoEstaticoBD.CantidadUnidadesOK(cliente);
         cantidades["NEUTRAL"] = RastreoEstaticoBD.CantidadUnidadesNeutral(cliente);
         cantidades["FALLANDO"] = RastreoEstaticoBD.CantidadUnidadesSinReportar(cliente);
     }
     JSON = JsonConvert.SerializeObject(cantidades, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
     return JSON;
 }
    public string UltimosRangosOperacionTemperatura()
    {
        var rangosCliente = new Dictionary<string, List<double>>();
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            List<Vehiculo> vehiculos = AutentificacionBD.VehiculosCliente(cliente);
            List<string> unidades = new List<string>();
            foreach (Vehiculo v in vehiculos)
            {
                unidades.Add(v.Unidad);
            }
            foreach (string unidad in unidades)
            {
                List<double> rangosUnidad = RastreoEstaticoBD.UltimosRangosOperacionTemperatura(unidad);
                rangosCliente.Add(unidad, rangosUnidad);
            }
        }

        string JSON = JsonConvert.SerializeObject(rangosCliente, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }); ;
        return JSON;
    }
    public string UltimaUbicacionTransporteDebug(List<string> unidades, int zona)
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            List<Ubicacion> ultimaUbicacion = RastreoEstaticoBD.UltimaUbicacionTransporteDebug(unidades, cliente);
            List<Vehiculo> vehiculos = AutentificacionBD.VehiculosCliente(new Codificador().Desencriptar(Cookie.Values.Get("Cliente")));

            string timezoneBD = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(b => b.BaseUtcOffset.Hours == -10).Id;
            string timezoneCliente = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(b => b.BaseUtcOffset.Hours == zona).Id;

            foreach (Ubicacion ubicacion in ultimaUbicacion)
            {
                //fecha de ubicacion
                ubicacion.Fecha = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(ubicacion.Fecha, timezoneBD, timezoneCliente).AddHours(-1);
                //fecha geocerca
                if (ubicacion.DatosGeocerca != null)
                {
                    ubicacion.DatosGeocerca.FechaHora = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(ubicacion.DatosGeocerca.FechaHora, timezoneBD, timezoneCliente).AddHours(-1);
                    //ubicacion.DatosGeocerca.FechaHora = ubicacion.DatosGeocerca.FechaHora.AddHours(zona);
                }
                //ubicacion.Descripcion = vehiculos.Find(b => b.Unidad.Equals(ubicacion.Unidad)).Descripcion;
                ubicacion.Descripcion = vehiculos.Find(b => b.Unidad.ToLower().Equals(ubicacion.Unidad.ToLower())).Descripcion;

            }
            if (Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km")
                ultimaUbicacion.ForEach(b => b.Velocidad = ParseUbicacion.convertirKmhMph(b.Velocidad));

            string json = JsonConvert.SerializeObject(ultimaUbicacion, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            return json;
        }
        else
            return "error404";
    }
        protected void BtnEditarCadastro_Click(object sender, EventArgs e)
        {
            try
            {
                // Limpa a mensagem de alerta, caso haja algum texto:
                lblMsg.Text = String.Empty;

                Usuario usuario = new Usuario
                {
                    IdUsuario = Usuario.IdUsuario,
                    Nome      = txtNome.Value.Trim(),
                    Login     = txtLogin.Value.Trim(),
                    Email     = Usuario.Email,
                    Senha     = Codificador.Criptografar(txtSenha.Value)
                };

                if (usuario.Senha != Usuario.Senha)
                {
                    lblMsg.Text = "A senha digitada não corresponde à senha cadastrada.";
                    txtSenha.Focus();
                    return;
                }
                if (chkAlterarSenha.Checked)
                {
                    if (!txtVerificarSenha.Value.Equals(txtNovaSenha.Value))
                    {
                        lblMsg.Text = "A nova senha digitada está diferente do campo de validação.";
                        txtNovaSenha.Focus();
                        return;
                    }
                    usuario.Senha = Codificador.Criptografar(txtNovaSenha.Value);
                }

                UsuarioManager.EditUsuario(usuario);
                Usuario = UsuarioManager.GetUsuarioById(usuario.IdUsuario);
                Sessao.IniciarSessao(Usuario);
                Response.Redirect("Resumo", true);
            }
            catch (Exception ex)
            {
                switch (ex.GetType().Name)
                {
                case "UsuarioNomeException":
                    txtNome.Focus();
                    break;

                case "UsuarioLoginException":
                    txtLogin.Focus();
                    break;

                case "UsuarioSenhaException":
                    txtSenha.Focus();
                    break;

                case "UsuarioEmailException":
                default:
                    throw ex;
                }
                lblMsg.Text             = ex.Message;
                chkAlterarSenha.Checked = false;
            }
        }
    public string ConsultaRalenti(string unidad, long fechaInicial, long fechaFinal, int zona)
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            cliente = cliente.Replace("\0", string.Empty);
            DateTime fInicial = Util.FromUnixMilis(fechaInicial);
            DateTime fFinal = Util.FromUnixMilis(fechaFinal);

            //Salvar la evidencia del historico
            RastreoEstaticoBD.SalvarEvidenciaHistorico(cliente, fInicial, fFinal);

            Historico ralenti = RastreoEstaticoBD.Ralenti(cliente, unidad, fInicial, fFinal);
            ralenti.Descripcion = AutentificacionBD.GetDescripcionUnidad(unidad);
            ralenti.Ubicaciones.ForEach(b => b.Fecha = b.Fecha.AddHours(zona));

            if (ralenti.Ubicaciones.Count > 0)
            {
                List<Ubicacion> ubicacionesIdling = new List<Ubicacion>();
                Ubicacion ultimaUbicacion = ralenti.Ubicaciones[0];
                int suma = 0;
                int totalRalenti = 0;

                if (ultimaUbicacion.Evento == 15) // si son de tipo 15(ralenti viejo) aplicar este metodo de calculo
                {
                    foreach (Ubicacion ubicacionIdling in ralenti.Ubicaciones)
                    {
                        if (ubicacionIdling.Fecha.Subtract(ultimaUbicacion.Fecha).TotalMinutes < 15)
                        {
                            suma += 10;
                            ultimaUbicacion = ubicacionIdling;

                        }
                        else
                        {
                            totalRalenti += suma;
                            ultimaUbicacion.Tiempo = suma;

                            ultimaUbicacion.Fecha.AddMinutes(-suma);
                            ubicacionesIdling.Add(ultimaUbicacion);
                            ultimaUbicacion = ubicacionIdling;
                            suma = 10;
                        }
                    }
                    totalRalenti += suma;
                    ultimaUbicacion.Tiempo = suma; // check this for the 70 71
                    ultimaUbicacion.Fecha.AddMinutes(-suma);
                    ubicacionesIdling.Add(ultimaUbicacion);
                }
                else
                {
                    int tiempoAgregado = 3; // tiempo agregado (lo que decida el albitro :P ) en el que comienza el ralenti
                    bool inicio = false; // si sucedio primero 70 despues 71
                    DateTime fechaInicioRal = new DateTime(); // fecha hora que inicio ralenti
                    double tiempoRalenti = 0; // tiempo que duro en ralenti
                    suma = 0;
                    totalRalenti = 0;
                    foreach (Ubicacion ubicacionIdling in ralenti.Ubicaciones)
                    {
                        if(ubicacionIdling.Evento == 70){ // inicio ralenti en esta ubicacion

                            fechaInicioRal = ubicacionIdling.Fecha;
                            inicio = true;
                            tiempoRalenti = tiempoAgregado; // tiempo agregado
                            ultimaUbicacion = ubicacionIdling;
                        }else if(inicio){ // evento 71 y ya paso el 70
                            double tiempoDiferenciaRalenti	= ubicacionIdling.Fecha.Subtract(fechaInicioRal).TotalMinutes;
                            tiempoRalenti += tiempoDiferenciaRalenti;

                            inicio = false;
                            ultimaUbicacion.Tiempo = tiempoRalenti;
                            totalRalenti += (int)tiempoRalenti;
                            ubicacionesIdling.Add(ultimaUbicacion);
                            ultimaUbicacion = ubicacionIdling;

                        }

                    }

                }

                ralenti.TMuerto = totalRalenti.ToString();
                //ralenti.TiempoTotal = totalRalenti.ToString();
                ralenti.Ubicaciones = ubicacionesIdling;
                ralenti.FechaInicio = fInicial.ToString("dd/MM/yyyy hh:mm tt");
                ralenti.FechaFin = fFinal.ToString("dd/MM/yyyy hh:mm tt");
            }
            string json = JsonConvert.SerializeObject(ralenti, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            return json;
        }
        else
            return "error404";
    }
    public string ConsultaTiempoMuerto(string unidad, long fechaInicial, long fechaFinal, int minutos, List<PuntoGrupo> puntos,int zona)
    {
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            cliente = cliente.Replace("\0", string.Empty);
            DateTime fInicial = Util.FromUnixMilis(fechaInicial);
            DateTime fFinal = Util.FromUnixMilis(fechaFinal);
            Historico historico = RastreoEstaticoBD.Historico(cliente, unidad, fInicial, fFinal);
            historico.Descripcion = AutentificacionBD.GetDescripcionUnidad(unidad);
            string json;

            //Salvar la evidencia del historico
            RastreoEstaticoBD.SalvarEvidenciaHistorico(cliente, fInicial, fFinal);

            //List<Ubicacion> ResumenHistorico = Historico.CalcularResumenReporte(historico, Util.GetValorCookie(HttpContext.Current, "Cultura", "Culture") == "en-US").Resumidas;
            Historico resumen = Historico.CalcularResumenReporte(historico, Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km");
            if (resumen != null && resumen.Resumidas != null && resumen.Resumidas.Count > 0)
            {
                resumen.Ubicaciones = resumen.Resumidas.FindAll(b => b.Tiempo >= minutos);
                resumen.Ubicaciones.ForEach(b => b.Fecha = b.Fecha.AddHours(zona));
                //si se cuenta con mas de un punto, entonces validar la posicion con los puntos.
                if (puntos != null && puntos.Count > 0)
                {
                    List<Ubicacion> fueraDePuntos = new List<Ubicacion>();
                    //each para comparar las posiciones de los puntos con la ubicacion
                    foreach (Ubicacion ubicacion in resumen.Ubicaciones)
                    {
                        //bool dentro = true;
                        int fuera = 0;
                        foreach (PuntoGrupo punto in puntos)
                        {
                            double[] coordenadasUTMpunto = ConversionesGeograficas.LatLonToUTMXY(punto.x, punto.y);
                            double[] coordenadasUTMUbi = ConversionesGeograficas.LatLonToUTMXY(ubicacion.Latitud, ubicacion.Longitud);
                            double distancia = Math.Sqrt(Math.Pow((coordenadasUTMUbi[0] - coordenadasUTMpunto[0]), 2) + Math.Pow((coordenadasUTMUbi[1] - coordenadasUTMpunto[1]), 2));
                            if (distancia > 200)
                            {
                                fuera++;
                            }
                        }
                        if (fuera == puntos.Count)
                        {
                            fueraDePuntos.Add(ubicacion);
                        }
                    }
                    resumen.Ubicaciones = fueraDePuntos;

                    //enviar json
                    json = JsonConvert.SerializeObject(resumen, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });

                }
                else
                {
                    //Enviar json
                    json = JsonConvert.SerializeObject(resumen, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
                }
            }
            else
            {
                //Enviar Json
                json = JsonConvert.SerializeObject(historico, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
            }

            //Enviar Json
            return json;
        }
        else
            return "error404";
    }
 public string CapacidadCombustibleMax(string unidad)
 {
     string JSON = "";
     int cantidad = 0;
     HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
     if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
     {
         string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
         cantidad = RastreoEstaticoBD.CapacidadCombustibleMax(unidad);
     }
     JSON = JsonConvert.SerializeObject(cantidad, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
     return JSON;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        int EVENTO_ON = 3;
        int EVENTO_OFF = 4;
        HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string fInicial = Request.QueryString["fInicial"];
            string fFinal = Request.QueryString["fFinal"];
            string aUnidades = Request.QueryString["aUnidades"];
            string zone = Request.QueryString["zona"];

            if (!string.IsNullOrEmpty(fInicial) && !string.IsNullOrEmpty(fFinal) && !string.IsNullOrEmpty(aUnidades) && !string.IsNullOrEmpty(zone))
            {
                Int64 fechaInicial = Int64.Parse(fInicial);
                Int64 fechaFinal = Int64.Parse(fFinal);
                List<string> unidades = aUnidades.Split(',').ToList();
                int zona = Int32.Parse(zone);

                string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
                DateTime fi = Util.FromUnixMilis(fechaInicial).AddHours(zona);
                DateTime ff = Util.FromUnixMilis(fechaFinal).AddHours(zona);
                List<string> unidadesSeleccionadas = new List<string>();
                List<ReporteOnOff> reportes = new List<ReporteOnOff>();

                foreach (string unidad in unidades)
                {
                    Historico historico = RastreoEstaticoBD.Historico(cliente, unidad, fi, ff);
                    historico.Descripcion = AutentificacionBD.GetDescripcionUnidad(unidad);
                    historico.Ubicaciones.ForEach(b => b.Fecha = b.Fecha.AddHours(zona));
                    historico = Historico.CalcularResumenReporte(historico, Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km");
                    historico.Ubicaciones = historico.Resumidas;

                    if (historico.Ubicaciones != null)
                    {
                        unidadesSeleccionadas.Add(historico.Descripcion);
                        historico.Ubicaciones = historico.Ubicaciones.Where(u => u.Latitud != 0 && u.Longitud != 0 && (u.Evento == EVENTO_ON || u.Evento == EVENTO_OFF)).ToList();
                        //historico.Ubicaciones = historico.Ubicaciones.Where(u => (u.Evento == EVENTO_ON || u.Evento == EVENTO_OFF) ).ToList();
                    }
                    if (Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km" && historico.Ubicaciones != null)
                        historico.Ubicaciones.ForEach(b => b.Velocidad = ParseUbicacion.convertirKmhMph(b.Velocidad));
                    if (historico.Ubicaciones == null)
                        historico.Ubicaciones = new List<Ubicacion>();
                    ReporteOnOff reporte = new ReporteOnOff();
                    ReporteOnOff reporteTmp = new ReporteOnOff();
                    Ubicacion ubicacionAnterior = new Ubicacion();
                    //bool bReporteExistente = false;
                    //bool firstCompleteEvent = false; // after the first time i can do the same thing over and over again.
                    bool firstTimeCicle=true;
                    System.Diagnostics.Debug.WriteLine("reporte vehiculo  " + historico.Ubicaciones.Count);
                    foreach (Ubicacion ubicacion in historico.Ubicaciones)
                    {
                        if (firstTimeCicle) // primera vez solo registrar el inicio de un on-off
                        {
                            reporte.FechaOn = ubicacion.Fecha;
                            reporte.Vehiculo = historico.Descripcion;
                            reporte.VehiculoID = unidad;
                            reporte.Distancia = ubicacion.DistanciaEntrePuntoInicial;
                            reporte.CoordenadasON = ubicacion.Latitud + "," + ubicacion.Longitud;
                            ubicacionAnterior = ubicacion;
                            firstTimeCicle = false;

                        }else{ // consecuentemente se tiene
                            reporte.FechaOn = ubicacionAnterior.Fecha;  // posicion anterior
                            reporte.Vehiculo = historico.Descripcion;
                            reporte.VehiculoID = unidad;
                            reporte.Distancia = ubicacionAnterior.DistanciaEntrePuntoInicial;
                            reporte.CoordenadasON = ubicacionAnterior.Latitud + "," + ubicacionAnterior.Longitud;

                            //calcular distancia
                            reporte.Distancia = ubicacion.DistanciaEntrePuntoInicial - reporte.Distancia; // ayuda a mi mismo acomulado menos acumalado siguiente da lo de este
                            //ya existia un reporte previamente
                            reporte.FechaOff = ubicacion.Fecha;
                            //asignar coordenadas
                            reporte.CoordenadasOFF = ubicacion.Latitud + "," + ubicacion.Longitud;
                            //cambiar bandera y reiniciar valor
                            if (reporte.Distancia > 20)
                            {
                                reportes.Add(reporte);
                            }
                            ubicacionAnterior = ubicacion;
                            reporte = new ReporteOnOff();
                        }
                    }
                }

                aVehiculos.InnerText = string.Join(",", unidadesSeleccionadas.ToArray());
                spanFechaInicial.InnerText = fi.ToString();
                spanFechaFinal.InnerText = ff.ToString();

                resumenCaption.InnerHtml = "<h1>"+ Resources.Reportes.aspx.ReporteOnOff+"</h1>";
                resumenCaption.InnerHtml += "<span>" + Resources.Reportes.aspx.Vehiculos + ": </span>" + string.Join(",", unidadesSeleccionadas.ToArray()) + "<br/>";
                resumenCaption.InnerHtml += "<span>" + Resources.Reportes.aspx.FechaInicial + ": </span>" + fi.ToString() + "<br/>";
                resumenCaption.InnerHtml += "<span>" + Resources.Reportes.aspx.FechaFinal + ": </span>" + ff.ToString() + "<br/>";

                reportes = reportes.OrderBy(x => x.Vehiculo).ThenBy(x => x.FechaOn).ToList();
                string rows = "";
                bool english = false;
                if (Util.GetValorCookie(HttpContext.Current, "Cultura", "Metric") != "Km")
                {
                    english = true;
                }
                foreach (ReporteOnOff reporte in reportes)
                {
                    reporte.Distancia = reporte.Distancia / 1000;
                    if(english)
                    {
                        reporte.Distancia = reporte.Distancia * 0.621371192;
                    }
                    rows += "<tr>" +
                                "<td><span>" + reporte.Vehiculo + "</span</td>" +
                                "<td><span>" + reporte.FechaOn.ToString() + "</span</td>" +
                                "<td class='coordenadaON' data-coordenada='"+reporte.CoordenadasON+"'><span>Direccion ON</span</td>" +
                                "<td><span>" + reporte.FechaOff + "</span</td>" +
                                "<td class='coordenadaOFF' data-coordenada='"+reporte.CoordenadasOFF+"'><span>Direccion OFF</span</td>" +
                                "<td><span>" + Math.Round(reporte.Distancia, 2) + "</span</td>" +
                            "</tr>";
                }
                ubicacionesRows.InnerHtml = rows;
            }

        }
        else {
            //No esta en sesion, por lo cual eliminar cookie y redirijir a login
        }
    }
    public string CapacidadCombustibleTanques(string unidad)
    {
        string JSON = "";
        List<int> cantidades = new List<int>();
        string[] res = new string[2];
        HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies.Get("Usuario");
        if (Cookie != null && AutentificacionBD.VerificarToken(Cookie.Values.Get("Token")))
        {
            string cliente = new Codificador().Desencriptar(Cookie.Values.Get("Cliente"));
            cantidades = RastreoEstaticoBD.CapacidadesTanquesCombustible(unidad);

        }
        JSON = JsonConvert.SerializeObject(cantidades, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
        res[0] = JSON;
        res[1] = unidad;
        string resS = JsonConvert.SerializeObject(res, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore });
        return resS;
    }