Exemplo 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);
            }
        }
Exemplo n.º 2
0
        private static async Task RunAsync()
        {
            var cts = new CancellationTokenSource();

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

            listener.Connecting += (o, e) => { Console.WriteLine("Connecting ..."); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offine"); };
            listener.Online     += (o, e) => { Console.WriteLine("Onine"); };

            await listener.OpenAsync(cts.Token);

            Console.WriteLine("Server Listening ...");

            cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));

            new Task(() => Console.In.ReadLineAsync().ContinueWith((s) => { cts.Cancel(); })).Start();

            while (true)
            {
                var relayConnection = await listener.AcceptConnectionAsync();

                if (relayConnection == null)
                {
                    break;
                }

                ProcessMessagesOnConnection(relayConnection, cts);
            }

            await listener.CloseAsync(cts.Token);
        }
Exemplo n.º 3
0
        private static async Task RunAsync()
        {
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            // Subscribe to the status events.
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };

            // Provide an HTTP request handler
            listener.RequestHandler = ProcessRelayedHttpRequest;

            // Opening the listener establishes the control channel to
            // the Azure Relay service. The control channel is continuously
            // maintained, and is reestablished when connectivity is disrupted.
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
Exemplo n.º 4
0
        async Task ListenerShutdownWithPendingAcceptsTest(EndpointTestType endpointTestType)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = GetHybridConnectionListener(endpointTestType);
                var client = GetHybridConnectionClient(endpointTestType);

                TestUtility.Log($"Opening {listener}");
                await listener.OpenAsync(TimeSpan.FromSeconds(20));

                var acceptTasks = new List <Task <HybridConnectionStream> >(600);
                TestUtility.Log($"Calling listener.AcceptConnectionAsync() {acceptTasks.Capacity} times");
                for (int i = 0; i < acceptTasks.Capacity; i++)
                {
                    acceptTasks.Add(listener.AcceptConnectionAsync());
                    Assert.False(acceptTasks[i].IsCompleted);
                }

                TestUtility.Log($"Closing {listener}");
                await listener.CloseAsync(TimeSpan.FromSeconds(10));

                listener = null;
                for (int i = 0; i < acceptTasks.Count; i++)
                {
                    Assert.True(acceptTasks[i].Wait(TimeSpan.FromSeconds(5)));
                    Assert.Null(acceptTasks[i].Result);
                }
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
Exemplo n.º 5
0
        private static async Task RunAsync()
        {
            var cts           = new CancellationTokenSource();
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            // Subscribe to the status events
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };
            // Establish the control channel to the Azure Relay service
            await listener.OpenAsync(cts.Token);

            Console.WriteLine("Server listening");
            // Providing callback for cancellation token that will close the listener.
            cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));
            // Start a new thread that will continuously read the console.
            new Task(() =>
                     Console.In.ReadLineAsync().ContinueWith((s) => { cts.Cancel(); })).Start();
            // Accept the next available, pending connection request.
            while (true)
            {
                var relayConnection = await listener.AcceptConnectionAsync();

                if (relayConnection == null)
                {
                    break;
                }

                ProcessMessagesOnConnection(relayConnection, cts);
            }

// Close the listener after we exit the processing loop
            await listener.CloseAsync(cts.Token);
        }
Exemplo n.º 6
0
        public HybridConnectionListener CreateHybridListener(string hybridConnectionName, string responseMessage)
        {
            RelayConnectionStringBuilder connectionStringBuilder = new RelayConnectionStringBuilder(Connections.HybridRelayConnectionString)
            {
                EntityPath = hybridConnectionName
            };
            //var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(connectionStringBuilder.SharedAccessKeyName, connectionStringBuilder.SharedAccessKey);
            //var uri = new Uri(string.Format("https://{0}/{1}", connectionStringBuilder.Endpoint.Host, hybridConnectionName));
            var listener = new HybridConnectionListener(connectionStringBuilder.ToString());

            // Subscribe to the status events.
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK";
                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.Write(responseMessage);
                }

                // The context MUST be closed here
                context.Response.Close();
            };

            listener.OpenAsync().Wait();
            Console.WriteLine("Server listening");
            return(listener);
        }
Exemplo n.º 7
0
        private async Task OpenAsync()
        {
            var tokenProvider =
                TokenProvider.CreateSharedAccessSignatureTokenProvider(_heHybridConnectionSetting.KeyName,
                                                                       _heHybridConnectionSetting.Key);

            _listener = new HybridConnectionListener(
                new Uri(
                    $"sb://{_heHybridConnectionSetting.RelayNamespace}/{_heHybridConnectionSetting.ConnectionName}"),
                tokenProvider)
            {
                RequestHandler = context =>
                {
                    var content        = new StreamReader(context.Request.InputStream).ReadToEnd();
                    var eventGridEvent = JsonConvert.DeserializeObject <List <EventGridEvent> >(content);
                    _eventGridEvents.AddRange(eventGridEvent);
                }
            };
            await _listener.OpenAsync();

            while (!_stopThread)
            {
                await Task.Delay(500);
            }
        }
Exemplo n.º 8
0
        static async Task RunAsync(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("dotnet 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 listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", ns, hc)), tokenProvider);

            // TODO:
            // use this code (line 36) to hard code a specific proxy URL.
            //var webProxy = new WebProxy("http://192.168.1.140:808");

            // TODO:
            // use this code (line 40) to use the system settings for the user running the code. Lines 40, 41 were added to original sample
            var webProxy = HttpWebRequest.DefaultWebProxy;

            listener.Proxy = webProxy;

            // Subscribe to the status events.
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK";
                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine("hello client, this is server speaking!");
                }

                // The context MUST be closed here
                context.Response.Close();
            };

            // Opening the listener establishes the control channel to
            // the Azure Relay service. The control channel is continuously
            // maintained, and is reestablished when connectivity is disrupted.
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener
            await listener.CloseAsync();
        }
Exemplo n.º 9
0
        static async Task RunAsync(string[] args)
        {
            var ns      = "<your namespace url from shared access policy- just the fdqn no protocols>";
            var hc      = "<your hybrid connection name - can be found in portal under the relay>"; //This is the name for the current store - one per store to be cofigured when running the service in the store
            var keyname = "<shared access key name such as RootManageSharedAccessKey>";
            var key     = "<key value from the shared access policies>";

            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname, key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", ns, hc)), tokenProvider);

            // Subscribe to the status events.
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                var contextRequest            = context.Request;
                System.IO.Stream       body   = contextRequest.InputStream;
                System.IO.StreamReader reader = new System.IO.StreamReader(body, Encoding.UTF8);
                string targetUrl = reader.ReadToEnd();
                body.Close();

                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK";
                string result = "";

                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUrl);
                    request.Method    = "Get";
                    request.KeepAlive = true;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        result = sr.ReadToEnd();
                    }

                    Console.WriteLine(result);
                    sw.WriteLine(result);
                }

                context.Response.Close();
            };
            // Opening the listener establishes the control channel to
            // the Azure Relay service. The control channel is continuously
            // maintained, and is reestablished when connectivity is disrupted.
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener
            await listener.CloseAsync();
        }
Exemplo n.º 10
0
        async Task RawWebSocketSenderTest(EndpointTestType endpointTestType)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = GetHybridConnectionListener(endpointTestType);

                var clientWebSocket = new ClientWebSocket();
                var wssUri          = await GetWebSocketConnectionUri(endpointTestType);

                using (var cancelSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
                {
                    TestUtility.Log($"Opening {listener}");
                    await listener.OpenAsync(cancelSource.Token);

                    await clientWebSocket.ConnectAsync(wssUri, cancelSource.Token);

                    var listenerStream = await listener.AcceptConnectionAsync();

                    TestUtility.Log("Client and Listener are connected!");
                    Assert.Null(clientWebSocket.SubProtocol);

                    byte[] sendBuffer = this.CreateBuffer(1024, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                    await clientWebSocket.SendAsync(new ArraySegment <byte>(sendBuffer), WebSocketMessageType.Binary, true, cancelSource.Token);

                    TestUtility.Log($"clientWebSocket wrote {sendBuffer.Length} bytes");

                    byte[] readBuffer = new byte[sendBuffer.Length];
                    await this.ReadCountBytesAsync(listenerStream, readBuffer, 0, readBuffer.Length, TimeSpan.FromSeconds(30));

                    Assert.Equal(sendBuffer, readBuffer);

                    TestUtility.Log("Calling clientStream.CloseAsync");
                    var clientStreamCloseTask = clientWebSocket.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "From Test Code", cancelSource.Token);
                    TestUtility.Log("Reading from listenerStream");
                    int bytesRead = await this.SafeReadAsync(listenerStream, readBuffer, 0, readBuffer.Length);

                    TestUtility.Log($"listenerStream.Read returned {bytesRead} bytes");
                    Assert.Equal(0, bytesRead);

                    TestUtility.Log("Calling listenerStream.CloseAsync");
                    var   listenerStreamCloseTask = listenerStream.CloseAsync(cancelSource.Token);
                    await listenerStreamCloseTask;
                    TestUtility.Log("Calling listenerStream.CloseAsync completed");
                    await clientStreamCloseTask;
                    TestUtility.Log("Calling clientStream.CloseAsync completed");

                    TestUtility.Log($"Closing {listener}");
                    await listener.CloseAsync(TimeSpan.FromSeconds(10));

                    listener = null;
                }
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
        public async Task OpenAsync(CancellationToken cancelToken)
        {
            _listener.RequestHandler = ListenerRequestHandler;
            await _listener.OpenAsync(cancelToken);

            Console.WriteLine("Azure Service Bus is listening on \n\r\t{0}\n\rand routing requests to \n\r\t{1}\n\r\n\r", _listener.Address, _httpClient.BaseAddress);
            Console.WriteLine("Press [Enter] to exit");
        }
        public async Task OpenAsync(CancellationToken cancelToken)
        {
            listener.RequestHandler = (context) => this.RequestHandler(context);
            await listener.OpenAsync(cancelToken);

            Console.WriteLine($"Forwarding from {listener.Address} to {httpClient.BaseAddress}.");
            Console.WriteLine("utcTime, request, statusCode, durationMs");
        }
Exemplo n.º 13
0
        static async Task RunAsync(string[] args)
        {
            if (args.Length < 4)
            {
                Console.WriteLine("dotnet 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 listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", ns, hc)), tokenProvider);

            // Subscribe to the status events.
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };

            // Provide an HTTP request handler
            listener.RequestHandler = async(context) =>
            {
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                Console.WriteLine();
                Console.WriteLine("=====HEADERS=====");
                Console.WriteLine(context.Request.Headers.ToString());
                Console.WriteLine("=====BODY=====");
                using (var sr = new StreamReader(context.Request.InputStream))
                {
                    Console.WriteLine(await sr.ReadToEndAsync());
                }

                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK";
                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine("hello!");
                }

                // The context MUST be closed here
                context.Response.Close();
            };

            // Opening the listener establishes the control channel to
            // the Azure Relay service. The control channel is continuously
            // maintained, and is reestablished when connectivity is disrupted.
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener
            await listener.CloseAsync();
        }
Exemplo n.º 14
0
        async Task WriteLargeDataSetTest(EndpointTestType endpointTestType, int kilobytesToSend = 1024)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = GetHybridConnectionListener(endpointTestType);
                var client = GetHybridConnectionClient(endpointTestType);

                TestUtility.Log($"Opening {listener}");
                await listener.OpenAsync(TimeSpan.FromSeconds(30));

                var clientStream = await client.CreateConnectionAsync();

                var listenerStream = await listener.AcceptConnectionAsync();

                TestUtility.Log($"clientStream and listenerStream connected! {listenerStream}");

                byte[] sendBuffer = this.CreateBuffer(kilobytesToSend * 1024, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                byte[] readBuffer = new byte[sendBuffer.Length];

                TestUtility.Log($"Sending {sendBuffer.Length} bytes from client->listener");
                var sendTask = clientStream.WriteAsync(sendBuffer, 0, sendBuffer.Length);
                var readTask = this.ReadCountBytesAsync(listenerStream, readBuffer, 0, readBuffer.Length, TimeSpan.FromSeconds(30));

                await Task.WhenAll(sendTask, readTask);

                TestUtility.Log($"Sending and Reading complete");
                Assert.Equal(sendBuffer, readBuffer);

                TestUtility.Log($"Sending {sendBuffer.Length} bytes from listener->client");
                sendTask = listenerStream.WriteAsync(sendBuffer, 0, sendBuffer.Length);
                readTask = this.ReadCountBytesAsync(clientStream, readBuffer, 0, readBuffer.Length, TimeSpan.FromSeconds(30));

                await Task.WhenAll(sendTask, readTask);

                TestUtility.Log($"Sending and Reading complete");
                Assert.Equal(sendBuffer, readBuffer);

                TestUtility.Log("Calling clientStream.Shutdown");
                clientStream.Shutdown();
                int bytesRead = await this.SafeReadAsync(listenerStream, readBuffer, 0, readBuffer.Length);

                TestUtility.Log($"listenerStream.Read returned {bytesRead} bytes");
                Assert.Equal(0, bytesRead);

                TestUtility.Log("Calling listenerStream.Dispose");
                listenerStream.Dispose();

                TestUtility.Log("Calling clientStream.Dispose");
                clientStream.Dispose();
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
        async Task Verbs()
        {
            var endpointTestType = EndpointTestType.Authenticated;
            HybridConnectionListener listener = this.GetHybridConnectionListener(endpointTestType);

            try
            {
                RelayConnectionStringBuilder connectionString = GetConnectionStringBuilder(endpointTestType);
                Uri endpointUri = connectionString.Endpoint;

                TestUtility.Log("Calling HybridConnectionListener.Open");
                await listener.OpenAsync(TimeSpan.FromSeconds(30));

                Uri hybridHttpUri = new UriBuilder("https://", endpointUri.Host, endpointUri.Port, connectionString.EntityPath).Uri;
                using (var client = new HttpClient {
                    BaseAddress = hybridHttpUri
                })
                {
                    client.DefaultRequestHeaders.ExpectContinue = false;

                    HttpMethod[] methods = new HttpMethod[]
                    {
                        HttpMethod.Delete, HttpMethod.Get, HttpMethod.Head, HttpMethod.Options, HttpMethod.Post, HttpMethod.Put, HttpMethod.Trace
                    };

                    foreach (HttpMethod method in methods)
                    {
                        TestUtility.Log($"Testing HTTP Verb: {method}");
                        string actualMethod = string.Empty;
                        listener.RequestHandler = (context) =>
                        {
                            TestUtility.Log($"RequestHandler: {context.Request.HttpMethod} {context.Request.Url}");
                            actualMethod = context.Request.HttpMethod;
                            context.Response.Close();
                        };

                        var request = new HttpRequestMessage();
                        await AddAuthorizationHeader(connectionString, request, hybridHttpUri);

                        request.Method = method;
                        LogRequestLine(request, client);
                        using (HttpResponseMessage response = await client.SendAsync(request))
                        {
                            TestUtility.Log($"Response: HTTP/{response.Version} {(int)response.StatusCode} {response.ReasonPhrase}");
                            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                            Assert.Equal(method.Method, actualMethod);
                        }
                    }
                }

                await listener.CloseAsync(TimeSpan.FromSeconds(10));
            }
            finally
            {
                await SafeCloseAsync(listener);
            }
        }
        async Task EmptyRequestEmptyResponse(EndpointTestType endpointTestType)
        {
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60));
            HybridConnectionListener listener = this.GetHybridConnectionListener(endpointTestType);

            try
            {
                await listener.OpenAsync(cts.Token);

                listener.RequestHandler = async(context) =>
                {
                    TestUtility.Log($"RequestHandler: {context.Request.HttpMethod} {context.Request.Url}");
                    await context.Response.CloseAsync();
                };

                RelayConnectionStringBuilder connectionString = GetConnectionStringBuilder(endpointTestType);
                Uri endpointUri   = connectionString.Endpoint;
                Uri hybridHttpUri = new UriBuilder("https://", endpointUri.Host, endpointUri.Port, connectionString.EntityPath).Uri;

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

                    var getRequest = new HttpRequestMessage();
                    getRequest.Method = HttpMethod.Get;
                    await AddAuthorizationHeader(connectionString, getRequest, hybridHttpUri);

                    LogRequest(getRequest, client);
                    using (HttpResponseMessage response = await client.SendAsync(getRequest))
                    {
                        LogResponse(response);
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        Assert.Equal(0, response.Content.ReadAsStreamAsync().Result.Length);
                    }

                    var postRequest = new HttpRequestMessage();
                    postRequest.Method = HttpMethod.Post;
                    await AddAuthorizationHeader(connectionString, postRequest, hybridHttpUri);

                    LogRequest(postRequest, client);
                    using (HttpResponseMessage response = await client.SendAsync(postRequest))
                    {
                        LogResponse(response);
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        Assert.Equal(0, response.Content.ReadAsStreamAsync().Result.Length);
                    }
                }

                await listener.CloseAsync(cts.Token);
            }
            finally
            {
                await SafeCloseAsync(listener);
            }
        }
Exemplo n.º 17
0
        async Task ClientShutdownTest(EndpointTestType endpointTestType)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = GetHybridConnectionListener(endpointTestType);
                var client = GetHybridConnectionClient(endpointTestType);

                TestUtility.Log($"Opening {listener}");
                await listener.OpenAsync(TimeSpan.FromSeconds(30));

                var clientStream = await client.CreateConnectionAsync();

                var listenerStream = await listener.AcceptConnectionAsync();

                TestUtility.Log("Client and Listener HybridStreams are connected!");

                byte[] sendBuffer = this.CreateBuffer(1024, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                await clientStream.WriteAsync(sendBuffer, 0, sendBuffer.Length);

                TestUtility.Log($"clientStream wrote {sendBuffer.Length} bytes");

                byte[] readBuffer = new byte[sendBuffer.Length];
                await this.ReadCountBytesAsync(listenerStream, readBuffer, 0, readBuffer.Length, TimeSpan.FromSeconds(30));

                Assert.Equal(sendBuffer, readBuffer);

                TestUtility.Log("Calling clientStream.Shutdown");
                clientStream.Shutdown();
                int bytesRead = await this.SafeReadAsync(listenerStream, readBuffer, 0, readBuffer.Length);

                TestUtility.Log($"listenerStream.Read returned {bytesRead} bytes");
                Assert.Equal(0, bytesRead);

                TestUtility.Log("Calling listenerStream.Shutdown and Dispose");
                listenerStream.Shutdown();
                listenerStream.Dispose();
                bytesRead = await this.SafeReadAsync(clientStream, readBuffer, 0, readBuffer.Length);

                TestUtility.Log($"clientStream.Read returned {bytesRead} bytes");
                Assert.Equal(0, bytesRead);

                TestUtility.Log("Calling clientStream.Dispose");
                clientStream.Dispose();

                TestUtility.Log($"Closing {listener}");
                await listener.CloseAsync(TimeSpan.FromSeconds(10));

                listener = null;
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
Exemplo n.º 18
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);
            }
        }
Exemplo n.º 19
0
        private static async Task RunAsync()
        {
            // Create the listener
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var listener      = new HybridConnectionListener(new Uri($"sb://{RelayNamespace}/{ConnectionName}"), tokenProvider);

            // Subscribe to the status events
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Check service is offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Check service is online"); };

            // Create an array of credit status values
            var statuses = new List <string>
            {
                "Good",
                "Some issues",
                "Bad"
            };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Obtain the name from the request
                var reader        = new StreamReader(context.Request.InputStream);
                var requestedName = reader.ReadToEnd();
                Console.WriteLine("A request was received to check status for: " + requestedName);

                // Pick a status at random
                Random r     = new Random();
                var    index = r.Next(statuses.Count);

                // Formulate and send the response
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "Status check successful";

                using (var writer = new StreamWriter(context.Response.OutputStream))
                {
                    writer.WriteLine($"Status check for {requestedName}: {statuses[index]}");
                }

                // Close the context
                context.Response.Close();
            };

            // Open the listener
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
Exemplo n.º 20
0
        private static async Task RunAsync()
        {
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            // Subscribe to the status events.
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                if (context.Request.HttpMethod.Contains("POST"))
                {
                    // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                    context.Response.StatusCode        = HttpStatusCode.OK;
                    context.Response.StatusDescription = "OK";
                    var body = new StreamReader(context.Request.InputStream).ReadToEnd();
                    using (var sw = new StreamWriter(context.Response.OutputStream))
                    {
                        sw.WriteLine("hello");
                    }
                }

                if (context.Request.HttpMethod.Contains("GET"))
                {
                    // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                    context.Response.StatusCode        = HttpStatusCode.OK;
                    context.Response.StatusDescription = "OK";
                    using (var sw = new StreamWriter(context.Response.OutputStream))
                    {
                        sw.WriteLine("world!");
                    }
                }



                // The context MUST be closed here
                context.Response.Close();
            };

            // Opening the listener establishes the control channel to
            // the Azure Relay service. The control channel is continuously
            // maintained, and is reestablished when connectivity is disrupted.
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
Exemplo n.º 21
0
        async Task HybridConnectionTest(EndpointTestType endpointTestType, bool useBuiltInClientWebSocket)
        {
            HybridConnectionListener listener = null;

            try
            {
                listener = this.GetHybridConnectionListener(endpointTestType);
                listener.UseBuiltInClientWebSocket = useBuiltInClientWebSocket;
                var client = GetHybridConnectionClient(endpointTestType);
                client.UseBuiltInClientWebSocket = useBuiltInClientWebSocket;

                TestUtility.Log($"Opening {listener}");
                await listener.OpenAsync(TimeSpan.FromSeconds(30));

                var clientStream = await client.CreateConnectionAsync();

                var listenerStream = await listener.AcceptConnectionAsync();

                TestUtility.Log("Client and Listener HybridStreams are connected!");

                byte[] sendBuffer = this.CreateBuffer(1024, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
                await clientStream.WriteAsync(sendBuffer, 0, sendBuffer.Length);

                TestUtility.Log($"clientStream wrote {sendBuffer.Length} bytes");

                byte[] readBuffer = new byte[sendBuffer.Length];
                await this.ReadCountBytesAsync(listenerStream, readBuffer, 0, readBuffer.Length, TimeSpan.FromSeconds(30));

                Assert.Equal(sendBuffer, readBuffer);

                TestUtility.Log("Calling clientStream.CloseAsync");
                var clientStreamCloseTask = clientStream.CloseAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token);
                TestUtility.Log("Reading from listenerStream");
                int bytesRead = await this.SafeReadAsync(listenerStream, readBuffer, 0, readBuffer.Length);

                TestUtility.Log($"listenerStream.Read returned {bytesRead} bytes");
                Assert.Equal(0, bytesRead);

                TestUtility.Log("Calling listenerStream.CloseAsync");
                var   listenerStreamCloseTask = listenerStream.CloseAsync(new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token);
                await listenerStreamCloseTask;
                TestUtility.Log("Calling listenerStream.CloseAsync completed");
                await clientStreamCloseTask;
                TestUtility.Log("Calling clientStream.CloseAsync completed");

                TestUtility.Log($"Closing {listener}");
                await listener.CloseAsync(TimeSpan.FromSeconds(10));

                listener = null;
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
Exemplo n.º 22
0
        private static async Task RunAsync()
        {
            var cts = new CancellationTokenSource();

            //  var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, myKey);
            //  var listener = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

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


            // Subscribe to the status events
            Console.BackgroundColor = ConsoleColor.Yellow;
            Console.ForegroundColor = ConsoleColor.Black;
            listener.Connecting    += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline       += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online        += (o, e) => { Console.WriteLine("Online"); };

            // Opening the listener will establish the control channel to
            // the Azure Relay service. The control channel will be continuously
            // maintained and reestablished when connectivity is disrupted.
            await listener.OpenAsync(cts.Token);

            Console.BackgroundColor = ConsoleColor.Yellow;
            Console.ForegroundColor = ConsoleColor.Black;
            Console.WriteLine("Server " + RelayNamespace + " is listening...");
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;

            // Providing callback for cancellation token that will close the listener.
            cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));

            // Start a new thread that will continuously read the console.
            new Task(() => Console.In.ReadLineAsync().ContinueWith((s) => { cts.Cancel(); })).Start();

            // Accept the next available, pending connection request.
            // Shutting down the listener will allow a clean exit with
            // this method returning null
            while (true)
            {
                var relayConnection = await listener.AcceptConnectionAsync();

                if (relayConnection == null)
                {
                    break;
                }

                ProcessMessagesOnConnection(relayConnection, cts);
            }

            // Close the listener after we exit the processing loop
            await listener.CloseAsync(cts.Token);
        }
        private static async Task RunAsync()
        {
            var cts           = new CancellationTokenSource();
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            // Subscribe to the status events
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Credit check service is offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Credit check service is online"); };

            // Create an array of credit status values
            List <string> creditStatuses = new List <string>();

            creditStatuses.Add("Good");
            creditStatuses.Add("Some issues");
            creditStatuses.Add("Bad");

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Obtain the name from the request
                TextReader tr            = new StreamReader(context.Request.InputStream);
                String     requestedName = tr.ReadToEnd();
                Console.WriteLine("A request was received to check credit for: " + requestedName);

                // Pick a status at random
                Random r     = new Random();
                int    index = r.Next(creditStatuses.Count);

                // Formulate and send the response
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "Credit check successful";
                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine("Credit check for {0}: {1}", requestedName, creditStatuses[index]);
                }

                // Close the context
                context.Response.Close();
            };

            // Open the listener
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
        async Task LargeRequestEmptyResponse(EndpointTestType endpointTestType)
        {
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60));
            HybridConnectionListener listener = this.GetHybridConnectionListener(endpointTestType);

            try
            {
                await listener.OpenAsync(cts.Token);

                string requestBody = null;
                listener.RequestHandler = async(context) =>
                {
                    TestUtility.Log("HybridConnectionListener.RequestHandler invoked with Request:");
                    TestUtility.Log($"{context.Request.HttpMethod} {context.Request.Url}");
                    context.Request.Headers.AllKeys.ToList().ForEach((k) => TestUtility.Log($"{k}: {context.Request.Headers[k]}"));
                    requestBody = StreamToString(context.Request.InputStream);
                    TestUtility.Log($"Body Length: {requestBody.Length}");
                    await context.Response.CloseAsync();
                };

                RelayConnectionStringBuilder connectionString = GetConnectionStringBuilder(endpointTestType);
                Uri endpointUri   = connectionString.Endpoint;
                Uri hybridHttpUri = new UriBuilder("https://", endpointUri.Host, endpointUri.Port, connectionString.EntityPath).Uri;

                using (var client = new HttpClient {
                    BaseAddress = hybridHttpUri
                })
                {
                    client.DefaultRequestHeaders.ExpectContinue = false;
                    var postRequest = new HttpRequestMessage();
                    await AddAuthorizationHeader(connectionString, postRequest, hybridHttpUri);

                    postRequest.Method = HttpMethod.Post;
                    var body = new string('y', 65 * 1024);
                    postRequest.Content = new StringContent(body);
                    LogRequest(postRequest, client, showBody: false);
                    using (HttpResponseMessage response = await client.SendAsync(postRequest, cts.Token))
                    {
                        LogResponse(response);
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        Assert.Equal(0, response.Content.ReadAsStreamAsync().Result.Length);
                        Assert.Equal(body.Length, requestBody.Length);
                    }
                }

                await listener.CloseAsync(cts.Token);
            }
            finally
            {
                await SafeCloseAsync(listener);
            }
        }
Exemplo n.º 25
0
        private async Task RunAsync()
        {
            // Create a new hybrid connection client
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, key);
            var listener      = new HybridConnectionListener(new Uri($"sb://{relayNamespace}/{connectionName}"), tokenProvider);

            // Open the listener and register it in Service Bus
            var cts = new CancellationTokenSource();
            await listener.OpenAsync(cts.Token);

            // Callback for cancellation token that will close the listener
            cts.Token.Register(() => listener.CloseAsync(CancellationToken.None));

            await Listen(listener, cts)
            .ContinueWith((t) => listener.CloseAsync(cts.Token));
        }
        public void Start()
        {
            _log.Information("Relay: {idx}:{relay}. Opening relay listener connection", _forwarderIdx, _relayListener.Address);

            try
            {
                _relayListener.OpenAsync(CancellationToken.None).GetAwaiter().GetResult();

                _relayListener.AcceptConnectionAsync().ContinueWith(StreamAccepted);
            }
            catch (Exception e)
            {
                _log.Error(e, "Relay: {idx}:{relay}. Unable to connect", _forwarderIdx, _relayListener.Address);
                throw;
            }
        }
Exemplo n.º 27
0
        private static async Task RunAsync()
        {
            var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(KeyName, Key);
            var listener      = new HybridConnectionListener(new Uri(string.Format("sb://{0}/{1}", RelayNamespace, ConnectionName)), tokenProvider);

            // Subscribe to the status events.
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                var name = context.Request.Headers["PassThrough"];
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK";

                var env = new StringBuilder();
                env.Append($"Machine Name = {Environment.MachineName}\r\n");
                env.Append($"OS Version = {Environment.OSVersion}\r\n");
                env.Append($"Current Directory = {Environment.CurrentDirectory}\r\n");
                env.Append($"Current User = {Environment.UserName}\r\n");

                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine(env.ToString());
                    sw.WriteLine("hello, " + name);
                }
                Console.WriteLine("request from " + name);
                // The context MUST be closed here
                context.Response.Close();
            };

            // Opening the listener establishes the control channel to
            // the Azure Relay service. The control channel is continuously
            // maintained, and is reestablished when connectivity is disrupted.
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
        /// <summary>
        /// Opens the listener and starts listening thread
        /// </summary>
        private async Task OpenAsync()
        {
            _listener = new HybridConnectionListener(_uri, _tokenProvider);

            // Subscribe to the status events
            _listener.Connecting   += (o, e) => OnConnecting(o, e);
            _listener.Offline      += (o, e) => OnDisconnected(o, e);
            _listener.Online       += (o, e) => OnConnected(o, e);
            _listener.AcceptHandler = (c) => OnAcceptAsync(c);

            await _listener.OpenAsync(_cts.Token).ConfigureAwait(false);

            _listenerTask = Task.Factory.StartNew(async() => await ListenAsync(), _cts.Token,
                                                  TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap();

            ProxyEventSource.Log.LocalListenerStarted(this);
        }
Exemplo n.º 29
0
        private static async Task RunAsync()
        {
            var cts = new CancellationTokenSource();

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

            // Subscribe to the status events.
            listener.Connecting += (o, e) => { Console.WriteLine("Connecting"); };
            listener.Offline    += (o, e) => { Console.WriteLine("Offline"); };
            listener.Online     += (o, e) => { Console.WriteLine("Online"); };

            // Provide an HTTP request handler
            listener.RequestHandler = (context) =>
            {
                // Do something with context.Request.Url, HttpMethod, Headers, InputStream...
                context.Response.StatusCode        = HttpStatusCode.OK;
                context.Response.StatusDescription = "OK, This is pretty neat";

                var bytes = new byte[context.Request.InputStream.Length];
                var aaa   = context.Request.InputStream.Read(bytes, 0, bytes.Length);
                var str   = Encoding.UTF8.GetString(bytes);

                using (var sw = new StreamWriter(context.Response.OutputStream))
                {
                    sw.WriteLine(str);
                    Console.WriteLine(str);
                }

                // The context MUST be closed here
                context.Response.Close();
            };

            // Opening the listener establishes the control channel to
            // the Azure Relay service. The control channel is continuously
            // maintained, and is reestablished when connectivity is disrupted.
            await listener.OpenAsync();

            Console.WriteLine("Server listening");

            // Start a new thread that will continuously read the console.
            await Console.In.ReadLineAsync();

            // Close the listener after you exit the processing loop.
            await listener.CloseAsync();
        }
Exemplo n.º 30
0
        public async Task <bool> OpenService()
        {
            try
            {
                await relayListener.OpenAsync(CancellationToken.None);

#pragma warning disable 4014
                relayListener.AcceptConnectionAsync().ContinueWith(t => StreamAccepted(t.Result));
#pragma warning restore 4014
            }
            catch (Exception e)
            {
                Trace.TraceError("Unable to connect: {0}", e.Message);
                return(false);
            }
            return(true);
        }