private async void ExecuteUploadVPCommand(object obj) { string vpbody = null; bool sendAck = false; string callbackEndpoint = string.Empty; var dlg = new NewSTMMessageDialog(); dlg.ViewModel.ShowAcknowledgement = true; dlg.ViewModel.ShowCallbackEndpoint = true; if (dlg.ShowDialog() == true) { var newMsg = new PublishedMessageContract { Message = dlg.ViewModel.StmMsg, //MessageID = dlg.ViewModel.Id }; sendAck = dlg.ViewModel.Acknowledgement; vpbody = newMsg.Message; callbackEndpoint = Uri.EscapeDataString(dlg.ViewModel.CallbackEndpoint ?? string.Empty); } if (!string.IsNullOrEmpty(vpbody)) { Busy = true; BusyContent = "Uploading voyageplan"; await Task.Factory.StartNew(() => { var visService = new VisService(); if (sendAck) { string myAck = ConfigurationManager.AppSettings.Get("VisPublicUrl").Replace("{database}", VisService.DbName); string endpointUri = SelectedService.EndpointUri; if (!string.IsNullOrEmpty(callbackEndpoint)) { endpointUri = WebRequestHelper.CombineUrl(endpointUri, string.Format("/voyagePlans?callbackEndpoint={0}", Uri.EscapeDataString(callbackEndpoint)) + string.Format("&deliveryAckEndPoint={0}", Uri.EscapeDataString(myAck))); } else { endpointUri = WebRequestHelper.CombineUrl(endpointUri, string.Format("/voyagePlans?deliveryAckEndPoint={0}", Uri.EscapeDataString(myAck ?? string.Empty))); } var result = visService.CallService(vpbody, endpointUri, "POST", "text/xml; charset=utf-8"); MessageBox.Show(result); } else { string endpointUri = WebRequestHelper.CombineUrl(SelectedService.EndpointUri, "/voyagePlans"); if (!string.IsNullOrEmpty(callbackEndpoint)) { endpointUri += string.Format("?callbackEndpoint={0}", Uri.EscapeDataString(callbackEndpoint)); } var result = visService.CallService(vpbody, endpointUri, "POST", "text/xml; charset=utf-8"); MessageBox.Show(result); } }); Busy = false; } }
private void SendToAmssService(string message, string dataId, string amssEndpoint, Identity identity) { var paramList = new List <KeyValuePair <string, string> >(); var p1 = new KeyValuePair <string, string>("dataId", dataId); paramList.Add(p1); p1 = new KeyValuePair <string, string>("amssEndpoint", amssEndpoint); paramList.Add(p1); var requestObj = new CallServiceRequestObj { Body = message, EndpointMethod = WebRequestHelper.CombineUrl(amssEndpoint, "/amss/state_update"), Headers = null, RequestType = "POST", }; try { var headers = new List <Header> { new Header("content-type", "application/xml") }; requestObj.Headers = headers; _logEventService.LogInfo(EventNumber.SPIS_amss_request, EventDataType.PCM, paramList, JsonConvert.SerializeObject(requestObj, Newtonsoft.Json.Formatting.Indented)); var client = new SSC.Internal.SccPrivateService(); var queueResult = client.CallService(requestObj); if (queueResult.StatusCode < 200 || queueResult.StatusCode >= 300) { throw new Exception("Unable to send state update. " + queueResult.StatusCode + " " + queueResult.Body); } _logEventService.LogSuccess(EventNumber.SPIS_amss_response, EventDataType.Other, paramList, JsonConvert.SerializeObject(queueResult, Newtonsoft.Json.Formatting.Indented)); } catch (Exception ex) { log.Error(ex.Message, ex); _logEventService.LogError(EventNumber.SPIS_amss_request, EventType.Error_internal, paramList, JsonConvert.SerializeObject(requestObj, Newtonsoft.Json.Formatting.Indented)); // Send notification var notification = new Interfaces.Notification(); notification.FromOrgName = identity.Name; notification.FromOrgId = identity.UID; notification.FromServiceId = InstanceContext.CallerServiceId; notification.NotificationType = EnumNotificationType.ERROR_MESSAGE; notification.Subject = "Unable to send message"; notification.Body = string.Format("Unable to send message with id {0} to identity {1}, {2}. {3}", dataId, identity.Name, identity.UID, ex.Message); notification.NotificationSource = EnumNotificationSource.SPIS; _notificationService.Notify(notification); } }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="dataId"></param> /// <param name="endpoint"></param> /// <param name="identity"></param> public void SendMessage(string message, string dataId, string endpoint, Identity identity) { var client = new SSC.Internal.SccPrivateService(); string msg = string.Format("Voyageplan with uvid {0} sent to subscriber {1}", dataId, identity.Name); //Add event logging var paramList = new List <KeyValuePair <string, string> >(); var param = new KeyValuePair <string, string>("Message", msg); paramList.Add(param); try { var result = client.CallService(new CallServiceRequestObj { Body = message, EndpointMethod = WebRequestHelper.CombineUrl(endpoint, "voyagePlans?uvid=" + dataId), Headers = new List <Header> { new Header("content-type", "text/xml; charset=utf-8") }, RequestType = "POST", }); if (result.StatusCode != 200) { throw new Exception(result.Body); } log.Info(msg); _logEventService.LogSuccess(EventNumber.VIS_publishMessage, EventDataType.RTZ, paramList, message); } catch (Exception ex) { log.Error(ex.Message, ex); //logg event _logEventService.LogError(EventNumber.VIS_publishMessage, EventType.Error_internal, paramList, ex.Message); // Send notification var notification = new Interfaces.Notification(); notification.FromOrgName = identity.Name; notification.FromOrgId = identity.UID; notification.FromServiceId = InstanceContext.CallerServiceId; notification.NotificationType = EnumNotificationType.ERROR_MESSAGE; notification.Subject = "Unable to send message to subscriber"; notification.Body = string.Format("Voyageplan with UVID {0} could not be sent to subscriber {1}, {2}", dataId, identity.Name, identity.UID); notification.NotificationSource = EnumNotificationSource.VIS; _notificationService.Notify(notification); } }
static void Main(string[] args) { try { log.Debug("============================================================================================"); log.Debug("Program PollingQueueWorker is starting"); log.Debug("============================================================================================"); //1. Loopa genom alla databaser var conString = ConfigurationManager.AppSettings["connectionString"]; log.Debug(string.Format("Trying to connect to database using connection string {0}.", conString)); using (var con = new SqlConnection(conString)) { con.Open(); log.Debug(string.Format("Successfully connected to {0}.", conString)); DataTable databases = con.GetSchema("Databases"); foreach (DataRow database in databases.Rows) { string databaseName = database.Field <String>("database_name"); log.Debug(string.Format("Database: {0}", databaseName)); InstanceContext.Instance = databaseName; if (databaseName == "master") { continue; } string conStringDb = conString + string.Format(";Initial Catalog={0}", databaseName); log.Debug(string.Format("Trying to connect to database using connection string {0}.", conStringDb)); using (var conDB = new SqlConnection(conStringDb)) { conDB.Open(); log.Debug(string.Format("Successfully connected to {0}.", conStringDb)); //2. Kolla om tabellen SpisSubscription finns if (TableExists(conDB, "SpisSubscription")) { log.Debug(string.Format("Loading instance settings for database {0}", databaseName)); // Load instance settings DataTable settings = LookUpTable("SpisInstanceSettings", conDB); if (settings.Rows.Count == 0) { continue; } InstanceContext.Password = settings.Rows[0]["Password"].ToString(); InstanceContext.ServiceId = settings.Rows[0]["ServiceId"].ToString(); InstanceContext.ServiceName = settings.Rows[0]["ServiceName"].ToString(); InstanceContext.StmModuleUrl = settings.Rows[0]["StmModuleUrl"].ToString(); var b = (byte[])settings.Rows[0]["ClientCertificate"]; var encryptionPassword = ConfigurationManager.AppSettings["EncryptionPassword"]; var cert = new X509Certificate2(b, Encryption.DecryptString(InstanceContext.Password, encryptionPassword)); InstanceContext.ClientCertificate = cert; Console.WriteLine("Instance: " + InstanceContext.ServiceName); log.Debug(string.Format("Successfully loaded instance settings {0} for database {1}.", InstanceContext.ServiceName, databaseName)); string sqlQuery = "SELECT * FROM SpisSubscription"; SqlCommand cmd = new SqlCommand(sqlQuery, conDB); log.Debug(string.Format("Trying to execute sql command {0} for database {1}.", sqlQuery, databaseName)); try { using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { log.Debug(string.Format("Successfully executed sql command. Entering loop for reading each row.")); //4. För varje post while (reader.Read()) { string queueEndpoint = reader["MbEndpoint"].ToString(); string queueId = reader["QueueId"].ToString(); log.Debug(string.Format("Data reader result for queueEndpoint = {0} and queueId = {1}", queueEndpoint, queueId)); //4a. Är kön skapad? if (string.IsNullOrEmpty(queueId)) { //Skapa kö log.Debug("Queue did not exist, creating queue."); queueId = CreateQueue(queueEndpoint, settings); } string endPoint = WebRequestHelper.CombineUrl(queueEndpoint, string.Format("/mb/mqs/{0}", queueId)); log.Debug(string.Format("Polling queue by calling SSC Callservice with endpoint = {0}.", endPoint)); //4b. Gör ett anrop till SSC CallService var queueClient = new SSC.Internal.SccPrivateService(); try { var queueResult = queueClient.CallService(new CallServiceRequestObj { Body = null, EndpointMethod = endPoint, Headers = null, RequestType = "GET", }); Console.WriteLine("Polling queue, http result: " + queueResult.StatusCode); log.Debug("Polling queue, http result: " + queueResult.StatusCode); //4c. Lagra respons i UploadedMessage if (queueResult.StatusCode == 200) { var spisUrl = ConfigurationManager.AppSettings["spisUrl"]; spisUrl = spisUrl.Replace("{instance}", databaseName); log.Debug(string.Format("Store response in UploadedMessage table through public api endpoint {0}", spisUrl)); var xml = new XmlDocument(); xml.LoadXml(queueResult.Body); XmlNodeList messages = xml.SelectNodes("//*[local-name()='portCallMessage']"); Console.WriteLine(messages.Count + " messages fetched from queue"); for (int i = 0; i < messages.Count; i++) { if (messages[i].OuterXml.Length > 0) { WebHeaderCollection h = new WebHeaderCollection(); h.Add("content-type", "text/xml; charset=utf-8"); var uploadResponse = WebRequestHelper.Post(spisUrl, messages[i].OuterXml, h, true); if (uploadResponse.HttpStatusCode != HttpStatusCode.OK) { log.Debug("Failed to store message in SPIS. " + uploadResponse.Body); } } } Console.WriteLine(messages.Count + " messages sent to SPIS"); log.Debug(string.Format("{0} messages sent to SPIS.", messages.Count)); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); log.Error(string.Format("Catching exception for database {0}, error: {1}", databaseName, ex.ToString())); } } } } } catch (Exception ex) { log.Error("Exception: " + ex.ToString()); } } else { log.Debug(string.Format("Table SpisSubscription did not exist in database {0}", databaseName)); } } } } log.Debug(Environment.NewLine); log.Debug("********************************************************************************************"); log.Debug("End Program PollingQueueWorker"); log.Debug("********************************************************************************************"); log.Debug(Environment.NewLine); } catch (Exception ex) { log.Error(ex.Message, ex); } }
private static string CreateQueue(string queueEndpoint, DataTable settings) { string queueId = string.Empty; var IMO = settings.Rows[0]["IMO"].ToString(); var MMSI = settings.Rows[0]["MMSI"].ToString(); string vesselId = ConfigurationManager.AppSettings["vesselId"]; if (!string.IsNullOrEmpty(IMO)) { vesselId += "IMO:" + IMO; } else if (!string.IsNullOrEmpty(MMSI)) { vesselId += "MMSI:" + MMSI; } else { Console.WriteLine("Failed to find vessel identifier."); return(string.Empty); } var queueFilter = new List <QueueFilter> { new QueueFilter { type = "VESSEL", element = vesselId } //new QueueFilter //{ // type="TIME_TYPE", element="ESTIMATED" //}, //new QueueFilter //{ // type="TIME_TYPE", element="RECOMMENDED" //} }; var filter = JsonConvert.SerializeObject(queueFilter); var client = new SSC.Internal.SccPrivateService(); try { var headers = new List <Header> { new Header("content-type", "application/json; charset=utf-8") }; var queueResult = client.CallService(new CallServiceRequestObj { Body = filter, EndpointMethod = WebRequestHelper.CombineUrl(queueEndpoint, "/mb/mqs"), Headers = headers, RequestType = "POST", }); if (queueResult.StatusCode == 200 || queueResult.StatusCode == 201) { queueId = queueResult.Body; } else { throw new Exception("Unable to create queue. " + queueResult.StatusCode + " " + queueResult.Body); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); throw; } return(queueId); }
/// <summary> /// /// </summary> /// <param name="messages"></param> public void SendAck(IList <UploadedMessage> messages) { var client = new STM.SSC.Internal.SccPrivateService(); foreach (var message in messages) { try { if (message.DeliveryAckReqested && !message.AckDelivered) { var ackObject = new DeliveryAck { AckResult = "OK", FromId = message.FromOrg.UID, FromName = message.FromOrg.Name, Id = Guid.NewGuid().ToString(), ReferenceId = message.MessageID, TimeOfDelivery = DateTime.UtcNow, ToId = InstanceContext.ServiceId, ToName = InstanceContext.ServiceName }; var response = client.CallService(new CallServiceRequestObj { Body = JsonConvert.SerializeObject(ackObject), EndpointMethod = WebRequestHelper.CombineUrl(message.DeliveryAckEndpoint, "acknowledgement"), Headers = new List <Header> { new Header("content-type", "application/json; charset=utf-8") }, RequestType = "POST", }); if (response.StatusCode != 200) { log.Debug("Error from call service " + response.Body); throw new Exception("Call service returned " + response.StatusCode); } //Add logg event switch (message.MessageType.Name) { case "RTZ": _logEventService.LogSuccess(EventNumber.VIS_sendAcknowledgement, EventDataType.RTZ, null, JsonConvert.SerializeObject(ackObject, Formatting.Indented)); break; case "TXT": _logEventService.LogSuccess(EventNumber.VIS_sendAcknowledgement, EventDataType.TXT, null, JsonConvert.SerializeObject(ackObject, Formatting.Indented)); break; case "S124": _logEventService.LogSuccess(EventNumber.VIS_sendAcknowledgement, EventDataType.S124, null, JsonConvert.SerializeObject(ackObject, Formatting.Indented)); break; case "PCM": _logEventService.LogSuccess(EventNumber.VIS_sendAcknowledgement, EventDataType.PCM, null, JsonConvert.SerializeObject(ackObject, Formatting.Indented)); break; } } } catch (Exception ex) { log.Error(ex.Message, ex); // Send notification var notification = new Internal.Interfaces.Notification(); notification.FromOrgName = message.FromOrg.Name; notification.FromOrgId = message.FromOrg.UID; notification.FromServiceId = message.FromServiceId; notification.NotificationType = EnumNotificationType.ERROR_MESSAGE; notification.Subject = "Unable to send acknowledgement"; notification.Body = string.Format("Acknowledgement for voyageplan with UVID {0} could not be sent to {1}, {2}", message.MessageID, message.FromOrg.Name, message.FromOrg.UID); notification.NotificationSource = EnumNotificationSource.VIS; _notificationService.Notify(notification); } } }
private string SetupQueue(string message, string dataId, string mbEndpoint, Identity identity) { string result = null; string vesselId = ConfigurationManager.AppSettings["vesselId"]; if (!string.IsNullOrEmpty(InstanceContext.IMO)) { vesselId += "IMO:" + InstanceContext.IMO; } else if (!string.IsNullOrEmpty(InstanceContext.MMSI)) { vesselId += "MMSI:" + InstanceContext.MMSI; } else { throw new Exception("Failed to find vessel identifier."); } try { // Setup filter var queueFilter = new List <QueueFilter> { new QueueFilter { type = "VESSEL", element = vesselId } }; var headers = new List <Header> { new Header("content-type", "application/json; charset=utf-8") }; var client = new SSC.Internal.SccPrivateService(); var queueResult = client.CallService(new CallServiceRequestObj { Body = JsonConvert.SerializeObject(queueFilter), EndpointMethod = WebRequestHelper.CombineUrl(mbEndpoint, "/mb/mqs"), Headers = headers, RequestType = "POST", }); if (queueResult.StatusCode == 200 || queueResult.StatusCode == 201) { result = queueResult.Body; } else { throw new Exception("Unable to create queue. " + queueResult.StatusCode + " " + queueResult.Body); } } catch (Exception ex) { log.Error(ex.Message, ex); // Send notification var notification = new Interfaces.Notification(); notification.FromOrgName = identity.Name; notification.FromOrgId = identity.UID; notification.FromServiceId = InstanceContext.CallerServiceId; notification.NotificationType = EnumNotificationType.ERROR_MESSAGE; notification.NotificationSource = EnumNotificationSource.SPIS; notification.Subject = "Unable to send set up message broker queue"; notification.Body = string.Format("Unable to create queue for message with id {0}, identity {1}, {2}", dataId, identity.Name, identity.UID); _notificationService.Notify(notification); } return(result); }