How to: Post a message to a persistent chat room

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

Describes how to post regular and story messages to a Microsoft Lync 2013 Preview persistent chat room.

This How to shows you the code that you add to a simple persistent chat window so that a user can post a message to a chat room. A user can post a regular message or an alert message to a chat room and the message can be plain text, rich-text (RTF), or the message can be sent in both formats.

A message can be sent to a chat room even if the user is not an active participant in the chat room. There are two requirements to post messages to a chat room:

  • The user must be a member of the chat room.

  • If the chat room is an RoomType.Auditorium chat room, the user must be a presenter in the auditorium.

Tip Tip

The user must join a chat room before they can post messages to the chat room. The user is added to the participant list and a Room.ParticipantAdded event is raised on any other client that is registered for the event and whose user is an active participant in the chat room.

A user is automatically joined to a followed chat room when the user signs in to Microsoft Lync 2013 Preview. In this case, the ParticipantAdded event is raised on other clients when the member-user signs in to .

In some scenarios, it is important that a message that is posted to a chat room comply with content and formatting constraints imposed by the organization that administers the Persistent Chat Server. For example, a multinational IT company may want to make sure that a user’s message does not contain language that can offend another chat room user. To make this message filtering possible, the Lync platform exposes an event that is raised when a message posting operation has started but is pending review by a logical message filter. The filter catches the event, runs filter logic on the message, updates the message as necessary, and then posts the message or cancels it. For information about how to build a message filter, see How to: Filter and format persistent chat room messages.

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 post messages. For information about getting a chat room, see How to: Get persistent chat rooms. Your application must declare a button and an RTF text box. The RTF text box accepts the message string to post and the button posts the message.

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 chat rooms that are queried, searched for, or gotten from the followed chat 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 = "";

        /// <summary>
        /// The default color of the message send button. Used to restore the color after a local user
        /// message post is successful
        /// </summary>
        private System.Drawing.Color originalSendButtonColor;
        


The following example constructs the simple chat window UI and saves the original background color of the send button.

        /// <summary>
        /// Simple chat window constructor
        /// </summary>
        public SimpleChat()
        {
            InitializeComponent();
 
            // Save the original color of the message post button.
            originalSendButtonColor = btnSendMessage.BackColor;
          
        }

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

To prepare to post messages

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

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

  3. Register for chat room events.

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

The following example registers for chat room events, reads chat room properties, and gets the chat room participant roster.

        /// <summary>
        /// Registers for message, state, and participant related events on a chat room.
        /// </summary>
        private void FillRoomProperties(Room room)
        {
            if (_room != null)
            {
                //Un-Register for event raised when a new message is posted to the chat 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 chat room.
                _room.MessagesReceived -= room_MessagesReceived;

            }


            _room = room;

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

            //Register for event raised when a new message is posted to the chat 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 chat 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();
        }


After you have prepared to post messages to a chat room by following the steps in the previous procedure, you are ready to accept a user’s text input and post new messages to the selected chat room.

To post a message to a chat room

  1. Declare and instantiate an instance of IDictionary<Microsoft.Lync.Model.Room.RoomMessageFormat, string> that you add formatted message strings to. The dictionary is passed into the message posting method as the first argument.

  2. Add both versions of the message to the dictionary declared in the previous step.

    1. Add the key/value pair of RoomMessageFormat.PlainText/ plain-text-formatted string (the message text) to the dictionary declared in the previous step.

    2. Add the key/value pair of RoomMessageFormat.Rtf/ Rtf formatted version of the message string to the dictionary declared in the previous step.

  3. Join the chat room if the current Room.JoinedState is RoomJoinState.NotJoined.

  4. If the message is a regular message, call the Room.BeginSendMessage overload of the method.

    Note Note

    The following code example passes RoomMessageType.Regular as the second argument without asking a user for input. Normally, you would put a choice control on your window that lets a user select one of the four message types.

    When the text of the message is long enough to justify displaying the message as a story in the Lync 2013 Preview persistent chat window, set the RoomMessageType to RoomMessageType.Story

  5. If the user wants to send a story instead of a regular message and has provided a story title, call the Room.BeginSendStoryMessage method.

  6. Handle the Room.MessagesReceived event.

  7. Iterate over the collection of new messages and find a message whose sender URI matches the local user’s URI and message text matches the newly posted message. If a match is found, the message was posted to the chat room.

Tip Tip

If posting a plain-text message only, call Room.BeginSendMessage, passing the plain-text message string in the first argument instead of the IDictionary instance.

Tip Tip

The following list describes two ways that you can confirm if a local user’s message was posted to a chat room.

  • Code a try/catch block around the Room.EndSendMessage method that you call inside a callback method passed into the Room.BeginSendMessage method. If an exception is not raised and the user is a member of the chat room with permission to post, the post succeeded.

  • Handle the Room.MessagesReceived event. If one of the messages in the collection of new messages posted to the chat room originated with the local user, the post succeeded.

Code examples

The following example gets the user’s message text and then posts the plain text formatted version of the message to a chat room.

        /// <summary>
        /// Handles the event raised when the user clicks the Send button
        /// </summary>
        /// <param name="followedRoom">Room. The chat room to post to</param>
        /// <param name="messageTitle">string. The title of the story</param>
        /// <param name="messageBody">string. The message body</param>
        private void SendAMessage(Room followedRoom, string messageTitle, string messageBody)
        {
            //Send a message if the user has selected a room
            if (followedRoom == null || _client.State != ClientState.SignedIn)
            {
                Console.WriteLine("Message was not sent");
                return;
            }
            try
            {
                //If the user is not joined to the room then try to join the room
                if (followedRoom.JoinedState != RoomJoinState.Success)
                {
                    followedRoom.BeginJoin((ar) => { followedRoom.EndJoin(ar); }, null);
                }

                //If the user is connected (joined) to the room then send the message
                if (followedRoom.JoinedState == RoomJoinState.Success)
                {
                    //Post the story

                    IDictionary<RoomMessageFormat, string> roomMessageDictionary = new Dictionary<RoomMessageFormat, string>();
                    roomMessageDictionary.Add(RoomMessageFormat.PlainText, messageBody);

                    // If the user added a story title, then send message as a story.
                    if (messageTitle.Length > 0)
                    {
                        followedRoom.BeginSendStoryMessage(roomMessageDictionary, messageTitle, (ar) =>
                        {
                            try
                            {
                                followedRoom.EndSendStoryMessage(ar);
                                Console.WriteLine( "Message Sent" );
                            }
                            catch (OperationException oe)
                            {
                                Console.WriteLine("Lync client failed to send the message: " + oe.Message);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Exception on send message: " + ex.Message);
                            }
                        }, null);
                    }

                    // if the user did not provide a story title, then send as regular message.
                    else
                    {
                        followedRoom.BeginSendMessage(roomMessageDictionary, RoomMessageType.Regular, (ar) =>
                        {
                            try
                            {
                                followedRoom.EndSendMessage(ar);
                                Console.WriteLine("Message Sent");
                            }
                            catch (OperationException oe)
                            {
                                Console.WriteLine("Lync client failed to send the message: " + oe.Message);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Exception on send message: " + ex.Message);
                            }
                        }, null);
                    }
                }
            }
            catch (JoinRoomFailException)
            {
                Console.WriteLine("Failed to join room");
            }
            catch (JoinRoomUnauthorizedException)
            {
                Console.WriteLine("Not authorized to join room");
            }
            catch (OperationException oe)
            {
                Console.WriteLine("Operation Exception on post message " + oe.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception on post message " + ex.Message);
            }
        }


Important note Important

Room.EndSendMessage raises an exception if the sent message contains an invalid RTF string.

Community Additions

Show:
© 2015 Microsoft