internal ReadReceipt(string senderId, string chatMessageId, DateTimeOffset?readOn) { SenderId = senderId; Sender = new CommunicationUser(senderId); ChatMessageId = chatMessageId; ReadOn = readOn; }
public async Task GivenAggregateCommunicationRequestFor5ApplicationsSubmittedFor3Recipients_ShouldQueue3ComposeMessages() { var recipientOne = new CommunicationUser("1", "*****@*****.**", "a", "person", UserParticipation.PrimaryUser); var recipientTwo = new CommunicationUser("2", "*****@*****.**", "b", "person", UserParticipation.PrimaryUser); var recipientThree = new CommunicationUser("3", "*****@*****.**", "c", "person", UserParticipation.PrimaryUser); var messages = Enumerable.Concat(Enumerable.Concat(Enumerable.Repeat(new CommunicationMessage() { Recipient = recipientOne }, 3), Enumerable.Repeat(new CommunicationMessage() { Recipient = recipientTwo }, 3)), Enumerable.Repeat(new CommunicationMessage() { Recipient = recipientThree }, 3)); var from = DateTime.UtcNow.AddDays(-1); var to = DateTime.UtcNow; _mockRepository.Setup(x => x.GetScheduledMessagesSinceAsync(CommunicationConstants.RequestType.ApplicationSubmitted, DeliveryFrequency.Daily, from, to)) .ReturnsAsync(messages); var aggCommRequest = new AggregateCommunicationRequest(Guid.NewGuid(), CommunicationConstants.RequestType.ApplicationSubmitted, DeliveryFrequency.Daily, DateTime.UtcNow, from, to); await _sut.ProcessAggregateCommunicationRequestAsync(aggCommRequest); _mockRepository.Verify(x => x.GetScheduledMessagesSinceAsync(aggCommRequest.RequestType, aggCommRequest.Frequency, aggCommRequest.FromDateTime, aggCommRequest.ToDateTime), Times.Once); _mockComposeQueuePublisher.Verify(x => x.AddMessageAsync(It.IsAny <AggregateCommunicationComposeRequest>()), Times.Exactly(3)); }
internal CommunicationUserToken(string id, string token, DateTimeOffset expiresOn) { Id = id; User = new CommunicationUser(id); Token = token; ExpiresOn = expiresOn; }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log) { string code = req.Query["entryCode"]; string correctCode = Environment.GetEnvironmentVariable("EntryCode"); if (correctCode != null && code.ToLower() == correctCode.ToLower()) { CommunicationIdentityClient _client = new CommunicationIdentityClient(Environment.GetEnvironmentVariable("ACS_Connection_String")); Response <CommunicationUser> userResponse = await _client.CreateUserAsync(); CommunicationUser user = userResponse.Value; Response <CommunicationUserToken> tokenResponse = await _client.IssueTokenAsync(user, scopes : new[] { CommunicationTokenScope.VoIP }); string token = tokenResponse.Value.Token; DateTimeOffset expiresOn = tokenResponse.Value.ExpiresOn; return(new OkObjectResult(tokenResponse)); } else { Random rnd = new Random(); System.Threading.Thread.Sleep(rnd.Next(500, 5000)); return(new UnauthorizedResult()); } }
public async Task <IHttpActionResult> ACSRefreshAsync(TokenRequest request) { var client = new CommunicationIdentityClient(connectionString); var identitytoRefresh = new CommunicationUser(request.UserEmail); var tokenResponse = await client.IssueTokenAsync(identitytoRefresh, scopes : new[] { CommunicationTokenScope.VoIP }); return(Ok(tokenResponse.Value)); }
/// <summary> /// A member of the chat thread. /// </summary> /// <param name="communicationUser">Instance of <see cref="CommunicationUser"/>.</param> public ChatThreadMember(CommunicationUser communicationUser) { if (communicationUser == null || communicationUser.Id == null) { throw new ArgumentNullException(nameof(communicationUser)); } User = communicationUser; }
/// <summary> /// A member of the chat thread. /// </summary> /// <param name="communicationUser">Instance of <see cref="CommunicationUser"/>.</param> public ChatParticipant(CommunicationUser communicationUser) { if (communicationUser == null || communicationUser.Id == null) { throw new ArgumentNullException(nameof(communicationUser)); } User = communicationUser; }
internal ChatThread(ChatThreadInternal chatThreadInternal) { Id = chatThreadInternal.Id; Topic = chatThreadInternal.Topic; CreatedOn = chatThreadInternal.CreatedOn; CreatedBy = new CommunicationUser(chatThreadInternal.CreatedBy); Participants = chatThreadInternal.Participants.Select(x => x.ToChatParticipant()).ToList(); }
internal ChatThread(ChatThreadInternal chatThreadInternal) { Id = chatThreadInternal.Id; Topic = chatThreadInternal.Topic; CreatedOn = chatThreadInternal.CreatedOn; CreatedBy = new CommunicationUser(chatThreadInternal.CreatedBy); Members = chatThreadInternal.Members.Select(x => x.ToChatThreadMember()).ToList(); }
public User(string userId, CommunicationUser communicationUser) { UserId = userId; CommunicationUser = communicationUser; ChatThreadMember = new ChatThreadMember(CommunicationUser) { DisplayName = UserId, ShareHistoryTime = new System.DateTimeOffset(), User = communicationUser }; }
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 CommunicationUser(senderId); }
/// <summary>Asynchronously deletes a <see cref="CommunicationUser"/>, 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(CommunicationUser 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; } }
/// <summary>Revokes all the tokens created for a user.</summary> /// <param name="communicationUser">The <see cref="CommunicationUser"/> 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(CommunicationUser 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>Issues a token for a <see cref="CommunicationUser"/>.</summary> /// <param name="scopes">The scopes that the token should have.</param> /// <param name="communicationUser">The <see cref="CommunicationUser"/> 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(CommunicationUser 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; } }
/// <summary>Asynchronously deletes a <see cref="CommunicationUser"/>, 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> public virtual async Task <Response> DeleteUserAsync(CommunicationUser communicationUser, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CommunicationIdentityClient)}.{nameof(DeleteUser)}"); scope.Start(); try { return(await RestClient.DeleteAsync(communicationUser.Id, cancellationToken).ConfigureAwait(false)); } catch (Exception ex) { scope.Failed(ex); throw; } }
public async Task <CommunicationUserToken> RefreshTokenAsync(string resourceConnectionString, string identity) { try { var communicationIdentityClient = new CommunicationIdentityClient(resourceConnectionString); var user = new CommunicationUser(identity); var tokenResponse = await communicationIdentityClient.IssueTokenAsync(user, scopes : new[] { CommunicationTokenScope.Chat }); return(tokenResponse); } catch { throw; } }
public async Task <IActionResult> GetAsync() { try { Response <CommunicationUser> userResponse = await _client.CreateUserAsync(); CommunicationUser user = userResponse.Value; Response <CommunicationUserToken> tokenResponse = await _client.IssueTokenAsync(user, scopes : new[] { CommunicationTokenScope.VoIP }); string token = tokenResponse.Value.Token; DateTimeOffset expiresOn = tokenResponse.Value.ExpiresOn; return(this.Ok(tokenResponse)); } catch (RequestFailedException ex) { Console.WriteLine($"Error occured while Generating Token: {ex}"); return(this.Ok(this.Json(ex))); } }
public void E2E_ThreadCreateUpdateGetDelete_MemberAddUpdateRemove_MessageGetSendUpdate_NotificationTyping_ReadReceiptGetSend() { //arr CommunicationUser user1, user2, user3; string token1, token2, token3; CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient(); (user1, token1) = CreateUserAndToken(communicationIdentityClient); (user2, token2) = CreateUserAndToken(communicationIdentityClient); (user3, token3) = CreateUserAndToken(communicationIdentityClient); var topic = "Thread sync from C# sdk"; var messageContent = "This is message 1 content"; var updatedMessageContent = "This is message 1 content updated"; var displayNameMessage = "DisplayName sender message 1"; var updatedTopic = "Updated topic - C# sdk"; var members = new List <ChatThreadMember> { new ChatThreadMember(user1), new ChatThreadMember(user2) }; ChatClient chatClient = CreateInstrumentedChatClient(token1); ChatClient chatClient2 = CreateInstrumentedChatClient(token2); //act #region Snippet:Azure_Communication_Chat_Tests_E2E_InitializeChatThreadClient //@@ChatThreadClient chatThreadClient1 = chatClient.CreateChatThread("Thread topic", members); // Alternatively, if you have created a chat thread before and you have its threadId, you can create a ChatThreadClient instance using: //@@ChatThreadClient chatThreadClient2 = chatClient.GetChatThreadClient("threadId"); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_InitializeChatThreadClient ChatThreadClient chatThreadClient = CreateInstrumentedChatThreadClient(chatClient, topic, members); ChatThreadClient chatThreadClient2 = CreateInstrumentedChatThreadClient(chatClient, topic, members); #region Snippet:Azure_Communication_Chat_Tests_E2E_UpdateThread chatThreadClient.UpdateThread("Updated topic - C# sdk"); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_UpdateThread var threadId = chatThreadClient.Id; #region Snippet:Azure_Communication_Chat_Tests_E2E_GetChatThread ChatThread chatThread = chatClient.GetChatThread(threadId); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_GetChatThread #region Snippet:Azure_Communication_Chat_Tests_E2E_GetChatThreadsInfo Pageable <ChatThreadInfo> threads = chatClient.GetChatThreadsInfo(); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_GetChatThreadsInfo var threadsCount = threads.Count(); #region Snippet:Azure_Communication_Chat_Tests_E2E_SendMessage SendChatMessageResult sendChatMessageResult = chatThreadClient.SendMessage("This is message 1 content", ChatMessagePriority.High, displayNameMessage); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_SendMessage SendChatMessageResult sendChatMessageResult2 = chatThreadClient.SendMessage(messageContent, ChatMessagePriority.High, displayNameMessage); var messageId = sendChatMessageResult.Id; #region Snippet:Azure_Communication_Chat_Tests_E2E_GetMessage ChatMessage message = chatThreadClient.GetMessage(messageId); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_GetMessage #region Snippet:Azure_Communication_Chat_Tests_E2E_GetMessages Pageable <ChatMessage> messages = chatThreadClient.GetMessages(); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_GetMessages var getMessagesCount = messages.Count(); #region Snippet:Azure_Communication_Chat_Tests_E2E_UpdateMessage chatThreadClient.UpdateMessage(messageId, "This is message 1 content updated"); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_UpdateMessage Response <ChatMessage> actualUpdateMessage = chatThreadClient.GetMessage(messageId); #region Snippet:Azure_Communication_Chat_Tests_E2E_DeleteMessage chatThreadClient.DeleteMessage(messageId); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_DeleteMessage Pageable <ChatMessage> messagesAfterOneDeleted = chatThreadClient.GetMessages(); ChatMessage deletedChatMessage = messagesAfterOneDeleted.First(x => x.Id == messageId); #region Snippet:Azure_Communication_Chat_Tests_E2E_GetMembers Pageable <ChatThreadMember> chatThreadMembers = chatThreadClient.GetMembers(); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_GetMembers var chatThreadMembersCount = chatThreadMembers.Count(); var newMember = new ChatThreadMember(user3); #region Snippet:Azure_Communication_Chat_Tests_E2E_AddMembers chatThreadClient.AddMembers(members: new[] { newMember }); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_AddMembers Pageable <ChatThreadMember> chatThreadMembersAfterOneAdded = chatThreadClient.GetMembers(); var chatThreadMembersAfterOneAddedCount = chatThreadMembersAfterOneAdded.Count(); CommunicationUser memberToBeRemoved = user3; //Better name for the snippet #region Snippet:Azure_Communication_Chat_Tests_E2E_RemoveMember chatThreadClient.RemoveMember(user: memberToBeRemoved); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_RemoveMember Pageable <ChatThreadMember> chatThreadMembersAfterOneDeleted = chatThreadClient.GetMembers(); var chatThreadMembersAfterOneDeletedCount = chatThreadMembersAfterOneDeleted.Count(); Response typingNotificationResponse = chatThreadClient.SendTypingNotification(); #region Snippet:Azure_Communication_Chat_Tests_E2E_SendTypingNotification chatThreadClient.SendTypingNotification(); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_SendTypingNotification #region Snippet:Azure_Communication_Chat_Tests_E2E_SendReadReceipt chatThreadClient.SendReadReceipt(messageId); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_SendReadReceipt chatThreadClient.SendReadReceipt(sendChatMessageResult2.Id); #region Snippet:Azure_Communication_Chat_Tests_E2E_GetReadReceipts Pageable <ReadReceipt> readReceipts = chatThreadClient.GetReadReceipts(); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_GetReadReceipts var readReceiptsCount = readReceipts.Count(); #region Snippet:Azure_Communication_Chat_Tests_E2E_DeleteChatThread chatClient.DeleteChatThread(threadId); #endregion Snippet:Azure_Communication_Chat_Tests_E2E_DeleteChatThread //assert Assert.AreEqual(updatedTopic, chatThread.Topic); Assert.AreEqual(2, chatThread.Members.Count); Assert.AreEqual(messageContent, message.Content); Assert.AreEqual(displayNameMessage, message.SenderDisplayName); Assert.AreEqual(ChatMessagePriority.High, message.Priority); Assert.AreEqual(2, threadsCount); Assert.AreEqual(5, getMessagesCount); //Including all types Assert.AreEqual(updatedMessageContent, actualUpdateMessage.Value.Content); Assert.IsTrue(deletedChatMessage.DeletedOn.HasValue); Assert.AreEqual(2, chatThreadMembersCount); Assert.AreEqual(3, chatThreadMembersAfterOneAddedCount); Assert.AreEqual(2, chatThreadMembersAfterOneDeletedCount); Assert.AreEqual((int)HttpStatusCode.OK, typingNotificationResponse.Status); // TODO: Commenting out the assert below for now as it is flakey due to server-side delay; currently in investigation // Assert.AreEqual(1, readReceiptsCount); }
public async Task E2E_ThreadCreateUpdateGetDelete_MemberAddUpdateRemove_MessageGetSendUpdate_NotificationTyping_ReadReceiptGetSend_Async() { //arr CommunicationUser user1, user2, user3; string token1, token2, token3; CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient(); (user1, token1) = await CreateUserAndTokenAsync(communicationIdentityClient); (user2, token2) = await CreateUserAndTokenAsync(communicationIdentityClient); (user3, token3) = await CreateUserAndTokenAsync(communicationIdentityClient); var topic = "Thread Async from C# sdk"; var contentMessage = "This is message 1"; var updatedMessageContent = "This is message 1 updated"; var displayNameMessage = "DisplayName sender message 1"; var updatedTopic = "Updated topic - C# sdk"; var members = new List <ChatThreadMember> { new ChatThreadMember(user1), new ChatThreadMember(user2) }; ChatClient chatClient = CreateInstrumentedChatClient(token1); ChatClient chatClient2 = CreateInstrumentedChatClient(token2); //act ChatThreadClient chatThreadClient = await CreateInstrumentedChatThreadClientAsync(chatClient, topic, members); ChatThreadClient chatThreadClient2 = await CreateInstrumentedChatThreadClientAsync(chatClient, topic, members); await chatThreadClient.UpdateThreadAsync(updatedTopic); ChatThread chatThread = await chatClient.GetChatThreadAsync(chatThreadClient.Id); AsyncPageable <ChatThreadInfo> threads = chatClient.GetChatThreadsInfoAsync(); var threadsCount = threads.ToEnumerableAsync().Result.Count; SendChatMessageResult sendChatMessageResult = await chatThreadClient.SendMessageAsync(contentMessage, ChatMessagePriority.High, displayNameMessage); SendChatMessageResult sendChatMessageResult2 = await chatThreadClient.SendMessageAsync(contentMessage, ChatMessagePriority.High, displayNameMessage); ChatMessage message = await chatThreadClient.GetMessageAsync(sendChatMessageResult.Id); AsyncPageable <ChatMessage> messages = chatThreadClient.GetMessagesAsync(); var getMessagesCount = messages.ToEnumerableAsync().Result.Count; var messageId = sendChatMessageResult.Id; await chatThreadClient.UpdateMessageAsync(messageId, updatedMessageContent); Response <ChatMessage> actualUpdateMessage = await chatThreadClient.GetMessageAsync(messageId); await chatThreadClient.DeleteMessageAsync(messageId); AsyncPageable <ChatMessage> messagesAfterOneDeleted = chatThreadClient.GetMessagesAsync(); ChatMessage deletedChatMessage = messagesAfterOneDeleted.ToEnumerableAsync().Result.First(x => x.Id == messageId); AsyncPageable <ChatThreadMember> chatThreadMembers = chatThreadClient.GetMembersAsync(); var chatThreadMembersCount = chatThreadMembers.ToEnumerableAsync().Result.Count; var newMember = new ChatThreadMember(user3); await chatThreadClient.AddMembersAsync(new List <ChatThreadMember> { newMember }); AsyncPageable <ChatThreadMember> chatThreadMembersAfterOneAdded = chatThreadClient.GetMembersAsync(); var chatThreadMembersAfterOneAddedCount = chatThreadMembersAfterOneAdded.ToEnumerableAsync().Result.Count(); CommunicationUser userToBeRemoved = user3; //Better name for the snippet await chatThreadClient.RemoveMemberAsync(userToBeRemoved); AsyncPageable <ChatThreadMember> chatThreadMembersAfterOneDeleted = chatThreadClient.GetMembersAsync(); var chatThreadMembersAfterOneDeletedCount = chatThreadMembersAfterOneDeleted.ToEnumerableAsync().Result.Count(); Response typingNotificationResponse = await chatThreadClient.SendTypingNotificationAsync(); await chatThreadClient.SendTypingNotificationAsync(); await chatThreadClient.SendReadReceiptAsync(messageId); await chatThreadClient.SendReadReceiptAsync(sendChatMessageResult2.Id); AsyncPageable <ReadReceipt> readReceipts = chatThreadClient.GetReadReceiptsAsync(); var readReceiptsCount = readReceipts.ToEnumerableAsync().Result.Count(); await chatClient.DeleteChatThreadAsync(chatThreadClient.Id); //assert Assert.AreEqual(updatedTopic, chatThread.Topic); Assert.AreEqual(2, chatThread.Members.Count); Assert.AreEqual(contentMessage, message.Content); Assert.AreEqual(displayNameMessage, message.SenderDisplayName); Assert.AreEqual(ChatMessagePriority.High, message.Priority); Assert.AreEqual(2, threadsCount); Assert.AreEqual(5, getMessagesCount); //Including all types Assert.AreEqual(updatedMessageContent, actualUpdateMessage.Value.Content); Assert.IsTrue(deletedChatMessage.DeletedOn.HasValue); Assert.AreEqual(2, chatThreadMembersCount); Assert.AreEqual(3, chatThreadMembersAfterOneAddedCount); Assert.AreEqual(2, chatThreadMembersAfterOneDeletedCount); Assert.AreEqual((int)HttpStatusCode.OK, typingNotificationResponse.Status); //TODO: Commenting out the assert below for now as it is flakey due to server-side delay; currently in investigation // Assert.AreEqual(1, readReceiptsCount); }
public Azure.Response RemoveMember(CommunicationUser user) => RemoveMemberAsync(user).Result;
public async Task <CommunicationUserPreference> GetUserPreferenceAsync(string requestType, CommunicationUser user) { var userPref = new CommunicationUserPreference() { Channels = DeliveryChannelPreferences.None }; var userPreference = await _repository.GetAsync(user.UserId); switch (requestType) { case CommunicationConstants.RequestType.VacancyRejected: SetPreferencesForVacancyRejectedNotification(userPref, userPreference); return(userPref); case CommunicationConstants.RequestType.ApplicationSubmitted: SetPreferencesForApplicationSubmittedNotification(userPref, userPreference); return(userPref); case CommunicationConstants.RequestType.VacancyWithdrawnByQa: case CommunicationConstants.RequestType.ProviderBlockedProviderNotification: case CommunicationConstants.RequestType.ProviderBlockedEmployerNotificationForTransferredVacancies: case CommunicationConstants.RequestType.ProviderBlockedEmployerNotificationForLiveVacancies: case CommunicationConstants.RequestType.ProviderBlockedEmployerNotificationForPermissionOnly: SetPreferencesForMandatoryOrganisationEmailNotification(userPref); return(userPref); default: throw new NotImplementedException($"User preferences not implemented for request {requestType}"); } }
internal ChatParticipant(ChatParticipantInternal chatThreadMemberInternal) { User = new CommunicationUser(chatThreadMemberInternal.Id); DisplayName = chatThreadMemberInternal.DisplayName; ShareHistoryTime = chatThreadMemberInternal.ShareHistoryTime; }
public async Task <Azure.Response> RemoveMemberAsync(CommunicationUser user) { return(await Client.RemoveMemberAsync(user)); }
public async Task CreateGetUpdateDeleteThreadAsync() { CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString); Response <CommunicationUser> threadMember = await communicationIdentityClient.CreateUserAsync(); CommunicationUserToken communicationUserToken = await communicationIdentityClient.IssueTokenAsync(threadMember.Value, new[] { CommunicationTokenScope.Chat }); string userToken = communicationUserToken.Token; string endpoint = TestEnvironment.ChatApiUrl(); string threadCreatorId = communicationUserToken.User.Id; #region Snippet:Azure_Communication_Chat_Tests_Samples_CreateChatClient ChatClient chatClient = new ChatClient( new Uri(endpoint), new CommunicationUserCredential(userToken)); #endregion Snippet:Azure_Communication_Chat_Tests_Samples_CreateChatClient var threadCreator = new CommunicationUser(threadCreatorId); #region Snippet:Azure_Communication_Chat_Tests_Samples_CreateThread var chatParticipant = new ChatParticipant(threadCreator) { DisplayName = "UserDisplayName" }; ChatThreadClient chatThreadClient = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new[] { chatParticipant }); string threadId = chatThreadClient.Id; #endregion Snippet:Azure_Communication_Chat_Tests_Samples_CreateThread #region Snippet:Azure_Communication_Chat_Tests_Samples_GetThread ChatThread chatThread = await chatClient.GetChatThreadAsync(threadId); #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetThread #region Snippet:Azure_Communication_Chat_Tests_Samples_GetThreads AsyncPageable <ChatThreadInfo> chatThreadsInfo = chatClient.GetChatThreadsInfoAsync(); await foreach (ChatThreadInfo chatThreadInfo in chatThreadsInfo) { Console.WriteLine($"{ chatThreadInfo.Id}"); } #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetThreads #region Snippet:Azure_Communication_Chat_Tests_Samples_UpdateThread var topic = "new topic"; await chatThreadClient.UpdateTopicAsync(topic); #endregion Snippet:Azure_Communication_Chat_Tests_Samples_UpdateThread #region Snippet:Azure_Communication_Chat_Tests_Samples_DeleteThread await chatClient.DeleteChatThreadAsync(threadId); #endregion Snippet:Azure_Communication_Chat_Tests_Samples_DeleteThread var josh = new ChatParticipant(new CommunicationUser("invalid user")); #region Snippet:Azure_Communication_Chat_Tests_Samples_Troubleshooting try { ChatThreadClient chatThreadClient_ = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new[] { josh }); } catch (RequestFailedException ex) { Console.WriteLine(ex.Message); } #endregion Snippet:Azure_Communication_Chat_Tests_Samples_Troubleshooting catch (Exception ex) { Assert.Fail($"Unexpected error: {ex}"); } }
public async Task GetAddRemoveMembersAsync() { CommunicationIdentityClient communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString); Response <CommunicationUser> joshResponse = await communicationIdentityClient.CreateUserAsync(); CommunicationUser josh = joshResponse.Value; Response <CommunicationUser> gloriaResponse = await communicationIdentityClient.CreateUserAsync(); CommunicationUser gloria = gloriaResponse.Value; Response <CommunicationUser> amyResponse = await communicationIdentityClient.CreateUserAsync(); CommunicationUser amy = amyResponse.Value; CommunicationUserToken joshTokenResponse = await communicationIdentityClient.IssueTokenAsync(josh, new[] { CommunicationTokenScope.Chat }); ChatClient chatClient = new ChatClient( new Uri(TestEnvironment.ChatApiUrl()), new CommunicationUserCredential(joshTokenResponse.Token)); var chatParticipant = new ChatParticipant(josh) { DisplayName = "Josh", ShareHistoryTime = DateTime.MinValue }; ChatThreadClient chatThreadClient = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new[] { chatParticipant }); string threadId = chatThreadClient.Id; #region Snippet:Azure_Communication_Chat_Tests_Samples_GetParticipants AsyncPageable <ChatParticipant> allParticipants = chatThreadClient.GetParticipantsAsync(); await foreach (ChatParticipant participant in allParticipants) { Console.WriteLine($"{participant.User.Id}:{participant.DisplayName}:{participant.ShareHistoryTime}"); } #endregion Snippet:Azure_Communication_Chat_Tests_GetMembers #region Snippet:Azure_Communication_Chat_Tests_Samples_AddParticipants var participants = new[] { new ChatParticipant(josh) { DisplayName = "Josh" }, new ChatParticipant(gloria) { DisplayName = "Gloria" }, new ChatParticipant(amy) { DisplayName = "Amy" } }; await chatThreadClient.AddParticipantsAsync(participants); #endregion Snippet:Azure_Communication_Chat_Tests_Samples_AddParticipants #region Snippet:Azure_Communication_Chat_Tests_Samples_RemoveParticipant await chatThreadClient.RemoveParticipantAsync(gloria); #endregion Snippet:Azure_Communication_Chat_Tests_Samples_RemoveParticipant await chatClient.DeleteChatThreadAsync(threadId); }