Пример #1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id;
                if (Request.QueryString["id"] == null || !int.TryParse(Request.QueryString["id"], out id))
                {
                    LblInfo.Text = CultureManager.GetError("NO_ENTREGA_INFO");
                    return;
                }

                var entrega = DAOFactory.EntregaDistribucionDAO.FindById(id);
                if (entrega != null)
                {
                    lblEntrega.Text  = entrega.Descripcion;
                    lblViaje.Text    = entrega.Viaje.Codigo;
                    lblVehiculo.Text = entrega.Viaje.Vehiculo != null ? entrega.Viaje.Vehiculo.Interno : CultureManager.GetError("NO_VEHICLE_ASSIGNED");
                    lblEstado.Text   = CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entrega.Estado));
                    if (entrega.ReferenciaGeografica != null)
                    {
                        lblDireccion.Text = GeocoderHelper.GetDescripcionEsquinaMasCercana(entrega.ReferenciaGeografica.Latitude, entrega.ReferenciaGeografica.Longitude);
                    }
                    lblEntrada.Text = (entrega.Entrada.HasValue ? entrega.Entrada.Value.ToDisplayDateTime().ToString("yyyy/MM/dd HH:mm") : string.Empty);
                    lblManual.Text  = (entrega.Manual.HasValue ? entrega.Manual.Value.ToDisplayDateTime().ToString("yyyy/MM/dd HH:mm") : string.Empty);
                    lblSalida.Text  = (entrega.Salida.HasValue ? entrega.Salida.Value.ToDisplayDateTime().ToString("yyyy/MM/dd HH:mm") : string.Empty);
                    lnkMonitorCiclo.Attributes.Add("id", entrega.Viaje.Id.ToString("#0"));
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Message data binding.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var id = !string.IsNullOrEmpty(Request.QueryString["id"]) ? Convert.ToInt32(Request.QueryString["id"]) : 0;

            var message = DAOFactory.LogMensajeDAO.FindById(id);

            if (message == null)
            {
                return;
            }

            lblCoche.Text   = message.Coche.Interno;
            lblMensaje.Text = message.Texto;

            lblCorner.Text = GeocoderHelper.GetDescripcionEsquinaMasCercana(message.Latitud, message.Longitud);

            lblFecha.Text = string.Concat(message.Fecha.ToDisplayDateTime().ToShortDateString(), " ", message.Fecha.ToDisplayDateTime().TimeOfDay.ToString());

            lblLink.Visible = message.TieneFoto;
            if (lblLink.Visible)
            {
                lblLink.Text = @"<div class=""withPhoto""></div>";

                const string link = "window.open('../../Common/Pictures?e={0}', 'Fotos_{0}', 'width=345,height=408,directories=no,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no');";

                lblLink.Attributes.Add("onclick", string.Format(link, message.Id));
            }
        }
Пример #3
0
        private void BindProvincias()
        {
            var provincias = GeocoderHelper.BuscarProvincias();

            cbProvincia.DataSource = provincias;
            cbProvincia.DataBind();
        }
Пример #4
0
        protected void BtNormalSearchClick(object sender, EventArgs e)
        {
            var calle = txtCalle.Text.Trim();
            int altura;

            if (!int.TryParse(txtAltura.Text.Trim(), out altura))
            {
                altura = -1;
            }

            var esquina   = txtEsquina.Text.Trim();
            var partido   = txtPartido.Text.Trim();
            var provincia = Convert.ToInt32(cbProvincia.SelectedValue);

            if (string.IsNullOrEmpty(calle))
            {
                return;
            }
            if (string.IsNullOrEmpty(esquina) && altura < 0)
            {
                return;
            }

            var result = GeocoderHelper.GetDireccion(calle, altura, esquina, partido, provincia);

            SetResults(result);
        }
Пример #5
0
        protected override void OnRowDataBound(C1GridView grid, C1GridViewRowEventArgs e, TolvaTourVo dataItem)
        {
            var vehiculo = DAOFactory.CocheDAO.FindById(dataItem.IdVehiculo);

            var posInicio = new GPSPoint(dataItem.EntradaHora, (float)dataItem.LatitudInicio, (float)dataItem.LongitudInicio);
            var posFin    = new GPSPoint(dataItem.SalidaHora, (float)dataItem.LatitudFin, (float)dataItem.LongitudFin);

            var estadoInicio = GeocercaManager.CalcularEstadoVehiculo(vehiculo, posInicio, DAOFactory);
            var estadoFin    = GeocercaManager.CalcularEstadoVehiculo(vehiculo, posFin, DAOFactory);

            var geocerca = estadoInicio.GeocercasDentro.Intersect(estadoFin.GeocercasDentro).FirstOrDefault();
            var text     = geocerca != null
                ? geocerca.Geocerca.Descripcion
                : GeocoderHelper.GetDescripcionEsquinaMasCercana(dataItem.LatitudInicio, dataItem.LongitudInicio);

            e.Row.Cells[TolvaTourVo.Index.Ubicacion].Text = text;
            if (dataItem.Entrada == DateTime.MinValue)
            {
                e.Row.Cells[TolvaTourVo.Index.Entrada].Text     = "";
                e.Row.Cells[TolvaTourVo.Index.EntradaHora].Text = "";
            }
            if (dataItem.Salida == DateTime.MinValue)
            {
                e.Row.Cells[TolvaTourVo.Index.Salida].Text     = "";
                e.Row.Cells[TolvaTourVo.Index.SalidaHora].Text = "";
            }
        }
Пример #6
0
        private static void SendMail(LogMensajeBase log)
        {
            const int minutes = 15;
            var       monitor = Config.Monitor.HistoricMonitorLink;
            var       link    = log.Coche != null
                ? String.Format(@"{0}?Planta={1}&TypeMobile={2}&Movil={3}&InitialDate={4}&FinalDate={5}&MessageCenterIndex={6}&ShowMessages=1&Empresa={7}&ShowPOIS=1",
                                monitor,
                                log.Coche.Linea != null?log.Coche.Linea.Id : -1,
                                log.Coche.TipoCoche.Id, log.Coche.Id,
                                log.Fecha.AddMinutes(-minutes).ToString(CultureInfo.InvariantCulture),
                                log.Fecha.AddMinutes(minutes).ToString(CultureInfo.InvariantCulture),
                                log.Id,
                                log.Coche.Empresa != null?log.Coche.Empresa.Id : log.Coche.Linea != null?log.Coche.Linea.Empresa.Id : -1)
                                : monitor;

            var chofer = log.Chofer != null?string.Format("Chofer: {0}", log.Chofer.Entidad.Descripcion) : "Sin Chofer Identificado";

            var responsable = log.Coche != null && log.Coche.Chofer != null && log.Coche.Chofer.Entidad != null ? log.Coche.Chofer.Entidad.Descripcion : "Sin Responsable Asignado";

            var parameters = log.Coche != null
                                 ? new List <string>
            {
                log.Coche.Linea != null ? log.Coche.Linea.Descripcion : log.Coche.Empresa != null ? log.Coche.Empresa.RazonSocial : "Sistema",
                string.Concat(log.Coche.Interno, " - ", chofer),
                responsable,
                log.Coche.ToLocalString(log.Fecha, true),
                GeocoderHelper.GetDescripcionEsquinaMasCercana(log.Latitud, log.Longitud),
                log.Texto,
                link
            }
                                 : new List <string>
            {
                "Sistema",
                "(Ninguno)",
                responsable,
                string.Format("{0} {1}", log.Fecha.ToShortDateString(), log.Fecha.ToShortTimeString()),
                GeocoderHelper.GetDescripcionEsquinaMasCercana(log.Latitud, log.Longitud),
                log.Texto,
                link
            };

            var destinatarios = log.Accion.DestinatariosMail;

            if (log.Accion.ReportaDepartamento && log.Accion.Departamento.Empleado != null && log.Accion.Departamento.Empleado.Mail != string.Empty)
            {
                destinatarios = destinatarios + ";" + log.Accion.Departamento.Empleado.Mail;
            }
            if (log.Accion.ReportaCentroDeCostos && log.Accion.CentroDeCostos.Empleado != null && log.Accion.CentroDeCostos.Empleado.Mail != string.Empty)
            {
                destinatarios = destinatarios + ";" + log.Accion.CentroDeCostos.Empleado.Mail;
            }

            var asunto = log.Accion.AsuntoMail.Trim() != string.Empty
                                 ? log.Accion.AsuntoMail.Trim()
                                 : log.Texto;

            SendMailToAllDestinations(destinatarios, log.Chofer, asunto, parameters);
        }
Пример #7
0
        public void AddFromLatLon(double lat, double lon)
        {
            var dir = GeocoderHelper.GetEsquinaMasCercana(lat, lon);

            if (dir == null)
            {
                return;
            }
            SetDireccion(dir);
        }
Пример #8
0
        protected void BtSmartSearchClick(object sender, EventArgs e)
        {
            var frase = txtSmartSearch.Text.Trim();

            if (string.IsNullOrEmpty(frase))
            {
                return;
            }
            var result = GeocoderHelper.GetDireccionSmartSearch(frase);

            SetResults(result);
        }
Пример #9
0
        public Respuesta <ProvinciaVO[]> GetProvincias(string sessionId)
        {
            try
            {
                ValidateLoginInfo(sessionId, Securables.WebServiceGeocoder);
                var provincias = GeocoderHelper.BuscarProvincias().ToArray();

                return(Respuesta <ProvinciaVO[]> .Create(provincias));
            }
            catch (Exception ex)
            {
                return(Respuesta <ProvinciaVO[]> .CreateError(ex.Message));
            }
        }
Пример #10
0
        private void MnuStartXMLRequest_Click(object sender, EventArgs e)
        {
            if (olvBinds.SelectedObject == null)
            {
                return;
            }
            var _geocoder = GeocoderHelper.GetGeocoder() as Geocoding.Google.GoogleGeocoder;

            if (_geocoder == null)
            {
                return;
            }
            _geocoder.Language = Helpers.GeocoderHelper.QueryLanguage;
            System.Diagnostics.Process.Start(_geocoder.BuildWebRequest((olvBinds.SelectedObject as Bind).OriginalAddress));
        }
Пример #11
0
        public Respuesta <DireccionVO[]> GetSmartSearch(string sessionId, string frase)
        {
            try
            {
                ValidateLoginInfo(sessionId, Securables.WebServiceGeocoder);

                var direcciones = GeocoderHelper.GetDireccionSmartSearch(frase).ToArray();

                return(Respuesta <DireccionVO[]> .Create(direcciones));
            }
            catch (Exception ex)
            {
                return(Respuesta <DireccionVO[]> .CreateError(ex.Message));
            }
        }
Пример #12
0
        public Respuesta <DireccionVO[]> GetDireccion(string sessionId, string calle, int altura, string esquina, string partido, int provincia)
        {
            try
            {
                ValidateLoginInfo(sessionId, Securables.WebServiceGeocoder);

                var direcciones = GeocoderHelper.GetDireccion(calle, altura, esquina, partido, provincia).ToArray();

                return(Respuesta <DireccionVO[]> .Create(direcciones));
            }
            catch (Exception ex)
            {
                return(Respuesta <DireccionVO[]> .CreateError(ex.Message));
            }
        }
Пример #13
0
        protected void btnNomenclar_Click(object sender, EventArgs e)
        {
            var empresaId = cbEmpreaNomenclador.Selected;
            var clientes  = DAOFactory.ClienteDAO.FindAll().Where(c => c.Empresa.Id == empresaId && !c.Baja);
            var puntos    = DAOFactory.PuntoEntregaDAO.GetList(new[] { -1 }, new[] { -1 }, clientes.Select(c => c.Id));

            var cant = 0;

            foreach (var punto in puntos)
            {
                try
                {
                    var direccion = GeocoderHelper.GetEsquinaMasCercana(punto.ReferenciaGeografica.Latitude, punto.ReferenciaGeografica.Longitude);

                    if (direccion != null)
                    {
                        punto.ReferenciaGeografica.Direccion.Calle       = direccion.Calle;
                        punto.ReferenciaGeografica.Direccion.Altura      = direccion.Altura;
                        punto.ReferenciaGeografica.Direccion.Partido     = direccion.Partido;
                        punto.ReferenciaGeografica.Direccion.Provincia   = direccion.Provincia;
                        punto.ReferenciaGeografica.Direccion.Pais        = "Argentina";
                        punto.ReferenciaGeografica.Direccion.Descripcion = direccion.Direccion;

                        punto.ReferenciaGeografica.Direccion.IdMapa    = (short)direccion.IdMapaUrbano;
                        punto.ReferenciaGeografica.Direccion.IdCalle   = direccion.IdPoligonal;
                        punto.ReferenciaGeografica.Direccion.IdEsquina = direccion.IdEsquina;

                        punto.Nomenclado          = true;
                        punto.DireccionNomenclada = direccion.Direccion;

                        DAOFactory.ReferenciaGeograficaDAO.SaveOrUpdate(punto.ReferenciaGeografica);
                        DAOFactory.PuntoEntregaDAO.SaveOrUpdate(punto);
                        cant++;
                    }
                    ;
                }
                catch (Exception ex)
                {
                    STrace.Exception(GetType().FullName, ex);
                }
            }

            infoLabel1.Mode = InfoLabelMode.INFO;
            infoLabel1.Text = "Se han nomenclado " + cant + " puntos de entrega.";
        }
Пример #14
0
        private void CalcularHorarioPorDistancia(ViajeDistribucion distribucion)
        {
            var index = distribucion.Detalles.Count - 1;

            if (index < 0)
            {
                return;
            }
            if (index == 0)
            {
                distribucion.Detalles[index].Programado      = distribucion.Inicio;
                distribucion.Detalles[index].ProgramadoHasta = distribucion.Inicio;
                return;
            }

            var velocidadPromedio = GetVelocidad(distribucion);

            var prev = distribucion.Detalles[index - 1];
            var item = distribucion.Detalles[index];

            var prevDate = prev.Programado;

            var prevPunto = prev.PuntoEntrega != null
                                ? prev.PuntoEntrega.ReferenciaGeografica
                                : prev.Linea.ReferenciaGeografica;
            var punto = item.PuntoEntrega != null
                            ? item.PuntoEntrega.ReferenciaGeografica
                            : item.Linea.ReferenciaGeografica;

            var demora = prev.TipoServicio != null ? prev.TipoServicio.Demora : 0;

            var distancia = GeocoderHelper.CalcularDistacia(prevPunto.Latitude,
                                                            prevPunto.Longitude,
                                                            punto.Latitude,
                                                            punto.Longitude);
            var tiempoViaje = TimeSpan.FromHours(distancia / velocidadPromedio);

            var hora = prevDate.AddMinutes(demora).Add(tiempoViaje);

            distribucion.Detalles[index].Programado      = hora;
            distribucion.Detalles[index].ProgramadoHasta = hora;
            distribucion.Fin = hora;
        }
Пример #15
0
    public Respuesta <string> GetEsquinaMasCercana(string interno, string empresa, string linea)
    {
        try
        {
            var emp = DAOFactory.EmpresaDAO.FindByCodigo(empresa);
            if (emp == null)
            {
                return(Respuesta <string> .CreateError("Empresa " + empresa + " no encontrada"));
            }
            var lin = DAOFactory.LineaDAO.FindByCodigo(emp.Id, linea);
            if (lin == null)
            {
                return(Respuesta <string> .CreateError("Linea " + linea + " no encontrada"));
            }
            if (!lin.Interfaceable)
            {
                return(Respuesta <string> .CreateError("La Linea " + linea + " no acepta consultas de esta interface"));
            }

            var coche = DAOFactory.CocheDAO.FindByInterno(new[] { emp.Id }, new[] { lin.Id }, interno);
            if (coche == null)
            {
                return(Respuesta <string> .CreateError("No se encontraro el movil con interno " + interno));
            }

            var pos = DAOFactory.LogPosicionDAO.GetLastOnlineVehiclePosition(coche);
            if (pos == null)
            {
                return(Respuesta <string> .CreateError("No se encontro posicion para el movil " + interno));
            }
            var dir = GeocoderHelper.GetEsquinaMasCercana(pos.Latitud, pos.Longitud);
            return(Respuesta <string> .Create(dir == null
                                              ?string.Format("({0}, {1})", pos.Latitud, pos.Longitud)
                                              : dir.Direccion));
        }
        catch (Exception ex)
        {
            return(Respuesta <string> .CreateError(ex.Message));
        }
    }
Пример #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int p;
                if (Request.QueryString["p"] == null || !int.TryParse(Request.QueryString["p"], out p))
                {
                    lblDescripcion.Text = CultureManager.GetError("NO_POI_INFO");
                    return;
                }
                var idsLineas = Request.QueryString["l"].Split(',').Select(l => Convert.ToInt32(l)).ToList();

                if (idsLineas.Count <= 0)
                {
                    lblDescripcion.Text = CultureManager.GetError("NO_POI_INFO");
                    return;
                }

                var poi = DAOFactory.ReferenciaGeograficaDAO.FindById(p);
                lblTipo.Text        = poi.TipoReferenciaGeografica.Descripcion;
                lblDescripcion.Text = poi.Codigo + @" - " + poi.Descripcion;
                lblDireccion.Text   = GeocoderHelper.GetDescripcionEsquinaMasCercana(poi.Latitude, poi.Longitude);
                imgTipo.ImageUrl    = IconDir + (poi.Icono != null ? poi.Icono.PathIcono : poi.TipoReferenciaGeografica.Icono.PathIcono);

                int idEmpresa;
                if (Request.QueryString["e"] == null || !int.TryParse(Request.QueryString["e"], out idEmpresa))
                {
                    idEmpresa = poi.Empresa != null ? poi.Empresa.Id : -1;
                }

                var pois = DAOFactory.ReferenciaGeograficaDAO.GetVehiculosCercanos(new[] { idEmpresa }, idsLineas, poi.Id);
                if (pois.Count > 10)
                {
                    pois.RemoveRange(10, pois.Count - 10);
                }
                gridMov.DataSource = pois;
                gridMov.DataBind();
            }
        }
Пример #17
0
        public void FindByLatLon(double latitud, double longitud)
        {
            var result = GeocoderHelper.GetEsquinaMasCercana(latitud, longitud)
                         ?? new DireccionVO
            {
                Altura       = -1,
                Calle        = string.Empty,
                Direccion    = string.Format("({0}, {1})", latitud, longitud),
                IdEsquina    = -1,
                IdMapaUrbano = -1,
                IdPoligonal  = -1,
                IdProvincia  = -1,
                Partido      = string.Empty,
                Provincia    = string.Empty,
            };

            result.Latitud  = latitud;
            result.Longitud = longitud;
            SetDireccion(DireccionFromVo(result));

            updControl.Update();
        }
Пример #18
0
        /// <summary>
        /// Initial data binding.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!string.IsNullOrEmpty(Request.QueryString["latitude"]) && !string.IsNullOrEmpty(Request.QueryString["longitude"]))
            {
                var latitude  = Convert.ToDouble(Request.QueryString["latitude"], CultureInfo.InvariantCulture);
                var longitude = Convert.ToDouble(Request.QueryString["longitude"], CultureInfo.InvariantCulture);

                lblEsquina.Text = GeocoderHelper.GetDescripcionEsquinaMasCercana(latitude, longitude);
            }

            if (!string.IsNullOrEmpty(Request.QueryString["inicio"]))
            {
                lblInicio.Text = Request.QueryString["inicio"];
            }
            if (!string.IsNullOrEmpty(Request.QueryString["duracion"]))
            {
                lblDuracion.Text = Request.QueryString["duracion"];
            }
            if (!string.IsNullOrEmpty(Request.QueryString["distancia"]))
            {
                lblDistancia.Text = string.Concat(Request.QueryString["distancia"], "km");
            }

            if (!string.IsNullOrEmpty(Request.QueryString["velocidadMinima"]))
            {
                lblVelocidadMinima.Text = string.Concat(Request.QueryString["velocidadMinima"], "km/h");
            }
            if (!string.IsNullOrEmpty(Request.QueryString["velocidadMaxima"]))
            {
                lblVelocidadMaxima.Text = string.Concat(Request.QueryString["velocidadMaxima"], "km/h");
            }
            if (!string.IsNullOrEmpty(Request.QueryString["velocidadPromedio"]))
            {
                lblVelocidadPromedio.Text = string.Concat(Convert.ToInt32(Request.QueryString["velocidadPromedio"]), " km/h");
            }
        }
Пример #19
0
        private void CalcularKm(ViajeDistribucion viaje)
        {
            EntregaDistribucion anterior = null;
            var detalles = viaje.GetEntregasOrdenadas();

            foreach (var entrega in detalles)
            {
                if (entrega.PuntoEntrega != null && entrega.Estado != EntregaDistribucion.Estados.Completado &&
                    entrega.Estado != EntregaDistribucion.Estados.NoCompletado)
                {
                    continue;
                }

                if (anterior != null)
                {
                    var changed = false;
                    if (!entrega.KmGps.HasValue || entrega.KmGps.Value == 0)
                    {
                        entrega.KmGps = DAOFactory.CocheDAO.GetDistance(viaje.Vehiculo.Id, anterior.ManualOSalida, entrega.ManualOSalida);
                        changed       = true;
                    }
                    if (!entrega.KmCalculado.HasValue || entrega.KmCalculado.Value == 0)
                    {
                        entrega.KmCalculado = GeocoderHelper.CalcularDistacia(anterior.ReferenciaGeografica.Latitude,
                                                                              anterior.ReferenciaGeografica.Longitude,
                                                                              entrega.ReferenciaGeografica.Latitude,
                                                                              entrega.ReferenciaGeografica.Longitude);
                        changed = true;
                    }
                    if (changed)
                    {
                        DAOFactory.EntregaDistribucionDAO.SaveOrUpdate(entrega);
                    }
                }
                anterior = entrega;
            }
        }
Пример #20
0
        /// <summary>
        /// Sends a SMS with info about the event.
        /// </summary>
        /// <param name="log"></param>
        private static void SendSms(LogMensajeBase log)
        {
            var parameters = log.Coche != null
                                 ? new List <string>
            {
                log.Coche.Linea != null? log.Coche.Linea.Descripcion : log.Coche.Empresa != null ? log.Coche.Empresa.RazonSocial : "Sistema",
                log.Coche.Interno,
                log.Coche.ToLocalString(log.Fecha, false),
                log.Texto,
                GeocoderHelper.GetDescripcionEsquinaMasCercana(log.Latitud, log.Longitud),
                log.Coche.Chofer != null ? log.Coche.Chofer.Entidad.Descripcion : string.Empty
            }
                                 : new List <string>
            {
                "Sistema",
                "(Ninguno)",
                string.Format("{0} {1}", log.Fecha.ToShortDateString(), log.Fecha.ToShortTimeString()),
                log.Texto,
                GeocoderHelper.GetDescripcionEsquinaMasCercana(log.Latitud, log.Longitud),
                string.Empty
            };

            SendSms(log.Accion.DestinatariosSms, parameters);
        }
Пример #21
0
        protected override void Import(List <ImportRow> rows)
        {
            var empresa = cbEmpresa.Selected > 0 ? DAOFactory.EmpresaDAO.FindById(cbEmpresa.Selected) : null;
            var linea   = cbLinea.Selected > 0 ? DAOFactory.LineaDAO.FindById(cbLinea.Selected) : null;
            var tipoReferenciaDefault = cbTipoGeoRef.Selected > 0 ? DAOFactory.TipoReferenciaGeograficaDAO.FindById(cbTipoGeoRef.Selected) : null;

            var empresas = new [] { cbEmpresa.Selected };
            var lineas   = new[] { cbLinea.Selected };

            using (var transaction = SmartTransaction.BeginTransaction())
            {
                try
                {
                    foreach (var row in rows)
                    {
                        var tipoCliente = row.GetString(GetColumnByValue(Fields.TipoCliente.Value));
                        var cliente     = DAOFactory.ClienteDAO.FindByDescripcion(new[] { empresa.Id }, new[] { -1 }, tipoCliente);
                        var codigo      = row.GetString(GetColumnByValue(Fields.Codigo.Value));

                        var pto = DAOFactory.PuntoEntregaDAO.FindByCode(new[] { cliente.Empresa.Id }, new[] { cliente.Linea != null ? cliente.Linea.Id : -1 }, new[] { cliente.Id }, codigo);

                        if (pto == null)
                        {
                            var descripcion         = IsMapped(Fields.Descripcion.Value) ? row.GetString(GetColumnByValue(Fields.Descripcion.Value)) : codigo;
                            var longitud            = row.GetDouble(GetColumnByValue(Fields.Longitud.Value));
                            var latitud             = row.GetDouble(GetColumnByValue(Fields.Latitud.Value));
                            var vigenciaDesde       = DateTime.Now;
                            var direccionNomenclada = row.GetString(GetColumnByValue(Fields.Direccion.Value));
                            var geoRef   = new ReferenciaGeografica();
                            var telefono = "";

                            var tipoReferencia = tipoReferenciaDefault;
                            if (tipoReferencia == null)
                            {
                                throw new ApplicationException("Tipo de Referencia Geográfica inválido");
                            }


                            if (latitud.HasValue &&
                                longitud.HasValue)
                            {
                                if (direccionNomenclada == null)
                                {
                                    direccionNomenclada = string.Format("({0}, {1})", latitud.Value, longitud.Value);
                                }
                                geoRef = GetReferenciaGeografica(tipoReferencia, null, empresa, linea, codigo, descripcion, vigenciaDesde, null,
                                                                 latitud.Value, longitud.Value);
                            }

                            pto = CreatePuntoEntrega(cliente, codigo, descripcion, telefono, geoRef);
                        }
                        else
                        {
                            var descripcion = IsMapped(Fields.Descripcion.Value) ? row.GetString(GetColumnByValue(Fields.Descripcion.Value)) : codigo;
                            var longitud    = row.GetDouble(GetColumnByValue(Fields.Longitud.Value));
                            var latitud     = row.GetDouble(GetColumnByValue(Fields.Latitud.Value));

                            pto.Descripcion = descripcion;
                            pto.Nombre      = descripcion;

                            if (pto.ReferenciaGeografica.Latitude != latitud ||
                                pto.ReferenciaGeografica.Longitude != longitud)
                            {
                                pto.ReferenciaGeografica.Direccion.Vigencia.Fin = DateTime.UtcNow;
                                pto.ReferenciaGeografica.Poligono.Vigencia.Fin  = DateTime.UtcNow;

                                #region var posicion = new Direccion()

                                var direccion = GeocoderHelper.GetEsquinaMasCercana(latitud.Value, longitud.Value);

                                var posicion = new Direccion
                                {
                                    Altura       = direccion != null ? direccion.Altura : -1,
                                    IdMapa       = (short)(direccion != null ? direccion.IdMapaUrbano : -1),
                                    Provincia    = direccion != null ? direccion.Provincia : string.Empty,
                                    IdCalle      = direccion != null ? direccion.IdPoligonal : -1,
                                    IdEsquina    = direccion != null ? direccion.IdEsquina : -1,
                                    IdEntrecalle = -1,
                                    Latitud      = latitud.Value,
                                    Longitud     = longitud.Value,
                                    Partido      = direccion != null ? direccion.Partido : string.Empty,
                                    Pais         = string.Empty,
                                    Calle        = direccion != null ? direccion.Calle : string.Empty,
                                    Descripcion  =
                                        direccion != null
                                            ? direccion.Direccion
                                            : string.Format("({0}, {1})", latitud.Value.ToString(CultureInfo.InvariantCulture),
                                                            longitud.Value.ToString(CultureInfo.InvariantCulture)),
                                    Vigencia = new Vigencia {
                                        Inicio = DateTime.UtcNow
                                    }
                                };

                                #endregion

                                #region var poligono = new Poligono()

                                var poligono = new Poligono {
                                    Radio = 100, Vigencia = new Vigencia {
                                        Inicio = DateTime.UtcNow
                                    }
                                };
                                poligono.AddPoints(new[] { new PointF((float)longitud, (float)latitud) });

                                #endregion

                                pto.ReferenciaGeografica.AddHistoria(posicion, poligono, DateTime.UtcNow);

                                DAOFactory.ReferenciaGeograficaDAO.SaveOrUpdate(pto.ReferenciaGeografica);
                            }
                        }

                        DAOFactory.PuntoEntregaDAO.SaveOrUpdate(pto);
                    }
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    throw ex;
                }
            }
        }
Пример #22
0
        private void RecalcularHoras(int index)
        {
            var delta = GetDeltas();

            DeltaTime.Set(delta);

            var d            = StartDate.Get();
            var saleDePlanta = DateTime.MinValue;
            var saleDeObra   = DateTime.MinValue;

            var coche             = cbMovil.Selected > 0 ? DAOFactory.CocheDAO.FindById(cbMovil.Selected) : null;
            var velocidadPromedio = coche != null ? (coche.VelocidadPromedio > 0 ? coche.VelocidadPromedio
                : (coche.TipoCoche.VelocidadPromedio > 0 ? coche.TipoCoche.VelocidadPromedio : 20))
                                        : 20;

            var direccionLinea = GetDireccionLinea();
            var direccionMapa  = GetDireccionPuntoDeEntrega();

            foreach (C1GridViewRow item in gridEstados.Rows)
            {
                var estadoId = (int)gridEstados.DataKeys[item.RowIndex].Value;
                var estado   = DAOFactory.EstadoDAO.FindById(estadoId);

                if (estado.EsPuntoDeControl == 5)
                {
                    saleDePlanta = d;                               //Sale de Planta
                }
                if (estado.EsPuntoDeControl == 7)
                {
                    saleDeObra = d;                               //Sale de Obra
                }
                //if (item.RowIndex == 0) continue;
                if (item.RowIndex <= index)
                {
                    var txt = item.FindControl("txtHoraEstado") as TextBox;
                    if (txt != null)
                    {
                        d = GetHours(txt.Text, d);
                    }
                    continue;
                }

                if (estado.EsPuntoDeControl == 6 && saleDePlanta != DateTime.MinValue)
                {
                    //Llega a Obra
                    var distancia = direccionLinea != null && direccionMapa != null?
                                    GeocoderHelper.CalcularDistacia(direccionLinea.Latitude, direccionLinea.Longitude, direccionMapa.Latitude, direccionMapa.Longitude)
                                        : 0;

                    var horas = distancia / velocidadPromedio;

                    d = d.Add(horas > 0 ? TimeSpan.FromHours(horas) : delta[item.RowIndex]);

                    var txt = item.FindControl("txtHoraEstado") as TextBox;
                    var lbl = item.FindControl("lblDiaProgramado") as Label;
                    if (txt != null)
                    {
                        txt.Text = d.ToString("HH:mm");
                    }
                    if (lbl != null)
                    {
                        lbl.Text = d.ToString("dd-MM-yyyy");
                    }
                }
                else if (estado.EsPuntoDeControl == 8 && saleDeObra != DateTime.MinValue)
                {
                    ////Llega a Planta

                    var distancia = direccionLinea != null && direccionMapa != null?
                                    GeocoderHelper.CalcularDistacia(direccionMapa.Latitude, direccionMapa.Longitude, direccionLinea.Latitude, direccionLinea.Longitude)
                                        : 0;

                    var horas = distancia / velocidadPromedio;

                    d = d.Add(horas > 0 ? TimeSpan.FromHours(horas) : delta[item.RowIndex]);

                    var txt = item.FindControl("txtHoraEstado") as TextBox;
                    var lbl = item.FindControl("lblDiaProgramado") as Label;
                    if (txt != null)
                    {
                        txt.Text = d.ToString("HH:mm");
                    }
                    if (lbl != null)
                    {
                        lbl.Text = d.ToString("dd-MM-yyyy");
                    }
                }
                else
                {
                    //Normal
                    d = d.Add(delta[item.RowIndex]);

                    var txt = item.FindControl("txtHoraEstado") as TextBox;
                    var lbl = item.FindControl("lblDiaProgramado") as Label;
                    if (txt != null)
                    {
                        txt.Text = d.ToString("HH:mm");
                    }
                    if (lbl != null)
                    {
                        lbl.Text = d.ToString("dd-MM-yyyy");
                    }
                }
            }

            updGridEstados.Update();
        }
Пример #23
0
        public void RaiseCallbackEvent(string eventArgument)
        {
//            _inCallback = true;
            var idx       = eventArgument.IndexOf(':');
            var eventName = eventArgument.Substring(0, idx);
            var eventArgs = eventArgument.Length > idx?eventArgument.Substring(idx + 1) : "";

            switch (eventName)
            {
            case "Tick":
                OnTick(eventArgs);
                break;

            case "Click":
                var clickCoord = ParseCoord(eventArgs);
                if (clickCoord != null)
                {
                    OnClick(clickCoord.Latitud, clickCoord.Longitud);
                }
                break;

            case "MarkAddress":
                var markCoord = ParseCoord(eventArgs);
                if (markCoord != null)
                {
                    var dir = GeocoderHelper.GetDescripcionEsquinaMasCercana(markCoord.Latitud, markCoord.Longitud);
                    AddMarkers(GeocoderMarkersLayer, MarkerFactory.CreateMarker("0", DefaultMarkerIcon, markCoord.Latitud, markCoord.Longitud, dir));
                }
                break;

            //case "ContextMenuCallback":
            //    break;
            case "DrawPolygon":
                var points = ParsePolygon(eventArgs);
                OnDrawPolygon(points);
                break;

            case "DrawSquare":
                var bounds = ParseSquare(eventArgs);
                OnDrawSquare(bounds);
                break;

            case "DrawCircle":
                var circle = ParseCircle(eventArgs);
                if (circle != null)
                {
                    OnDrawCircle(circle.Latitud, circle.Longitud, circle.Radio);
                }
                break;

            case "DrawLine":
                var pointsPath = ParseLine(eventArgs);
                OnDrawLine(pointsPath);
                break;

            default:
                var args         = eventArgs.Split(',');
                var defaultCoord = ParseCoord(eventArgs);
                if (defaultCoord != null)
                {
                    OnCallback(eventName, args[2], defaultCoord.Latitud, defaultCoord.Longitud);
                }
                break;
            }
//            _inCallback = false;
        }
Пример #24
0
        public void ParseRutas(out int rutas, out int entregas, out string observaciones)
        {
            const int vigencia = 12;

            var te   = new TimeElapsed();
            var rows = ParseExcelFile(Llfile.FilePath, true);

            STrace.Trace(Component, string.Format("Archivo parseado en {0} segundos", te.getTimeElapsed().TotalSeconds));
            te.Restart();
            PreBufferRutas(rows);
            STrace.Trace(Component, string.Format("PreBufferRutas en {0} segundos", te.getTimeElapsed().TotalSeconds));

            var listViajes        = new List <ViajeDistribucion>();
            var listReferencias   = new List <ReferenciaGeografica>();
            var listPuntosEntrega = new List <PuntoEntrega>();

            rutas         = 0;
            entregas      = 0;
            observaciones = string.Empty;

            STrace.Trace(Component, "Cantidad de filas: " + rows.Count);
            var filas = 0;

            foreach (var row in rows)
            {
                filas++;
                STrace.Trace(Component, string.Format("Procesando fila: {0}/{1}", filas, rows.Count));

                var codigoLinea = "4"; // POR DEFAULT ES MUNRO
                var linea       = _lineasBuffer.SingleOrDefault(l => l.DescripcionCorta == codigoLinea);
                if (linea == null)
                {
                    observaciones = "Valor inválido para el campo LINEA";
                    continue;
                }

                var sFecha        = row[Properties.DistribucionCCU.Fecha].ToString().Trim();
                var planilla      = row[Properties.DistribucionCCU.Planilla].ToString().Trim();
                var codCliente    = row[Properties.DistribucionCCU.CodigoCliente].ToString().Trim();
                var factura       = row[Properties.DistribucionCCU.Factura].ToString().Trim();
                var sHectolitros  = row[Properties.DistribucionCCU.Hectolitros].ToString().Trim().Replace('.', ',');
                var sImporteTotal = row[Properties.DistribucionCCU.ImporteTotal].ToString().Trim().Replace('.', ',');
                var hectolitros   = Convert.ToDouble(sHectolitros);
                var importeTotal  = Convert.ToDouble(sImporteTotal);

                var dia   = Convert.ToInt32(sFecha.Substring(0, 2));
                var mes   = Convert.ToInt32(sFecha.Substring(3, 2));
                var anio  = Convert.ToInt32(sFecha.Substring(6, 4));
                var gmt   = new TimeSpan(-3, 0, 0);
                var fecha = new DateTime(anio, mes, dia, 4, 0, 0).Subtract(gmt);

                if (listViajes.Count == 0 || planilla != listViajes.Last().Codigo)
                {
                    var byCode = _viajesBuffer.SingleOrDefault(v => v.Codigo == planilla);
                    if (byCode != null)
                    {
                        continue;
                    }
                }

                ViajeDistribucion viaje;

                if (listViajes.Count > 0 && listViajes.Any(v => v.Codigo == planilla))
                {
                    viaje = listViajes.SingleOrDefault(v => v.Codigo == planilla);
                }
                else
                {
                    viaje = new ViajeDistribucion
                    {
                        Empresa      = this.Empresa,
                        Linea        = linea,
                        Codigo       = planilla,
                        Inicio       = fecha,
                        Fin          = fecha,
                        Tipo         = ViajeDistribucion.Tipos.Desordenado,
                        RegresoABase = true,
                        Estado       = ViajeDistribucion.Estados.Pendiente,
                        Alta         = DateTime.UtcNow,
                        NumeroViaje  = 1
                    };

                    listViajes.Add(viaje);
                    rutas++;
                }

                if (viaje.Detalles.Count == 0)
                {
                    //el primer elemento es la base
                    var origen = new EntregaDistribucion
                    {
                        Linea           = linea,
                        Descripcion     = linea.Descripcion,
                        Estado          = EntregaDistribucion.Estados.Pendiente,
                        Orden           = 0,
                        Programado      = fecha,
                        ProgramadoHasta = fecha,
                        Viaje           = viaje
                    };
                    viaje.Detalles.Add(origen);

                    var llegada = new EntregaDistribucion
                    {
                        Linea           = linea,
                        Descripcion     = linea.Descripcion,
                        Estado          = EntregaDistribucion.Estados.Pendiente,
                        Orden           = viaje.Detalles.Count,
                        Programado      = fecha,
                        ProgramadoHasta = fecha,
                        Viaje           = viaje
                    };
                    viaje.Detalles.Add(llegada);
                }

                if (viaje.Detalles.Where(d => d.PuntoEntrega != null).Any(d => d.PuntoEntrega.Codigo == codCliente))
                {
                    var detalle = viaje.Detalles.Where(d => d.PuntoEntrega != null).SingleOrDefault(d => d.PuntoEntrega.Codigo == codCliente);
                    detalle.Volumen += hectolitros;
                    detalle.Valor    = importeTotal;
                    continue;
                }

                var puntoEntrega = _clientesBuffer.SingleOrDefault(p => p.Codigo == codCliente);

                if (puntoEntrega == null)
                {
                    observaciones = "Valor inválido para el campo PUNTO ENTREGA";
                    continue;
                }
                else
                {
                    var end = fecha.AddHours(vigencia);
                    if (puntoEntrega.ReferenciaGeografica.Vigencia.Fin < end)
                    {
                        puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end;
                    }

                    listReferencias.Add(puntoEntrega.ReferenciaGeografica);
                    listPuntosEntrega.Add(puntoEntrega);
                }

                var entrega = new EntregaDistribucion
                {
                    Cliente         = puntoEntrega.Cliente,
                    PuntoEntrega    = puntoEntrega,
                    Descripcion     = factura,
                    Estado          = EntregaDistribucion.Estados.Pendiente,
                    Orden           = viaje.Detalles.Count - 1,
                    Programado      = fecha,
                    ProgramadoHasta = fecha.AddMinutes(Empresa.MarginMinutes),
                    Viaje           = viaje,
                    Volumen         = hectolitros,
                    Valor           = importeTotal
                };

                viaje.Detalles.Add(entrega);
                entregas++;
            }

            var nroViaje = 0;

            foreach (var viajeDistribucion in listViajes)
            {
                nroViaje++;
                if (viajeDistribucion.Detalles.Count > 0)
                {
                    var dirBase           = viajeDistribucion.Detalles.First().ReferenciaGeografica;
                    var velocidadPromedio = 20;

                    var hora       = viajeDistribucion.Inicio;
                    var nroEntrega = 0;
                    foreach (var detalle in viajeDistribucion.Detalles)
                    {
                        nroEntrega++;
                        STrace.Trace(Component, string.Format("Calculando horarios, viaje {0}/{1}, entrega {2}/{3}", nroViaje, listViajes.Count, nroEntrega, viajeDistribucion.Detalles.Count()));
                        var distancia = GeocoderHelper.CalcularDistacia(dirBase.Latitude, dirBase.Longitude, detalle.ReferenciaGeografica.Latitude, detalle.ReferenciaGeografica.Longitude);
                        var horas     = distancia / velocidadPromedio;
                        var demora    = detalle.TipoServicio != null ? detalle.TipoServicio.Demora : 0;
                        detalle.Programado      = hora.AddHours(horas).AddMinutes(demora);
                        detalle.ProgramadoHasta = detalle.Programado.AddMinutes(Empresa.MarginMinutes);
                        detalle.KmCalculado     = distancia;
                        dirBase = detalle.ReferenciaGeografica;
                        hora    = detalle.Programado;
                    }
                }

                var maxDate = viajeDistribucion.Detalles.Max(d => d.Programado);
                viajeDistribucion.Fin = maxDate;

                var ultimo = viajeDistribucion.Detalles.Last(e => e.Linea != null);
                ultimo.Programado      = maxDate;
                ultimo.ProgramadoHasta = maxDate.AddMinutes(Empresa.MarginMinutes);
                ultimo.Orden           = viajeDistribucion.Detalles.Count - 1;
            }

            STrace.Trace(Component, "Guardando referencias geográficas: " + listReferencias.Count);
            te.Restart();
            foreach (var referenciaGeografica in listReferencias)
            {
                DaoFactory.ReferenciaGeograficaDAO.Guardar(referenciaGeografica);
                AddReferenciasGeograficas(referenciaGeografica);
            }
            STrace.Trace(Component, string.Format("Referencias guardadas en {0} segundos", te.getTimeElapsed().TotalSeconds));

            STrace.Trace(Component, "Guardando puntos de entrega: " + listPuntosEntrega.Count);
            te.Restart();
            foreach (var puntoEntrega in listPuntosEntrega)
            {
                DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntrega);
            }
            STrace.Trace(Component, string.Format("Puntos guardados en {0} segundos", te.getTimeElapsed().TotalSeconds));

            STrace.Trace(Component, "Guardando Viajes: " + listViajes.Count);
            te.Restart();
            foreach (var viajeDistribucion in listViajes)
            {
                DaoFactory.ViajeDistribucionDAO.SaveOrUpdate(viajeDistribucion);
            }
            STrace.Trace(Component, string.Format("Viajes guardados en {0} segundos", te.getTimeElapsed().TotalSeconds));
        }
Пример #25
0
        private void GetCenter(IEnumerable <List <RoutePosition> > routes)
        {
            var centerPosition = PosCenterIndex;

            if (centerPosition == null)
            {
                return;
            }

            foreach (var position in routes.SelectMany(route => route.Where(position => position.Id.Equals(centerPosition.Value))))
            {
                Monitor.AddMarkers(Layers.Eventos, new Marker(position.Date.ToDisplayDateTime().ToString(), Images.CurrentPosition, position.Latitude, position.Longitude,
                                                              string.Format("javascript:gCP('{0}', '{1}', '{2}')", GeocoderHelper.GetDescripcionEsquinaMasCercana(position.Latitude, position.Longitude),
                                                                            position.Date.ToDisplayDateTime(), position.Speed),
                                                              DrawingFactory.GetSize(21, 25), DrawingFactory.GetOffset(-10.5, -25)));

                _x = position.Latitude;
                _y = position.Longitude;

                Monitor.TriggerEvent(position.Date.ToDisplayDateTime().ToString(), Layers.Eventos, PopupEvent);
            }
        }
Пример #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int id;
                if (Request.QueryString["id"] == null || !int.TryParse(Request.QueryString["id"], out id))
                {
                    LblInfo.Text = CultureManager.GetError("NO_ENTREGA_INFO");
                    return;
                }

                var entrega = DAOFactory.EntregaDistribucionDAO.FindById(id);
                if (entrega != null)
                {
                    var icono = entrega.PuntoEntrega.ReferenciaGeografica.Icono != null?Path.Combine(IconDir, entrega.PuntoEntrega.ReferenciaGeografica.Icono.PathIcono) : ResolveUrl("~/point.png");

                    imgIcono.Src        = icono;
                    lblCodigo.Text      = string.Format("{0} - {1}<br>{2}", entrega.PuntoEntrega.Codigo, entrega.PuntoEntrega.Descripcion, GeocoderHelper.GetDescripcionEsquinaMasCercana(entrega.PuntoEntrega.ReferenciaGeografica.Latitude, entrega.PuntoEntrega.ReferenciaGeografica.Longitude));
                    lblDescripcion.Text = entrega.Descripcion;
                    lblProgramado.Text  = entrega.Programado.ToDisplayDateTime().ToString("HH:mm");
                    //lblGps.Text = entrega.KmGps.HasValue ? entrega.KmGps.Value.ToString(CultureInfo.InvariantCulture) : "N/D";
                    lblEntrada.Text = entrega.Entrada.HasValue ? entrega.Entrada.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty;
                    lblManual.Text  = entrega.Manual.HasValue ? entrega.Manual.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty;
                    lblSalida.Text  = entrega.Salida.HasValue ? entrega.Salida.Value.ToDisplayDateTime().ToString("HH:mm") : string.Empty;
                    //lblCalculado.Text = entrega.KmCalculado.HasValue ? entrega.KmCalculado.Value.ToString(CultureInfo.InvariantCulture) : "N/D";
                    //lblControlado.Text = entrega.Viaje.Controlado && entrega.KmControlado.HasValue ? entrega.KmControlado.Value.ToString(CultureInfo.InvariantCulture) : "N/D";
                    lblEstado.Text = CultureManager.GetLabel(EntregaDistribucion.Estados.GetLabelVariableName(entrega.Estado));
                    lnkEditarPunto.OnClientClick = string.Format("window.open('../Parametrizacion/GeoRefAlta.aspx?id={0}')", entrega.PuntoEntrega.ReferenciaGeografica.Id);
                }
            }
        }
Пример #27
0
        public void Parse(out int rutas, out int entregas)
        {
            const int vigencia = 24;

            var te   = new TimeElapsed();
            var rows = ParseFile(Llfile.FilePath, Properties.DistribucionReginaldLee.Anchos).Rows;

            STrace.Trace(Component, string.Format("Archivo parseado en {0} segundos", te.getTimeElapsed().TotalSeconds));
            te.Restart();
            PreBufferRows(rows);
            STrace.Trace(Component, string.Format("PreBufferRows en {0} segundos", te.getTimeElapsed().TotalSeconds));

            var listViajes      = new List <ViajeDistribucion>(rows.Count);
            var listPuntos      = new List <PuntoEntrega>();
            var listReferencias = new List <ReferenciaGeografica>();

            rutas    = 0;
            entregas = 0;

            STrace.Trace(Component, "Cantidad de filas: " + rows.Count);
            var filas = 0;

            foreach (var row in rows)
            {
                filas++;
                STrace.Trace(Component, string.Format("Procesando fila: {0}/{1}", filas, rows.Count));

                var ruta = row.Cells[Properties.DistribucionReginaldLee.CodigoRuta].ToString().Trim();
                if (ruta == string.Empty)
                {
                    ThrowProperty("CODIGO_RUTA", Llfile.Strategy);
                }

                var nroViaje = 1;
                if (ruta.Contains(","))
                {
                    var rutaSplitted = ruta.Split(',');
                    int.TryParse(rutaSplitted[1], out nroViaje);
                }

                var codEntrega = row.Cells[Properties.DistribucionReginaldLee.CodigoPedido].ToString().Trim();
                if (codEntrega == string.Empty)
                {
                    ThrowProperty("CODIGO_ENTREGA", Llfile.Strategy);
                }

                var codCliente = row.Cells[Properties.DistribucionReginaldLee.CodigoCliente].ToString().Trim();
                if (codCliente == string.Empty)
                {
                    ThrowProperty("CODIGO_CLIENTE", Llfile.Strategy);
                }

                var    rowWithCoords = true;
                double latitud;
                double longitud;

                if (!double.TryParse(row.Cells[Properties.DistribucionReginaldLee.Latitud].ToString().Trim(), out latitud))
                {
                    rowWithCoords = false;
                }
                if (!double.TryParse(row.Cells[Properties.DistribucionReginaldLee.Longitud].ToString().Trim(), out longitud))
                {
                    rowWithCoords = false;
                }

                var orientacionSouthNorth = row.Cells[Properties.DistribucionReginaldLee.OrientacionNorthSouth].ToString().Trim();
                var orientacionEastWest   = row.Cells[Properties.DistribucionReginaldLee.OrientacionEastWest].ToString().Trim();

                if (orientacionSouthNorth.Equals("S"))
                {
                    latitud = latitud * (-1);
                }
                if (orientacionEastWest.Equals("W"))
                {
                    longitud = longitud * (-1);
                }

                var fecha = row.Cells[Properties.DistribucionReginaldLee.Fecha].ToString().Trim();
                if (fecha == string.Empty)
                {
                    ThrowProperty("FECHA", Llfile.Strategy);
                }

                int dia, mes, anio, hr, min;
                int.TryParse(fecha.Substring(0, 4), out anio);
                int.TryParse(fecha.Substring(5, 2), out mes);
                int.TryParse(fecha.Substring(8, 2), out dia);
                int.TryParse(fecha.Substring(11, 2), out hr);
                int.TryParse(fecha.Substring(14, 2), out min);

                var gmt  = new TimeSpan(-3, 0, 0);
                var date = new DateTime(anio, mes, dia, hr, min, 0).Subtract(gmt);

                int packs;
                if (!int.TryParse(row.Cells[Properties.DistribucionReginaldLee.Packs].ToString().Trim(), out packs))
                {
                    try
                    {
                        ThrowProperty("PACKS", Llfile.Strategy);
                    }
                    catch (Exception ex2)
                    {
                        STrace.Exception(Component, ex2, String.Format("Error en Fila #{0}: {1}", filas, ex2.Message));
                        continue;
                    }
                }

                var codigo = date.ToString("yyMMdd") + "|" + ruta;

                if (listViajes.Count == 0 || codigo != listViajes.Last().Codigo)
                {
                    var byCode = _viajesBuffer.SingleOrDefault(v => v.Codigo == codigo);
                    if (byCode != null)
                    {
                        continue;
                    }
                }

                ViajeDistribucion item;

                if (listViajes.Count > 0 && listViajes.Any(v => v.Codigo == codigo))
                {
                    item = listViajes.SingleOrDefault(v => v.Codigo == codigo);
                }
                else
                {
                    item = new ViajeDistribucion {
                        Codigo = codigo
                    };
                    rutas++;

                    Coche vehiculo = null;
                    var   interno  = row.Cells[Properties.DistribucionReginaldLee.Interno].ToString().Trim();
                    if (interno.Length == 3)
                    {
                        interno = "0" + interno;
                    }
                    if (!string.IsNullOrEmpty(interno))
                    {
                        vehiculo = _cochesBuffer.SingleOrDefault(c => c.Interno == interno);
                    }

                    if (vehiculo == null)
                    {
                        ThrowProperty("VEHICULO", Llfile.Strategy);
                    }
                    else if (vehiculo.Linea == null)
                    {
                        ThrowProperty("BASE", Llfile.Strategy);
                    }

                    item.Empresa      = Empresa;
                    item.Linea        = vehiculo.Linea;
                    item.Vehiculo     = vehiculo;
                    item.Inicio       = date;
                    item.Fin          = date;
                    item.Tipo         = ViajeDistribucion.Tipos.Desordenado;
                    item.RegresoABase = true;
                    item.Estado       = ViajeDistribucion.Estados.Pendiente;
                    item.Alta         = DateTime.UtcNow;
                    item.NumeroViaje  = Convert.ToInt32(nroViaje);

                    listViajes.Add(item);
                }

                // Entregas
                if (item.Detalles.Count == 0)
                {   // Si no existe, agrego la salida de base
                    var origen = new EntregaDistribucion
                    {
                        Linea           = item.Linea,
                        Descripcion     = item.Linea.Descripcion,
                        Estado          = EntregaDistribucion.Estados.Pendiente,
                        Orden           = 0,
                        Programado      = date,
                        ProgramadoHasta = date,
                        Viaje           = item
                    };
                    item.Detalles.Add(origen);

                    var llegada = new EntregaDistribucion
                    {
                        Linea           = item.Linea,
                        Descripcion     = item.Linea.Descripcion,
                        Estado          = EntregaDistribucion.Estados.Pendiente,
                        Orden           = item.Detalles.Count,
                        Programado      = date,
                        ProgramadoHasta = date,
                        Viaje           = item
                    };
                    item.Detalles.Add(llegada);
                }

                if (item.Detalles.Any(d => d.PuntoEntrega != null && d.PuntoEntrega.Codigo == codCliente))
                {
                    var repetido = item.Detalles.FirstOrDefault(d => d.PuntoEntrega != null && d.PuntoEntrega.Codigo == codCliente);
                    repetido.Bultos += packs;
                    continue;
                }

                TipoServicioCiclo tipoServicio = null;
                var tipoServ = _tiposServicioBuffer.SingleOrDefault(ts => ts.Linea.Id == item.Linea.Id || ts.Linea == null);
                if (tipoServ != null && tipoServ.Id > 0)
                {
                    tipoServicio = tipoServ;
                }

                var puntoEntrega = _puntosBuffer.SingleOrDefault(p => p.Codigo == codCliente);
                if (puntoEntrega == null)
                {
                    var descCliente = row.Cells[Properties.DistribucionReginaldLee.DescripcionCliente].ToString().Trim();

                    var puntoDeInteres = new ReferenciaGeografica
                    {
                        Codigo                   = codCliente,
                        Descripcion              = descCliente,
                        Empresa                  = Empresa,
                        Linea                    = item.Linea,
                        EsFin                    = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsFin,
                        EsInicio                 = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsInicio,
                        EsIntermedio             = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.EsIntermedio,
                        InhibeAlarma             = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.InhibeAlarma,
                        TipoReferenciaGeografica = Cliente.ReferenciaGeografica.TipoReferenciaGeografica,
                        Vigencia                 = new Vigencia {
                            Inicio = date.Date, Fin = date.AddHours(vigencia)
                        },
                        Icono = Cliente.ReferenciaGeografica.TipoReferenciaGeografica.Icono
                    };

                    if (!rowWithCoords)
                    {
                        try
                        {
                            ThrowProperty("LATITUD_LONGITUD", Llfile.Strategy);
                        }
                        catch (Exception ex)
                        {
                            STrace.Exception(Component, ex, String.Format("Error en Fila #{0}: {1}", filas, ex.Message));
                            continue;
                        }
                    }

                    var posicion = GetNewDireccion(latitud, longitud);

                    var poligono = new Poligono {
                        Radio = 50, Vigencia = new Vigencia {
                            Inicio = date.Date
                        }
                    };
                    poligono.AddPoints(new[] { new PointF((float)longitud, (float)latitud) });

                    puntoDeInteres.Historia.Add(new HistoriaGeoRef
                    {
                        ReferenciaGeografica = puntoDeInteres,
                        Direccion            = posicion,
                        Poligono             = poligono,
                        Vigencia             = new Vigencia {
                            Inicio = date.Date
                        }
                    });

                    listReferencias.Add(puntoDeInteres);

                    puntoEntrega = new PuntoEntrega
                    {
                        Cliente              = Cliente,
                        Codigo               = codCliente,
                        Descripcion          = descCliente,
                        Telefono             = string.Empty,
                        Baja                 = false,
                        ReferenciaGeografica = puntoDeInteres,
                        Nomenclado           = true,
                        DireccionNomenclada  = string.Empty,
                        Nombre               = descCliente
                    };
                }
                else
                {
                    if (!rowWithCoords)
                    {
                        try
                        {
                            ThrowProperty("LATITUD_LONGITUD", Llfile.Strategy);
                        }
                        catch (Exception ex)
                        {
                            STrace.Exception(Component, ex, String.Format("Error en Fila #{0}: {1}", filas, ex.Message));
                            continue;
                        }
                    }

                    if (!puntoEntrega.ReferenciaGeografica.IgnoraLogiclink && (puntoEntrega.ReferenciaGeografica.Latitude != latitud || puntoEntrega.ReferenciaGeografica.Longitude != longitud))
                    {
                        puntoEntrega.ReferenciaGeografica.Direccion.Vigencia.Fin = date.Date;
                        puntoEntrega.ReferenciaGeografica.Poligono.Vigencia.Fin  = date.Date;

                        var posicion = GetNewDireccion(latitud, longitud);
                        var poligono = new Poligono {
                            Radio = 50, Vigencia = new Vigencia {
                                Inicio = date.Date
                            }
                        };
                        poligono.AddPoints(new[] { new PointF((float)longitud, (float)latitud) });

                        puntoEntrega.ReferenciaGeografica.AddHistoria(posicion, poligono, date.Date);
                    }

                    if (puntoEntrega.ReferenciaGeografica.Vigencia.Inicio > date.Date)
                    {
                        puntoEntrega.ReferenciaGeografica.Vigencia.Inicio = date.Date;
                    }

                    var end = date.AddHours(vigencia);
                    if (puntoEntrega.ReferenciaGeografica.Vigencia.Fin < end)
                    {
                        puntoEntrega.ReferenciaGeografica.Vigencia.Fin = end;
                    }

                    puntoEntrega.ReferenciaGeografica.Linea = item.Linea;
                    listReferencias.Add(puntoEntrega.ReferenciaGeografica);
                }

                listPuntos.Add(puntoEntrega);

                var kms      = 0.0;
                var orden    = item.Detalles.Count - 1;
                var anterior = item.Detalles.FirstOrDefault(d => d.Orden == orden - 1);
                if (anterior != null)
                {
                    kms = GeocoderHelper.CalcularDistacia(anterior.ReferenciaGeografica.Latitude, anterior.ReferenciaGeografica.Longitude, puntoEntrega.ReferenciaGeografica.Latitude, puntoEntrega.ReferenciaGeografica.Longitude);
                }
                var entrega = new EntregaDistribucion
                {
                    Cliente         = puntoEntrega.Cliente,
                    PuntoEntrega    = puntoEntrega,
                    Descripcion     = codEntrega,
                    Estado          = EntregaDistribucion.Estados.Pendiente,
                    Orden           = orden,
                    Programado      = date,
                    ProgramadoHasta = date,
                    TipoServicio    = tipoServicio,
                    Viaje           = item,
                    Bultos          = packs
                };

                item.Detalles.Add(entrega);
                entregas++;

                var maxDate = item.Detalles.Max(d => d.Programado);
                item.Fin = maxDate;

                var ultimo = item.Detalles.Last(e => e.Linea != null);
                ultimo.Programado      = maxDate;
                ultimo.ProgramadoHasta = maxDate;
                ultimo.Orden           = item.Detalles.Count - 1;
            }

            STrace.Trace(Component, "Guardando referencias geográficas: " + listReferencias.Count);
            te.Restart();
            foreach (var referenciaGeografica in listReferencias)
            {
                DaoFactory.ReferenciaGeograficaDAO.Guardar(referenciaGeografica);
            }
            STrace.Trace(Component, string.Format("Referencias guardadas en {0} segundos", te.getTimeElapsed().TotalSeconds));

            STrace.Trace(Component, "Guardando puntos de entrega: " + listPuntos.Count);
            te.Restart();
            foreach (var puntoEntrega in listPuntos)
            {
                DaoFactory.PuntoEntregaDAO.SaveOrUpdate(puntoEntrega);
            }
            STrace.Trace(Component, string.Format("Puntos guardados en {0} segundos", te.getTimeElapsed().TotalSeconds));

            STrace.Trace(Component, "Guardando Viajes: " + listViajes.Count);
            te.Restart();
            foreach (var viajeDistribucion in listViajes)
            {
                DaoFactory.ViajeDistribucionDAO.SaveOrUpdate(viajeDistribucion);
            }
            STrace.Trace(Component, string.Format("Viajes guardados en {0} segundos", te.getTimeElapsed().TotalSeconds));
        }
Пример #28
0
        protected void ShowMensaje(LogMensaje mensaje)
        {
            var iconDir = IconDir;

            var color = mensaje.Accion != null
                            ? Color.FromArgb(100, mensaje.Accion.Red, mensaje.Accion.Green, mensaje.Accion.Blue)
                            : Color.Gray;

            panelTitle.BackColor = color;
            panelTitle.ForeColor = color.GetBrightness() < 40 ? Color.White: Color.Black;

            if (mensaje.Accion != null && mensaje.Accion.PopIcon > 0)
            {
                imgAccion.ImageUrl = string.Format("{0}/{1}", iconDir, mensaje.Accion.PopUpIcon.PathIcono);
            }
            else
            {
                imgAccion.Visible = false;
            }

            lbMensaje.Text    = mensaje.Texto;
            lblHora.Text      = mensaje.Fecha.ToDisplayDateTime().ToString("dd/MM/yyyy HH:mm");
            lblRecepcion.Text = mensaje.FechaAlta.HasValue
                                    ? "(" + mensaje.FechaAlta.Value.ToDisplayDateTime().ToString("dd/MM/yyyy HH:mm") + ")"
                                    : string.Empty;

            var pos = mensaje.Fecha;

            var link = string.Format(
                "../Monitor/MonitorHistorico/monitorHistorico.aspx?Planta={0}&TypeMobile={1}&Movil={2}&InitialDate={3}&FinalDate={4}&ShowMessages=0&ShowPOIS=0&Empresa={5}",
                mensaje.Coche.Linea != null ? mensaje.Coche.Linea.Id : -1, mensaje.Coche.TipoCoche.Id, mensaje.Coche.Id, pos.Subtract(TimeSpan.FromMinutes(15)).ToString(CultureInfo.InvariantCulture),
                pos.Add(TimeSpan.FromMinutes(1)).ToString(CultureInfo.InvariantCulture), mensaje.Coche.Empresa != null ? mensaje.Coche.Empresa.Id : mensaje.Coche.Linea != null ? mensaje.Coche.Linea.Empresa.Id : -1);

            lbMensaje.OnClientClick = string.Format("window.open('{0}', '" + CultureManager.GetMenu("OPE_MON_HISTORICO") + "')", link);

            lblMovil.Text = mensaje.Coche.Interno;
            var imgMovl = string.Format("{0}/{1}", iconDir, mensaje.Coche.TipoCoche.IconoNormal.PathIcono);

            imgMovil.ImageUrl = imgMovl;

            var chofer = mensaje.Chofer ?? mensaje.Coche.Chofer;

            lblChofer.Text = chofer != null
                                 ? string.Format("{0} - {1}", chofer.Legajo, chofer.Entidad.Descripcion)
                                 : CultureManager.GetString("Labels", "SIN_CHOFER");

            lblDireccion.Text = GeocoderHelper.GetDescripcionEsquinaMasCercana(mensaje.Latitud, mensaje.Longitud);

            lblLatitud.Text  = mensaje.Latitud.ToString(CultureInfo.InvariantCulture);
            lblLongitud.Text = mensaje.Longitud.ToString(CultureInfo.InvariantCulture);

            Monitor1.ImgPath          = Config.Monitor.GetMonitorImagesFolder(this);
            Monitor1.GoogleMapsScript = GoogleMapsKey;
            Monitor1.EnableTimer      = false;
            Monitor1.AddLayers(LayerFactory.GetGoogleStreet(CultureManager.GetLabel("LAYER_GSTREET"), 8),
                               //LayerFactory.GetCompumap(CultureManager.GetLabel("LAYER_COMPUMAP"), Config.Map.CompumapTiles, 8),
                               LayerFactory.GetOpenStreetMap(CultureManager.GetLabel("LAYER_OSM")),
                               LayerFactory.GetGoogleSatellite(CultureManager.GetLabel("LAYER_GSAT"), 8),
                               LayerFactory.GetGoogleHybrid(CultureManager.GetLabel("LAYER_GHIBRIDO"), 8),
                               LayerFactory.GetGooglePhysical(CultureManager.GetLabel("LAYER_GFISICO"), 8),
                               LayerFactory.GetMarkers(LayerVehiculos, true));
            Monitor1.AddControls(ControlFactory.GetLayerSwitcher(),
                                 ControlFactory.GetNavigation());
            Monitor1.SetCenter(mensaje.Latitud, mensaje.Longitud, 7);
            Monitor1.AddMarkers(LayerVehiculos, MarkerFactory.CreateMarker(mensaje.Coche.Id.ToString("#0"), imgMovl, mensaje.Latitud, mensaje.Longitud));

            var empresa = mensaje.Coche.Empresa;
            var linea   = mensaje.Coche.Linea;
            var user    = WebSecurity.AuthenticatedUser != null?DAOFactory.UsuarioDAO.FindById(WebSecurity.AuthenticatedUser.Id) : null;

            var mensajes = DAOFactory.MensajeDAO.FindByTipo(null, empresa, linea, user);
            var messages = mensajes.Where(m => m.TipoMensaje.DeAtencion).OrderBy(m => m.Descripcion);

            cbMensaje.ClearItems();
            cbMensaje.AddItem(CultureManager.GetControl("DDL_NO_MESSAGE"), cbMensaje.NoneValue);
            foreach (var msg in messages)
            {
                cbMensaje.AddItem(msg.Descripcion, msg.Id);
            }

            if (mensaje.Estado > 0)
            {
                btAceptar.Visible  = false;
                btIgnorar.ImageUrl = "~/Operacion/btAtras.gif";

                var atencion = DAOFactory.AtencionEventoDAO.GetByEvento(mensaje.Id);
                if (atencion != null)
                {
                    panelUsuario.Visible = true;
                    lblUsuario.Text      = atencion.Usuario.NombreUsuario;
                    panelFecha.Visible   = true;
                    lblFecha.Text        = atencion.Fecha.ToDisplayDateTime().ToString("dd/MM/yyyy HH:mm");
                    cbMensaje.SetSelectedValue(atencion.Mensaje.Id);
                    cbMensaje.Enabled      = false;
                    txtObservacion.Text    = atencion.Observacion;
                    txtObservacion.Enabled = false;
                }
            }

            if (!WebSecurity.IsSecuredAllowed(Securables.EventAttention))
            {
                btAceptar.Visible  = false;
                btIgnorar.ImageUrl = "~/Operacion/btAtras.gif";
            }
        }
Пример #29
0
        public void ProcessArchivo(LogicLinkFile archivo)
        {
            archivo.Status = LogicLinkFile.Estados.Procesando;
            DaoFactory.LogicLinkFileDAO.SaveOrUpdate(archivo);

            using (var transaction = SmartTransaction.BeginTransaction())
            {
                try
                {
                    STrace.Trace(Component, "Procesando con Estrategia: " + archivo.Strategy);
                    var rutas               = 0;
                    var entregas            = 0;
                    var clientes            = 0;
                    var asignaciones        = 0;
                    var result              = string.Empty;
                    var observaciones       = string.Empty;
                    ViajeDistribucion viaje = null;

                    switch (archivo.Strategy)
                    {
                    case LogicLinkFile.Estrategias.DistribucionFemsa:
                        DistribucionFemsa.Parse(archivo, out rutas, out entregas);
                        _update = true;
                        result  = string.Format("Archivo procesado exitosamente. Rutas: {0} - Entregas: {1}", rutas, entregas);
                        break;

                    case LogicLinkFile.Estrategias.DistribucionQuilmes:
                        DistribucionQuilmes.Parse(archivo, out rutas, out entregas, out observaciones);
                        _update = true;
                        result  = string.Format("Archivo procesado exitosamente. Rutas: {0} - Entregas: {1}", rutas, entregas);
                        if (observaciones != string.Empty)
                        {
                            result = result + " (" + observaciones + ")";
                        }
                        break;

                    case LogicLinkFile.Estrategias.DistribucionMusimundo:
                        DistribucionMusimundo.Parse(archivo, out rutas, out entregas, out observaciones);
                        _update = true;
                        result  = string.Format("Archivo procesado exitosamente. Rutas: {0} - Entregas: {1}", rutas, entregas);
                        if (observaciones != string.Empty)
                        {
                            result = result + " (" + observaciones + ")";
                        }
                        break;

                    case LogicLinkFile.Estrategias.DistribucionBrinks:
                        //DistribucionBrinks.Parse(archivo, out rutas, out entregas);
                        break;

                    case LogicLinkFile.Estrategias.DistribucionSos:
                        viaje  = DistribucionSos.Parse(archivo, out rutas, out entregas);
                        result = string.Format("Archivo procesado exitosamente. Rutas: {0} - Entregas: {1}", rutas, entregas);
                        break;

                    case LogicLinkFile.Estrategias.DistribucionReginaldLee:
                        DistribucionReginaldLee.Parse(archivo, out rutas, out entregas);
                        _update = true;
                        result  = string.Format("Archivo procesado exitosamente. Rutas: {0} - Entregas: {1}", rutas, entregas);
                        break;

                    case LogicLinkFile.Estrategias.DistribucionCCU:
                        var extension = GetFileName(archivo.FilePath);
                        switch (extension)
                        {
                        case "Rutas.xlsx":
                            DistribucionCCU.ParseRutas(archivo, out rutas, out entregas, out observaciones);
                            _update = true;
                            result  = string.Format("Archivo procesado exitosamente. Rutas: {0} - Entregas: {1}", rutas, entregas);
                            break;

                        case "Clientes.xlsx":
                            DistribucionCCU.ParseClientes(archivo, out clientes);
                            result = string.Format("Archivo procesado exitosamente. Clientes: {0}", clientes);
                            break;

                        case "Asigno.xlsx":
                            DistribucionCCU.ParseAsignaciones(archivo, out asignaciones, out observaciones);
                            result = string.Format("Archivo procesado exitosamente. Asignaciones: {0}", asignaciones);
                            break;

                        default:
                            result = string.Format("Extensión '" + extension + "' no válida.");
                            break;
                        }
                        break;

                    case LogicLinkFile.Estrategias.PedidosPetrobras:
                        var pedidos = 0;
                        PedidosPetrobras.Parse(archivo, out pedidos, out observaciones);
                        result = string.Format("Archivo procesado exitosamente. Pedidos: {0}", pedidos);
                        if (observaciones != string.Empty)
                        {
                            result = result + " (" + observaciones + ")";
                        }
                        break;

                    case LogicLinkFile.Estrategias.AsignacionClienteEmpleado:
                        var asignados = 0;
                        AsignacionClienteEmpleado.Parse(archivo, out asignados, out observaciones);
                        result = string.Format("Archivo procesado exitosamente. Asignados: {0}", asignados);
                        if (observaciones != string.Empty)
                        {
                            result = result + " (" + observaciones + ")";
                        }
                        break;

                    case LogicLinkFile.Estrategias.AsignacionCodigoViaje:
                        var viajes = 0;
                        AsignacionCodigoViaje.Parse(archivo, out viajes, out observaciones);
                        result = string.Format("Archivo procesado exitosamente. Viajes: {0}", viajes);
                        if (observaciones != string.Empty)
                        {
                            result = result + " (" + observaciones + ")";
                        }
                        break;
                    }

                    archivo.Status        = LogicLinkFile.Estados.Procesado;
                    archivo.DateProcessed = DateTime.UtcNow;
                    archivo.Result        = result;
                    DaoFactory.LogicLinkFileDAO.SaveOrUpdate(archivo);

                    transaction.Commit();

                    if (archivo.Strategy == LogicLinkFile.Estrategias.DistribucionSos)
                    {
                        if (viaje != null)
                        {
                            foreach (var detalle in viaje.Detalles)
                            {
                                if (detalle.PuntoEntrega != null && detalle.PuntoEntrega.ReferenciaGeografica != null)
                                {
                                    _update = true;
                                }
                            }

                            if (viaje.Vehiculo != null && viaje.Estado == ViajeDistribucion.Estados.Pendiente)
                            {
                                var tieneViajeEnCurso = DaoFactory.ViajeDistribucionDAO.FindEnCurso(viaje.Vehiculo) != null;
                                if (!tieneViajeEnCurso)
                                {
                                    //var ciclo = new CicloLogisticoDistribucion(viaje, DaoFactory,
                                    //    new MessageSaver(DaoFactory));
                                    //var evento = new InitEvent(DateTime.UtcNow);
                                    //ciclo.ProcessEvent(evento);
                                }
                                if (viaje.Vehiculo.Dispositivo != null)
                                {
                                    var msg   = new StringBuilder();
                                    var desde = viaje.Detalles[1].ReferenciaGeografica;
                                    var hasta = viaje.Detalles[2].ReferenciaGeografica;
                                    msg.Append("Viaje: " + viaje.Codigo);
                                    msg.Append("<br>Desde: " + GeocoderHelper.GetDescripcionEsquinaMasCercana(desde.Latitude, desde.Longitude));
                                    msg.Append("<br>Hasta: " + GeocoderHelper.GetDescripcionEsquinaMasCercana(hasta.Latitude, hasta.Longitude));

                                    var message = MessageSender.CreateSubmitTextMessage(viaje.Vehiculo.Dispositivo, new MessageSaver(DaoFactory));
                                    message.AddMessageText(msg.ToString());
                                    message.Send();

                                    //STrace.Trace(Component, "Ruta Aceptada: " + MessageCode.RutaAceptada.ToString());
                                    //STrace.Trace(Component, "Ruta Rechazada: " + MessageCode.RutaRechazada.ToString());

                                    //var msgText = "Acepta la asignacion del servicio <br><b>" + viaje.Codigo + "</b>?";
                                    //var replies = new[] { Convert.ToUInt32(MessageCode.RutaAceptada.ToString()),
                                    //                      Convert.ToUInt32(MessageCode.RutaRechazada.ToString()) };
                                    //message = MessageSender.CreateSubmitCannedResponsesTextMessage(viaje.Vehiculo.Dispositivo, new MessageSaver(DaoFactory));
                                    //message.AddMessageText(msgText)
                                    //       .AddTextMessageId(Convert.ToUInt32(viaje.Id))
                                    //       .AddCannedResponses(replies)
                                    //       .AddAckEvent(MessageCode.GarminCannedMessageReceived.GetMessageCode());

                                    //message.Send();
                                }
                            }
                        }
                    }

                    STrace.Trace(Component, result);
                }
                catch (Exception ex)
                {
                    AddError(ex);
                    transaction.Rollback();
                    ClearData();

                    archivo.Status = LogicLinkFile.Estados.Cancelado;
                    var result = "Archivo procesado erroneamente. Exception: " + ex.Message;
                    archivo.Result = result;
                    DaoFactory.LogicLinkFileDAO.SaveOrUpdate(archivo);

                    STrace.Trace(Component, result);
                }
                finally
                {
                    ClearData();
                }
            }
        }
Пример #30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }

            if (Request.QueryString["c"] == null)
            {
                lblDescripcion.Text = CultureManager.GetError("NO_VEHICLE_INFO");
                return;
            }

            IdEntidad = Convert.ToInt32(Request.QueryString["c"]);

            IdsLineas   = Request.QueryString["l"].Split(' ').Select(l => Convert.ToInt32(l)).ToList();
            IdsEmpresas = !string.IsNullOrEmpty(Request.QueryString["e"])
                              ? Request.QueryString["e"].Split(' ').Select(l => Convert.ToInt32(l)).ToList()
                              : new List <int> {
                -1
            };

            var entidad = DAOFactory.EntidadDAO.FindById(IdEntidad);

            IdDispositivo = entidad.Dispositivo != null ? entidad.Dispositivo.Id : -1;

            lblDescripcion.Text = entidad.Descripcion;
            lblTipo.Text        = entidad.TipoEntidad.Descripcion;
            imgTipo.ImageUrl    = IconDir + entidad.ReferenciaGeografica.Icono.PathIcono;

            var subEntidades = DAOFactory.SubEntidadDAO.GetList(new[] { entidad.Empresa.Id },
                                                                new[] { entidad.Linea != null ? entidad.Linea.Id : -1 },
                                                                new[] { entidad.TipoEntidad.Id },
                                                                new[] { entidad.Id },
                                                                new[] { entidad.Dispositivo != null ? entidad.Dispositivo.Id : -1 },
                                                                new[] { -1 });

            var fechaUltimaMedicion = DateTime.MinValue;

            foreach (var subEntidad in subEntidades)
            {
                var ultimaMedicion = DAOFactory.MedicionDAO.GetUltimaMedicionHasta(subEntidad.Sensor.Dispositivo.Id, subEntidad.Sensor.Id, DateTime.UtcNow);

                var label = new Label {
                    Text = subEntidad.Descripcion + @": "
                };
                divValor.Controls.Add(label);
                label = new Label {
                    Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                };

                switch (subEntidad.Sensor.TipoMedicion.Codigo)
                {
                case "TEMP":
                    if (ultimaMedicion != null)
                    {
                        fechaUltimaMedicion = ultimaMedicion.FechaMedicion > fechaUltimaMedicion
                                                      ? ultimaMedicion.FechaMedicion
                                                      : fechaUltimaMedicion;

                        label.Text = ultimaMedicion.Valor;
                        divValor.Controls.Add(label);

                        //EVALUO CONEXION
                        label = new Label {
                            Text = @" Energía: "
                        };
                        divValor.Controls.Add(label);
                        label = new Label {
                            Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                        };

                        var ultimoEventoConexion = DAOFactory.LogEventoDAO.GetLastBySensoresAndCodes(new[] { subEntidad.Sensor.Id },
                                                                                                     new[] { Convert.ToInt32(MessageIdentifier.TemperaturePowerDisconected).ToString(),
                                                                                                             Convert.ToInt32(MessageIdentifier.TemperaturePowerReconected).ToString() });

                        if (ultimoEventoConexion != null &&
                            ultimoEventoConexion.Mensaje.Codigo == Convert.ToInt32(MessageIdentifier.TemperaturePowerDisconected).ToString())
                        {
                            label.Text = @"Off";
                        }
                        else
                        {
                            label.Text = @"On";
                        }
                        divValor.Controls.Add(label);

                        //EVALUO DESCONGELAMIENTO
                        label = new Label {
                            Text = @" Desc: "
                        };
                        divValor.Controls.Add(label);
                        label = new Label {
                            Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                        };

                        var ultimoEventoDescongelamiento =
                            DAOFactory.LogEventoDAO.GetLastBySensoresAndCodes(new[] { subEntidad.Sensor.Id },
                                                                              new[] { Convert.ToInt32(MessageIdentifier.TemperatureThawingButtonPressed).ToString(),
                                                                                      Convert.ToInt32(MessageIdentifier.TemperatureThawingButtonUnpressed).ToString() });

                        if (ultimoEventoDescongelamiento != null &&
                            ultimoEventoDescongelamiento.Mensaje.Codigo == Convert.ToInt32(MessageIdentifier.TemperatureThawingButtonPressed).ToString())
                        {
                            label.Text = @"On";
                        }
                        else
                        {
                            label.Text = @"Off";
                        }
                        divValor.Controls.Add(label);
                    }
                    else
                    {
                        label.Text = @"-";
                        divValor.Controls.Add(label);

                        //EVALUO CONEXION
                        label = new Label {
                            Text = @" Energía: "
                        };
                        divValor.Controls.Add(label);
                        label = new Label {
                            Text = @"-", Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                        };
                        divValor.Controls.Add(label);
                        //EVALUO DESCONGELAMIENTO
                        label = new Label {
                            Text = @" Desc: "
                        };
                        divValor.Controls.Add(label);
                        label = new Label {
                            Text = @"-", Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                        };
                        divValor.Controls.Add(label);
                    }
                    break;

                case "EST":
                    if (ultimaMedicion != null)
                    {
                        fechaUltimaMedicion = ultimaMedicion.FechaMedicion > fechaUltimaMedicion
                                                      ? ultimaMedicion.FechaMedicion
                                                      : fechaUltimaMedicion;


                        //EVALUO CHECK
                        var ultimoCheckPoint =
                            DAOFactory.LogEventoDAO.GetLastBySensoresAndCodes(new[] { subEntidad.Sensor.Id },
                                                                              new[] { Convert.ToInt32(MessageIdentifier.CheckpointReached).ToString() });

                        if (ultimoCheckPoint != null)
                        {
                            label = new Label {
                                Text = @"Último Control: ", ForeColor = Color.FromArgb(66, 66, 66)
                            };
                            divValor.Controls.Add(label);
                            label = new Label
                            {
                                Height    = Unit.Pixel(10),
                                ForeColor = Color.FromArgb(66, 66, 66),
                                Text      = ultimoCheckPoint.Fecha.ToDisplayDateTime().ToString("dd/MM/yyyy HH:mm")
                            };
                            divValor.Controls.Add(label);
                        }
                        else
                        {
                            //EVALUO 911
                            label = new Label {
                                Text = @" 911: ", ForeColor = Color.FromArgb(66, 66, 66)
                            };
                            divValor.Controls.Add(label);
                            label = new Label {
                                Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                            };

                            var ultimoEvento911 =
                                DAOFactory.LogEventoDAO.GetLastBySensoresAndCodes(new[] { subEntidad.Sensor.Id },
                                                                                  new[] { Convert.ToInt32(MessageIdentifier.KeyboardButton1).ToString() });

                            if (ultimoEvento911 != null &&
                                ultimoEvento911.Fecha > DateTime.UtcNow.AddMinutes(-10))
                            {
                                label.Text = @"On";
                            }
                            else
                            {
                                label.Text = @"Off";
                            }
                            divValor.Controls.Add(label);

                            //EVALUO AMBULANCIA
                            label = new Label {
                                Text = @" Amb: ", ForeColor = Color.FromArgb(66, 66, 66)
                            };
                            divValor.Controls.Add(label);
                            label = new Label {
                                Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                            };

                            var ultimoEventoAmbulancia =
                                DAOFactory.LogEventoDAO.GetLastBySensoresAndCodes(new[] { subEntidad.Sensor.Id },
                                                                                  new[] { Convert.ToInt32(MessageIdentifier.KeyboardButton2).ToString() });

                            if (ultimoEventoAmbulancia != null &&
                                ultimoEventoAmbulancia.Fecha > DateTime.UtcNow.AddMinutes(-10))
                            {
                                label.Text = @"On";
                            }
                            else
                            {
                                label.Text = @"Off";
                            }
                            divValor.Controls.Add(label);

                            //EVALUO BOMBEROS
                            label = new Label {
                                Text = @" Bomb: ", ForeColor = Color.FromArgb(66, 66, 66)
                            };
                            divValor.Controls.Add(label);
                            label = new Label {
                                Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                            };

                            var ultimoEventoBombero =
                                DAOFactory.LogEventoDAO.GetLastBySensoresAndCodes(new[] { subEntidad.Sensor.Id },
                                                                                  new[] { Convert.ToInt32(MessageIdentifier.KeyboardButton3).ToString() });

                            if (ultimoEventoBombero != null &&
                                ultimoEventoBombero.Fecha > DateTime.UtcNow.AddMinutes(-10))
                            {
                                label.Text = @"On";
                            }
                            else
                            {
                                label.Text = @"Off";
                            }
                            divValor.Controls.Add(label);
                        }
                    }
                    else
                    {
                        label = new Label {
                            Text = @" 911: - Amb: - Bomb: -", Height = Unit.Pixel(10), ForeColor = Color.FromArgb(66, 66, 66)
                        };
                        divValor.Controls.Add(label);
                    }
                    break;

                case "NU":
                    if (ultimaMedicion != null)
                    {
                        fechaUltimaMedicion = ultimaMedicion.FechaMedicion > fechaUltimaMedicion
                                                      ? ultimaMedicion.FechaMedicion
                                                      : fechaUltimaMedicion;

                        label.Text = ultimaMedicion.Valor;
                        divValor.Controls.Add(label);
                    }
                    else
                    {
                        label.Text = @"-";
                        divValor.Controls.Add(label);
                    }
                    break;

                case "TIME":
                    if (ultimaMedicion != null)
                    {
                        fechaUltimaMedicion = ultimaMedicion.FechaMedicion > fechaUltimaMedicion
                                                      ? ultimaMedicion.FechaMedicion
                                                      : fechaUltimaMedicion;

                        var time = new TimeSpan(0, 0, 0, int.Parse(ultimaMedicion.Valor));
                        label.Text = time.ToString();
                        divValor.Controls.Add(label);
                    }
                    else
                    {
                        label.Text = @"-";
                        divValor.Controls.Add(label);
                    }
                    break;

                default:
                    if (ultimaMedicion != null)
                    {
                        fechaUltimaMedicion = ultimaMedicion.FechaMedicion > fechaUltimaMedicion
                                                      ? ultimaMedicion.FechaMedicion
                                                      : fechaUltimaMedicion;

                        label.Text = ultimaMedicion.Valor;
                        divValor.Controls.Add(label);
                    }
                    else
                    {
                        label.Text = @"-";
                        divValor.Controls.Add(label);
                    }
                    break;
                }

                label = new Label {
                    Text = @"<br/>"
                };
                divValor.Controls.Add(label);
            }

            lblFechaPosicion.Text = fechaUltimaMedicion != DateTime.MinValue ? fechaUltimaMedicion.ToDisplayDateTime().ToString("dddd dd \"de\" MMMM \"de\" yyyy HH:mm:ss") : "-";

            try
            {
                lblPosicion.Text = GeocoderHelper.GetDescripcionEsquinaMasCercana(entidad.ReferenciaGeografica.Latitude, entidad.ReferenciaGeografica.Longitude);
            }
            catch
            {
                lblPosicion.Text = @"Posición erronea.";
            }
        }