コード例 #1
0
ファイル: MetadataDirectory.cs プロジェクト: jesumarquez/lt
        private static void LoadAssemblies(String path)
        {
            STrace.Debug(typeof(ApplicationLoader).FullName, "Getting DLL filenames...");
            var files = Directory.GetFiles(path, "Logictracker*.dll");

            STrace.Debug(typeof(ApplicationLoader).FullName, String.Format("{0} DLL found...", files.Count()));
            var asms = new List <Assembly>();

            foreach (var file in files)
            {
                try
                {
                    //STrace.Debug(typeof(ApplicationLoader).FullName, String.Format("Assembly.LoadFrom({0}...", file));
                    var a = Assembly.LoadFrom(file);
                    asms.Add(a);
                }
                catch (BadImageFormatException)
                {
                    STrace.Error(typeof(MetadataDirectory).FullName, String.Format("Could not load assembly: {0}", file));
                }
            }

            foreach (var a in asms)
            {
                try
                {
                    LoadAssembly(a);
                }
                catch (BadImageFormatException)
                {
                    STrace.Error(typeof(MetadataDirectory).FullName, String.Format("Could not load assembly: {0}", a));
                }
            }
        }
コード例 #2
0
 /// <summary>
 ///     Close an ISession and unbind it from the current
 ///     NHibernate Context.
 /// </summary>
 public static void CloseSession()
 {
     if (CurrentSessionContext.HasBind(SessionFactory))
     {
         var session = CurrentSessionContext.Unbind(SessionFactory);
         if (session == null)
         {
             return;
         }
         if (session.Transaction != null && session.Transaction.IsActive)
         {
             STrace.Error(typeof(NHibernateHelper).FullName, String.Format("A non closed transaction is Active at CloseSession()!: {0}", HttpContext.Current != null ?HttpContext.Current.Request.CurrentExecutionFilePath : "No context?"));
             try
             {
                 session.Transaction.Commit();
             }
             catch (Exception ex)
             {
                 STrace.Exception(typeof(NHibernateHelper).FullName, ex, "CloseSession();");
                 try
                 {
                     session.Transaction.Rollback();
                 }
                 catch (Exception ex2)
                 {
                     STrace.Exception(typeof(NHibernateHelper).FullName, ex2, "CloseSession(); doing rollback");
                 }
             }
         }
         session.Close();
         session.Dispose();
     }
 }
コード例 #3
0
ファイル: BaseCodec.cs プロジェクト: jesumarquez/lt
        /// <summary>
        /// Ejecuta dentro de un lock por codec
        /// </summary>
        /// <param name="execute"> action a ejecutar dentro del lock</param>
        /// <param name="callerName"> action a ejecutat en el timeout </param>
        /// <param name="detailForOnFail"> actions a ejecutar en el fail </param>
        /// <returns> true si se pudo ejecutar dentro de lock</returns>
        public bool ExecuteOnGuard(Action execute, String callerName, String detailForOnFail)
        {
            bool rv = false;

            if (_deviceLock.WaitOne(TimeSpan.FromMinutes(1)))
            {
                try
                {
                    SessionHelper.CreateSession();
                    execute();
                    SessionHelper.CloseSession();
                    rv = true;
                }
                catch (Exception e)
                {
                    var context = new Dictionary <String, String> {
                        { "Detalle", detailForOnFail }
                    };
                    STrace.Debug(GetType().FullName, Id, detailForOnFail);
                    STrace.Exception(GetType().FullName, e, Id, context,
                                     String.Format("Exception during '{0}'", callerName));
                }
                finally
                {
                    _deviceLock.Set();
                }
            }
            else
            {
                STrace.Error(GetType().FullName, Id, String.Format("Lock timeout: {0}", callerName));
            }

            return(rv);
        }
コード例 #4
0
ファイル: IQuadTree.cs プロジェクト: jesumarquez/lt
        public bool SyncronizeQuadtree(ulong messageId, bool full, int baseRevision)
        {
            try
            {
                var QTreeFile = DataProvider.GetDetalleDispositivo(Id, "PARAM_QTREE_FILE").As("");

                if (String.IsNullOrEmpty(QTreeFile))
                {
                    STrace.Error(GetType().FullName, Id, @"No se fotea geogrilla por no estar el Detalle ""PARAM_QTREE_FILE""");
                    return(false);
                }

                if (baseRevision == 0 && !full)
                {
                    STrace.Error(GetType().FullName, Id, @"No se fotea Geogrilla diferencial ya que el detalle ""known_qtree_revision"" es cero, si quiere enviar toda la geogrilla utilize el comando ""Enviar Full Qtree""");
                    return(false);
                }
                var td = new TaskData
                {
                    Device    = this,
                    Path      = Path.Combine(Config.Qtree.QtreeGteDirectory, QTreeFile),
                    BaseRev   = baseRevision,
                    Full      = full,
                    MessageId = messageId,
                };
                ThreadPool.QueueUserWorkItem(CreateGeogrillaTxt, td);
                return(true);
            }
            catch (Exception e)
            {
                STrace.Exception(GetType().FullName, e, Id);
                return(false);
            }
        }
コード例 #5
0
        public static RunMode GetRunMode(String file)
        {
            try
            {
                var xDoc = XDocument.Load(file);

                if (xDoc.Root == null)
                {
                    return(RunMode.Invalid);
                }

                var rm = xDoc.Root.Attribute("RunMode");

                if (rm == null)
                {
                    return(RunMode.Invalid);
                }

                return((RunMode)Enum.Parse(typeof(RunMode), rm.Value));
            }
            catch (Exception)
            {
                STrace.Error(typeof(FrameworkElement).FullName, String.Format("Error determinando el modo de ejecucion de la aplicacion {0}", file));

                return(RunMode.Invalid);
            }
        }
コード例 #6
0
ファイル: TasaTranslator.cs プロジェクト: jesumarquez/lt
        public HandleResults HandleMessage(Position message)
        {
            if (message == null || message.GeoPoints.Count < 1)
            {
                STrace.Error(GetType().FullName, message.GetDeviceId(), "Position: null or empty");
                return(HandleResults.BreakSuccess);
            }

            const char code = 'Q';             // FueSolicitada? 'Q' : 'P';

            foreach (var p in message.GeoPoints)
            {
                STrace.Debug(GetType().FullName, message.DeviceId, "HANDLE --> <Position>");
                Enqueue(
                    String.Format("{6},{0},{1},{2},{3},{4},{5},",
                                  message.DeviceId,
                                  p.Date.ToString("dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture),               //sacar el formato del config.
                                  p.Lat.ToString(CultureInfo.InvariantCulture),
                                  p.Lon.ToString(CultureInfo.InvariantCulture),
                                  p.Speed,
                                  p.Course,
                                  code
                                  ));
            }
            return(HandleResults.BreakSuccess);
        }
コード例 #7
0
        private void ReportarAssistCargo(LogMensajeBase log, string assistCargoCode)
        {
            try
            {
                if (!log.Coche.ReportaAssistCargo)
                {
                    return;
                }

                STrace.Debug(GetType().FullName, log.Dispositivo.Id, String.Format("AssistCargo Event: {0} -> {1}: {2}", log.Coche.Patente, Config.AssistCargo.AssistCargoEventQueue, assistCargoCode));

                var queue = new IMessageQueue(Config.AssistCargo.AssistCargoEventQueue);

                if (queue.LoadResources())
                {
                    var data = new TextEvent(log.Dispositivo.Id, 0, DateTime.UtcNow)
                    {
                        Text     = assistCargoCode,
                        GeoPoint = new GPSPoint(log.Fecha, (float)log.Latitud, (float)log.Longitud)
                    };
                    queue.Send(data, MessageQueueTransactionType.Automatic);
                }
                else
                {
                    STrace.Error(GetType().FullName, log.Dispositivo.Id, String.Format("Problemas cargando la cola: {0}", Config.AssistCargo.AssistCargoEventQueue));
                }
            }
            catch (Exception e)
            {
                STrace.Exception(GetType().FullName, e, log.Dispositivo.Id);
            }
        }
コード例 #8
0
ファイル: PeriodData.cs プロジェクト: jesumarquez/lt
        private void LoadPosiciones()
        {
            var posicionDao = DaoFactory.LogPosicionDAO;

            var maxMonths = Vehiculo.Empresa != null ? Vehiculo.Empresa.MesesConsultaPosiciones : 3;

            var t = new TimeElapsed();

            PosicionSiguiente = posicionDao.GetFirstPositionNewerThanDate(Vehiculo.Id, Fin, maxMonths);
            var ts = t.getTimeElapsed().TotalSeconds;

            if (ts > 1)
            {
                STrace.Error("Logictracker.Scheduler.Tasks.Mantenimiento.DatamartGeneration", string.Format("GetFirstPositionNewerThanDate en {0} segundos", ts));
            }

            t.Restart();
            PosicionAnterior = Vehiculo.LastOdometerUpdate.HasValue ? posicionDao.GetFirstPositionOlderThanDate(Vehiculo.Id, Inicio, maxMonths) : null;
            ts = t.getTimeElapsed().TotalSeconds;
            if (ts > 1)
            {
                STrace.Error("Logictracker.Scheduler.Tasks.Mantenimiento.DatamartGeneration", string.Format("GetFirstPositionOlderThanDate en {0} segundos", ts));
            }

            t.Restart();
            var originalPositions = posicionDao.GetPositionsBetweenDates(Vehiculo.Id, Inicio, Fin, maxMonths);

            ts = t.getTimeElapsed().TotalSeconds;
            if (ts > 1)
            {
                STrace.Error("Logictracker.Scheduler.Tasks.Mantenimiento.DatamartGeneration", string.Format("GetPositionsBetweenDates: {0} posiciones en {1} segundos", originalPositions.Count, ts));
            }

            if (Vehiculo.Dispositivo != null && !DaoFactory.DetalleDispositivoDAO.GetDiscardsInvalidPositionsValue(Vehiculo.Dispositivo.Id))
            {
                Posiciones = CorrectGeorefferenciation(originalPositions);
            }
            else
            {
                var cleanPositions    = new List <LogPosicion>();
                var lastValidPosition = PosicionAnterior;
                foreach (var position in originalPositions)
                {
                    if (!EsPosicionValida(lastValidPosition, position))
                    {
                        posicionDao.Delete(position);
                        var discartedPosition = new LogPosicionDescartada(position, DiscardReason.DatamartCleanUp);
                        DaoFactory.LogPosicionDescartadaDAO.Save(discartedPosition);
                    }
                    else
                    {
                        cleanPositions.Add(position);
                        lastValidPosition = position;
                    }
                }
                Posiciones = CorrectGeorefferenciation(cleanPositions);
            }
        }
コード例 #9
0
ファイル: GeocercaManager.cs プロジェクト: jesumarquez/lt
        private static QtreeNode GetQtree(int empresa, int linea)
        {
            var lastMod = ReferenciaGeograficaDAO.GetLastUpdate(empresa, linea);
            var key     = GetQtreeKey(empresa, linea);

            var root = Qtrees.ContainsKey(key) ? Qtrees[key] : null;

            if (root != null && lastMod < root.LastUpdate)
            {
                return(root);
            }

            if (Monitor.TryEnter(Qtrees))
            {
                try
                {
                    STrace.Error("ResetQtree", string.Format("qtree UPDATE ---> Empresa: {0} - Linea: {1}", empresa, linea));

                    using (var transaction = SmartTransaction.BeginTransaction())
                    {
                        var daoFactory = new DAOFactory();
                        var geocercas  = daoFactory.ReferenciaGeograficaDAO.GetGeocercasFor(empresa, linea);
                        transaction.Commit();

                        var keyToRemove = string.Empty;
                        if (root != null)
                        {
                            keyToRemove = key;
                        }
                        root = new QtreeNode();

                        foreach (var geocerca in geocercas)
                        {
                            root.AddValue(geocerca);
                        }

                        if (keyToRemove != string.Empty)
                        {
                            Qtrees.Remove(keyToRemove);
                        }
                        Qtrees.Add(key, root);
                    }

                    STrace.Trace("DispatcherLock", string.Format("qtree NEW ---> {0} | {1}", empresa, linea));
                }
                finally
                {
                    Monitor.Exit(Qtrees);
                }
            }
            else
            {
                STrace.Trace("DispatcherLock", string.Format("qtree OLD ---> {0} | {1}", empresa, linea));
            }

            return(root);
        }
コード例 #10
0
ファイル: MessageHandler.cs プロジェクト: jesumarquez/lt
 public override bool LoadResources()
 {
     if (MessageQueue == null)
     {
         STrace.Error(GetType().FullName, String.Format("MessageHandler<{0}> No tiene message queue.", typeof(T).Name));
         return(false);
     }
     return(true);
 }
コード例 #11
0
 public bool StackBind(ILayer bottom, ILayer top)
 {
     if (top is IDispatcherLayer)
     {
         DispatcherLayer = top as IDispatcherLayer;
         return(true);
     }
     STrace.Error(GetType().FullName, "Falta IDispatcherLayer!");
     return(false);
 }
コード例 #12
0
        protected override void OnExecute(Timer timer)
        {
            var inicio = DateTime.UtcNow;

            //var mail = new MailSender(Config.Mailing.ReportSchedulerMailingConfiguration);
            var queue = GetMailReportQueue();

            if (queue == null)
            {
                STrace.Error(ComponentName, "Cola no encontrada: revisar configuracion");
                return;
            }

            // BUSCO TODOS LAS PROGRAMACIONES DIARIAS
            var reportesProgramados = new List <ProgramacionReporte>();

            // SI ES LUNES AGREGO LAS PROGRAMACIONES SEMANALES
            if (DateTime.UtcNow.ToDisplayDateTime().DayOfWeek == DayOfWeek.Monday)
            {
                reportesProgramados.AddRange(DaoFactory.ProgramacionReporteDAO.FindByPeriodicidad('S'));
            }
            else
            {
                reportesProgramados = DaoFactory.ProgramacionReporteDAO.FindByPeriodicidad('D');
            }

            // SI ES 1° AGREGO LAS PROGRAMACIONES MENSUALES
            if (DateTime.UtcNow.ToDisplayDateTime().Day == 1)
            {
                reportesProgramados.AddRange(DaoFactory.ProgramacionReporteDAO.FindByPeriodicidad('M'));
            }

            foreach (var reporte in reportesProgramados)
            {
                if ("MANUAL".Equals(reporte.ReportName))
                {
                    continue;
                }

                var cmd = GenerateReportCommand(reporte);
                if (cmd != null)
                {
                    queue.Send(cmd);
                }
            }

            //genera un FinalExecutionCommand
            queue.Send(GenerateReportCommand(new ProgramacionReporte()));

            var fin      = DateTime.UtcNow;
            var duracion = fin.Subtract(inicio).TotalMinutes;

            DaoFactory.DataMartsLogDAO.SaveNewLog(inicio, fin, duracion, DataMartsLog.Moludos.ReportScheduler, "Report Scheduler finalizado exitosamente");
        }
コード例 #13
0
ファイル: Scheduler.cs プロジェクト: jesumarquez/lt
 private void SerializerUnknownAttribute(object sender, XmlAttributeEventArgs e)
 {
     STrace.Error(GetType().FullName, String.Format(
                      "UnknownAttribute, Name={0} InnerXml={1} LineNumber={2} LinePosition={3} ObjectBeingDeserialized={4} sender={5}",
                      e.Attr.Name,
                      e.Attr.InnerXml,
                      e.LineNumber,
                      e.LinePosition,
                      e.ObjectBeingDeserialized,
                      sender));
 }
コード例 #14
0
        /// <summary>
        /// Gets the device associated to the givenn DeviceId.
        /// </summary>
        /// <param name="idNum"></param>
        /// <returns></returns>
        public Dispositivo GetByIdNum(int idNum)
        {
            var Devices = Session.Query <Dispositivo>().Where(d => d.IdNum == idNum && d.Estado < 2).Cacheable();

            if (Devices.Count() > 1)
            {
                STrace.Error(typeof(DispositivoDAO).FullName, String.Format("Error grave, el dispositivo con DeviceId '{0}' se encuentra dado de alta mas de una vez, IDs: '{1}'", idNum, String.Join("', '", Devices.Select(dev => dev.Id.ToString("D4")).ToArray())));
                return(null);
            }
            return(Devices.SingleOrDefault());
        }
コード例 #15
0
ファイル: Scheduler.cs プロジェクト: jesumarquez/lt
 private void SerializerUnknownNode(object sender, XmlNodeEventArgs e)
 {
     STrace.Error(GetType().FullName, String.Format(
                      "UnknownNode, Name={0} LocalName={1} NamespaceUri={2} Text={3} NodeType={4} ObjectBeingDeserialized={5} sender={6}",
                      e.Name,
                      e.LocalName,
                      e.NamespaceURI,
                      e.Text,
                      e.NodeType,
                      e.ObjectBeingDeserialized,
                      sender));
 }
コード例 #16
0
ファイル: ApplicationLoader.cs プロジェクト: jesumarquez/lt
        private static void WindowsMain(string file)
        {
            if (!Environment.UserInteractive)
            {
                STrace.Error(typeof(ApplicationLoader).FullName, String.Format("La aplicacion {0} se declaro como WinForm, pero no hay escritorio accesible.", file));
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Mainform());
        }
コード例 #17
0
        public static void Process(Coche vehiculo, IEvent data, bool ignoreMessages)
        {
            try
            {
                if (vehiculo.Dispositivo == null)
                {
                    return;
                }

                var daoFactory   = new DAOFactory();
                var messageSaver = ignoreMessages ? null : new MessageSaver(daoFactory);

                ICicloLogistico ciclo  = null;
                var             garmin = data as GarminEvent;
                if (garmin != null && garmin.DetailId > 0)
                {
                    var detailId = Convert.ToInt32(garmin.DetailId);

                    var entrega = daoFactory.EntregaDistribucionDAO.FindById(detailId);
                    if (entrega == null)
                    {
                        STrace.Error(typeof(CicloLogisticoFactory).FullName, detailId, "No se ha encontrado una distribucion para el vehiculo (" + garmin.DetailId.ToString("#0") + ")");
                    }
                    else
                    {
                        if (entrega.Viaje == null)
                        {
                            STrace.Error(typeof(CicloLogisticoFactory).FullName, detailId, "No se ha encontrado el ticket para la entrega (" + entrega.Id + ")");
                        }
                        else
                        {
                            var ticket = entrega.Viaje;
                            ciclo = new CicloLogisticoDistribucion(ticket, daoFactory, messageSaver);
                        }
                    }
                }
                else
                {
                    ciclo = GetCiclo(vehiculo, messageSaver, daoFactory);
                }

                if (ciclo == null)
                {
                    return;
                }
                ciclo.ProcessEvent(data);
            }
            catch (Exception ex)
            {
                STrace.Exception(typeof(CicloLogisticoFactory).FullName, ex);
            }
        }
コード例 #18
0
        /// <summary>
        /// Gets datamart regeneration periods.
        /// </summary>
        /// <param name="vehicle"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <param name="refference"></param>
        /// <returns></returns>
        public List <RegenerateDatamart> GetDaysToRegenerate(Coche vehicle, DateTime from, DateTime to, DateTime refference)
        {
            var posicionesDao = new LogPosicionDAO();

            int maxMonths;

            try
            {
                maxMonths = vehicle != null && vehicle.Empresa != null ? vehicle.Empresa.MesesConsultaPosiciones : 3;
            }
            catch (Exception)
            {
                maxMonths = 3;
            }

            var te    = new TimeElapsed();
            var start = posicionesDao.GetRegenerationStartDate(vehicle.Id, from, to, refference, maxMonths);
            var ts    = te.getTimeElapsed().TotalSeconds;

            if (ts > 1)
            {
                STrace.Error("Logictracker.Scheduler.Tasks.Mantenimiento.DatamartGeneration", string.Format("GetRegenerationStartDate en {0} segundos", ts));
            }

            if (!start.HasValue)
            {
                return(new List <RegenerateDatamart>());
            }

            var startDate = start.Value;

            te.Restart();
            var endDate = posicionesDao.GetRegenerationEndDate(vehicle.Id, from, to, maxMonths);

            ts = te.getTimeElapsed().TotalSeconds;
            if (ts > 1)
            {
                STrace.Error("Logictracker.Scheduler.Tasks.Mantenimiento.DatamartGeneration", string.Format("GetRegenerationEndDate en {0} segundos", ts));
            }

            var result = new List <RegenerateDatamart>();

            while (startDate < endDate)
            {
                var period = new RegenerateDatamart(startDate);
                result.Add(period);
                startDate = startDate.AddDays(1);
            }

            return(result);
        }
コード例 #19
0
ファイル: FrameworkElement.cs プロジェクト: jesumarquez/lt
 public void SafeUnloadResources()
 {
     try
     {
         if (!UnloadResources())
         {
             STrace.Error(GetType().FullName, String.Format("Error on UnloadResources() on XmlElement: <{0} x:Key={1} />", GetName(), StaticKey ?? "null"));
         }
     }
     catch (Exception e)
     {
         STrace.Exception(GetType().FullName, e, String.Format("Exception on UnloadResources() on XmlElement: <{0} x:Key={1} />", GetName(), StaticKey ?? "null"));
     }
 }
コード例 #20
0
ファイル: FrameworkElement.cs プロジェクト: jesumarquez/lt
 public void SafeLoadResources()
 {
     try
     {
         if (!LoadResources())
         {
             STrace.Error(typeof(FrameworkElement).FullName, String.Format("Error on LoadResources() on XmlElement: <{0} x:Key={1} />", GetName(), StaticKey ?? "null"));
         }
     }
     catch (Exception e)
     {
         STrace.Exception(typeof(FrameworkElement).FullName, e, String.Format("Exception on LoadResources() on XmlElement: <{0} x:Key={1} />", GetName(), StaticKey ?? "null"));
     }
 }
コード例 #21
0
 public static void SafeServiceStop(this IService me)
 {
     try
     {
         if (!me.ServiceStop())
         {
             STrace.Error(me.GetType().FullName, String.Format("Error on ServiceStop() on XmlElement: <{0} x:Key={1} />", me.GetName(), me.GetStaticKey() ?? "null"));
         }
     }
     catch (Exception e)
     {
         STrace.Exception(me.GetType().FullName, e, String.Format("Exception on ServiceStop() on XmlElement: <{0} x:Key={1} />", me.GetName(), me.GetStaticKey() ?? "null"));
     }
 }
コード例 #22
0
ファイル: AccessInterface.cs プロジェクト: jesumarquez/lt
        private void DoWork()
        {
            var daoFactory = new DAOFactory();
            var buffer     = new Byte[420];

            Connect();

            var receive = true;

            while (receive)
            {
                try
                {
                    _socket.ReceiveFrom(buffer, 0, 419, SocketFlags.None, ref _remoteEndPoint);
                    if (buffer[9] != 0x51)
                    {
                        continue;
                    }

                    var mac = BitConverter.ToString(buffer, 10, 6).Replace("-", String.Empty);
                    var dev = daoFactory.DispositivoDAO.GetByIMEI(mac);
                    if (dev == null)
                    {
                        STrace.Error(GetType().FullName, String.Format("Access no esta dado de alta, dar de alta un Dispositivo con el Imei: {0}", mac));
                        continue;
                    }

                    var rfid    = BitConverter.ToString(buffer, 31, 4).Replace("-", String.Empty);
                    var entrada = StringUtils.AreBitsSet(buffer[27], 0x01);
                    var dt      = new DateTime(buffer[26] + (DateTime.UtcNow.Year / 100) * 100, buffer[25], buffer[24], buffer[23], buffer[22], buffer[21]);
                    var msg     = MessageIdentifierX.FactoryRfid(dev.Id, 0, null, dt, rfid, entrada ? 3 : 4);
                    if (msg == null)
                    {
                        STrace.Debug(GetType().FullName, dev.Id, String.Format("Se descarta: DateTime={0} UserId={1} EsEntrada={2}", dt, rfid, entrada));
                        continue;
                    }

                    STrace.Debug(GetType().FullName, String.Format("Llego: DateTime={0} UserId={1} EsEntrada={2}", dt, rfid, entrada));
                    Dispatcher.Dispatch(msg);
                }
                catch (ThreadAbortException)
                {
                    receive = false;
                }
                catch (Exception e)
                {
                    STrace.Exception(GetType().FullName, e, "Stopping Access Main Loop due to exception");
                }
            }
        }
コード例 #23
0
        public IEnumerable <Geocerca> GetGeocercasFor(int empresaId, int lineaId, Dictionary <int, Direccion> direcciones, Dictionary <int, Poligono> poligonos)
        {
            var t    = new TimeElapsed();
            var sqlQ = Session.CreateSQLQuery("exec [dbo].[sp_getReferenciasGeoVigentes] @company = :company, @branch = :branch;");

            sqlQ.SetInt32("company", empresaId);
            sqlQ.SetInt32("branch", lineaId);
            sqlQ.SetResultTransformer(Transformers.AliasToBean(typeof(Geocerca)));
            var results = sqlQ.List <Geocerca>();

            STrace.Debug("DispatcherLock", string.Format("sp_getReferenciasGeoVigentes {0} en {1} segundos", results.Count(), t.getTimeElapsed().TotalSeconds));

            t = new TimeElapsed();
            foreach (var geo in results)
            {
                Direccion direccion = null;
                if (geo.DireccionId != null)
                {
                    if (direcciones.ContainsKey(geo.DireccionId.Value))
                    {
                        direccion = direcciones[geo.DireccionId.Value];
                    }
                    else
                    {
                        STrace.Error("DispatcherLock", string.Format("ERROR DIRECCION NO ENCONTRADA EN CACHE !!! {0} ({1},{2}) ", geo.DireccionId.Value, empresaId, lineaId));
                    }
                }

                Poligono poligono = null;
                if (geo.PoligonoId != null)
                {
                    if (poligonos.ContainsKey(geo.PoligonoId.Value))
                    {
                        poligono = poligonos[geo.PoligonoId.Value];
                    }
                    else
                    {
                        STrace.Error("DispatcherLock", string.Format("ERROR POLIGONO NO ENCONTRADO EN CACHE !!! {0} ({1},{2}) ", geo.PoligonoId.Value, empresaId, lineaId));
                    }
                }

                if (direccion != null || poligono != null)
                {
                    geo.Calculate(direccion, poligono);
                }
            }
            STrace.Debug("DispatcherLock", string.Format("geo.Calculate {0} en {1} segundos", results.Count(), t.getTimeElapsed().TotalSeconds));
            return(results);
        }
コード例 #24
0
ファイル: LogPosicionVO.cs プロジェクト: jesumarquez/lt
        /// <summary>
        /// Instanciates a new position vo based on the givenn position.
        /// </summary>
        /// <param name="lastPosition"></param>
        public LogPosicionVo(LogPosicionBase lastPosition)
        {
            var te = new TimeElapsed();

            Id             = lastPosition.Id;
            FechaRecepcion = lastPosition.FechaRecepcion;
            FechaMensaje   = lastPosition.FechaMensaje;
            Longitud       = lastPosition.Longitud;
            Latitud        = lastPosition.Latitud;
            Altitud        = lastPosition.Altitud;
            IdDispositivo  = lastPosition.Dispositivo.Id;
            try
            {
                Dispositivo     = lastPosition.Dispositivo.Codigo;
                TipoDispositivo = String.Format("{0} - {1}", lastPosition.Dispositivo.TipoDispositivo.Fabricante, lastPosition.Dispositivo.TipoDispositivo.Modelo);
                //Firmware = lastPosition.Dispositivo.FullFirmwareVersion;
                //Qtree = lastPosition.Dispositivo.QtreeRevision;
                EstadoDispositivo = lastPosition.Dispositivo.Estado;
            }
            catch {}

            Velocidad = lastPosition.Velocidad;
            Curso     = lastPosition.Curso;
            MotorOn   = lastPosition.MotorOn;
            HDop      = lastPosition.HDop;

            var totalSecs = te.getTimeElapsed().TotalSeconds;

            if (totalSecs > 1)
            {
                STrace.Error("DispatcherLock", lastPosition.Dispositivo.Id, "LogPosicionVo #1: " + totalSecs);
            }

            te.Restart();
            ApplyVehicleData(lastPosition.Coche);
            totalSecs = te.getTimeElapsed().TotalSeconds;
            if (totalSecs > 1)
            {
                STrace.Error("DispatcherLock", lastPosition.Dispositivo.Id, "ApplyVehicleData: " + totalSecs);
            }

            te.Restart();
            HasValidParents(lastPosition);
            totalSecs = te.getTimeElapsed().TotalSeconds;
            if (totalSecs > 1)
            {
                STrace.Error("DispatcherLock", lastPosition.Dispositivo.Id, "HasValidParents: " + totalSecs);
            }
        }
コード例 #25
0
ファイル: CocheDAO.cs プロジェクト: jesumarquez/lt
        /// <summary>
        /// Gets the vehicle assigned to the specified device id.
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public Coche FindMobileByDevice(int deviceId)
        {
            lock (GetLockByDevice(deviceId))
            {
                var devVeh = RetrieveDevKey(deviceId);
                if (!string.IsNullOrEmpty(devVeh))
                {
                    var cocheId = Convert.ToInt32(devVeh);
                    var coche   = cocheId == 0 ? null : FindById(cocheId);
                    if (coche == null)
                    {
                        STrace.Error("FindMobileByDevice", deviceId, "coche == null");
                        return(null);
                    }
                    if (coche.Dispositivo == null)
                    {
                        STrace.Error("FindMobileByDevice", deviceId, "coche.Dispositivo == null");
                        return(null);
                    }
                    if (coche.Dispositivo.Id != deviceId)
                    {
                        STrace.Error("FindMobileByDevice", deviceId, "coche.Dispositivo.Id != deviceId");
                        return(null);
                    }
                    return(coche);
                }

                try
                {
                    var dc = GetDetachedCriteriaByDevice(0, new[] { deviceId });
                    var c  = GetCriteria(dc, null);

                    var cocheObjs = c.List <Coche>();
                    if (cocheObjs.Count() > 1)
                    {
                        throw new ApplicationException("Dispositivo asignado a mas de un Vehiculo");
                    }

                    var cocheObj = cocheObjs.FirstOrDefault();
                    StoreDevKey(deviceId, cocheObj);
                    return(cocheObj);
                }
                catch (Exception e)
                {
                    STrace.Exception(typeof(CocheDAO).FullName, e, deviceId);
                    return(null);
                }
            }
        }
コード例 #26
0
        public bool LoadResources()
        {
            try
            {
                if (System.Messaging.MessageQueue.Exists(MessageQueue.QueueName))
                {
                    Handler = new MessageQueue(MessageQueue.QueueName);
                    if (MessageQueue.Transactional != Handler.Transactional)
                    {
                        STrace.Error(typeof(IMessageQueue).FullName, String.Format("MSMQ '{0}' - 'Transactional' no coincide.", MessageQueue.QueueName));
                        MessageQueue.Transactional = Handler.Transactional;
                    }

                    /*if (Recoverable != Handler.DefaultPropertiesToSend.Recoverable)
                     * {
                     *  STrace.Debug(typeof(IMessageQueue).FullName, String.Format("MSMQ '{0}' - 'Recoverable' no coincide.", QueueName));
                     *  Recoverable = Handler.DefaultPropertiesToSend.Recoverable;
                     * }//*/
                }
                else
                {
                    Handler = System.Messaging.MessageQueue.Create(MessageQueue.QueueName, MessageQueue.Transactional);
                    Handler.DefaultPropertiesToSend.Recoverable = MessageQueue.Recoverable;
                }

                Handler.SetPermissions(MessageQueue.OwnerGroup ?? Config.Queue.QueueUser, MessageQueueAccessRights.FullControl);

                var formatter = (MessageQueue.Formatter ?? "BINARY").ToUpper();
                if (formatter.StartsWith("BINARY"))
                {
                    Handler.Formatter = new BinaryMessageFormatter();
                }
                else if (formatter.StartsWith("XML"))
                {
                    Handler.Formatter = new XmlMessageFormatter(new[] { typeof(String) });
                }
                else if (formatter.StartsWith("ACTIVEX"))
                {
                    Handler.Formatter = new ActiveXMessageFormatter();
                }
                return(true);
            }
            catch (Exception e)
            {
                STrace.Exception(typeof(IMessageQueue).FullName, e, String.Format("Error inicializando la cola '{0}'", MessageQueue.QueueName));
                Handler = null;
                return(false);
            }
        }
コード例 #27
0
 public void UpdateGeocercas(Dictionary <int, List <int> > empresasLineas)
 {
     // recibo un diccionario (_empresasLineas), pero armo uno nuevo (leDict)
     if (empresasLineas.Count > 0)
     {
         foreach (var k in empresasLineas.Keys)
         {
             foreach (var v in empresasLineas[k])
             {
                 ResetLastModQtree(k, v);
                 STrace.Error("ResetQtree", "qtree RESET ---> Empresa: " + k + " - Linea: " + v);
             }
         }
     }
 }
コード例 #28
0
ファイル: BaseDeviceCommand.cs プロジェクト: jesumarquez/lt
        private string getCommandFrom(String command)
        {
            var mCommand = Regex.Match(command, getCommandPattern());

            if (mCommand.Success &&
                mCommand.Groups["command"].Success)
            {
                return(mCommand.Groups["command"].Value);
            }
            else
            {
                STrace.Error(typeof(BaseDeviceCommand).FullName, IdNum ?? 0, "RECEIVED COMMAND: " + command);
                return(null);
            }
        }
コード例 #29
0
ファイル: Task.cs プロジェクト: jesumarquez/lt
        /// <summary>
        /// Determina si el tanque estuvo debajo del porcentaje configurado desde el ultimo reporte.
        /// </summary>
        /// <param name="tank"></param>
        /// <param name="vol"></param>
        /// <param name="volDif"></param>
        /// <returns></returns>
        private bool HasBeenBelowPercentageSinceLastEvent(Tanque tank, VolumenHistorico vol, double volDif)
        {
            var lastMessage = DaoFactory.TanqueDAO.FindLastMessageByCode(tank.Id, CodeTDifRealVsTeoricoSuperada);

            if (lastMessage == null)
            {
                STrace.Error(GetType().FullName, "Last message date was NULL");

                return(true);
            }

            var lastMovementBelowDifference = DaoFactory.VolumenHistoricoDAO.FindLastTeoricVolumeBelowRealAndTeoricDifference(tank.Id, vol.Fecha, lastMessage.Fecha, volDif);

            return(lastMovementBelowDifference != null);
        }
コード例 #30
0
        private LogMensajeBase DiscardDueToInvalidMessage(String code, Coche coche, GPSPoint inicio, Dispositivo device, GPSPoint fin, Empleado driver, DateTime dt)
        {
            if (coche != null)
            {
                STrace.Error(GetType().FullName, coche.Dispositivo.Id, String.Format("A message with code {0} was not found for the vehicle {1} (id={2}).", code, coche.Interno, coche.Id));
            }
            else
            {
                STrace.Error(GetType().FullName, device.Id, String.Format("A message with code {0} was not found.", code));
            }

            DiscardEvent(null, device, coche, driver, dt, inicio, fin, DiscardReason.NoMessageFound, code);

            return(null);
        }