Пример #1
0
 public Evento(String nombre, String descripcion, float costo, Ubicacion ubicacion, TipoEvento tipoEvento, Horario horario)
     : base()
 {
     this.nombre = nombre;
     this.descripcion = descripcion;
     this.costo = costo;
     this.ubicacion = ubicacion;
     this.tipoEvento = tipoEvento;
     this.horario = horario;
 }
Пример #2
0
 public Evento( String nombre, String descripcion, float costo, Boolean estado, Ubicacion ubicacion, Categoria categoria, TipoEvento tipoEvento, Horario horario)
     : base()
 {
     this.nombre = nombre;
     this.descripcion = descripcion;
     this.costo = costo;
     this.ubicacion = ubicacion;
     this.categoria = categoria;
     this.tipoEvento = tipoEvento;
     this.horario = horario;
     this.estado = estado;
 }
Пример #3
0
 public Evento(int id, String nombre, String descripcion, float costo, Boolean estado, Persona persona, Ubicacion ubicacion, Categoria categoria, TipoEvento tipoEvento, Horario horario)
 {
     this.id = id;
     this.nombre = nombre;
     this.descripcion = descripcion;
     this.persona = persona;
     this.costo = costo;
     this.ubicacion = ubicacion;
     this.categoria = categoria;
     this.tipoEvento = tipoEvento;
     this.horario = horario;
     this.estado = estado;
 }
Пример #4
0
        public static void Persistir(NVEntities db, List<UbicacionPicking> ubicaciones)
        {
            // Esta es la parte que no vamos a poder testar
            /*
             * Si Id = 0 hay que insertar una nueva db.Ubicaciones.add, copiando pasillo, fila, columna de CopiaId
             * Si cantidad es distinto a cantidadNueva hay que modificar y poner estado nuevo, NºOrdenLinPedidoVta
             * y PedidoVta (ojo que el pedido hay que leerlo de db.LinPedidoVtas).
             * */

            foreach(UbicacionPicking ubicacion in ubicaciones)
            {
                Ubicacion ubicacionOriginal;

                // Error cuando llega con Id == 0 y CopiaId == 0. Escribir test que falle y poner
                // un if (ubicacion.Id == 0 && ubicacion.CopiaId == 0), que inserte la ubicación.
                // Lo que está ahora irá en el else de ese if
                if (ubicacion.Id == 0) // && ubicacion.CopiaId != 0
                {
                    ubicacionOriginal = db.Ubicaciones.SingleOrDefault(u => u.NºOrden == ubicacion.CopiaId);
                    Ubicacion nuevaUbicacion = new Ubicacion
                    {
                        Almacén = ubicacionOriginal.Almacén,
                        Cantidad = ubicacion.CantidadNueva,
                        Empresa = ubicacionOriginal.Empresa,
                        Estado = ubicacion.EstadoNuevo,
                        Número = ubicacion.Producto
                    };
                    if (ubicacion.EstadoNuevo != Constantes.Ubicaciones.PENDIENTE_UBICAR)
                    {
                        nuevaUbicacion.Pasillo = ubicacionOriginal.Pasillo;
                        nuevaUbicacion.Fila = ubicacionOriginal.Fila;
                        nuevaUbicacion.Columna = ubicacionOriginal.Columna;
                    };
                    db.Ubicaciones.Add(nuevaUbicacion);
                } else if (ubicacion.Cantidad != ubicacion.CantidadNueva)
                {
                    ubicacionOriginal = db.Ubicaciones.SingleOrDefault(u => u.NºOrden == ubicacion.Id);
                    LinPedidoVta lineaVenta = db.LinPedidoVtas.SingleOrDefault(l => l.Nº_Orden == ubicacion.LineaPedidoVentaId);
                    if (lineaVenta != null)
                    {
                        ubicacionOriginal.PedidoVta = lineaVenta.Número;
                        ubicacionOriginal.NºOrdenVta = ubicacion.LineaPedidoVentaId;
                    }
                    ubicacionOriginal.Estado = ubicacion.EstadoNuevo;
                    ubicacionOriginal.Cantidad = ubicacion.CantidadNueva;
                }
            }
        }
Пример #5
0
        public static void InsertUbicacion(Ubicacion objAcceso)
        {
            try
            {
                UbicacionTableAdapter localAdapter = new UbicacionTableAdapter();
                object resutl = localAdapter.InsertUbicacionEnvio(
                    objAcceso.UsuarioId,
                    objAcceso.Descripcion,
                    objAcceso.Latitud,
                    objAcceso.Longitud);

                log.Debug("Se insertó la Ubicacion con el usuario Id: " + objAcceso.UsuarioId);
            }
            catch (Exception q)
            {
                log.Error("Ocurrió un error al insertar el Area", q);
                throw q;
            }
        }
        public void eliminarUbicacionPorPublicacion(Ubicacion ubi, Publicacion publi,
                                                    SqlTransaction transaction)
        {
            string query = "DELETE FROM [TheBigBangQuery].[Ubicaciones_publicacion] " +
                           "WHERE [ubpu_id_ubicacion] = '" + ubi.id.ToString() + "' AND [ubpu_id_publicacion] = '" + publi.id.ToString() + "'";

            try
            {
                SqlCommand command = new SqlCommand();

                command.Transaction = transaction;
                command.CommandText = query;

                DatabaseConection.executeQuery(command).Close();
            }
            catch (Exception ex) {
                throw new SqlDeleteException("Error al borrar ubicacion", SqlDeleteException.CODE_UBICACION);
            }
        }
Пример #7
0
        public ActionResult SetUbicacion(int markerIndex, double?latitud, double?longitud)
        {
            if (longitud == null || longitud == -1)
            {
                longitud = Ubicacion.DefaultLongitud;
            }

            if (latitud == null || latitud == -1)
            {
                latitud = Ubicacion.DefaultLatitud;
            }

            Ubicacion model = new Ubicacion()
            {
                MarkerIndex = markerIndex, Longitud = longitud, Latitud = latitud
            };

            return(PartialView("_SetUbicacion", model));
        }
Пример #8
0
        protected void lnk_change_status_click(object sender, CommandEventArgs args)
        {
            try
            {
                int Id = 0;
                int.TryParse(args.CommandName, out Id);
                bool status = false;
                bool.TryParse(args.CommandArgument.ToString(), out status);

                Ubicacion o = new Ubicacion();
                o.Id = Id;
                CatalogCtrl.UbicacionChangeStatus(o, status);
                fillCatalog(CatalogCtrl.UbicacionfillEvenInactive());
            }
            catch (Exception e)
            {
                ((MstCasc)this.Master).setError = e.Message;
            }
        }
Пример #9
0
        public HttpResponseMessage Put(FormDataCollection form)
        {
            Ubicacion ubicacion = new Ubicacion();

            ubicacion.Provincia1  = form.Get("Provincia");
            ubicacion.Canton1     = form.Get("Canton");
            ubicacion.Distrito1   = form.Get("Distrito");
            ubicacion.Barrio1     = form.Get("Barrio");
            ubicacion.OtrasSenas1 = form.Get("OtrasSenas");
            ubicacion.ID1         = Convert.ToInt32(form.Get("ID"));

            string[] respuesta = new string[2];
            respuesta[0] = ubicacion.Insert_Ubicacion();
            respuesta[1] = form.Get("ID");

            HttpResponseMessage response = Request.CreateResponse <string[]>(HttpStatusCode.Created, respuesta);

            return(response);
        }
Пример #10
0
        public static Ubicacion Buscar(int id)
        {
            Contexto  contexto  = new Contexto();
            Ubicacion Ubicacion = new Ubicacion();

            try
            {
                Ubicacion = contexto.Ubicacion.Find(id);
            }
            catch
            {
                throw;
            }
            finally
            {
                contexto.Dispose();
            }
            return(Ubicacion);
        }
Пример #11
0
        public static bool Modificar(Ubicacion Ubicacion)
        {
            bool paso = false;

            Contexto contexto = new Contexto();

            try
            {
                contexto.Entry(Ubicacion).State = EntityState.Modified;
                paso = (contexto.SaveChanges() > 0);

                contexto.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            return(paso);
        }
Пример #12
0
        private List <Ubicacion> FromRowsToUbicaciones(DataTable table)
        {
            List <Ubicacion> ubicaciones = new List <Ubicacion>();

            foreach (DataRow row in table.Rows)
            {
                Ubicacion ubicacion = new Ubicacion();

                ubicacion.Fila        = Convert.ToChar(row["Ubicacion_Fila"]);
                ubicacion.Asiento     = Convert.ToInt32(row["Ubicacion_Asiento"]);
                ubicacion.Precio      = Convert.ToInt32(row["Ubicacion_Precio"]);
                ubicacion.Descripcion = Convert.ToString(row["Ubicacion_Descripcion"]);
                ubicacion.Publicacion = Convert.ToInt64(row["Ubicacion_Publicacion"]);

                ubicaciones.Add(ubicacion);
            }

            return(ubicaciones);
        }
        /// <summary>
        /// Clic en el botón de eliminar ubicación.
        /// </summary>
        private void btnEliminar_Click(object sender, EventArgs e)
        {
            try
            {
                if (Mensaje.mostrarMensajeConfirmacion("MensajeUbicacionEliminacion") == DialogResult.Yes)
                {
                    Ubicacion ubicacion = (Ubicacion)dgvUbicaciones.SelectedRows[0].DataBoundItem;

                    _mantenimiento.eliminarUbicacion(ubicacion);

                    dgvUbicaciones.Rows.Remove(dgvUbicaciones.SelectedRows[0]);
                    Mensaje.mostrarMensaje("MensajeUbicacionConfirmacionEliminacion");
                }
            }
            catch (Excepcion ex)
            {
                ex.mostrarMensaje();
            }
        }
        public async Task <IHttpActionResult> PutUbicacion(int id, Ubicacion ubicacion)
        {
            if (ubicacion == null)
            {
                return(BadRequest("El modelo esta vacio"));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (ubicacion.Id == 0 && id > 0)
            {
                ubicacion.Id = id;
            }

            db.Entry(ubicacion).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (Exception e)
            {
                var a = e;
            }
            //catch (DbUpdateConcurrencyException)
            //{
            //    if (!UbicacionExists(id))
            //    {
            //        return NotFound();
            //    }
            //    else
            //    {
            //        throw;
            //    }
            //}
            Ubicacion u = db.Ubicaciones.Find(id);

            return(Ok(u));
            //return StatusCode(HttpStatusCode.NoContent);
        }
Пример #15
0
        public Ubicacion getUbicacionporDescripcion(string ssDescripcion)
        {
            Ubicacion oUbicacion = new Ubicacion();
            DataSet   ds         = new DataSet();

            Database      db         = EnterpriseLibraryContainer.Current.GetInstance <Database>("Inventario");
            StringBuilder sqlCommand = new StringBuilder();

            sqlCommand.AppendLine("SELECT idUbicacion ");
            sqlCommand.AppendLine("		, Descripcion ");
            sqlCommand.AppendLine("		, idRegion ");
            //sqlCommand.AppendLine("		, Estatus ");
            sqlCommand.AppendLine("FROM Ubicacion ");
            sqlCommand.AppendLine("WHERE Estatus = 1 ");
            sqlCommand.AppendLine("AND   Descripcion = @Descripcion");

            DbCommand selectCommand = null;

            selectCommand = db.GetSqlStringCommand(sqlCommand.ToString());
            db.AddInParameter(selectCommand, "@Descripcion", DbType.String, ssDescripcion);

            try
            {
                ds = db.ExecuteDataSet(selectCommand);
            }
            catch (DataException ex)
            {
                throw ex;
            }

            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    oUbicacion.idUbicacion = Convert.ToInt32(dr["idUbicacion"]);
                    oUbicacion.descripcion = dr["Descripcion"].ToString();
                    oUbicacion.idRegion    = Convert.ToInt32(dr["idRegion"]);
                    //oUbicacion.estatus = Convert.ToBoolean(dr["Estatus"]);
                }
            }
            return(oUbicacion);
        }
Пример #16
0
        private Perfil ObtenerMiPerfil()
        {
            Perfil p = new Perfil();

            con.Open();
            SqlCommand cmd = new SqlCommand("USP_OBTENER_PERFIL_INSTRUCTOR", con);

            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@CODUSU", (((Usuario)Session["usuario"]).codigo));
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                p.codigo       = reader.GetInt32(0);
                p.nombres      = reader.GetString(1);
                p.apPaterno    = reader.GetString(2);
                p.apMaterno    = reader.GetString(3);
                p.especialidad = reader.GetString(4);
                p.sobreMi      = reader.GetString(5);
                p.cv           = reader.GetString(6);
                p.calificacion = reader.GetInt32(7);
                p.verificado   = reader.GetBoolean(8);
                p.conectado    = reader.GetBoolean(9);

                Ubicacion u = new Ubicacion();
                u.latitud       = reader.GetDecimal(10);
                u.longitud      = reader.GetDecimal(11);
                p.idPerfil      = reader.GetInt32(12);
                p.ubicacion     = u;
                p.transacciones = ListadoTransacciones(con, p.codigo);
                p.reseñas       = ListadoResenas(con, p.idPerfil);
                p.cursos        = ListadoPreferenciaEnsenanza(con, p.codigo);
                p.horarios      = ListadoHorarios(con, p.codigo);
                p.citas         = ListadoMisCitas(con, ((Usuario)Session["usuario"]).codigo);
                int idUsuario = ((Usuario)Session["usuario"]).codigo;
            }

            con.Close();
            reader.Close();

            return(p);
        }
Пример #17
0
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            if (!checkFields())
            {
                MessageBox.Show("Por favor llene todas las entradas");
                return;
            }

            using (ActivosEntities db = new ActivosEntities())
            {
                Ubicacion ubicacion = new Ubicacion
                {
                    Codigo_Ubicacion = Id,
                    Descripcion      = tbxDescripcion.Text,
                    Direccion        = tbxDireccion.Text,
                    Edificio         = tbxEdificio.Text,
                    Estado           = cbxEstado.SelectedItem.ToString()
                };

                if (Id != 0)
                {
                    var ubInDb = db.Ubicacion.FirstOrDefault(ubi => ubi.Codigo_Ubicacion == ubicacion.Codigo_Ubicacion);

                    if (ubInDb != null)
                    {
                        db.Entry(ubInDb).State    = System.Data.Entity.EntityState.Detached;
                        db.Entry(ubicacion).State = System.Data.Entity.EntityState.Modified;
                    }

                    MessageBox.Show("La ubicacion ha sido modificado exitosamente.");
                }
                else
                {
                    db.Ubicacion.Add(ubicacion);
                    MessageBox.Show("La ubicacion ha sido creado exitosamente.");
                }

                db.SaveChanges();

                Close();
            }
        }
Пример #18
0
        public int ActualizaUbicacion(int i_idUbicacion, string s_descripcion, int i_idRegion, string s_estatus)
        {
            Ubicacion   objUbicacion = new Ubicacion();
            DLUbicacion odlUbicacion = new DLUbicacion();

            objUbicacion.idUbicacion = i_idUbicacion;
            objUbicacion.descripcion = s_descripcion;
            objUbicacion.idRegion    = i_idRegion;
            objUbicacion.estatus     = s_estatus;

            try
            {
                odlUbicacion.UpdateUbicacion(ref objUbicacion);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(objUbicacion.idUbicacion);
        }
Пример #19
0
        public void Buscarbutton_Click(object sender, EventArgs e)
        {
            Ubicacion Ubicaciones = new Ubicacion();

            int.TryParse(IDnumericUpDown.Text, out int id);

            Limpiar();

            Ubicaciones = UbicacionesBLL.Buscar(id);

            if (Ubicaciones != null)
            {
                MessageBox.Show("Producto Encontrado.");
                LlenaCampo(Ubicaciones);
            }
            else
            {
                MessageBox.Show("Producto no encontrado.");
            }
        }
Пример #20
0
        private void InicioTipoMantenimiento()
        {
            switch (TipoMnt)
            {
            case TipoMantenimiento.Nuevo:
                pkIdEntidad.EditValue = IdEntidadMnt;
                CargarReferencias();
                ValoresPorDefecto();
                btnEliminar.Enabled   = false;
                btnActualizar.Enabled = false;
                UbicacionMnt          = new Ubicacion();
                break;

            case TipoMantenimiento.Modificar:
                pkIdEntidad.EditValue = IdEntidadMnt;
                CargarReferencias();
                TraerDatos();
                break;
            }
        }
Пример #21
0
        public void deleteUbicacion(Ubicacion item)
        {
            try
            {
                using (var db = new PROYECTOVUELO02Entities1())
                {
                    Ubicacion obj = db.Ubicacion.Where(x => x.id_ == item.id_).FirstOrDefault();

                    if (obj != null)
                    {
                        db.Ubicacion.Remove(obj);
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("Verifica los datos a eliminar");
            }
        }
Пример #22
0
        public static Evento MapModel(EventoEntity entidad)
        {
            Ubicacion ubicacion = new Ubicacion()
            {
                Latitud  = entidad.Latitud,
                Longitud = entidad.Longitud
            };
            Frecuencia frecuencia = new Frecuencia(ObtenerDiasFrecuencia(entidad.Frecuencia));

            return(new Evento()
            {
                EventoId = entidad.EventoId,
                FechaInicio = entidad.FechaInicio,
                Nombre = entidad.Nombre,
                UsuarioId = entidad.UsuarioId,
                Ubicacion = ubicacion,
                Formalidad = ObtenerFormalidadEnum(entidad.Formalidad),
                Frecuencia = frecuencia
            });
        }
        public IActionResult Create(string ubicacion)
        {
            if (!string.IsNullOrEmpty(ubicacion))
            {
                var persistencia = new Ubicacion()
                {
                    Nombre = ubicacion
                };
                _service.Create(persistencia);

                TempData["created"] = "Registro Creado Correctamente";
                return(RedirectToAction("Index"));
            }

            else
            {
                TempData["created"] = "Error";
                return(RedirectToAction("Index"));
            }
        }
Пример #24
0
        public ActionResult Modificacion(Ubicacion ubicacion)
        {
            ISession session = NHibernateHelper.GetCurrentSession();

            try
            {
                using (ITransaction tx = session.BeginTransaction())
                {
                    ubicacion.FechaModificacion = DateTime.Now;
                    session.Update(ubicacion);
                    tx.Commit();
                }
            }
            finally
            {
                NHibernateHelper.CloseSession();
            }

            return(RedirectToAction("Index"));
        }
Пример #25
0
 public void saveUbicacion(Ubicacion ubicacion)
 {
     try
     {
         this.spExecute("ESECUELE.saveUbicacion", new List <SqlParameter>()
         {
             new SqlParameter("@publicacion", ubicacion.publicacion),
             new SqlParameter("@filas", ubicacion.filas),
             new SqlParameter("@asientos", ubicacion.asientos),
             new SqlParameter("@precio", ubicacion.precio),
             new SqlParameter("@sinNumerar", ubicacion.sinNumerar),
             new SqlParameter("@ocupados", ubicacion.ocupados),
             new SqlParameter("@tipo", ubicacion.tipo.id)
         });
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Пример #26
0
        /// <summary>
        /// Registrar una ubicación de un ATM.
        /// </summary>
        /// <param name="u">Objeto Ubicacion con los datos de la ubicación</param>
        public void agregarUbicacion(ref Ubicacion u)
        {
            SqlCommand comando = _manejador.obtenerProcedimiento("InsertUbicacion");

            _manejador.agregarParametro(comando, "@oficina", u.Oficina, SqlDbType.VarChar);
            _manejador.agregarParametro(comando, "@direccion", u.Direccion, SqlDbType.VarChar);
            _manejador.agregarParametro(comando, "@direccion_exacta", u.Direccion_exacta, SqlDbType.VarChar);
            _manejador.agregarParametro(comando, "@provincia", u.Provincia, SqlDbType.TinyInt);

            try
            {
                u.ID = (short)_manejador.ejecutarEscalar(comando);
                comando.Connection.Close();
            }
            catch (Exception)
            {
                comando.Connection.Close();
                throw new Excepcion("ErrorUbicacionRegistro");
            }
        }
Пример #27
0
 public UbicacionViewModel(Ubicacion ubicacion)
 {
     if (ubicacion != null)
     {
         this.UbicacionId  = ubicacion.UbicacionId;
         this.PublicKey    = ubicacion.PublicKey;
         this.Calle        = ubicacion.Calle;
         this.NoExterior   = ubicacion.NoExterior;
         this.NoInterior   = ubicacion.NoInterior;
         this.Colonia      = ubicacion.Colonia;
         this.Localidad    = ubicacion.Localidad;
         this.Municipio    = ubicacion.Municipio;
         this.Estado       = ubicacion.Estado;
         this.Pais         = ubicacion.Pais;
         this.CodigoPostal = ubicacion.CodigoPostal;
         this.Referencia   = ubicacion.Referencia;
         this.Ordinal      = ubicacion.Ordinal;
         //this.Status = ubicacion.Status;
     }
 }
Пример #28
0
        protected void btnBUscar_Click(object sender, EventArgs e)
        {
            UbicacionServiceClient proxy = new UbicacionServiceClient();
            Ubicacion ubi = new Ubicacion();

            try
            {
                GMap1.reset();
                ubi = proxy.listaUbicacion(TextBox1.Text);
                GLatLng milocacion = new GLatLng(ubi.latitud, ubi.longitud);
                GMap1.setCenter(milocacion, 14);

                XPinLetter Xpin = new XPinLetter(PinShapes.pin_star, "H", Color.Blue, Color.White, Color.Chocolate);
                GMap1.Add(new GMarker(milocacion, new GMarkerOptions(new GIcon(Xpin.ToString(), Xpin.Shadow()))));
            }
            catch (Exception ex)
            {
                Label2.Text = ex.Message;
            }
        }
Пример #29
0
        public void ActualizarUbicacion(Ubicacion item)
        {
            try
            {
                using (var db = new PROYECTOVUELO03Entities())
                {
                    Ubicacion obj = db.Ubicacion.Where(x => x.Id_Ubicacion == item.Id_Ubicacion).FirstOrDefault();

                    if (obj != null)
                    {
                        obj.nombre_ubicacion = item.nombre_ubicacion;
                        obj.id_avion         = item.id_avion;
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception)
            {
                throw new Exception("Verifica los datos a actualizar");
            }
        }
Пример #30
0
        private Bulto ParseBulto(dsAlmacen.BULTOSRow row)
        {
            Bulto bulto = Bulto.Parse(row);

            dsAlmacen.ARTICULOSDataTable dtArticulo = new dsAlmacen.ARTICULOSDataTable();
            dtArticulo.FillByORACLE_CODE(row.ARTICULO);
            if (dtArticulo.Count == 1)
            {
                bulto.Articulo = Articulo.Parse(dtArticulo[0]);
            }

            dsAlmacen.UBICACIONESDataTable dtUbicacion = new dsAlmacen.UBICACIONESDataTable();
            dtUbicacion.FillByCODUBI(bulto.Ubicacion.Codigo);

            if (dtUbicacion.Count == 1)
            {
                bulto.Ubicacion = Ubicacion.Parse(dtUbicacion[0]);
            }

            return(bulto);
        }
Пример #31
0
        public string actualizaUbicacion(Ubicacion ubicacion)
        {
            string rutaCola = @".\private$\proyecto";

            if (!MessageQueue.Exists(rutaCola))
            {
                MessageQueue.Create(rutaCola);
            }

            MessageQueue cola    = new MessageQueue(rutaCola);
            Message      mensaje = new Message();

            mensaje.Label = "Registro la intencion";
            mensaje.Body  = new Ubicacion()
            {
                idEnvio = ubicacion.idEnvio, latitud = ubicacion.latitud, longitud = ubicacion.longitud
            };
            cola.Send(mensaje);

            return(ubicacion.idEnvio);
        }
        public SeleccionAsiento(Ubicaciones formUbicaciones, Ubicacion ubicacion, Compra compra)
        {
            InitializeComponent();

            this.compra          = compra;
            this.ubicacion       = ubicacion;
            this.formUbicaciones = formUbicaciones;

            Servidor servidor = Servidor.getInstance();
            //Aca hay que buscar en la base todas las filas que tienen asientos disponibles para la publicacion seleccionada

            List <Char> lista = new List <Char>();

            lista      = formUbicaciones.asientosDisponibles.Select(a => a.Fila).ToList();
            this.filas = new HashSet <Char>(lista);

            foreach (char f in filas)
            {
                comboBoxFila.Items.Add(f);
            }
        }
Пример #33
0
        /// <summary>
        /// Metodo que obtiene una ubicacion usando la IP.
        /// </summary>
        /// (sflores)
        /// <param></param>
        /// <returns>Ubiczcion</returns>
        public static Ubicacion ubicacion( )
        {
            var        ip      = getUserIP( );
            var        url     = "http://freegeoip.net/xml/" + ip;
            WebRequest request = WebRequest.Create(url);

            using (WebResponse response = ( HttpWebResponse )request.GetResponse( ))
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream( ), Encoding.UTF8))
                {
                    DataSet dsResult = new DataSet( );
                    dsResult.ReadXml(reader);

                    DataRow   row = dsResult.Tables["response"].Select( )[0];
                    Ubicacion u   = new Ubicacion( );
                    u.lat = float.Parse(row["Latitude"].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                    u.lon = float.Parse(row["Longitude"].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                    return(u);
                }
            }
        }
Пример #34
0
        /// <summary>
        /// Actualizar los datos de la ubicación de un ATM en el sistema.
        /// </summary>
        /// <param name="u">Objeto Ubicacion con los datos de la ubicación</param>
        public void actualizarUbicacion(Ubicacion u)
        {
            SqlCommand comando = _manejador.obtenerProcedimiento("UpdateUbicacion");

            _manejador.agregarParametro(comando, "@oficina", u.Oficina, SqlDbType.VarChar);
            _manejador.agregarParametro(comando, "@direccion", u.Direccion, SqlDbType.VarChar);
            _manejador.agregarParametro(comando, "@direccion_exacta", u.Direccion_exacta, SqlDbType.VarChar);
            _manejador.agregarParametro(comando, "@provincia", u.Provincia, SqlDbType.TinyInt);
            _manejador.agregarParametro(comando, "@ubicacion", u, SqlDbType.SmallInt);

            try
            {
                _manejador.ejecutarConsultaActualizacion(comando);
                comando.Connection.Close();
            }
            catch (Exception)
            {
                comando.Connection.Close();
                throw new Excepcion("ErrorUbicacionActualizacion");
            }
        }
Пример #35
0
        async void OnTapCrearPin(object sender, MapClickedEventArgs args)
        {
            string nombre = await DisplayPromptAsync("Título",
                                                     "Introduce número y título",
                                                     "Añadir", "Cancelar",
                                                     placeholder : "Por ejemplo: 1. Alcazaba");

            //El nombre es null cuando el usuario
            //pulsa el botón de Cancelar.
            if (nombre == null)
            {
                return;
            }
            if (Ruta.Ubicaciones == null)
            {
                Ruta.Ubicaciones = new List <Ubicacion>();
            }
            Pin nuevoPin = new Pin
            {
                Position = args.Position,
                Label    = nombre,
                Type     = PinType.SearchResult
            };

            nuevoPin.InfoWindowClicked += async(s, arg) =>
            {
                string pinName = ((Pin)s).Label;
                await DisplayAlert("Info Window Clicked",
                                   $"El audio que toca es {pinName}.", "Ok");
            };
            double    x         = nuevoPin.Position.Latitude;
            double    y         = nuevoPin.Position.Longitude;
            Ubicacion ubicacion = new Ubicacion(Ruta.Id, nombre, x, y);

            Ruta.Ubicaciones.Add(ubicacion);
            if (nuevoPin.Position != new Position())
            {
                Map.Pins.Add(nuevoPin);
            }
        }
Пример #36
0
        public static List<Ubicacion> getUbicaciones()
        {
            List<Ubicacion> result = new List<Ubicacion>();

            DataTable dt = GetLocalidades();
            foreach(DataRow rw in dt.Rows)
            {
                Ubicacion ubicacion = new Ubicacion();

                ubicacion.IDPais = Int32.Parse(rw["IDPAIS"].ToString());
                ubicacion.IDProvincia = Int32.Parse(rw["IDPROVINCIA"].ToString());
                ubicacion.IDCiudad = Int32.Parse(rw["IDCIUDAD"].ToString());
                ubicacion.IDLocalidad = Int32.Parse(rw["IDLOCALIDAD"].ToString());
                ubicacion.Pais = rw["PAIS"].ToString();
                ubicacion.Provincia = rw["PROVINCIA"].ToString();
                ubicacion.Localidad = rw["LOCALIDAD"].ToString();
                ubicacion.Ciudad = rw["CIUDAD"].ToString();

                result.Add(ubicacion);
            }

            return result;
        }
Пример #37
0
        public static Ubicacion GetUbicacionById(int idLocalidad)
        {
            Ubicacion resultUbicacion = null;

            DataTable dt = GetLocalidades();
            string selectClause = string.Format("IDLOCALIDAD = {0}", idLocalidad);

            DataRow[] rows = GetLocalidades().Select(selectClause);

            if (rows.Length > 0)
            {
                DataRow dr = rows[0];
                resultUbicacion = new Ubicacion();

                resultUbicacion.IDLocalidad = idLocalidad;
                resultUbicacion.IDCiudad = Int32.Parse(dr["IDCIUDAD"].ToString());
                resultUbicacion.IDProvincia = Int32.Parse(dr["IDPROVINCIA"].ToString());
                resultUbicacion.IDPais = Int32.Parse(dr["IDPAIS"].ToString());

            }

            return resultUbicacion;
        }
Пример #38
0
    /// <summary>
    /// Obtiene un Histórico de un vehículo de Transporte, en base a una fecha inicial y una fecha final.
    /// </summary>
    /// <param name="cliente">Identificador del cliente</param>
    /// <param name="unidad">Identificador de la unidad</param>
    /// <param name="fechaInicial">Fecha Inicial</param>
    /// <param name="fechaFinal">Fecha Final</param>
    /// <returns></returns>
    public static Historico HistoricoTransporteDebug(string cliente, string unidad, DateTime fechaInicial, DateTime fechaFinal)
    {
        string query = "SELECT   Fecha, Velocidad, Evento, VolumenCombustibleGlobal, VolumenesCombustible, AcumuladoEventoCombustible, MagnitudEventoCombustible " +
            " FROM   Ubicacion_" + cliente +
            " WHERE (Unidad = @unidad) AND (Fecha BETWEEN @fechaInicial AND @fechaFinal) AND VolumenCombustibleGlobal IS NOT NULL " +
            " ORDER BY Fecha ASC";
        Historico historicoUnidad = new Historico();
        List<Ubicacion> ubicaciones = new List<Ubicacion>();
        Ubicacion ubicacion;
        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                sqlCommand.Parameters.AddWithValue("@unidad", unidad);
                sqlCommand.Parameters.AddWithValue("@fechaInicial", fechaInicial);
                sqlCommand.Parameters.AddWithValue("@fechaFinal", fechaFinal);

                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        ubicacion = new Ubicacion();
                        ubicacion.Fecha = (DateTime)sqlDataReader["Fecha"];
                        ubicacion.Velocidad = (int)(double)sqlDataReader["Velocidad"];
                        ubicacion.Evento = (byte)((int)sqlDataReader["Evento"]);

                        // Combustible
                        ubicacion.CombustibleGlobal = (int)sqlDataReader["VolumenCombustibleGlobal"];

                        string volumenesFlat = (string)sqlDataReader["VolumenesCombustible"];
                        ubicacion.VolumenesCombustible = comasToLista(volumenesFlat);
                        ubicacion.MagnitudEventoAcumuladoCombustible = (int)sqlDataReader["AcumuladoEventoCombustible"];
                        ubicacion.MagnitudCambioCombustible = (int)sqlDataReader["MagnitudEventoCombustible"];

                        ubicaciones.Add(ubicacion);
                    }
                    historicoUnidad.UnidadID = unidad;
                    historicoUnidad.Ubicaciones = ubicaciones;
                }
            }
        }
        return historicoUnidad;
    }
Пример #39
0
    /// <summary>
    /// Obtiene un Histórico de un vehículo de Transporte, en base a una fecha inicial y una fecha final.
    /// </summary>
    /// <param name="cliente">Identificador del cliente</param>
    /// <param name="unidad">Identificador de la unidad</param>
    /// <param name="fechaInicial">Fecha Inicial</param>
    /// <param name="fechaFinal">Fecha Final</param>
    /// <returns></returns>
    public static Historico HistoricoTransporte(string cliente, string unidad, DateTime fechaInicial, DateTime fechaFinal)
    {
        string query = "SELECT *" +
            " FROM   Ubicacion_" + cliente +
            " WHERE (Unidad = @unidad) AND (Fecha BETWEEN @fechaInicial AND @fechaFinal) " + // AND VolumenCombustibleGlobal IS NOT NULL " +
            "ORDER BY Fecha ASC";
        Historico historicoUnidad = new Historico();
        List<Ubicacion> ubicaciones = new List<Ubicacion>();
        Ubicacion ubicacion;
        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();

            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                        sqlCommand.CommandTimeout = 60;
                sqlCommand.Parameters.AddWithValue("@unidad", unidad);
                sqlCommand.Parameters.AddWithValue("@fechaInicial", fechaInicial);
                sqlCommand.Parameters.AddWithValue("@fechaFinal", fechaFinal);

                /* Parche para obtener el valor ultimo conocido ... basicamente el ultimo que tenia combustible */
                int VolumenCombustibleGlobalAnterior = 0;
                string VolumenesCombustibleAnterior = "0,0,0,0";
                int MagnitudEventoCombustibleAnterior = 0;
                int AcumuladoEventoCombustibleAnterior = 0;

                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        ubicacion = new Ubicacion();
                        ubicacion.Fecha = (DateTime)sqlDataReader["Fecha"];
                        ubicacion.Velocidad = (int)(double)sqlDataReader["Velocidad"];

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        ubicacion.Latitud = p.Y;
                        ubicacion.Longitud = p.X;
                        ubicacion.Evento = (byte)((int)sqlDataReader["Evento"]);

                        // Por si el Odometro es null
                        if (!DBNull.Value.Equals(sqlDataReader["uodo"]))
                        {
                            ubicacion.odometro = (int)sqlDataReader["uodo"];
                            ubicacion.orientacion = (int)sqlDataReader["uori"];

                        }
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "ubat"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["ubat"]))
                            {
                                ubicacion.porcentajeBateria = (int)sqlDataReader["ubat"];
                            }
                        }

                       	// Valor artificial para ser no desplegado, nunca deberian llegar a el, estan en el infierno...
                        ubicacion.temperatura = 666;
                        ubicacion.sensoresTemperatura = new List<double>();
                       	// Si tiene campos de TPV
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperatura") && DataRecordExtensions.HasColumn(sqlDataReader, "presion"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperatura"]))
                            {
                                ubicacion.temperatura = (double)sqlDataReader["temperatura"];
                            }
                        }

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperaturas"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperaturas"]))
                            {
                                ubicacion.sensoresTemperatura = extraerTemperaturas((string)sqlDataReader["temperaturas"]);
                            }
                            if (!DBNull.Value.Equals(sqlDataReader["EstadoThermo"]))
                            {
                                ubicacion.estatusTermo = Int32.Parse((string)sqlDataReader["EstadoThermo"]);
                            }
                        }

                        // Combustible
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "VolumenCombustibleGlobal"))
                        {
                            string volumenesFlat = "0,0,0,0";
                            if (!DBNull.Value.Equals(sqlDataReader["VolumenCombustibleGlobal"]))
                            {
                                ubicacion.CombustibleGlobal = (int)(sqlDataReader["VolumenCombustibleGlobal"]);
                                volumenesFlat = (string)sqlDataReader["VolumenesCombustible"];
                                ubicacion.MagnitudCambioCombustible = (int)sqlDataReader["MagnitudEventoCombustible"];
                                if (DataRecordExtensions.HasColumn(sqlDataReader, "AcumuladoEventoCombustible"))
                                {
                                    if (!DBNull.Value.Equals(sqlDataReader["AcumuladoEventoCombustible"]))
                                    {
                                        ubicacion.MagnitudEventoAcumuladoCombustible = (int)sqlDataReader["AcumuladoEventoCombustible"];
                                        // valores del ultimo conocido
                                        VolumenCombustibleGlobalAnterior = ubicacion.CombustibleGlobal;
                                        VolumenesCombustibleAnterior = volumenesFlat;
                                        MagnitudEventoCombustibleAnterior = ubicacion.MagnitudCambioCombustible;
                                        AcumuladoEventoCombustibleAnterior = ubicacion.MagnitudEventoAcumuladoCombustible;
                                    }
                                }
                            }
                            else
                            {
                                ubicacion.CombustibleGlobal = VolumenCombustibleGlobalAnterior;
                                volumenesFlat = VolumenesCombustibleAnterior;
                                ubicacion.MagnitudCambioCombustible = MagnitudEventoCombustibleAnterior;
                                ubicacion.MagnitudEventoAcumuladoCombustible = AcumuladoEventoCombustibleAnterior;
                            }
                            // Transformamos el string de 1,1,1,1 a una lista de enteros para asignarla a la ubicacion
                            ubicacion.VolumenesCombustible = comasToLista(volumenesFlat);
                        }
                        // Eventos de servicio, no todas las tables contienen estos campos
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "IDCliente"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["IDCliente"]))
                            {
                                ubicacion.dispensadorIdCliente = (string)sqlDataReader["IDCliente"];
                                ubicacion.dispensadorEntrega = (double)sqlDataReader["Entrega"];
                            }
                        }

                        ubicaciones.Add(ubicacion);
                    }
                    historicoUnidad.UnidadID = unidad;
                    historicoUnidad.Ubicaciones = ubicaciones;
                }
            }
        }
        return historicoUnidad;
    }
Пример #40
0
    /// <summary>
    /// Excesos de Velocidad
    /// </summary>
    /// <param name="cliente">Identificador del cliente</param>
    /// <param name="unidad">Identificador de la unidad</param>
    /// <param name="fechaInicial">Fecha inicial del reporte</param>
    /// <param name="fechaFinal">Fecha final del reporte</param>
    /// <param name="velocidad">Velocidad del reporte</param>
    /// <returns></returns>
    public static Historico ExcesosVelocidad(string cliente, string unidad, DateTime fechaInicial, DateTime fechaFinal, int velocidad)
    {
        string query = "SELECT  Fecha, Velocidad, Longitud, Latitud, Evento" +
            " FROM   Ubicacion_" + cliente +
            " WHERE  (Unidad = @unidad) AND (Fecha BETWEEN @fechaInicial AND @fechaFinal) AND (Velocidad  >= @velocidad)" +
            " ";
        Historico historicoVelocidad = new Historico();
        List<Ubicacion> ubicaciones = new List<Ubicacion>();
        Ubicacion ubicacion;
        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();

            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                sqlCommand.Parameters.AddWithValue("@unidad", unidad);
                sqlCommand.Parameters.AddWithValue("@fechaInicial", fechaInicial);
                sqlCommand.Parameters.AddWithValue("@fechaFinal", fechaFinal);
                sqlCommand.Parameters.AddWithValue("@velocidad", velocidad);

                //sqlCommand.CommandTimeout = 11;
                sqlCommand.CommandTimeout = 30;

                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        ubicacion = new Ubicacion();
                        ubicacion.Fecha = (DateTime)sqlDataReader["Fecha"];
                        ubicacion.Velocidad = (int)((double)sqlDataReader["Velocidad"]);

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        ubicacion.Latitud = p.Y;
                        ubicacion.Longitud = p.X;

                        ubicacion.Evento = (byte)((int)sqlDataReader["Evento"]);

                        // Valor artificial para ser no desplegado, nunca deberian llegar a el, estan en el infierno...
                        ubicacion.temperatura = 666;
                        ubicacion.sensoresTemperatura = new List<double>();
                       	// Si tiene campos de TPV
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperatura") && DataRecordExtensions.HasColumn(sqlDataReader, "presion"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperatura"]))
                            {
                                ubicacion.temperatura = (double)sqlDataReader["temperatura"];
                            }
                        }

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperaturas"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperaturas"]))
                            {
                                ubicacion.sensoresTemperatura = extraerTemperaturas((string)sqlDataReader["temperaturas"]);
                            }
                            if (!DBNull.Value.Equals(sqlDataReader["EstadoThermo"]))
                            {
                                ubicacion.estatusTermo = Int32.Parse((string)sqlDataReader["EstadoThermo"]);
                            }
                        }

                        if (ubicacion.Velocidad < 201)
                            ubicaciones.Add(ubicacion);
                    }
                    historicoVelocidad.UnidadID = unidad;
                    ubicaciones.Sort();
                    historicoVelocidad.Ubicaciones = ubicaciones;
                }
            }
        }
        return historicoVelocidad;
    }
Пример #41
0
 public Pedido()
 {
     ubicacion = new Ubicacion();
     activo = true;
 }
Пример #42
0
    /// <summary>
    /// Obtiene un histórico de ralentí de una unidad de transporte
    /// </summary>
    /// <param name="cliente">Identificador del cliente</param>
    /// <param name="unidad">Identificador de la unidad</param>
    /// <param name="fechaInicial">Fecha inicial del reporte</param>
    /// <param name="fechaFinal">Fecha final del reporte</param>
    /// <returns></returns>
    public static Historico RalentiTrans(string cliente, string unidad, DateTime fechaInicial, DateTime fechaFinal)
    {
        string query = "SELECT Fecha, Velocidad, Longitud, Latitud, Evento, VolumenCombustibleGlobal" +
         " FROM   Ubicacion_" + cliente +
         " WHERE  (Unidad = @unidad) AND (Fecha BETWEEN @fechaInicial AND @fechaFinal) AND (Evento = 70 OR Evento = 71)" +
         "ORDER BY Fecha ASC";

        Historico historicoRalenti = new Historico();
        List<Ubicacion> ubicaciones = new List<Ubicacion>();
        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                sqlCommand.Parameters.AddWithValue("@unidad", unidad);
                sqlCommand.Parameters.AddWithValue("@fechaInicial", fechaInicial);
                sqlCommand.Parameters.AddWithValue("@fechaFinal", fechaFinal);

                //sqlCommand.CommandTimeout = 11;
                sqlCommand.CommandTimeout = 23;
                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        Ubicacion ubicacion = new Ubicacion();
                        ubicacion.Fecha = (DateTime)sqlDataReader["Fecha"];
                        ubicacion.Velocidad = (int)((double)sqlDataReader["Velocidad"]);

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        ubicacion.Latitud = p.Y;
                        ubicacion.Longitud = p.X;
                        bool after = true;
                        ubicacion.Evento = (byte)((int)sqlDataReader["Evento"]);

                        if (((int)sqlDataReader["Evento"]) == 70)
                        {
                            //ubicacion.CombustibleGlobal = valueFuelNextAfterEvent(cliente, unidad, ubicacion.Fecha );

                            after = true;
                        }
                        else
                        {
                            //ubicacion.CombustibleGlobal = valueFuelBeforeEvent(cliente, unidad, ubicacion.Fecha );
                            after = false;
                        }

                        ubicacion.CombustibleGlobal = valueOfFuelEvent(cliente, unidad, ubicacion.Fecha, after);

                        if (ubicacion.Velocidad < 201)
                            ubicaciones.Add(ubicacion);
                    }
                    historicoRalenti.UnidadID = unidad;
                    historicoRalenti.Ubicaciones = ubicaciones;
                }
            }
        }
        return historicoRalenti;
    }
Пример #43
0
    /// <summary>
    /// Obtiene la última posicion de las unidades pedidas, version para Zeek Transporte, considera funcionalidad de combustible.
    /// </summary>
    /// <param name="unidades">Arreglo de identificadores de las unidades</param>
    /// <returns></returns>
    public static List<Ubicacion> UltimaUbicacionTransporteDebug(List<string> unidades, string cliente)
    {
        //query con notificacion geocercas
        string query = "select p.unidad, fecha, velocidad, latitud, longitud, evento, VolumenCombustibleGlobal, VolumenesCombustible, VolumenesCombustibleCrudos, NivelesCombustible, r.accion, r.fechahora, r.geocerca " +
                       "from PosicionActualcombustible p " +
                       "left outer join reportegeocercaactual r " +
                       "on p.unidad=r.unidad " +
                       "where p.unidad in (";

        //concatenar las unidades en el query
        foreach (string unidad in unidades)
            query += "'" + unidad + "', ";
        //quitar la última coma y espacio
        query = query.Remove(query.Length - 2);
        //agregar los dos paréntesis finales.
        query += ")";

        Ubicacion ubicacion;
        List<Ubicacion> listaUbicaciones = new List<Ubicacion>();
        List<Geocerca> NombresGeocercas = GeocercasBD.getGeocercasNombre(cliente);
        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        ubicacion = new Ubicacion();
                        ubicacion.Unidad = (string)sqlDataReader["Unidad"];
                        ubicacion.Fecha = (DateTime)sqlDataReader["Fecha"];
                        ubicacion.Velocidad = (int)((double)sqlDataReader["Velocidad"]);

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        ubicacion.Latitud = p.Y;
                        ubicacion.Longitud = p.X;
                        ubicacion.Evento = (byte)((int)sqlDataReader["Evento"]);

                        // Combustible
                        ubicacion.CombustibleGlobal = ((int)sqlDataReader["VolumenCombustibleGlobal"]);

                        // Transformamos el string de 1,1,1,1 a una lista de enteros para asignarla a la ubicacion
                        string volumenesFlat = (string)sqlDataReader["VolumenesCombustible"];
                        ubicacion.VolumenesCombustible = comasToLista(volumenesFlat);

                        string crudosFlat = (string)sqlDataReader["VolumenesCombustibleCrudos"];
                        ubicacion.VolumenesCombustibleCrudos = comasToLista(crudosFlat);

                        string nivelesFlat = (string)sqlDataReader["NivelesCombustible"];
                        ubicacion.NivelesCombustible = comasToLista(nivelesFlat);

                        //datos de geocerca
                        if (!DBNull.Value.Equals(sqlDataReader["geocerca"]))
                        {

                            string geoID = (string)sqlDataReader["geocerca"];
                            //Verificamos si se tiene un nombre de la geocerca. De lo contrario no guardar
                            if (NombresGeocercas.Find(x => x.GeocercaID == geoID) != null)
                            {
                                ReporteGeocerca reporte = new ReporteGeocerca();
                                reporte.GeocercaID = geoID;
                                string nombre = NombresGeocercas.Find(x => x.GeocercaID == reporte.GeocercaID).Nombre;
                                reporte.GeocercaNombre = (!string.IsNullOrEmpty(nombre)) ? nombre : "";
                                reporte.FechaHora = (DateTime)sqlDataReader["fechahora"];
                                reporte.Accion = (int)sqlDataReader["accion"];//accion 0 - entrada. accion 1 = salida
                                ubicacion.DatosGeocerca = reporte;
                            }
                        }
                        listaUbicaciones.Add(ubicacion);
                    }
                }
            }
        }

        return listaUbicaciones;
    }
Пример #44
0
        public void TestObtenerUbicacion()
        {
            UbicacionServiceClient proxy = new UbicacionServiceClient();

             Ubicacion ubi = new Ubicacion();

             ubi = proxy.listaUbicacion("em124");

             Assert.AreEqual(ubi.latitud, -12.1017361);
             Assert.AreEqual(ubi.longitud, -77.0001988);
        }
Пример #45
0
        public void TestRegistrarUbicacion()
        {
            UbicacionServiceClient proxy = new UbicacionServiceClient();

             Ubicacion ubi = new Ubicacion();
             ubi.idEnvio = "EM126";
             ubi.latitud = -12.1017361;
             ubi.longitud= -77.0001988;
             string user = proxy.actualizaUbicacion(ubi);

             Assert.AreEqual("EM126",user);
        }
Пример #46
0
    /// <summary>
    /// Obtiene un Histórico de Eventos, en base a una fecha inicial y una fecha final.
    /// </summary>
    /// <param name="cliente">Identificador del cliente</param>
    /// <param name="unidad">Identificador de la unidad</param>
    /// <param name="fechaInicial">Fecha Inicial del reporte</param>
    /// <param name="fechaFinal">Fecha Final del reporte</param>
    /// <returns></returns>
    public static Historico Eventos(string cliente, string unidad, DateTime fechaInicial, DateTime fechaFinal)
    {
        string query = "SELECT   *" +
            " FROM   Ubicacion_" + cliente +
            " WHERE (Unidad = @unidad) AND (Fecha BETWEEN @fechaInicial AND @fechaFinal) AND (Evento > 1)" +
            " ";
        Historico historicoEventos = new Historico();
        List<Ubicacion> eventos = new List<Ubicacion>();

        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                sqlCommand.Parameters.AddWithValue("@unidad", unidad);
                sqlCommand.Parameters.AddWithValue("@fechaInicial", fechaInicial);
                sqlCommand.Parameters.AddWithValue("@fechaFinal", fechaFinal);

                //sqlCommand.CommandTimeout = 11;
                sqlCommand.CommandTimeout = 30;

                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        Ubicacion evento = new Ubicacion();
                        evento.Fecha = (DateTime)sqlDataReader["Fecha"];
                        evento.Velocidad = (int)((double)sqlDataReader["Velocidad"]);

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        evento.Latitud = p.Y;
                        evento.Longitud = p.X;

                        evento.Evento = (byte)((int)sqlDataReader["Evento"]);

                       // evento.odometro = (int)sqlDataReader["uodo"];
                       // evento.orientacion = (int)sqlDataReader["uori"];

                        if (evento.Velocidad < 201)
                            eventos.Add(evento);

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "IDCliente"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["IDCliente"]))
                            {
                                evento.dispensadorIdCliente = (string)sqlDataReader["IDCliente"];
                                evento.dispensadorEntrega = (double)sqlDataReader["Entrega"];
                            }
                        }

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "ubat"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["ubat"]))
                            {
                                evento.porcentajeBateria = (int)sqlDataReader["ubat"];
                            }
                        }

                        // Valor artificial para ser no desplegado, nunca deberian llegar a el, estan en el infierno...
                        evento.temperatura = 666;
                        evento.sensoresTemperatura = new List<double>();
                       	// Si tiene campos de TPV
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperatura") && DataRecordExtensions.HasColumn(sqlDataReader, "presion"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperatura"]))
                            {
                                evento.temperatura = (double)sqlDataReader["temperatura"];
                            }
                        }

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperaturas"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperaturas"]))
                            {
                                evento.sensoresTemperatura = extraerTemperaturas((string)sqlDataReader["temperaturas"]);
                            }
                            if (!DBNull.Value.Equals(sqlDataReader["EstadoThermo"]))
                            {
                                evento.estatusTermo = Int32.Parse((string)sqlDataReader["EstadoThermo"]);
                            }
                        }

                    }
                    historicoEventos.UnidadID = unidad;
                    eventos.Sort();
                    historicoEventos.Ubicaciones = eventos;
                }
            }
        }
        return historicoEventos;
    }
    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
        }
    }
Пример #48
0
    /// <summary>
    /// Obtiene un Histórico de un vehículo, en base a una fecha inicial y una fecha final.
    /// </summary>
    /// <param name="cliente">Identificador del cliente</param>
    /// <param name="unidad">Identificador de la unidad</param>
    /// <param name="fechaInicial">Fecha Inicial</param>
    /// <param name="fechaFinal">Fecha Final</param>
    /// <returns></returns>
    public static Historico Historico(string cliente, string unidad, DateTime fechaInicial, DateTime fechaFinal)
    {
        string query = "SELECT *" +
            " FROM   Ubicacion_" + cliente +
            " WHERE (Unidad = @unidad) AND (Fecha BETWEEN @fechaInicial AND @fechaFinal)" +
            " ";
        Historico historicoUnidad = new Historico();
        List<Ubicacion> ubicaciones = new List<Ubicacion>();
        Ubicacion ubicacion;
        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                sqlCommand.Parameters.AddWithValue("@unidad", unidad);
                sqlCommand.Parameters.AddWithValue("@fechaInicial", fechaInicial);
                sqlCommand.Parameters.AddWithValue("@fechaFinal", fechaFinal);

                //sqlCommand.CommandTimeout = 15;
                sqlCommand.CommandTimeout = 60;
                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        ubicacion = new Ubicacion();
                        ubicacion.Fecha = (DateTime)sqlDataReader["Fecha"];
                        ubicacion.Velocidad = (int)(double)sqlDataReader["Velocidad"];

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        ubicacion.Latitud = p.Y;
                        ubicacion.Longitud = p.X;

                        ubicacion.Evento = (byte)((int)sqlDataReader["Evento"]);

                       // ubicacion.odometro = (int)sqlDataReader["uodo"];
                       // ubicacion.orientacion = (int)sqlDataReader["uori"];

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "uodo"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["uodo"]))
                            {
                                ubicacion.odometro = (int)sqlDataReader["uodo"];
                            }
                        }

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "ubat"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["ubat"]))
                            {
                                ubicacion.porcentajeBateria = (int)sqlDataReader["ubat"];
                            }
                        }

                       	// Valor artificial para ser no desplegado, nunca deberian llegar a el, estan en el infierno...
                        ubicacion.temperatura = 666;
                       	// Si tiene campos de TPV
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperatura") && DataRecordExtensions.HasColumn(sqlDataReader, "presion"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperatura"]))
                            {
                                ubicacion.temperatura = (double)sqlDataReader["temperatura"];
                            }
                        }

                        // Eventos de servicio, no todas las tables contienen estos campos
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "IDCliente"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["IDCliente"]))
                            {
                                ubicacion.dispensadorIdCliente = (string)sqlDataReader["IDCliente"];
                                ubicacion.dispensadorEntrega = (double)sqlDataReader["Entrega"];
                            }
                        }

                        ubicaciones.Add(ubicacion);
                    }
                    historicoUnidad.UnidadID = unidad;
                    ubicaciones.Sort();
                    historicoUnidad.Ubicaciones = ubicaciones;
                }
            }
        }
        return historicoUnidad;
    }
Пример #49
0
    public static List<Ubicacion> MultiEventos(string cliente, List<string> unidades, DateTime fechaInicial, DateTime fechaFinal)
    {
        var multiEventos = new List<Ubicacion>();
        string queryUnidades = unidadesParaQuery(unidades);

        string query = "SELECT * FROM Ubicacion_" + cliente + " WHERE (Unidad IN ( " + queryUnidades + " ) AND (Fecha >= @fechaInicial AND Fecha <= @fechaFinal) AND (Evento > 1)) ";

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

                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        Ubicacion evento = new Ubicacion();
                        evento.Unidad = (string)sqlDataReader["Unidad"];
                        evento.Fecha = (DateTime)sqlDataReader["Fecha"];
                        evento.Velocidad = (int)((double)sqlDataReader["Velocidad"]);

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        evento.Latitud = p.Y;
                        evento.Longitud = p.X;

                        evento.Evento = (byte)((int)sqlDataReader["Evento"]);

                        // Por si el Odometro es null
                        if (!DBNull.Value.Equals(sqlDataReader["uodo"]))
                        {
                            evento.odometro = (int)sqlDataReader["uodo"];
                            evento.orientacion = (int)sqlDataReader["uori"];
                        }

                        // Fuel
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "MagnitudEventoCombustible"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["MagnitudEventoCombustible"]))
                            {
                                // Combustible
                                evento.MagnitudCambioCombustible = (int)sqlDataReader["MagnitudEventoCombustible"];
                                evento.MagnitudEventoAcumuladoCombustible = (int)sqlDataReader["AcumuladoEventoCombustible"];
                                evento.CombustibleGlobal = (int)sqlDataReader["VolumenCombustibleGlobal"];
                                string volumenesFlat = (string)sqlDataReader["VolumenesCombustible"];
                                evento.VolumenesCombustible = comasToLista(volumenesFlat);
                            }
                        }

                        // Gas
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "IDCliente"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["IDCliente"]))
                            {
                                evento.dispensadorIdCliente = (string)sqlDataReader["IDCliente"];
                                evento.dispensadorEntrega = (double)sqlDataReader["Entrega"];
                                evento.dispensadorTipo = (string)sqlDataReader["Tipo"];
                                evento.dispensadorNumServicio = (int)sqlDataReader["NumServicio"];
                                evento.dispensadorFolio = (string)sqlDataReader["Folio"];
                                evento.dispensadorPrecio = (double)sqlDataReader["Precio"];
                                evento.dispensadorTipoDocumento = (string)sqlDataReader["TipoDocumento"];
                                evento.dispensadorAcumulado = (double)sqlDataReader["Acumulado"];
                                evento.dispensadorDensidad = (double)sqlDataReader["Densidad"];
                                evento.dispensadorTemperatura = (double)sqlDataReader["Temperatura"];
                                evento.dispensadorEsn = (string)sqlDataReader["Esn"];
                                evento.dispensadorTipoVenta = (string)sqlDataReader["TipoVenta"];
                            }
                        }
                       	// Valor artificial para ser no desplegado, nunca deberian llegar a el, estan en el infierno...
                        evento.temperatura = 666;
                        evento.sensoresTemperatura = new List<double>();
                       	// Si tiene campos de TPV
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperatura") && DataRecordExtensions.HasColumn(sqlDataReader, "presion"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperatura"]))
                            {
                                evento.temperatura = (double)sqlDataReader["temperatura"];
                            }
                        }

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperaturas"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperaturas"]))
                            {
                                evento.sensoresTemperatura = extraerTemperaturas((string)sqlDataReader["temperaturas"]);
                            }
                            if (!DBNull.Value.Equals(sqlDataReader["EstadoThermo"]))
                            {
                                evento.estatusTermo = Int32.Parse((string)sqlDataReader["EstadoThermo"]);
                            }
                        }
                        multiEventos.Add(evento);
                    }
                    multiEventos.Sort();
                }
            }
        }
        return multiEventos;
    }
Пример #50
0
    /// <summary>
    /// Obtiene la última posicion de las unidades pedidas, version para Zeek Transporte, considera funcionalidad de combustible.
    /// </summary>
    /// <param name="unidades">Arreglo de identificadores de las unidades</param>
    /// <returns></returns>
    public static List<Ubicacion> UltimaUbicacionTransporte(List<string> unidades, string cliente)
    {
        //query con notificacion geocercas
        // p.unidad, fecha, velocidad, latitud, longitud, evento, VolumenCombustibleGlobal, VolumenesCombustible, r.accion, r.fechahora, r.geocerca
        string query = "select * " +
                       "from posicionactualCombustible p " +
                       "left outer join reportegeocercaactual r " +
                       "on p.unidad=r.unidad " +
                       "where p.unidad in (";

        //concatenar las unidades en el query
        foreach (string unidad in unidades)
            query += "'" + unidad + "', ";
        //quitar la última coma y espacio
        query = query.Remove(query.Length - 2);
        //agregar los dos paréntesis finales.
        query += ")";

        Ubicacion ubicacion;
        List<Ubicacion> listaUbicaciones = new List<Ubicacion>();
        List<Geocerca> NombresGeocercas = GeocercasBD.getGeocercasNombre(cliente);
        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        ubicacion = new Ubicacion();
                        ubicacion.Unidad = (string)sqlDataReader["Unidad"];
                        ubicacion.Fecha = (DateTime)sqlDataReader["Fecha"];
                        ubicacion.Velocidad = (int)((double)sqlDataReader["Velocidad"]);

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        ubicacion.Latitud = p.Y;
                        ubicacion.Longitud = p.X;
                        ubicacion.Evento = (byte)((int)sqlDataReader["Evento"]);

                        //ubicacion.odometro = (int)sqlDataReader["uodo"];
                        //ubicacion.orientacion = (int)sqlDataReader["uori"];

                        // Combustible
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "VolumenCombustibleGlobal"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["VolumenCombustibleGlobal"]))
                            {
                                ubicacion.CombustibleGlobal = ((int)sqlDataReader["VolumenCombustibleGlobal"]);

                                // Transformamos el string de 1,1,1,1 a una lista de enteros para asignarla a la ubicacion
                                string volumenesFlat = (string)sqlDataReader["VolumenesCombustible"];
                                List<string> volumenesString = volumenesFlat.Split(',').ToList();
                                List<int> volumenes = new List<int>();
                                foreach (string v in volumenesString)
                                {
                                    volumenes.Add(int.Parse(v));
                                }
                                ubicacion.VolumenesCombustible = volumenes;
                            }
                        }

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "ubat"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["ubat"]))
                            {
                                ubicacion.porcentajeBateria = (int)sqlDataReader["ubat"];
                            }
                        }

                       	// Valor artificial para ser no desplegado, nunca deberian llegar a el, estan en el infierno...
                        ubicacion.temperatura = 666;
                        ubicacion.sensoresTemperatura = new List<double>();
                       	// Si tiene campos de TPV
                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperatura") && DataRecordExtensions.HasColumn(sqlDataReader, "presion"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperatura"]))
                            {
                                ubicacion.temperatura = (double)sqlDataReader["temperatura"];
                            }
                        }

                        if (DataRecordExtensions.HasColumn(sqlDataReader, "temperaturas"))
                        {
                            if (!DBNull.Value.Equals(sqlDataReader["temperaturas"]))
                            {
                                ubicacion.sensoresTemperatura = extraerTemperaturas((string)sqlDataReader["temperaturas"]);
                            }
                            if (!DBNull.Value.Equals(sqlDataReader["EstadoThermo"]))
                            {
                                ubicacion.estatusTermo = Int32.Parse((string)sqlDataReader["EstadoThermo"]);
                            }
                        }

                        //datos de geocerca
                        if (!DBNull.Value.Equals(sqlDataReader["geocerca"]))
                        {

                            string geoID = (string)sqlDataReader["geocerca"];
                            //Verificamos si se tiene un nombre de la geocerca. De lo contrario no guardar
                            if (NombresGeocercas.Find(x => x.GeocercaID == geoID) != null)
                            {
                                ReporteGeocerca reporte = new ReporteGeocerca();
                                reporte.GeocercaID = geoID;
                                string nombre = NombresGeocercas.Find(x => x.GeocercaID == reporte.GeocercaID).Nombre;
                                reporte.GeocercaNombre = (!string.IsNullOrEmpty(nombre)) ? nombre : "";
                                reporte.FechaHora = (DateTime)sqlDataReader["fechahora"];
                                reporte.Accion = (int)sqlDataReader["accion"];//accion 0 - entrada. accion 1 = salida
                                ubicacion.DatosGeocerca = reporte;
                            }
                        }
                        listaUbicaciones.Add(ubicacion);
                    }
                }
            }
        }

        return listaUbicaciones;
    }
Пример #51
0
    public static List<Ubicacion> getEventosCombustibleTipo(string cliente, string unidad, DateTime fechaInicial, DateTime fechaFinal, int numEvent)
    {
        string query = "SELECT   Fecha, Velocidad, Longitud, Latitud, Evento, VolumenCombustibleGlobal, VolumenesCombustible, MagnitudEventoCombustible, AcumuladoEventoCombustible" +
           " FROM   Ubicacion_" + cliente +
           " WHERE (Unidad = @unidad) AND (Fecha BETWEEN @fechaInicial AND @fechaFinal) AND (Evento = " + numEvent + ")" +
           " ORDER BY Fecha ASC";
        Historico historicoEventos = new Historico();
        List<Ubicacion> eventos = new List<Ubicacion>();

        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringBD"].ConnectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection))
            {
                sqlCommand.Parameters.AddWithValue("@unidad", unidad);
                sqlCommand.Parameters.AddWithValue("@fechaInicial", fechaInicial);
                sqlCommand.Parameters.AddWithValue("@fechaFinal", fechaFinal);

                using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        Ubicacion evento = new Ubicacion();
                        evento.Fecha = (DateTime)sqlDataReader["Fecha"];
                        evento.Velocidad = (int)((double)sqlDataReader["Velocidad"]);

                        int latitud = (int)sqlDataReader["Latitud"];
                        int longitud = (int)sqlDataReader["Longitud"];
                        System.Drawing.PointF p = GPSInfo.ParseLatitudLongitud(latitud, longitud);
                        evento.Latitud = p.Y;
                        evento.Longitud = p.X;
                        evento.MagnitudCambioCombustible = (int)sqlDataReader["MagnitudEventoCombustible"];
                        evento.MagnitudEventoAcumuladoCombustible = (int)sqlDataReader["AcumuladoEventoCombustible"];
                        evento.Evento = (byte)((int)sqlDataReader["Evento"]);
                        eventos.Add(evento);
                        // Combustible
                        evento.CombustibleGlobal = (int)sqlDataReader["VolumenCombustibleGlobal"];

                        string volumenesFlat = (string)sqlDataReader["VolumenesCombustible"];
                        evento.VolumenesCombustible = comasToLista(volumenesFlat);
                    }
                    historicoEventos.UnidadID = unidad;
                    historicoEventos.Ubicaciones = eventos;
                }
            }
        }
        return historicoEventos.Ubicaciones;
    }