/// <summary>
        /// Verifica si se cumple alguna condicion de activacion para un request activo.
        /// Estas condiciones son:
        ///   * La fecha actual es mayor a la de inicio. (Si la fecha de inicio esta especificada)
        ///   * La distancia al port o portfacility es menor o igual que la especificada. (Si AccessType=3)
        /// </summary>
        /// <param name="aspr"></param>
        /// <param name="UtcNow"></param>
        /// <returns></returns>
        private bool RequestReadyToActive(ActiveShipPositionRequest aspr, DateTime UtcNow)
        {
            var ddpm       = new DDPVersionManager();
            var currentDDP = ddpm.GetCurrentDDPVersion();

            var spr = aspr.ShipPositionRequest;
            var spm = new ShipPositionManager();

            if (ShipPositionRequestHelper.IsOneTimePoll(spr.RequestType) == true)
            {
                return(true);
            }

            if (spr.AccessType != 3 && spr.StartTimeSpecified != 0 && UtcNow >= spr.StartTime)
            {
                return(true);
            }

            if (spr.AccessType == 3 && spm.IsShipInArea(spr.IMONum, spr.Item, double.Parse(spr.Distance), currentDDP.Id) == true)
            {
                return(true);
            }

            return(false);
        }
示例#2
0
        public string GetShipState(Ship ship)
        {
            ShipDataAccess          sda  = null;
            StandingOrderDataAccess soda = null;

            try
            {
                sda  = new ShipDataAccess();
                soda = new StandingOrderDataAccess();

                var spman               = new ShipPositionManager();
                var ddpman              = new DDPVersionManager();
                var ddpver              = ddpman.GetCurrentDDPVersion();
                var lastpos             = spman.GetLastShipPosition(ship.IMONum);
                List <StandingOrder> so = new List <StandingOrder>();


                if (lastpos != null)
                {
                    so = soda.GetOrdersForPosition(lastpos, ddpver);
                }

                if (so.Count != 0)
                {
                    return("blue");
                }

                if (sda.HasActiveRequest(ship) != 0)
                {
                    return("green");
                }

                if (lastpos != null)
                {
                    if (DateTime.UtcNow - lastpos.TimeStamp > TimeSpan.FromDays(1))
                    {
                        return("red");
                    }
                }

                return("normal");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                return("normal");
            }
            finally
            {
                if (sda != null)
                {
                    sda.Dispose();
                }
                if (soda != null)
                {
                    soda.Dispose();
                }
            }
        }
示例#3
0
        /// <summary>
        /// Procesa un mensaje de tipo SARSurpicRequest.
        /// </summary>
        /// <param name="msg">Mensaje SARSURPICRequest</param>
        public void ProcessSARSURPICRequest(SARSURPICType SARSURPICRequest)
        {
            var configMgr           = new ConfigurationManager();
            var shipPositionManager = new ShipPositionManager();

            List <ShipPosition> shipPositions;

            if (SARSURPICRequest.ItemElementName == DataCenterLogic.DataCenterTypes.ItemChoiceType1.SARCircularArea)
            {
                shipPositions = shipPositionManager.GetLastPositionsInCircularArea(SARSURPICRequest.Item, int.Parse(SARSURPICRequest.NumberOfPositions));
            }
            else
            {
                shipPositions = shipPositionManager.GetLastPositionsInRectangularArea(SARSURPICRequest.Item, int.Parse(SARSURPICRequest.NumberOfPositions));
            }

            if (shipPositions.Count == 0)
            {
                DataCenterTypesIDE.ReceiptType receipt = new DataCenterLogic.DataCenterTypesIDE.ReceiptType();
                receipt.DDPVersionNum = DDPVersionManager.currentDDP();
                receipt.Destination   = SARSURPICRequest.DataUserRequestor;
                receipt.Message       = "No positions";
                receipt.MessageId     = MessageIdManager.Generate();
                receipt.MessageType   = DataCenterLogic.DataCenterTypesIDE.messageTypeType3.Item7;
                receipt.Originator    = "1005";
                receipt.ReceiptCode   = DataCenterLogic.DataCenterTypesIDE.receiptCodeType.Item7;
                receipt.ReferenceId   = SARSURPICRequest.MessageId;
                receipt.schemaVersion = decimal.Parse(configMgr.Configuration.SchemaVersion);
                receipt.test          = DataCenterLogic.DataCenterTypesIDE.testType.Item1;
                receipt.TimeStamp     = DateTime.UtcNow;

                //Receipt sent
                Message msgout = new Message(receipt);
                msgout.Label = "receipt";
                QueueManager.Instance().EnqueueOut(msgout);
            }
            else
            {
                using (var shipdao = new ShipDataAccess())
                {
                    var sprm = new ShipPositionReportManager();
                    foreach (ShipPosition shipPos in shipPositions)
                    {
                        sprm.SendReport(SARSURPICRequest.DataUserRequestor, shipPos, SARSURPICRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.responseTypeType.Item4, DataCenterLogic.DataCenterTypesIDE.messageTypeType.Item3);
                    }
                }
            }

            using (var dao = new SARSURPICRequestDataAccess())
            {
                dao.Create(TypeHelper.Map2DB(SARSURPICRequest), 0);
            }
            log.Info("SARSURPICRequest successfully processed");
        }
        /// <summary>
        /// Procesa un pedido de posicion historica.
        /// Los pedidos de posicion historicas son RequestType 7 y RequestType 9
        /// </summary>
        /// <param name="shipPositionRequest">Mensaje de ShipPositionRequest</param>
        /// <param name="ship">Barco al que se hace referencia</param>
        private void ProcessHistoricShipPositionRequest(DataCenterLogic.DataCenterTypes.ShipPositionRequestType shipPositionRequest, Ship ship)
        {
            log.Info("Procesando ShipPositionRequest Historico");
            log.Debug("Obteniendo CgId de LRITId");

            //Obtener Contracting goverment ID
            ContractingGovermentManager cgmgr = new ContractingGovermentManager();
            var ddpm       = new DDPVersionManager();
            var currentDDP = ddpm.GetCurrentDDPVersion();

            var contractingGoverment = cgmgr.GetContractingGovermentByLRITId(shipPositionRequest.DataUserRequestor, currentDDP.Id);

            if (contractingGoverment == null)
            {
                log.Info("CGID no válido se envia recibo");
                ReceiptManager.SendReceipt(shipPositionRequest.DataUserRequestor, shipPositionRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.receiptCodeType.Item7,
                                           string.Format("Invalid Contracting Government ID"));
                return;
            }

            ShipPositionManager spm = new ShipPositionManager();

            List <ShipPosition> positions = new List <ShipPosition>();

            log.Debug("Verificando si se pide ultima posicion");
            if (ShipPositionRequestHelper.IsMostRecentPosition(shipPositionRequest.RequestType))
            {
                ShipPosition pos = spm.GetLastShipPosition(shipPositionRequest.IMONum);
                if (pos != null)
                {
                    positions.Add(pos);
                }
            }
            else
            {
                log.Debug("No, se piden mas posiciones");
                log.Debug("Verificando titulacion");
                positions = spm.GetShipPositionHistory(shipPositionRequest.IMONum,
                                                       shipPositionRequest.RequestDuration.startTime,
                                                       shipPositionRequest.RequestDuration.stopTime);
            }

            if (positions.Count == 0)
            {
                log.Info("No hay posiciones");
                //The ship didnt send message in that period
                ReceiptManager.SendReceipt(shipPositionRequest.DataUserRequestor, shipPositionRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.receiptCodeType.Item6,
                                           string.Format("No archived data for the request"));
                return;
            }

            var configMgr = new ConfigurationManager();

            log.Debug("Procesando Posiciones");

            int not_entitled_count = 0;

            var ddpVersion = ddpm.DDPFromDate(DateTime.UtcNow);
            var cgOld      = cgmgr.GetContractingGovermentByLRITId(shipPositionRequest.DataUserRequestor, ddpVersion.Id);

            foreach (ShipPosition position in positions)
            {
                bool verifyWatersOf = true;
                if (shipPositionRequest.AccessType == accessTypeType.Item3 || shipPositionRequest.AccessType == accessTypeType.Item5)
                {
                    verifyWatersOf = false;
                }

                //Solo valido titulacion si el access type es distinto a 6 (SAR)
                if (shipPositionRequest.AccessType != accessTypeType.Item6 && (ddpVersion == null || cgmgr.IsEntitled(cgOld, position, ddpVersion, verifyWatersOf) == false))
                {
                    not_entitled_count++;
                    continue;
                }

                var sprm = new ShipPositionReportManager();

                if (ShipPositionRequestHelper.IsMostRecentPosition(shipPositionRequest.RequestType))
                {
                    sprm.SendReport(shipPositionRequest.DataUserRequestor, position, shipPositionRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.responseTypeType.Item4, DataCenterLogic.DataCenterTypesIDE.messageTypeType.Item3);
                }
                else
                {
                    if (shipPositionRequest.AccessType == accessTypeType.Item3 || shipPositionRequest.AccessType == accessTypeType.Item5)
                    {
                        sprm.SendReport(shipPositionRequest.DataUserRequestor, position, shipPositionRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.responseTypeType.Item3, DataCenterLogic.DataCenterTypesIDE.messageTypeType.Item1);
                    }
                    else if (shipPositionRequest.AccessType == accessTypeType.Item1)
                    {
                        sprm.SendReport(shipPositionRequest.DataUserRequestor, position, shipPositionRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.responseTypeType.Item1, DataCenterLogic.DataCenterTypesIDE.messageTypeType.Item1);
                    }
                    else if (shipPositionRequest.AccessType == accessTypeType.Item2)
                    {
                        sprm.SendReport(shipPositionRequest.DataUserRequestor, position, shipPositionRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.responseTypeType.Item2, DataCenterLogic.DataCenterTypesIDE.messageTypeType.Item1);
                    }
                    else
                    {
                        sprm.SendReport(shipPositionRequest.DataUserRequestor, position, shipPositionRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.responseTypeType.Item4, DataCenterLogic.DataCenterTypesIDE.messageTypeType.Item1);
                    }
                }

                log.Debug("Report Enviado");
            }

            //Hubo alguna posicion para la que no tuvo permiso
            if (not_entitled_count != 0)
            {
                ReceiptManager.SendReceipt(shipPositionRequest.DataUserRequestor, shipPositionRequest.MessageId, DataCenterLogic.DataCenterTypesIDE.receiptCodeType.Item7,
                                           string.Format("Not entitled to recieve {0} positions", not_entitled_count));
                log.Debug("Receipt Enviado");
            }

            return;
        }
示例#5
0
        /// <summary>
        /// Envia el comando al ASP que sera transmitido al ASP
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="minutes">El periodo del reporte en minutos</param>
        /// <param name="ship"></param>
        /// <param name="poll"></param>
        public void CreatePollMessage(DateTime startTime, int minutes, Ship ship, PollAction poll)
        {
            //Only for satamatics
            if (ship.issata != 0)
            {
                var msg2 = new DataCenterLogic.DCASP.PollMessageSata();
                msg2.equipmentId = ship.Mobile;

                if (poll == PollAction.Reprogram)
                {
                    msg2.reprog  = true;
                    msg2.minutes = minutes;
                    log.Info("CreatePollMessage: enviando PollAction.Reprogram al ASP");
                }
                else if (poll == PollAction.Stop)
                {
                    msg2.reprog  = true;
                    msg2.minutes = 0;
                    log.Info("CreatePollMessage: enviando PollAction.Stop al ASP");
                }
                else if (poll == PollAction.Report)
                {
                    msg2.reprog  = false;
                    msg2.minutes = 0;
                    log.Info("CreatePollMessage: enviando PollAction.Report al ASP");
                }

                var cc2 = new DataCenterLogic.DCASP.LRITDCASPServiceSoapClient();
                if (System.Configuration.ConfigurationManager.AppSettings["send2servers"] != "False")
                {
                    cc2.PollShipSata(msg2);
                }
                return;
            }

            var msg   = new DataCenterLogic.DCASP.PollMessage();
            var spman = new ShipPositionManager();

            var pos = spman.GetLastShipPosition(ship.IMONum);

            if (pos != null)
            {
                msg.OceanRegion = (DCASP.EOceanRegion)pos.Region;
            }
            else
            {
                msg.OceanRegion = DCASP.EOceanRegion.AORW;
            }
            msg.DNID         = ship.DNID;
            msg.PollType     = DCASP.EPollType.IndividualPoll;
            msg.ResponseType = DCASP.EResponseType.DataReport;
            msg.SubAddress   = DCASP.ESubAddress.Others;
            msg.Address      = ship.Mobile;
            msg.MemberNumber = ship.Member;


            switch (poll)
            {
            case PollAction.Report:
            {
                msg.CommandType     = DCASP.ECommandType.DataReport;
                msg.StartFrame      = 0;
                msg.NumberOfReports = 0;
                ShipManager.ChangeShipStatus(ShipStatus.Polling, ship);
                log.Info("Enviando Solicitud de report a ASP");
                break;
            }

            case PollAction.Reprogram:
            {
                msg.CommandType     = DCASP.ECommandType.ProgramDataReporting;
                msg.StartFrame      = TimeToFrame(startTime.TimeOfDay);
                msg.NumberOfReports = MinutesToTimesPerDay(minutes);
                ShipManager.ChangeShipStatus(ShipStatus.Polling, ship);
                log.Info("Enviando Solicitud de report periodico a ASP");
                break;
            }

            case PollAction.Stop:
            {
                msg.CommandType     = DCASP.ECommandType.StopDataReserving;
                msg.StartFrame      = 0;
                msg.NumberOfReports = 0;
                ShipManager.ChangeShipStatus(ShipStatus.Polling, ship);
                log.Info("Enviando Solicitud de Stop a ASP");
                break;
            }
            }
            //UNCOMMENT!
            var cc = new DataCenterLogic.DCASP.LRITDCASPServiceSoapClient();

            if (System.Configuration.ConfigurationManager.AppSettings["send2servers"] != "False")
            {
                cc.PollShip(msg);
            }
        }
        /// <summary>
        /// Esta es la funcion principal del manejador de pedidos activos.
        /// Itera y procesa todos los pedidos activo.
        /// Es encargada de enviar (cuando se cumplan las condiciones) los mensajes a la cola de salida.
        /// </summary>
        public void Process(int hour, int mins) //hora: 0-23, minutes={0, 15, 30, 45}
        {
            //log.Info("Procesando Active Ship Position Request");
            using (var asprda = new ActiveShipPositionRequestDataAccess())
            {
                List <ActiveShipPositionRequest> asprlist = asprda.GetAll();
                foreach (ActiveShipPositionRequest aspr in asprlist)
                {
                    try
                    {
                        //Verifica si el tiempo de inicio ya paso
                        var      spm    = new ShipPositionManager();
                        var      spr    = aspr.ShipPositionRequest;
                        DateTime UtcNow = DateTime.UtcNow;
                        //log.Debug("Verificando estado del ASPR");
                        if (aspr.Status == 0)
                        {
                            //Condicion para activar el envio
                            if (RequestReadyToActive(aspr, UtcNow) == true)
                            {
                                if (TryReprog(spr) == true)
                                {
                                    asprda.Update(aspr.Id, 1, UtcNow);
                                    log.Debug("Reprogramado OK ==> estado ACTIVO");
                                }
                                else
                                {
                                    log.Error("Reprogramado ERROR");
                                }
                            }
                        }
                        else
                        {
                            //Status = 1
                            if (spr.StopTime != null && UtcNow >= spr.StopTime)
                            {
                                var IMONum         = aspr.ShipPositionRequest.IMONum;
                                var currentReqType = ShipPositionRequestHelper.GetMinutes(aspr.ShipPositionRequest.RequestType);
                                var minReqType     = GetMinPeriodForShip(IMONum, 0);

                                log.Debug("Se cumplio Stop Time del request eliminando request activo");

                                asprda.Remove(aspr);

                                //Verifica si el request tiene frecuencia distinta a la actual y reprograma si es necesario
                                //si el request caduco reprograma para que reporte cada 6 horas
                                log.Debug("Verificando si hay que reprogramar el equipo");
                                if (minReqType == currentReqType)
                                {
                                    using (var sda = new ShipDataAccess())
                                    {
                                        int newMinPeriod = GetMinPeriodForShip(IMONum, 0);

                                        if (newMinPeriod == -1)
                                        {
                                            newMinPeriod = 360;
                                        }

                                        //Reprogram ASP
                                        try
                                        {
                                            var aspman = new AspManager();
                                            aspman.CreatePollMessage(DateTime.UtcNow.AddMinutes(8), newMinPeriod, sda.getByIMONum(spr.IMONum), PollAction.Reprogram);
                                        }
                                        catch (Exception ex)
                                        {
                                            ShipManager.ChangeShipStatus(ShipStatus.Error, sda.getByIMONum(spr.IMONum));
                                            log.Error("Hubo un error en la reprogramacion del barco" + Environment.NewLine + Environment.NewLine + ex + Environment.NewLine + Environment.NewLine);
                                        }
                                    }
                                }
                                //log.Debug("ASPR " + aspr.Id + " REMOVED: Status: " + aspr.Status + " Barco:" + spr.IMONum);
                                //log.Debug("Requestor: " + spr.DataUserRequestor);
                                //log.Debug("Access-Request Type: " + spr.AccessType + "-" + spr.RequestType);
                                continue;
                            }

                            //log.Debug("Verificando si es request de unica vez");
                            //ONE TIME POLL
                            if (ShipPositionRequestHelper.IsOneTimePoll(spr.RequestType) == true)
                            {
                                //log.Debug("verificando si hay nueva posicion registrada");
                                ShipPosition spos = spm.GetLastShipPosition(spr.IMONum);
                                if (spos != null && spos.TimeStamp > aspr.LastTime)
                                {
                                    log.Debug("Nueva posicion con fecha > LastTime ... verificando titulacion");
                                    CheckEntitlementAndSendReportOrReceipt(spr, spos);
                                    asprda.Remove(aspr);
                                    ShipManager.ChangeShipStatus(ShipStatus.Ok, ShipManager.getByIMONum(spr.IMONum));
                                    log.Debug("ASPR " + aspr.Id + " REMOVED: Status: " + aspr.Status + " Barco:" + spr.IMONum);
                                    log.Debug("Requestor: " + spr.DataUserRequestor);
                                    log.Debug("Access-Request Type: " + spr.AccessType + "-" + spr.RequestType);
                                    continue;
                                }
                            }
                            //PERIODIC REPORT
                            else if (ShipPositionRequestHelper.IsPeriodicRequest(spr.RequestType) == true)
                            {
                                if (spr.RequestType == 2 && new int[] { 0, 15, 30, 45 }.Contains(mins) == false) //15 minute periodic rate
                                {
                                    continue;
                                }
                                if (spr.RequestType == 3 && new int[] { 0, 30 }.Contains(mins) == false) //30 minute periodic rate
                                {
                                    continue;
                                }
                                if (spr.RequestType == 4 && mins != 0) //1 hour periodic rate
                                {
                                    continue;
                                }
                                if (spr.RequestType == 5 && (new int[] { 0, 3, 6, 9, 12, 15, 18, 21 }.Contains(hour) == false || mins != 0)) //3 hour periodic rate
                                {
                                    continue;
                                }
                                if (spr.RequestType == 6 && (new int[] { 0, 6, 12, 18 }.Contains(hour) == false || mins != 0)) //6 hour periodic rate
                                {
                                    continue;
                                }
                                if (spr.RequestType == 10 && (new int[] { 0, 12 }.Contains(hour) == false || mins != 0)) //12 hour periodic rate
                                {
                                    continue;
                                }
                                if (spr.RequestType == 11 && (hour != 0 || mins != 0)) //24 hour periodic rate
                                {
                                    continue;
                                }

                                int minutes = ShipPositionRequestHelper.GetMinutes(spr.RequestType);
                                log.Debug("Procesando requerimiento periodico de " + minutes + " minutos");

                                //TimeSpan delta = TimeSpan.FromMinutes(minutes);
                                //if (DCDebug == "true")
                                //  delta = TimeSpan.FromSeconds(minutes);
                                //if (UtcNow >= aspr.LastTime.AddSeconds(delta.TotalSeconds))
                                //{

                                //log.Debug("se cumplio el periodo");
                                ShipPosition spos = spm.GetLastShipPosition(spr.IMONum);
                                if (spos != null)
                                {
                                    //La ultima posicion para el barco es mas nueva que la ultima que mande?
                                    if (spos.TimeStamp > aspr.LastTime)
                                    {
                                        CheckEntitlementAndSendReportOrReceipt(spr, spos);
                                        ShipManager.ChangeShipStatus(ShipStatus.Ok, ShipManager.getByIMONum(spr.IMONum));
                                    }
                                    else
                                    if (spos.TimeStamp < aspr.LastTime)
                                    {
                                        //Feature-add: +30' estados del Active Ship Position Report
                                        log.Info("No new position since last report");
                                        ReceiptManager.SendReceipt(spr.DataUserRequestor, spr.MessageId, DataCenterLogic.DataCenterTypesIDE.receiptCodeType.Item7,
                                                                   string.Format("No new position since last report"));
                                        return;
                                    }
                                    asprda.Update(aspr.Id, 1, spos.TimeStamp);
                                    log.Debug("ASPR " + aspr.Id + " UPDATED: Status: " + aspr.Status + " Barco:" + spr.IMONum);
                                    log.Debug("Requestor: " + spr.DataUserRequestor);
                                    log.Debug("Access-Request Type: " + spr.AccessType + "-" + spr.RequestType);
                                }
                                else
                                {
                                    log.Error("Hubo un problema al verificar la titulacion y enviar la respuesta");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error procesando ASPR", ex);
                    }
                } //foreach
            }
        }
示例#7
0
        /// <summary>
        /// Esta funcion es llamada cuando hay un mensaje nuevo en la cola de entrada
        /// </summary>
        /// <param name="sender">Object Sender</param>
        /// <param name="e">Async events</param>
        private void queue_PeekCompleted(object sender, PeekCompletedEventArgs e)
        {
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromMinutes(15)))
            {
                Message msg   = null;
                string  msgId = "NA";
                try
                {
                    msg = inputQueue.Receive(MessageQueueTransactionType.Automatic);

                    if (msg.Label == "receipt")
                    {
                        log.Debug("Se detecto receipt en queue...");
                        var receipt = (DataCenterLogic.DataCenterTypes.ReceiptType)(msg.Body);
                        msgId = receipt.MessageId;
                        var rman = new ReceiptManager();
                        rman.ProcessReceipt(receipt);
                    }
                    else
                    if (msg.Label == "pricingNotification")
                    {
                        log.Debug("Se detecto pricingNotification en queue...");
                        var pricingNotification = (PricingNotificationType)(msg.Body);
                        msgId = pricingNotification.MessageId;
                        var pman = new PricingManager();
                        pman.ProcessPricingNotification(pricingNotification);
                    }
                    else
                    if (msg.Label == "shipPositionReport")
                    {
                        log.Debug("Se detecto shipPositionReport en queue...");
                        var shipPositionReport = (DataCenterLogic.DataCenterTypes.ShipPositionReportType)(msg.Body);
                        msgId = shipPositionReport.MessageId;
                        var sprman = new ShipPositionReportManager();
                        sprman.ProcessShipPositionReport(shipPositionReport);
                    }
                    else
                    if (msg.Label == "pricingUpdate")
                    {
                        log.Debug("Se detecto pricingUpdate en queue...");
                        var pricingUpdate = (DataCenterLogic.DataCenterTypes.PricingUpdateType)(msg.Body);
                        msgId = pricingUpdate.MessageId;
                        var pman = new PricingManager();
                        pman.ProcessPricingUpdate(pricingUpdate);
                    }
                    else
                    if (msg.Label == "SARSURPICRequest")
                    {
                        log.Debug("Se detecto SARSURPICRequest en queue...");
                        var SARSURPICRequest = (DataCenterLogic.DataCenterTypes.SARSURPICType)(msg.Body);
                        msgId = SARSURPICRequest.MessageId;
                        var ssman = new SARSURPICManager();
                        ssman.ProcessSARSURPICRequest(SARSURPICRequest);
                    }
                    else
                    if (msg.Label == "ddpNotification")
                    {
                        log.Debug("Se detecto ddpNotification en queue...");
                        var ddpNotification = (DataCenterLogic.DataCenterTypes.DDPNotificationType)(msg.Body);
                        msgId = ddpNotification.MessageId;
                        var DDPman = new DDPManager();
                        DDPman.ProcessDDPNotification(ddpNotification);
                    }
                    else
                    if (msg.Label == "ddpUpdate")
                    {
                        log.Debug("Se detecto ddpUpdate en queue...");
                        var DDPman    = new DDPManager();
                        var ddpUpdate = (DataCenterTypes.DDPUpdateType)(msg.Body);
                        msgId = ddpUpdate.MessageId;
                        DDPman.ProcessDDPUpdate(ddpUpdate);
                    }
                    else
                    if (msg.Label == "shipPositionRequest")
                    {
                        log.Debug("Se detecto shipPositionRequest en queue...");
                        var shipPositionRequest = (DataCenterTypes.ShipPositionRequestType)(msg.Body);
                        msgId = shipPositionRequest.MessageId;
                        var sprm = new ShipPositionRequestManager();
                        sprm.ProcessShipPositionRequest(shipPositionRequest);
                    }
                    else
                    if (msg.Label == "systemStatus")
                    {
                        log.Debug("Se detecto systemStatus en queue...");
                        var systemStatus = (DataCenterTypes.SystemStatusType)(msg.Body);
                        msgId = systemStatus.MessageId;
                        var ssm = new SystemStatusManager();
                        ssm.ProcessSystemStatus(systemStatus);
                    }
                    else
                    if (msg.Label == "")
                    {
                        log.Debug("Se detecto mensaje del ASP en queue... tipo:");
                        var type = msg.Body.GetType().ToString();

                        switch (type)
                        {
                        case "Common.PositionMessage":
                        {
                            log.Debug("Position Message");
                            var aspPos = (Common.PositionMessage)(msg.Body);
                            var spm    = new ShipPositionManager();
                            spm.ProcessASPPosition(aspPos);
                            break;
                        }

                        case "Common.PollResponse":
                        {
                            log.Debug("PollResponse");
                            var aspPollResponse = (Common.PollResponse)(msg.Body);
                            var spm             = new ShipManager();
                            spm.ProcessPollResponse(aspPollResponse);
                            break;
                        }

                        case "Common.HeartBeatMessage":
                        {
                            log.Debug("HeartBeat");
                            var aspHb = (Common.HeartBeatMessage)(msg.Body);
                            var spm   = new SystemStatusManager();
                            spm.ProcessAspHeartBeat(aspHb);
                            break;
                        }

                        default:
                        {
                            break;
                        }
                        }
                    }
                    else
                    {
                        log.Error(string.Format("Mensaje no conocido en cola '{0}'", msg.Label));
                    }

                    scope.Complete();
                    wrong_count = 0;

                    //Dump message to disk
                    try
                    {
                        if (System.Configuration.ConfigurationManager.AppSettings["save_messages"] == "yes")
                        {
                            string folder = System.Configuration.ConfigurationManager.AppSettings["save_folder"];
                            if (folder == string.Empty)
                            {
                                folder = "c:\\msgs";
                            }
                            string fullpath = string.Format("{0}\\{1:yyyyMMdd}\\in", folder, DateTime.UtcNow);
                            Directory.CreateDirectory(fullpath);

                            string xmlstr = OutputMessageManager.messageToString(msg);
                            string lbl    = msg.Label;
                            if (lbl == "")
                            {
                                lbl = msg.Body.GetType().ToString();
                            }
                            File.WriteAllText(string.Format("{0}\\{1}-{2}.txt", fullpath, lbl, msgId), xmlstr);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Error intentando guardar mensaje de entrada en disco", ex);
                    }
                }
                catch (Exception ex)
                {
                    wrong_count++;
                    try
                    {
                        log.Error("Error handling message" + Environment.NewLine + Environment.NewLine + ex + Environment.NewLine + Environment.NewLine);
                    }
                    catch
                    {
                    }

                    //Poison messages
                    if (wrong_count > 3)
                    {
                        wrong_count = 0;
                        try
                        {
                            var serializer   = new System.Xml.Serialization.XmlSerializer(msg.Body.GetType());
                            var stringWriter = new System.IO.StringWriter();
                            serializer.Serialize(stringWriter, msg.Body);

                            scope.Complete();
                            log.Error("MSGDUMP: " + stringWriter.ToString());
                        }
                        catch (Exception ex2)
                        {
                            log.Error("UNABLE TO DUMP MESSAGE: " + ex.Message, ex2);
                        }
                    }
                }
            }

            inputQueue.BeginPeek();
        }