Exemplo n.º 1
0
 void Start()
 {
     chatClient = new ChatClient(this);
     characterName = PlayFabDataStore.characterName;
     chatField.text = "<color=yellow>Welcome to Soulless! Have Fun!</color>\n";
     Connect();
 }
Exemplo n.º 2
0
        /// <summary>
        /// Used to login to chat service.
        /// </summary>
        /// <param name="userInfo">User informations</param>
        public void Login(UserInfo userInfo)
        {
            //Check nick if it is being used by another user
            if (FindClientByNick(userInfo.Nick) != null)
            {
                throw new NickInUseException("The nick '" + userInfo.Nick + "' is being used by another user. Please select another one.");
            }

            //Get a reference to the current client that is calling this method
            var client = CurrentClient;

            //Get a proxy object to call methods of client when needed
            var clientProxy = client.GetClientProxy<IChatClient>();

            //Create a ChatClient and store it in a collection
            var chatClient = new ChatClient(client, clientProxy, userInfo);
            _clients[client.ClientId] = chatClient;

            //Register to Disconnected event to know when user connection is closed
            client.Disconnected += Client_Disconnected;

            //Start a new task to send user list to new user and to inform
            //all users that a new user joined to room
            Task.Factory.StartNew(
                () =>
                {
                    OnUserListChanged();
                    SendUserListToClient(chatClient);
                    SendUserLoginInfoToAllClients(userInfo);
                });
        }
Exemplo n.º 3
0
 public static void Run()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     var client = new ChatClient();
     Application.Run(client.Form);
 }
Exemplo n.º 4
0
        private static async Task ChatAsync(ChatClient from, ChatClient to)
        {
            await from.WriteLineAsync("Found one say hi");
            await to.WriteLineAsync("Found one say hi");

            var fromTask = from.Stream.CopyToAsync(to.Stream);
            var toTask = to.Stream.CopyToAsync(from.Stream);

            var result = await Task.WhenAny(fromTask, toTask);

            if (fromTask.IsCompleted && toTask.IsCompleted)
            {
                // Noop
                from.Dispose();
                to.Dispose();
            }
            else if (result == fromTask)
            {
                from.Dispose();
                await to.WriteLineAsync("Your partner left!");
                Match(to);
            }
            else if (result == toTask)
            {
                to.Dispose();
                await from.WriteLineAsync("Your partner left!");
                Match(from);
            }
        }
 public ChatWindow(ChatClient c, MainClient o)
 {
     InitializeComponent();
     this.chat = c;
     this.online = o;
     chat.DataReceived += Chat_DataReceived;
 }
Exemplo n.º 6
0
        public static void Main(string[] args)
        {
            Console.Write("Please enter your userName: "******"Starting...");

            var chat = new ChatClient(userName);

            _chattedEventObserver = new ChattedEventObserver();
            chat.Feed.Subscribe(_chattedEventObserver);
            new Task(chat.Start, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning).Start();

            _talker = new ChatTalker(chat.Queue, _cancellationTokenSource, userName);

            _talker.Send("({0} joined)", userName);

            new Task(_talker.Start, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning).Start();
            while (!_cancellationTokenSource.Token.IsCancellationRequested)
            {
                _cancellationTokenSource.Token.WaitHandle.WaitOne(new TimeSpan(0, 0, 1));
            }

            _talker.Send("({0} left)", userName);

            // TODO: console close/shutdown?
            // http://stackoverflow.com/questions/6591786/graceful-shutdown-of-console-apps-in-win-vista-7-2008
        }
Exemplo n.º 7
0
        public MainForm()
        {
            InitializeComponent();
            AlignWindow();

            //Start Dinu!
            Stream stream = File.Open("config.info", FileMode.Open);
            BinaryFormatter bformatter = new BinaryFormatter();
            bformatter = new BinaryFormatter();

            ConnectingSettingsData info = (ConnectingSettingsData)bformatter.Deserialize(stream);
            stream.Close();

            int port = Int32.Parse(info.port);

            _chatClient = new ChatClient(info.ip, port);
            _chatClient.SetMessageReceiver(ReceiveMessage);
            _chatClient.SetFileReceiver(ConfirmFileReceivement, GetSavePath);
            _chatClient.SetFriendRequestConfirmation(ConfirmFriendRequest);
            _chatClient.SetNotifier(Notify);

            //or in other place

            //End Dinu!
        }
Exemplo n.º 8
0
 private void buttonRegister_Click(object sender, EventArgs e)
 {
     var _chatClient = new ChatClient("Unisex");
     var user = new User();
     try
     {
         if (textBoxUsername.Text != null && textBoxUsername.Text != "" && textBoxPassword.Text != null && textBoxPassword.Text != "" &&
             (radioButtonMan.Checked || radioButtonWoman.Checked))
         {
             user.UserName = textBoxUsername.Text;
             user.Password = textBoxPassword.Text;
             if (radioButtonMan.Checked)
                 user.Gender = radioButtonMan.Text;
             if (radioButtonWoman.Checked)
                 user.Gender = radioButtonWoman.Text;
             _chatClient.RegisterUser(user);
             this.Hide();
         }
         else
         {
             MessageBox.Show("All fields must be completed");
         }
     }
     catch (FaultException ex)
     {
         GlobalMethods.ErrorMessages("Unisex", "Service error", ex.Message);
         MessageBox.Show("Service error");
     }
     catch (Exception ex)
     {
         GlobalMethods.ErrorMessages("Unisex", "Client error", ex.Message);
         MessageBox.Show("Client error");
     }
 }
Exemplo n.º 9
0
    public void Start()
    {
        DontDestroyOnLoad(gameObject);
        this.ChatPanel.gameObject.SetActive(true);

        Application.runInBackground = true; // this must run in background or it will drop connection if not focussed.

        if (string.IsNullOrEmpty(ChatAppId))
        {
            Debug.LogError("You need to set the chat app ID in the inspector in order to continue.");

            return;
        }

        if (string.IsNullOrEmpty(UserName))
        {
            UserName = "******" + Environment.TickCount%99; //made-up username
        }

        this.chatClient = new ChatClient(this);
        this.chatClient.Connect(ChatAppId, "1.0", new ExitGames.Client.Photon.Chat.AuthenticationValues(UserName));

        this.ChannelToggleToInstantiate.gameObject.SetActive(false);
        Debug.Log("Connecting as: " + UserName);
    }
Exemplo n.º 10
0
    public void Start()
    {
        DontDestroyOnLoad(this.gameObject);
        Application.runInBackground = true; // this must run in background or it will drop connection if not focussed.

        if (string.IsNullOrEmpty(this.UserName))
        {
            this.UserName = "******" + Environment.TickCount%99; //made-up username
        }

        chatClient = new ChatClient(this);
        chatClient.Connect(ChatAppId, "1.0", this.UserName, null);

        if (this.AlignBottom)
        {
            this.GuiRect.y = Screen.height - this.GuiRect.height;
        }
        if (this.FullScreen)
        {
            this.GuiRect.x = 0;
            this.GuiRect.y = 0;
            this.GuiRect.width = Screen.width;
            this.GuiRect.height = Screen.height;
        }

        Debug.Log(this.UserName);
    }
Exemplo n.º 11
0
 // 异步的Join操作,首先调用BeginJoin,该操作完成后将调用OnEndJoin。
 public void Connect(Person p)
 {
     InstanceContext site = new InstanceContext(this);
     proxy = new ChatClient(site);
     IAsyncResult iar =
     proxy.BeginJoin(p, new AsyncCallback(OnEndJoin), null);
 }
    /// <summary>
    /// Initializes connection with chat system, entering the room with the same name as the room the player is in.
    /// </summary>
    public void StartConnection()
    {
		chatActive = true;
        this.roomName = MultiplayerRoomsManager.instance.myRoomInfo.name;

        this.client = new ChatClient(this);
        this.client.Connect("90dae08d-093a-4c23-983d-4d950fcc90a2", "1.0", AccountManager.instance.displayName, null);
    }
Exemplo n.º 13
0
	public void LoginChat (string username) 
	{
		FindObjectOfType<PartyMatchmaker>().ClearParty();
		chatClient = new ChatClient( this , ExitGames.Client.Photon.ConnectionProtocol.Udp);
		ExitGames.Client.Photon.Chat.AuthenticationValues auth = new ExitGames.Client.Photon.Chat.AuthenticationValues();
		auth.UserId = username;
		chatClient.Connect( appID, "1.0", auth);
	}
Exemplo n.º 14
0
		public ChatRoomCreateWindow(ChatClient client)
		{
			DataContext = ChatRoom = new ChatRoom();

			InitializeComponent();

			ParentRoom.ItemsSource = new[] { new ChatRoom {Name = "", Id = 0} }.Concat(client.GrantedRooms).ToList();
		}
Exemplo n.º 15
0
 public ChatForm()
 {
     InitializeComponent();
     EnterServerIp();
     chatClient = new ChatClient(this, serverIp, serverPort);
     ChangeContentSize();
     DoLogin();
 }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            var messageBusSubscriber = new MessageBusSubscriber();
            messageBusSubscriber.Start();
            var chatClient = new ChatClient();
            chatClient.Start();

            messageBusSubscriber.Stop();
        }
Exemplo n.º 17
0
 // 调用客户端代理的Abort与Close方法
 public void AbortProxy()
 {
     if (proxy != null)
     {
         proxy.Abort();
         proxy.Close();
         proxy = null;
     }
 }
Exemplo n.º 18
0
        public ChatForm(ChatClient chatClient, string lroom)
        {
            this.InitializeComponent();

            this.chatClient = chatClient;
            this.room = lroom;
            this.Text = String.Format("User '{0}' at room '{1}' on server '{2}'", chatClient.Login, this.room, chatClient.Server);
            chatClient.MessageProcessor.addProcessor(this.room, this.OnReceiveMsg);//Ala event
            this.refreshDestination();
        }
Exemplo n.º 19
0
        //volatile string[] rms = null;
        public SelRoomForm(ChatClient chatClient)
        {
            this.InitializeComponent();

            this.chatClient = chatClient;
            this.refreshRooms();
            this.tbRoom.Text = "r1";
            this.tbPass.Text="r1pass";
            this.tbConfPass.Text = "r1pass";
        }
Exemplo n.º 20
0
 public Form1()
 {
     InitializeComponent();
     ws.MaxBufferPoolSize = int.MaxValue;
     ws.MaxReceivedMessageSize = int.MaxValue;
     ws.ReaderQuotas.MaxArrayLength = int.MaxValue;
     ws.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
     ws.ReaderQuotas.MaxStringContentLength = int.MaxValue;
     proxy = new ChatClient(new InstanceContext(this), ws, address);
 }
Exemplo n.º 21
0
 public static void SubmitUserMessage(string endpoint, string userName, string message, int userID, int roomID)
 {
     var _chatClient = new ChatClient(endpoint);
     var userMessage = new UserMessage();
     userMessage.Message = message;
     userMessage.UserID = userID;
     userMessage.RoomID = roomID;
     userMessage.Submitter = userName;
     userMessage.TimeStamp = DateTime.Now;
     _chatClient.SubmitUserMessage(userMessage);
 }
Exemplo n.º 22
0
 public static void ErrorMessages(string endpoint, string errorType, string messages, int roomID = 0, string userName = "")
 {
     var _chatClient = new ChatClient(endpoint);
     var error = new Error()
     {
         RoomID = roomID,
         UserName = userName,
         Time = DateTime.Now,
         ErrorType = errorType,
         Messages = messages
     };
     _chatClient.ErrorMessages(error);
 }
Exemplo n.º 23
0
 public FTSender(string IP, string PORT, string fileName, ChatClient.ClientForm me)
 {
     if (ChatClient.ClientForm.serverBusy == true)
     {
         MessageBox.Show("Another file transfer is in Progress!", "Server Busy", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     this.IP = IP;
     this.PORT = PORT;
     this.fileName = fileName;
     FTSender.me = me;
     size = new FileInfo(fileName).Length;
 }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            string severIp = "127.0.0.1";

            Console.WriteLine("===== Connecting =====");

            ChatClient c1 = new ChatClient("Vasya", severIp);
            c1.Connected += (msg) => Console.WriteLine("Connected - " + msg);
            c1.MessageRecieved += (msg) => Console.WriteLine("Recieved msg from server:" + msg);
            c1.ErrorRecieved += (msg) => Console.WriteLine("Error:" + msg);
            Thread.Sleep(500);

            ChatClient c2 = new ChatClient("Petya", severIp);
            c2.Connected += (msg) => Console.WriteLine("Connected - " + msg);
            c2.MessageRecieved += (msg) => Console.WriteLine("Recieved msg from server:" + msg);
            c2.ErrorRecieved += (msg) => Console.WriteLine("Error error from server:" + msg);
            Thread.Sleep(500);

            ChatClient c3 = new ChatClient("Misha", severIp);
            c3.Connected += (msg) => Console.WriteLine("Connected - " + msg);
            c3.MessageRecieved += (msg) => Console.WriteLine("Recieved msg from server:" + msg);
            c3.ErrorRecieved += (msg) => Console.WriteLine("Error error from server:" + msg);
            Thread.Sleep(500);

            Console.WriteLine("===== Connecting end =====");
            Console.WriteLine("===== Messaging =====");
            try
            {
                for (int i = 0; i < 10; i++)
                {
                    c1.SendMessage("c1_" + i.ToString() + " from " + c1.UserName);
                    c2.SendMessage("c2_" + i.ToString() + " from " + c2.UserName);
                    c3.SendMessage("c3_" + i.ToString() + " from " + c3.UserName);
                    Thread.Sleep(1000);
                }
                Console.WriteLine("===== Messaging end=====");
            }
            catch (Exception ex)
            {
                Utils.LogException(ex);
            }
            finally
            {
                c1.Disconnect();
                c2.Disconnect();
                c3.Disconnect();

                Console.WriteLine("Press any key...");
                Console.ReadLine();
            }
        }
Exemplo n.º 25
0
        public LogonForm(ChatClient chatClient)
        {
            this.InitializeComponent();

            ////System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;

            this.chatClient = chatClient;

            // TODO: remove after debug
            this.tbLogin.Text = @"user1";
            this.tbPass.Text = @"qwe`123";

            this.cbServer.Text = Properties.Settings.Default.DefServer;
            this.nudPort.Value = Convert.ToDecimal(Properties.Settings.Default.DefPort);
        }
    // Use this for initialization
    void Start()
    {


        ChatText = GameObject.Find("ChatText").GetComponent<Text>();
        ChatInput = GameObject.Find("ChatInput").GetComponent<InputField>();
        DisconnectButton = GameObject.Find("DisconnectButton").GetComponent<Button>();
        DontDestroyOnLoad(gameObject);
        Application.runInBackground = true;

        _chat = new ChatClient(this);





    }
Exemplo n.º 27
0
 public FTReciever(String IP, String PORT, string fileName, StreamWriter sw, 
     String sender,Int64 size, ChatClient.ClientForm me, OBJTYPE objType, Object parent)
 {
     if (ChatClient.ClientForm.serverBusy == true)
     {
         MessageBox.Show("Another file transfer is in Progress!", "Server Busy", MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     listener = new TcpListener(IPAddress.Parse(ChatClient.ClientForm.myIp), int.Parse(PORT));
     this.saveFile = fileName;
     this.swSender = sw;
     this.sender = sender;
     this.size = size;
     FTReciever.me = me;
     this.objType = objType;
     FTReciever.parent = parent;
 }
Exemplo n.º 28
0
        public void Connect(string host, string port, UserDTO user)
        {
            try
            {
                CurrentUser = user;
                _chatClient = new ChatClient(new InstanceContext(this));

                var servicePath = _chatClient.Endpoint.ListenUri.AbsolutePath;
                _chatClient.Endpoint.Address = new EndpointAddress("net.tcp://" + host + ":" + port + servicePath);

                _chatClient.Open();

                RegisterServiceEvents();

                _chatClient.ConnectAsync(CurrentUser);
            }
            catch (Exception ex)
            {
                Exception(this, new ExceptionEventArgs { Message = ex.Message });
            }
        }
Exemplo n.º 29
0
        // Fire and forget
        private static async void Match(ChatClient connection)
        {
            try
            {
                await connection.WriteLineAsync("Waiting for a partner...");

                ChatClient partner;
                if (_queue.TryDequeue(out partner) && partner.Socket.Connected)
                {
                    await ChatAsync(partner, connection);
                }
                else
                {
                    _queue.Enqueue(connection);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Exemplo n.º 30
0
    public static void Main()
    {
        var client = new ChatClient();
        var peer = new PhotonPeer(client, ConnectionProtocol.Tcp);

        // connect
        client.connected = false;
        peer.Connect("127.0.0.1:4530", "ChatServer");
        while (!client.connected)
        {
            peer.Service();
        }

        var buffer = new StringBuilder();
        while (true)
        {
            peer.Service();

            // read input
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key != ConsoleKey.Enter)
                {
                    // store input
                    buffer.Append(key.KeyChar);
                }
                else
                {
                    // send to server
                    var parameters = new Dictionary<byte, object> { { 1, buffer.ToString() } };
                    peer.OpCustom(1, parameters, true);
                    buffer.Length = 0;
                }
            }
        }
    }
        public async Task SendGetUpdateDeleteMessagesSendNotificationReadReceiptsAsync()
        {
            CommunicationIdentityClient            communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString);
            Response <CommunicationUserIdentifier> threadMember = await communicationIdentityClient.CreateUserAsync();

            CommunicationUserToken communicationUserToken = await communicationIdentityClient.IssueTokenAsync(threadMember.Value, new[] { CommunicationTokenScope.Chat });

            string userToken            = communicationUserToken.Token;
            string endpoint             = TestEnvironment.ChatApiUrl();
            string theadCreatorMemberId = threadMember.Value.Id;

            ChatClient chatClient = new ChatClient(
                new Uri(endpoint),
                new CommunicationTokenCredential(userToken));

            var chatThreadMember = new ChatThreadMember(new CommunicationUserIdentifier(theadCreatorMemberId))
            {
                DisplayName      = "UserDisplayName",
                ShareHistoryTime = DateTime.MinValue
            };
            ChatThreadClient chatThreadClient = await chatClient.CreateChatThreadAsync(topic : "Hello world!", members : new[] { chatThreadMember });

            string threadId = chatThreadClient.Id;

            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendMessage
            var content           = "hello world";
            var priority          = ChatMessagePriority.Normal;
            var senderDisplayName = "sender name";
            SendChatMessageResult sendMessageResult = await chatThreadClient.SendMessageAsync(content, priority, senderDisplayName);

            #endregion Snippet:Azure_Communication_Chat_Tests_SendMessage

            var messageId = sendMessageResult.Id;
            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetMessage
            ChatMessage chatMessage = await chatThreadClient.GetMessageAsync(messageId);

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetMessage

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetMessages
            AsyncPageable <ChatMessage> allMessages = chatThreadClient.GetMessagesAsync();
            await foreach (ChatMessage message in allMessages)
            {
                Console.WriteLine($"{message.Id}:{message.Sender.Id}:{message.Content}");
            }
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetMessages

            #region Snippet:Azure_Communication_Chat_Tests_Samples_UpdateMessage
            await chatThreadClient.UpdateMessageAsync(messageId, "updated message content");

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_UpdateMessage

            //Note : Due to the async nature of the storage, moving coverage to CI tests
            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendReadReceipt
            //@@await chatThreadClient.SendReadReceiptAsync(messageId);
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_SendReadReceipt

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetReadReceipts
            AsyncPageable <ReadReceipt> allReadReceipts = chatThreadClient.GetReadReceiptsAsync();
            await foreach (ReadReceipt readReceipt in allReadReceipts)
            {
                Console.WriteLine($"{readReceipt.ChatMessageId}:{readReceipt.Sender.Id}:{readReceipt.ReadOn}");
            }
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetReadReceipts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_DeleteMessage
            await chatThreadClient.DeleteMessageAsync(messageId);

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_DeleteMessage

            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendTypingNotification
            await chatThreadClient.SendTypingNotificationAsync();

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_SendTypingNotification

            await chatClient.DeleteChatThreadAsync(threadId);
        }
Exemplo n.º 32
0
        public void Remove(ChatClient client)
        {
            var user = _users.FirstOrDefault(u => client.User == u);

            user.ConnectedClients.Remove(client);
        }
Exemplo n.º 33
0
 private void Start()
 {
     client = new ChatClient(this);
     client.Connect(PhotonNetwork.PhotonServerSettings.ChatAppID, "anything", new ExitGames.Client.Photon.Chat.AuthenticationValues(PhotonNetwork.playerName));
     Debug.Log("开始链接");
 }
Exemplo n.º 34
0
        private void HandleChatClient(ChatClient chatClient)
        {
            var neighbor = _station.GetNeighbor(chatClient.RemoteAddress);

            ChatWindowManager.Show(neighbor, chatClient);
        }
Exemplo n.º 35
0
 public void Add(ChatClient client)
 {
     _db.ChatClients.Add(client);
     _db.SaveChanges();
 }
 protected ChatThreadClient GetInstrumentedChatThreadClient(ChatClient chatClient, string threadId)
 {
     return(InstrumentClient(chatClient.GetChatThreadClient(threadId)));
 }
Exemplo n.º 37
0
 private static void MessageText_OnPressEnter()
 {
     ChatClient.SendMessage(MessageText.Text.ToString());
     MessageText.Text = string.Empty;
 }
Exemplo n.º 38
0
        public async Task SendGetUpdateDeleteMessagesSendNotificationReadReceiptsAsync()
        {
            CommunicationIdentityClient            communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.LiveTestDynamicConnectionString);
            Response <CommunicationUserIdentifier> threadMember = await communicationIdentityClient.CreateUserAsync();

            AccessToken communicationUserToken = await communicationIdentityClient.GetTokenAsync(threadMember.Value, new[] { CommunicationTokenScope.Chat });

            string userToken            = communicationUserToken.Token;
            string theadCreatorMemberId = threadMember.Value.Id;

            ChatClient chatClient = new ChatClient(
                TestEnvironment.LiveTestDynamicEndpoint,
                new CommunicationTokenCredential(userToken));

            var chatParticipant = new ChatParticipant(new CommunicationUserIdentifier(theadCreatorMemberId))
            {
                DisplayName      = "UserDisplayName",
                ShareHistoryTime = DateTimeOffset.MinValue
            };
            CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new[] { chatParticipant });

            ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(createChatThreadResult.ChatThread.Id);

            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendMessage
            SendChatMessageResult sendChatMessageResult = await chatThreadClient.SendMessageAsync(content : "hello world");

            var messageId = sendChatMessageResult.Id;
            #endregion Snippet:Azure_Communication_Chat_Tests_SendMessage

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetMessage
            ChatMessage chatMessage = await chatThreadClient.GetMessageAsync(messageId);

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetMessage

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetMessages
            AsyncPageable <ChatMessage> allMessages = chatThreadClient.GetMessagesAsync();
            await foreach (ChatMessage message in allMessages)
            {
                Console.WriteLine($"{message.Id}:{message.Content.Message}");
            }
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetMessages

            #region Snippet:Azure_Communication_Chat_Tests_Samples_UpdateMessage
            await chatThreadClient.UpdateMessageAsync(messageId, "updated message content");

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_UpdateMessage

            //Note : Due to the async nature of the storage, moving coverage to CI tests
            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendReadReceipt
            //@@await chatThreadClient.SendReadReceiptAsync(messageId);
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_SendReadReceipt

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetReadReceipts
            AsyncPageable <ChatMessageReadReceipt> allReadReceipts = chatThreadClient.GetReadReceiptsAsync();
            await foreach (ChatMessageReadReceipt readReceipt in allReadReceipts)
            {
                Console.WriteLine($"{readReceipt.ChatMessageId}:{((CommunicationUserIdentifier)readReceipt.Sender).Id}:{readReceipt.ReadOn}");
            }
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_GetReadReceipts

            #region Snippet:Azure_Communication_Chat_Tests_Samples_DeleteMessage
            await chatThreadClient.DeleteMessageAsync(messageId);

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_DeleteMessage

            #region Snippet:Azure_Communication_Chat_Tests_Samples_SendTypingNotification
            await chatThreadClient.SendTypingNotificationAsync();

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_SendTypingNotification

            await chatClient.DeleteChatThreadAsync(chatThreadClient.Id);
        }
        public async Task CreateGetUpdateDeleteThreadAsync()
        {
            CommunicationIdentityClient            communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString);
            Response <CommunicationUserIdentifier> threadCreatorIdentifier     = await communicationIdentityClient.CreateUserAsync();

            CommunicationUserIdentifier kimberly = await communicationIdentityClient.CreateUserAsync();

            AccessToken communicationUserToken = await communicationIdentityClient.IssueTokenAsync(threadCreatorIdentifier.Value, new[] { CommunicationTokenScope.Chat });

            string userToken = communicationUserToken.Token;
            string endpoint  = TestEnvironment.ChatApiUrl();

            #region Snippet:Azure_Communication_Chat_Tests_Samples_CreateChatClient
            ChatClient chatClient = new ChatClient(
                new Uri(endpoint),
                new CommunicationTokenCredential(userToken));
            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_CreateChatClient

            #region Snippet:Azure_Communication_Chat_Tests_Samples_CreateThread
            var chatParticipant = new ChatParticipant(communicationIdentifier: kimberly)
            {
                DisplayName = "Kim"
            };
            CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new[] { chatParticipant });

            string           threadId         = createChatThreadResult.ChatThread.Id;
            ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(threadId);
            #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
            await chatThreadClient.UpdateTopicAsync(topic : "new 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 CommunicationUserIdentifier("invalid user"));
            #region Snippet:Azure_Communication_Chat_Tests_Samples_Troubleshooting
            try
            {
                CreateChatThreadResult createChatThreadErrorResult = 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}");
            }
        }
Exemplo n.º 40
0
        public static void Main(string[] args)
        {
            Task.Run(async() =>
            {
                try
                {
                    Logger.SetLogLevel(LogLevel.Debug);
                    Logger.LogOccurred += Logger_LogOccurred;

                    using (StreamWriter writer = new StreamWriter(File.Open("Packets.txt", FileMode.Create)))
                    {
                        await writer.FlushAsync();
                    }

                    System.Console.WriteLine("Connecting to Twitch...");

                    connection = TwitchConnection.ConnectViaLocalhostOAuthBrowser(clientID, clientSecret, scopes).Result;
                    if (connection != null)
                    {
                        System.Console.WriteLine("Twitch connection successful!");

                        user = await connection.NewAPI.Users.GetCurrentUser();
                        if (user != null)
                        {
                            System.Console.WriteLine("Logged in as: " + user.display_name);

                            System.Console.WriteLine("Connecting to Chat...");

                            chat = new ChatClient(connection);

                            chat.OnDisconnectOccurred += Chat_OnDisconnectOccurred;
                            chat.OnSentOccurred       += Chat_OnSentOccurred;
                            chat.OnPacketReceived     += Chat_OnPacketReceived;

                            chat.OnPingReceived      += Chat_OnPingReceived;
                            chat.OnUserListReceived  += Chat_OnUserListReceived;
                            chat.OnUserJoinReceived  += Chat_OnUserJoinReceived;
                            chat.OnUserLeaveReceived += Chat_OnUserLeaveReceived;
                            chat.OnMessageReceived   += Chat_OnMessageReceived;

                            await chat.Connect();

                            await Task.Delay(1000);

                            await chat.AddCommandsCapability();
                            await chat.AddTagsCapability();
                            await chat.AddMembershipCapability();

                            await Task.Delay(1000);

                            UserModel broadcaster = await connection.NewAPI.Users.GetCurrentUser();

                            await chat.Join(broadcaster);

                            await Task.Delay(2000);

                            System.Console.WriteLine(string.Format("There are {0} users currently in chat", initialUserList.Count()));

                            await chat.SendMessage(broadcaster, "Hello World!");

                            while (true)
                            {
                                System.Console.ReadLine();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.ToString());
                }
            }).Wait();

            System.Console.ReadLine();
        }
Exemplo n.º 41
0
 public Frame(ChatClient client, Account user)
 {
     InitializeComponent();
     Client = client;
     User   = user;
 }
Exemplo n.º 42
0
        public async Task GetAddRemoveMembersAsync()
        {
            CommunicationIdentityClient            communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString);
            Response <CommunicationUserIdentifier> joshResponse = await communicationIdentityClient.CreateUserAsync();

            CommunicationUserIdentifier            josh           = joshResponse.Value;
            Response <CommunicationUserIdentifier> gloriaResponse = await communicationIdentityClient.CreateUserAsync();

            CommunicationUserIdentifier            gloria      = gloriaResponse.Value;
            Response <CommunicationUserIdentifier> amyResponse = await communicationIdentityClient.CreateUserAsync();

            CommunicationUserIdentifier amy = amyResponse.Value;

            AccessToken joshTokenResponse = await communicationIdentityClient.GetTokenAsync(josh, new[] { CommunicationTokenScope.Chat });

            ChatClient chatClient = new ChatClient(
                TestEnvironment.Endpoint,
                new CommunicationTokenCredential(joshTokenResponse.Token));

            var chatParticipant = new ChatParticipant(josh)
            {
                DisplayName      = "Josh",
                ShareHistoryTime = DateTime.MinValue
            };
            CreateChatThreadResult createChatThreadResult = await chatClient.CreateChatThreadAsync(topic : "Hello world!", participants : new[] { chatParticipant });

            ChatThreadClient chatThreadClient = chatClient.GetChatThreadClient(createChatThreadResult.ChatThread.Id);

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetParticipants
            AsyncPageable <ChatParticipant> allParticipants = chatThreadClient.GetParticipantsAsync();
            await foreach (ChatParticipant participant in allParticipants)
            {
                Console.WriteLine($"{((CommunicationUserIdentifier)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(chatThreadClient.Id);
        }
Exemplo n.º 43
0
 public CreateRoomHandler(ChatClient client)
     : base()
 {
     m_Client = client;
 }
Exemplo n.º 44
0
 public Plain(ChatClient client) : base(client, client.AuthCred)
 {
 }
Exemplo n.º 45
0
        public void ThreadCGUD_ParticipantAUR_MessageGSU_NotificationT()
        {
            //arr
            Console.WriteLine($"ThreadCGUD_ParticipantAUR_MessageGSU_NotificationT Running on RecordedTestMode : {Mode}");
            CommunicationIdentityClient communicationIdentityClient = CreateInstrumentedCommunicationIdentityClient();

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

            var topic = "Thread sync from C# sdk";
            var displayNameMessage = "DisplayName sender message 1";
            var participants       = new[]
            {
                new ChatParticipant(user1),
                new ChatParticipant(user2),
                new ChatParticipant(user3)
            };
            ChatClient chatClient  = CreateInstrumentedChatClient(token1);
            ChatClient chatClient2 = CreateInstrumentedChatClient(token2);
            ChatClient chatClient3 = CreateInstrumentedChatClient(token3);

            //act
            #region Snippet:Azure_Communication_Chat_Tests_E2E_InitializeChatThreadClient
            //@@ChatThreadClient chatThreadClient1 = chatClient.CreateChatThread("Thread topic", participants);
            // 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, participants);
            var threadId = chatThreadClient.Id;
            ChatThreadClient chatThreadClient2 = CreateInstrumentedChatThreadClient(chatClient, topic, participants);
            ChatThreadClient chatThreadClient3 = GetInstrumentedChatThreadClient(chatClient3, threadId);

            string updatedTopic = "Launch meeting";
            #region Snippet:Azure_Communication_Chat_Tests_E2E_UpdateThread
            chatThreadClient.UpdateTopic(topic: "Launch meeting");
            #endregion Snippet:Azure_Communication_Chat_Tests_E2E_UpdateThread

            #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();

            string messageContent = "Let's meet at 11am";
            #region Snippet:Azure_Communication_Chat_Tests_E2E_SendMessage
            string messageId = chatThreadClient.SendMessage("Let's meet at 11am");
            #endregion Snippet:Azure_Communication_Chat_Tests_E2E_SendMessage
            string messageContent2 = "Content for message 2";
            string messageId2      = chatThreadClient2.SendMessage(messageContent2, ChatMessagePriority.High, displayNameMessage);
            string messageContent3 = "Content for message 3";
            string messageId3      = chatThreadClient3.SendMessage(messageContent3, ChatMessagePriority.High, displayNameMessage);
            string messageContent4 = "Content for message 4";
            string messageId4      = chatThreadClient3.SendMessage(messageContent4, ChatMessagePriority.High, displayNameMessage);
            string messageContent5 = "Content for message 5";
            string messageId5      = chatThreadClient3.SendMessage(messageContent5, ChatMessagePriority.High, displayNameMessage);
            string messageContent6 = "Content for message 6";
            string messageId6      = chatThreadClient3.SendMessage(messageContent6, ChatMessagePriority.High, displayNameMessage);

            #region Snippet:Azure_Communication_Chat_Tests_E2E_GetMessage
            ChatMessage message = chatThreadClient.GetMessage(messageId);
            #endregion Snippet:Azure_Communication_Chat_Tests_E2E_GetMessage
            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);

            #region Snippet:Azure_Communication_Chat_Tests_E2E_GetMessages
            Pageable <ChatMessage> messages = chatThreadClient.GetMessages();
            #endregion Snippet:Azure_Communication_Chat_Tests_E2E_GetMessages
            Pageable <ChatMessage> messages2 = chatThreadClient2.GetMessages();
            var getMessagesCount             = messages.Count();
            var getMessagesCount2            = messages2.Count();

            # region Pagination assertions
Exemplo n.º 46
0
 private void ValidateMessage(ChatClient chatClient, ChatMessageEventModel message, string messageText)
 {
     Assert.IsNotNull(message);
     Assert.AreEqual(message.user_name.ToString(), chatClient.User.username, true);
     Assert.IsTrue(message.message.message.First().text.Equals(messageText));
 }
 public UpdateAccountHandler(ChatClient client)
 {
     this.client = client;
 }
Exemplo n.º 48
0
 private void Start()
 {
     chatClient = GetComponent <ChatClient>();
     Invoke("JoinRequest", 1f);
 }
Exemplo n.º 49
0
        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            this.LoginButton.IsEnabled = false;

            string clientID = ConfigurationManager.AppSettings["ClientID"];

            if (string.IsNullOrEmpty(clientID))
            {
                throw new ArgumentException("ClientID value isn't set in application configuration");
            }

            this.connection = await MixerConnection.ConnectViaShortCode(clientID,
                                                                        new List <OAuthClientScopeEnum>()
            {
                OAuthClientScopeEnum.chat__chat,
                OAuthClientScopeEnum.chat__connect,
                OAuthClientScopeEnum.channel__details__self,
                OAuthClientScopeEnum.channel__update__self,
                OAuthClientScopeEnum.user__details__self,
                OAuthClientScopeEnum.user__log__self,
                OAuthClientScopeEnum.user__notification__self,
                OAuthClientScopeEnum.user__update__self,
            },
                                                                        (OAuthShortCodeModel code) =>
            {
                this.ShortCodeTextBox.Text = code.code;
                Process.Start("https://mixer.com/oauth/shortcode");
            });

            if (this.connection != null)
            {
                this.user = await this.connection.Users.GetCurrentUser();

                this.channel = await this.connection.Channels.GetChannel(this.user.username);

                this.chatClient = await ChatClient.CreateFromChannel(this.connection, channel);

                this.chatClient.OnDisconnectOccurred    += ChatClient_OnDisconnectOccurred;
                this.chatClient.OnMessageOccurred       += ChatClient_MessageOccurred;
                this.chatClient.OnUserJoinOccurred      += ChatClient_UserJoinOccurred;
                this.chatClient.OnUserLeaveOccurred     += ChatClient_UserLeaveOccurred;
                this.chatClient.OnUserTimeoutOccurred   += ChatClient_UserTimeoutOccurred;
                this.chatClient.OnUserUpdateOccurred    += ChatClient_UserUpdateOccurred;
                this.chatClient.OnPollStartOccurred     += ChatClient_PollStartOccurred;
                this.chatClient.OnPollEndOccurred       += ChatClient_PollEndOccurred;
                this.chatClient.OnPurgeMessageOccurred  += ChatClient_PurgeMessageOccurred;
                this.chatClient.OnDeleteMessageOccurred += ChatClient_DeleteMessageOccurred;
                this.chatClient.OnClearMessagesOccurred += ChatClient_ClearMessagesOccurred;

                IEnumerable <ChatUserModel> users = await this.connection.Chats.GetUsers(this.channel);

                this.viewerCount = users.Count();
                this.CurrentViewersTextBlock.Text = this.viewerCount.ToString();

                if (await this.chatClient.Connect() && await this.chatClient.Authenticate())
                {
                    this.LoginGrid.Visibility = Visibility.Collapsed;
                    this.ChatGrid.Visibility  = Visibility.Visible;
                }
            }

            this.LoginButton.IsEnabled = true;
        }
Exemplo n.º 50
0
        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);
            Assert.AreEqual(1, readReceiptsCount);
        }
Exemplo n.º 51
0
 public MainPageViewModel()
 {
     _client = Bootstrapper.Container.GetInstance <ChatClient>();
     CurrentUser.Chats.ForEach(x => { ChatsViewModels.Add(x); });
 }
Exemplo n.º 52
0
        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);
            Assert.AreEqual(1, readReceiptsCount);
        }
Exemplo n.º 53
0
 public EnterRoomHandler(ChatClient client)
     : base()
 {
     m_Client = client;
 }
        public async Task GetAddRemoveMembersAsync()
        {
            CommunicationIdentityClient            communicationIdentityClient = new CommunicationIdentityClient(TestEnvironment.ConnectionString);
            Response <CommunicationUserIdentifier> threadMember1 = await communicationIdentityClient.CreateUserAsync();

            Response <CommunicationUserIdentifier> threadMember2 = await communicationIdentityClient.CreateUserAsync();

            Response <CommunicationUserIdentifier> threadMember3 = await communicationIdentityClient.CreateUserAsync();

            CommunicationUserToken communicationUserToken1 = await communicationIdentityClient.IssueTokenAsync(threadMember1.Value, new[] { CommunicationTokenScope.Chat });

            CommunicationUserToken communicationUserToken2 = await communicationIdentityClient.IssueTokenAsync(threadMember2.Value, new[] { CommunicationTokenScope.Chat });

            CommunicationUserToken communicationUserToken3 = await communicationIdentityClient.IssueTokenAsync(threadMember3.Value, new[] { CommunicationTokenScope.Chat });

            string userToken            = communicationUserToken1.Token;
            string endpoint             = TestEnvironment.ChatApiUrl();
            string theadCreatorMemberId = communicationUserToken1.User.Id;

            ChatClient chatClient = new ChatClient(
                new Uri(endpoint),
                new CommunicationTokenCredential(userToken));

            var chatThreadMember = new ChatThreadMember(new CommunicationUserIdentifier(theadCreatorMemberId))
            {
                DisplayName      = "UserDisplayName",
                ShareHistoryTime = DateTime.MinValue
            };
            ChatThreadClient chatThreadClient = await chatClient.CreateChatThreadAsync(topic : "Hello world!", members : new[] { chatThreadMember });

            string threadId = chatThreadClient.Id;

            #region Snippet:Azure_Communication_Chat_Tests_Samples_GetMembers
            AsyncPageable <ChatThreadMember> allMembers = chatThreadClient.GetMembersAsync();
            await foreach (ChatThreadMember member in allMembers)
            {
                Console.WriteLine($"{member.User.Id}:{member.DisplayName}:{member.ShareHistoryTime}");
            }
            #endregion Snippet:Azure_Communication_Chat_Tests_GetMembers

            var memberId1 = theadCreatorMemberId;
            var memberId2 = communicationUserToken2.User.Id;
            var memberId3 = communicationUserToken3.User.Id;

            #region Snippet:Azure_Communication_Chat_Tests_Samples_AddMembers
            var members = new[]
            {
                new ChatThreadMember(new CommunicationUserIdentifier(memberId1))
                {
                    DisplayName = "display name member 1"
                },
                new ChatThreadMember(new CommunicationUserIdentifier(memberId2))
                {
                    DisplayName = "display name member 2"
                },
                new ChatThreadMember(new CommunicationUserIdentifier(memberId3))
                {
                    DisplayName = "display name member 3"
                }
            };
            await chatThreadClient.AddMembersAsync(members);

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_AddMembers

            var memberId = memberId2;
            #region Snippet:Azure_Communication_Chat_Tests_Samples_RemoveMember
            await chatThreadClient.RemoveMemberAsync(new CommunicationUserIdentifier(memberId));

            #endregion Snippet:Azure_Communication_Chat_Tests_Samples_RemoveMember

            await chatClient.DeleteChatThreadAsync(threadId);
        }
Exemplo n.º 55
0
 public void Remove(ChatClient client)
 {
     _db.ChatClients.Remove(client);
     _db.SaveChanges();
 }
Exemplo n.º 56
0
 internal MessageManager(ChatClient client)
 {
     ChatClient = client;
 }
Exemplo n.º 57
0
 public RoomMessageHandler(ChatClient client)
     : base()
 {
     m_Client = client;
 }
Exemplo n.º 58
0
 public GetRoomListHandler(ChatClient client)
     : base()
 {
     m_Client = client;
 }
        public int handle(ChatClient client)
        {
            if (!Console.IsOutputRedirected)
            {
                Console.Clear();
            }
            List <byte> contentList = new List <byte>();

            Console.Write("Enter proposed conversation name: ");
            string conversationName = Console.ReadLine();

            while (conversationName == "")
            {
                Console.WriteLine("Conversation name cannot be empty!");
                Console.Write("Enter proposed conversation name: ");
                conversationName = Console.ReadLine();
            }
            foreach (byte b in BitConverter.GetBytes(Encoding.UTF8.GetByteCount(conversationName)))
            {
                contentList.Add(b);
            }
            foreach (byte b in Encoding.UTF8.GetBytes(conversationName))
            {
                contentList.Add(b);
            }
            string userName = client.chatSystem.LoggedInName;

            foreach (byte b in BitConverter.GetBytes(Encoding.UTF8.GetByteCount(userName)))
            {
                contentList.Add(b);
            }
            foreach (byte b in Encoding.UTF8.GetBytes(userName))
            {
                contentList.Add(b);
            }
            Console.WriteLine("Who other than you is to be part of the conversation?");
            while (userName != "")
            {
                Console.WriteLine("Enter name of next user you wish to add to conversation (or empty line to stop): ");
                userName = Console.ReadLine();
                if (userName == "")
                {
                    break;
                }
                foreach (byte b in BitConverter.GetBytes(Encoding.UTF8.GetByteCount(userName)))
                {
                    contentList.Add(b);
                }
                foreach (byte b in Encoding.UTF8.GetBytes(userName))
                {
                    contentList.Add(b);
                }
            }
            byte[] message = contentList.ToArray();
            client.socketFacade.sendMessage(3, message);
            bool response = false;

            lock (client)
            {
                while (!client.responseReady)
                {
                    Monitor.Wait(client);
                }
                response             = client.responseStatus;
                client.responseReady = false;
                Monitor.Pulse(client);
            }
            if (response)
            {
                Console.WriteLine("Successfully added conversation: {0}", conversationName);
                Console.WriteLine("Press ENTER to continue...");
                Console.ReadLine();
                return(20);
            }
            else
            {
                Console.WriteLine("At least one of entered users does not exist!");
                Console.WriteLine("Press ENTER to continue...");
                Console.ReadLine();
                return(2001);
            }
        }
Exemplo n.º 60
0
 public EnterLobbyHandler(ChatClient client)
     : base()
 {
     m_Client = client;
 }