public FindIdentitiesResponseObj FindIdentities()
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            _logEventService.LogInfo(EventNumber.VIS_consumeService, EventDataType.None, null, null);

            try
            {
                var responsObjects = _sscService.FindIdentities();

                _logEventService.LogSuccess(EventNumber.VIS_consumeService, EventDataType.Other, null, JsonConvert.SerializeObject(responsObjects, Formatting.Indented));

                //set last interaction time
                var conInfo = _connectionInformationService.Get().FirstOrDefault();
                if (conInfo == null)
                {
                    _connectionInformationService.Insert(new ConnectionInformation {
                        LastInteraction = DateTime.UtcNow
                    });
                }
                else
                {
                    conInfo.LastInteraction = DateTime.UtcNow;
                    _connectionInformationService.Update(conInfo);
                }
                _context.SaveChanges();

                return(responsObjects);
            }
            catch (HttpResponseException ex)
            {
                _logEventService.LogError(EventNumber.VIS_consumeService, EventType.Error_internal,
                                          null, JsonConvert.SerializeObject(ex.Response, Formatting.Indented));

                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);

                string msg = "VIS internal server error. " + ex.Message;

                _logEventService.LogError(EventNumber.VIS_consumeService, EventType.Error_internal,
                                          null, ex.Message);

                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
        private void SetLastInteractionTime()
        {
            var conInfo = _connectionInformationService.Get().FirstOrDefault();

            if (conInfo == null)
            {
                _connectionInformationService.Insert(new ConnectionInformation {
                    LastInteraction = DateTime.UtcNow
                });
            }
            else
            {
                conInfo.LastInteraction = DateTime.UtcNow;
                _connectionInformationService.Update(conInfo);
            }
        }
        public CallServiceResponseObj CallService([FromBody] CallServiceRequestObj callServiceObj)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            var requestString = JsonConvert.SerializeObject(callServiceObj, Formatting.Indented);

            _logEventService.LogInfo(EventNumber.VIS_consumeService, EventDataType.Unknown, null, requestString);
            try
            {
                var result         = _sscService.CallService(callServiceObj);
                var responseString = JsonConvert.SerializeObject(result, Formatting.Indented);
                _logEventService.LogSuccess(EventNumber.VIS_consumeService, EventDataType.Unknown, null, responseString);

                //Set last interaction time
                var conInfo = _connectionInformationService.Get().FirstOrDefault();
                if (conInfo == null)
                {
                    _connectionInformationService.Insert(new ConnectionInformation {
                        LastInteraction = DateTime.UtcNow
                    });
                }
                else
                {
                    conInfo.LastInteraction = DateTime.UtcNow;
                    _connectionInformationService.Update(conInfo);
                }
                _context.SaveChanges();

                return(result);
            }
            catch (HttpResponseException ex)
            {
                var errorString = JsonConvert.SerializeObject(ex.Response, Formatting.Indented);
                _logEventService.LogError(EventNumber.VIS_consumeService, EventType.Error_internal,
                                          null, errorString);
                throw;
            }
            catch (Exception ex)
            {
                string msg = "VIS internal server error. " + ex.Message;

                _logEventService.LogError(EventNumber.VIS_consumeService, EventType.Error_internal,
                                          null, ex.Message);

                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
        public virtual Models.GetVoyagePlanResponse GetVoyagePlans([FromUri] string uvid = null, [FromUri] string routeStatus = null)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            GetVoyagePlanResponse result;

            var request = Request;
            var headers = request.Headers;

            var paramList = new List <KeyValuePair <string, string> >();
            var param     = new KeyValuePair <string, string>("uvid", uvid);

            paramList.Add(param);
            param = new KeyValuePair <string, string>("routeStatus", routeStatus);
            paramList.Add(param);

            // Get identity ether from internal id talbe or from id registry
            var identity = _identityService.GetCallerIdentity();

            // Get the calling serviceId
            if (string.IsNullOrEmpty(InstanceContext.CallerServiceId))
            {
                var msg = "Missing 'incomingServiceId'";
                log.Debug(msg);
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, msg);
            }
            log.Debug("incomingServiceId: " + InstanceContext.CallerServiceId);

            // Get the calling organisation identity
            if (string.IsNullOrEmpty(InstanceContext.CallerOrgId))
            {
                throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Missing organizationId in request");
            }
            log.Debug("incomingOrganizationId: " + InstanceContext.CallerServiceId);

            try
            {
                _logEventService.LogInfo(EventNumber.VIS_getVoyagePlan_request, EventDataType.None, paramList, null);

                if (string.IsNullOrEmpty(uvid) && string.IsNullOrEmpty(routeStatus))
                {
                    result = GetPublishedVoyagePlans(identity, paramList);
                }

                else if (!string.IsNullOrEmpty(uvid) && string.IsNullOrEmpty(routeStatus))
                {
                    if (!FormatValidation.IsValidUvid(uvid))
                    {
                        throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Invalid UVID format");
                    }
                    result = GetPublishedVoyagePlans(identity, paramList, uvid);
                }

                else if (string.IsNullOrEmpty(uvid) && !string.IsNullOrEmpty(routeStatus))
                {
                    int routeStatusInt = -1;
                    if (int.TryParse(routeStatus, out routeStatusInt))
                    {
                        if (routeStatusInt <= 0 || routeStatusInt > 7)
                        {
                            throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Argument {0} out of range.", routeStatus));
                        }
                    }
                    else
                    {
                        throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Argument {0} format unknown.", routeStatus));
                    }
                    result = GetPublishedVoyagePlans(identity, paramList, null, routeStatusInt);
                }
                else
                {
                    if (!FormatValidation.IsValidUvid(uvid))
                    {
                        throw CreateHttpResponseException(HttpStatusCode.BadRequest, "Invalid UVID format");
                    }

                    int routeStatusInt = -1;
                    if (int.TryParse(routeStatus, out routeStatusInt))
                    {
                        if (routeStatusInt <= 0 || routeStatusInt > 8)
                        {
                            throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Argument {0} out of range.", routeStatus));
                        }
                    }
                    else
                    {
                        throw CreateHttpResponseException(HttpStatusCode.BadRequest, string.Format("Argument {0} format unknown.", routeStatus));
                    }
                    result = GetPublishedVoyagePlans(identity, paramList, uvid, routeStatusInt);
                }
                _logEventService.LogSuccess(EventNumber.VIS_getVoyagePlan_response, EventDataType.Other,
                                            paramList, JsonConvert.SerializeObject(result, Formatting.Indented));

                var conStatus = _connectionInformationService.Get().FirstOrDefault();
                if (conStatus != null && conStatus.LastInteraction != null)
                {
                    result.LastInteractionTime = conStatus.LastInteraction;
                    result.LastInteractionTime = DateTime.SpecifyKind(result.LastInteractionTime.Value, DateTimeKind.Utc);
                }

                return(result);
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);
                _logEventService.LogError(EventNumber.VIS_getVoyagePlan_request, EventType.Error_internal, paramList,
                                          JsonConvert.SerializeObject(ex.Response, Formatting.Indented));
                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                _logEventService.LogError(EventNumber.VIS_getVoyagePlan_request, EventType.Error_internal, paramList, ex.Message);

                string msg = "VIS internal server error. " + ex.Message;
                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
        public MessageEnvelope GetMessage(string limitQuery = null)
        {
            log.Info("Incoming request to " + GetCurrentMethod());

            int limitNumberOfMessages = 0;

            if (int.TryParse(limitQuery, out limitNumberOfMessages))
            {
                log.Info(string.Format("LimitQuery parsed successfully to {0}.", limitNumberOfMessages));
            }

            try
            {
                var result = new MessageEnvelope();
                result.Messages = new List <Message>();
                var uploadedMessages = new List <UploadedMessage>();
                var mTypes           = _messageTypeService.Get(m => m.Name != "PCM").ToList();

                if (limitNumberOfMessages > 0)
                {
                    uploadedMessages = _uploadedMessageService.GetMessagesByLimitNumber(limitNumberOfMessages, mTypes);
                }
                else
                {
                    uploadedMessages = _uploadedMessageService.GetAllUnFetchedMessages(mTypes);
                }

                foreach (var uploadedMessage in uploadedMessages)
                {
                    uploadedMessage.FetchedByShip = true;
                    uploadedMessage.FetchTime     = DateTime.UtcNow;
                    _uploadedMessageService.Update(uploadedMessage);

                    var messageToAdd = new Message();
                    messageToAdd.Id            = uploadedMessage.MessageID;
                    messageToAdd.FromOrgId     = uploadedMessage.FromOrg.UID;
                    messageToAdd.FromOrgName   = uploadedMessage.FromOrg.Name;
                    messageToAdd.FromServiceId = uploadedMessage.FromServiceId;
                    messageToAdd.MessageType   = uploadedMessage.MessageType.Name;
                    messageToAdd.ReceivedAt    = uploadedMessage.ReceiveTime;

                    if (messageToAdd.ReceivedAt.HasValue)
                    {
                        messageToAdd.ReceivedAt = DateTime.SpecifyKind(messageToAdd.ReceivedAt.Value, DateTimeKind.Utc);
                    }

                    var messageBody = Serialization.ByteArrayToString(uploadedMessage.Message);
                    messageToAdd.StmMessage       = new StmMessage(messageBody);
                    messageToAdd.CallbackEndpoint = uploadedMessage.CallbackEndpoint;

                    result.Messages.Add(messageToAdd);
                }
                _context.SaveChanges();

                result.NumberOfMessages          = uploadedMessages.Count;
                result.RemainingNumberOfMessages = _uploadedMessageService.GetNumberOfRemainingMessages(mTypes);

                _uploadedMessageService.SendAck(uploadedMessages);

                //set last interaction time
                var conInfo = _connectionInformationService.Get().FirstOrDefault();
                if (conInfo == null)
                {
                    _connectionInformationService.Insert(new ConnectionInformation {
                        LastInteraction = DateTime.UtcNow
                    });
                }
                else
                {
                    conInfo.LastInteraction = DateTime.UtcNow;
                    _connectionInformationService.Update(conInfo);
                }

                _context.SaveChanges();
                return(result);
            }
            catch (HttpResponseException ex)
            {
                log.Error(ex.Message, ex);

                throw;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);

                string msg = "VIS internal server error. " + ex.Message;
                throw CreateHttpResponseException(HttpStatusCode.InternalServerError, msg);
            }
        }
        public List <Notification> GetNotification()
        {
            // log.Info("Incoming request to " + GetCurrentMethod());

            List <Notification> result = new List <Notification>();

            try
            {
                var notifications = _notificationService.Get(x => x.FetchedByShip == false && x.NotificationSource == Common.DataAccess.Entities.NotificationSource.VIS);

                if (notifications != null)
                {
                    foreach (var notification in notifications)
                    {
                        var receivedAt            = DateTime.SpecifyKind(notification.ReceivedAt, DateTimeKind.Utc);
                        var NotificationCreatedAt = DateTime.SpecifyKind(notification.NotificationCreatedAt, DateTimeKind.Utc);

                        result.Add(new Notification
                        {
                            Body                  = notification.Body,
                            FromOrgId             = notification.FromOrgId,
                            FromOrgName           = notification.FromOrgName,
                            FromServiceId         = notification.FromServiceId,
                            MessageWaiting        = 0,
                            NotificationCreatedAt = NotificationCreatedAt,
                            NotificationType      = (EnumNotificationType)notification.NotificationType,
                            ReceivedAt            = receivedAt,

                            Subject            = notification.Subject,
                            NotificationSource = EnumNotificationSource.VIS
                        });

                        notification.FetchedByShip = true;
                        notification.FetchTime     = DateTime.UtcNow;
                        _notificationService.Update(notification);
                    }
                }

                //set last interaction time
                var conInfo = _connectionInformationService.Get().FirstOrDefault();
                if (conInfo == null)
                {
                    _connectionInformationService.Insert(new STM.Common.DataAccess.Entities.ConnectionInformation
                    {
                        LastInteraction = DateTime.UtcNow
                    });
                }
                else
                {
                    conInfo.LastInteraction = DateTime.UtcNow;
                    _connectionInformationService.Update(conInfo);
                }

                _context.SaveChanges();
                return(result);
            }
            catch (Exception ex)
            {
                logger.Debug(ex);
                throw new HttpResponseException(HttpStatusCode.InternalServerError);
            }
        }