Ejemplo n.º 1
0
        private string ProcessGenericEvent(Event generico, string code)
        {
            var text = ExtraText.GetExtraText(generico, code).Trim().ToUpperInvariant();

            MessageSaver.Save(generico, code, Dispositivo, Coche, GetChofer(generico.GetRiderId()), generico.GetDateTime(), generico.GeoPoint, text, ZonaManejo);
            return(code);
        }
Ejemplo n.º 2
0
        private void CheckDailyOdometer(Coche coche, DateTime fin)
        {
            var refference = coche.KilometrosDiarios.Equals(0) ? coche.TipoCoche.KilometrosDiarios : coche.KilometrosDiarios;

            if (refference.Equals(0))
            {
                return;
            }

            if (coche.DailyOdometer < refference)
            {
                return;
            }

            if (coche.LastDailyOdometerRaise.HasValue && coche.LastDailyOdometerRaise.Value.AddHours(-3).DayOfYear == fin.AddHours(-3).DayOfYear)
            {
                return;
            }

            var text = String.Format(" (Referencia: {0}km)", (Int32)refference);

            var lastPosition = DaoFactory.LogPosicionDAO.GetFirstPositionOlderThanDate(coche.Id, fin, 1);

            MessageSaver.Save(MessageCode.KilometersExceded.GetMessageCode(), coche, fin, lastPosition.ToGpsPoint(), text);

            coche.LastDailyOdometerRaise = fin;
        }
Ejemplo n.º 3
0
        private void Preasignar(SosTicket ticket)
        {
            var storedTicket = DaoFactory.SosTicketDAO.FindByCodigo(ticket.NumeroServicio);

            if (storedTicket == null)
            {
                DaoFactory.SosTicketDAO.SaveOrUpdate(ticket);
            }

            //S:	20151119303932
            //O:	SAN MARTIN  500, CORDOBA
            //D:	COLON 1000, CORDOBA
            //Di:	CORREA DE DISTRIBUCION
            var mensaje = string.Format("Preasignacion: {0}<br>O:{1}<br>D:{2}<br>Di:{3}",
                                        ticket.NumeroServicio,
                                        ticket.Origen.Direccion + ", " + ticket.Origen.Localidad,
                                        ticket.Destino.Direccion + ", " + ticket.Destino.Localidad,
                                        ticket.Diagnostico);

            var ms      = new MessageSaver(DaoFactory);
            var lastPos = ticket.Distribucion.Vehiculo.IsLastPositionInCache() ? ticket.Distribucion.Vehiculo.RetrieveLastPosition() : null;
            var point   = lastPos != null ? new GPSPoint(lastPos.FechaMensaje, (float)lastPos.Latitud, (float)lastPos.Longitud, (float)(lastPos.Velocidad), GPSPoint.SourceProviders.GpsProvider, (float)lastPos.Altitud) : null;

            ms.Save(MessageCode.ServicioPreasignado.GetMessageCode(), ticket.Distribucion.Vehiculo, DateTime.UtcNow, null, ticket.NumeroServicio);
            SendQuestionToGarmin(mensaje, ticket.Distribucion);
        }
Ejemplo n.º 4
0
        private void ProcessConfirmacionUbox(string code, Event generico, GPSPoint point)
        {
            var extraText    = string.Empty;
            var distribucion = DaoFactory.ViajeDistribucionDAO.FindEnCurso(Coche);

            if (distribucion != null)
            {
                var estado   = GeocercaManager.CalcularEstadoVehiculo(Coche, point, DaoFactory);
                var detalles = distribucion.Detalles.Where(d => estado.GeocercasDentro.Select(g => g.Geocerca.Id).Contains(d.ReferenciaGeografica.Id));

                var conEntrada = detalles.Where(d => d.Entrada.HasValue && !d.Manual.HasValue)
                                 .OrderBy(d => d.Entrada.Value);

                detalles = conEntrada.Any() ? conEntrada : detalles.Where(d => !d.Manual.HasValue);

                var detalle = detalles.Any() ? detalles.First() : null;

                if (detalle != null)
                {
                    DaoFactory.Session.Refresh(detalle);

                    extraText      = " (" + detalle.Orden + ") -> " + detalle.Viaje.Codigo + " - " + detalle.Descripcion;
                    detalle.Estado = generico.GetData().ToString("#0") == MessageCode.TareaRealizada.GetMessageCode() ? EntregaDistribucion.Estados.Completado : EntregaDistribucion.Estados.NoCompletado;
                    detalle.Manual = generico.GetDateTime();
                    DaoFactory.EntregaDistribucionDAO.SaveOrUpdate(detalle);
                }
            }

            var textoEvento = ExtraText.GetExtraText(generico, code) + extraText;
            var chofer      = GetChofer(generico.GetRiderId());

            MessageSaver.Save(generico, code, Dispositivo, Coche, chofer, generico.GetDateTime(), generico.GeoPoint, textoEvento, ZonaManejo);
            MessageSaver.Save(MessageCode.EstadoLogisticoCumplidoManual.GetMessageCode(), Coche, chofer, generico.GetDateTime(), generico.GeoPoint, textoEvento);
        }
Ejemplo n.º 5
0
        private string ProcessVelocidadExcedidaGenericEvent(IGeoPoint generico)
        {
            var text   = ExtraText.GetVelocidadExcedidaExtraText(generico, Coche);
            var chofer = GetChofer(generico.GetRiderId());
            var fecha  = generico.GetDateTime();
            var evento = MessageSaver.Save(generico, MessageCode.SpeedingTicket.GetMessageCode(), Dispositivo, Coche, chofer, fecha, generico.GeoPoint, text, ZonaManejo);

            var infraccion = new Infraccion
            {
                Vehiculo         = Coche,
                Alcanzado        = generico.GeoPoint.Speed.Unpack(),
                CodigoInfraccion = Infraccion.Codigos.ExcesoVelocidad,
                Empleado         = evento.Chofer,
                Fecha            = fecha,
                Latitud          = generico.GeoPoint.Lat,
                Longitud         = generico.GeoPoint.Lon,
                FechaFin         = null,
                LatitudFin       = 0,
                LongitudFin      = 0,
                Permitido        = 0,
                Zona             = ZonaManejo,
                FechaAlta        = DateTime.UtcNow
            };

            DaoFactory.InfraccionDAO.Save(infraccion);

            return(MessageCode.SpeedingTicket.GetMessageCode());
        }
Ejemplo n.º 6
0
        private string ProcessPanicEvent(Event generico, string code)
        {
            var text   = ExtraText.GetExtraText(generico, code).Trim().ToUpperInvariant();
            var chofer = GetChofer(generico.GetRiderId());
            var fecha  = generico.GetDateTime();
            var evento = MessageSaver.Save(generico, code, Dispositivo, Coche, chofer, fecha, generico.GeoPoint, text, ZonaManejo);

            var infraccion = new Infraccion
            {
                Vehiculo         = Coche,
                Alcanzado        = generico.GeoPoint.Speed.Unpack(),
                CodigoInfraccion = Infraccion.Codigos.Panico,
                Empleado         = evento.Chofer,
                Fecha            = fecha,
                Latitud          = generico.GeoPoint.Lat,
                Longitud         = generico.GeoPoint.Lon,
                FechaFin         = null,
                LatitudFin       = 0,
                LongitudFin      = 0,
                Permitido        = 0,
                Zona             = ZonaManejo,
                FechaAlta        = DateTime.UtcNow
            };

            DaoFactory.InfraccionDAO.Save(infraccion);

            return(code);
        }
Ejemplo n.º 7
0
        public static void ProcessEstadoLogistico(Coche vehiculo, Event evento, string code)
        {
            try
            {
                if (vehiculo.Dispositivo == null)
                {
                    return;
                }

                var daoFactory   = new DAOFactory();
                var distribucion = daoFactory.ViajeDistribucionDAO.FindEnCurso(vehiculo);

                if (distribucion != null)
                {
                    var messageSaver = new MessageSaver(daoFactory);
                    CicloLogisticoDistribucion ciclo = null;
                    ciclo = new CicloLogisticoDistribucion(distribucion, daoFactory, messageSaver);

                    if (ciclo != null)
                    {
                        ciclo.ProcessEstadoLogistico(evento, code);
                    }
                }
            }
            catch (Exception ex)
            {
                STrace.Exception(typeof(CicloLogisticoFactory).FullName, ex);
            }
        }
Ejemplo n.º 8
0
    public static void SaveBinary(Publisher publisher)
    {
        MemoryStream memoryStream = new MemoryStream();
        float        value        = Time.realtimeSinceStartup - Dispatcher.startTime;

        memoryStream.Write(BitConverter.GetBytes(value), 0, 4);
        value = Dispatcher.deltaTime;
        memoryStream.Write(BitConverter.GetBytes(Time.deltaTime), 0, 4);
        MessageSaver.WriteStringToBin(publisher.domain, memoryStream);
        MessageSaver.WriteStringToBin(publisher.message, memoryStream);
        if (publisher.data != null)
        {
            MessageData[] data = publisher.data;
            for (int i = 0; i < data.Length; i++)
            {
                MessageData messageData = data[i];
                MessageSaver.WriteDataToBin(messageData.var, memoryStream);
            }
        }
        byte[] buffer = BitConverter.GetBytes((int)memoryStream.Length);
        MessageSaver.instance.binStream.Write(buffer, 0, 4);
        buffer = memoryStream.GetBuffer();
        MessageSaver.instance.binStream.Write(buffer, 0, (int)memoryStream.Position);
        memoryStream.Close();
        MessageSaver.instance.binStream.Flush();
    }
Ejemplo n.º 9
0
    private static object ReadDataFromBin(MemoryStream stream)
    {
        switch (TypeUtils.ByteToDataType((byte)stream.ReadByte()))
        {
        case DataType.Int32:
            return(MessageSaver.BinToInt32(stream));

        case DataType.Single:
            return(MessageSaver.BinToSingle(stream));

        case DataType.String:
            return(MessageSaver.BinToString(stream));

        case DataType.Vector2:
            return(MessageSaver.BinToVector2(stream));

        case DataType.Vector3:
            return(MessageSaver.BinToVector3(stream));

        case DataType.Vector4:
            return(MessageSaver.BinToVector4(stream));

        case DataType.Quaternion:
            return(MessageSaver.BinToQuaternion(stream));

        default:
            return(null);
        }
    }
Ejemplo n.º 10
0
        public void FinishReport(ViajeDistribucion viaje)
        {
            var ticket = DaoFactory.SosTicketDAO.FindByCodigo(viaje.Codigo);

            if (ticket != null)
            {
                ticket.Distribucion   = viaje;
                ticket.EstadoServicio = (int)CodigoEstado.Finalizado;
                DaoFactory.SosTicketDAO.SaveOrUpdate(ticket);

                var ms      = new MessageSaver(DaoFactory);
                var lastPos = ticket.Distribucion.Vehiculo.IsLastPositionInCache() ? ticket.Distribucion.Vehiculo.RetrieveLastPosition() : null;
                var point   = lastPos != null ? new GPSPoint(lastPos.FechaMensaje, (float)lastPos.Latitud, (float)lastPos.Longitud, (float)(lastPos.Velocidad), GPSPoint.SourceProviders.GpsProvider, (float)lastPos.Altitud) : null;
                if (EntregaDistribucion.Estados.EstadosOk.Contains(viaje.Detalles.Last().Estado))
                {
                    ms.Save(MessageCode.ServicioFinalizado.GetMessageCode(), ticket.Distribucion.Vehiculo, DateTime.UtcNow, null, ticket.NumeroServicio);
                }
                else
                {
                    ms.Save(MessageCode.SolicitaAsistencia.GetMessageCode(), ticket.Distribucion.Vehiculo, DateTime.UtcNow, null, ticket.NumeroServicio);
                }

                UpdateToSos(viaje.Vehiculo.Interno, viaje.Codigo, ticket.EstadoServicio, ticket.Diagnostico);
            }
        }
Ejemplo n.º 11
0
        private void UpdateVehicleOdometers(Coche coche, double kilometros, double horas, int dias, DateTime fin)
        {
            if (coche.Odometros.Count.Equals(0))
            {
                return;
            }

            foreach (MovOdometroVehiculo odometro in coche.Odometros)
            {
                UpdateOdometerValues(coche, odometro, kilometros, horas, dias, fin);

                if (odometro.Vencido() && !odometro.UltimoDisparo.HasValue)
                {
                    odometro.UltimoDisparo = fin;
                    if (odometro.Odometro.EsIterativo)
                    {
                        odometro.ResetOdometerValues();
                    }
                    var lastPosition = DaoFactory.LogPosicionDAO.GetFirstPositionOlderThanDate(coche.Id, fin, 1);
                    MessageSaver.Save(MessageCode.OdometerExpired.GetMessageCode(), coche, fin, lastPosition.ToGpsPoint(), odometro.Odometro.Descripcion);
                }
                else if (odometro.SuperoSegundoAviso() && !odometro.FechaSegundoAviso.HasValue)
                {
                    odometro.FechaSegundoAviso = fin;
                    var lastPosition = DaoFactory.LogPosicionDAO.GetFirstPositionOlderThanDate(coche.Id, fin, 1);
                    MessageSaver.Save(MessageCode.OdometerSecondWarning.GetMessageCode(), coche, fin, lastPosition.ToGpsPoint(), odometro.Odometro.Descripcion);
                }
                else if (odometro.SuperoPrimerAviso() && !odometro.FechaPrimerAviso.HasValue)
                {
                    odometro.FechaPrimerAviso = fin;
                    var lastPosition = DaoFactory.LogPosicionDAO.GetFirstPositionOlderThanDate(coche.Id, fin, 1);
                    MessageSaver.Save(MessageCode.OdometerFirstWarning.GetMessageCode(), coche, fin, lastPosition.ToGpsPoint(), odometro.Odometro.Descripcion);
                }
            }
        }
Ejemplo n.º 12
0
 protected void SaveMessage(string messageCode, string text, GPSPoint position, DateTime fecha)
 {
     if (MessageSaver == null)
     {
         return;
     }
     MessageSaver.Save(null, messageCode, Vehiculo.Dispositivo, Vehiculo, Empleado, fecha, position, text);
 }
Ejemplo n.º 13
0
 protected void SaveMessage(string messageCode, string text, GPSPoint position, DateTime fecha, ViajeDistribucion viaje, EntregaDistribucion entrega)
 {
     if (MessageSaver == null)
     {
         return;
     }
     MessageSaver.Save(null, messageCode, Vehiculo.Dispositivo, Vehiculo, Empleado, fecha, position, text, viaje, entrega);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Saves a no report warning event.
        /// </summary>
        /// <param name="vehicle"></param>
        /// <param name="position"></param>
        private void SaveNoReportEvent(Coche vehicle, LogUltimaPosicionVo position)
        {
            var lastPositionDate = GetLastPositionDate(vehicle, position);
            var text             = String.Format(" - Vehiculo: {0} - Último Reporte: {1}", position.Coche, lastPositionDate);

            STrace.Trace(GetType().FullName, String.Format("The vehicle {0} needs to be checked (last position on: {1}).", position.Coche, lastPositionDate));

            MessageSaver.Save(MessageCode.NoReport.GetMessageCode(), vehicle, DateTime.UtcNow, null, text);
        }
Ejemplo n.º 15
0
        private static void Status_Received(object sender, BasicDeliverEventArgs args)
        {
            var body = args.Body.ToArray();

            var message = Encoding.UTF8.GetString(body);
            var status  = JsonConvert.DeserializeObject <Status>(message);

            MessageSaver.SaveStatusToDatabase(status);
        }
Ejemplo n.º 16
0
 public void Save_NotMailPasessed_DoNothingReturnNull()
 {
     // arrange
     var File = new Mock<IFileWrap>(MockBehavior.Strict); // avoid method calls of file
     MessageSaver Saver = new MessageSaver(File.Object,null, null, null);
     // action
     string[] FileName = Saver.Save(null);
     // assert
     Assert.AreEqual(0,FileName.Length);
 }
Ejemplo n.º 17
0
        private string ProcessEstadoLogistico(string code, IGeoPoint generico)
        {
            if (code.Length == 1)
            {
                code = code.PadLeft(2, '0');
            }

            MessageSaver.Save(generico, code, Dispositivo, Coche, null, generico.GetDateTime(), generico.GeoPoint, string.Empty, ZonaManejo);

            return(code);
        }
Ejemplo n.º 18
0
 private void SendMessage()
 {
     try
     {
         var saver  = new MessageSaver(DaoFactory);
         var inicio = new GPSPoint(DateTime.UtcNow, (float)Latitud, (float)Longitud);
         saver.Save(Mensaje.Codigo, Coche, inicio.Date, inicio, txtTextoMensaje.Text);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Process the givenn message as a VelocidadExcedida event.
        /// </summary>
        /// <param name="velocidadExcedida">A message.</param>
        private HandleResults ProcessVelocidadExcedidaEvent(SpeedingTicket velocidadExcedida)
        {
            var inicio = velocidadExcedida.StartPoint ?? velocidadExcedida.TicketPoint;

            if (IsInvalidVelocidadExcedidaMessage(inicio, velocidadExcedida))
            {
                return(HandleResults.BreakSuccess);
            }

            var texto              = GetVelocidadExcedidaText(velocidadExcedida);
            var chofer             = GetChofer(velocidadExcedida.GetRiderId());
            var velocidadPermitida = Convert.ToInt32(velocidadExcedida.SpeedLimit);
            var velocidadAlcanzada = Convert.ToInt32(velocidadExcedida.SpeedReached);
            var estado             = GeocercaManager.CalcularEstadoVehiculo(Coche, inicio, DaoFactory);
            var zona = estado != null && estado.ZonaManejo != null && estado.ZonaManejo.ZonaManejo > 0
                    ? DaoFactory.ZonaDAO.FindById(estado.ZonaManejo.ZonaManejo) : null;

            if (Coche.Empresa.AsignoInfraccionPorAgenda)
            {
                var reserva = DaoFactory.AgendaVehicularDAO.FindByVehicleAndDate(Coche.Id, inicio.Date);
                if (reserva != null)
                {
                    chofer = reserva.Empleado;
                }
            }

            var evento = MessageSaver.Save(velocidadExcedida, MessageCode.SpeedingTicket.GetMessageCode(), Dispositivo, Coche, chofer, inicio.Date, inicio, velocidadExcedida.EndPoint, texto, velocidadPermitida, velocidadAlcanzada, null, zona);

            var infraccion = new Infraccion
            {
                Vehiculo         = Coche,
                Alcanzado        = velocidadAlcanzada,
                CodigoInfraccion = Infraccion.Codigos.ExcesoVelocidad,
                Empleado         = evento.Chofer,
                Fecha            = inicio.Date,
                Latitud          = inicio.Lat,
                Longitud         = inicio.Lon,
                FechaFin         = velocidadExcedida.EndPoint.Date,
                LatitudFin       = velocidadExcedida.EndPoint.Lat,
                LongitudFin      = velocidadExcedida.EndPoint.Lon,
                Permitido        = velocidadPermitida,
                Zona             = zona,
                FechaAlta        = DateTime.UtcNow
            };

            DaoFactory.InfraccionDAO.Save(infraccion);

            return(HandleResults.Success);
        }
Ejemplo n.º 20
0
    private void _WriteXMLFile(Publisher publisher)
    {
        XmlElement root = this.xmlDoc.CreateElement("Publisher");
        float      num  = Time.realtimeSinceStartup - BlackBoard.Read <float>("time", "DispatcherStartedTime");

        MessageSaver.WriteXMLElement("Time", num, this.xmlDoc, root);
        MessageSaver.WriteXMLElement("Domain", publisher.domain, this.xmlDoc, root);
        MessageSaver.WriteXMLElement("Message", publisher.message, this.xmlDoc, root);
        for (int i = 0; i < publisher.data.Length; i++)
        {
            string elementName = publisher.data[i].GetType().ToString();
            MessageSaver.WriteXMLElement(elementName, publisher.data[i].Read <object>(), this.xmlDoc, root);
        }
        this.xmlDoc.Save("data.xml");
    }
Ejemplo n.º 21
0
        protected void btIniciar_Click(object sender, EventArgs e)
        {
            mpePanel.Hide();
            if (TicketToInitId.Get() <= 0)
            {
                return;
            }

            var date = dtHora.SelectedDate;

            if (!date.HasValue)
            {
                ThrowMustEnter("FECHA");
            }

            var ticket = DAOFactory.TicketDAO.FindById(TicketToInitId.Get());

            TicketToInitId.Set(-1);

            SetStartDate(ticket, SecurityExtensions.ToDataBaseDateTime(date.Value));

            var messageSaver = new MessageSaver(DAOFactory);

            var ciclo = new CicloLogisticoHormigon(ticket, DAOFactory, messageSaver);

            var evento = new InitEvent(DateTime.UtcNow);

            try
            {
                ciclo.ProcessEvent(evento);
                ShowInfo(CultureManager.GetSystemMessage("CLOG_START_SENT") + ticket.Vehiculo.Interno);
                Bind();
                if (TieneDocumentosVencidos.Get())
                {
                    messageSaver.Save(MessageCode.CicloLogisticoIniciadoDocumentosInvalidos.GetMessageCode(),
                                      ticket.Vehiculo, evento.Date.AddSeconds(1), null, string.Empty);
                }
            }
            catch (NoVehicleException)
            {
                ShowError(new ApplicationException(CultureManager.GetError("TICKET_NO_VEHICLE_ASSIGNED")));
            }
            catch //AlreadyOpenException, QueueException, Exception
            {
                ShowError(new ApplicationException(CultureManager.GetError("CLOG_MESSAGE_NOT_SENT") + ticket.Vehiculo.Interno));
            }
        }
Ejemplo n.º 22
0
        protected override void OnExecute(Timer timer)
        {
            STrace.Trace(ComponentName, "Inicio de la tarea");

            var empresas = DaoFactory.EmpresaDAO.GetList();

            foreach (var empresa in empresas)
            {
                if (empresa.ControlaInicioDistribucion)
                {
                    STrace.Trace(ComponentName, string.Format("Control de salida habilitado para: {0}", empresa.RazonSocial));
                    var tareas = DaoFactory.ViajeDistribucionDAO.GetList(new[] { empresa.Id },
                                                                         new[] { -1 }, // LINEAS
                                                                         new[] { -1 }, // TRANSPORTISTAS
                                                                         new[] { -1 }, // DEPARTAMENTOS
                                                                         new[] { -1 }, // CENTROS DE COSTO
                                                                         new[] { -1 }, // SUB CENTROS DE COSTO
                                                                         new[] { -1 }, // VEHICULOS
                                                                         new[] { (int)ViajeDistribucion.Estados.EnCurso },
                                                                         DateTime.Today,
                                                                         DateTime.Today.AddDays(1));
                    STrace.Trace(ComponentName, string.Format("Cantidad de tareas en curso: {0}", tareas.Count()));

                    foreach (var viaje in tareas)
                    {
                        if (DateTime.UtcNow > viaje.Inicio.AddMinutes(viaje.Umbral) &&
                            viaje.EntregasPendientesCount == viaje.EntregasTotalCount)
                        {
                            STrace.Trace(ComponentName, string.Format("Viaje Atrasado - Código: {0}", viaje.Codigo));
                            var maxMonths = viaje.Vehiculo.Empresa != null ? viaje.Vehiculo.Empresa.MesesConsultaPosiciones : 3;
                            var alarmas   = DaoFactory.LogMensajeDAO.GetByVehicleAndCode(viaje.Vehiculo.Id, MessageCode.AtrasoTicket.GetMessageCode(), viaje.Inicio.AddMinutes(viaje.Umbral), DateTime.UtcNow, maxMonths);
                            if (!alarmas.Any())
                            {
                                var code = MessageCode.AtrasoTicket.GetMessageCode();
                                MessageSaver.Save(code, viaje.Vehiculo, viaje.Empleado, DateTime.UtcNow, null, " - Inicio " + viaje.Codigo);
                                STrace.Trace(ComponentName, "Evento generado");
                            }
                            else
                            {
                                STrace.Trace(ComponentName, "Ya se generó alarma");
                            }
                        }
                    }
                }
            }
            STrace.Trace(ComponentName, "Fin de la tarea");
        }
Ejemplo n.º 23
0
        public bool SendMessagesMobile(string deviceId, List <LogMensaje> mensajes)
        {
            var device = DaoFactory.DispositivoDAO.FindByImei(deviceId);

            if (device == null)
            {
                return(false);
            }

            var employee = DaoFactory.EmpleadoDAO.FindEmpleadoByDevice(device);

            if (employee == null)
            {
                return(false);
            }

            var vehicle = DaoFactory.CocheDAO.FindByChofer(employee.Id);

            if (vehicle == null)
            {
                return(false);
            }

            foreach (var mensaje in mensajes)
            {
                mensaje.IdCoche       = vehicle.Id;
                mensaje.CodigoMensaje = MessageCode.SubmitTextMessage.GetMessageCode();
                mensaje.Dispositivo   = device;

                var msg = new MessageSaver(DaoFactory);

                var position = new GPSPoint();

                if ((mensaje.Latitud != 0) && (mensaje.Longitud != 0))
                {
                    position = new GPSPoint(mensaje.Fecha, (float)mensaje.Latitud, (float)mensaje.Longitud);
                }

                msg.Save(MessageCode.TextEvent.GetMessageCode(), vehicle, employee, mensaje.Fecha, position, mensaje.Texto);

                //var codes = new List<string> { MessageCode.TextEvent.GetMessageCode() };
                //mensaje.Mensaje = DaoFactory.MensajeDAO.FindByCodes(codes.AsEnumerable()).FirstOrDefault();
                //DaoFactory.LogMensajeDAO.Save(mensaje);
            }
            return(true);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Determines if the givenn speed message has valid values.
        /// </summary>
        /// <param name="inicio"></param>
        /// <param name="velocidadExcedida"></param>
        /// <returns></returns>
        private Boolean IsInvalidVelocidadExcedidaMessage(GPSPoint inicio, SpeedingTicket velocidadExcedida)
        {
            var discardReason = DiscardReason.None;

            if (velocidadExcedida.EndPoint == null || inicio == null)
            {
                discardReason = DiscardReason.MissingPositions;
            }
            else if (FechaInvalida(velocidadExcedida.EndPoint.Date, DeviceParameters))
            {
                discardReason = DiscardReason.InvalidDate;
            }
            else if (FechaInvalida(inicio.Date, DeviceParameters))
            {
                discardReason = DiscardReason.InvalidDate;
            }
            else if (FueraDelGlobo(inicio))
            {
                discardReason = DiscardReason.OutOfGlobe;
            }
            else if (FueraDelGlobo(velocidadExcedida.EndPoint))
            {
                discardReason = DiscardReason.OutOfGlobe;
            }
            else if (VelocidadInvalida(velocidadExcedida))
            {
                discardReason = DiscardReason.InvalidSpeed;
            }
            else if (InvalidDuration(velocidadExcedida, inicio))
            {
                discardReason = DiscardReason.InvalidDuration;
            }
            else if (InvalidTicketData(velocidadExcedida, inicio))
            {
                discardReason = DiscardReason.InvalidTicketData;
            }

            if (discardReason.Equals(DiscardReason.None))
            {
                return(false);
            }

            MessageSaver.Discard(MessageCode.SpeedingTicket.GetMessageCode(), Dispositivo, Coche, GetChofer(velocidadExcedida.GetRiderId()), inicio.GetDate(), inicio, velocidadExcedida.EndPoint, discardReason);

            return(true);
        }
Ejemplo n.º 25
0
        protected override void OnSave()
        {
            EditObject.Empresa      = DAOFactory.EmpresaDAO.FindById(cbEmpresa.Selected);
            EditObject.Linea        = DAOFactory.LineaDAO.FindById(cbLinea.Selected);
            EditObject.Departamento = cbDepartamento.Selected > 0 ? DAOFactory.DepartamentoDAO.FindById(cbDepartamento.Selected) : null;
            EditObject.Vehiculo     = DAOFactory.CocheDAO.FindById(int.Parse(cbVehiculo.SelectedValue));
            EditObject.Empleado     = DAOFactory.EmpleadoDAO.FindById(auEmpleado.Selected);
            EditObject.Turno        = cbTurno.Selected > 0 ? DAOFactory.ShiftDAO.FindById(cbTurno.Selected) : null;

            EditObject.FechaDesde = dtpDesde.SelectedDate.Value.ToDataBaseDateTime();
            EditObject.FechaHasta = dtpHasta.SelectedDate.Value.ToDataBaseDateTime();
            EditObject.Destino    = txtDestino.Text;

            DAOFactory.AgendaVehicularDAO.SaveOrUpdate(EditObject);

            var msgSaver = new MessageSaver(DAOFactory);

            msgSaver.Save(MessageCode.VehiculoAgendado.GetMessageCode(), EditObject.Vehiculo, EditObject.Empleado, DateTime.UtcNow, null, string.Format("Vehículo {0} asignado a {1}", EditObject.Vehiculo.Patente, EditObject.Empleado.Entidad != null ? EditObject.Empleado.Entidad.Descripcion : string.Empty));
        }
Ejemplo n.º 26
0
    public static List <Publisher> ReadXMLFile()
    {
        if (!File.Exists("data.xml"))
        {
            return(null);
        }
        List <Publisher> list          = new List <Publisher>();
        XmlTextReader    xmlTextReader = new XmlTextReader("data.xml");

        while (xmlTextReader.Read())
        {
            XmlNodeType nodeType = xmlTextReader.NodeType;
            if (nodeType == XmlNodeType.Element && xmlTextReader.Name == "Publisher")
            {
                list.Add(MessageSaver.ReadXMLPublisher(xmlTextReader.ReadSubtree()));
            }
        }
        return(list);
    }
Ejemplo n.º 27
0
        public void ConfirmaPatente(SosTicket ticket, bool confirmacionOk)
        {
            if (confirmacionOk)
            {
                ticket.EstadoServicio = (int)CodigoEstado.Llegada;
                DaoFactory.SosTicketDAO.SaveOrUpdate(ticket);

                var ms      = new MessageSaver(DaoFactory);
                var lastPos = ticket.Distribucion.Vehiculo.IsLastPositionInCache() ? ticket.Distribucion.Vehiculo.RetrieveLastPosition() : null;
                var point   = lastPos != null ? new GPSPoint(lastPos.FechaMensaje, (float)lastPos.Latitud, (float)lastPos.Longitud, (float)(lastPos.Velocidad), GPSPoint.SourceProviders.GpsProvider, (float)lastPos.Altitud) : null;
                ms.Save(MessageCode.LlegadaServicio.GetMessageCode(), ticket.Distribucion.Vehiculo, DateTime.UtcNow, null, ticket.NumeroServicio);

                UpdateToSos(ticket.Distribucion.Vehiculo.Interno, ticket.Distribucion.Codigo, ticket.EstadoServicio, ticket.Diagnostico);
            }
            else
            {
                var msgText = "Patente erronea. Por favor, informe los 3 digitos de la patente del vehiculo correspondiente al servicio " + ticket.Distribucion.Codigo;
                SendQuestionPatenteToGarmin(msgText, ticket.Distribucion);
            }
        }
Ejemplo n.º 28
0
        public string SendMessageByRouteAndDelivery(int routeId, string messageCode, string text, DateTime dateTime, long deliveryId, float lat, float lon, string deviceId)
        {
            var device = DaoFactory.DispositivoDAO.FindByImei(deviceId);

            if (device == null)
            {
                return(messageCode);
            }

            var employee = DaoFactory.EmpleadoDAO.FindEmpleadoByDevice(device);

            if (employee == null)
            {
                return(messageCode);
            }

            //var companies = new[] { employee.Empresa.Id };
            //var lineas = employee.Linea != null ? new[] { employee.Linea.Id } : new int[] { };

            var route    = DaoFactory.ViajeDistribucionDAO.FindById(routeId);
            var delivery = DaoFactory.EntregaDistribucionDAO.FindById(int.Parse(deliveryId.ToString()));
            var vehicle  = DaoFactory.CocheDAO.FindByChofer(employee.Id);

            GPSPoint point = null;

            if ((lat != 0) && (lon != 0))
            {
                point = new GPSPoint(dateTime.ToUniversalTime(), lat, lon);
            }

            var msgSaver    = new MessageSaver(DaoFactory);
            var description = "Ciclo Logistico ->" + text;

            if ((route != null) && (delivery != null))
            {
                description = string.Format("Ciclo Logistico {0} - {1} : {2}", route.Codigo, delivery.Descripcion, text);
            }

            msgSaver.Save(null, MessageCode.TextEvent.GetMessageCode(), device, vehicle, employee, dateTime.ToUniversalTime(), point, description, route, delivery);
            return(string.Empty);
        }
Ejemplo n.º 29
0
        public void Save_TextMail_SaveText()
        {
            // arrange
            string Titulo = @"titulo:\";
            string Content = "blablabla";
            var File = new Mock<IFileWrap>();

            MessageSaver Saver = new MessageSaver(File.Object, @"C:\", new PathWrap(),null);
            var TextMessageStub = new Mock<IMessage>();

            TextMessageStub.Setup(m => m.Title).Returns(Titulo);

            TextMessageStub.Setup(m => m.Text).Returns(Content);
            TextMessageStub.Setup(m => m.IsHtml).Returns(false);
            // action
            string[] FileNames = Saver.Save(new [] {TextMessageStub.Object});
            // assert
            string Filepath = @"C:\titulo__.txt";
            Assert.AreEqual(Filepath, FileNames[0]);
            File.Verify(f => f.WriteAllText(Filepath, Content), Times.Once());
        }
Ejemplo n.º 30
0
        private void Asignar(SosTicket ticket)
        {
            var storedTicket = DaoFactory.SosTicketDAO.FindByCodigo(ticket.NumeroServicio);

            ticket.Distribucion = storedTicket == null?BuildRoute(ticket) : UpdateRoute(ticket);

            DaoFactory.SosTicketDAO.SaveOrUpdate(ticket);

            var mensaje = string.Format("Asignado: {0}<br>De {1}<br>a {2}<br>{3}",
                                        ticket.NumeroServicio,
                                        ticket.Origen.Direccion + ", " + ticket.Origen.Localidad,
                                        ticket.Destino.Direccion + ", " + ticket.Destino.Localidad,
                                        ticket.Diagnostico.Split('-')[1]);

            var ms      = new MessageSaver(DaoFactory);
            var lastPos = ticket.Distribucion.Vehiculo.IsLastPositionInCache() ? ticket.Distribucion.Vehiculo.RetrieveLastPosition() : null;
            var point   = lastPos != null ? new GPSPoint(lastPos.FechaMensaje, (float)lastPos.Latitud, (float)lastPos.Longitud, (float)(lastPos.Velocidad), GPSPoint.SourceProviders.GpsProvider, (float)lastPos.Altitud) : null;

            ms.Save(MessageCode.ServicioAsignado.GetMessageCode(), ticket.Distribucion.Vehiculo, DateTime.UtcNow, null, ticket.NumeroServicio);
            SendQuestionToGarmin(mensaje, ticket.Distribucion);
        }
Ejemplo n.º 31
0
        public void ResponsePreasigno(ViajeDistribucion dist, bool accepted)
        {
            var ticket = DaoFactory.SosTicketDAO.FindByCodigo(dist.Codigo);

            if (accepted)
            {
                ticket.Preasignado             = DateTime.Now;
                ticket.PreasignacionNotificada = true;
                ticket.EstadoServicio          = (int)CodigoEstado.PreasignadoAceptado;

                //envio de informacion del servicio
                var mensaje = string.Format("{0}<br>{1}<br>{2}<br>{3}",
                                            ticket.NumeroServicio + " (" + ticket.Prioridad + ")",
                                            ticket.Patente.Substring(0, 3) + "XXX " + ticket.Marca + " " + ticket.Color,
                                            ticket.Observacion,
                                            ticket.Diagnostico.Split('-')[1] + " $" + ticket.CobroAdicional);
                SendMessageToGarmin(mensaje, dist);

                var ms      = new MessageSaver(DaoFactory);
                var lastPos = ticket.Distribucion.Vehiculo.IsLastPositionInCache() ? ticket.Distribucion.Vehiculo.RetrieveLastPosition() : null;
                var point   = lastPos != null ? new GPSPoint(lastPos.FechaMensaje, (float)lastPos.Latitud, (float)lastPos.Longitud, (float)(lastPos.Velocidad), GPSPoint.SourceProviders.GpsProvider, (float)lastPos.Altitud) : null;
                ms.Save(MessageCode.ServicioPreasignadoAceptado.GetMessageCode(), ticket.Distribucion.Vehiculo, DateTime.UtcNow, null, ticket.NumeroServicio);
            }
            else
            {
                ticket.Rechazado             = true;
                ticket.Cancelado             = DateTime.Now;
                ticket.CancelacionNotificada = true;
                ticket.EstadoServicio        = (int)CodigoEstado.PreasignadoRechazado;

                var ms      = new MessageSaver(DaoFactory);
                var lastPos = ticket.Distribucion.Vehiculo.IsLastPositionInCache() ? ticket.Distribucion.Vehiculo.RetrieveLastPosition() : null;
                var point   = lastPos != null ? new GPSPoint(lastPos.FechaMensaje, (float)lastPos.Latitud, (float)lastPos.Longitud, (float)(lastPos.Velocidad), GPSPoint.SourceProviders.GpsProvider, (float)lastPos.Altitud) : null;
                ms.Save(MessageCode.ServicioPreasignadoRechazado.GetMessageCode(), ticket.Distribucion.Vehiculo, DateTime.UtcNow, null, ticket.NumeroServicio);
            }
            DaoFactory.SosTicketDAO.SaveOrUpdate(ticket);

            UpdateToSos(dist.Vehiculo.Interno, dist.Codigo, ticket.EstadoServicio, ticket.Diagnostico);
        }
Ejemplo n.º 32
0
    public static List <Publisher> LoadBinary()
    {
        List <Publisher> list   = new List <Publisher>();
        Stream           stream = new FileStream(Application.persistentDataPath + "/Data.bin", FileMode.Open, FileAccess.Read, FileShare.None);

        Debug.Log("File size : " + stream.Length);
        while (stream.Position < stream.Length)
        {
            byte[] array = new byte[4];
            stream.Read(array, 0, 4);
            int num = BitConverter.ToInt32(array, 0);
            array = new byte[num];
            stream.Read(array, 0, num);
            MemoryStream       memoryStream = new MemoryStream(array);
            float              time         = (float)MessageSaver.BinToSingle(memoryStream);
            float              deltaTime    = (float)MessageSaver.BinToSingle(memoryStream);
            string             domain       = MessageSaver.BinToString(memoryStream);
            string             message      = MessageSaver.BinToString(memoryStream);
            List <MessageData> list2        = new List <MessageData>();
            while (memoryStream.Position < memoryStream.Length)
            {
                object value = MessageSaver.ReadDataFromBin(memoryStream);
                list2.Add(new MessageData(value));
            }
            list.Add(new Publisher(domain, message, new object[]
            {
                ""
            })
            {
                data      = list2.ToArray(),
                time      = time,
                deltaTime = deltaTime
            });
            memoryStream.Close();
        }
        stream.Close();
        return(list);
    }