Hello There, Guest!
View New Posts  |  View Today's Posts
Lync 2010 Auto Responder

  • 0 Vote(s) - 0 Average


06-05-2015, 09:43 AM #1
KoBE
¯\_(ツ)_/¯
******
Global Moderators
Posts: 4,862 Threads:494 Joined: Jun 2011 Reputation: 67

Lync 2010 Auto Responder
So, I'm at my new gig and they use Lync 2010 for in-house instant messaging. I've decided to play around with the Lync SDK and made a make shift Auto Repsonder. I'm not using it for anything like mimicing being at work (although it'd be relatively easy to do). I'm more so doing it to play around with the SDK. So far I've made one command (/menu) which returns today's lunch menu formatted in RichTextFormat.

Any ideas for more functionality? I plan on posting the code to GitHub eventually. The hard part is that github is blocked for whatever reason here. So making commits might prove difficult. Either way, stay tuned for some fresh source code from me. I know it's been awhile.

06-08-2015, 10:49 AM #2
KoBE
¯\_(ツ)_/¯
******
Global Moderators
Posts: 4,862 Threads:494 Joined: Jun 2011 Reputation: 67

RE: Lync 2010 Auto Responder
Alright, I'll go ahead and post some code now. :P So far all I've had it 'auto respond' is it reaches out to our company website and parses the cafeteria lunch menu. It also has a random joke auto response as well.

I haven't been able to get it on GitHub yet. Once I do I'll remove the code from this thread and replace it with the GitHub Repository. Please note this code isn't finished. It's merely a small project I'm working on sort of as a proof of concept. This is was also made with the intention of running from a console application, so multi-threading has not been implemented. I have little experience with the Lync SDK but I'll try to help out anyone that comes across questions in regards to this or the SDK in general.

Requirements: You must have the Lync 2010 SDK installed and referenced in your project ( http://www.microsoft.com/en-us/download/...x?id=18898 )

LyncManager.cs
Code:
using System;
using System.Collections.Generic;

//lync
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;

namespace TechLifeForum
{
    public class LyncManager
    {
        // main client for interacting with Lync
        private LyncClient lyncClient = LyncClient.GetClient();

        // bool to determine if already initialized
        private bool IsInit;

        // list of active converstations
        private List<Conversation> activeConversations = new List<Conversation>();

        // accessible events
        public event EventHandler<ConversationAddedEventArgs> ConversationAdded = delegate { };
        public event EventHandler<ConversationRemovedEventArgs> ConversationRemoved = delegate { };
        public event EventHandler<MessageReceivedEventArgs> MessageReceived = delegate { };
        public event EventHandler<AvailabilityChangedEventArgs> AvailabilityChanged = delegate { };
        public event EventHandler<StateChangedEventArgs> StateChanged = delegate { };

        /// <summary>
        /// Creates a LyncManager class. Intitialize() will start interaction with Lync.
        /// </summary>
        public LyncManager() { }

        /// <summary>
        /// Start interaction with the installed LyncClient
        /// </summary>
        public void Initilize()
        {
            // don't initilize twice
            if (IsInit)
                return;

            // add any existing conversations
            foreach (Conversation c in lyncClient.ConversationManager.Conversations)
                AddConversation(c, true);

            // listen for new conversations
            lyncClient.ConversationManager.ConversationAdded += new EventHandler<ConversationManagerEventArgs>((o, e) =>
            {
                AddConversation(e.Conversation);
            });

            // listen for conversations being closed
            lyncClient.ConversationManager.ConversationRemoved += new EventHandler<ConversationManagerEventArgs>((o, e) =>
            {
                activeConversations.Remove(e.Conversation);

                string displayName = e.Conversation.Participants[1].Contact.GetContactInformation(ContactInformationType.DisplayName).ToString();
                ConversationRemoved(null, new ConversationRemovedEventArgs(displayName, e.Conversation));
            });

            // listen for Availability changes
            lyncClient.Self.Contact.ContactInformationChanged += Contact_ContactInformationChanged;

            // listen for state changes
            lyncClient.StateChanged += new EventHandler<ClientStateChangedEventArgs>((o, e) =>
            {
                StateChanged(null, new StateChangedEventArgs(e.OldState.ToString(), e.NewState.ToString()));
            });

            IsInit = true;

        }

        /// <summary>
        /// Sends a message into a conversation
        /// </summary>
        /// <param name="conversation">The intended conversation.</param>
        /// <param name="message">The message to be sent.</param>
        /// <param name="richText">RichTextFormat indicator (Default: False)</param>
        public void SendMessage(Conversation conversation, string message, bool richText = false)
        {
            InstantMessageModality modality = (InstantMessageModality)conversation.SelfParticipant.Modalities[ModalityTypes.InstantMessage];

            Dictionary<InstantMessageContentType, string> formattedMessage = new Dictionary<InstantMessageContentType, string>(1);

            if (richText)
                formattedMessage.Add(InstantMessageContentType.RichText, message);
            else
                formattedMessage.Add(InstantMessageContentType.PlainText, message);

            modality.BeginSendMessage(formattedMessage, (ar) =>
            {
                // TODO: try/catch and raise MessageError

                // end's the sending of the message
                ((InstantMessageModality)ar.AsyncState).EndSendMessage(ar);

            }, modality);
        }

        #region PrivateMethods

        /// <summary>
        /// Add the conversation to the activeConversations list as well as event listeners to the conversation
        /// </summary>
        /// <param name="c">The conversation being added</param>
        /// <param name="Existing">If the converssation was open before launching the application (Default: False)</param>
        private void AddConversation(Conversation c, bool Existing = false)
        {
            // TODO: return a list of participants instead
            //       it is possible to be added to a
            //       converstation with multiple particpants


            // add to our active convo list
            activeConversations.Add(c);

            // first participant other than yourself (TODO: list of particpants names)
            string displayName = c.Participants[1].Contact.GetContactInformation(ContactInformationType.DisplayName).ToString();

            // let the user know we added a convo
            ConversationAdded(null, new ConversationAddedEventArgs(displayName, c, Existing));

            // subscribe to each partcipant already in the convo
            // only needs to do this if it's an existing convo
            // new conversations will fire the ParticipantAdded event
            if (Existing)
                foreach (Participant p in c.Participants)
                    AddParticpant(p);

            // if new partcipants are added, subscribe to them
            c.ParticipantAdded += new EventHandler<ParticipantCollectionChangedEventArgs>(Conversation_ParticipantAdded);
        }

        private void Conversation_ParticipantAdded(object sender, ParticipantCollectionChangedEventArgs e)
        {
            AddParticpant(e.Participant);
        }

        /// <summary>
        /// Subscribes MessageReceived event handlers to each new partcipant
        /// </summary>
        /// <param name="p">New particpant</param>
        private void AddParticpant(Participant p)
        {
            // make sure it's not the logged in user
            if (!p.IsSelf)
            {
                p.Contact.ContactInformationChanged += Contact_ContactInformationChanged;
                InstantMessageModality modality = (InstantMessageModality)p.Modalities[ModalityTypes.InstantMessage];
                modality.InstantMessageReceived += modality_InstantMessageReceived;
            }
        }

        private void Contact_ContactInformationChanged(object sender, ContactInformationChangedEventArgs e)
        {
            try
            {
                if (e.ChangedContactInformation.Contains(ContactInformationType.Availability))
                {
                    Contact contact = (Contact)sender;

                    string displayName = contact.GetContactInformation(ContactInformationType.DisplayName).ToString();
                    string availability = contact.GetContactInformation(ContactInformationType.Activity).ToString();
                    AvailabilityChanged(null, new AvailabilityChangedEventArgs(displayName, availability));
                }
            }
            catch (NotSignedInException nsiEx)
            {
                Console.WriteLine("Not Signed In Exception (contactInfoChanged)");
            }
        }

        // raises the message received event
        private void modality_InstantMessageReceived(object sender, MessageSentEventArgs e)
        {
            InstantMessageModality modality = (InstantMessageModality)sender;
            string displayName = modality.Participant.Contact.GetContactInformation(ContactInformationType.DisplayName).ToString();
            string message = e.Text;

            MessageReceived(sender, new MessageReceivedEventArgs(displayName, message, modality.Conversation));
        }

        #endregion
    }
}

EventArguements.cs
Code:
using System;

// lync
using Microsoft.Lync.Model.Conversation;

namespace TechLifeForum
{
    public class ConversationAddedEventArgs : EventArgs
    {
        public string DisplayName { get; internal set; }
        public Conversation Conversation { get; internal set; }
        public bool Existing { get; internal set; }
        public ConversationAddedEventArgs(string DisplayName, Conversation Conversation, bool Existing)
        {
            this.DisplayName = DisplayName;
            this.Conversation = Conversation;

            // if there were already conversations open when class is initiated
            this.Existing = Existing;
        }
    }
    public class ConversationRemovedEventArgs : EventArgs
    {
        public string DisplayName { get; internal set; }
        public Conversation Conversation { get; internal set; }
        public ConversationRemovedEventArgs(string DisplayName, Conversation Conversation)
        {
            this.DisplayName = DisplayName;
            this.Conversation = Conversation;
        }
    }
    public class MessageReceivedEventArgs : EventArgs
    {
        public string DisplayName { get; internal set; }
        public string Message { get; internal set; }
        public Conversation Conversation { get; internal set; }
        public MessageReceivedEventArgs(string DisplayName, string Message, Conversation Conversation)
        {
            this.DisplayName = DisplayName;
            this.Message = Message;
            this.Conversation = Conversation;
        }
    }
    public class StateChangedEventArgs : EventArgs
    {
        public string OldState { get; internal set; }
        public string NewState { get; internal set; }
        public StateChangedEventArgs(string OldState, string NewState)
        {
            this.OldState = OldState;
            this.NewState = NewState;
        }
    }
    public class AvailabilityChangedEventArgs : EventArgs
    {
        public string DisplayName { get; internal set; }
        public string Activity { get; internal set; }
        public AvailabilityChangedEventArgs(string DisplayName, string Activity)
        {
            this.DisplayName = DisplayName;
            this.Activity = Activity;
        }
    }
}

Sample Usage:
Code:
// example usage
LyncManager lync = new LyncManager();

// add event handlers before starting the lyncClient
lync.AvailabilityChanged += lync_AvailabilityChanged;
lync.ConversationAdded += lync_ConversationAdded;
lync.ConversationRemoved += lync_ConversationRemoved;
lync.MessageReceived += lync_MessageReceived;
lync.StateChanged += lync_StateChanged;

// start it up
lync.Initilize();


// sample message response
static void lync_MessageReceived(object sender, MessageReceivedEventArgs e)
{
    Console.WriteLine("Message from: " + e.DisplayName);

    if (e.Message.StartsWith("/joke"))
    {
        lync.SendMessage(e.Conversation, GetJoke(),true);
    }
}
This post was last modified: 06-08-2015, 02:09 PM by KoBE. Edit Reason: source fix




Forum Jump:


Possibly Related Threads...
Thread Author Replies Views Last Post
   Screenshot Utility with Auto Upload KoBE 12 7,385 08-28-2014, 08:12 PM
Last Post: KoBE
   [Tutorial]Auto Update Tutorial for VB.Net Gemster 8 18,075 02-08-2014, 04:34 AM
Last Post: assasaha
   DateTimePicker Auto Update? Lee Stevens 4 2,743 01-17-2014, 10:58 AM
Last Post: Miklo
   [Help] VB 2010 IRC-Simulation KALEV 4 1,710 04-07-2013, 02:28 PM
Last Post: KALEV
Big Grin  Auto Login v1 (Converted) Morpheus 8 3,985 05-25-2012, 05:15 PM
Last Post: OneTXxL


Users browsing this thread: 1 Guest(s)