private async Task <InvokeResult> SendUDPMessage(MessageTransmissionPlan messageTemplate)
        {
            var buffer = GetMessageBytes(messageTemplate);
            await _tcpClient.WriteAsync(buffer, 0, buffer.Length);

            return(InvokeResult.Success);
        }
        private async Task <InvokeResult> SendIoTHubMessage(MessageTransmissionPlan plan)
        {
            var messageTemplate = plan.Message.Value;

            if (_azureIoTHubClient == null)
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Azure IoT Hub is null, could not send message");

                return(InvokeResult.FromError("Azure IoT Hub is null, could not send message"));
            }

            if (!_isConnected)
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Azure IoT Hub is not connected, could not send message");

                return(InvokeResult.FromError("Azure IoT Hub is not connected, could not send message"));
            }

            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending message to Azure IoT Hub {_simulator.DefaultEndPoint}");

            var textPayload = ReplaceTokens(_instance, plan, messageTemplate.TextPayload);
            var msg         = new Microsoft.Azure.Devices.Client.Message(GetMessageBytes(plan));
            await _azureIoTHubClient.SendEventAsync(msg);

            ReceivedContent = $"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessagePublished}";

            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, ReceivedContent);

            return(InvokeResult.Success);
        }
Esempio n. 3
0
        public async Task CreateRESTSimulator()
        {
            var sim = GetSimulator(TransportTypes.RestHttp);

            sim.Simulator.Value.Anonymous = true;

            var runtime = new SimulatorRuntime(_runtimeServices.Object, _notifPublisher, _adminLogger, sim);

            var msg = new MessageTemplate()
            {
                Transport   = Core.Models.EntityHeader <TransportTypes> .Create(TransportTypes.RestHttp),
                PayloadType = Core.Models.EntityHeader <PaylodTypes> .Create(PaylodTypes.String),
                TextPayload = "abc123",
                EndPoint    = "www.software-logistics.com",
                Port        = 80,
                HttpVerb    = "GET"
            };

            var plan = new MessageTransmissionPlan()
            {
                Message = Core.Models.EntityHeader <MessageTemplate> .Create(msg)
            };


            var result = await runtime.SendAsync(plan);

            AssertSuccess(result);
        }
        private String ReplaceTokens(SimulatorInstance instance, MessageTransmissionPlan plan, String input)
        {
            var msg = plan.Message.Value;

            if (String.IsNullOrEmpty(input))
            {
                return(String.Empty);
            }

            foreach (var attr in msg.DynamicAttributes)
            {
                var instanceValue = plan.Values.Where(atr => atr.Attribute.Id == attr.Id).FirstOrDefault();
                if (instanceValue == null || String.IsNullOrEmpty(instanceValue.Value))
                {
                    input = input.Replace($"~{attr.Key}~", attr.DefaultValue);
                }
                else
                {
                    if (instanceValue.Value.StartsWith("~random-int"))
                    {
                        input = RandomizeInt(input, instanceValue.Value, attr.Key);
                    }
                    else if (instanceValue.Value.StartsWith("~random-float"))
                    {
                        input = RandomizeFloat(input, instanceValue.Value, attr.Key);
                    }
                    else
                    {
                        input = input.Replace($"~{attr.Key}~", instanceValue.Value);
                    }
                }
            }

            input = input.Replace($"~deviceid~", String.IsNullOrEmpty(instance.DeviceId) ? _simulator.DeviceId : instance.DeviceId);
            input = input.Replace($"~datetime~", DateTime.Now.ToString());
            input = input.Replace($"~username~", _simulator.UserName);
            input = input.Replace($"~password~", _simulator.Password);
            input = input.Replace($"~accesskey~", _simulator.AccessKey);
            input = input.Replace($"~password~", _simulator.Password);
            input = input.Replace($"~datetimeiso8601~", DateTime.UtcNow.ToJSONString());

            input = RandomizeInt(input, input);
            input = RandomizeFloat(input, input);


            if (msg.AppendCR)
            {
                input += "\r";
            }

            if (msg.AppendLF)
            {
                input += "\n";
            }

            return(input);
        }
Esempio n. 5
0
        private async Task <InvokeResult> SendMQTTMessage(MessageTransmissionPlan plan)
        {
            var messageTemplate = plan.Message.Value;

            if (_mqttClient == null)
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "MQTT Client is null, could not send message");

                return(InvokeResult.FromError("MQTT Client is null, could not send message"));
            }

            if (!_mqttClient.IsConnected)
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "MQTT Client is not connected, reconnecting.");

                var connectResult = await _mqttClient.ConnectAsync();

                if (connectResult.Result == ConnAck.Accepted)
                {
                    await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "MQTT Client is not connected, reconnected.");
                }
                else
                {
                    await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "MQTT Client is not connected, could not connect, did not send message");

                    return(InvokeResult.FromError("MQTT Client is not is not connected, could not send message"));
                }
            }

            var qos = QOS.QOS0;

            if (!EntityHeader.IsNullOrEmpty(messageTemplate.QualityOfServiceLevel))
            {
                switch (messageTemplate.QualityOfServiceLevel.Value)
                {
                case QualityOfServiceLevels.QOS1: qos = QOS.QOS1; break;

                case QualityOfServiceLevels.QOS2: qos = QOS.QOS2; break;
                }
            }

            if (messageTemplate.PayloadType.Id == MessageTemplate.PayloadTypes_GeoPath)
            {
                return(await SendMQTTGeoMessage(plan));
            }


            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending message to MQTT Server {_simulator.DefaultEndPoint} with topic {messageTemplate.Topic}");

            await _mqttClient.PublishAsync(ReplaceTokens(_instance, plan, messageTemplate.Topic), GetMessageBytes(plan), qos, messageTemplate.RetainFlag);

            ReceivedContent = $"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessagePublished}";

            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, ReceivedContent);

            return(InvokeResult.Success);
        }
        public async Task <InvokeResult <string> > SendAsync(MessageTransmissionPlan plan)
        {
            IsBusy = true;

            _pointIndex = 0;

            var messageTemplate = plan.Message.Value;

            try
            {
                InvokeResult res = InvokeResult.FromError("");

                switch (messageTemplate.Transport.Value)
                {
                case TransportTypes.TCP: res = await SendTCPMessage(plan); break;

                case TransportTypes.UDP: res = await SendUDPMessage(plan); break;

                case TransportTypes.AzureServiceBus: res = await SendServiceBusMessage(plan); break;

                case TransportTypes.AzureEventHub: res = await SendEventHubMessage(plan); break;

                case TransportTypes.AzureIoTHub: res = await SendIoTHubMessage(plan); break;

                case TransportTypes.MQTT: res = await SendMQTTMessage(plan); break;

                case TransportTypes.RestHttps:
                case TransportTypes.RestHttp: res = await SendRESTRequestAsync(plan); break;
                }

                if (res.Successful)
                {
                    var msg = BuildRequestContent(plan);
                    return(InvokeResult <string> .Create(msg));
                }
                else
                {
                    return(InvokeResult <string> .FromInvokeResult(res));
                }
            }
            catch (Exception ex)
            {
                _adminLogger.AddException("Send", ex);

                ReceivedContent = ex.Message;

                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending {messageTemplate.Transport.Value} message {ex.Message}.");

                return(InvokeResult <string> .FromException("SendAsync", ex));
            }
            finally
            {
                IsBusy = false;
            }
        }
Esempio n. 7
0
        public async Task CreatAzureIoTHubSimulator()
        {
            var azIoTAccessKey = Environment.GetEnvironmentVariable("TEST_AZ_IOT_LISTENER_KEY");

            Assert.IsFalse(String.IsNullOrEmpty(azIoTAccessKey), "TEST_AZ_IOT_LISTENER_KEY");

            var azIoTAccountId = Environment.GetEnvironmentVariable("TEST_AZ_IOT_LISTENER_ACCOUNT_ID");

            Assert.IsFalse(String.IsNullOrEmpty(azIoTAccountId), "TEST_AZ_IOT_LISTENER_ACCOUNT_ID");

            var azIoTAccountPolicyName = Environment.GetEnvironmentVariable("TEST_AZ_IOT_LISTENER_POLICY_NAME");

            Assert.IsFalse(String.IsNullOrEmpty(azIoTAccountPolicyName), "TEST_AZ_IOT_LISTENER_POLICY_NAME");

            var ehCompatName = Environment.GetEnvironmentVariable("TEST_AZ_IOT_LISTENER_EH_COMPAT_NAME");

            Assert.IsFalse(String.IsNullOrEmpty(ehCompatName), "TEST_AZ_IOT_LISTENER_EH_COMPAT_NAME");

            var ehCompatEndPoint = Environment.GetEnvironmentVariable("TEST_AZ_IOT_LISTENER_EH_COMPAT_ENDPOINT");

            Assert.IsFalse(String.IsNullOrEmpty(ehCompatEndPoint), "TEST_AZ_IOT_LISTENER_EH_COMPAT_ENDPOINT");

            var azDeviceId = Environment.GetEnvironmentVariable("TEST_AZ_IOT_LISTENER_DEVICEID");

            Assert.IsFalse(String.IsNullOrEmpty(azDeviceId), "Missing TEST_AZ_IOT_LISTENER_DEVICEID");

            var sim = GetSimulator(TransportTypes.AzureIoTHub);

            sim.Simulator.Value.AccessKey     = azIoTAccessKey;
            sim.Simulator.Value.AccessKeyName = azIoTAccountPolicyName;

            var msg = new MessageTemplate()
            {
                Transport   = Core.Models.EntityHeader <TransportTypes> .Create(TransportTypes.RestHttp),
                PayloadType = Core.Models.EntityHeader <PaylodTypes> .Create(PaylodTypes.String),
                TextPayload = "abc123",
                EndPoint    = "www.software-logistics.com",
                Port        = 80,
                HttpVerb    = "GET"
            };


            var plan = new MessageTransmissionPlan()
            {
                Message = Core.Models.EntityHeader <MessageTemplate> .Create(msg)
            };

            var runtime = new SimulatorRuntime(_runtimeServices.Object, _notifPublisher, _adminLogger, sim);

            var result = await runtime.SendAsync(plan);

            AssertSuccess(result);
        }
Esempio n. 8
0
        public async Task CreateMQTTSimulator()
        {
            var testHostName = Environment.GetEnvironmentVariable("TEST_MQTT_HOST_NAME");

            Assert.IsFalse(String.IsNullOrEmpty(testHostName), "Missing environment variable TEST_MQTT_HOST_NAME");

            var testUserName = Environment.GetEnvironmentVariable("TEST_MQTT_USER_NAME");

            Assert.IsFalse(String.IsNullOrEmpty(testUserName), "Missing environment variable TEST_MQTT_USER_NAME");

            var testPwd = Environment.GetEnvironmentVariable("TEST_MQTT_PASSWORD");

            Assert.IsFalse(String.IsNullOrEmpty(testPwd), "Missing environment variable TEST_MQTT_PASSWORD");

            var sim = GetSimulator(TransportTypes.MQTT);

            sim.Simulator.Value.DefaultEndPoint = testHostName;
            sim.Simulator.Value.DefaultPort     = 1883;
            sim.Simulator.Value.UserName        = testUserName;
            sim.Simulator.Value.Password        = testPwd;

            var msg = new MessageTemplate()
            {
                PayloadType = Core.Models.EntityHeader <PaylodTypes> .Create(PaylodTypes.String),
                Topic       = "sendit",
                TextPayload = "abc123",
            };

            var runtime = new SimulatorRuntime(_runtimeServices.Object, _notifPublisher, _adminLogger, sim);

            var connectResult = await runtime.ConnectAsync();

            AssertSuccess(connectResult);

            var plan = new MessageTransmissionPlan()
            {
                Message = Core.Models.EntityHeader <MessageTemplate> .Create(msg)
            };

            var result = await runtime.SendAsync(plan);

            AssertSuccess(result);

            var disconnectResult = await runtime.DisconnectAsync();

            AssertSuccess(disconnectResult);
        }
        private async Task <InvokeResult> SendEventHubMessage(MessageTransmissionPlan messageTemplate)
        {
            if (String.IsNullOrEmpty(_simulator.DefaultEndPoint))
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Default End Point is Missing to send to Event Hub.");

                return(InvokeResult.FromError("Default End Point is Missing to send to Event Hub."));
            }

            if (String.IsNullOrEmpty(_simulator.AccessKeyName))
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Access Key Name is Missing to send to Event Hub.");

                return(InvokeResult.FromError("Access Key Name is Missing to send to Event Hub."));
            }

            if (String.IsNullOrEmpty(_simulator.HubName))
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Hub Name is Missing to send to Event Hub.");

                return(InvokeResult.FromError("Hub Name is Missing to send to Event Hub."));
            }

            if (String.IsNullOrEmpty(_simulator.AccessKey))
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Access Key is Missing to send to Event Hub.");

                return(InvokeResult.FromError("Access Key is Missing to send to Event Hub."));
            }

            var connectionString        = $"Endpoint=sb://{_simulator.DefaultEndPoint}.servicebus.windows.net/;SharedAccessKeyName={_simulator.AccessKeyName};SharedAccessKey={_simulator.AccessKey}";
            var connectionStringBuilder = new EventHubsConnectionStringBuilder(connectionString)
            {
                EntityPath = _simulator.HubName
            };

            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending message to Azure Event Hub {_simulator.DefaultEndPoint}");

            var client = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
            await client.SendAsync(new EventData(GetMessageBytes(messageTemplate)));

            ReceivedContent = $"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessagePublished}";

            return(InvokeResult.Success);
        }
        public byte[] GetMessageBytes(MessageTransmissionPlan plan)
        {
            var messageTemplate = plan.Message.Value;

            if (EntityHeader.IsNullOrEmpty(messageTemplate.PayloadType) || messageTemplate.PayloadType.Value == PaylodTypes.Binary)
            {
                return(GetBinaryPayload(messageTemplate.BinaryPayload));
            }
            else if (messageTemplate.PayloadType.Value == PaylodTypes.PointArray)
            {
                return(GetPointArrayPayload(messageTemplate.BinaryPayload));
            }
            else
            {
                var msgText = ReplaceTokens(_instance, plan, messageTemplate.TextPayload);
                return(System.Text.UTF8Encoding.UTF8.GetBytes(msgText));
            }
        }
Esempio n. 11
0
        public async Task CreateSBSimulator()
        {
            var sbTrasnamitterKey = Environment.GetEnvironmentVariable("TEST_SB_ACCESSKEY");

            Assert.IsFalse(String.IsNullOrEmpty(sbTrasnamitterKey));

            var accountId = System.Environment.GetEnvironmentVariable("TEST_SB_ACCOUNT_ID");

            Assert.IsFalse(String.IsNullOrEmpty(accountId), "TEST_SB_ACCOUNT_ID");

            var sbPolicyName = System.Environment.GetEnvironmentVariable("TEST_SB_POLICY_NAME");

            Assert.IsFalse(String.IsNullOrEmpty(sbPolicyName), "TEST_SB_POLICY_NAME");

            var sim = GetSimulator(TransportTypes.AzureServiceBus);

            var msg = new MessageTemplate()
            {
                Transport   = Core.Models.EntityHeader <TransportTypes> .Create(TransportTypes.RestHttp),
                PayloadType = Core.Models.EntityHeader <PaylodTypes> .Create(PaylodTypes.String),
                TextPayload = "abc123",
                EndPoint    = "www.software-logistics.com",
                Port        = 80,
                HttpVerb    = "GET"
            };


            var plan = new MessageTransmissionPlan()
            {
                Message = Core.Models.EntityHeader <MessageTemplate> .Create(msg)
            };

            var runtime = new SimulatorRuntime(_runtimeServices.Object, _notifPublisher, _adminLogger, sim);

            var result = await runtime.SendAsync(plan);

            AssertSuccess(result);
        }
        private async Task <InvokeResult> SendMQTTGeoMessage(MessageTransmissionPlan plan)
        {
            var messageTemplate = plan.Message.Value;

            var pointArray  = messageTemplate.TextPayload.Split('\r');
            var geoLocation = pointArray[_pointIndex++];
            var parts       = geoLocation.Split(',');
            var lat         = Convert.ToDouble(parts[0]);
            var lon         = Convert.ToDouble(parts[1]);
            var delay       = Convert.ToInt32(parts[2]) * 1000;

            await _mqttClient.PublishAsync(ReplaceTokens(_instance, plan, messageTemplate.Topic), $"{lat},{lon}");

            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Queue up point {_pointIndex} to send.");

            if (this._pointIndex < pointArray.Length)
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Queue up point {_pointIndex} to send.");

                _timer = new Timer(SendMqttGeoRequest, plan, delay, Timeout.Infinite);
            }

            return(InvokeResult.Success);
        }
        private String BuildRequestContent(MessageTransmissionPlan plan)
        {
            var messageTemplate = plan.Message.Value;

            var sentContent = new StringBuilder();

            switch (messageTemplate.Transport.Value)
            {
            case TransportTypes.TCP:
                sentContent.AppendLine($"Host   : {_simulator.DefaultEndPoint}");
                sentContent.AppendLine($"Port   : {messageTemplate.Port}");
                sentContent.AppendLine($"Body");
                sentContent.AppendLine($"---------------------------------");
                sentContent.Append(ReplaceTokens(_instance, plan, messageTemplate.TextPayload));
                break;

            case TransportTypes.UDP:
                sentContent.AppendLine($"Host   : {_simulator.DefaultEndPoint}");
                sentContent.AppendLine($"Port   : {messageTemplate.Port}");
                sentContent.AppendLine($"Body");
                sentContent.AppendLine($"---------------------------------");
                sentContent.Append(ReplaceTokens(_instance, plan, messageTemplate.TextPayload));
                break;

            case TransportTypes.AzureIoTHub:
                sentContent.AppendLine($"Host   : {_simulator.DefaultEndPoint}");
                sentContent.AppendLine($"Port   : {messageTemplate.Port}");
                sentContent.AppendLine($"Body");
                sentContent.AppendLine($"---------------------------------");
                sentContent.Append(ReplaceTokens(_instance, plan, messageTemplate.TextPayload));
                break;

            case TransportTypes.AzureEventHub:
                sentContent.AppendLine($"Host   : {_simulator.DefaultEndPoint}");
                sentContent.AppendLine($"Body");
                sentContent.AppendLine($"---------------------------------");
                sentContent.Append(ReplaceTokens(_instance, plan, messageTemplate.TextPayload));
                break;

            case TransportTypes.AzureServiceBus:
                sentContent.AppendLine($"Host   : {messageTemplate.Name}");
                //sentContent.AppendLine($"Queue   : {MsgTemplate.Qu}");
                sentContent.AppendLine($"Body");
                sentContent.AppendLine($"---------------------------------");
                sentContent.Append(ReplaceTokens(_instance, plan, messageTemplate.TextPayload));
                break;

            case TransportTypes.MQTT:
                sentContent.AppendLine($"Host         : {_simulator.DefaultEndPoint}");
                sentContent.AppendLine($"Port         : {messageTemplate.Port}");
                sentContent.AppendLine($"Topics");
                sentContent.AppendLine($"Publish      : {ReplaceTokens(_instance, plan, messageTemplate.Topic)}");
                sentContent.AppendLine($"Subscription : {ReplaceTokens(_instance, plan, _simulator.Subscription)}");

                sentContent.Append(ReplaceTokens(_instance, plan, messageTemplate.TextPayload));
                break;

            case TransportTypes.RestHttps:
            case TransportTypes.RestHttp:
            {
                var protocol = messageTemplate.Transport.Value == TransportTypes.RestHttps ? "https" : "http";
                var uri      = $"{protocol}://{_simulator.DefaultEndPoint}:{_simulator.DefaultPort}{ReplaceTokens(_instance, plan, messageTemplate.PathAndQueryString)}";
                sentContent.AppendLine($"Method       : {messageTemplate.HttpVerb}");
                sentContent.AppendLine($"Endpoint     : {uri}");
                var contentType = String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType;
                sentContent.AppendLine($"Content Type : {contentType}");

                if (_simulator.BasicAuth)
                {
                    var authCreds = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_simulator.UserName + ":" + _simulator.Password));
                    sentContent.AppendLine($"Authorization: Basic {authCreds}");
                }
                if (messageTemplate.MessageHeaders.Any())
                {
                    sentContent.AppendLine($"Custom Headers");
                }

                var idx = 1;
                foreach (var hdr in messageTemplate.MessageHeaders)
                {
                    sentContent.AppendLine($"\t{idx++}. {hdr.HeaderName}={ReplaceTokens(_instance, plan, hdr.Value)}");
                }

                if (messageTemplate.HttpVerb == "POST" || messageTemplate.HttpVerb == "PUT")
                {
                    sentContent.AppendLine("");
                    sentContent.AppendLine("Post Content");
                    sentContent.AppendLine("=========================");
                    sentContent.AppendLine(ReplaceTokens(_instance, plan, messageTemplate.TextPayload));
                }
            }
            break;
            }

            return(sentContent.ToString());
        }
        private async Task <InvokeResult> SendRESTRequestAsync(MessageTransmissionPlan plan)
        {
            var messageTemplate = plan.Message.Value;

            if (messageTemplate.PayloadType.Id == MessageTemplate.PayloadTypes_GeoPath)
            {
                return(await SendHTMLGeoMessage(plan));
            }

            using (var client = new HttpClient())
            {
                var protocol = messageTemplate.Transport.Value == TransportTypes.RestHttps ? "https" : "http";

                String uri = null;

                /*if (!String.IsNullOrEmpty(messageTemplate.EndPoint))
                 * {
                 *  uri = $"{protocol}://{messageTemplate.EndPoint}:{messageTemplate.Port}{ReplaceTokens(_instance, plan, messageTemplate.PathAndQueryString)}";
                 * }
                 * else */

                if (!String.IsNullOrEmpty(_simulator.DefaultEndPoint))
                {
                    uri = $"{protocol}://{_simulator.DefaultEndPoint}:{_simulator.DefaultPort}{ReplaceTokens(_instance, plan, messageTemplate.PathAndQueryString)}";
                }

                if (String.IsNullOrEmpty(uri))
                {
                    await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "End Point must be provided at the Simulator or Message Level");

                    return(InvokeResult.FromError("End Point must be provided at the Simulator or Message Level"));
                }

                if (!_simulator.Anonymous)
                {
                    if (_simulator.BasicAuth)
                    {
                        if (String.IsNullOrEmpty(_simulator.Password) || String.IsNullOrEmpty(_simulator.UserName))
                        {
                            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Simulator is not anonymous however user name and password not supplied for basic auth.");

                            return(InvokeResult.FromError("Simulator is not anonymous however user name and password not supplied for basic auth."));
                        }

                        var authCreds = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_simulator.UserName + ":" + _simulator.Password));
                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authCreds);
                    }
                    else
                    {
                        if (String.IsNullOrEmpty(_simulator.AuthHeader))
                        {
                            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Simulator is not anonymous however auth header is not provided and not basic auth.");

                            return(InvokeResult.FromError("Simulator is not anonymous however auth header is not provided and not basic auth.."));
                        }

                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(_simulator.AuthHeader);
                    }
                }

                System.Net.Http.HttpResponseMessage responseMessage = null;

                foreach (var hdr in messageTemplate.MessageHeaders)
                {
                    client.DefaultRequestHeaders.Add(hdr.HeaderName, ReplaceTokens(_instance, plan, hdr.Value));
                }

                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending: {messageTemplate.HttpVerb} to {uri}.");

                var messageBody = ReplaceTokens(_instance, plan, messageTemplate.TextPayload);
                try
                {
                    switch (messageTemplate.HttpVerb)
                    {
                    case MessageTemplate.HttpVerb_GET:
                        responseMessage = await client.GetAsync(uri);

                        break;

                    case MessageTemplate.HttpVerb_POST:
                        responseMessage = await client.PostAsync(uri, new StringContent(messageBody, Encoding.UTF8, String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType));

                        break;

                    case MessageTemplate.HttpVerb_PUT:
                        responseMessage = await client.PutAsync(uri, new StringContent(messageBody, Encoding.UTF8, String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType));

                        break;

                    case MessageTemplate.HttpVerb_DELETE:
                        responseMessage = await client.DeleteAsync(uri);

                        break;

                    default:
                        await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Unknown HTTP Verb [{messageTemplate.HttpVerb}]");

                        return(InvokeResult.FromError($"Unknown HTTP Verb [{messageTemplate.HttpVerb}]"));
                    }
                }
                catch (HttpRequestException ex)
                {
                    var fullResponseString = new StringBuilder();
                    fullResponseString.AppendLine(ex.Message);
                    if (ex.InnerException != null)
                    {
                        fullResponseString.AppendLine(ex.InnerException.Message);
                    }

                    await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending message: {ex.Message}.");

                    ReceivedContent = fullResponseString.ToString();
                    return(InvokeResult.FromException("SendRESTRequestAsync", ex));
                }

                if (responseMessage.IsSuccessStatusCode)
                {
                    var responseContent = await responseMessage.Content.ReadAsStringAsync();

                    var fullResponseString = new StringBuilder();
                    fullResponseString.AppendLine($"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessageSent}");
                    fullResponseString.AppendLine($"Response Code: {(int)responseMessage.StatusCode} ({responseMessage.ReasonPhrase})");
                    foreach (var hdr in responseMessage.Headers)
                    {
                        fullResponseString.AppendLine($"{hdr.Key}\t:{hdr.Value.FirstOrDefault()}");
                    }
                    fullResponseString.AppendLine();
                    fullResponseString.Append(responseContent);
                    ReceivedContent = fullResponseString.ToString();

                    if (ReceivedContent.Length > 255)
                    {
                        await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, ReceivedContent.Substring(0, 250));
                    }
                    else
                    {
                        await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, ReceivedContent);
                    }

                    await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Success sending message.");

                    return(InvokeResult.Success);
                }
                else
                {
                    ReceivedContent = $"{responseMessage.StatusCode} - {responseMessage.ReasonPhrase}";

                    await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending message: {ReceivedContent}.");

                    return(InvokeResult.FromError(ReceivedContent));
                }
            }
        }
        private async Task <InvokeResult> SendHTMLGeoMessage(MessageTransmissionPlan plan)
        {
            var messageTemplate = plan.Message.Value;

            var pointArray  = messageTemplate.TextPayload.Split('\r');
            var geoLocation = pointArray[_pointIndex++];
            var parts       = geoLocation.Split(',');
            var lat         = Convert.ToDouble(parts[0]);
            var lon         = Convert.ToDouble(parts[1]);
            var delay       = Convert.ToInt32(parts[2]) * 1000;

            using (var client = new HttpClient())
            {
                var protocol = messageTemplate.Transport.Value == TransportTypes.RestHttps ? "https" : "http";
                var uri      = $"{protocol}://{_simulator.DefaultEndPoint}:{_simulator.DefaultPort}{ReplaceTokens(_instance, plan, messageTemplate.PathAndQueryString)}";

                if (!this._simulator.Anonymous)
                {
                    if (String.IsNullOrEmpty(_simulator.Password))
                    {
                        await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Simulator is not anonymous however credentials not supplied.");

                        return(InvokeResult.FromError("Simulator is not anonymous however credentials not supplied."));
                    }

                    var authCreds = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_simulator.UserName + ":" + _simulator.Password));
                    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authCreds);
                }

                System.Net.Http.HttpResponseMessage responseMessage = null;

                foreach (var hdr in messageTemplate.MessageHeaders)
                {
                    client.DefaultRequestHeaders.Add(hdr.HeaderName, ReplaceTokens(_instance, plan, hdr.Value));
                }

                var messageBody = ReplaceTokens(_instance, plan, messageTemplate.TextPayload);
                messageBody = $"{{'latitude':{lat}, 'longitude':{lon}}}";

                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending Geo Point {messageBody} via {messageTemplate.HttpVerb} to {uri}.");

                try
                {
                    switch (messageTemplate.HttpVerb)
                    {
                    case MessageTemplate.HttpVerb_GET:
                        responseMessage = await client.GetAsync(uri);

                        break;

                    case MessageTemplate.HttpVerb_POST:
                        responseMessage = await client.PostAsync(uri, new StringContent(messageBody, Encoding.UTF8, String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType));

                        break;

                    case MessageTemplate.HttpVerb_PUT:
                        responseMessage = await client.PutAsync(uri, new StringContent(messageBody, Encoding.UTF8, String.IsNullOrEmpty(messageTemplate.ContentType) ? "text/plain" : messageTemplate.ContentType));

                        break;

                    case MessageTemplate.HttpVerb_DELETE:
                        responseMessage = await client.DeleteAsync(uri);

                        break;
                    }
                }
                catch (HttpRequestException ex)
                {
                    var fullResponseString = new StringBuilder();
                    fullResponseString.AppendLine(ex.Message);
                    if (ex.InnerException != null)
                    {
                        fullResponseString.AppendLine(ex.InnerException.Message);
                    }

                    ReceivedContent = fullResponseString.ToString();

                    await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending GeoPoint: {ex.Message}.");

                    return(InvokeResult.FromException("SendRESTRequestAsync", ex));
                }

                if (responseMessage.IsSuccessStatusCode)
                {
                    var responseContent = await responseMessage.Content.ReadAsStringAsync();

                    var fullResponseString = new StringBuilder();
                    fullResponseString.AppendLine($"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessageSent}");
                    fullResponseString.AppendLine($"Response Code: {(int)responseMessage.StatusCode} ({responseMessage.ReasonPhrase})");
                    foreach (var hdr in responseMessage.Headers)
                    {
                        fullResponseString.AppendLine($"{hdr.Key}\t:{hdr.Value.FirstOrDefault()}");
                    }
                    fullResponseString.AppendLine();
                    fullResponseString.Append(responseContent);
                    ReceivedContent = fullResponseString.ToString();
                    if (this._pointIndex < pointArray.Length)
                    {
                        await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Queue up point {_pointIndex} to send.");

                        _timer = new Timer(SendHttpGeoRequest, plan, delay, Timeout.Infinite);
                    }

                    return(InvokeResult.Success);
                }
                else
                {
                    ReceivedContent = $"{responseMessage.StatusCode} - {responseMessage.ReasonPhrase}";
                    await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Error sending GeoPoint: {ReceivedContent}.");

                    return(InvokeResult.FromError(ReceivedContent));
                }
            }
        }
        private async Task <InvokeResult> SendServiceBusMessage(MessageTransmissionPlan plan)
        {
            var messageTemplate = plan.Message.Value;

            if (String.IsNullOrEmpty(_simulator.DefaultEndPoint))
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Default End Point is Missing to send to Service Bus.");

                return(InvokeResult.FromError("Default End Point is Missing to send to Event Hub."));
            }

            if (String.IsNullOrEmpty(_simulator.AccessKeyName))
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Access Key Name is Missing to send to Service Bus.");

                return(InvokeResult.FromError("Access Key Name is Missing to send to Event Hub."));
            }

            if (String.IsNullOrEmpty(_simulator.QueueName))
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Queue Name is Missing to send to Service Bus.");

                return(InvokeResult.FromError("Queue Name is Missing to send to Event Hub."));
            }

            if (String.IsNullOrEmpty(_simulator.AccessKey))
            {
                await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, "Access Key is Missing to send to Service Bus.");

                return(InvokeResult.FromError("Access Key is Missing to send to Event Hub."));
            }

            var connectionString = $"Endpoint=sb://{_simulator.DefaultEndPoint}.servicebus.windows.net/;SharedAccessKeyName={_simulator.AccessKeyName};SharedAccessKey={_simulator.AccessKey}";
            var bldr             = new ServiceBusConnectionStringBuilder(connectionString)
            {
                EntityPath = messageTemplate.QueueName
            };

            var client = new QueueClient(bldr, ReceiveMode.PeekLock, Microsoft.Azure.ServiceBus.RetryExponential.Default);

            var msg = new Microsoft.Azure.ServiceBus.Message()
            {
                Body        = GetMessageBytes(plan),
                To          = messageTemplate.To,
                ContentType = messageTemplate.ContentType
            };

            if (!String.IsNullOrEmpty(msg.MessageId))
            {
                msg.MessageId = msg.MessageId;
            }

            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, $"Sending message to Service Bus {_simulator.DefaultEndPoint}");

            await client.SendAsync(msg);

            await client.CloseAsync();

            ReceivedContent = $"{DateTime.Now} {SimulatorRuntimeResources.SendMessage_MessagePublished}";

            await _notificationPublisher.PublishTextAsync(Targets.WebSocket, Channels.Simulator, InstanceId, ReceivedContent);

            return(InvokeResult.Success);
        }