Beispiel #1
0
        static async Task Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: publisher <connectionString>");
                return;
            }

            var connectionString = args[0];
            var hub = "test01";

            var serviceClient = new WebPubSubServiceClient(connectionString, hub);
            var user          = "******";
            var count         = 0;

            do
            {
                Console.WriteLine($"Sending {count}");

                serviceClient.SendToUser(user, RequestContent.Create(new {
                    TimeStamp = DateTime.UtcNow,
                    Message   = $"Hello World - {count}"
                }));

                count++;
                await Task.Delay(5000);
            }while(true);
        }
 public void ParseConnectionStringTests(string connectionString, string url, string key)
 {
     connectionString     = string.Format(connectionString, $"AccessKey={key}"); // this is so that credscan is not triggered.
     var(uri, credential) = WebPubSubServiceClient.ParseConnectionString(connectionString);
     Assert.AreEqual(new Uri(url), uri);
     Assert.AreEqual(key, credential.Key);
 }
Beispiel #3
0
 public void ParseConnectionStringTests(string connectionString, string url)
 {
     connectionString     = string.Format(connectionString, FakeAccessKey);
     var(uri, credential) = WebPubSubServiceClient.ParseConnectionString(connectionString);
     Assert.AreEqual(new Uri(url), uri);
     Assert.AreEqual(FakeAccessKey, credential.Key);
 }
Beispiel #4
0
        static async Task Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: subscriber <connectionString>");
                return;
            }

            var connectionString = args[0];
            var hub  = "test01";
            var user = "******";

            var serviceClient = new WebPubSubServiceClient(connectionString, hub);
            var url           = serviceClient.GetClientAccessUri(userId: user);

            using (var client = new WebsocketClient(url, () =>
            {
                var inner = new ClientWebSocket();
                inner.Options.AddSubProtocol("json.webpubsub.azure.v1");
                return(inner);
            }))
            {
                client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
                await client.Start();

                Console.WriteLine("Connected.");
                Console.Read();
            }
        }
Beispiel #5
0
        static async Task Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: subscriber <connectionString> <hub>");
                return;
            }
            var connectionString = args[0];
            var hub = args[1];

            // Either generate the URL or fetch it from server or fetch a temp one from the portal
            var serviceClient = new WebPubSubServiceClient(connectionString, hub);
            var url           = serviceClient.GetClientAccessUri();

            using (var client = new WebsocketClient(url, () =>
            {
                var inner = new ClientWebSocket();
                inner.Options.AddSubProtocol("json.webpubsub.azure.v1");
                return(inner);
            }))
            {
                client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
                await client.Start();

                Console.WriteLine("Connected.");
                Console.Read();
            }
        }
Beispiel #6
0
        public void HelloWorldWithConnectionString()
        {
            var connectionString = TestEnvironment.ConnectionString;

            var serviceClient = new WebPubSubServiceClient(connectionString, "some_hub");

            serviceClient.SendToAll("Hello World!");
        }
Beispiel #7
0
        public void Authenticate()
        {
            var endpoint = TestEnvironment.Endpoint;
            var key      = TestEnvironment.Key;

            #region Snippet:WebPubSubAuthenticate
            var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));
            #endregion
        }
        public void HelloWorld()
        {
            var connectionString = TestEnvironment.ConnectionString;

            #region Snippet:WebPubSubHelloWorld
            var serviceClient = new WebPubSubServiceClient(connectionString, "some_hub");

            serviceClient.SendToAll("Hello World!");
            #endregion
        }
        public void Authenticate()
        {
            var connectionString = TestEnvironment.ConnectionString;
            var endpoint         = ParseConnectionString(connectionString)["Endpoint"];
            var key = ParseConnectionString(connectionString)["AccessKey"];

            #region Snippet:WebPubSubAuthenticate
            // Create a WebPubSubServiceClient that will authenticate using a key credential.
            var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));
            #endregion
        }
Beispiel #10
0
        public void HelloWorld()
        {
            var endpoint = TestEnvironment.Endpoint;
            var key      = TestEnvironment.Key;

            #region Snippet:WebPubSubHelloWorld
            var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));

            serviceClient.SendToAll("Hello World!");
            #endregion
        }
        public void BinaryMessage()
        {
            var connectionString = TestEnvironment.ConnectionString;

            #region Snippet:WebPubSubSendBinary
            var serviceClient = new WebPubSubServiceClient(connectionString, "some_hub");

            Stream stream = BinaryData.FromString("Hello World!").ToStream();
            serviceClient.SendToAll(RequestContent.Create(stream), ContentType.ApplicationOctetStream);
            #endregion
        }
Beispiel #12
0
        public void BinaryMessage()
        {
            var endpoint = TestEnvironment.Endpoint;
            var key      = TestEnvironment.Key;

            #region Snippet:WebPubSubSendBinary
            var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));

            Stream stream = BinaryData.FromString("Hello World!").ToStream();
            serviceClient.SendToAll(RequestContent.Create(stream), ContentType.ApplicationOctetStream);
            #endregion
        }
Beispiel #13
0
        public void TestGenerateUriContainsExpectedPayloadsDto(string userId, string[] roles)
        {
            var serviceClient = new WebPubSubServiceClient(string.Format("Endpoint=http://localhost;Port=8080;AccessKey={0};Version=1.0;", FakeAccessKey), "hub");
            var expiresAt     = DateTimeOffset.UtcNow + TimeSpan.FromMinutes(5);
            var uri           = serviceClient.GenerateClientAccessUri(expiresAt, userId, roles);
            var token         = HttpUtility.ParseQueryString(uri.Query).Get("access_token");

            Assert.NotNull(token);
            var jwt = JwtTokenHandler.ReadJwtToken(token);

            var audience = jwt.Claims.FirstOrDefault(s => s.Type == "aud");

            Assert.NotNull(audience);
            Assert.AreEqual("http://localhost:8080/client/hubs/hub", audience.Value);
            var iat = jwt.Claims.FirstOrDefault(s => s.Type == "iat")?.Value;

            Assert.NotNull(iat);
            Assert.IsTrue(long.TryParse(iat, out var issuedAt));
            var exp = jwt.Claims.FirstOrDefault(s => s.Type == "exp")?.Value;

            Assert.NotNull(exp);
            Assert.IsTrue(long.TryParse(exp, out var expireAt));

            // default expire after should be ~5 minutes (~300 seconds)
            var expireAfter = expireAt - issuedAt;

            Assert.IsTrue(expireAfter > 295 && expireAfter < 305);

            var sub = jwt.Claims.Where(s => s.Type == "sub").Select(s => s.Value).ToArray();

            if (userId != null)
            {
                Assert.AreEqual(1, sub.Length);
                Assert.AreEqual(userId, sub[0]);
            }
            else
            {
                Assert.IsEmpty(sub);
            }

            var roleClaims = jwt.Claims.Where(s => s.Type == "role").Select(s => s.Value).ToArray();

            if (roles?.Length > 0)
            {
                Assert.AreEqual(roles, roleClaims);
            }
            else
            {
                Assert.IsEmpty(roleClaims);
            }
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Usage: publisher <endpoint> <key> <hub>");
                return;
            }
            var endpoint = args[0];
            var key      = args[1];
            var hub      = args[2];

            // Either generate the token or fetch it from server or fetch a temp one from the portal
            var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), hub, new Azure.AzureKeyCredential(key));

            serviceClient.SendToAll(new string(Enumerable.Repeat('c', 2038).ToArray()));
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Usage: publisher <connectionString> <hub> <message>");
                return;
            }
            var connectionString = args[0];
            var hub     = args[1];
            var message = args[2];

            // Either generate the token or fetch it from server or fetch a temp one from the portal
            var serviceClient = new WebPubSubServiceClient(connectionString, hub);

            serviceClient.SendToAll(message);
        }
        public void JsonMessage()
        {
            var connectionString = TestEnvironment.ConnectionString;

            #region Snippet:WebPubSubSendJson
            var serviceClient = new WebPubSubServiceClient(connectionString, "some_hub");

            serviceClient.SendToAll(RequestContent.Create(
                                        new
            {
                Foo = "Hello World!",
                Bar = 42
            }),
                                    ContentType.ApplicationJson);
            #endregion
        }
Beispiel #17
0
        public void AddUserToGroup()
        {
            var endpoint = TestEnvironment.Endpoint;
            var key      = TestEnvironment.Key;

            var client = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));

            client.AddUserToGroup("some_group", "some_user");

            // Avoid sending messages to users who do not exist.
            if (client.UserExists("some_user").Value)
            {
                client.SendToUser("some_user", "Hi, I am glad you exist!");
            }

            client.RemoveUserFromGroup("some_group", "some_user");
        }
Beispiel #18
0
        public void JsonMessage()
        {
            var endpoint = TestEnvironment.Endpoint;
            var key      = TestEnvironment.Key;

            #region Snippet:WebPubSubSendJson
            var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), "some_hub", new AzureKeyCredential(key));

            serviceClient.SendToAll(RequestContent.Create(
                                        new
            {
                Foo = "Hello World!",
                Bar = 42
            }),
                                    ContentType.ApplicationJson);
            #endregion
        }
        public void AddUserToGroup()
        {
            var connectionString = TestEnvironment.ConnectionString;
            var client           = new WebPubSubServiceClient(connectionString, "some_hub");

            #region Snippet:WebPubSubAddUserToGroup
            client.AddUserToGroup("some_group", "some_user");

            // Avoid sending messages to users who do not exist.
            if (client.UserExists("some_user").Value)
            {
                client.SendToUser("some_user", "Hi, I am glad you exist!");
            }

            client.RemoveUserFromGroup("some_group", "some_user");
            #endregion
        }
        public void TestGenerateUriUseSameKidWithSameKey(string connectionString)
        {
            var serviceClient = new WebPubSubServiceClient(" Endpoint=http://localhost;Port=8080;AccessKey=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGH;Version=1.0;", "hub");
            var uri1          = serviceClient.GetClientAccessUri();
            var uri2          = serviceClient.GetClientAccessUri();

            Assert.AreEqual("localhost:8080", uri1.Authority);
            Assert.AreEqual("/client/hubs/hub", uri1.AbsolutePath);
            var token1 = HttpUtility.ParseQueryString(uri1.Query).Get("access_token");

            Assert.NotNull(token1);
            var token2 = HttpUtility.ParseQueryString(uri2.Query).Get("access_token");

            Assert.NotNull(token2);
            var jwt1 = JwtTokenHandler.ReadJwtToken(token1);
            var jwt2 = JwtTokenHandler.ReadJwtToken(token2);

            Assert.AreEqual(jwt1.Header.Kid, jwt2.Header.Kid);
        }
Beispiel #21
0
        public void TestGenerateUriUseSameKidWithSameKey(string connectionString, string hub, string expectedUrl)
        {
            var serviceClient = new WebPubSubServiceClient(string.Format(connectionString, FakeAccessKey), hub);
            var uri1          = serviceClient.GenerateClientAccessUri();
            var uri2          = serviceClient.GenerateClientAccessUri();
            var urlBuilder    = new UriBuilder(uri1);

            urlBuilder.Query = string.Empty;
            Assert.AreEqual(expectedUrl, urlBuilder.Uri.ToString());
            var token1 = HttpUtility.ParseQueryString(uri1.Query).Get("access_token");

            Assert.NotNull(token1);
            var token2 = HttpUtility.ParseQueryString(uri2.Query).Get("access_token");

            Assert.NotNull(token2);
            var jwt1 = JwtTokenHandler.ReadJwtToken(token1);
            var jwt2 = JwtTokenHandler.ReadJwtToken(token2);

            Assert.AreEqual(jwt1.Header.Kid, jwt2.Header.Kid);
        }
Beispiel #22
0
        public async Task ServiceClientCanBroadcastMessages()
        {
            WebPubSubServiceClientOptions options = InstrumentClientOptions(new WebPubSubServiceClientOptions());

            var serviceClient = new WebPubSubServiceClient(TestEnvironment.ConnectionString, nameof(ServiceClientCanBroadcastMessages), options);
            // broadcast messages
            var textContent = "Hello";
            var response    = await serviceClient.SendToAllAsync(textContent, ContentType.TextPlain);

            Assert.AreEqual(202, response.Status);

            var jsonContent = BinaryData.FromObjectAsJson(new { hello = "world" });

            response = await serviceClient.SendToAllAsync(RequestContent.Create(jsonContent), ContentType.ApplicationJson);

            Assert.AreEqual(202, response.Status);
            var binaryContent = BinaryData.FromString("Hello");

            response = await serviceClient.SendToAllAsync(RequestContent.Create(binaryContent), ContentType.ApplicationOctetStream);

            Assert.AreEqual(202, response.Status);
        }
Beispiel #23
0
        static async Task Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.WriteLine("Usage: subscriber <endpoint> <key> <hub>");
                return;
            }
            var endpoint = args[0];
            var key      = args[1];
            var hub      = args[2];

            // Either generate the URL or fetch it from server or fetch a temp one from the portal
            var serviceClient = new WebPubSubServiceClient(new Uri(endpoint), hub, new Azure.AzureKeyCredential(key));
            var url           = serviceClient.GetClientAccessUri(claims: new System.Security.Claims.Claim[] {
                new System.Security.Claims.Claim("sub", "userId")
            });

            // start the connection
            using var client = new WebSocketClient(url, (message, type) =>
            {
                Console.WriteLine(Encoding.UTF8.GetString(message.Span));
                return(default);
            },
        public void ReverseProxyEndpointRedirection()
        {
            var mockResponse = new MockResponse(202);
            var transport    = new MockTransport(mockResponse);

            var wpsEndpoint  = "https://wps.contoso.com/";
            var apimEndpoint = "https://apim.contoso.com/";
            var credentail   = new AzureKeyCredential("abcdabcdabcdabcdabcdabcdabcdabcd");

            var options = new WebPubSubServiceClientOptions();

            options.Transport            = transport;
            options.ReverseProxyEndpoint = new Uri(apimEndpoint);

            var client = new WebPubSubServiceClient(new Uri(wpsEndpoint), "test_hub", credentail, options);

            var response = client.SendToAll("Hello World!");

            Assert.AreEqual(202, response.Status);

            var requestUri = transport.SingleRequest.Uri.ToUri();

            Assert.AreEqual(new Uri(apimEndpoint).Host, requestUri.Host);
        }
Beispiel #25
0
        public async Task SimpleWebSocketClientCanConnectAndReceiveMessage()
        {
            WebPubSubServiceClientOptions options = InstrumentClientOptions(new WebPubSubServiceClientOptions());

            var serviceClient = new WebPubSubServiceClient(TestEnvironment.ConnectionString, nameof(SimpleWebSocketClientCanConnectAndReceiveMessage), options);

            var url = await serviceClient.GetClientAccessUriAsync();

            // start the connection
            using var client = new WebSocketClient(url, IsSimpleClientEndSignal);

            // connected
            await client.WaitForConnected.OrTimeout();

            // broadcast messages

            var textContent = "Hello";
            await serviceClient.SendToAllAsync(textContent, ContentType.TextPlain);

            var jsonContent = BinaryData.FromObjectAsJson(new { hello = "world" });
            await serviceClient.SendToAllAsync(RequestContent.Create(jsonContent), ContentType.ApplicationJson);

            var binaryContent = BinaryData.FromString("Hello");
            await serviceClient.SendToAllAsync(RequestContent.Create(binaryContent), ContentType.ApplicationOctetStream);

            await serviceClient.SendToAllAsync(RequestContent.Create(GetEndSignalBytes()), ContentType.ApplicationOctetStream);

            await client.LifetimeTask.OrTimeout();

            var frames = client.ReceivedFrames;

            Assert.AreEqual(3, frames.Count);
            Assert.AreEqual(textContent, frames[0].MessageAsString);
            Assert.AreEqual(jsonContent.ToString(), frames[1].MessageAsString);
            CollectionAssert.AreEquivalent(binaryContent.ToArray(), frames[2].MessageBytes);
        }
 public TraduireNotificationService(WebPubSubServiceClient serviceClient)
 {
     _serviceClient = serviceClient;
 }
Beispiel #27
0
 // For tests.
 public WebPubSubService(WebPubSubServiceClient client)
 {
     _client = client;
 }
Beispiel #28
0
 public WebPubSubService(string connectionString, string hub)
 {
     _client = new WebPubSubServiceClient(connectionString, hub);
 }
 public WebPubSubService(string connectionString, string hub)
 {
     _serviceConfig = new ServiceConfigParser(connectionString);
     _client        = new WebPubSubServiceClient(connectionString, hub);
 }
 public TranscriptionActor(ActorHost host, ILogger <TranslationOnProcessing> logger, IConfiguration configuration, DaprClient Client, AzureCognitiveServicesClient CogsClient, WebPubSubServiceClient ServiceClient)
     : base(host)
 {
     _client        = Client;
     _logger        = logger;
     _configuration = configuration;
     _cogsClient    = CogsClient;
     _serviceClient = new TraduireNotificationService(ServiceClient);
 }