How to: Display new persistent chat room message as they are posted

[This is preliminary documentation and is subject to change.]

This topic shows you the code that you add to a simple persistent chat room window so that a user can read messages posted to a chat room. The topic continues the scenario introduced with the How to: Create a persistent chat room client topic. The code in following samples updates the chat room window messages list with the contents of new messages posted to the chat room.

Before you start the procedures in this topic, your application must declare and initialize a Microsoft.Lync.Model.LyncClient instance, and the client must be signed in. For more information, see How to: Sign In to Lync.

You must also have an instance of Microsoft.Lync.Model.Room.Room where the user has permission to read messages. For information about getting a room, see How to: Get persistent chat rooms. Your application must declare a list. The list displays messages posted to the room.

Code example

The following example references the namespaces that are used in the following Windows Forms examples.

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Room;
using System.Collections;

The following example declares the class fields that are referenced later in this topic.

        /// <summary>
        /// The LyncClient class instance that encapsulates the Lync client platform
        /// </summary>
        private LyncClient _client=null;

        /// <summary>
        /// The Room instance that a user joins from the list of rooms that are queried, searched for, or gotten from the followed rooms list
        /// </summary>
        private Room _room = null;

        /// <summary>
        /// The Uri of the local user who can post a message to a chat room
        /// </summary>
        private string _senderUri = "";

        


When you have obtained a Microsoft.Lync.Model.Room.Room instance selected by a user, register for a set of room events so that you can receive notification of messages posted to the room by other users or a message that is posted to the room by the local user.

To register for Room events

  1. Un-register for events on the previously selected room that is referenced by the _room class field.

  2. Set the _room class field to the newly selected room.

  3. Register for chat room events.

  4. Read room properties and update the UI with the room title, description, and unread message count.

The following example registers for room events and reads room properties.

        /// <summary>
        /// Registers for message, state, and participant related events on a room.
        /// </summary>
        private void FillRoomProperties(Room room)
        {
            if (_room != null)
            {
                //Un-Register for event raised when a new message is posted to the room or the user has read a message.
                _room.UnreadMessageCountChanged -= room_UnreadMessageCountChanged;

                //Un-Register for the event raised when users have posted messages to the room.
                _room.MessagesReceived -= room_MessagesReceived;

            }


            _room = room;

            //Clear the messages from a previous room choice out of the message list box
            listBoxMessages.Items.Clear();

            //Register for event raised when a new message is posted to the room or the user has read a message.
            _room.UnreadMessageCountChanged += new EventHandler<UnreadMessageCountChangedEventArgs>(room_UnreadMessageCountChanged);

            //Register for the event raised when users have posted messages to the room.
            _room.MessagesReceived += new EventHandler<RoomMessagesEventArgs>(room_MessagesReceived);


            if (_room.Properties != null)
            {
                if (_room.Properties[RoomProperty.Description] != null)
                {
                    RoomDescription_label.Text = _room.Properties[RoomProperty.Description].ToString();
                }
            }
            txtUnreadMessageCountChanged.Text = _room.UnreadRoomMessageCount.ToString();
        }


The Room.MessagesReceived event is raised when any room participant succeeds in posting to a room. The event data, Microsoft.Lync.Model.Room.RoomMessagesEventArgs, contains the message that is posted. Normally the event data message collection contains one message but this may not always be the case. For this reason, you should iterate on the full collection and process each message.

To handle the MessagesReceived event

  1. Read the RoomMessagesEventArgs.Messages property to get the collection of messages sent to a room.

  2. For each Microsoft.Lync.Model.Room.RoomMessage object in the messages collection, read the RoomMessage.SenderUri property to get the sender’s Uri.

    1. Get a Microsoft.Lync.Model.Contact instance that represents the user that is sending the message by calling the ContactManager.GetContactByUri method and passing the sender Uri in the first argument.

    2. Get the display name of the user that is sending the message by calling the Contact.GetContactInformation method, specifying the ContactInformationType.DisplayName property.

    3. Read the RoomMessage.MessageDictionary property to get the dictionary that contains the message in each format.

    4. Get the plain text of the message by calling the RoomMessageDictionary.TryGetValue method. The message text is returned in an out parameter string. Pass the RoomMessageFormat.PlainText enumerator into the method.

    5. Get the message sent time and date by reading the RoomMessage.SentTime property. A DateTime object is returned.

Code example

The following two examples demonstrate the tasks listed in the previous procedure. The first example is an event callback method that is invoked by the platform when a collection of new messages are posted to a room. The second example is a helper method that is invoked on the UI thread and updates the room message list control.

/// <summary>
        /// This event is raised when any room member has posted a message to the room. This includes
        /// the local user.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void room_MessagesReceived(object sender, RoomMessagesEventArgs e)
        {
           
            //Get the collection of newly posted messages.
           IList<RoomMessage> receivedMessages = e.Messages;

            //Invoke a delegate on the UI thread that updates the message list with the contents of the new message.
           listBoxMessages.Invoke(new LoadPostedMessagesDelegate(LoadPostedMessages), new object[] { receivedMessages });

        }

The following example updates the message list for the chat room window. It gets the message send date and time, the message type, the message sender display name, and the plain text of the message.

        /// <summary>
        /// Loads a list box with a collection of messages
        /// </summary>
        /// <param name="messages"></param>
        private void LoadPostedMessages(IList<RoomMessage> messages)
        {
                //Add a header row to the list box
                listBoxMessages.Items.Add("Messages retrieved: " + messages.Count.ToString());
                listBoxMessages.Items.Add("Sent Time\t\tType\tSender");

                //Declare Contact object to be initialized with the object returned from GetContactByUri
                Contact senderContact;

                foreach (RoomMessage message in messages)
                {
                    object messageObject = null;

                    //Get the sender as a Contact instance
                    senderContact = _client.ContactManager.GetContactByUri(message.SenderUri);

                    //Get the display name of the message sender
                    string senderName = senderContact.GetContactInformation(ContactInformationType.DisplayName).ToString();

                    //Get the plain text version of a message
                    message.MessageDictionary.TryGetValue(RoomMessageFormat.PlainText, out messageObject);
                    string messageContent = (string)messageObject;

                    //create an item in the list box composed of message sent time - TAB character - message type - sender display name
                    listBoxMessages.Items.Add(message.SentTime.ToString() + "\t" + message.MessageDictionary.Type + "\t" + senderName);

                    //Create an item in the list box composed of the TAB character and message string
                    listBoxMessages.Items.Add("\t" + messageContent);

                    //Create item composed of TAB TAB and line separator
                    listBoxMessages.Items.Add("\t\t------------------");

                    messageObject = null;

                   
                }
        }


Community Additions

Show:
© 2014 Microsoft