Beispiel #1
0
 public Config()
 {
     relayConnectionStringBuilder = new RelayConnectionStringBuilder();
     fileSystemWatchers           = new List <FileSystemWatcher>();
     localForward  = new List <LocalForward>();
     remoteForward = new List <RemoteForward>();
 }
        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));
        }
        internal HybridConnectionBaseOperator(ILocalSwitchboard switchboard, string hybridConnectionString, string hybridConnectionName, bool createConnectionIfItDoesNotExist)
        {
            connectionItems = new RelayConnectionStringBuilder(hybridConnectionString)
            {
                EntityPath = hybridConnectionName
            };
            if (String.IsNullOrEmpty(connectionItems.EntityPath))
            {
                throw new HybridConnectionNameNoSpecifiedInEntityPathException(hybridConnectionString);
            }

            this.hybridConnectionString = hybridConnectionString;
            this.hybridConnectionName   = hybridConnectionName;

            if (createConnectionIfItDoesNotExist)
            {
                CreateHybridConnectionIfDoesNotExist();
            }

            if (null != switchboard)
            {
                this.Switchboards.Add(switchboard);
                switchboard.Operator = this;
            }

            StartListener();
        }
        static void ConfigureListCommand(CommandLineApplication hcCommand)
        {
            hcCommand.RelayCommand("list", (listCmd) =>
            {
                listCmd.Description          = "List HybridConnection(s)";
                var connectionStringArgument = listCmd.Argument("connectionString", "Relay ConnectionString");

                listCmd.OnExecute(async() =>
                {
                    string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument);
                    if (string.IsNullOrEmpty(connectionString))
                    {
                        TraceMissingArgument(connectionStringArgument.Name);
                        listCmd.ShowHelp();
                        return(1);
                    }

                    var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString);
                    RelayTraceSource.TraceInfo($"Listing HybridConnections for {connectionStringBuilder.Endpoint.Host}");
                    RelayTraceSource.TraceInfo($"{"Path",-38} {"ListenerCount",-15} {"RequiresClientAuth",-20}");
                    var namespaceManager = new RelayNamespaceManager(connectionString);
                    IEnumerable <HybridConnectionDescription> hybridConnections = await namespaceManager.GetHybridConnectionsAsync();
                    foreach (var hybridConnection in hybridConnections)
                    {
                        RelayTraceSource.TraceInfo($"{hybridConnection.Path,-38} {hybridConnection.ListenerCount,-15} {hybridConnection.RequiresClientAuthorization}");
                    }

                    return(0);
                });
            });
        }
Beispiel #5
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);
            }
        }
        static void ConfigureSendCommand(CommandLineApplication hcCommand)
        {
            hcCommand.RelayCommand("send", (sendCmd) =>
            {
                sendCmd.Description          = "HybridConnection send command";
                var pathArgument             = sendCmd.Argument("path", "HybridConnection path");
                var connectionStringArgument = sendCmd.Argument("connectionString", "Relay ConnectionString");

                var numberOption        = sendCmd.Option(CommandStrings.NumberTemplate, CommandStrings.NumberDescription, CommandOptionType.SingleValue);
                var methodOption        = sendCmd.Option("-m|--method <method>", "The HTTP Method (GET|POST|PUT|DELETE|WEBSOCKET)", CommandOptionType.SingleValue);
                var requestOption       = sendCmd.Option(CommandStrings.RequestTemplate, CommandStrings.RequestDescription, CommandOptionType.SingleValue);
                var requestLengthOption = sendCmd.Option(CommandStrings.RequestLengthTemplate, CommandStrings.RequestLengthDescription, CommandOptionType.SingleValue);

                sendCmd.OnExecute(async() =>
                {
                    string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument);
                    if (string.IsNullOrEmpty(connectionString))
                    {
                        TraceMissingArgument(connectionStringArgument.Name);
                        sendCmd.ShowHelp();
                        return(1);
                    }

                    var connectionStringBuilder        = new RelayConnectionStringBuilder(connectionString);
                    connectionStringBuilder.EntityPath = pathArgument.Value ?? connectionStringBuilder.EntityPath ?? DefaultPath;

                    int number            = GetIntOption(numberOption, 1);
                    string method         = GetStringOption(methodOption, "GET");
                    string requestContent = GetMessageBody(requestOption, requestLengthOption, null);
                    await HybridConnectionTests.VerifySendAsync(connectionStringBuilder, number, method, requestContent, RelayTraceSource.Instance);
                    return(0);
                });
            });
        }
        static void ConfigureCreateCommand(CommandLineApplication hcCommand)
        {
            hcCommand.RelayCommand("create", (createCmd) =>
            {
                createCmd.Description = "Create a HybridConnection";

                var pathArgument             = createCmd.Argument("path", "HybridConnection path");
                var connectionStringArgument = createCmd.Argument("connectionString", "Relay ConnectionString");

                var requireClientAuthOption = createCmd.Option(
                    CommandStrings.RequiresClientAuthTemplate, CommandStrings.RequiresClientAuthDescription, CommandOptionType.SingleValue);

                createCmd.OnExecute(async() =>
                {
                    string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument);
                    if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(pathArgument.Value))
                    {
                        TraceMissingArgument(string.IsNullOrEmpty(connectionString) ? connectionStringArgument.Name : pathArgument.Name);
                        createCmd.ShowHelp();
                        return(1);
                    }

                    var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString);
                    RelayTraceSource.TraceInfo($"Creating HybridConnection '{pathArgument.Value}' in {connectionStringBuilder.Endpoint.Host}...");
                    var hcDescription = new HybridConnectionDescription(pathArgument.Value);
                    hcDescription.RequiresClientAuthorization = GetBoolOption(requireClientAuthOption, true);
                    var namespaceManager = new RelayNamespaceManager(connectionString);
                    await namespaceManager.CreateHybridConnectionAsync(hcDescription);
                    RelayTraceSource.TraceInfo($"Creating HybridConnection '{pathArgument.Value}' in {connectionStringBuilder.Endpoint.Host} succeeded");
                    return(0);
                });
            });
        }
        static void ConfigureDeleteCommand(CommandLineApplication hcCommand)
        {
            hcCommand.RelayCommand("delete", (deleteCmd) =>
            {
                deleteCmd.Description        = "Delete a HybridConnection";
                var pathArgument             = deleteCmd.Argument("path", "HybridConnection path");
                var connectionStringArgument = deleteCmd.Argument("connectionString", "Relay ConnectionString");

                deleteCmd.OnExecute(async() =>
                {
                    string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument);
                    if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(pathArgument.Value))
                    {
                        TraceMissingArgument(string.IsNullOrEmpty(connectionString) ? connectionStringArgument.Name : pathArgument.Name);
                        deleteCmd.ShowHelp();
                        return(1);
                    }

                    var connectionStringBuilder = new RelayConnectionStringBuilder(connectionString);
                    RelayTraceSource.TraceInfo($"Deleting HybridConnection '{pathArgument.Value}' in {connectionStringBuilder.Endpoint.Host}...");
                    var namespaceManager = new RelayNamespaceManager(connectionString);
                    await namespaceManager.DeleteHybridConnectionAsync(pathArgument.Value);
                    RelayTraceSource.TraceInfo($"Deleting HybridConnection '{pathArgument.Value}' in {connectionStringBuilder.Endpoint.Host} succeeded");
                    return(0);
                });
            });
        }
        static void ConfigureListenCommand(CommandLineApplication hcCommand)
        {
            hcCommand.RelayCommand("listen", (listenCmd) =>
            {
                listenCmd.Description        = "HybridConnection listen command";
                var pathArgument             = listenCmd.Argument("path", "HybridConnection path");
                var connectionStringArgument = listenCmd.Argument("connectionString", "Relay ConnectionString");

                var responseOption            = listenCmd.Option("--response <response>", "Response to return", CommandOptionType.SingleValue);
                var responseLengthOption      = listenCmd.Option("--response-length <responseLength>", "Length of response to return", CommandOptionType.SingleValue);
                var responseChunkLengthOption = listenCmd.Option("--response-chunk-length <responseLength>", "Length of response to return", CommandOptionType.SingleValue);
                var statusCodeOption          = listenCmd.Option("--status-code <statusCode>", "The HTTP Status Code to return (200|201|401|404|etc.)", CommandOptionType.SingleValue);
                var statusDescriptionOption   = listenCmd.Option("--status-description <statusDescription>", "The HTTP Status Description to return", CommandOptionType.SingleValue);

                listenCmd.OnExecute(async() =>
                {
                    string connectionString = ConnectionStringUtility.ResolveConnectionString(connectionStringArgument);
                    if (string.IsNullOrEmpty(connectionString))
                    {
                        TraceMissingArgument(connectionStringArgument.Name);
                        listenCmd.ShowHelp();
                        return(1);
                    }

                    string response                    = GetMessageBody(responseOption, responseLengthOption, "<html><head><title>Azure Relay HybridConnection</title></head><body>Response Body from Listener</body></html>");
                    var connectionStringBuilder        = new RelayConnectionStringBuilder(connectionString);
                    connectionStringBuilder.EntityPath = pathArgument.Value ?? connectionStringBuilder.EntityPath ?? DefaultPath;
                    var statusCode          = (HttpStatusCode)GetIntOption(statusCodeOption, 200);
                    int responseChunkLength = GetIntOption(responseChunkLengthOption, response.Length);
                    return(await HybridConnectionTests.VerifyListenAsync(RelayTraceSource.Instance, connectionStringBuilder, response, responseChunkLength, statusCode, statusDescriptionOption.Value()));
                });
            });
        }
Beispiel #10
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);
        }
        async Task ListenerAuthenticationFailureTest()
        {
            HybridConnectionListener listener = null;

            try
            {
                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";
                }

                listener = new HybridConnectionListener(badAuthConnectionString.ToString());

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

                Assert.Contains("token has an invalid signature", exception.Message);
                Assert.Contains(badAuthConnectionString.EntityPath, exception.Message, StringComparison.OrdinalIgnoreCase);
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
        async Task ListenerNonExistantHybridConnectionTest()
        {
            HybridConnectionListener listener = null;

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

                listener = new HybridConnectionListener(fakeEndpointConnectionStringBuilder.ToString());

                // Endpoint does not exist. TrackingId:Guid_G10, SystemTracker:sb://contoso.servicebus.windows.net/d0c500e7-2ad0-4e36-bf40-0fe2431a394e, Timestamp:5/7/2018 5:47:21 PM
                var exception = await Assert.ThrowsAsync <EndpointNotFoundException>(() => listener.OpenAsync());

                Assert.Contains("Endpoint does not exist", exception.Message);
                Assert.Contains(fakeEndpointConnectionStringBuilder.EntityPath, exception.Message);
            }
            finally
            {
                await this.SafeCloseAsync(listener);
            }
        }
 public UrlPrefix(string prefix, TokenProvider tokenProvider)
 {
     if (!Uri.IsWellFormedUriString(prefix, UriKind.Absolute))
     {
         try
         {
             var rcb = new RelayConnectionStringBuilder(prefix);
             this.prefixUri = string.IsNullOrEmpty(rcb.EntityPath)?rcb.Endpoint: new Uri(rcb.Endpoint, rcb.EntityPath);
             if (this.prefixUri.AbsolutePath.EndsWith("/"))
             {
                 this.prefixUri = new UriBuilder(this.prefixUri)
                 {
                     Path = this.prefixUri.AbsolutePath.Substring(0, this.prefixUri.AbsolutePath.Length - 1)
                 }.Uri;
             }
             this.TokenProvider =
                 !string.IsNullOrEmpty(rcb.SharedAccessSignature) ? TokenProvider.CreateSharedAccessSignatureTokenProvider(rcb.SharedAccessSignature) :
                 !(string.IsNullOrEmpty(rcb.SharedAccessKeyName) || string.IsNullOrEmpty(rcb.SharedAccessKey)) ? TokenProvider.CreateSharedAccessSignatureTokenProvider(rcb.SharedAccessKeyName, rcb.SharedAccessKey) :
                 null;
         }
         catch (Exception e)
         {
             throw new ArgumentException("prefix", e);
         }
     }
     else if (!Uri.TryCreate(prefix, UriKind.Absolute, out prefixUri))
     {
         throw new ArgumentException("prefix");
     }
     if (tokenProvider != null)
     {
         TokenProvider = tokenProvider;
     }
 }
Beispiel #14
0
 public OrgRelayServer()
 {
     if (ConnectionString.Length == 0)
     {
         throw new Exception("Please set the connection string property or call the parameterized constructor.");
     }
     _conn = new RelayConnectionStringBuilder(ConnectionString);
 }
        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);
            }
        }
        public OrgRelayClient()
        {
            if (ConnectionString == "")
            {
                throw new Exception("Missing connection string");
            }

            _conn = new RelayConnectionStringBuilder(ConnectionString);
        }
        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);
            }
        }
Beispiel #18
0
        //HybridConnectionClient client;
        //Task<HybridConnectionStream> connectionTask = null;

        internal RecieveResponseFromRequestByType(Type requestType, Type responseType, string relayConnectionString)
        {
            connectionStringBuilder = new RelayConnectionStringBuilder(relayConnectionString)
            {
                EntityPath = hybridConnectionName
            };
            this.hybridConnectionName = connectionStringBuilder.EntityPath;
            this.requestType          = requestType;
            this.responseType         = responseType;
        }
Beispiel #19
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;
 }
        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);
            }
        }
Beispiel #21
0
 internal RecieveResponseFromRequestByType(Type requestType, Type responseType, string relayConnectionString, string hybridConnectionName)
 {
     //https://docs.microsoft.com/en-us/azure/service-bus-relay/relay-hybrid-connections-dotnet-api-overview
     connectionStringBuilder = new RelayConnectionStringBuilder(relayConnectionString)
     {
         EntityPath = hybridConnectionName
     };
     //client = new HybridConnectionClient(connectionStringBuilder.ToString());
     //connectionTask = client.CreateConnectionAsync();
     this.hybridConnectionName = hybridConnectionName;
     this.requestType          = requestType;
     this.responseType         = responseType;
 }
        private void CreateHybridConnectionIfDoesNotExist()
        {
            var t = new RelayConnectionStringBuilder(hybridConnectionString);

            t.EntityPath = string.Empty;
            NamespaceManager            ns = NamespaceManager.CreateFromConnectionString(t.ToString().TrimEnd(';'));
            HybridConnectionDescription rd;

            if (!ns.HybridConnectionExists(hybridConnectionName, out rd))
            {
                ns.CreateHybridConnection(hybridConnectionName);
            }
        }
        /// <summary>
        /// Returns a HybridConnectionListener based on the EndpointTestType (authenticated/unauthenticated).
        /// </summary>
        protected HybridConnectionListener GetHybridConnectionListener(EndpointTestType endpointTestType)
        {
            // Even if the endpoint is unauthenticated, the *listener* still needs to be authenticated
            if (endpointTestType == EndpointTestType.Unauthenticated)
            {
                var connectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString)
                {
                    EntityPath = Constants.UnauthenticatedEntityPath
                };
                return(new HybridConnectionListener(connectionStringBuilder.ToString()));
            }

            return(new HybridConnectionListener(GetConnectionString(endpointTestType)));
        }
        public void ManagedIdentityConnectionStringTest()
        {
            string connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;Authentication=Managed Identity";

            TestUtility.Log("Testing connectionstring: " + connectionString);
            Type managedIdentityTokenProviderType = TokenProvider.CreateManagedIdentityTokenProvider().GetType();
            var  connectionStringBuilder          = new RelayConnectionStringBuilder(connectionString);

            Assert.Equal(RelayConnectionStringBuilder.AuthenticationType.ManagedIdentity, connectionStringBuilder.Authentication);
            HybridConnectionListener listener = new HybridConnectionListener(connectionString);

            Assert.Equal(managedIdentityTokenProviderType, listener.TokenProvider.GetType());
            HybridConnectionClient client = new HybridConnectionClient(connectionString);

            Assert.Equal(managedIdentityTokenProviderType, client.TokenProvider.GetType());

            connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;Authentication=ManagedIdentity";
            TestUtility.Log("Testing connectionstring: " + connectionString);
            connectionStringBuilder = new RelayConnectionStringBuilder(connectionString);
            Assert.Equal(RelayConnectionStringBuilder.AuthenticationType.ManagedIdentity, connectionStringBuilder.Authentication);
            listener = new HybridConnectionListener(connectionString);
            Assert.Equal(managedIdentityTokenProviderType, listener.TokenProvider.GetType());
            client = new HybridConnectionClient(connectionString);
            Assert.Equal(managedIdentityTokenProviderType, client.TokenProvider.GetType());

            connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;Authentication=Garbage";
            TestUtility.Log("Testing connectionstring: " + connectionString);
            connectionStringBuilder = new RelayConnectionStringBuilder(connectionString);
            Assert.Equal(RelayConnectionStringBuilder.AuthenticationType.Other, connectionStringBuilder.Authentication);

            // We should not be allowing intergers to be parsed as a valid AuthenticationType value
            connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;Authentication=1";
            TestUtility.Log("Testing connectionstring: " + connectionString);
            connectionStringBuilder = new RelayConnectionStringBuilder(connectionString);
            Assert.Equal(RelayConnectionStringBuilder.AuthenticationType.Other, connectionStringBuilder.Authentication);

            // Do not allow SharedAccessKeyName/SharedAccessKey to co-exist with AuthenticationType.ManagedIdentity
            connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=SomeKeyString;Authentication=Managed Identity";
            TestUtility.Log("Testing connectionstring: " + connectionString);
            connectionStringBuilder = new RelayConnectionStringBuilder(connectionString);
            Assert.Throws <ArgumentException>(() => connectionStringBuilder.ToString());

            // Do not allow SharedAccessSignature to co-exist with AuthenticationType.ManagedIdentity
            connectionString = "Endpoint=sb://contoso.servicebus.windows.net/;EntityPath=hc1;SharedAccessSignature=SomeKeySignature;Authentication=Managed Identity";
            TestUtility.Log("Testing connectionstring: " + connectionString);
            connectionStringBuilder = new RelayConnectionStringBuilder(connectionString);
            Assert.Throws <ArgumentException>(() => connectionStringBuilder.ToString());
        }
        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);
        }
Beispiel #26
0
        internal static string GetRelayUrl()
        {
            var connectionString = Environment.GetEnvironmentVariable("RELAY_TEST_CONNECTIONSTRING_NOAUTH");

            Assert.NotNull(connectionString);
            Assert.False(string.IsNullOrEmpty(connectionString));
            var cb = new RelayConnectionStringBuilder(connectionString);

            Assert.NotNull(connectionString);
            Assert.False(string.IsNullOrEmpty(connectionString));

            return(new Uri(new UriBuilder(cb.Endpoint)
            {
                Scheme = Uri.UriSchemeHttps
            }.Uri, cb.EntityPath.EndsWith("/")?cb.EntityPath:cb.EntityPath + "/").AbsoluteUri);
        }
Beispiel #27
0
        internal static TokenProvider CreateTokenProvider()
        {
            var connectionString = Environment.GetEnvironmentVariable("RELAY_TEST_CONNECTIONSTRING_NOAUTH");

            Assert.NotNull(connectionString);
            Assert.False(string.IsNullOrEmpty(connectionString));
            var cb = new RelayConnectionStringBuilder(connectionString);

            if (!string.IsNullOrEmpty(cb.SharedAccessSignature))
            {
                return(TokenProvider.CreateSharedAccessSignatureTokenProvider(cb.SharedAccessSignature));
            }
            else
            {
                return(TokenProvider.CreateSharedAccessSignatureTokenProvider(cb.SharedAccessKeyName, cb.SharedAccessKey));
            }
        }
        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);
            }
        }
        /// <summary>
        /// Since these tests all share a common connection string, this method will modify the
        /// endpoint / shared access keys as needed based on the EndpointTestType.
        /// </summary>
        protected RelayConnectionStringBuilder GetConnectionStringBuilder(EndpointTestType endpointTestType)
        {
            var connectionStringBuilder = new RelayConnectionStringBuilder(this.ConnectionString);

            if (endpointTestType == EndpointTestType.Unauthenticated)
            {
                connectionStringBuilder.EntityPath            = Constants.UnauthenticatedEntityPath;
                connectionStringBuilder.SharedAccessKey       = string.Empty;
                connectionStringBuilder.SharedAccessKeyName   = string.Empty;
                connectionStringBuilder.SharedAccessSignature = string.Empty;
            }
            else
            {
                connectionStringBuilder.EntityPath = Constants.AuthenticatedEntityPath;
            }

            return(connectionStringBuilder);
        }
Beispiel #30
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);
            }
        }