Export (0) Print
Expand All

How to: Request messages that have been posted to a persistent chat room

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

The typical behavior of a persistent chat room client is to display the most recently posted messages in a chat room initially upon opening the chat room window. A user will ask for progressively older messages so that they can read back through any chat room threads. Two Microsoft Lync 2013 Preview API methods can be used to implement this behavior in your application.

Immediately after your persistent chat room window is opened, you get the newest chat room messages by using the value of the Room.UnreadRoomMessageCount property in a request for the newest messages. You can ask for up to 50 messages to be returned. Use the oldest message Id from the response to the initial message request and then ask for a set of older messages. These two requests are represented by the methods described in this topic. Once you have obtained the message history that you want, you maintain the message list by adding any new message posted. For information about getting new messages, see How to: Display new persistent chat room message as they are posted.

Before you complete the steps in this topic, your application must declare and initialize an instance of Microsoft.Lync.Model.LyncClient and the Lync 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 chat room, see How to: Get persistent chat rooms. Your application must declare a button and a list box. The button click event code starts the request for messages and the list box shows the text of the messages that are returned.

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 in the following sections of 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;
     


The following procedure requests the most recently posted messages in a room. Up to 50 messages can be returned by one request.

To request the newest unread messages

  1. Read the Room.UnreadRoomMessageCount property. If the returned number is greater than the number of messages that you can display at one time in your UI, then you should request only the number of messages that you can display. The balance of the unread messages can be requested in the procedure in the next section.

  2. Call the Room.BeginRetrieveLatestMessages method, specifying the number of messages to return in the first argument.

  3. Call the Room.EndRetrieveLatestMessages method to get the collection of messages returned by the request operation.

  4. Get the message Id of the earliest message in the collection by reading the RoomMessage.Id property on the message at index value 0 in the collection. This value is used in the request for additional unread messages described in the next section.

  5. Iterate on the collection of messages returned from the call to the Room.EndRetrieveLatestMessages method. For each message, complete the steps in the Display a Posted Message procedure to get the message values that you display in your message list.

After you have filled a message list with the messages you get from the previous procedure, you may want to get subsequent sets of older messages. The following procedure requests successively older sets of messages.

To request posted messages

  1. Get the Id of the oldest message you obtained in the previous procedure (step 4).

  2. Call the Room.BeginRetrieveAdditionalMessages method, passing the message Id of the oldest message from the previous step.

  3. Call the Room.EndRetrieveAdditionalMessages method to get the collection of messages.

  4. Get the message Id of the earliest message in the collection by reading the RoomMessage.Id property of the message at index 0 in the collection. This value is used in the next request for unread messages.

  5. Iterate on the collection of messages returned from the call to the Room.EndRetrieveLatestMessages method. For each message, do the steps in the Display a Posted Message procedure to get the message values that you display in your message list.

The following procedure loads each message in the result set into a list in the UI.

To display a posted message

  1. Get the name of the message poster.

    1. Call the ContactManager.GetContactByUri method, passing the value of the RoomMessage.SenderUri property.

    2. Get the display name of the Microsoft.Lync.Model.Contact object returned in the previous step by calling the Contact.GetContactInformation method. Pass the ContactInformationType.DisplayName enumerator.

  2. Get the plain-text message by calling the RoomMessageDictionaryTryGetValue(RoomMessageFormat, Object) method on the RoomMessage.MessageDictionary property of the message.

Code examples

The following example requests the most recent 50 messages.

            try
            {
 
                //retrieve at least 50 messages
                if (_room.UnreadRoomMessageCount <= 50)
                {
                    _room.BeginRetrieveLatestMessages(_room.UnreadRoomMessageCount, GetMessagesCallback, "Latest");
                }
 
                //If there are more than 50 unread messages, get up to 50 unread messages.
                else
                {
                    _room.BeginRetrieveLatestMessages(50, GetMessagesCallback, "Latest");
                }
            }
            catch (OperationException oe)
            {
                Console.WriteLine(oe.Message);
            }

The following example asks for the next set of unread messages.

        /// <summary>
        /// Gets a set of previously posted messages.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRetrieveAdditionalMessages_Click(object sender, EventArgs e)
        {
            try
            {


                //Retrieve messages with Ids up to (but not including) the message Id specified in the first argument
                _room.BeginRetrieveAdditionalMessages(txtLastMessageID.Text, count, GetMessagesCallback, "Additional");



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


The following example is invoked on the platform thread when the asynchronous message retrieve operation is completed.

Important note Important

If you requested messages from a room that the user does not have permission to read, an exception is raised when you call the Room.EndRetrieveAdditionalMessages method.

        /// <summary>
        /// Invoked by platform thread when the message retrieve operation is completed.
        /// </summary>
        /// <param name="ar"></param>
        private void GetMessagesCallback(IAsyncResult ar)
        {

            //Declare a list to contain the collection of room messages returned by the operation
            IList<RoomMessage> messages;
            try
            {

                //Call the EndRetrieveXXXMessages operation that corresponds to the
                //BeginRetrieveXXXMessges method call that started the operation
                if (ar.AsyncState.ToString() == "Latest")
                {
                    //Get the collection of the latest messages sent to the room
                    messages = _room.EndRetrieveLatestMessages(ar);
                }
                else
                {
                    //Get the collection of messages up to the specified message
                    messages = _room.EndRetrieveAdditionalMessages(ar);
                }

                //Invoke a delegate on the UI thread that loads the message collection in the message list box.                
                listBoxMessages.Invoke(new LoadPostedMessagesDelegate(LoadPostedMessages), new object[] { messages });
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception on EndRetrieveXXMessages " + ex.Message);
            }
        }


The following example iterates on the collection of Microsoft.Lync.Model.Room.RoomMessage objects in the collection returned in the previous example. Inside of the foreach loop, the example gets the message sender name, sent date, message type, and message text. These string values are concatenated into a string and added to the message list box.

        /// <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;
                //Set the last message Id to the earliest message Id gotten in this collection
                txtLastMessageID.Text = messages[0].Id.ToString();
 

                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
                    if (message.MessageDictionary.TryGetValue(RoomMessageFormat.PlainText, out messageObject))
                    {
                        message.MessageDictionary.TryGetValue(RoomMessageFormat.PlainText, out messageObject);
                        string messageContent = (string)messageObject;

                        //create an item in the list box constructed 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 constructed 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