Esempio n. 1
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
        /// </summary>
        ///
        /// <param name="fullyQualifiedNamespace">The fully qualified Service Bus namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
        /// <param name="credential">The Azure managed identity credential to use for authorization.  Access controls may be specified by the Service Bus namespace or the requested Service Bus entity, depending on Azure configuration.</param>
        /// <param name="options">A set of options to apply when configuring the connection.</param>
        internal ServiceBusConnection(
            string fullyQualifiedNamespace,
            TokenCredential credential,
            ServiceBusClientOptions options)
        {
            Argument.AssertWellFormedServiceBusNamespace(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
            Argument.AssertNotNull(credential, nameof(credential));

            ValidateConnectionOptions(options);
            switch (credential)
            {
            case SharedAccessSignatureCredential _:
                break;

            case ServiceBusSharedKeyCredential sharedKeyCredential:
                credential = sharedKeyCredential.AsSharedAccessSignatureCredential(BuildAudienceResource(options.TransportType, fullyQualifiedNamespace, EntityPath));
                break;
            }

            var tokenCredential = new ServiceBusTokenCredential(credential, BuildAudienceResource(options.TransportType, fullyQualifiedNamespace, EntityPath));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            TransportType           = options.TransportType;
            RetryOptions            = options.RetryOptions;

#pragma warning disable CA2214 // Do not call overridable methods in constructors. This internal method is virtual for testing purposes.
            _innerClient = CreateTransportClient(tokenCredential, options);
#pragma warning restore CA2214 // Do not call overridable methods in constructors
        }
Esempio n. 2
0
        static SecurityContext AuthenticateClient(TransportClient client)
        {
            TransportStream stream = client.GetStream();

            byte[] clientToken;
            byte[] serverToken;

            // create client context
            SecurityContext clientContext = authModule.CreateSecurityContext(clientCredentials, SecurityContextAttributes.Identify, null, out clientToken);

            while (true)
            {
                if (clientToken != null)
                {
                    // send client token to server
                    SendBuffer(stream, clientToken);
                }

                if (clientContext.State == SecurityContextState.Completed)
                {
                    // authentication completed
                    break;
                }

                // receive server token
                serverToken = ReceiveBuffer(stream);

                // update security context
                authModule.UpdateSecurityContext(clientContext, SecurityContextAttributes.Identify, serverToken, out clientToken);
            }

            return(clientContext);
        }
        /// <summary>
        /// 创建客户端。
        /// </summary>
        /// <param name="endPoint">终结点。</param>
        /// <returns>传输客户端实例。</returns>
        public async Task <ITransportClient> CreateClientAsync(EndPoint endPoint)
        {
            var key = endPoint;

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"准备为服务端地址:{key}创建客户端。");
            }
            try
            {
                return(await _clients.GetOrAdd(key, k => new Lazy <Task <ITransportClient> >(async() =>
                {
                    // 客户端对象
                    var bootstrap = _bootstrap;
                    // 异步连接返回channel
                    var channel = await bootstrap.ConnectAsync(k);
                    var messageListener = new MessageListener();
                    // 设置监听
                    channel.GetAttribute(messageListenerKey).Set(messageListener);
                    // 实例化发送者
                    var messageSender = new DotNettyMessageClientSender(_transportMessageEncoder, channel);
                    // 设置channel属性
                    channel.GetAttribute(messageSenderKey).Set(messageSender);
                    channel.GetAttribute(origEndPointKey).Set(k);
                    // 创建客户端
                    var client = new TransportClient(messageSender, messageListener, _logger, _serviceExecutor);
                    return client;
                })).Value);
            }
            catch
            {
                _clients.TryRemove(key, out var value);
                throw;
            }
        }
        /// <summary>
        ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
        /// </summary>
        ///
        /// <param name="fullyQualifiedNamespace">The fully qualified Service Bus namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
        /// <param name="credential">The Azure managed identity credential to use for authorization.  Access controls may be specified by the Service Bus namespace or the requested Service Bus entity, depending on Azure configuration.</param>
        /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
        ///
        internal ServiceBusConnection(
            string fullyQualifiedNamespace,
            TokenCredential credential,
            ServiceBusClientOptions connectionOptions = default)
        {
            Argument.AssertNotNullOrEmpty(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
            Argument.AssertNotNull(credential, nameof(credential));

            connectionOptions = connectionOptions?.Clone() ?? new ServiceBusClientOptions();
            ValidateConnectionOptions(connectionOptions);
            switch (credential)
            {
            case SharedAccessSignatureCredential _:
                break;

            case ServiceBusSharedKeyCredential sharedKeyCredential:
                credential = sharedKeyCredential.AsSharedAccessSignatureCredential(BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, EntityName));
                break;
            }

            var tokenCredential = new ServiceBusTokenCredential(credential, BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, EntityName));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            TransportType           = connectionOptions.TransportType;

            _innerClient = CreateTransportClient(tokenCredential, connectionOptions);
        }
Esempio n. 5
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string to use for connecting to the Service Bus namespace.</param>
        /// <param name="options">A set of options to apply when configuring the connection.</param>
        ///
        /// <remarks>
        ///   If the connection string is copied from the Service Bus entity itself, it will contain the name of the desired Service Bus entity,
        ///   and can be used directly without passing the  name="entityName" />.  The name of the Service Bus entity should be
        ///   passed only once, either as part of the connection string or separately.
        /// </remarks>
        ///
        internal ServiceBusConnection(
            string connectionString,
            ServiceBusClientOptions options)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
            Argument.AssertNotNull(options, nameof(options));

            options = options.Clone();

            ValidateConnectionOptions(options);
            var builder = new ServiceBusConnectionStringBuilder(connectionString);

            FullyQualifiedNamespace = builder.FullyQualifiedNamespace;
            TransportType           = options.TransportType;
            EntityPath = builder.EntityName;
            var sharedAccessSignature = new SharedAccessSignature
                                        (
                BuildAudienceResource(options.TransportType, FullyQualifiedNamespace, EntityPath),
                builder.SasKeyName,
                builder.SasKey
                                        );

            var sharedCredentials = new SharedAccessSignatureCredential(sharedAccessSignature);
            var tokenCredentials  = new ServiceBusTokenCredential(
                sharedCredentials,
                BuildAudienceResource(options.TransportType, FullyQualifiedNamespace, EntityPath));

            _innerClient = CreateTransportClient(tokenCredentials, options);
        }
Esempio n. 6
0
 public HttpPilotClient()
 {
     _client            = new TransportClient();
     _marshaller        = new Marshaller(new CallServiceAdapter(_client));
     _unmarshaller      = new Unmarshaller(this);
     _transportCallback = new CallbackReceiverAdapter(_unmarshaller, CallbackError);
 }
Esempio n. 7
0
        public void OnAcceptClient(TransportClient transportClient)
        {
            Console.WriteLine("Broadcaster.OnAcceptClient");
            Client client = new Client(transportClient, SessionManager.Instance);

            clients.TryAdd(transportClient, client);
        }
Esempio n. 8
0
        public void TestTransportServer()
        {
            ICodec <string> codec = new StringCodec();

            BlockingCollection <string> queue = new BlockingCollection <string>();
            List <string> events = new List <string>();

            IPEndPoint endpoint      = new IPEndPoint(_localIpAddress, 0);
            var        remoteHandler = Observer.Create <TransportEvent <string> >(tEvent => queue.Add(tEvent.Data));

            using (var server = new TransportServer <string>(endpoint, remoteHandler, codec, _tcpPortProvider))
            {
                server.Run();

                IPEndPoint remoteEndpoint = new IPEndPoint(_localIpAddress, server.LocalEndpoint.Port);
                using (var client = new TransportClient <string>(remoteEndpoint, codec, _tcpClientFactory))
                {
                    client.Send("TestTransportServer - 1");
                    client.Send("TestTransportServer - 2");
                    client.Send("TestTransportServer - 3");

                    events.Add(queue.Take());
                    events.Add(queue.Take());
                    events.Add(queue.Take());
                }
            }

            Assert.Equal(3, events.Count);
            Assert.Equal("TestTransportServer - 1", events[0]);
            Assert.Equal("TestTransportServer - 2", events[1]);
            Assert.Equal("TestTransportServer - 3", events[2]);
        }
Esempio n. 9
0
        // Sets up given transport client type
        public void SetTransport(TransportType transport)
        {
            // Stop existing transport client if any, when nulled out it will be collected
            // by garbage collecter after existing connections have been terminated.
            if (transportClient != null)
            {
                transportClient.Stop();
                transportClient = null;
            }

            // Create new transport client instance
            switch (transport)
            {
            case TransportType.SHORTPOLLING:
                Func <string> getShortPollingEndpoint = () => { return(GetHttpPollingEndpoint("shortpolling")); };
                transportClient = new ShortPolling(getShortPollingEndpoint, GetHttpHeaders, ProcessMessagesString);
                break;

            case TransportType.LONGPOLLING:
                Func <string> getLongPollingEndpoint = () => { return(GetHttpPollingEndpoint("longpolling")); };
                transportClient = new LongPolling(getLongPollingEndpoint, GetHttpHeaders, ProcessMessagesString);
                break;

            default:
                throw new Exception("Invalid transport type: " + transport);
            }
        }
Esempio n. 10
0
        public void TestTransportServerEvent()
        {
            ICodec <TestEvent> codec = new TestEventCodec();
            int port = NetworkUtils.GenerateRandomPort(6000, 7000);

            BlockingCollection <TestEvent> queue = new BlockingCollection <TestEvent>();
            List <TestEvent> events = new List <TestEvent>();

            IPEndPoint endpoint      = new IPEndPoint(IPAddress.Any, port);
            var        remoteHandler = Observer.Create <TransportEvent <TestEvent> >(tEvent => queue.Add(tEvent.Data));

            using (var server = new TransportServer <TestEvent>(endpoint, remoteHandler, codec))
            {
                server.Run();

                IPEndPoint remoteEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
                using (var client = new TransportClient <TestEvent>(remoteEndpoint, codec))
                {
                    client.Send(new TestEvent("Hello"));
                    client.Send(new TestEvent(", "));
                    client.Send(new TestEvent("World!"));

                    events.Add(queue.Take());
                    events.Add(queue.Take());
                    events.Add(queue.Take());
                }
            }

            Assert.AreEqual(3, events.Count);
        }
Esempio n. 11
0
        private StoreClient GetMockStoreClient()
        {
            Mock <IAddressResolver> mockAddressCache    = this.GetMockAddressCache();
            AddressSelector         addressSelector     = new AddressSelector(mockAddressCache.Object, Protocol.Tcp);
            TransportClient         mockTransportClient = this.GetMockTransportClient();
            ISessionContainer       sessionContainer    = new SessionContainer(string.Empty);

            StoreReader storeReader = new StoreReader(mockTransportClient, addressSelector, sessionContainer);

            Mock <IAuthorizationTokenProvider> mockAuthorizationTokenProvider = new Mock <IAuthorizationTokenProvider>();

            // setup max replica set size on the config reader
            ReplicationPolicy replicationPolicy = new ReplicationPolicy();

            replicationPolicy.MaxReplicaSetSize = 4;
            Mock <IServiceConfigurationReader> mockServiceConfigReader = new Mock <IServiceConfigurationReader>();

            mockServiceConfigReader.SetupGet(x => x.UserReplicationPolicy).Returns(replicationPolicy);

            return(new StoreClient(
                       mockAddressCache.Object,
                       sessionContainer,
                       mockServiceConfigReader.Object,
                       mockAuthorizationTokenProvider.Object,
                       Protocol.Tcp,
                       mockTransportClient));
        }
            internal TransportClientWrapper(
                TransportClient client,
                Action <Uri, ResourceOperation, DocumentServiceRequest> interceptor,
                bool injectCpuMonitor = false)
            {
                Debug.Assert(client != null);
                Debug.Assert(interceptor != null);

                if (injectCpuMonitor)
                {
                    CpuMonitor.OverrideRefreshInterval(TimeSpan.FromMilliseconds(100));
                    this.cpuMonitor = new CpuMonitor();
                    this.cpuMonitor.Start();
                    Stopwatch watch = Stopwatch.StartNew();

                    // Artifically burning some CPU to generate CPU load history
                    CpuLoadHistory cpuLoadHistory = null;
                    while ((cpuLoadHistory = this.cpuMonitor.GetCpuLoad()) == null ||
                           cpuLoadHistory.ToString() == emptyCpuLoadHistoryText)
                    {
                        Task.Delay(10).Wait();
                    }
                }
                this.baseClient  = client;
                this.interceptor = interceptor;
            }
Esempio n. 13
0
        public void TransportClient_DoesThrowFor404WithReadSessionNotAvailable_WithUseStatusCodeForFailures()
        {
            using (DocumentServiceRequest request =
                       DocumentServiceRequest.Create(
                           OperationType.Query,
                           ResourceType.Document,
                           ExceptionlessTests.resourceUri,
                           new MemoryStream(Encoding.UTF8.GetBytes("content1")),
                           AuthorizationTokenType.PrimaryMasterKey,
                           null))
            {
                request.UseStatusCodeForFailures = true;
                StoreResponse mockStoreResponse404 = new StoreResponse();
                mockStoreResponse404.ResponseHeaderNames = new string[1] {
                    WFConstants.BackendHeaders.SubStatus
                };
                mockStoreResponse404.ResponseHeaderValues = new string[1] {
                    ((int)SubStatusCodes.ReadSessionNotAvailable).ToString()
                };
                mockStoreResponse404.Status = (int)HttpStatusCode.NotFound;


                TransportClient.ThrowServerException(
                    string.Empty,
                    mockStoreResponse404,
                    ExceptionlessTests.resourceUri,
                    Guid.NewGuid(),
                    request);
            }
        }
Esempio n. 14
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="EventHubConnection"/> class.
        /// </summary>
        ///
        /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
        /// <param name="eventHubName">The name of the specific Event Hub to associate the connection with.</param>
        /// <param name="credential">The Azure managed identity credential to use for authorization.  Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
        /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
        ///
        public EventHubConnection(string fullyQualifiedNamespace,
                                  string eventHubName,
                                  TokenCredential credential,
                                  EventHubConnectionOptions connectionOptions = default)
        {
            Argument.AssertWellFormedEventHubsNamespace(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
            Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
            Argument.AssertNotNull(credential, nameof(credential));

            connectionOptions = connectionOptions?.Clone() ?? new EventHubConnectionOptions();
            ValidateConnectionOptions(connectionOptions);

            switch (credential)
            {
            case SharedAccessSignatureCredential _:
                break;

            case EventHubSharedKeyCredential sharedKeyCredential:
                credential = sharedKeyCredential.AsSharedAccessSignatureCredential(BuildConnectionAudience(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName));
                break;
            }

            var tokenCredential = new EventHubTokenCredential(credential, BuildConnectionAudience(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            EventHubName            = eventHubName;
            Options = connectionOptions;

#pragma warning disable CA2214 // Do not call overridable methods in constructors. This internal method is virtual for testing purposes.
            InnerClient = CreateTransportClient(fullyQualifiedNamespace, eventHubName, tokenCredential, connectionOptions);
#pragma warning restore CA2214 // Do not call overridable methods in constructors.
        }
 public HttpPilotClient(IMarshallingFactory factory)
 {
     _client            = new TransportClient();
     _marshaller        = factory.GetMarshaller(new CallServiceAdapter(_client));
     _unmarshaller      = factory.GetUnmarshaller(this);
     _transportCallback = new CallbackReceiverAdapter(_unmarshaller, CallbackError);
 }
        /// <summary>
        ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
        /// </summary>
        ///
        /// <param name="fullyQualifiedNamespace">The fully qualified Service Bus namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
        /// <param name="credential">The Azure managed identity credential to use for authorization.  Access controls may be specified by the Service Bus namespace or the requested Service Bus entity, depending on Azure configuration.</param>
        /// <param name="options">A set of options to apply when configuring the connection.</param>
        ///
        internal ServiceBusConnection(
            string fullyQualifiedNamespace,
            TokenCredential credential,
            ServiceBusClientOptions options)
        {
            Argument.AssertWellFormedServiceBusNamespace(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
            Argument.AssertNotNull(credential, nameof(credential));

            options = options?.Clone() ?? new ServiceBusClientOptions();
            ValidateConnectionOptions(options);
            switch (credential)
            {
            case SharedAccessSignatureCredential _:
                break;

            case ServiceBusSharedKeyCredential sharedKeyCredential:
                credential = sharedKeyCredential.AsSharedAccessSignatureCredential(BuildAudienceResource(options.TransportType, fullyQualifiedNamespace, EntityPath));
                break;
            }

            var tokenCredential = new ServiceBusTokenCredential(credential, BuildAudienceResource(options.TransportType, fullyQualifiedNamespace, EntityPath));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            TransportType           = options.TransportType;
            Options      = options;
            RetryOptions = options.RetryOptions;

            _innerClient = CreateTransportClient(tokenCredential, options);
        }
Esempio n. 17
0
        private StoreClient GetMockStoreClient()
        {
            Mock <IAddressResolver> mockAddressCache    = this.GetMockAddressCache();
            AddressSelector         addressSelector     = new AddressSelector(mockAddressCache.Object, Protocol.Tcp);
            TransportClient         mockTransportClient = this.GetMockTransportClient();
            ISessionContainer       sessionContainer    = new SessionContainer(string.Empty);

            StoreReader storeReader = new StoreReader(mockTransportClient, addressSelector, new AddressEnumerator(), sessionContainer);

            Mock <IAuthorizationTokenProvider> mockAuthorizationTokenProvider = new Mock <IAuthorizationTokenProvider>();

            mockAuthorizationTokenProvider.Setup(provider => provider.AddSystemAuthorizationHeaderAsync(
                                                     It.IsAny <DocumentServiceRequest>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.FromResult(0));

            // setup max replica set size on the config reader
            ReplicationPolicy replicationPolicy = new ReplicationPolicy();

            replicationPolicy.MaxReplicaSetSize = 4;
            Mock <IServiceConfigurationReader> mockServiceConfigReader = new Mock <IServiceConfigurationReader>();

            mockServiceConfigReader.SetupGet(x => x.UserReplicationPolicy).Returns(replicationPolicy);

            return(new StoreClient(
                       mockAddressCache.Object,
                       sessionContainer,
                       mockServiceConfigReader.Object,
                       mockAuthorizationTokenProvider.Object,
                       Protocol.Tcp,
                       mockTransportClient));
        }
Esempio n. 18
0
        /// <summary>
        /// 创建客户端。
        /// </summary>
        /// <param name="endPoint">终结点。</param>
        /// <returns>传输客户端实例。</returns>
        public ITransportClient CreateClient(EndPoint endPoint)
        {
            var key = endPoint.ToString();

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.Debug($"准备为服务端地址:{key}创建客户端。");
            }
            return(_clients.GetOrAdd(key
                                     , k => new Lazy <ITransportClient>(() =>
            {
                var messageListener = new MessageListener();

                _bootstrap.Handler(new ActionChannelInitializer <ISocketChannel>(c =>
                {
                    var pipeline = c.Pipeline;
                    pipeline.AddLast(new LengthFieldPrepender(4));
                    pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4));
                    pipeline.AddLast(new DefaultChannelHandler(messageListener, _serializer));
                }));

                var bootstrap = _bootstrap;
                var channel = bootstrap.ConnectAsync(endPoint);
                var messageSender = new DotNettyMessageClientSender(_serializer, channel);
                var client = new TransportClient(messageSender, messageListener, _logger, _serializer);
                return client;
            }
                                                                        )).Value);
        }
Esempio n. 19
0
        /// <summary>
        /// 创建客户端。
        /// </summary>
        /// <param name="endPoint">终结点。</param>
        /// <returns>传输客户端实例。</returns>
        public ITransportClient CreateClient(EndPoint endPoint)
        {
            var key = endPoint;

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"准备为服务端地址:{key}创建客户端。");
            }
            try
            {
                return(_clients.GetOrAdd(key
                                         , k => new Lazy <ITransportClient>(() =>
                {
                    var bootstrap = _bootstrap;
                    var channel = bootstrap.ConnectAsync(k).Result;

                    var messageListener = new MessageListener();
                    channel.GetAttribute(messageListenerKey).Set(messageListener);
                    var messageSender = new DotNettyMessageClientSender(_transportMessageEncoder, channel);
                    channel.GetAttribute(messageSenderKey).Set(messageSender);
                    channel.GetAttribute(origEndPointKey).Set(k);

                    var client = new TransportClient(messageSender, messageListener, _logger, _serviceExecutor);
                    return client;
                }
                                                                            )).Value);
            }
            catch
            {
                _clients.TryRemove(key, out var value);
                throw;
            }
        }
        /// <summary>
        ///   Initializes a new instance of the <see cref="EventHubConnection"/> class.
        /// </summary>
        ///
        /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
        /// <param name="eventHubName">The name of the specific Event Hub to associate the connection with.</param>
        /// <param name="credential">The Azure managed identity credential to use for authorization.  Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
        /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
        ///
        public EventHubConnection(string fullyQualifiedNamespace,
                                  string eventHubName,
                                  TokenCredential credential,
                                  EventHubConnectionOptions connectionOptions = default)
        {
            Argument.AssertNotNullOrEmpty(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
            Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
            Argument.AssertNotNull(credential, nameof(credential));

            connectionOptions = connectionOptions?.Clone() ?? new EventHubConnectionOptions();
            ValidateConnectionOptions(connectionOptions);

            switch (credential)
            {
            case SharedAccessSignatureCredential _:
                break;

            case EventHubSharedKeyCredential sharedKeyCredential:
                credential = sharedKeyCredential.AsSharedAccessSignatureCredential(BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName));
                break;
            }

            var tokenCredential = new EventHubTokenCredential(credential, BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            EventHubName            = eventHubName;
            Options = connectionOptions;

            InnerClient = CreateTransportClient(fullyQualifiedNamespace, eventHubName, tokenCredential, connectionOptions);
        }
Esempio n. 21
0
 public InjectableTransportClientMock(TransportClient transportClient,
                                      string connectionString,
                                      EventHubConnectionOptions clientOptions = default) : base(connectionString, clientOptions)
 {
     TransportClient = transportClient;
     SetTransportClient(transportClient);
 }
        public void TransportClient_DoesNotThrowFor429_WithUseStatusCodeFor429()
        {
            using (DocumentServiceRequest request =
                       DocumentServiceRequest.Create(
                           OperationType.Query,
                           ResourceType.Document,
                           ExceptionlessTests.resourceUri,
                           new MemoryStream(Encoding.UTF8.GetBytes("content1")),
                           AuthorizationTokenType.PrimaryMasterKey,
                           null))
            {
                request.UseStatusCodeFor429 = true;
                StoreResponse mockStoreResponse429 = new StoreResponse
                {
                    Status = (int)StatusCodes.TooManyRequests
                };

                TransportClient.ThrowServerException(
                    string.Empty,
                    mockStoreResponse429,
                    ExceptionlessTests.resourceUri,
                    Guid.NewGuid(),
                    request);
            }
        }
Esempio n. 23
0
        public void TestTransportSenderStage()
        {
            ICodec <string> codec    = new StringCodec();
            IPEndPoint      endpoint = new IPEndPoint(_localIpAddress, 0);

            List <string> events = new List <string>();
            BlockingCollection <string> queue = new BlockingCollection <string>();

            // Server echoes the message back to the client
            var remoteHandler = Observer.Create <TransportEvent <string> >(tEvent => tEvent.Link.Write(tEvent.Data));

            using (TransportServer <string> server = new TransportServer <string>(endpoint, remoteHandler, codec, _tcpPortProvider))
            {
                server.Run();

                var        clientHandler  = Observer.Create <TransportEvent <string> >(tEvent => queue.Add(tEvent.Data));
                IPEndPoint remoteEndpoint = new IPEndPoint(_localIpAddress, server.LocalEndpoint.Port);
                using (var client = new TransportClient <string>(remoteEndpoint, codec, clientHandler))
                {
                    client.Send("Hello");
                    client.Send(", ");
                    client.Send(" World");

                    events.Add(queue.Take());
                    events.Add(queue.Take());
                    events.Add(queue.Take());
                }
            }

            Assert.Equal(3, events.Count);
            Assert.Equal(events[0], "Hello");
            Assert.Equal(events[1], ", ");
            Assert.Equal(events[2], " World");
        }
Esempio n. 24
0
        public void TestTransportServerEvent()
        {
            ICodec <TestEvent> codec = new TestEventCodec();

            BlockingCollection <TestEvent> queue = new BlockingCollection <TestEvent>();
            List <TestEvent> events = new List <TestEvent>();

            IPEndPoint endpoint      = new IPEndPoint(_localIpAddress, 0);
            var        remoteHandler = Observer.Create <TransportEvent <TestEvent> >(tEvent => queue.Add(tEvent.Data));

            using (var server = new TransportServer <TestEvent>(endpoint, remoteHandler, codec, _tcpPortProvider))
            {
                server.Run();

                IPEndPoint remoteEndpoint = new IPEndPoint(_localIpAddress, server.LocalEndpoint.Port);
                using (var client = new TransportClient <TestEvent>(remoteEndpoint, codec))
                {
                    client.Send(new TestEvent("Hello"));
                    client.Send(new TestEvent(", "));
                    client.Send(new TestEvent("World!"));

                    events.Add(queue.Take());
                    events.Add(queue.Take());
                    events.Add(queue.Take());
                }
            }

            Assert.Equal(3, events.Count);
            Assert.Equal(events[0].Message, "Hello");
            Assert.Equal(events[1].Message, ", ");
            Assert.Equal(events[2].Message, "World!");
        }
Esempio n. 25
0
    /**
     * Is invoked when application launches. Connects the Client to the Server
     */
    public void OnUserConnect(string address, int port)
    {
        ChannelDispatcher dispatcher = new ChannelDispatcher();

        this.transport = new TransportClient(dispatcher);

        sessionClient = new SessionClient(this.transport, this);
        dispatcher.RegisterChannel(sessionClient);

        surfaceClient = new SurfaceClient(this, this.transport);
        dispatcher.RegisterChannel(surfaceClient);

        inputClient = new InputClient(this.transport);
        dispatcher.RegisterChannel(inputClient);

        try
        {
            this.transport.Connect(address, port);
            DisplayStatusText("Welcome! You are connected to Screenary server at " + address + " : " + port);
        }
        catch (TransportException e)
        {
            ExceptionDialog exception = new ExceptionDialog("Operation Fail", "Could not connect to Screenary server at "
                                                            + address + " : " + port + "\nVerify connections.");
        }
    }
Esempio n. 26
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string to use for connecting to the Service Bus namespace.</param>
        /// <param name="entityName">The name of the specific Service Bus entity to associate the connection with (if not contained in connectionString).</param>
        /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
        ///
        /// <remarks>
        ///   If the connection string is copied from the Service Bus entity itself, it will contain the name of the desired Service Bus entity,
        ///   and can be used directly without passing the <paramref name="entityName" />.  The name of the Service Bus entity should be
        ///   passed only once, either as part of the connection string or separately.
        /// </remarks>
        ///
        public ServiceBusConnection(
            string connectionString,
            string entityName,
            ServiceBusConnectionOptions connectionOptions)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));

            connectionOptions = connectionOptions?.Clone() ?? new ServiceBusConnectionOptions();

            ValidateConnectionOptions(connectionOptions);
            var builder = new ServiceBusConnectionStringBuilder(connectionString);

            var fullyQualifiedNamespace = builder.FullyQualifiedNamespace;

            if (string.IsNullOrEmpty(entityName))
            {
                entityName = builder.EntityName;
            }

            var sharedAccessSignature = new SharedAccessSignature
                                        (
                BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, entityName),
                builder.SasKeyName,
                builder.SasKey
                                        );

            var sharedCredentials = new SharedAccessSignatureCredential(sharedAccessSignature);
            var tokenCredentials  = new ServiceBusTokenCredential(sharedCredentials, BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, entityName));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            EntityName    = entityName;
            InnerClient   = CreateTransportClient(fullyQualifiedNamespace, entityName, tokenCredentials, connectionOptions);
            TransportType = connectionOptions.TransportType;
        }
Esempio n. 27
0
        public void TestTransportSenderStage()
        {
            ICodec <string> codec    = new StringCodec();
            int             port     = NetworkUtils.GenerateRandomPort(6000, 7000);
            IPEndPoint      endpoint = new IPEndPoint(IPAddress.Any, port);

            List <string> events = new List <string>();
            BlockingCollection <string> queue = new BlockingCollection <string>();

            // Server echoes the message back to the client
            var remoteHandler = Observer.Create <TransportEvent <string> >(tEvent => tEvent.Link.Write(tEvent.Data));

            using (TransportServer <string> server = new TransportServer <string>(endpoint, remoteHandler, codec))
            {
                server.Run();

                var        clientHandler  = Observer.Create <TransportEvent <string> >(tEvent => queue.Add(tEvent.Data));
                IPEndPoint remoteEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
                using (var client = new TransportClient <string>(remoteEndpoint, codec, clientHandler))
                {
                    client.Send("Hello");
                    client.Send(", ");
                    client.Send(" World");

                    events.Add(queue.Take());
                    events.Add(queue.Take());
                    events.Add(queue.Take());
                }
            }

            Assert.AreEqual(3, events.Count);
        }
        /// <summary>
        ///   Initializes a new instance of the <see cref="EventHubConnection"/> class.
        /// </summary>
        ///
        /// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the shared key properties are contained in this connection string, but not the Event Hub name.</param>
        /// <param name="eventHubName">The name of the specific Event Hub to associate the connection with.</param>
        /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
        ///
        /// <remarks>
        ///   If the connection string is copied from the Event Hub itself, it will contain the name of the desired Event Hub,
        ///   and can be used directly without passing the <paramref name="eventHubName" />.  The name of the Event Hub should be
        ///   passed only once, either as part of the connection string or separately.
        /// </remarks>
        ///
        public EventHubConnection(string connectionString,
                                  string eventHubName,
                                  EventHubConnectionOptions connectionOptions)
        {
            Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));

            connectionOptions = connectionOptions?.Clone() ?? new EventHubConnectionOptions();
            ValidateConnectionOptions(connectionOptions);

            ConnectionStringProperties connectionStringProperties = ConnectionStringParser.Parse(connectionString);

            ValidateConnectionProperties(connectionStringProperties, eventHubName, nameof(connectionString));

            var fullyQualifiedNamespace = connectionStringProperties.Endpoint.Host;

            if (string.IsNullOrEmpty(eventHubName))
            {
                eventHubName = connectionStringProperties.EventHubName;
            }

            var sharedAccessSignature = new SharedAccessSignature
                                        (
                BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName),
                connectionStringProperties.SharedAccessKeyName,
                connectionStringProperties.SharedAccessKey
                                        );

            var sharedCredentials = new SharedAccessSignatureCredential(sharedAccessSignature);
            var tokenCredentials  = new EventHubTokenCredential(sharedCredentials, BuildAudienceResource(connectionOptions.TransportType, fullyQualifiedNamespace, eventHubName));

            FullyQualifiedNamespace = fullyQualifiedNamespace;
            EventHubName            = eventHubName;
            Options     = connectionOptions;
            InnerClient = CreateTransportClient(fullyQualifiedNamespace, eventHubName, tokenCredentials, connectionOptions);
        }
Esempio n. 29
0
 public NameRegisterClient(TransportClient<NamingEvent> client,
                           BlockingCollection<NamingRegisterResponse> registerQueue,
                           BlockingCollection<NamingUnregisterResponse> unregisterQueue)
 {
     _client = client;
     _registerResponseQueue = registerQueue;
     _unregisterResponseQueue = unregisterQueue;
 }
Esempio n. 30
0
 /// <summary>
 /// Constructs a new NameLookupClient.
 /// </summary>
 /// <param name="client">The transport client used to connect to the NameServer</param>
 /// <param name="lookupQueue">The queue used to signal that a response
 /// has been received from the NameServer</param>
 /// <param name="getAllQueue">The queue used to signal that a GetAllResponse 
 /// has been received from the NameServer</param>
 public NameLookupClient(TransportClient<NamingEvent> client,
                         BlockingCollection<NamingLookupResponse> lookupQueue,
                         BlockingCollection<NamingGetAllResponse> getAllQueue)
 {
     _client = client;
     _lookupResponseQueue = lookupQueue;
     _getAllResponseQueue = getAllQueue;
 }
Esempio n. 31
0
 /// <summary>
 /// Constructs a new NameLookupClient.
 /// </summary>
 /// <param name="client">The transport client used to connect to the NameServer</param>
 /// <param name="lookupQueue">The queue used to signal that a response
 /// has been received from the NameServer</param>
 /// <param name="getAllQueue">The queue used to signal that a GetAllResponse
 /// has been received from the NameServer</param>
 public NameLookupClient(TransportClient <NamingEvent> client,
                         BlockingCollection <NamingLookupResponse> lookupQueue,
                         BlockingCollection <NamingGetAllResponse> getAllQueue)
 {
     _client = client;
     _lookupResponseQueue = lookupQueue;
     _getAllResponseQueue = getAllQueue;
 }
Esempio n. 32
0
 /// <summary>
 /// Creates an instance of the Device Provisioning Client.
 /// </summary>
 /// <param name="globalDeviceEndpoint">The global device endpoint host-name.</param>
 /// <param name="idScope">The IDScope for the Device Provisioning Service.</param>
 /// <param name="securityClient">The security client instance.</param>
 /// <param name="transport">The type of transport (e.g. HTTP, AMQP, MQTT).</param>
 /// <returns>An instance of the DPSDeviceClient</returns>
 public static ProvisioningDeviceClient Create(
     string globalDeviceEndpoint,
     string idScope,
     SecurityClient securityClient,
     TransportClient transport)
 {
     throw new System.NotImplementedException();
 }
Esempio n. 33
0
 public Session(TransportClient transport, ISessionResponseListener listener)
     : base(transport, listener)
 {
 }
Esempio n. 34
0
 public Surface(TransportClient transport)
     : base(transport)
 {
 }