Exemple #1
0
 internal ChatMessageReadReceipt(string senderId, string chatMessageId, DateTimeOffset readOn)
 {
     SenderId      = senderId;
     Sender        = new CommunicationUserIdentifier(senderId);
     ChatMessageId = chatMessageId;
     ReadOn        = readOn;
 }
Exemple #2
0
 internal CommunicationUserToken(string id, string token, DateTimeOffset expiresOn)
 {
     Id        = id;
     User      = new CommunicationUserIdentifier(id);
     Token     = token;
     ExpiresOn = expiresOn;
 }
 internal ChatMessageContent(string message, string topic, CommunicationUserIdentifier communicationUserIdentifier, IReadOnlyList <ChatParticipant> participants)
 {
     Initiator    = communicationUserIdentifier;
     Message      = message;
     Topic        = topic;
     Participants = participants;
 }
 internal ChatThread(ChatThreadInternal chatThreadInternal)
 {
     Id        = chatThreadInternal.Id;
     Topic     = chatThreadInternal.Topic;
     CreatedOn = chatThreadInternal.CreatedOn;
     CreatedBy = new CommunicationUserIdentifier(chatThreadInternal.CreatedBy);
     Members   = chatThreadInternal.Members.Select(x => x.ToChatThreadMember()).ToList();
 }
Exemple #5
0
 /// <summary>
 ///  A member of the chat thread.
 /// </summary>
 /// <param name="communicationUser">Instance of <see cref="CommunicationUserIdentifier"/>.</param>
 public ChatThreadMember(CommunicationUserIdentifier communicationUser)
 {
     if (communicationUser == null || communicationUser.Id == null)
     {
         throw new ArgumentNullException(nameof(communicationUser));
     }
     User = communicationUser;
 }
Exemple #6
0
 internal ChatThread(ChatThreadInternal chatThreadInternal)
 {
     Id        = chatThreadInternal.Id;
     Topic     = chatThreadInternal.Topic;
     CreatedOn = chatThreadInternal.CreatedOn;
     CreatedBy = new CommunicationUserIdentifier(chatThreadInternal.CreatedBy);
     DeletedOn = chatThreadInternal.DeletedOn;
 }
        internal ChatMessageContent(ChatMessageContentInternal chatMessageContentInternal)
        {
            if (chatMessageContentInternal.Initiator != null)
            {
                Initiator = new CommunicationUserIdentifier(chatMessageContentInternal.Initiator);
            }

            Message      = chatMessageContentInternal.Message;
            Topic        = chatMessageContentInternal.Topic;
            Participants = chatMessageContentInternal.Participants.Select(x => new ChatParticipant(x)).ToList().AsReadOnly();
        }
        internal CommunicationUserIdentifierAndToken(CommunicationIdentity identity, CommunicationIdentityAccessToken accessToken)
        {
            if (identity == null)
            {
                throw new ArgumentNullException(nameof(identity));
            }

            Identity            = identity;
            InternalAccessToken = accessToken;
            User         = new CommunicationUserIdentifier(identity.Id);
            _accessToken = accessToken is null ? null : new AccessToken(accessToken.Token, accessToken.ExpiresOn);
        }
Exemple #9
0
        internal async Task <IEnumerable <CallConnection> > CreateGroupCallOperation(CallingServerClient callingServerClient, string groupId, string from, string to, string callBackUri)
        {
            CallConnection?fromCallConnection = null;
            CallConnection?toCallConnection   = null;

            try
            {
                CommunicationIdentifier fromParticipant = new CommunicationUserIdentifier(from);
                CommunicationIdentifier toParticipant   = new CommunicationUserIdentifier(to);

                JoinCallOptions fromCallOptions = new JoinCallOptions(
                    new Uri(callBackUri),
                    new MediaType[] { MediaType.Audio },
                    new EventSubscriptionType[] { EventSubscriptionType.ParticipantsUpdated });
                fromCallConnection = await callingServerClient.JoinCallAsync(groupId, fromParticipant, fromCallOptions).ConfigureAwait(false);

                SleepInTest(1000);
                Assert.IsFalse(string.IsNullOrWhiteSpace(fromCallConnection.CallConnectionId));

                JoinCallOptions joinCallOptions = new JoinCallOptions(
                    new Uri(callBackUri),
                    new MediaType[] { MediaType.Audio },
                    new EventSubscriptionType[] { EventSubscriptionType.ParticipantsUpdated });

                toCallConnection = await callingServerClient.JoinCallAsync(groupId, toParticipant, joinCallOptions).ConfigureAwait(false);

                SleepInTest(1000);
                Assert.IsFalse(string.IsNullOrWhiteSpace(toCallConnection.CallConnectionId));

                return(new CallConnection[] { fromCallConnection, toCallConnection });
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine(ex.Message);
                Assert.Fail($"Unexpected error: {ex}");
                throw;
            }
            catch (Exception ex)
            {
                Assert.Fail($"Unexpected error: {ex}");

                if (fromCallConnection != null)
                {
                    await fromCallConnection.HangupAsync().ConfigureAwait(false);
                }

                if (toCallConnection != null)
                {
                    await toCallConnection.HangupAsync().ConfigureAwait(false);
                }
                throw;
            }
        }
Exemple #10
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Console.WriteLine("Azure Communication Services - Access Tokens Quickstart");

            //  Authenticate the client
            // This code demonstrates how to fetch your connection string
            // from an environment variable.
            string connectionString = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_CONNECTION_STRING");
            var    client           = new CommunicationIdentityClient(connectionString);

            // This code demonstrates how to fetch your endpoint and access key
            // from an environment variable.

            /*string endpoint = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_ENDPOINT");
             * string accessKey = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_ACCESSKEY");
             * var client = new CommunicationIdentityClient(new Uri(endpoint), new AzureKeyCredential(accessKey));*/

            // Update documentation with URI details

            /*TokenCredential tokenCredential = new DefaultAzureCredential();
             * string endPoint = Environment.GetEnvironmentVariable("COMMUNICATION_SERVICES_ENDPOINT");
             * var client = new CommunicationIdentityClient(new Uri(endPoint), tokenCredential);*/

            // Create an identity
            var identityResponse = await client.CreateUserAsync();

            var identity = identityResponse.Value;

            Console.WriteLine($"\nCreated an identity with ID: {identity.Id}");

            // Issue an access token with the "voip" scope for an identity
            var tokenResponse = await client.GetTokenAsync(identity, scopes : new[] { CommunicationTokenScope.VoIP });

            var token     = tokenResponse.Value.Token;
            var expiresOn = tokenResponse.Value.ExpiresOn;

            Console.WriteLine($"\nIssued an access token with 'voip' scope that expires at {expiresOn}:");
            Console.WriteLine(token);

            // Refresh access tokens
            var identityToRefresh    = new CommunicationUserIdentifier(identity.Id);
            var refreshTokenResponse = await client.GetTokenAsync(identityToRefresh, scopes : new[] { CommunicationTokenScope.VoIP });

            // Revoke access tokens
            await client.RevokeTokensAsync(identity);

            Console.WriteLine($"\nSuccessfully revoked all access tokens for identity with ID: {identity.Id}");

            // Delete an identity
            await client.DeleteUserAsync(identity);

            Console.WriteLine($"\nDeleted the identity with ID: {identity.Id}");
        }
Exemple #11
0
        public async Task RemoveParticipantShouldSucceed()
        {
            //arrange
            var id = "8:acs:1b5cc06b-f352-4571-b1e6-d9b259b7c776_00000007-0464-274b-b274-5a3a0d000101";
            CommunicationUserIdentifier identifier       = new CommunicationUserIdentifier(id);
            ChatThreadClient            chatThreadClient = CreateMockChatThreadClient(204, GetParticipantsApiResponsePayload);

            //act
            Response RemoveParticipantResponse = await chatThreadClient.RemoveParticipantAsync(identifier);

            //assert
            Assert.AreEqual(204, RemoveParticipantResponse.Status);
        }
 internal ChatMessage(string id, ChatMessageType type, string sequenceId, string version, ChatMessageContent content, string senderDisplayName, DateTimeOffset createdOn, string senderId, DateTimeOffset?deletedOn, DateTimeOffset?editedOn)
 {
     Id                = id;
     Type              = type;
     SequenceId        = sequenceId;
     Version           = version;
     Content           = content;
     SenderDisplayName = senderDisplayName;
     CreatedOn         = createdOn;
     Sender            = new CommunicationUserIdentifier(senderId);
     DeletedOn         = deletedOn;
     EditedOn          = editedOn;
 }
Exemple #13
0
 /// <summary> Remove a member from a thread .</summary>
 /// <param name="user"><see cref="CommunicationUserIdentifier" /> to be removed from the chat thread participants.</param>
 /// <param name="cancellationToken"> The cancellation token to use. </param>
 /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
 public virtual Response RemoveParticipant(CommunicationUserIdentifier user, CancellationToken cancellationToken = default)
 {
     using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(ChatThreadClient)}.{nameof(RemoveParticipant)}");
     scope.Start();
     try
     {
         return(_chatThreadRestClient.RemoveChatParticipant(Id, user.Id, cancellationToken));
     }
     catch (Exception ex)
     {
         scope.Failed(ex);
         throw;
     }
 }
 /// <summary>Asynchronously revokes all the tokens created for a <see cref="CommunicationUserIdentifier"/>.</summary>
 /// <param name="communicationUser">The <see cref="CommunicationUserIdentifier"/> whose tokens should get revoked.</param>
 /// <param name="cancellationToken">The cancellation token to use.</param>
 public virtual async Task <Response> RevokeTokensAsync(CommunicationUserIdentifier communicationUser, CancellationToken cancellationToken = default)
 {
     using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CommunicationIdentityClient)}.{nameof(RevokeTokens)}");
     scope.Start();
     try
     {
         return(await RestClient.RevokeAccessTokensAsync(communicationUser.Id, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception ex)
     {
         scope.Failed(ex);
         throw;
     }
 }
 /// <summary>Asynchronously deletes a <see cref="CommunicationUserIdentifier"/>, revokes its tokens and deletes its data.</summary>
 /// <param name="communicationUser"> The user to be deleted.</param>
 /// <param name="cancellationToken"> The cancellation token to use.</param>
 /// <exception cref="RequestFailedException">The server returned an error.</exception>
 public virtual Response DeleteUser(CommunicationUserIdentifier communicationUser, CancellationToken cancellationToken = default)
 {
     using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CommunicationIdentityClient)}.{nameof(DeleteUser)}");
     scope.Start();
     try
     {
         return(RestClient.Delete(communicationUser.Id, cancellationToken));
     }
     catch (Exception ex)
     {
         scope.Failed(ex);
         throw;
     }
 }
 internal ChatMessage(string id, string type, ChatMessagePriority?priority, string version, string content, string senderDisplayName, DateTimeOffset?createdOn, string senderId, DateTimeOffset?deletedOn, DateTimeOffset?editedOn)
 {
     Id                = id;
     Type              = type;
     Priority          = priority;
     Version           = version;
     Content           = content;
     SenderDisplayName = senderDisplayName;
     CreatedOn         = createdOn;
     SenderId          = senderId;
     DeletedOn         = deletedOn;
     EditedOn          = editedOn;
     Sender            = new CommunicationUserIdentifier(senderId);
 }
Exemple #17
0
 /// <summary>Issues a token for a <see cref="CommunicationUserIdentifier"/>.</summary>
 /// <param name="scopes">The scopes that the token should have.</param>
 /// <param name="communicationUser">The <see cref="CommunicationUserIdentifier"/> for whom to issue a token.</param>
 /// <param name="cancellationToken">The cancellation token to use.</param>
 /// <exception cref="RequestFailedException">The server returned an error.</exception>
 public virtual Response <CommunicationUserToken> IssueToken(CommunicationUserIdentifier communicationUser, IEnumerable <CommunicationTokenScope> scopes, CancellationToken cancellationToken = default)
 {
     using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CommunicationIdentityClient)}.{nameof(IssueToken)}");
     scope.Start();
     try
     {
         return(RestClient.IssueToken(communicationUser.Id, scopes.Select(x => x.ToString()), cancellationToken));
     }
     catch (Exception ex)
     {
         scope.Failed(ex);
         throw;
     }
 }
Exemple #18
0
 /// <summary>Revokes all the tokens created for a user.</summary>
 /// <param name="communicationUser">The <see cref="CommunicationUserIdentifier"/> whose tokens will be revoked.</param>
 /// <param name="issuedBefore">All tokens that are issued prior to this time should get revoked.</param>
 /// <param name="cancellationToken">The cancellation token to use.</param>
 /// <exception cref="RequestFailedException">The server returned an error.</exception>
 public virtual Response RevokeTokens(CommunicationUserIdentifier communicationUser, DateTimeOffset?issuedBefore = default, CancellationToken cancellationToken = default)
 {
     using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CommunicationIdentityClient)}.{nameof(RevokeTokens)}");
     scope.Start();
     try
     {
         return(RestClient.Update(communicationUser.Id, issuedBefore ?? DateTime.UtcNow, cancellationToken));
     }
     catch (Exception ex)
     {
         scope.Failed(ex);
         throw;
     }
 }
 /// <summary>Gets a token for a <see cref="CommunicationUserIdentifier"/>.</summary>
 /// <param name="communicationUser">The <see cref="CommunicationUserIdentifier"/> for whom to get a token.</param>
 /// <param name="scopes">The scopes that the token should have.</param>
 /// <param name="cancellationToken">The cancellation token to use.</param>
 /// <exception cref="RequestFailedException">The server returned an error.</exception>
 public virtual Response <AccessToken> GetToken(CommunicationUserIdentifier communicationUser, IEnumerable <CommunicationTokenScope> scopes, CancellationToken cancellationToken = default)
 {
     using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CommunicationIdentityClient)}.{nameof(GetToken)}");
     scope.Start();
     try
     {
         Response <CommunicationIdentityAccessToken> response = RestClient.IssueAccessToken(communicationUser.Id, scopes, cancellationToken);
         return(Response.FromValue(new AccessToken(response.Value.Token, response.Value.ExpiresOn), response.GetRawResponse()));
     }
     catch (Exception ex)
     {
         scope.Failed(ex);
         throw;
     }
 }
Exemple #20
0
        public async Task <IActionResult> Put([FromQuery] string id)
        {
            //Refresh token for already generated token identifier
            var identityToRefresh = new CommunicationUserIdentifier(id.ToString());
            var tokenResponse     = await _client.GetTokenAsync(identityToRefresh, scopes : new[] { CommunicationTokenScope.VoIP, CommunicationTokenScope.Chat });


            return(Ok(new
            {
                Token = tokenResponse.Value.Token,
                ExpiresOn = tokenResponse.Value.ExpiresOn,
                Identity = identityToRefresh.Id,
                Endpoint = _endpoint
            }));
        }
        public async Task <AccessToken> RefreshTokenAsync(string resourceConnectionString, string identity)
        {
            try
            {
                var communicationIdentityClient = new CommunicationIdentityClient(resourceConnectionString);
                var user          = new CommunicationUserIdentifier(identity);
                var tokenResponse = await communicationIdentityClient.GetTokenAsync(user, scopes : new[] { CommunicationTokenScope.Chat });

                return(tokenResponse);
            }
            catch
            {
                throw;
            }
        }
 internal ChatMessage(ChatMessageInternal chatMessageInternal)
 {
     Id                = chatMessageInternal.Id;
     Type              = chatMessageInternal.Type;
     SequenceId        = chatMessageInternal.SequenceId;
     Version           = chatMessageInternal.Version;
     Content           = new ChatMessageContent(chatMessageInternal.Content);
     SenderDisplayName = chatMessageInternal.SenderDisplayName;
     CreatedOn         = chatMessageInternal.CreatedOn;
     if (chatMessageInternal.SenderId != null)
     {
         Sender = new CommunicationUserIdentifier(chatMessageInternal.SenderId);
     }
     DeletedOn = chatMessageInternal.DeletedOn;
     EditedOn  = chatMessageInternal.EditedOn;
 }
Exemple #23
0
        public async Task GetTokenWithNullScopesShouldThrow()
        {
            try
            {
                CommunicationIdentityClient client         = CreateClientWithConnectionString();
                CommunicationUserIdentifier userIdentifier = await client.CreateUserAsync();

                Response <AccessToken> accessToken = await client.GetTokenAsync(communicationUser : userIdentifier, scopes : null);
            }
            catch (ArgumentNullException ex)
            {
                Assert.AreEqual("scopes", ex.ParamName);
                return;
            }
            Assert.Fail("RevokeTokensAsync should have thrown an exception.");
        }
        private async Task <CallConnection> CreateCallAsync(string targetPhoneNumber)
        {
            try
            {
                //Preparting request data
                var source           = new CommunicationUserIdentifier(callConfiguration.SourceIdentity);
                var target           = new PhoneNumberIdentifier(targetPhoneNumber);
                var createCallOption = new CreateCallOptions(
                    new Uri(callConfiguration.AppCallbackUrl),
                    new List <MediaType> {
                    MediaType.Audio
                },
                    new List <EventSubscriptionType> {
                    EventSubscriptionType.ParticipantsUpdated, EventSubscriptionType.DtmfReceived
                }
                    );
                createCallOption.AlternateCallerId = new PhoneNumberIdentifier(callConfiguration.SourcePhoneNumber);

                Logger.LogMessage(Logger.MessageType.INFORMATION, "Performing CreateCall operation");
                var call = await callClient.CreateCallConnectionAsync(source,
                                                                      new List <CommunicationIdentifier>() { target },
                                                                      createCallOption, reportCancellationToken)
                           .ConfigureAwait(false);

                Logger.LogMessage(Logger.MessageType.INFORMATION, $"CreateCallConnectionAsync response --> {call.GetRawResponse()}, Call Connection Id: { call.Value.CallConnectionId}");

                Logger.LogMessage(Logger.MessageType.INFORMATION, $"Call initiated with Call Connection id: { call.Value.CallConnectionId}");

                RegisterToCallStateChangeEvent(call.Value.CallConnectionId);

                //Wait for operation to complete
                await callEstablishedTask.Task.ConfigureAwait(false);

                return(call.Value);
            }
            catch (Exception ex)
            {
                Logger.LogMessage(Logger.MessageType.ERROR, string.Format("Failure occured while creating/establishing the call. Exception: {0}", ex.Message));
                throw ex;
            }
        }
Exemple #25
0
        public static async Task <IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
            HttpRequest req, ILogger log)
        {
            var  userId = req.Query["userId"];
            User user;

            var connectionString = Environment.GetEnvironmentVariable("COMM_SERVICES_CONNECTION_STRING");
            var client           = new CommunicationIdentityClient(connectionString);

            if (string.IsNullOrWhiteSpace(userId) || AuthenticatedUsers.All(a => a.Id != userId))
            {
                var identityWithTokenResponse =
                    await client.CreateUserWithTokenAsync(new[] { CommunicationTokenScope.Chat });

                user = new User(identityWithTokenResponse.Value.user.Id,
                                identityWithTokenResponse.Value.token.ExpiresOn, identityWithTokenResponse.Value.token.Token);
                AuthenticatedUsers.Add(user);
            }
            else
            {
                var existingUser = AuthenticatedUsers.Single(a => a.Id == userId);
                if (existingUser.ExpiresOn > DateTimeOffset.Now)
                {
                    user = existingUser;
                }
                else
                {
                    var identityToRefresh = new CommunicationUserIdentifier(existingUser.Id);
                    var updatedToken      =
                        await client.IssueTokenAsync(identityToRefresh, new[] { CommunicationTokenScope.Chat });

                    existingUser.AccessToken = updatedToken.Value.Token;
                    existingUser.ExpiresOn   = updatedToken.Value.ExpiresOn;
                    user = existingUser;
                }
            }

            return(new OkObjectResult(user));
        }
        public async Task <IActionResult> GetAsync(string identity)
        {
            try
            {
                CommunicationUserIdentifier identifier = new CommunicationUserIdentifier(identity);
                Response <AccessToken>      response   = await this.client.IssueTokenAsync(identifier, scopes : new[] { CommunicationTokenScope.VoIP });

                var responseValue  = response.Value;
                var clientResponse = new
                {
                    token     = responseValue.Token,
                    expiresOn = responseValue.ExpiresOn,
                };

                return(this.Ok(clientResponse));
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Error occured while Generating Token: {ex}");
                return(this.Ok(this.Json(ex)));
            }
        }
        public void ThreadCGUD_ParticipantAUR_MessageGSU_NotificationT()
        {
            //arr
            Console.WriteLine($"ThreadCGUD_ParticipantAUR_MessageGSU_NotificationT Running on RecordedTestMode : {Mode}");
            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();

            (CommunicationUserIdentifier user1, string token1) = CreateUserAndToken(communicationIdentityClient);
            (CommunicationUserIdentifier user2, _)             = CreateUserAndToken(communicationIdentityClient);
            (CommunicationUserIdentifier user3, string token3) = CreateUserAndToken(communicationIdentityClient);
            (CommunicationUserIdentifier user4, _)             = CreateUserAndToken(communicationIdentityClient);
            (CommunicationUserIdentifier user5, _)             = CreateUserAndToken(communicationIdentityClient);

            string repeatabilityRequestId1 = "contoso-F0A747F1-6245-4307-8267-B974340677D2";
            string repeatabilityRequestId2 = "contoso-A0A747F1-6245-4307-8267-B974340677DA";

            var topic = "Thread sync from C# sdk";
            var displayNameMessage = "DisplayName sender message 1";
            var participants       = new[]
            {
                new ChatParticipant(user1)
                {
                    DisplayName = "user1"
                },
                new ChatParticipant(user2)
                {
                    DisplayName = "user2"
                },
                new ChatParticipant(user3)
                {
                    DisplayName = "user3"
                }
            };

            ChatClient chatClient  = CreateInstrumentedChatClient(token1);
            ChatClient chatClient3 = CreateInstrumentedChatClient(token3);

            //act
            CreateChatThreadResult createChatThreadResult = chatClient.CreateChatThread(topic, participants, repeatabilityRequestId1);
            ChatThreadClient       chatThreadClient       = GetInstrumentedChatThreadClient(chatClient, createChatThreadResult.ChatThread.Id);
            var threadId = chatThreadClient.Id;

            CreateChatThreadResult createChatThreadResult2 = chatClient.CreateChatThread(topic, participants, repeatabilityRequestId2);
            ChatThreadClient       chatThreadClient2       = GetInstrumentedChatThreadClient(chatClient, createChatThreadResult2.ChatThread.Id);
            ChatThreadClient       chatThreadClient3       = GetInstrumentedChatThreadClient(chatClient3, threadId);

            Pageable <ChatParticipant> chatParticipantsOnCreation = chatThreadClient.GetParticipants();
            var chatParticipantsOnCreationCount = chatParticipantsOnCreation.Count();

            string updatedTopic = "Launch meeting";

            chatThreadClient.UpdateTopic(topic: "Launch meeting");

            ChatThread chatThread = chatClient.GetChatThread(threadId);

            string messageContent  = "Let's meet at 11am";
            string messageId       = chatThreadClient.SendMessage("Let's meet at 11am");
            string messageContent2 = "Content for message 2";
            string messageId2      = chatThreadClient2.SendMessage(messageContent2, ChatMessageType.Text, displayNameMessage);
            string messageContent3 = "Content for message 3";
            string messageId3      = chatThreadClient3.SendMessage(messageContent3, ChatMessageType.Html, displayNameMessage);
            string messageContent4 = "Content for message 4";
            string messageId4      = chatThreadClient3.SendMessage(messageContent4, ChatMessageType.Text, displayNameMessage);
            string messageContent5 = "Content for message 5";
            string messageId5      = chatThreadClient3.SendMessage(messageContent5, ChatMessageType.Html, displayNameMessage);
            string messageContent6 = "Content for message 6";
            string messageId6      = chatThreadClient3.SendMessage(messageContent6, ChatMessageType.Text, displayNameMessage);

            ChatMessage message  = chatThreadClient.GetMessage(messageId);
            ChatMessage message2 = chatThreadClient2.GetMessage(messageId2);
            ChatMessage message3 = chatThreadClient3.GetMessage(messageId3);
            ChatMessage message4 = chatThreadClient3.GetMessage(messageId4);
            ChatMessage message5 = chatThreadClient3.GetMessage(messageId5);
            ChatMessage message6 = chatThreadClient3.GetMessage(messageId6);

            Pageable <ChatMessage> messages  = chatThreadClient.GetMessages();
            Pageable <ChatMessage> messages2 = chatThreadClient2.GetMessages();
            var getMessagesCount             = messages.Count();
            var getMessagesCount2            = messages2.Count();

            Pageable <ChatMessage> pageableMessages = chatThreadClient.GetMessages();

            PageableTester <ChatMessage> .AssertPagination(enumerableResource : pageableMessages, expectedPageSize : 2, expectedTotalResources : 8);

            string updatedMessageContent = "Instead of 11am, let's meet at 2pm";

            chatThreadClient.UpdateMessage(messageId, content: "Instead of 11am, let's meet at 2pm");
            Response <ChatMessage> actualUpdateMessage = chatThreadClient.GetMessage(messageId);

            chatThreadClient.DeleteMessage(messageId);
            Pageable <ChatMessage> messagesAfterOneDeleted = chatThreadClient.GetMessages();
            ChatMessage            deletedChatMessage      = messagesAfterOneDeleted.First(x => x.Id == messageId);

            Pageable <ChatParticipant> chatParticipants = chatThreadClient.GetParticipants();
            var chatParticipantsCount = chatParticipants.Count();

            var newParticipant = new ChatParticipant(user4)
            {
                DisplayName = "user4"
            };
            var newParticipant2 = new ChatParticipant(user5)
            {
                DisplayName = "user5"
            };

            chatThreadClient.AddParticipants(participants: new[] { newParticipant });
            AddChatParticipantsResult addChatParticipantsResult = chatThreadClient.AddParticipant(newParticipant2);

            Pageable <ChatParticipant> chatParticipantsAfterTwoAdded = chatThreadClient.GetParticipants();

            PageableTester <ChatParticipant> .AssertPagination(enumerableResource : chatParticipantsAfterTwoAdded, expectedPageSize : 2, expectedTotalResources : 5);

            var chatParticipantsAfterTwoAddedCount = chatParticipantsAfterTwoAdded.Count();

            Pageable <ChatMessage> messagesAfterParticipantsAdded = chatThreadClient.GetMessages();
            ChatMessage            participantAddedMessage        = messagesAfterParticipantsAdded.First(x => x.Type == ChatMessageType.ParticipantAdded);

            CommunicationUserIdentifier participantToBeRemoved = user4;

            chatThreadClient.RemoveParticipant(identifier: participantToBeRemoved);
            Pageable <ChatParticipant> chatParticipantAfterOneDeleted = chatThreadClient.GetParticipants();
            var chatParticipantAfterOneDeletedCount = chatParticipantAfterOneDeleted.Count();

            Pageable <ChatMessage> messagesAfterParticipantRemoved = chatThreadClient.GetMessages();
            ChatMessage            participantRemovedMessage       = messagesAfterParticipantRemoved.First(x => x.Type == ChatMessageType.ParticipantRemoved);

            Response typingNotificationResponse = chatThreadClient.SendTypingNotification();

            chatThreadClient.SendTypingNotification();

            Pageable <ChatThreadInfo> threads = chatClient.GetChatThreadsInfo();
            var threadsCount = threads.Count();

            chatClient.DeleteChatThread(threadId);

            //assert
            Assert.AreEqual(updatedTopic, chatThread.Topic);
            Assert.AreEqual(3, chatParticipantsOnCreationCount);
            Assert.AreEqual(messageContent, message.Content.Message);
            Assert.AreEqual(updatedMessageContent, actualUpdateMessage.Value.Content.Message);
            Assert.AreEqual(ChatMessageType.Text, message.Type);

            Assert.AreEqual(messageContent2, message2.Content.Message);
            Assert.AreEqual(displayNameMessage, message2.SenderDisplayName);
            Assert.AreEqual(messageContent3, message3.Content.Message);
            Assert.AreEqual(messageContent4, message4.Content.Message);
            Assert.AreEqual(messageContent5, message5.Content.Message);
            Assert.AreEqual(messageContent6, message6.Content.Message);

            Assert.AreEqual(2, threadsCount);
            Assert.AreEqual(8, getMessagesCount);  //Including all types : 5 text message, 3 control messages
            Assert.AreEqual(3, getMessagesCount2); //Including all types : 1 text message, 2 control messages

            Assert.AreEqual(1, participantAddedMessage.Content.Participants.Count);
            Assert.AreEqual(user5.Id, CommunicationIdentifierSerializer.Serialize(participantAddedMessage.Content.Participants[0].User).CommunicationUser.Id);
            Assert.AreEqual("user5", participantAddedMessage.Content.Participants[0].DisplayName);

            Assert.AreEqual(1, participantRemovedMessage.Content.Participants.Count);
            Assert.AreEqual(user4.Id, CommunicationIdentifierSerializer.Serialize(participantRemovedMessage.Content.Participants[0].User).CommunicationUser.Id);
            Assert.AreEqual("user4", participantRemovedMessage.Content.Participants[0].DisplayName);

            Assert.IsTrue(deletedChatMessage.DeletedOn.HasValue);
            Assert.AreEqual(3, chatParticipantsCount);
            Assert.AreEqual(5, chatParticipantsAfterTwoAddedCount);
            Assert.AreEqual(4, chatParticipantAfterOneDeletedCount);
            Assert.IsNull(addChatParticipantsResult.Errors);
            Assert.AreEqual((int)HttpStatusCode.OK, typingNotificationResponse.Status);
        }
        public async Task ThreadCGUD_ParticipantAUR_MessageGSU_NotificationT_Async()
        {
            //arr
            Console.WriteLine($"ThreadCGUD_ParticipantAUR_MessageGSU_NotificationT_Async Running on RecordedTestMode : {Mode}");
            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();

            (CommunicationUserIdentifier user1, string token1) = await CreateUserAndTokenAsync(communicationIdentityClient);

            (CommunicationUserIdentifier user2, _) = await CreateUserAndTokenAsync(communicationIdentityClient);

            (CommunicationUserIdentifier user3, string token3) = await CreateUserAndTokenAsync(communicationIdentityClient);

            (CommunicationUserIdentifier user4, _) = await CreateUserAndTokenAsync(communicationIdentityClient);

            (CommunicationUserIdentifier user5, _) = await CreateUserAndTokenAsync(communicationIdentityClient);

            string repeatabilityRequestId1 = "contoso-C0A747F1-6245-4307-8267-B974340677DC";
            string repeatabilityRequestId2 = "contoso-D0A747F1-6245-4307-8267-B974340677DD";

            var topic = "Thread async from C# sdk";
            var displayNameMessage = "DisplayName sender message 1";
            var participants       = new List <ChatParticipant>
            {
                new ChatParticipant(user1)
                {
                    DisplayName = "user1"
                },
                new ChatParticipant(user2)
                {
                    DisplayName = "user2"
                },
                new ChatParticipant(user3)
                {
                    DisplayName = "user3"
                }
            };
            ChatClient chatClient  = CreateInstrumentedChatClient(token1);
            ChatClient chatClient3 = CreateInstrumentedChatClient(token3);

            //act
            CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic, participants, repeatabilityRequestId1);

            ChatThreadClient chatThreadClient = GetInstrumentedChatThreadClient(chatClient, createChatThreadResult.ChatThread.Id);
            var threadId = chatThreadClient.Id;
            CreateChatThreadResult createChatThreadResult2 = await chatClient.CreateChatThreadAsync(topic, participants, repeatabilityRequestId2);

            ChatThreadClient chatThreadClient2 = GetInstrumentedChatThreadClient(chatClient, createChatThreadResult2.ChatThread.Id);
            ChatThreadClient chatThreadClient3 = GetInstrumentedChatThreadClient(chatClient3, threadId);

            AsyncPageable <ChatParticipant> chatParticipantsOnCreation = chatThreadClient.GetParticipantsAsync();
            var chatParticipantsOnCreationCount = chatParticipantsOnCreation.ToEnumerableAsync().Result.Count;

            var updatedTopic = "Updated topic - C# sdk";
            await chatThreadClient.UpdateTopicAsync(updatedTopic);

            ChatThread chatThread = await chatClient.GetChatThreadAsync(threadId);

            string messageContent = "Content for message 1";
            string messageId      = await chatThreadClient.SendMessageAsync(messageContent, ChatMessageType.Text, displayNameMessage);

            string messageContent2 = "Content for message 2";
            string messageId2      = await chatThreadClient2.SendMessageAsync(messageContent2, ChatMessageType.Html, displayNameMessage);

            string messageContent3 = "Content for message 3";
            string messageId3      = await chatThreadClient3.SendMessageAsync(messageContent3, ChatMessageType.Text, displayNameMessage);

            string messageContent4 = "Content for message 4";
            string messageId4      = await chatThreadClient3.SendMessageAsync(messageContent4, ChatMessageType.Html, displayNameMessage);

            string messageContent5 = "Content for message 5";
            string messageId5      = await chatThreadClient3.SendMessageAsync(messageContent5, ChatMessageType.Text, displayNameMessage);

            string messageContent6 = "Content for message 6";
            string messageId6      = await chatThreadClient3.SendMessageAsync(messageContent6, ChatMessageType.Html, displayNameMessage);

            ChatMessage message = await chatThreadClient.GetMessageAsync(messageId);

            ChatMessage message2 = await chatThreadClient2.GetMessageAsync(messageId2);

            ChatMessage message3 = await chatThreadClient3.GetMessageAsync(messageId3);

            ChatMessage message4 = await chatThreadClient3.GetMessageAsync(messageId4);

            ChatMessage message5 = await chatThreadClient3.GetMessageAsync(messageId5);

            ChatMessage message6 = await chatThreadClient3.GetMessageAsync(messageId6);

            AsyncPageable <ChatMessage> messages  = chatThreadClient.GetMessagesAsync();
            AsyncPageable <ChatMessage> messages2 = chatThreadClient2.GetMessagesAsync();
            var getMessagesCount  = messages.ToEnumerableAsync().Result.Count;
            var getMessagesCount2 = messages2.ToEnumerableAsync().Result.Count;

            #region Messages Pagination assertions
            AsyncPageable <ChatMessage> messagesPaginationTest = chatThreadClient.GetMessagesAsync();
            await PageableTester <ChatMessage> .AssertPaginationAsync(enumerableResource : messagesPaginationTest, expectedPageSize : 2, expectedTotalResources : 8);

            #endregion

            var updatedMessageContent = "This is message 1 content updated";
            await chatThreadClient.UpdateMessageAsync(messageId, updatedMessageContent);

            Response <ChatMessage> actualUpdateMessage = await chatThreadClient.GetMessageAsync(messageId);

            await chatThreadClient.DeleteMessageAsync(messageId);

            List <ChatMessage> messagesAfterOneDeleted = chatThreadClient.GetMessagesAsync().ToEnumerableAsync().Result;
            ChatMessage        deletedChatMessage      = messagesAfterOneDeleted.First(x => x.Id == messageId);

            #region Participants Pagination assertions
            AsyncPageable <ChatParticipant> chatParticipants = chatThreadClient.GetParticipantsAsync();
            var chatParticipantsCount = chatParticipants.ToEnumerableAsync().Result.Count;
            #endregion

            var newParticipant = new ChatParticipant(user4)
            {
                DisplayName = "user4"
            };
            var newParticipant2 = new ChatParticipant(user5)
            {
                DisplayName = "user5"
            };
            AddChatParticipantsResult addChatParticipantsResult = await chatThreadClient.AddParticipantsAsync(participants : new[] { newParticipant });

            AddChatParticipantsResult addChatParticipantsResult2 = await chatThreadClient.AddParticipantAsync(newParticipant2);

            AsyncPageable <ChatParticipant> chatParticipantsAfterTwoOneAdded = chatThreadClient.GetParticipantsAsync();
            await PageableTester <ChatParticipant> .AssertPaginationAsync(enumerableResource : chatParticipantsAfterTwoOneAdded, expectedPageSize : 2, expectedTotalResources : 5);

            var chatParticipantsAfterTwoOneAddedCount = chatParticipantsAfterTwoOneAdded.ToEnumerableAsync().Result.Count;

            List <ChatMessage> messagesAfterParticipantsAdded = chatThreadClient.GetMessagesAsync().ToEnumerableAsync().Result;
            ChatMessage        participantAddedMessage        = messagesAfterParticipantsAdded.First(x => x.Type == ChatMessageType.ParticipantAdded);

            CommunicationUserIdentifier participantToBeRemoved = user4;
            await chatThreadClient.RemoveParticipantAsync(identifier : participantToBeRemoved);

            AsyncPageable <ChatParticipant> chatParticipantAfterOneDeleted = chatThreadClient.GetParticipantsAsync();
            var chatParticipantAfterOneDeletedCount = chatParticipantAfterOneDeleted.ToEnumerableAsync().Result.Count;

            List <ChatMessage> messagesAfterParticipantRemoved = chatThreadClient.GetMessagesAsync().ToEnumerableAsync().Result;
            ChatMessage        participantRemovedMessage       = messagesAfterParticipantRemoved.First(x => x.Type == ChatMessageType.ParticipantRemoved);

            ChatMessage participantRemovedMessage2 = await chatThreadClient.GetMessageAsync(participantRemovedMessage.Id);

            Response typingNotificationResponse = await chatThreadClient.SendTypingNotificationAsync();

            await chatThreadClient.SendTypingNotificationAsync();

            AsyncPageable <ChatThreadInfo> threads = chatClient.GetChatThreadsInfoAsync();
            var threadsCount = threads.ToEnumerableAsync().Result.Count;

            await chatClient.DeleteChatThreadAsync(threadId);

            //assert
            Assert.AreEqual(updatedTopic, chatThread.Topic);
            Assert.AreEqual(3, chatParticipantsOnCreationCount);
            Assert.AreEqual(messageContent, message.Content.Message);
            Assert.AreEqual(displayNameMessage, message.SenderDisplayName);
            Assert.AreEqual(updatedMessageContent, actualUpdateMessage.Value.Content.Message);
            Assert.AreEqual(ChatMessageType.Text, message.Type);

            Assert.AreEqual(messageContent2, message2.Content.Message);
            Assert.AreEqual(messageContent3, message3.Content.Message);
            Assert.AreEqual(messageContent4, message4.Content.Message);
            Assert.AreEqual(messageContent5, message5.Content.Message);
            Assert.AreEqual(messageContent6, message6.Content.Message);

            Assert.AreEqual(2, threadsCount);
            Assert.AreEqual(8, getMessagesCount);  //Including all types : 5 text message, 3 control messages
            Assert.AreEqual(3, getMessagesCount2); //Including all types : 1 text message, 2 control messages

            Assert.AreEqual(1, participantAddedMessage.Content.Participants.Count);
            Assert.AreEqual(user5.Id, CommunicationIdentifierSerializer.Serialize(participantAddedMessage.Content.Participants[0].User).CommunicationUser.Id);
            Assert.AreEqual("user5", participantAddedMessage.Content.Participants[0].DisplayName);

            Assert.AreEqual(1, participantRemovedMessage.Content.Participants.Count);
            Assert.AreEqual(user4.Id, CommunicationIdentifierSerializer.Serialize(participantRemovedMessage.Content.Participants[0].User).CommunicationUser.Id);
            Assert.AreEqual("user4", participantRemovedMessage.Content.Participants[0].DisplayName);

            Assert.IsTrue(deletedChatMessage.DeletedOn.HasValue);
            Assert.AreEqual(3, chatParticipantsCount);
            Assert.AreEqual(5, chatParticipantsAfterTwoOneAddedCount);
            Assert.AreEqual(4, chatParticipantAfterOneDeletedCount);
            Assert.IsNull(addChatParticipantsResult.Errors);
            Assert.IsNull(addChatParticipantsResult2.Errors);
            Assert.AreEqual((int)HttpStatusCode.OK, typingNotificationResponse.Status);
        }
 /// <summary>Asynchronously gets a Relay Configuration for a <see cref="CommunicationUserIdentifier"/>.</summary>
 /// <param name="communicationUser">The <see cref="CommunicationUserIdentifier"/> for whom to issue a token.</param>
 /// <param name="routeType"> The specified <see cref="RouteType"/> for the relay request </param>
 /// <param name="cancellationToken">The cancellation token to use.</param>
 public virtual async Task <Response <CommunicationRelayConfiguration> > GetRelayConfigurationAsync(CommunicationUserIdentifier communicationUser = null, RouteType?routeType = null, CancellationToken cancellationToken = default)
 {
     using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CommunicationRelayClient)}.{nameof(GetRelayConfiguration)}");
     scope.Start();
     try
     {
         return(await RestClient.IssueRelayConfigurationAsync(communicationUser?.Id, routeType, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception ex)
     {
         scope.Failed(ex);
         throw;
     }
 }
Exemple #30
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            Uri endpoint = new Uri("https://<RESOURCE_NAME>.communication.azure.com");

            CommunicationTokenCredential communicationTokenCredential = new CommunicationTokenCredential("<Access_Token>");
            ChatClient chatClient = new ChatClient(endpoint, communicationTokenCredential);

            // <Start a chat thread>
            var chatParticipant = new ChatParticipant(identifier: new CommunicationUserIdentifier(id: "<Access_ID>"))
            {
                DisplayName = "UserDisplayName"
            };
            CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new[] { chatParticipant });

            // <Get a chat thread client>
            ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(threadId: createChatThreadResult.ChatThread.Id);
            string           threadId         = chatThreadClient.Id;

            // <List all chat threads>
            AsyncPageable <ChatThreadItem> chatThreadItems = chatClient.GetChatThreadsAsync();

            await foreach (ChatThreadItem chatThreadItem in chatThreadItems)
            {
                Console.WriteLine($"{ chatThreadItem.Id}");
            }

            // <Send a message to a chat thread>
            SendChatMessageResult sendChatMessageResult = await chatThreadClient.SendMessageAsync(content : "hello world", type : ChatMessageType.Text);

            string messageId = sendChatMessageResult.Id;

            // <Receive chat messages from a chat thread>
            AsyncPageable <ChatMessage> allMessages = chatThreadClient.GetMessagesAsync();

            await foreach (ChatMessage message in allMessages)
            {
                Console.WriteLine($"{message.Id}:{message.Content.Message}");
            }

            // <Add a user as a participant to the chat thread>
            var josh   = new CommunicationUserIdentifier(id: "<Access_ID_For_Josh>");
            var gloria = new CommunicationUserIdentifier(id: "<Access_ID_For_Gloria>");
            var amy    = new CommunicationUserIdentifier(id: "<Access_ID_For_Amy>");

            var participants = new[]
            {
                new ChatParticipant(josh)
                {
                    DisplayName = "Josh"
                },
                new ChatParticipant(gloria)
                {
                    DisplayName = "Gloria"
                },
                new ChatParticipant(amy)
                {
                    DisplayName = "Amy"
                }
            };
            await chatThreadClient.AddParticipantsAsync(participants : participants);

            // <Get thread participants>
            AsyncPageable <ChatParticipant> allParticipants = chatThreadClient.GetParticipantsAsync();

            await foreach (ChatParticipant participant in allParticipants)
            {
                Console.WriteLine($"{((CommunicationUserIdentifier)participant.User).Id}:{participant.DisplayName}:{participant.ShareHistoryTime}");
            }

            // <Send read receipt>
            await chatThreadClient.SendReadReceiptAsync(messageId : messageId);
        }