Esempio n. 1
0
        async Task NonExistantHCEntityTest()
        {
            HybridConnectionListener listener = null;

            try
            {
                TestUtility.Log("Setting ConnectionStringBuilder.EntityPath to a new GUID");
                var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString)
                {
                    EntityPath = Guid.NewGuid().ToString()
                };
                var fakeEndpointConnectionString = fakeEndpointConnectionStringBuilder.ToString();

                listener = new HybridConnectionListener(fakeEndpointConnectionString);
                var client = new HybridConnectionClient(fakeEndpointConnectionString);
#if NET451
                await Assert.ThrowsAsync <EndpointNotFoundException>(() => listener.OpenAsync());

                await Assert.ThrowsAsync <EndpointNotFoundException>(() => client.CreateConnectionAsync());
#else
                await Assert.ThrowsAsync <RelayException>(() => listener.OpenAsync());

                await Assert.ThrowsAsync <RelayException>(() => client.CreateConnectionAsync());
#endif
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
Esempio n. 2
0
        private async Task InitializeDataChannel()
        {
            var dataChannelFactory = new HybridConnectionClient(_relay, _tokenProvider);

            var stream = await dataChannelFactory.CreateConnectionAsync();

            _log.Information("Relay: {relay}. New data channel is established", _relay);

            try
            {
                await _tunnelPreamble.WriteAsync(stream);

                EnsureDownlinkPump(stream);

                _canAcceptUntil = DateTime.UtcNow.Add(_ttl);
            }
            catch (AuthorizationFailedException e)
            {
                _log.Error(e, "Relay: {relay}. Authorization failed", _relay);
                CloseDataChannel();
                throw;
            }
            catch (Exception e)
            {
                _log.Error(e, "Relay: {relay}. Unable to establish data channel", _relay);
                CloseDataChannel();
                throw;
            }
        }
Esempio n. 3
0
        private static async Task RunAsync()
        {
            // Create a new hybrid connection client.
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var client        = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            // Initiate the connection.
            var relayConnection = await client.CreateConnectionAsync();

            Console.WriteLine("Enter lines of text to send to the server with ENTER");
            var reader = new StreamReader(relayConnection);
            var writer = new StreamWriter(relayConnection)
            {
                AutoFlush = true
            };

            while (true)
            {
                var messageToSend = Console.ReadLine();
                if (string.IsNullOrEmpty(messageToSend))
                {
                    break;
                }

                await writer.WriteLineAsync(messageToSend);

                var textFromListener = await reader.ReadLineAsync();

                Console.WriteLine(textFromListener);
            }

            await relayConnection.CloseAsync(CancellationToken.None);
        }
        static async Task TestStreaming(HybridConnectionListener listener, RelayConnectionStringBuilder connectionString, TraceSource traceSource)
        {
            traceSource.TraceInformation("Testing Streaming (WebSocket) mode");
            RunAcceptPump(listener);

            var client       = new HybridConnectionClient(connectionString.ToString());
            var requestBytes = Encoding.UTF8.GetBytes("<data>Request payload from sender</data>");
            HybridConnectionStream stream = await client.CreateConnectionAsync();

            string connectionName = $"S:HybridConnectionStream({stream.TrackingContext.TrackingId})";

            RelayTraceSource.TraceInfo($"{connectionName} initiated");
            RunConnectionPump(stream, connectionName);
            for (int i = 0; i < 2; i++)
            {
                await stream.WriteAsync(requestBytes, 0, requestBytes.Length);

                RelayTraceSource.TraceVerbose($"{connectionName} wrote {requestBytes.Length} bytes");
            }

            using (var closeCts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
            {
                RelayTraceSource.TraceVerbose($"{connectionName} closing");
                await stream.CloseAsync(closeCts.Token);

                RelayTraceSource.TraceInfo($"{connectionName} closed");
            }

            await Task.Delay(TimeSpan.FromMilliseconds(100));
        }
Esempio n. 5
0
        async Task NonExistantNamespaceTest(EndpointTestType endpointTestType)
        {
            HybridConnectionListener listener = null;

            try
            {
                TestUtility.Log("Setting ConnectionStringBuilder.Endpoint to 'sb://fakeendpoint.com'");

                var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString)
                {
                    Endpoint = new Uri("sb://fakeendpoint.com")
                };

                if (endpointTestType == EndpointTestType.Authenticated)
                {
                    fakeEndpointConnectionStringBuilder.EntityPath = Constants.AuthenticatedEntityPath;
                }
                else
                {
                    fakeEndpointConnectionStringBuilder.EntityPath = Constants.UnauthenticatedEntityPath;
                }

                var fakeEndpointConnectionString = fakeEndpointConnectionStringBuilder.ToString();

                listener = new HybridConnectionListener(fakeEndpointConnectionString);
                var client = new HybridConnectionClient(fakeEndpointConnectionString);

// TODO: Remove this once .NET Core supports inspecting the StatusCode/Description. https://github.com/dotnet/corefx/issues/13773
#if NET451
                await Assert.ThrowsAsync <EndpointNotFoundException>(() => listener.OpenAsync());

                await Assert.ThrowsAsync <EndpointNotFoundException>(() => client.CreateConnectionAsync());
#else
                await Assert.ThrowsAsync <RelayException>(() => listener.OpenAsync());

                await Assert.ThrowsAsync <RelayException>(() => client.CreateConnectionAsync());
#endif
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
Esempio n. 6
0
 public RecieveResponseFromRequest(string relayConnectionString, string relayName)
 {
     //https://docs.microsoft.com/en-us/azure/service-bus-relay/relay-hybrid-connections-dotnet-api-overview
     connectionStringBuilder = new RelayConnectionStringBuilder(relayConnectionString)
     {
         EntityPath = relayName
     };
     client         = new HybridConnectionClient(connectionStringBuilder.ToString());
     connectionTask = client.CreateConnectionAsync();
     this.relayName = relayName;
 }
        /// <summary>
        /// We run two concurrent loops on the connection. One reads input from the console and writes it to the connection
        /// with a stream writer. The other reads lines of input from the connection with a stream reader and writes them to the console.
        /// Entering a blank line will shut down the write task after sending it to the server. The server will then cleanly shut down
        /// the connection which will terminate the read task.
        /// </summary>
        /// <returns></returns>
        protected async Task RunAsync()
        {
            // Initiate the connection
            _relayConnection = await _client.CreateConnectionAsync();

            var reads = GetReads(_relayConnection);

            // Wait for both tasks to complete
            await Task.WhenAll(reads);

            await _relayConnection.CloseAsync(CancellationToken.None);
        }
Esempio n. 8
0
    private static async Task RunAsync()
    {
        Console.WriteLine("Enter lines of text to send to the server with ENTER");
        // Create a new hybrid connection client
        var tokenProvider =
            TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
        var client = new HybridConnectionClient(new
                                                Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);
        // Initiate the connection
        var relayConnection = await client.CreateConnectionAsync();

        var reads = Task.Run(async() =>
        {
            var reader = new StreamReader(relayConnection);
            var writer = Console.Out;
            do
            {
                // Read a full line of UTF-8 text up to newline
                string line = await reader.ReadLineAsync();
                // if the string is empty or null, we are done.
                if (String.IsNullOrEmpty(line))
                {
                    break;
                }
                // Write to the console
                await writer.WriteLineAsync(line);
            } while (true);
        });
        // Read from the console and write to the hybrid connection
        var writes = Task.Run(async() =>
        {
            var reader = Console.In;
            var writer = new StreamWriter(relayConnection)
            {
                AutoFlush = true
            };
            do
            {
                // Read a line form the console
                string line = await reader.ReadLineAsync();
                await writer.WriteLineAsync(line);
                if (String.IsNullOrEmpty(line))
                {
                    break;
                }
            } while (true);
        });
        await Task.WhenAll(reads, writes);

        await
        relayConnection.CloseAsync(CancellationToken.None);
    }
Esempio n. 9
0
        public async Task OpenAsync(CancellationToken token)
        {
            if (_connection != null)
            {
                throw new InvalidOperationException("Connection already open");
            }

            _connection = await _client.CreateConnectionAsync();

            token.ThrowIfCancellationRequested();

            IsOpen = true;
        }
        void EnsureConnection()
        {
            lock (connectLock)
            {
                if (dataChannel == null)
                {
                    multiplexedOutputStream = new ThrottledQueueBufferedStream(10);

                    QueueBufferedStream multiplexedInputStream = new QueueBufferedStream();

                    dataChannelFactory = new HybridConnectionClient(endpointVia, tokenProvider);
                    dataChannel        = dataChannelFactory.CreateConnectionAsync().GetAwaiter().GetResult();

                    try
                    {
                        var preambleWriter = new BinaryWriter(dataChannel);
                        preambleWriter.Write("np:" + toPipe);

                        rawInputPump = new StreamBufferWritePump(dataChannel, multiplexedInputStream.Write);
                        rawInputPump.BeginRunPump(RawInputPumpCompleted, false);

                        inputPump = new MultiplexConnectionInputPump(multiplexedInputStream.Read, CorrelateConnection, null);
                        inputPump.Run(false);

                        outputPump = new StreamBufferWritePump(multiplexedOutputStream, WriteToDataChannel);
                        outputPump.BeginRunPump(MultiplexPumpCompleted, null);
                    }
                    catch (AuthorizationFailedException af)
                    {
                        Trace.TraceError("Authorization failed: {0}", af.Message);
                        if (dataChannel != null)
                        {
                            DataChannelClose();
                            dataChannel = null;
                        }
                        throw;
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Unable to establish data channel: {0}", ex.Message);
                        if (dataChannel != null)
                        {
                            DataChannelClose();
                            dataChannel = null;
                        }
                        throw;
                    }
                }
            }
        }
Esempio n. 11
0
        private static async Task RunAsync()
        {
            Console.WriteLine("Enter lines of text to send to the server with ENTER");


            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var client        = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);


            var relayConnection = await client.CreateConnectionAsync();

            var reads = Task.Run(async() => {
                var reader = new StreamReader(relayConnection);
                var writer = Console.Out;
                do
                {
                    string line = await reader.ReadLineAsync();

                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }

                    await writer.WriteLineAsync(line);
                }while (true);
            });

            var writes = Task.Run(async() => {
                var reader = Console.In;
                var writer = new StreamWriter(relayConnection)
                {
                    AutoFlush = true
                };
                do
                {
                    string line = await reader.ReadLineAsync();
                    await writer.WriteLineAsync(line);
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                }while (true);
            });

            await Task.WhenAll(reads, writes);

            await relayConnection.CloseAsync(CancellationToken.None);
        }
Esempio n. 12
0
        async Task NonExistantNamespaceTest(EndpointTestType endpointTestType)
        {
            string badAddress = $"sb://fakeendpoint.{Guid.NewGuid()}.com";
            HybridConnectionListener listener = null;

            try
            {
                TestUtility.Log($"Setting ConnectionStringBuilder.Endpoint to '{badAddress}'");

                var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString)
                {
                    Endpoint = new Uri(badAddress)
                };

                if (endpointTestType == EndpointTestType.Authenticated)
                {
                    fakeEndpointConnectionStringBuilder.EntityPath = Constants.AuthenticatedEntityPath;
                }
                else
                {
                    fakeEndpointConnectionStringBuilder.EntityPath = Constants.UnauthenticatedEntityPath;
                }

                var fakeEndpointConnectionString = fakeEndpointConnectionStringBuilder.ToString();

                listener = new HybridConnectionListener(fakeEndpointConnectionString);
                var client = new HybridConnectionClient(fakeEndpointConnectionString);

                TestUtility.Log($"Opening Listener");
                var relayException = await Assert.ThrowsAsync <RelayException>(() => listener.OpenAsync());

                TestUtility.Log($"Received Exception {relayException.ToStringWithoutCallstack()}");
                Assert.True(relayException.IsTransient, "Listener.Open() should return a transient Exception");

                TestUtility.Log($"Opening Client");
                relayException = await Assert.ThrowsAsync <RelayException>(() => client.CreateConnectionAsync());

                TestUtility.Log($"Received Exception {relayException.ToStringWithoutCallstack()}");
                Assert.True(relayException.IsTransient, "Client.Open() should return a transient Exception");
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
Esempio n. 13
0
        public async Task ExecuteAsync(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);

            Entity    entity    = (Entity)context.InputParameters["Target"];
            GisObject gisObject = new GisObject
            {
                Latitude  = (double)entity["Latitude"],
                Longitude = (double)entity["Longitude"]
            };

            // Create a new hybrid connection client
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key);
            var client        = new HybridConnectionClient(new Uri($"sb://{relayNamespace}/{connectionName}"), tokenProvider);

            // Initiate the connection
            var relayConnection = await client.CreateConnectionAsync();

            // Bi-directional sync of GIS data:
            //   1. Send a GIS object to the relay
            //   2. Receive a GIS object with the resolved address and update the entity
            //   3. Close the relay connection
            await new Task(
                () => SendToRelay(relayConnection, gisObject)
                .ContinueWith(async(t) =>
            {
                GisObject resolved = await ReadFromRelay(relayConnection);
                ShowAddress(resolved);
            })
                .ContinueWith(async(t) => await relayConnection.CloseAsync(CancellationToken.None))
                .Start());

            void ShowAddress(GisObject resolved)
            {
                var addr = resolved.Address;

                entity["Address"] = $"{addr.Line}, {addr.ZipCode} {addr.City}, {addr.Country}";
                service.Update(entity);
            }
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            HybridConnectionClient        client = new HybridConnectionClient("Endpoint=sb://relayzs.servicebus.windows.net/;SharedAccessKeyName=sas;SharedAccessKey=WBhKG1Fb51sYz4I1Nsv/mZsLhnru+O08YQxeq+SyRfo=;EntityPath=hybirdconn1");
            Task <HybridConnectionStream> task   = client.CreateConnectionAsync();

            while (!task.IsCompleted)
            {
            }
            HybridConnectionStream stream = task.Result;
            StreamWriter           writer = new StreamWriter(stream);
            StreamReader           reader = new StreamReader(stream);

            writer.WriteLine("Hello Server!");
            writer.Flush();
            String line = reader.ReadLine();

            Console.WriteLine(line);
            reader.Close();
            writer.Close();
        }
Esempio n. 15
0
        private HybridConnectionStream CreateConnection()
        {
            if (null == _hybridConnectionStream)
            {
                lock (_syncRoot)
                {
                    if (null == _hybridConnectionStream)
                    {
                        try
                        {
                            _hybridConnectionStream = _hybridConnectionClient.CreateConnectionAsync().Result;
                        }
                        catch (Exception e)
                        {
                            _logger.LogError(e, $"Unable to create hybrid connection for {_relayNamespace}/{_connectionName}");
                        }
                    }
                }
            }

            return(_hybridConnectionStream);
        }
Esempio n. 16
0
        public async Task ExecuteAsync(ParcelTrackingEntity parcel)
        {
            GisObject gisObject = new GisObject
            {
                Latitude  = parcel.Latitude,
                Longitude = parcel.Longitude
            };

            // Create a new hybrid connection client
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key);
            var client        = new HybridConnectionClient(new Uri($"sb://{relayNamespace}/{connectionName}"), tokenProvider);

            // Initiate the connection
            var relayConnection = await client.CreateConnectionAsync();

            // Bi-directional sync of GIS data:
            //   1. Send a GIS object to the relay
            //   2. Receive a GIS object with the resolved address and update the entity
            //   3. Close the relay connection
            await new Task(
                () => SendToRelay(relayConnection, gisObject)
                .ContinueWith(async(t) =>
            {
                GisObject resolved = await ReadFromRelay(relayConnection);
                ShowAddress(resolved);
            })
                .ContinueWith(async(t) => await relayConnection.CloseAsync(CancellationToken.None))
                .Start());

            void ShowAddress(GisObject resolved)
            {
                var addr = resolved.Address;

                parcel.Address = $"{addr.Line}, {addr.ZipCode} {addr.City}, {addr.Country}";
                Update(parcel); // Update the tracking information in the system
            }
        }
Esempio n. 17
0
        async Task NonExistantNamespaceTest(EndpointTestType endpointTestType)
        {
            HybridConnectionListener listener = null;

            try
            {
                TestUtility.Log("Setting ConnectionStringBuilder.Endpoint to 'sb://fakeendpoint.com'");

                var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString)
                {
                    Endpoint = new Uri("sb://fakeendpoint.com")
                };

                if (endpointTestType == EndpointTestType.Authenticated)
                {
                    fakeEndpointConnectionStringBuilder.EntityPath = Constants.AuthenticatedEntityPath;
                }
                else
                {
                    fakeEndpointConnectionStringBuilder.EntityPath = Constants.UnauthenticatedEntityPath;
                }

                var fakeEndpointConnectionString = fakeEndpointConnectionStringBuilder.ToString();

                listener = new HybridConnectionListener(fakeEndpointConnectionString);
                var client = new HybridConnectionClient(fakeEndpointConnectionString);

                await Assert.ThrowsAsync <EndpointNotFoundException>(() => listener.OpenAsync());

                await Assert.ThrowsAsync <EndpointNotFoundException>(() => client.CreateConnectionAsync());
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
Esempio n. 18
0
        private static async Task RunAsync()
        {
            Console.BackgroundColor = ConsoleColor.Yellow;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Client ready");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("Enter lines of text to send to the server with ENTER");

            // Create a new hybrid connection client
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, myKey);
            var client        = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            // Initiate the connection
            var relayConnection = await client.CreateConnectionAsync();

            try {
                // We run two conucrrent loops on the connection. One
                // reads input from the console and writes it to the connection
                // with a stream writer. The other reads lines of input from the
                // connection with a stream reader and writes them to the console.
                // Entering a blank line will shut down the write task after
                // sending it to the server. The server will then cleanly shut down
                // the connection which will terminate the read task.

                var reads = Task.Run(async() => {
                    // Initialize the stream reader over the connection
                    var reader = new StreamReader(relayConnection);
                    var writer = Console.Out;

                    do
                    {
                        // Read a full line of UTF-8 text up to newline
                        string line = await reader.ReadLineAsync();
                        // if the string is empty or null, we are done.
                        if (String.IsNullOrEmpty(line))
                        {
                            break;
                        }
                        // Write to the console
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        await writer.WriteLineAsync(line);
                        Console.ForegroundColor = ConsoleColor.White;
                    }while (true);
                });

                // Read from the console and write to the hybrid connection
                var writes = Task.Run(async() => {
                    var reader = Console.In;
                    var writer = new StreamWriter(relayConnection)
                    {
                        AutoFlush = true
                    };
                    do
                    {
                        // Read a line form the console
                        string line = await reader.ReadLineAsync();
                        // Write the line out, also when it's empty
                        await writer.WriteLineAsync(line);
                        // Quit when the line was empty
                        if (String.IsNullOrEmpty(line))
                        {
                            break;
                        }
                    }while (true);
                });

                // Wait for both tasks to complete
                await Task.WhenAll(reads, writes);

                await relayConnection.CloseAsync(CancellationToken.None);
            }
            catch (Exception ex)
            {
                Console.WriteLine("\n\nAn error occurred trying to reach the server:\n" + ex.InnerException);
                Console.WriteLine("Hit ENTER to exit");
                Console.ReadLine();
            }
        }
Esempio n. 19
0
        static async Task RunAsync(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("client [ns] [hc] [keyname] [key]");
                return;
            }

            Console.WriteLine("Enter lines of text to send to the server with ENTER");

            var ns      = args[0];
            var hc      = args[1];
            var keyname = args[2];
            var key     = args[3];

            // Create a new hybrid connection client
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname, key);
            var client        = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", ns, hc)), tokenProvider);

            // Initiate the connection
            var relayConnection = await client.CreateConnectionAsync();

            // We run two conucrrent loops on the connection. One
            // reads input from the console and writes it to the connection
            // with a stream writer. The other reads lines of input from the
            // connection with a stream reader and writes them to the console.
            // Entering a blank line will shut down the write task after
            // sending it to the server. The server will then cleanly shut down
            // the connection will will terminate the read task.

            var reads = Task.Run(async() => {
                // initialize the stream reader over the connection
                var reader = new StreamReader(relayConnection);
                var writer = Console.Out;
                do
                {
                    // read a full line of UTF-8 text up to newline
                    string line = await reader.ReadLineAsync();
                    // if the string is empty or null, we are done.
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                    // write to the console
                    await writer.WriteLineAsync(line);
                }while (true);
            });

            // read from the console and write to the hybrid connection
            var writes = Task.Run(async() => {
                var reader = Console.In;
                var writer = new StreamWriter(relayConnection)
                {
                    AutoFlush = true
                };
                do
                {
                    // read a line form the console
                    string line = await reader.ReadLineAsync();
                    // write the line out, also when it's empty
                    await writer.WriteLineAsync(line);
                    // quit when the line was empty
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                }while (true);
            });

            // wait for both tasks to complete
            await Task.WhenAll(reads, writes);

            await relayConnection.CloseAsync(CancellationToken.None);
        }
Esempio n. 20
0
        async Task ClientNonExistantHybridConnectionTest()
        {
            TestUtility.Log("Setting ConnectionStringBuilder.EntityPath to a new GUID");
            var fakeEndpointConnectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString)
            {
                EntityPath = Guid.NewGuid().ToString()
            };

            var client = new HybridConnectionClient(fakeEndpointConnectionStringBuilder.ToString());

            // Endpoint does not exist. TrackingId:GUID_G52, SystemTracker:sb://contoso.servicebus.windows.net/GUID, Timestamp:5/7/2018 5:51:25 PM
            var exception = await Assert.ThrowsAsync <EndpointNotFoundException>(() => client.CreateConnectionAsync());

            Assert.Contains("Endpoint does not exist", exception.Message);
            Assert.Contains(fakeEndpointConnectionStringBuilder.EntityPath, exception.Message);
        }
Esempio n. 21
0
        async Task ClientAuthenticationFailureTest()
        {
            var badAuthConnectionString = new RelayConnectionStringBuilder(this.ConnectionString)
            {
                EntityPath = Constants.AuthenticatedEntityPath
            };

            if (!string.IsNullOrEmpty(badAuthConnectionString.SharedAccessKeyName))
            {
                badAuthConnectionString.SharedAccessKey += "BAD";
            }
            else if (!string.IsNullOrEmpty(badAuthConnectionString.SharedAccessSignature))
            {
                badAuthConnectionString.SharedAccessSignature += "BAD";
            }

            var client = new HybridConnectionClient(badAuthConnectionString.ToString());

            // The token has an invalid signature. TrackingId:[Guid]_G63, SystemTracker:sb://contoso.servicebus.windows.net/authenticated, Timestamp:5/7/2018 5:20:05 PM
            var exception = await Assert.ThrowsAsync <AuthorizationFailedException>(() => client.CreateConnectionAsync());

            Assert.Contains("token", exception.Message);
            Assert.Contains(badAuthConnectionString.EntityPath, exception.Message, StringComparison.OrdinalIgnoreCase);
        }
Esempio n. 22
0
        RelayClintObservableInitializeAsync(
            string relayNamespace,
            string connectionName,
            string keyName,
            string key)
        {
            if (_isInitialized)
            {
                throw new RelayClientException("Relay client can only be initialized once. Create a new instance, if multiple clients are needed.");
            }

            _isInitialized = true;

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key);
            var client        = new HybridConnectionClient(new Uri($"sb://{relayNamespace}/{connectionName}"), tokenProvider);

            // Initiate the connection.
            _relayConnection = await client.CreateConnectionAsync();

            _writer = new StreamWriter(_relayConnection)
            {
                AutoFlush = true
            };

            var reader = new StreamReader(_relayConnection);

            var readerObservable = Observable.FromAsync(reader.ReadLineAsync);

            var observableMessages = Observable.Create <string>(obs =>
            {
                var disposableReader = Observable.While(
                    () => true,
                    readerObservable)
                                       .Subscribe(stringLine =>
                {
                    Debug.WriteLine(stringLine);
                    // If there's no input data, signal that
                    // you will no longer send data on this connection.
                    // Then, break out of the processing loop.
                    if (string.IsNullOrEmpty(stringLine))
                    {
                        obs.OnCompleted();
                    }

                    obs.OnNext(stringLine);
                },
                                                  ex =>
                {
                    Debug.WriteLine(ex.ToString());

                    if (ex is IOException)
                    {
                        // Catch an I/O exception. This likely occurred when
                        // the client disconnected.
                    }
                    else
                    {
                        obs.OnError(ex);
                    }
                },
                                                  obs.OnCompleted);

                return(new CompositeDisposable(
                           disposableReader,
                           Disposable.Create(() =>
                {
                    reader?.Dispose();
                    _writer?.Dispose();
                    _relayConnection?.Dispose();
                })));
            }).Publish().RefCount();

            return(observableMessages);
        }
Esempio n. 23
0
        static async Task RunAsync(string[] args)
        {
            Console.WriteLine("Enter lines of text to send to the server with ENTER");

            // Create a new hybrid connection client
            var client = new HybridConnectionClient("Endpoint=sb://vcrelay.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=lCl9YQGV+c/1SikptN9UaeGS8WoHBY5WlgxvhdS+83s="
                                                    , "demohc");


            // Initiate the connection
            var relayConnection = await client.CreateConnectionAsync();

            // We run two conucrrent loops on the connection. One
            // reads input from the console and writes it to the connection
            // with a stream writer. The other reads lines of input from the
            // connection with a stream reader and writes them to the console.
            // Entering a blank line will shut down the write task after
            // sending it to the server. The server will then cleanly shut down
            // the connection will will terminate the read task.

            var reads = Task.Run(async() => {
                // initialize the stream reader over the connection
                var reader = new StreamReader(relayConnection);
                var writer = Console.Out;
                do
                {
                    // read a full line of UTF-8 text up to newline
                    string line = await reader.ReadLineAsync();
                    // if the string is empty or null, we are done.
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                    // write to the console
                    await writer.WriteLineAsync(line);
                }while (true);
            });

            // read from the console and write to the hybrid connection
            var writes = Task.Run(async() => {
                var reader = Console.In;
                var writer = new StreamWriter(relayConnection)
                {
                    AutoFlush = true
                };
                do
                {
                    // read a line form the console
                    string line = await reader.ReadLineAsync();
                    // write the line out, also when it's empty
                    await writer.WriteLineAsync(line);
                    // quit when the line was empty
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                }while (true);
            });

            // wait for both tasks to complete
            await Task.WhenAll(reads, writes);

            await relayConnection.CloseAsync(CancellationToken.None);
        }
Esempio n. 24
0
        internal static async Task VerifySendAsync(RelayConnectionStringBuilder connectionString, int number, string httpMethod, string requestData, TraceSource traceSource)
        {
            Uri hybridHttpUri = new Uri($"https://{connectionString.Endpoint.GetComponents(UriComponents.HostAndPort, UriFormat.SafeUnescaped)}/{connectionString.EntityPath}");
            var tokenProvider = GetTokenProvider(connectionString);

            if (string.Equals("WS", httpMethod, StringComparison.OrdinalIgnoreCase) ||
                string.Equals("WEBSOCKET", httpMethod, StringComparison.OrdinalIgnoreCase))
            {
                var client       = new HybridConnectionClient(connectionString.ToString());
                var requestBytes = Encoding.UTF8.GetBytes(requestData ?? string.Empty);
                HybridConnectionStream stream = await client.CreateConnectionAsync();

                string connectionName = $"S:HybridConnectionStream({stream.TrackingContext.TrackingId})";
                RelayTraceSource.TraceInfo($"{connectionName} initiated");
                RunConnectionPump(stream, connectionName);
                for (int i = 0; i < number; i++)
                {
                    await stream.WriteAsync(requestBytes, 0, requestBytes.Length);

                    RelayTraceSource.TraceVerbose($"{connectionName} wrote {requestBytes.Length} bytes");
                }

                await Task.Delay(TimeSpan.FromSeconds(1));

                using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)))
                {
                    RelayTraceSource.TraceVerbose($"{connectionName} closing");
                    await stream.CloseAsync(cts.Token);

                    RelayTraceSource.TraceInfo($"{connectionName} closed");
                }

                return;
            }

            string token = null;

            if (tokenProvider != null)
            {
                token = (await tokenProvider.GetTokenAsync(hybridHttpUri.AbsoluteUri, TimeSpan.FromDays(2))).TokenString;
            }

            var stopwatch = new Stopwatch();

            using (var client = new HttpClient {
                BaseAddress = hybridHttpUri
            })
            {
                client.DefaultRequestHeaders.ExpectContinue = false;

                for (int i = 0; i < number; i++)
                {
                    stopwatch.Restart();
                    var httpRequest = new HttpRequestMessage();
                    if (token != null)
                    {
                        httpRequest.Headers.Add("ServiceBusAuthorization", token);
                    }

                    httpRequest.Method = new HttpMethod(httpMethod);
                    if (requestData != null)
                    {
                        httpRequest.Content = new StringContent(requestData);
                    }

                    LogHttpRequest(httpRequest, client, traceSource);
                    using (HttpResponseMessage response = await client.SendAsync(httpRequest))
                    {
                        LogHttpResponse(response, traceSource);
                    }

                    traceSource.TraceInformation($"Elapsed:  {stopwatch.ElapsedMilliseconds} ms");
                }
            }
        }
Esempio n. 25
0
        private static async Task RunAsync()
        {
            Console.WriteLine("Enter lines of text to send to the server with ENTER");

            // Create a new hybrid connection client
            var client = new HybridConnectionClient(ConnectionString);

            // Initiate the connection
            var relayConnection = await client.CreateConnectionAsync();

            // We run two conucrrent loops on the connection. One
            // reads input from the console and writes it to the connection
            // with a stream writer. The other reads lines of input from the
            // connection with a stream reader and writes them to the console.
            // Entering a blank line will shut down the write task after
            // sending it to the server. The server will then cleanly shut down
            // the connection which will terminate the read task.

            var reads = Task.Run(async() => {
                // Initialize the stream reader over the connection
                var reader = new StreamReader(relayConnection);
                var writer = Console.Out;
                do
                {
                    // Read a full line of UTF-8 text up to newline
                    string line = await reader.ReadLineAsync();
                    // If the string is empty or null, we are done.
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                    // Write to the console
                    await writer.WriteLineAsync(line);
                }while (true);
            });

            // Read from the console and write to the hybrid connection
            var writes = Task.Run(async() => {
                var reader = Console.In;
                var writer = new StreamWriter(relayConnection)
                {
                    AutoFlush = true
                };
                do
                {
                    // Read a line form the console
                    string line = await reader.ReadLineAsync();
                    // Write the line out, also when it's empty
                    await writer.WriteLineAsync(line);
                    // Quit when the line was empty
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                }while (true);
            });

            // Wait for both tasks to complete
            await Task.WhenAll(reads, writes);

            await relayConnection.CloseAsync(CancellationToken.None);
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("server [ns] [hc] [keyname] [key]");
                return;
            }

            var ns      = args[0];
            var hc      = args[1];
            var keyname = args[2];
            var key     = args[3];

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname, key);
            var sendAddress   = new Uri($"sb://{ns}/{hc}");
            var relayClient   = new HybridConnectionClient(sendAddress, tokenProvider);

            try
            {
                var relayConnection = relayClient.CreateConnectionAsync().GetAwaiter().GetResult();

                TTransport        transport = new TStreamTransport(relayConnection, relayConnection);
                TProtocol         protocol  = new TBinaryProtocol(transport);
                Calculator.Client client    = new Calculator.Client(protocol);

                transport.Open();
                try
                {
                    client.ping();
                    Console.WriteLine("ping()");

                    int sum = client.add(1, 1);
                    Console.WriteLine("1+1={0}", sum);

                    Work work = new Work();

                    work.Op   = Operation.DIVIDE;
                    work.Num1 = 1;
                    work.Num2 = 0;
                    try
                    {
                        int quotient = client.calculate(1, work);
                        Console.WriteLine("Whoa we can divide by 0");
                    }
                    catch (InvalidOperation io)
                    {
                        Console.WriteLine("Invalid operation: " + io.Why);
                    }

                    work.Op   = Operation.SUBTRACT;
                    work.Num1 = 15;
                    work.Num2 = 10;
                    try
                    {
                        int diff = client.calculate(1, work);
                        Console.WriteLine("15-10={0}", diff);
                    }
                    catch (InvalidOperation io)
                    {
                        Console.WriteLine("Invalid operation: " + io.Why);
                    }

                    SharedStruct log = client.getStruct(1);
                    Console.WriteLine("Check log: {0}", log.Value);
                }
                finally
                {
                    transport.Close();
                }
            }
            catch (TApplicationException x)
            {
                Console.WriteLine(x.StackTrace);
            }
        }
        private static async Task RunAsync()
        {
            Console.WriteLine("Enter lines of text to send to the server with ENTER");

            // Create a new hybrid connection client.
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var client        = new HybridConnectionClient(new Uri(String.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            // Initiate the connection.
            var relayConnection = await client.CreateConnectionAsync();

            // Run two concurrent loops on the connection. One
            // reads input from the console and then writes it to the connection
            // with a stream writer. The other reads lines of input from the
            // connection with a stream reader and then writes them to the console.
            // Entering a blank line shuts down the write task after
            // sending it to the server. The server then cleanly shuts down
            // the connection, which terminates the read task.

            var reads = Task.Run(async() => {
                // Initialize the stream reader over the connection.
                var reader = new StreamReader(relayConnection);
                var writer = Console.Out;
                do
                {
                    // Read a full line of UTF-8 text up to newline.
                    string line = await reader.ReadLineAsync();
                    // If the string is empty or null, you are done.
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                    // Write to the console.
                    await writer.WriteLineAsync(line);
                }while (true);
            });

            // Read from the console and write to the hybrid connection.
            var writes = Task.Run(async() => {
                var reader = Console.In;
                var writer = new StreamWriter(relayConnection)
                {
                    AutoFlush = true
                };
                do
                {
                    // Read a line from the console.
                    string line = await reader.ReadLineAsync();
                    // Write the line out, also when it's empty.
                    await writer.WriteLineAsync(line);
                    // Quit when the line is empty.
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }
                }while (true);
            });

            // Wait for both tasks to finish.
            await Task.WhenAll(reads, writes);

            await relayConnection.CloseAsync(CancellationToken.None);
        }
Esempio n. 28
0
        Task <HybridConnectionStream> ConnectClientSocketAsync(Uri address)
        {
            var client = new HybridConnectionClient(address, tokenProvider);

            return(client.CreateConnectionAsync());
        }
Esempio n. 29
0
        static async Task Main(string[] args)
        {
            string hostAddress;
            string hybridConnectionName;
            string clientId     = null;
            string tenantId     = null;
            string clientSecret = null;
            RbacAuthenticationOption option;

            if (args.Length == 2)
            {
                option               = RbacAuthenticationOption.ManagedIdentity;
                hostAddress          = args[0];
                hybridConnectionName = args[1];
            }
            else if (args.Length == 3)
            {
                option               = RbacAuthenticationOption.UserAssignedIdentity;
                hostAddress          = args[0];
                hybridConnectionName = args[1];
                clientId             = args[2];
            }
            else if (args.Length == 5)
            {
                option               = RbacAuthenticationOption.AAD;
                hostAddress          = args[0];
                hybridConnectionName = args[1];
                clientId             = args[2];
                tenantId             = args[3];
                clientSecret         = args[4];
            }
            else
            {
                Console.WriteLine("Please run with parameters of the following format for the corresponding RBAC authentication method:");
                Console.WriteLine("System Managed Identity: [HostAddress] [HybridConnectionName]");
                Console.WriteLine("User Assigned Identity: [HostAddress] [HybridConnectionName] [ClientId]");
                Console.WriteLine("Azure Active Directory:  [HostAddress] [HybridConnectionName] [ClientId] [TenantId] [ClientSecret]");
                Console.WriteLine("Press <Enter> to exit...");
                Console.ReadLine();
                return;
            }

            TokenProvider tokenProvider = null;

            switch (option)
            {
            case RbacAuthenticationOption.ManagedIdentity:
                tokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
                break;

            case RbacAuthenticationOption.UserAssignedIdentity:
                var managedCredential = new ManagedIdentityCredential(clientId);
                tokenProvider = TokenProvider.CreateManagedIdentityTokenProvider(managedCredential);
                break;

            case RbacAuthenticationOption.AAD:
                tokenProvider = GetAadTokenProvider(clientId, tenantId, clientSecret);
                break;
            }

            var hybridConnectionUri           = new Uri($"{hostAddress}/{hybridConnectionName}");
            HybridConnectionListener listener = null;

            try
            {
                // The HybridConnection should be already created through Azure Portal or other means
                Console.WriteLine($"Creating the Relay listener instance with RBAC option: {option}");
                listener = new HybridConnectionListener(hybridConnectionUri, tokenProvider);

                await listener.OpenAsync(TimeSpan.FromSeconds(10));

                Console.WriteLine("Created and connected the Relay listener instance.");

                Console.WriteLine($"Creating the Relay sender instance with RBAC option: {option}");
                var sender             = new HybridConnectionClient(hybridConnectionUri, tokenProvider);
                var createSenderTask   = sender.CreateConnectionAsync();
                var listenerAcceptTask = listener.AcceptConnectionAsync();
                using (HybridConnectionStream senderStream = await createSenderTask)
                    using (HybridConnectionStream listenerStream = await listenerAcceptTask)
                    {
                        Console.WriteLine("Created and connected the Relay sender instance.");
                        var senderCloseTask = senderStream.CloseAsync(CancellationToken.None);
                        await listenerStream.CloseAsync(CancellationToken.None);

                        await senderCloseTask;
                    }

                // Configure a RequestHandler for HTTP request/response mode
                listener.RequestHandler = (context) =>
                {
                    context.Response.StatusCode = HttpStatusCode.OK;
                    using (var sw = new StreamWriter(context.Response.OutputStream))
                    {
                        sw.WriteLine("hello!");
                    }

                    // The context must be closed to complete sending the response
                    context.Response.Close();
                };

                Console.WriteLine($"Sending a HTTP request by setting the token in request header with RBAC option: {option}");
                SecurityToken token = await tokenProvider.GetTokenAsync(hybridConnectionUri.AbsoluteUri, TimeSpan.FromMinutes(30));

                var request = new HttpRequestMessage();
                request.Headers.Add(HttpRequestHeader.Authorization.ToString(), token.TokenString);
                var requestUri = new UriBuilder(hybridConnectionUri)
                {
                    Scheme = "https"
                }.Uri;
                using (HttpClient client = new HttpClient {
                    BaseAddress = requestUri
                })
                {
                    using (var response = await client.SendAsync(request))
                    {
                        Console.WriteLine($"Response status code: {response.StatusCode}. Response reason phrase: {response.ReasonPhrase}");
                    }
                }

                Console.WriteLine($"Sending a HTTP request by setting the token in query string with RBAC option: {option}");
                token = await tokenProvider.GetTokenAsync(hybridConnectionUri.AbsoluteUri, TimeSpan.FromMinutes(30));

                request    = new HttpRequestMessage();
                requestUri = new UriBuilder(requestUri)
                {
                    Query = $"?sb-hc-token={token.TokenString}"
                }.Uri;
                using (HttpClient client = new HttpClient {
                    BaseAddress = requestUri
                })
                {
                    using (var response = await client.SendAsync(request))
                    {
                        Console.WriteLine($"Response status code: {response.StatusCode}. Response reason phrase: {response.ReasonPhrase}");
                    }
                }

                Console.WriteLine("Press <Enter> to exit...");
                Console.ReadLine();
            }
            finally
            {
                if (listener != null)
                {
                    await listener.CloseAsync();
                }
            }
        }