private static void PurgeExistingMessagesIfRequested(ITransportSettings settings)
		{
			if (settings.Address.IsLocal && settings.PurgeExistingMessages)
			{
				MsmqEndpointManagement.Manage(settings.Address, x => x.Purge());
			}
		}
        public Producer(ITransportSettings transportSettings, IDictionary<string, IList<string>> queueMappings)
        {
            _transportSettings = transportSettings;
            _queueMappings = queueMappings;
            _maxMessageSize = transportSettings.ClientSettings.ContainsKey("MessageSize") ? Convert.ToInt64(_transportSettings.ClientSettings["MessageSize"]) : 65536;
            _hosts = transportSettings.Host.Split(',');
            _activeHost = 0;

            Retry.Do(CreateConnection, ex =>
            {
                Logger.Error("Error creating producer - {0}", ex);

                if (_hosts.Length > 1)
                {
                    if (_activeHost < _hosts.Length - 1)
                    {
                        _activeHost++;
                    }
                    else
                    {
                        _activeHost = 0;
                    }
                }

            }, new TimeSpan(0, 0, 0, 10));
        }
        public IOutboundTransport BuildOutbound(ITransportSettings settings)
        {
            try
            {
                var msmqEndpointAddress = new MsmqEndpointAddress(settings.Address.Uri);
                var msmqSettings = GetTransportSettings(settings, msmqEndpointAddress);

                IMsmqEndpointAddress transportAddress = msmqSettings.MsmqAddress();

                if (transportAddress.IsLocal)
                {
                    ValidateLocalTransport(msmqSettings);
                }

                var connection = new MessageQueueConnection(transportAddress, QueueAccessMode.Send);
                var connectionHandler = new ConnectionHandlerImpl<MessageQueueConnection>(connection);

                if (msmqSettings.Transactional)
                    return new TransactionalOutboundMsmqTransport(transportAddress, connectionHandler);

                return new NonTransactionalOutboundMsmqTransport(transportAddress, connectionHandler);
            }
            catch (Exception ex)
            {
                throw new TransportException(settings.Address.Uri, "Failed to create MSMQ outbound transport", ex);
            }
        }
		public IOutboundTransport BuildOutbound(ITransportSettings settings)
		{
			try
			{
				var msmqEndpointAddress = new MsmqEndpointAddress(settings.Address.Uri);
				var msmqSettings = new TransportSettings(msmqEndpointAddress, settings)
				{
					Transactional = msmqEndpointAddress.IsTransactional
				};

				if (msmqSettings.MsmqAddress().IsLocal)
				{
					ValidateLocalTransport(msmqSettings);
				}

				if (msmqSettings.Transactional)
					return new TransactionalOutboundMsmqTransport(msmqSettings.MsmqAddress());

				return new NonTransactionalOutboundMsmqTransport(msmqSettings.MsmqAddress());
			}
			catch (Exception ex)
			{
				throw new TransportException(settings.Address.Uri, "Failed to create MSMQ outbound transport", ex);
			}
		}
		public IDuplexTransport BuildLoopback(ITransportSettings settings)
		{
			var address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

			var transport = new LoopbackRabbitMqTransport(address, BuildInbound(settings), BuildOutbound(settings));
			return transport;
		}
		public IInboundTransport BuildInbound(ITransportSettings settings)
		{
			try
			{
				var msmqEndpointAddress = new MsmqEndpointAddress(settings.Address.Uri);
				var msmqSettings = new TransportSettings(msmqEndpointAddress, settings)
					{
						Transactional = msmqEndpointAddress.IsTransactional
					};

				if (msmqSettings.MsmqAddress().IsLocal)
				{
					ValidateLocalTransport(msmqSettings);

					PurgeExistingMessagesIfRequested(msmqSettings);
				}

				if (msmqSettings.Transactional)
					return new TransactionalInboundMsmqTransport(msmqSettings.MsmqAddress(),
						msmqSettings.TransactionTimeout, msmqSettings.IsolationLevel);

				return new NonTransactionalInboundMsmqTransport(msmqSettings.MsmqAddress());
			}
			catch (Exception ex)
			{
				throw new TransportException(settings.Address.Uri, "Failed to create MSMQ inbound transport", ex);
			}
		}
        public IInboundTransport BuildInbound(ITransportSettings settings)
        {
            try
            {
                var msmqEndpointAddress = new MsmqEndpointAddress(settings.Address.Uri, settings.Transactional);
                var msmqSettings = GetTransportSettings(settings, msmqEndpointAddress);

                IMsmqEndpointAddress transportAddress = msmqSettings.MsmqAddress();

                if (transportAddress.IsLocal)
                {
                    ValidateLocalTransport(msmqSettings);

                    PurgeExistingMessagesIfRequested(msmqSettings);
                }

                var connection = new MessageQueueConnection(transportAddress, QueueAccessMode.Receive);
                var connectionHandler = new ConnectionHandlerImpl<MessageQueueConnection>(connection);

                if (msmqSettings.Transactional)
                    return new TransactionalInboundMsmqTransport(transportAddress, connectionHandler,
                        msmqSettings.TransactionTimeout, msmqSettings.IsolationLevel);

                return new NonTransactionalInboundMsmqTransport(transportAddress, connectionHandler);
            }
            catch (Exception ex)
            {
                throw new TransportException(settings.Address.Uri, "Failed to create MSMQ inbound transport", ex);
            }
        }
        public IInboundTransport BuildInbound(ITransportSettings settings)
        {
            EnsureProtocolIsCorrect(settings.Address.Uri);

            var client = GetConnection(settings.Address);
            return new InboundStompTransport(settings.Address, client);
        }
Example #9
0
        public async Task Test_Create_DeviceIdentity_WithEnv_ShouldThrow()
        {
            IIdentity identity = new DeviceIdentity(IotHubHostName, DeviceId);

            var transportSettings = new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) };

            await Assert.ThrowsAsync <InvalidOperationException>(() => new ClientProvider().CreateAsync(identity, transportSettings));
        }
        public async Task Message_ModuleSendSingleMessage_AmqpWs_WithProxy()
        {
            Client.AmqpTransportSettings amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only);
            amqpTransportSettings.Proxy = new WebProxy(ProxyServerAddress);
            ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings };

            await SendSingleMessageModule(transportSettings).ConfigureAwait(false);
        }
        public async Task Message_DeviceSendSingleMessage_Http_WithProxy()
        {
            Client.Http1TransportSettings httpTransportSettings = new Client.Http1TransportSettings();
            httpTransportSettings.Proxy = new WebProxy(ProxyServerAddress);
            ITransportSettings[] transportSettings = new ITransportSettings[] { httpTransportSettings };

            await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false);
        }
Example #12
0
		public EndpointSettings(IEndpointAddress address, IMessageSerializer serializer, ITransportSettings source)
			: base(address, source)
		{
			Guard.AgainstNull(source, "source");

			Serializer = serializer;
			ErrorAddress = GetErrorEndpointAddress();
		}
 static TransportSettings GetTransportSettings(ITransportSettings settings, MsmqEndpointAddress msmqEndpointAddress)
 {
     var msmqSettings = new TransportSettings(msmqEndpointAddress, settings)
         {
             Transactional = msmqEndpointAddress.IsTransactional,
         };
     return msmqSettings;
 }
        public async Task Message_DeviceSendSingleMessage_AmqpWs_WithHeartbeats()
        {
            Client.AmqpTransportSettings amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only);
            amqpTransportSettings.IdleTimeout = TimeSpan.FromMinutes(2);
            ITransportSettings[] transportSettings = new ITransportSettings[] { amqpTransportSettings };

            await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false);
        }
        public IOutboundTransport BuildError(ITransportSettings settings)
        {
            EnsureProtocolIsCorrect(settings.Address.Uri);

            var client = GetConnection(settings.Address);

            return(new OutboundStompTransport(settings.Address, client));
        }
Example #16
0
        public IDuplexTransport BuildLoopback(ITransportSettings settings)
        {
            RabbitMqEndpointAddress address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

            var transport = new Transport(address, () => BuildInbound(settings), () => BuildOutbound(settings));

            return(transport);
        }
Example #17
0
        public void TestSetupCertificateValidation_Amqp_ShouldSucceed()
        {
            ITransportSettings[] transportSettings = new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only) };
            var certs = new TrustBundleProvider().ParseCertificates(certificatesString);
            var customCertificateValidator = CustomCertificateValidator.Create(certs, transportSettings);

            Assert.IsNotNull(((AmqpTransportSettings)transportSettings[0]).RemoteCertificateValidationCallback);
        }
		public IOutboundTransport BuildOutbound(ITransportSettings settings)
		{
			var address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

			EnsureProtocolIsCorrect(address.Uri);

			return new OutboundRabbitMqTransport(address, GetConnection(address));
		}
Example #19
0
        public async Task CreateFromEnvironmentTest(
            Option <UpstreamProtocol> upstreamProtocol,
            Option <IWebProxy> webProxy,
            string productInfo)
        {
            // Arrange
            ITransportSettings receivedTransportSettings = null;

            var sdkModuleClient = new Mock <ISdkModuleClient>();

            var sdkModuleClientProvider = new Mock <ISdkModuleClientProvider>();

            sdkModuleClientProvider.Setup(s => s.GetSdkModuleClient(It.IsAny <ITransportSettings>()))
            .Callback <ITransportSettings>(t => receivedTransportSettings = t)
            .ReturnsAsync(sdkModuleClient.Object);

            bool     closeOnIdleTimeout            = false;
            TimeSpan idleTimeout                   = TimeSpan.FromMinutes(5);
            ConnectionStatusChangesHandler handler = (status, reason) => { };

            // Act
            var moduleClientProvider = new ModuleClientProvider(
                sdkModuleClientProvider.Object,
                upstreamProtocol,
                webProxy,
                productInfo,
                closeOnIdleTimeout,
                idleTimeout);
            IModuleClient moduleClient = await moduleClientProvider.Create(handler);

            // Assert
            Assert.NotNull(moduleClient);
            sdkModuleClientProvider.Verify(s => s.GetSdkModuleClient(It.IsAny <ITransportSettings>()), Times.Once);

            sdkModuleClient.Verify(s => s.SetProductInfo(productInfo), Times.Once);

            Assert.NotNull(receivedTransportSettings);
            UpstreamProtocol up = upstreamProtocol.GetOrElse(UpstreamProtocol.Amqp);

            switch (up)
            {
            case UpstreamProtocol.Amqp:
            case UpstreamProtocol.AmqpWs:
                var amqpTransportSettings = receivedTransportSettings as AmqpTransportSettings;
                Assert.NotNull(amqpTransportSettings);
                webProxy.ForEach(w => Assert.Equal(w, amqpTransportSettings.Proxy));
                break;

            case UpstreamProtocol.Mqtt:
            case UpstreamProtocol.MqttWs:
                var mqttTransportSettings = receivedTransportSettings as MqttTransportSettings;
                Assert.NotNull(mqttTransportSettings);
                webProxy.ForEach(w => Assert.Equal(w, mqttTransportSettings.Proxy));
                break;
            }

            sdkModuleClient.Verify(s => s.OpenAsync(), Times.Once);
        }
        public async Task Message_DeviceSendSingleMessage_AmqpWs_WithProxy()
        {
            var amqpTransportSettings = new Client.AmqpTransportSettings(Client.TransportType.Amqp_WebSocket_Only);

            amqpTransportSettings.Proxy = new WebProxy(s_proxyServerAddress);
            var transportSettings = new ITransportSettings[] { amqpTransportSettings };

            await SendSingleMessage(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false);
        }
Example #21
0
        public async Task Message_ModuleSendSingleMessage_MqttWs_WithProxy()
        {
            Client.Transport.Mqtt.MqttTransportSettings mqttTransportSettings =
                new Client.Transport.Mqtt.MqttTransportSettings(Client.TransportType.Mqtt_WebSocket_Only);
            mqttTransportSettings.Proxy = new WebProxy(ProxyServerAddress);
            ITransportSettings[] transportSettings = new ITransportSettings[] { mqttTransportSettings };

            await SendSingleMessageModule(TestDeviceType.Sasl, transportSettings).ConfigureAwait(false);
        }
Example #22
0
        static TransportSettings GetTransportSettings(ITransportSettings settings, MsmqEndpointAddress msmqEndpointAddress)
        {
            var msmqSettings = new TransportSettings(msmqEndpointAddress, settings)
            {
                Transactional = msmqEndpointAddress.IsTransactional,
            };

            return(msmqSettings);
        }
Example #23
0
 public Connection(ITransportSettings transportSettings, string queueName)
 {
     _hosts             = transportSettings.Host.Split(',');
     _transportSettings = transportSettings;
     _queueName         = queueName;
     _transportSettings = transportSettings;
     _heartbeatEnabled  = !transportSettings.ClientSettings.ContainsKey("HeartbeatEnabled") || (bool)transportSettings.ClientSettings["HeartbeatEnabled"];
     _heartbeatTime     = transportSettings.ClientSettings.ContainsKey("HeartbeatTime") ? Convert.ToUInt16((int)transportSettings.ClientSettings["HeartbeatTime"]) : Convert.ToUInt16(120);
 }
Example #24
0
        public async Task X509_DeviceDoesNotReceivePendingMessageUsingCallback_MqttWs()
        {
            var settings = new ITransportSettings[] { new MqttTransportSettings(Client.TransportType.Mqtt_WebSocket_Only)
                                                      {
                                                          CleanSession = true
                                                      } };

            await DoNotReceiveMessagesSentBeforeSubscriptionAsync(TestDeviceType.X509, settings).ConfigureAwait(false);
        }
		public IInboundTransport BuildInbound(ITransportSettings settings)
		{
			RabbitMqEndpointAddress address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

			EnsureProtocolIsCorrect(address.Uri);

			ConnectionHandler<RabbitMqConnection> connectionHandler = GetConnection(address);

			return new InboundRabbitMqTransport(address, connectionHandler, settings.PurgeExistingMessages);
		}
Example #26
0
        public void Throw_OnEmptyModelId()
        {
            IIdentity identity = new ModuleIdentity(IotHubHostName, DeviceId, ModuleId);

            var            transportSettings = new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) };
            string         modelId           = string.Empty;
            ITokenProvider tokenProvider     = new TestTokenProvider();

            Assert.Throws <ArgumentException>(() => new ClientProvider(Option.None <string>()).Create(identity, tokenProvider, transportSettings, Option.Some(modelId)));
        }
Example #27
0
        public TransportSettings([NotNull] IEndpointAddress address, [NotNull] ITransportSettings source)
        {
            Guard.AgainstNull(address, "address");
            Guard.AgainstNull(source, "source");

            Address = address;

            CreateIfMissing       = source.CreateIfMissing;
            PurgeExistingMessages = source.PurgeExistingMessages;
        }
Example #28
0
        public IOutboundTransport BuildError(ITransportSettings settings)
        {
            RabbitMqEndpointAddress address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

            EnsureProtocolIsCorrect(address.Uri);

            ConnectionHandler <RabbitMqConnection> connection = GetConnection(address);

            return(new OutboundRabbitMqTransport(address, connection, true));
        }
        public async Task Message_DeviceSendSingleMessage_Http_WithCustomeProxy()
        {
            Http1TransportSettings httpTransportSettings = new Http1TransportSettings();
            CustomWebProxy proxy = new CustomWebProxy();
            httpTransportSettings.Proxy = proxy;
            ITransportSettings[] transportSettings = new ITransportSettings[] { httpTransportSettings };

            await SendSingleMessage(transportSettings).ConfigureAwait(false);
            Assert.AreNotEqual(proxy.Counter, 0);
        }
		public IOutboundTransport BuildOutbound(ITransportSettings settings)
		{
			RabbitMqEndpointAddress address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

			EnsureProtocolIsCorrect(address.Uri);

			ConnectionHandler<RabbitMqConnection> connectionHandler = GetConnection(address);

			return new OutboundRabbitMqTransport(address, connectionHandler, false);
		}
Example #31
0
        public IInboundTransport BuildInbound(ITransportSettings settings)
        {
            RabbitMqEndpointAddress address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

            EnsureProtocolIsCorrect(address.Uri);

            ConnectionHandler <RabbitMqConnection> connectionHandler = GetConnection(address);

            return(new InboundRabbitMqTransport(address, connectionHandler, settings.PurgeExistingMessages));
        }
        public void GetTransportSettingsTest(Option <UpstreamProtocol> upstreamProtocol, int connectionPoolSize, Option <IWebProxy> proxy, ITransportSettings[] expectedTransportSettingsList, bool useServerHeartbeat)
        {
            const string expectedAuthChain = "e3;e2;e1";

            ITransportSettings[] transportSettingsList = CloudConnectionProvider.GetTransportSettings(upstreamProtocol, connectionPoolSize, proxy, useServerHeartbeat, expectedAuthChain);

            Assert.NotNull(transportSettingsList);
            Assert.Equal(expectedTransportSettingsList.Length, transportSettingsList.Length);
            for (int i = 0; i < expectedTransportSettingsList.Length; i++)
            {
                ITransportSettings expectedTransportSettings = expectedTransportSettingsList[i];
                ITransportSettings transportSettings         = transportSettingsList[i];

                Assert.Equal(expectedTransportSettings.GetType(), transportSettings.GetType());
                Assert.Equal(expectedTransportSettings.GetTransportType(), transportSettings.GetTransportType());

                // Check authchain via Reflection
                string authChain = (string)transportSettings.GetType()
                                   .GetProperty("AuthenticationChain", BindingFlags.NonPublic | BindingFlags.Instance)
                                   .GetValue(transportSettings);

                Assert.Equal(authChain, expectedAuthChain);

                switch (expectedTransportSettings)
                {
                case AmqpTransportSettings _:
                {
                    var expected = (AmqpTransportSettings)expectedTransportSettings;
                    var actual   = (AmqpTransportSettings)transportSettings;
                    Assert.True(expected.Equals(actual));     // AmqpTransportSettings impls Equals, but doesn't override Object.Equals

                    if (proxy == Option.None <IWebProxy>())
                    {
                        Assert.Null(actual.Proxy);
                    }
                    else
                    {
                        Assert.True(actual.Proxy is WebProxy);
                        Assert.Equal(((WebProxy)expected.Proxy).Address, ((WebProxy)actual.Proxy).Address);
                    }

                    break;
                }

                case MqttTransportSettings _:
                {
                    var expected = (MqttTransportSettings)expectedTransportSettings;
                    var actual   = (MqttTransportSettings)transportSettings;
                    Assert.True(actual.Proxy is WebProxy);
                    Assert.Equal(((WebProxy)expected.Proxy).Address, ((WebProxy)actual.Proxy).Address);
                    break;
                }
                }
            }
        }
Example #33
0
        public void Test_Create_ModuleIdentity_WithConnectionString_ShouldCreateModuleClient()
        {
            string    connectionString = $"HostName={IotHubHostName};DeviceId={DeviceId};ModuleId={ModuleId};SharedAccessKey={this.authKey}";
            IIdentity identity         = new ModuleIdentity(IotHubHostName, DeviceId, ModuleId);

            var     transportSettings = new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) };
            IClient client            = new ClientProvider().Create(identity, connectionString, transportSettings);

            Assert.NotNull(client);
            Assert.True(client is ModuleClientWrapper);
        }
Example #34
0
        protected virtual IAsyncResult OnBeginCreateFactory(IEnumerable <Uri> uriAddresses, AsyncCallback callback, object state)
        {
            ITransportSettings          transportSettings = this.GetTransportSettings();
            IServiceBusSecuritySettings tokenProvider     = transportSettings as IServiceBusSecuritySettings;

            if (tokenProvider != null)
            {
                tokenProvider.TokenProvider = this.TokenProvider;
            }
            return(transportSettings.BeginCreateFactory(uriAddresses, callback, state));
        }
        /// <summary>
        ///     Builds the duplex transport.
        /// </summary>
        /// <param name="settings"> The settings. </param>
        /// <returns> </returns>
        public IDuplexTransport BuildLoopback([NotNull] ITransportSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            _log.Debug("building duplex transport");

            return(new Transport(settings.Address, () => BuildInbound(settings), () => BuildOutbound(settings)));
        }
Example #36
0
        public void Test_Create_DeviceIdentity_WithTokenProvider_ShouldCreateDeviceClient()
        {
            IIdentity identity = new DeviceIdentity(IotHubHostName, DeviceId);

            var            transportSettings = new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) };
            ITokenProvider tokenProvider     = new TestTokenProvider();
            IClient        client            = new ClientProvider(Option.None <string>()).Create(identity, tokenProvider, transportSettings, Option.None <string>());

            Assert.NotNull(client);
            Assert.True(client is DeviceClientWrapper);
        }
Example #37
0
 /// <summary>
 /// Helper to create device client
 /// </summary>
 /// <param name="cs"></param>
 /// <param name="transportSetting"></param>
 /// <returns></returns>
 private static DeviceClient Create(IotHubConnectionStringBuilder cs,
     ITransportSettings transportSetting) {
     if (cs == null) {
         throw new ArgumentNullException(nameof(cs));
     }
     if (transportSetting != null) {
         return DeviceClient.CreateFromConnectionString(cs.ToString(),
             new ITransportSettings[] { transportSetting });
     }
     return DeviceClient.CreateFromConnectionString(cs.ToString());
 }
Example #38
0
        /// <summary>
        /// Determine whether the URL should be an API path, relative to BaseUrl, or is already a full URL
        /// </summary>
        /// <param name="path">path to update</param>
        /// <param name="settings">settings with <c>BaseUrl</c> assigned</param>
        /// <param name="authenticator">Optional authenticator callback</param>
        /// <remarks>Relative paths are expected to start with <c>/</c></remarks>
        /// <returns>Current path if full, api or base url path if relative</returns>
        public string MakePath(string path, ITransportSettings settings, Authenticator authenticator = null)
        {
            if (path.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase) ||
                path.StartsWith("https:", StringComparison.InvariantCultureIgnoreCase))
            {
                return(path);
            }
            var root = (authenticator == null ? settings.BaseUrl : _apiPath);

            return($"{root}{path}");
        }
        private async Task SendMessageTest(ITransportSettings transportSetting)
        {
            using TestDevice testDevice = await TestDevice.GetTestDeviceAsync(Logger, s_devicePrefix, TestDeviceType.X509).ConfigureAwait(false);

            using DeviceClient deviceClient = testDevice.CreateDeviceClient(new[] { transportSetting });
            await deviceClient.OpenAsync().ConfigureAwait(false);

            await MessageSendE2ETests.SendSingleMessageAsync(deviceClient, testDevice.Id, Logger).ConfigureAwait(false);

            await deviceClient.CloseAsync().ConfigureAwait(false);
        }
Example #40
0
        static async Task <LeafDevice> CreateWithSasAsync(
            string leafDeviceId,
            Option <string> parentId,
            IotHub iotHub,
            ITransportSettings transport,
            string edgeHostname,
            CancellationToken token,
            ClientOptions options,
            bool nestedEdge)
        {
            Device leaf = new Device(leafDeviceId)
            {
                Authentication = new AuthenticationMechanism
                {
                    Type = AuthenticationType.Sas
                }
            };

            await parentId.ForEachAsync(
                async p =>
            {
                Device edge = await GetEdgeDeviceIdentityAsync(p, iotHub, token);
                leaf.Scope  = edge.Scope;
            });

            // @To Remove this is a hack to be able to create lea. See PBI: 9171870
            string hostname = iotHub.Hostname;

            if (nestedEdge)
            {
                hostname = edgeHostname;
            }

            leaf = await iotHub.CreateDeviceIdentityAsync(leaf, token);

            return(await DeleteIdentityIfFailedAsync(
                       leaf,
                       iotHub,
                       token,
                       () =>
            {
                string connectionString =
                    $"HostName={hostname};" +
                    $"DeviceId={leaf.Id};" +
                    $"SharedAccessKey={leaf.Authentication.SymmetricKey.PrimaryKey};" +
                    $"GatewayHostName={edgeHostname}";

                return CreateLeafDeviceAsync(
                    leaf,
                    () => DeviceClient.CreateFromConnectionString(connectionString, new[] { transport }, options),
                    iotHub,
                    token);
            }));
        }
 /// <summary>
 /// Create client adapter
 /// </summary>
 /// <param name="product"></param>
 /// <param name="onError"></param>
 /// <param name="transportSetting"></param>
 /// <returns></returns>
 private Task <IClient> CreateAdapterAsync(string product, Action onError,
                                           ITransportSettings transportSetting = null)
 {
     if (_cs != null && string.IsNullOrEmpty(_cs.ModuleId))
     {
         return(DeviceClientAdapter.CreateAsync(product, _cs, transportSetting,
                                                _timeout, RetryPolicy, onError, _logger));
     }
     return(ModuleClientAdapter.CreateAsync(product, _cs, transportSetting,
                                            _timeout, RetryPolicy, onError, _logger));
 }
		public IDuplexTransport BuildLoopback(ITransportSettings settings)
		{
			try
			{
				return new Transport(BuildInbound(settings), BuildOutbound(settings));
			}
			catch (Exception ex)
			{
				throw new TransportException(settings.Address.Uri, "Failed to create MSMQ transport", ex);
			}
		}
		public IOutboundTransport BuildError(ITransportSettings settings)
		{
			var address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

			EnsureProtocolIsCorrect(address.Uri);

			IConnection connection = GetConnection(address);

			BindErrorExchangeToQueue(address, connection);

			return new OutboundRabbitMqTransport(address, connection);
		}
Example #44
0
        public void Test_Create_ModuleIdentity_WithAuthMethod_ShouldCreateModuleClient()
        {
            string    token                = TokenHelper.CreateSasToken(IotHubHostName);
            IIdentity identity             = new ModuleIdentity(IotHubHostName, DeviceId, ModuleId);
            var       authenticationMethod = new ModuleAuthenticationWithToken(DeviceId, ModuleId, token);

            var     transportSettings = new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) };
            IClient client            = new ClientProvider().Create(identity, authenticationMethod, transportSettings);

            Assert.NotNull(client);
            Assert.True(client is ModuleClientWrapper);
        }
Example #45
0
        public void Test_Create_DeviceIdentity_WithTokenProvider_AndModelId_AndGatewayHostName_ShouldCreateDeviceClient()
        {
            IIdentity identity = new DeviceIdentity(IotHubHostName, DeviceId);

            var            transportSettings = new ITransportSettings[] { new MqttTransportSettings(TransportType.Mqtt_Tcp_Only) };
            string         modelId           = "testModelId";
            ITokenProvider tokenProvider     = new TestTokenProvider();
            IClient        client            = new ClientProvider(Option.Some("testGatewayHostName")).Create(identity, tokenProvider, transportSettings, Option.Some(modelId));

            Assert.NotNull(client);
            Assert.True(client is DeviceClientWrapper);
        }
Example #46
0
        public EndpointSettings(IEndpointAddress address, IMessageSerializer serializer, ITransportSettings source)
            : base(address, source)
        {
            Guard.AgainstNull(source, "source");

            Serializer = serializer;

            var messageSerializers = new SupportedMessageSerializers();
            messageSerializers.AddSerializer(serializer);
            SupportedSerializers = messageSerializers;

            ErrorAddress = GetErrorEndpointAddress();
        }
        public Producer(ITransportSettings transportSettings, IDictionary<string, IList<string>> queueMappings)
        {
            _transportSettings = transportSettings;
            _queueMappings = queueMappings;

            if (_transportSettings.ClientSettings.ContainsKey("PublisherHost"))
            {
                _publishContext = new ZContext();
                _publisher = new ZSocket(_publishContext, ZSocketType.PUB);
                _publisher.Linger = TimeSpan.FromMilliseconds(1);
                _publisher.Bind(_transportSettings.ClientSettings["PublisherHost"].ToString());
            }
        }
		public EndpointBuilderImpl([NotNull] Uri uri, [NotNull] IEndpointSettings settings,
		                           [NotNull] ITransportSettings errorSettings,
		                           [NotNull] Func<ITransportFactory, ITransportSettings, IDuplexTransport> transportFactory,
		                           [NotNull] Func<ITransportFactory, ITransportSettings, IOutboundTransport>
		                           	errorTransportFactory)
		{
			Guard.AgainstNull(uri, "uri");

			_uri = uri;
			_settings = settings;
			_errorSettings = errorSettings;
			_transportFactory = transportFactory;
			_errorTransportFactory = errorTransportFactory;
		}
        public EndpointBuilderImpl([NotNull] Uri uri, [NotNull] IEndpointSettings settings,
            [NotNull] ITransportSettings errorSettings, [NotNull] DuplexTransportFactory transportFactory,
            [NotNull] OutboundTransportFactory errorTransportFactory,
            [NotNull] Func<IInboundMessageTracker> messageTrackerFactory)
        {
            Guard.AgainstNull(uri, "uri");

            _uri = uri;
            _settings = settings;
            _errorSettings = errorSettings;
            _transportFactory = transportFactory;
            _errorTransportFactory = errorTransportFactory;
            _messageTrackerFactory = messageTrackerFactory;
        }
        public Producer(ITransportSettings transportSettings, IDictionary<string, IList<string>> queueMappings)
        {
            _transportSettings = transportSettings;
            _queueMappings = queueMappings;
            _maxMessageSize = transportSettings.ClientSettings.ContainsKey("MessageSize") ? Convert.ToInt64(_transportSettings.ClientSettings["MessageSize"]) : 65536;
            _hosts = transportSettings.Host.Split(',');
            _activeHost = 0;

            _connectionFactory = new ConnectionFactory
            {
                HostName = _hosts[_activeHost],
                VirtualHost = "/",
                Protocol = Protocols.DefaultProtocol,
                Port = AmqpTcpEndpoint.UseDefaultPort
            };

            if (!string.IsNullOrEmpty(transportSettings.Username))
            {
                _connectionFactory.UserName = transportSettings.Username;
            }

            if (!string.IsNullOrEmpty(transportSettings.Password))
            {
                _connectionFactory.Password = transportSettings.Password;
            }

            if (_transportSettings.SslEnabled)
            {
                _connectionFactory.Ssl = new SslOption
                {
                    Enabled = true,
                    AcceptablePolicyErrors = transportSettings.AcceptablePolicyErrors,
                    ServerName = transportSettings.ServerName,
                    CertPassphrase = transportSettings.CertPassphrase,
                    CertPath = transportSettings.CertPath,
                    Certs = transportSettings.Certs,
                    Version = transportSettings.Version,
                    CertificateSelectionCallback = transportSettings.CertificateSelectionCallback,
                    CertificateValidationCallback = transportSettings.CertificateValidationCallback
                };
                _connectionFactory.Port = AmqpTcpEndpoint.DefaultAmqpSslPort;
            }

            if (!string.IsNullOrEmpty(transportSettings.VirtualHost))
            {
                _connectionFactory.VirtualHost = transportSettings.VirtualHost;
            }

            CreateConnection();
        }
Example #51
0
		public TransportSettings(IEndpointAddress address, ITransportSettings source)
		{
			Guard.AgainstNull(address, "address");
			Guard.AgainstNull(source, "source");

			Address = address;

			Transactional = source.Transactional;
			RequireTransactional = source.RequireTransactional;
			TransactionTimeout = source.TransactionTimeout;
			IsolationLevel = source.IsolationLevel;

			CreateIfMissing = source.CreateIfMissing;
			PurgeExistingMessages = source.PurgeExistingMessages;
		}
Example #52
0
        public EndpointBuilderImpl([NotNull] IEndpointAddress address, [NotNull] IEndpointSettings settings,
            [NotNull] ITransportSettings errorSettings, [NotNull] DuplexTransportFactory transportFactory,
            [NotNull] OutboundTransportFactory errorTransportFactory,
            [NotNull] Func<IInboundMessageTracker> messageTrackerFactory)
        {
            if (address == null)
                throw new ArgumentNullException("address");

            _address = address;
            _settings = settings;
            _errorSettings = errorSettings;
            _transportFactory = transportFactory;
            _errorTransportFactory = errorTransportFactory;
            _messageTrackerFactory = messageTrackerFactory;
        }
        DeviceClient(IotHubConnectionString iotHubConnectionString, ITransportSettings[] transportSettings)
        {
            this.iotHubConnectionString = iotHubConnectionString;

#if !WINDOWS_UWP
            var innerHandler = new RetryDelegatingHandler(
                new ErrorDelegatingHandler(
                    () => new RoutingDelegatingHandler(this.CreateTransportHandler, iotHubConnectionString, transportSettings)));
#else
            // UWP does not support retry yet. We need to make the underlying Message stream accessible internally on UWP
            // to be sure that either the stream has not been read or it is seekable to safely retry operation
            var innerHandler = new ErrorDelegatingHandler(
                () => new RoutingDelegatingHandler(this.CreateTransportHandler, iotHubConnectionString, transportSettings));
#endif
            this.InnerHandler = new GateKeeperDelegatingHandler(innerHandler);
        }
		public IDuplexTransport BuildLoopback(ITransportSettings settings)
		{
			try
			{
				ITransportSettings msmqSettings = new TransportSettings(new MsmqEndpointAddress(settings.Address.Uri), settings);

				IInboundTransport inboundTransport = BuildInbound(settings);
				IOutboundTransport outboundTransport = BuildOutbound(settings);

				return new Transport(msmqSettings.Address, () => inboundTransport, () => outboundTransport);
			}
			catch (Exception ex)
			{
				throw new TransportException(settings.Address.Uri, "Failed to create MSMQ transport", ex);
			}
		}
        public IDuplexTransport BuildLoopback(ITransportSettings settings)
        {
            try
            {
                var msmqEndpointAddress = new MsmqEndpointAddress(settings.Address.Uri, settings.Transactional, defaultRecoverable);
                TransportSettings msmqSettings = GetTransportSettings(settings, msmqEndpointAddress);

                IInboundTransport inboundTransport = BuildInbound(settings);
                IOutboundTransport outboundTransport = BuildOutbound(settings);

                return new Transport(msmqSettings.Address, () => inboundTransport, () => outboundTransport);
            }
            catch (Exception ex)
            {
                throw new TransportException(settings.Address.Uri, "Failed to create MSMQ transport", ex);
            }
        }
		public IInboundTransport BuildInbound(ITransportSettings settings)
		{
			try
			{
				ITransportSettings msmqSettings = new TransportSettings(new MsmqEndpointAddress(settings.Address.Uri), settings);

				if (msmqSettings.MsmqAddress().IsLocal)
				{
					ValidateLocalTransport(msmqSettings);

					PurgeExistingMessagesIfRequested(msmqSettings);
				}

				return new NonTransactionalInboundMsmqTransport(msmqSettings.MsmqAddress());
			}
			catch (Exception ex)
			{
				throw new TransportException(settings.Address.Uri, "Failed to create MSMQ inbound transport", ex);
			}
		}
 public static async Task<IMessagingServiceClient> CreateFromConnectionStringAsync(string connectionString, int connectionPoolSize, TimeSpan? connectionIdleTimeout)
 {
     DeviceClient client;
     if (connectionPoolSize > 0)
     {
         var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings
         {
             MaxPoolSize = unchecked ((uint)connectionPoolSize),
             Pooling = connectionPoolSize > 0
         };
         if (connectionIdleTimeout.HasValue)
         {
             amqpConnectionPoolSettings.ConnectionIdleTimeout = connectionIdleTimeout.Value;
         }
         var transportSettings = new ITransportSettings[]
         {
             new AmqpTransportSettings(TransportType.Amqp_Tcp_Only)
             {
                 AmqpConnectionPoolSettings = amqpConnectionPoolSettings
             },
             new AmqpTransportSettings(TransportType.Amqp_WebSocket_Only)
             {
                 AmqpConnectionPoolSettings = amqpConnectionPoolSettings
             }
         };
         client = DeviceClient.CreateFromConnectionString(connectionString, transportSettings);
     }
     else
     {
         client = DeviceClient.CreateFromConnectionString(connectionString);
     }
     try
     {
         await client.OpenAsync();
     }
     catch (IotHubException ex)
     {
         throw ComposeIotHubCommunicationException(ex);
     }
     return new IotHubClient(client);
 }
        static void ValidateLocalTransport(ITransportSettings settings)
        {
            MsmqEndpointManagement.Manage(settings.Address, q =>
                {
                    if (!q.Exists)
                    {
                        if (!settings.CreateIfMissing)
                            throw new TransportException(settings.Address.Uri,
                                "The transport does not exist and automatic creation is not enabled");

                        q.Create(settings.Transactional || settings.Address.IsTransactional);
                    }

                    if (settings.RequireTransactional)
                    {
                        if (!q.IsTransactional && (settings.Transactional || settings.Address.IsTransactional))
                            throw new TransportException(settings.Address.Uri,
                                "The transport is non-transactional but a transactional transport was requested");
                    }
                });
        }
 public IOutboundTransport BuildError(ITransportSettings settings)
 {
     return BuildOutbound(settings);
 }
        DefaultDelegatingHandler CreateTransportHandler(IotHubConnectionString iotHubConnectionString, ITransportSettings transportSetting)
        {
            switch (transportSetting.GetTransportType())
            {
                case TransportType.Amqp_WebSocket_Only:
                case TransportType.Amqp_Tcp_Only:
                    return new AmqpTransportHandler(iotHubConnectionString, transportSetting as AmqpTransportSettings);
                case TransportType.Http1:
                    return new HttpTransportHandler(iotHubConnectionString, transportSetting as Http1TransportSettings);
#if !WINDOWS_UWP && !NETMF
                case TransportType.Mqtt:
                    return new MqttTransportHandler(iotHubConnectionString, transportSetting as MqttTransportSettings);
#endif
                default:
                    throw new InvalidOperationException("Unsupported Transport Setting {0}".FormatInvariant(transportSetting));
            }
        }