/// <summary> /// Generates a new log evento with the specified data. /// </summary> /// <param name="coche"></param> /// <param name="dispositivo"></param> /// <param name="mensaje"></param> /// <param name="inicio"></param> /// <param name="fin"></param> /// <param name="chofer"></param> /// <param name="velAlcanzada"></param> /// <param name="velPermitida"></param> /// <param name="idPuntoDeInteres"></param> /// <param name="texto"></param> /// <param name="dt"></param> /// <returns></returns> private LogMensajeBase SaveEvent(Coche coche, Dispositivo dispositivo, MensajeVO mensaje, GPSPoint inicio, GPSPoint fin, Empleado chofer, Int32?velAlcanzada, Int32?velPermitida, Int32?idPuntoDeInteres, String texto, DateTime dt) { var ticket = DaoFactory.TicketDAO.FindEnCurso(dispositivo); var detalleTicket = ticket == null ? null : ticket.GetDetalleProximo(); var driver = chofer ?? (ticket != null ? ticket.Empleado : null); var log = new LogMensaje { Chofer = driver, Coche = coche, Dispositivo = dispositivo, Estado = 0, Fecha = inicio != null ? inicio.Date : (dt <= new DateTime(2010, 1, 1)) ? dt : DateTime.UtcNow, Expiracion = DateTime.UtcNow.AddDays(1), Horario = ticket, DetalleHorario = detalleTicket, Usuario = null, Latitud = inicio != null ? inicio.Lat : 0, Longitud = inicio != null ? inicio.Lon : 0, FechaFin = fin != null ? fin.Date : (DateTime?)null, LatitudFin = fin != null ? new Double?(fin.Lat) : null, LongitudFin = fin != null ? new Double?(fin.Lon) : null, VelocidadAlcanzada = velAlcanzada, VelocidadPermitida = velPermitida, IdPuntoDeInteres = idPuntoDeInteres, Mensaje = DaoFactory.MensajeDAO.FindById(mensaje.Id), Texto = string.Concat(mensaje.Texto, ' ', texto) }; SaveEvent(log); return(log); }
private void EnviaMensaje(Coche coche, Mensaje mensaje, TicketRechazo rechazo, Empleado empleado) { if (coche == null || mensaje == null) { return; } var lastPosition = DaoFactory.LogPosicionDAO.GetLastOnlineVehiclePosition(coche); var newEvent = new LogMensaje { Coche = coche, Chofer = empleado, CodigoMensaje = mensaje.Codigo, Dispositivo = coche.Dispositivo, Expiracion = DateTime.UtcNow.AddDays(1), Fecha = DateTime.UtcNow, FechaAlta = DateTime.UtcNow, FechaFin = DateTime.UtcNow, IdCoche = coche.Id, Latitud = lastPosition != null ? lastPosition.Latitud : 0, LatitudFin = lastPosition != null ? lastPosition.Latitud : 0, Longitud = lastPosition != null ? lastPosition.Longitud : 0, LongitudFin = lastPosition != null ? lastPosition.Longitud : 0, Mensaje = mensaje, Texto = "INFORME DE RECHAZO NRO " + rechazo.Id + ": " + mensaje.Descripcion + " -> " + rechazo.Entrega.Descripcion }; DaoFactory.LogMensajeDAO.Save(newEvent); }
private void GuardarEvento(LogMensaje log) { var t = new TimeElapsed(); DaoFactory.LogMensajeDAO.Save(log); var totalSeconds = t.getTimeElapsed().TotalSeconds; if (totalSeconds > 1) { STrace.Debug("DispatcherLock", log.Dispositivo.Id, String.Format("GuardarEvento/LogMensajeDAO.Save ({0} secs)", totalSeconds)); } if (log.Viaje == null && log.Entrega == null) { return; } t.Restart(); var evenDistri = new EvenDistri { LogMensaje = log, Fecha = log.Fecha, Entrega = log.Entrega, Viaje = log.Viaje ?? log.Entrega.Viaje }; DaoFactory.EvenDistriDAO.Save(evenDistri); totalSeconds = t.getTimeElapsed().TotalSeconds; if (totalSeconds > 1) { STrace.Debug("DispatcherLock", log.Dispositivo.Id, String.Format("GuardarEvento/EvenDistriDAO.Save ({0} secs)", totalSeconds)); } }
public static IEvent GetEvent(DAOFactory daoFactory, LogMensaje mensaje) { var inicio = new GPSPoint(mensaje.Fecha, (float)mensaje.Latitud, (float)mensaje.Longitud); var codigo = mensaje.Mensaje.Codigo; var idPuntoDeInteres = mensaje.IdPuntoDeInteres; const int extraData = 0; return(GetEvent(daoFactory, inicio, codigo, idPuntoDeInteres, extraData, -1, -1, null, mensaje.Chofer)); }
public TicketEvent(LogMensaje msg) { Fecha = msg.Fecha; //Fecha en la que se disparo el mensaje. Description = (msg.Mensaje != null)?msg.Mensaje.Descripcion: string.Empty; Scheduled = msg.DetalleHorario.Programado; Automatic = null; Chofer = (msg.Chofer != null)? msg.Chofer.Entidad.Descripcion: string.Empty; Camion = (msg.Coche != null)? msg.Coche.ToString():string.Empty; Ticket = String.Empty; }
public IEnumerable <MobileEvent> GetMobilesEventsByDistritoBase(int distritoId, int baseId) { LogMensaje log = null; Coche coche = null; TipoCoche tCoche = null; Empleado chofer = null; Mensaje mensaje = null; var q = NHibernate.SessionHelper.Current .QueryOver(() => log) .Inner.JoinAlias(() => log.Coche, () => coche) .Inner.JoinAlias(() => coche.TipoCoche, () => tCoche) .Inner.JoinAlias(() => log.Chofer, () => chofer) .Inner.JoinAlias(() => log.Mensaje, () => mensaje) .Where(() => log.Estado > 0) .Select(Projections.ProjectionList() .Add(Projections.Property(() => coche.Interno).As("Intern")) .Add(Projections.Property(() => tCoche.Descripcion).As("MobileType")) .Add(Projections.Property(() => chofer.Entidad.Descripcion).As("Driver")) //.Add(Projections.Property(() => log.Fecha.ToDisplayDateTime()).As("EventTime")) //.Add(Projections.Property(() => log.FechaAlta.HasValue ? log.FechaAlta.Value.ToDisplayDateTime() : (DateTime?)null).As("Reception")) .Add(Projections.Property(() => log.Texto).As("Message")) .Add(Projections.Property(() => mensaje.Id).As("IdMensaje")) .Add(Projections.Property(() => log.Latitud).As("Latitude")) .Add(Projections.Property(() => log.Longitud).As("Longitude")) //.Add(Projections.Property(() => log.GetIconUrl()).As("IconUrl")) //.Add(Projections.Property(() => log.FechaFin != null ? log.FechaFin.Value.ToDisplayDateTime() : log.FechaFin).As("EventEndTime")) .Add(Projections.Property(() => log.LatitudFin).As("FinalLatitude")) .Add(Projections.Property(() => log.LongitudFin).As("FinalLongitude")) .Add(Projections.Property(() => log.Id).As("Id")) .Add(Projections.Property(() => coche.Chofer.Entidad.Descripcion).As("Responsable")) .Add(Projections.Property(() => log.TieneFoto).As("TieneFoto")) .Add(Projections.Property(() => log.IdPuntoDeInteres).As("IdPuntoInteres")) .Add(Projections.Property(() => log.Estado).As("Atendido")) .Add(Projections.Property(() => log.Usuario).As("Usuario")) //.Add(Projections.Property(() => log.Estado > 0 ? DAOFactory.AtencionEventoDAO.GetByEvento(log.Id) : null).As("AtencionEvento")) ); if (distritoId != -1) { q = q.Where(m => coche.Empresa.Id == distritoId); } if (baseId != -1) { q = q.Where(m => coche.Linea.Id == baseId); } q = q.TransformUsing(Transformers.AliasToBean <MobileEvent>()); return(q.Future <MobileEvent>()); }
/// <summary> /// Returns the real email address from the givenn destination string. /// </summary> /// <param name="destinatario"></param> /// <param name="log"></param> /// <param name="sender"></param> /// <returns></returns> private static List <string> GetMailRealDestinatarios(string destinatario, LogMensaje log, MailSender sender) { var reporta1 = destinatario.ToUpper().Equals("REPORTA1"); var reporta2 = destinatario.ToUpper().Equals("REPORTA2"); var reporta3 = destinatario.ToUpper().Equals("REPORTA3"); if (!reporta1 && !reporta2 && !reporta3) { return new List <string> { destinatario } } ; var empleadoEvento = GetEmpleadoEvento(log); if (empleadoEvento == null) { return(null); } sender.Config.Subject = string.Concat(sender.Config.Subject, " - Envio a Responsable"); if (reporta1) { return empleadoEvento.Reporta1 == null ? null : new List <string> { empleadoEvento.Reporta1.Mail } } ; if (reporta2) { return empleadoEvento.Reporta2 == null ? null : new List <string> { empleadoEvento.Reporta2.Mail } } ; return(empleadoEvento.Reporta3 == null ? null : new List <string> { empleadoEvento.Reporta3.Mail }); }
private int GuardaLog(String Mensaje, byte IDTipoMensaje, string IDInstancia) { MilDiasEntities db = new MilDiasEntities(); try { LogMensaje logSMS = new LogMensaje(); logSMS.MENSAJE = Mensaje; logSMS.ID_TIPOMENSAJE = IDTipoMensaje; logSMS.FECHA = DateTime.Now; logSMS.ID_INSTANCIA = IDInstancia; db.LogMensaje.Add(logSMS); db.SaveChanges(); return(0); } catch (Exception e) { return(-1); } }
private void EnviarReporte(LogMensaje log) { var queue = GetMailReportMsmq(); IReportCommand reportCommand = null; var reportId = DaoFactory.ProgramacionReporteDAO.GetReportIdByReportName("MANUAL"); switch (log.Accion.Reporte) { case ProgramacionReporte.Reportes.EstadoEntregas: //var vehicles = new List<int> {log.Viaje.Vehiculo.Id}; //reportCommand = ReportService.CreateDeliverStatusReportCommand(reportId, log.Viaje.Empresa.Id, -1, log.Accion.DestinatariosMailReporte, // log.Fecha, log.Viaje.InicioReal.Value, vehicles); reportCommand = new DeliverStatusReportCommand { ReportId = reportId, //log.Id, CustomerId = log.Viaje.Empresa.Id, Email = log.Accion.DestinatariosMailReporte, FinalDate = log.Fecha, InitialDate = log.Viaje.InicioReal.Value, VehiclesId = new List <int> { log.Viaje.Vehiculo.Id }, ReportName = log.Viaje.Codigo }; break; default: break; } if (queue == null) { throw new ApplicationException("No se pudo acceder a la cola"); } if (reportCommand != null) { queue.Send(reportCommand); } }
public void Save(LogMensaje logMensaje, int type) { using (var tx = SmartTransaction.BeginTransaction()) { var dc = makeDetachedCriteriaFor(1, logMensaje.Coche, type).SetProjection(Projections.Property("Id")); var last = Session.CreateCriteria <LastVehicleEvent>().Add(Subqueries.PropertyIn("Id", dc)).UniqueResult <LastVehicleEvent>(); if (last == null) { last = new LastVehicleEvent { TipoEvento = type, Vehiculo = logMensaje.Coche } } ; last.LogMensaje = logMensaje; SaveOrUpdate(last); tx.Commit(); } } }
public HttpResponseMessage NotificacionSMS(HttpRequestMessage request) { MilDiasEntities db = new MilDiasEntities(); try { string xmlString = request.Content.ReadAsStringAsync().Result; var deserializerXML = new XmlSerializer(typeof(MTRequestNotify)); MTRequestNotify MTReqNot = new MTRequestNotify(); using (TextReader readerXML = new StringReader(xmlString)) { MTReqNot = (MTRequestNotify)deserializerXML.Deserialize(readerXML); } Inscripcion inscripcion = db.Embarazada.Where(e => e.TELEFONO == MTReqNot.Telefono.Msisdn).FirstOrDefault().Inscripcion.Where(i => i.ACTIVO == true).FirstOrDefault(); LogMensaje log = new LogMensaje(); log.FECHA = DateTime.Now; log.MENSAJE = xmlString; log.ID_INSTANCIA = inscripcion.ID_INSTANCIA; log.ID_TIPOMENSAJE = 11; db.LogMensaje.Add(log); db.SaveChanges(); return(new HttpResponseMessage(HttpStatusCode.OK)); } catch (Exception e) { LogMensaje log = new LogMensaje(); log.FECHA = DateTime.Now; log.MENSAJE = e.InnerException.Message; log.ID_TIPOMENSAJE = 6; db.LogMensaje.Add(log); db.SaveChanges(); return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } }
private IList <LogMensaje> SampleMessages() { var listMessage = new List <LogMensaje>(); var msg = new LogMensaje { Id = 4545, Texto = "Mensaje Saliente: unit test msg1", Fecha = DateTime.Now, Latitud = 0.0, Longitud = 0.0 }; listMessage.Add(msg); msg = new LogMensaje { Id = 4546, Texto = "Mensaje Saliente: unit test msg2", Fecha = DateTime.Now, Latitud = 0.0, Longitud = 0.0 }; listMessage.Add(msg); msg = new LogMensaje { Id = 4547, Texto = "Mensaje Saliente: unit test msg3", Fecha = DateTime.Now, Latitud = 0.0, Longitud = 0.0 }; listMessage.Add(msg); return(listMessage); }
/// <summary> /// Sends a mail with info about the event. /// </summary> /// <param name="log"></param> private static void SendMail(LogMensaje log) { var configFile = Config.Mailing.MailingConfiguration; if (string.IsNullOrEmpty(configFile)) { throw new Exception("No pudo cargarse configuracion de mailing."); } var sender = new MailSender(configFile); const int minutes = 15; var monitor = Config.Monitor.HistoricMonitorLink; var link = 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); var chofer = log.Chofer != null?string.Format("Chofer: {0}", log.Chofer.Entidad.Descripcion) : "Sin Chofer Identificado"; var responsable = log.Coche.Chofer != null && log.Coche.Chofer.Entidad != null ? log.Coche.Chofer.Entidad.Descripcion : "Sin Responsable Asignado"; var parameters = 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, GetFecha(log, true), AddresserHelper.GetDescripcionEsquinaMasCercana(log.Latitud, log.Longitud), log.Texto, link }; SendMailToAllDestinations(log, sender, parameters); }
/// <summary> /// Sends a mail with the givenn parameters to all the directions givenn in the message. /// </summary> /// <param name="log"></param> /// <param name="sender"></param> /// <param name="parameters"></param> private static void SendMailToAllDestinations(LogMensaje log, MailSender sender, List <string> parameters) { if (string.IsNullOrEmpty(log.Accion.DestinatariosMail)) { return; } var originalSubject = !string.IsNullOrEmpty(log.Accion.AsuntoMail) ? log.Accion.AsuntoMail : sender.Config.Subject; var destinatariosMail = log.Accion.DestinatariosMail.Replace(',', ';'); var destinos = destinatariosMail.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (destinos.Count().Equals(0)) { return; } foreach (var destinatario in destinos) { sender.Config.Subject = originalSubject; var destinatarios = GetDestinatarios(destinatario, log, sender); if (destinatarios == null || destinatarios.Count.Equals(0)) { continue; } foreach (var dest in destinatarios.Where(dest => !string.IsNullOrEmpty(dest))) { sender.Config.ToAddress = dest.Trim(); sender.SendMail(parameters.ToArray()); } } }
private Message ConvertToMessage(LogMensaje mensajeConfirmacion) { return(new Message()); }
/// <summary> /// Performs all actions associated to the event and saves it into database. /// </summary> /// <param name="log"></param> private void SaveEvent(LogMensaje log) { var appliesToAnyAction = false; var actions = GetActions(log.Mensaje); var filteredActions = FilterActions(actions, log); foreach (var accion in filteredActions) { appliesToAnyAction = true; DaoFactory.RemoveFromSession(log); log.Id = 0; log.Accion = accion; if (accion.CambiaMensaje) { log.Texto += string.Concat(" ", accion.MensajeACambiar); } if (accion.PideFoto) { PedirFoto(log); } if (accion.GrabaEnBase) { DaoFactory.LogMensajeDAO.Save(log); } if (accion.EsAlarmaDeMail) { SendMail(log); } if (accion.EsAlarmaSMS) { SendSms(log); } if (accion.Habilita) { HabilitarUsuario(log); } if (accion.Inhabilita) { InhabilitarUsuario(log); } if (accion.ReportarAssistCargo) { ReportarAssistCargo(log, accion.CodigoAssistCargo); } } if (!appliesToAnyAction) { if (DaoFactory.Session.Transaction != null && DaoFactory.Session.Transaction.IsActive) { DaoFactory.LogMensajeDAO.SaveWithoutTransaction(log); } else { DaoFactory.LogMensajeDAO.Save(log); } } }
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"; } }
// POST: api/Messages public IHttpActionResult Post([FromBody] List <CustomMessage> messages) { try { var deviceId = GetDeviceId(Request); if (deviceId == null) { return(Unauthorized()); } if (messages == null) { return(BadRequest()); } var mensajes = new List <LogMensaje>(); foreach (var message in messages) { var logMensaje = new LogMensaje { Fecha = message.DateTime, Texto = message.Description, Latitud = message.Latitude, Longitud = message.Longitude }; bool esMensajeOculto = false; if (!String.IsNullOrEmpty(message.codigomensaje) && message.codigomensaje.StartsWith("R")) { message.codigomensaje = message.codigomensaje.Substring(1, message.codigomensaje.Length - 1); TicketRechazo.MotivoRechazo rechazoEnum = (TicketRechazo.MotivoRechazo) int.Parse(message.codigomensaje.ToString()); switch (rechazoEnum) { case TicketRechazo.MotivoRechazo.MalFacturado: case TicketRechazo.MotivoRechazo.MalPedido: case TicketRechazo.MotivoRechazo.NoEncontroDomicilio: case TicketRechazo.MotivoRechazo.NoPedido: case TicketRechazo.MotivoRechazo.Cerrado: case TicketRechazo.MotivoRechazo.CaminoIntransitable: case TicketRechazo.MotivoRechazo.FaltaSinCargo: case TicketRechazo.MotivoRechazo.FueraDeHorario: case TicketRechazo.MotivoRechazo.FueraDeZona: case TicketRechazo.MotivoRechazo.ProductoNoApto: case TicketRechazo.MotivoRechazo.SinDinero: { esMensajeOculto = true; var messageLog = DaoFactory.LogMensajeDAO.FindById(message.Id); Dispositivo device = DaoFactory.DispositivoDAO.FindByImei(deviceId); if (device == null) { continue; } var employee = DaoFactory.EmpleadoDAO.FindEmpleadoByDevice(device); if (employee == null) { continue; } var idRechazo = Convert.ToInt32(messageLog.Texto.Split(':')[0].Split(' ').Last()); var rechazo = DaoFactory.TicketRechazoDAO.FindById(idRechazo); if (rechazo != null) { try { if (rechazo.UltimoEstado == TicketRechazo.Estado.Notificado1 || rechazo.UltimoEstado == TicketRechazo.Estado.Notificado2 || rechazo.UltimoEstado == TicketRechazo.Estado.Notificado3) { IMessageSaver saver = new MessageSaver(DaoFactory); var messagetEXT = MessageSender.CreateSubmitTextMessage(device, saver); string usuario = ""; try { rechazo.ChangeEstado(Logictracker.Types.BusinessObjects.Rechazos.TicketRechazo.Estado.Alertado, "Confirma atenciĆ³n", employee); DaoFactory.TicketRechazoDAO.SaveOrUpdate(rechazo); //El usuario tomo existosamente el rechazo foreach (var item in rechazo.Detalle) { if (item.Estado == TicketRechazo.Estado.Alertado) { usuario = item.Empleado.Entidad.Descripcion; break; } } messagetEXT.AddMessageText("INFORME DE RECHAZO NRO " + idRechazo + " SE CONFIRMA LA ASISTENCIA PARA: " + usuario); messagetEXT.Send(); } catch (Exception ex) { messagetEXT.AddMessageText("INFORME DE RECHAZO NRO " + idRechazo + " HA OCURRIDO UN ERROR, POR FAVOR INTENTE NUEVAMENTE ASISTIR EL RECHAZO"); messagetEXT.Send(); throw ex; } } else { //El usuario ya fue alertado IMessageSaver saver = new MessageSaver(DaoFactory); var messagetEXT = MessageSender.CreateSubmitTextMessage(device, saver); string usuario = ""; foreach (var item in rechazo.Detalle) { if (item.Estado == TicketRechazo.Estado.Alertado) { usuario = item.Empleado.Entidad.Descripcion; break; } } messagetEXT.AddMessageText("INFORME DE RECHAZO NRO " + idRechazo + " EL RECHAZO YA FUE TOMADO POR: " + usuario); messagetEXT.Send(); } } catch (Exception ex) { if (!ex.Message.ToString().Contains("Cambio de estado invalido")) { throw ex; } } } break; } default: { TicketRechazo.Estado rechazoEstadoEnum = (TicketRechazo.Estado) int.Parse(message.codigomensaje.ToString()); switch (rechazoEstadoEnum) { case TicketRechazo.Estado.RespuestaExitosa: { esMensajeOculto = true; var device = DaoFactory.DispositivoDAO.FindByImei(deviceId); if (device == null) { continue; } var employee = DaoFactory.EmpleadoDAO.FindEmpleadoByDevice(device); if (employee == null) { continue; } var rechazo = DaoFactory.TicketRechazoDAO.FindById(message.Id); if (rechazo != null && message.Id > 0) { try { if (rechazo.UltimoEstado != TicketRechazo.Estado.RespuestaExitosa) { rechazo.ChangeEstado(Logictracker.Types.BusinessObjects.Rechazos.TicketRechazo.Estado.RespuestaExitosa, message.Description, employee); DaoFactory.TicketRechazoDAO.SaveOrUpdate(rechazo); } } catch (Exception ex) { if (!ex.Message.ToString().Contains("Cambio de estado invalido")) { throw ex; } } } break; } case TicketRechazo.Estado.RespuestaConRechazo: { esMensajeOculto = true; var device = DaoFactory.DispositivoDAO.FindByImei(deviceId); if (device == null) { continue; } var employee = DaoFactory.EmpleadoDAO.FindEmpleadoByDevice(device); if (employee == null) { continue; } var rechazo = DaoFactory.TicketRechazoDAO.FindById(message.Id); if (rechazo != null && rechazo.Id != 0) { try { if (rechazo.UltimoEstado != TicketRechazo.Estado.RespuestaConRechazo) { rechazo.ChangeEstado(Logictracker.Types.BusinessObjects.Rechazos.TicketRechazo.Estado.RespuestaConRechazo, message.Description, employee); DaoFactory.TicketRechazoDAO.SaveOrUpdate(rechazo); } } catch (Exception ex) { if (!ex.Message.ToString().Contains("Cambio de estado invalido")) { throw ex; } } } break; } default: break; } break; } } } if (!esMensajeOculto) { mensajes.Add(logMensaje); } } var value = RouteService.SendMessagesMobile(deviceId, mensajes); return(CreatedAtRoute("DefaultApi", null, value)); } catch (Exception error) { LogicTracker.App.Web.Api.Providers.LogWritter.writeLog(error); return(BadRequest()); } }
/// <summary> /// Gets the email address from the destination string. /// </summary> /// <param name="destinatario"></param> /// <param name="log"></param> /// <param name="sender"></param> /// <returns></returns> private static List <string> GetDestinatarios(string destinatario, LogMensaje log, MailSender sender) { destinatario = destinatario.Trim(); return(string.IsNullOrEmpty(destinatario) ? null : GetMailRealDestinatarios(destinatario, log, sender)); }
public IHttpActionResult PostItem(TicketRechazoModel rechazoModel) { var transacion = SessionHelper.Current.BeginTransaction(); try { var rechazoEntity = new TicketRechazo(rechazoModel.Observacion, Usuario.Empleado, DateTime.UtcNow); Mapper.ModelToEntity(rechazoModel, rechazoEntity); EntityDao.Save(rechazoEntity); Mapper.EntityToModel(rechazoEntity, rechazoModel); var empleado = rechazoEntity.Entrega.Responsable; if (empleado != null) { var cocheDao = DAOFactory.GetDao <CocheDAO>(); var mensajeDao = DAOFactory.GetDao <MensajeDAO>(); var logMensajeDao = DAOFactory.GetDao <LogMensajeDAO>(); var coche = cocheDao.FindByChofer(empleado.Id); if (coche != null) { var mensajeVO = mensajeDao.GetByCodigo(TicketRechazo.GetCodigoMotivo(rechazoEntity.Motivo), coche.Empresa, coche.Linea); var mensaje = mensajeDao.FindById(mensajeVO.Id); if (mensaje != null) { var newEvent = new LogMensaje { Coche = coche, Chofer = empleado, CodigoMensaje = mensaje.Codigo, Dispositivo = coche.Dispositivo, Expiracion = DateTime.UtcNow.AddDays(1), Fecha = DateTime.UtcNow, FechaAlta = DateTime.UtcNow, FechaFin = DateTime.UtcNow, IdCoche = coche.Id, Latitud = 0, LatitudFin = 0, Longitud = 0, LongitudFin = 0, Mensaje = mensaje, Texto = "INFORME DE RECHAZO NRO " + rechazoEntity.Id + ": " + mensaje.Descripcion + " -> " + rechazoEntity.Entrega.Descripcion, Usuario = Usuario }; logMensajeDao.Save(newEvent); } } else { STrace.Warning(STrace.Module, new Exception("Vendedor sin choche asociado")); } } transacion.Commit(); return(Created(string.Concat("api/ticketrechazo/item/{0}", rechazoEntity.Id), rechazoModel)); } catch (Exception ex) { STrace.Exception(STrace.Module, ex); transacion.Rollback(); return(InternalServerError(ex)); } }
private void GenerarEventoResponsable(LogMensaje log) { if (log.Entrega == null || log.Entrega.PuntoEntrega == null) { return; } var empleado = log.Entrega.PuntoEntrega.Responsable; if (empleado == null) { return; } var coche = DaoFactory.CocheDAO.FindByChofer(empleado.Id); if (coche == null) { return; } var newEvent = new LogMensaje { Coche = coche, Chofer = empleado, CodigoMensaje = log.CodigoMensaje, Dispositivo = coche.Dispositivo, Entrega = log.Entrega, Estado = log.Estado, Expiracion = log.Expiracion, Fecha = log.Fecha, FechaAlta = DateTime.UtcNow, FechaFin = log.FechaFin, IdCoche = coche.Id, IdPuntoDeInteres = log.IdPuntoDeInteres, Latitud = log.Latitud, LatitudFin = log.LatitudFin, Longitud = log.Longitud, LongitudFin = log.LongitudFin, Mensaje = log.Mensaje, Texto = "INFORME DE: " + log.Texto, TieneFoto = log.TieneFoto, Usuario = log.Usuario, VelocidadAlcanzada = log.VelocidadAlcanzada, VelocidadPermitida = log.VelocidadPermitida, Viaje = log.Viaje, Zona = log.Zona }; DaoFactory.LogMensajeDAO.Save(newEvent); if (newEvent.Viaje == null && newEvent.Entrega == null) { return; } var evenDistri = new EvenDistri { LogMensaje = newEvent, Fecha = newEvent.Fecha, Entrega = newEvent.Entrega, Viaje = newEvent.Viaje ?? newEvent.Entrega.Viaje }; DaoFactory.EvenDistriDAO.Save(evenDistri); }
/// <summary> /// Performs all actions associated to the event and saves it into database. /// </summary> /// <param name="log"></param> private void ProcessActions(LogMensaje log) { var appliesToAnyAction = false; var t = new TimeElapsed(); var actions = DaoFactory.AccionDAO.FindByMensaje(log.Mensaje); var totalSeconds = t.getTimeElapsed().TotalSeconds; if (totalSeconds > 1) { STrace.Debug("DispatcherLock", log.Dispositivo.Id, String.Format("ProcessActions/FindByMensaje ({0} secs)", totalSeconds)); } t.Restart(); var filteredActions = FilterActions(actions, log); totalSeconds = t.getTimeElapsed().TotalSeconds; if (totalSeconds > 1) { STrace.Debug("DispatcherLock", log.Dispositivo.Id, String.Format("ProcessActions/FilterActions ({0} secs)", totalSeconds)); } t.Restart(); foreach (var accion in filteredActions) { appliesToAnyAction = true; DaoFactory.RemoveFromSession(log); log.Id = 0; log.Accion = accion; if (accion.CambiaMensaje) { log.Texto += string.Concat(" ", accion.MensajeACambiar); } if (accion.PideFoto) { PedirFoto(log); } if (accion.GrabaEnBase) { GuardarEvento(log); } if (accion.EsAlarmaDeMail) { SendMail(log); } if (accion.EsAlarmaSms) { SendSms(log); } if (accion.Habilita) { HabilitarUsuario(log.Accion); } if (accion.Inhabilita) { InhabilitarUsuario(log.Accion); } if (accion.ReportarAssistCargo) { ReportarAssistCargo(log, accion.CodigoAssistCargo); } if (accion.EnviaReporte) { EnviarReporte(log); } //if (accion.ReportaResponsableCuenta) GenerarEventoResponsable(log); } totalSeconds = t.getTimeElapsed().TotalSeconds; if (totalSeconds > 1) { STrace.Debug("DispatcherLock", log.Dispositivo.Id, String.Format("ProcessActions/foreach ({0} secs)", totalSeconds)); } t.Restart(); if (!appliesToAnyAction) { GuardarEvento(log); } totalSeconds = t.getTimeElapsed().TotalSeconds; if (totalSeconds > 1) { STrace.Debug("DispatcherLock", log.Dispositivo.Id, String.Format("ProcessActions/GuardarEvento ({0} secs)", totalSeconds)); } }
internal bool EnviarSMS(string ArgMensaje, string ArgCarrier, string ArgTelefono, bool ArgEsControl, string ArgInstancia, int ArgMes) { MilDiasEntities db = new MilDiasEntities(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://64.76.120.14:6064/minsaludsanjuan"); try { string responseText = ""; request.ContentType = "text/xml"; request.Method = "POST"; MTRequest MT = new MTRequest(); MT.Proveedor.Id = "minsaludsanjuan"; MT.Proveedor.Password = "******"; MT.Servicio.Id = ArgCarrier; MT.Servicio.ContentType = "0"; MT.Telefono.Msisdn = ArgTelefono; MT.Contenido.Text = quitarAcentos(ArgMensaje); var body = new StringWriter(); var serializerXML = new XmlSerializer(typeof(MTRequest)); serializerXML.Serialize(body, MT); byte[] postBytes = Encoding.UTF8.GetBytes(body.ToString()); //byte[] postBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(body.ToString()); request.ContentLength = postBytes.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postBytes, 0, postBytes.Length); requestStream.Close(); using (var response = (HttpWebResponse)request.GetResponse()) { var encoding = ASCIIEncoding.ASCII; //Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); using (var reader = new StreamReader(response.GetResponseStream(), encoding)) { responseText = reader.ReadToEnd(); } LogMensaje log = new LogMensaje(); log.FECHA = DateTime.Now; log.MENSAJE = responseText; log.ID_INSTANCIA = ArgInstancia; if (ArgEsControl == true) { log.ID_TIPOMENSAJE = 4; var deserializerXML = new XmlSerializer(typeof(MTResponse)); MTResponse MTResp = new MTResponse(); using (TextReader readerXML = new StringReader(responseText)) { MTResp = (MTResponse)deserializerXML.Deserialize(readerXML); } LogMensajeControl logControl = new LogMensajeControl(); logControl.FECHA = DateTime.Now; logControl.ID_INSTANCIA = ArgInstancia; logControl.ID_TRANSACCION = int.Parse(MTResp.Transaccion.IdTran); logControl.ID_RESPUESTA = 3; //Por defecto ponemos que no contesto logControl.MES = ArgMes; db.LogMensajeControl.Add(logControl); db.SaveChanges(); } else { log.ID_TIPOMENSAJE = 1; } db.LogMensaje.Add(log); db.SaveChanges(); } return(true); } catch (Exception e) { request.Abort(); LogMensaje log = new LogMensaje(); log.FECHA = DateTime.Now; log.MENSAJE = e.Message; log.ID_TIPOMENSAJE = 6; db.SaveChanges(); return(false); } }
public LogMensajeBase Save(IMessage evento, string codigo, Dispositivo dispositivo, Coche coche, Empleado chofer, DateTime fecha, GPSPoint inicio, GPSPoint fin, string texto, int?velPermitida, int?velAlcanzada, int?idReferenciaGeografica, Zona zonaManejo, ViajeDistribucion viaje, EntregaDistribucion entrega) { try { var device = dispositivo ?? DaoFactory.DispositivoDAO.GetGenericDevice(coche.Empresa); var driver = chofer ?? (coche != null && !coche.IdentificaChoferes ? coche.Chofer : null); if (string.IsNullOrEmpty(codigo.Trim())) { return(null); } var mensaje = DaoFactory.MensajeDAO.GetByCodigo(codigo, coche != null ? coche.Empresa : null, coche != null ? coche.Linea : null); if (mensaje == null) { return(DiscardDueToInvalidMessage(codigo, coche, inicio, device, fin, driver, fecha)); } var ticket = DaoFactory.TicketDAO.FindEnCurso(dispositivo); var detalleTicket = ticket == null ? null : ticket.GetDetalleProximo(); driver = driver ?? (ticket != null ? ticket.Empleado : null); if (mensaje.Acceso >= Usuario.NivelAcceso.SysAdmin) { return(null); //var log = new LogMensajeAdmin //{ // Chofer = driver, // Coche = coche, // Dispositivo = device, // Estado = 0, // Fecha = fecha, // FechaAlta = DateTime.UtcNow, // Expiracion = DateTime.UtcNow.AddDays(1), // Horario = ticket, // DetalleHorario = detalleTicket, // Usuario = null, // Latitud = inicio != null ? inicio.Lat : 0, // Longitud = inicio != null ? inicio.Lon : 0, // FechaFin = fin != null ? fin.Date : (DateTime?)null, // LatitudFin = fin != null ? new Double?(fin.Lat) : null, // LongitudFin = fin != null ? new Double?(fin.Lon) : null, // VelocidadAlcanzada = velAlcanzada, // VelocidadPermitida = velPermitida, // IdPuntoDeInteres = idReferenciaGeografica, // Mensaje = DaoFactory.MensajeDAO.FindById(mensaje.Id), // Texto = String.Concat(mensaje.Texto, ' ', texto), // TieneFoto = codigo == ((int)MessageIdentifier.Picture).ToString(CultureInfo.InvariantCulture) //}; //ProcessActions(log); //return log; } else { var log = new LogMensaje { Chofer = driver, Coche = coche, Dispositivo = device, Estado = 0, Fecha = fecha, FechaAlta = DateTime.UtcNow, Expiracion = DateTime.UtcNow.AddDays(1), Horario = ticket, DetalleHorario = detalleTicket, Usuario = null, Latitud = inicio != null ? inicio.Lat : 0, Longitud = inicio != null ? inicio.Lon : 0, FechaFin = fin != null ? fin.Date : (DateTime?)null, LatitudFin = fin != null ? new Double?(fin.Lat) : null, LongitudFin = fin != null ? new Double?(fin.Lon) : null, VelocidadAlcanzada = velAlcanzada, VelocidadPermitida = velPermitida, IdPuntoDeInteres = idReferenciaGeografica, Mensaje = DaoFactory.MensajeDAO.FindById(mensaje.Id), Texto = String.Concat(mensaje.Texto, ' ', texto), TieneFoto = codigo == ((int)MessageIdentifier.Picture).ToString(CultureInfo.InvariantCulture), Viaje = viaje, Entrega = entrega }; ProcessActions(log); if (MessageIdentifierX.IsEngineOnOffEvent(log.Mensaje)) { DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoMotor); } else if (MessageIdentifierX.IsGarminOnOffEvent(log.Mensaje)) { DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoGarmin); } else if (MessageIdentifierX.IsPrivacyOnOffEvent(log.Mensaje)) { DaoFactory.LastVehicleEventDAO.Save(log, Coche.Totalizador.EstadoGps); } return(log); } } catch (Exception ex) { STrace.Exception(GetType().FullName, ex); return(null); } }