void Conversation_ParticipantAdded(object sender, ParticipantCollectionChangedEventArgs e)
        {
            // add event handlers for modalities of participants other than self participant:
            if (e.Participant.IsSelf == false)
            {
                if (((Conversation)sender).Modalities.ContainsKey(ModalityTypes.InstantMessage))
                {
                    ((InstantMessageModality)e.Participant.Modalities[ModalityTypes.InstantMessage]).InstantMessageReceived += new EventHandler <MessageSentEventArgs>(ConversationTest_InstantMessageReceived);
                    ((InstantMessageModality)e.Participant.Modalities[ModalityTypes.InstantMessage]).IsTypingChanged        += new EventHandler <IsTypingChangedEventArgs>(ConversationTest_IsTypingChanged);
                }
                Conversation conversation = (Conversation)sender;

                InstantMessageModality imModality = (InstantMessageModality)conversation.Modalities[ModalityTypes.InstantMessage];

                IDictionary <InstantMessageContentType, string> textMessage = new Dictionary <InstantMessageContentType, string>();
                textMessage.Add(InstantMessageContentType.PlainText, "Hello World");

                if (imModality.CanInvoke(ModalityAction.SendInstantMessage))
                {
                    IAsyncResult asyncResult = imModality.BeginSendMessage(
                        textMessage,
                        SendMessageCallback,
                        imModality);
                }
            }
        }
Exemple #2
0
        void _convServ_MessageRecived(string message, string participantName, InstantMessageModality instantMessageModality)
        {
            if (!cbxSendResponse.Checked)
            {
                return;
            }

            secondFire = !secondFire;
            if (secondFire)
            {
                return;
            }

            _instMsgMod = instantMessageModality;

            switch (messageIndex)
            {
            case 0:
                Thread tMsg1 = new Thread(sndMsg1);
                tMsg1.Start();
                messageIndex++;
                break;

            case 1:
                Thread tMsg2 = new Thread(sndMsg2);
                tMsg2.Start();
                messageIndex++;
                break;

            default:
                //unsubscribe, we don't want to let them figure out its a bot
                _convServ.MessageRecived -= _convServ_MessageRecived;
                break;
            }
        }
        void Conversation_ParticipantAdded(object sender, ParticipantCollectionChangedEventArgs e)
        {
            // add event handlers for modalities of participants other than self participant:
            if (e.Participant.IsSelf == false)
            {
                if (((Conversation)sender).Modalities.ContainsKey(ModalityTypes.InstantMessage))
                {
                    ((InstantMessageModality)e.Participant.Modalities[ModalityTypes.InstantMessage]).InstantMessageReceived += new EventHandler <MessageSentEventArgs>(ConversationTest_InstantMessageReceived);
                    ((InstantMessageModality)e.Participant.Modalities[ModalityTypes.InstantMessage]).IsTypingChanged        += new EventHandler <IsTypingChangedEventArgs>(ConversationTest_IsTypingChanged);
                }
                Conversation conversation = (Conversation)sender;

                InstantMessageModality imModality = (InstantMessageModality)conversation.Modalities[ModalityTypes.InstantMessage];
                string messageContent             = "Hello World";
                IDictionary <InstantMessageContentType, string> formattedMessage = this.GenerateFormattedMessage(messageContent);

                try
                {
                    if (imModality.CanInvoke(ModalityAction.SendInstantMessage))
                    {
                        IAsyncResult asyncResult = imModality.BeginSendMessage(
                            formattedMessage,
                            SendMessageCallback,
                            imModality);
                    }
                }
                catch (LyncClientException ex)
                {
                    txtErrors.Text = ex.Message;
                }
            }
        }
Exemple #4
0
        void StartConversation(string myRemoteParticipantUri, string MSG)
        {
            foreach (var con in _conversationManager.Conversations)
            {
                if (con.Participants.Where(p => p.Contact.Uri == "sip:" + myRemoteParticipantUri).Count() > 0)
                {
                    if (con.Participants.Count == 2)
                    {
                        con.End();
                        break;
                    }
                }
            }

            Conversation _Conversation = _conversationManager.AddConversation();

            _Conversation.AddParticipant(_lyncClient.ContactManager.GetContactByUri(myRemoteParticipantUri));


            Dictionary <InstantMessageContentType, String> messages = new Dictionary <InstantMessageContentType, String>();

            messages.Add(InstantMessageContentType.PlainText, MSG);
            InstantMessageModality m = (InstantMessageModality)_Conversation.Modalities[ModalityTypes.InstantMessage];

            m.BeginSendMessage(messages, null, messages);
            LogMessage(myRemoteParticipantUri, MSG);
        }
Exemple #5
0
        // Callback method for the BeginSendContextData method.
        public void SendContextDataCallback(IAsyncResult res)
        {
            ConversationWindow     _conversationWindow = ((Automation)res.AsyncState).EndStartConversation(res);
            InstantMessageModality instantMessage      = (InstantMessageModality)_conversationWindow.Conversation.Modalities[ModalityTypes.InstantMessage];

            instantMessage.BeginSendMessage("hello sdx - success!", SendCMessageCallback, null);
        }
        /// <summary>
        /// Register for InstantMessageReceived events for the specified participant.
        /// </summary>
        /// <param name="participant"></param>
        private void SubcribeToParticipantMessages(Participant participant)
        {
            //registers for IM received messages
            InstantMessageModality remoteImModality = (InstantMessageModality)participant.Modalities[ModalityTypes.InstantMessage];

            remoteImModality.InstantMessageReceived += new EventHandler <MessageSentEventArgs>(remoteImModality_InstantMessageReceived);
        }
        private void OnAllRecipientsAdded(Conversation currentConversation)
        {
            InstantMessageModality imModality = currentConversation.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;

            IDictionary <InstantMessageContentType, string> textMessage = new Dictionary <InstantMessageContentType, string>();

            textMessage.Add(InstantMessageContentType.PlainText, _message);

            if (imModality.CanInvoke(ModalityAction.SendInstantMessage))
            {
                IAsyncResult asyncResult = imModality.BeginSendMessage(textMessage, ar => { SendMessageCallback(imModality, ar); }, null);
                if (!_sendIMEvent.WaitOne(75000))
                {
                    Trace.WriteLine($"SendIM action failed in timeout recipients = {string.Join(", ", _recipients)}");
                    SendIMTimeout = true;
                }
                else
                {
                    //if at the end of the send, it remains only 1 participant (me) ==> All other participants are offline
                    //AllPArticipantsOffline = (currentConversation.Participants.Count = 1)

                    Trace.WriteLine($"SendIM action succedeed recipients = {string.Join(", ", _recipients)}");
                    Thread.Sleep(250);
                }
            }
        }
        internal void SendMessage(string contactUri, string imText)
        {
            try
            {
                if (_Client.State == ClientState.SignedIn)
                {
                    ConversationManager myConversationManager = _Client.ConversationManager;
                    Conversation        myConversation        = myConversationManager.AddConversation();
                    Participant         myParticipant         = myConversation.AddParticipant(_Client.ContactManager.GetContactByUri(contactUri));

                    if (myParticipant.IsSelf == false)
                    {
                        if (myConversation.State == ConversationState.Active && myConversation.Properties.ContainsKey(ConversationProperty.Subject))
                        {
                            myConversation.Properties[ConversationProperty.Subject] = SUBJECT;
                        }

                        if (myConversation.Modalities.ContainsKey(ModalityTypes.InstantMessage))
                        {
                            InstantMessageModality imModality = (InstantMessageModality)myConversation.Modalities[ModalityTypes.InstantMessage];
                            if (imModality.CanInvoke(ModalityAction.SendInstantMessage))
                            {
                                Dictionary <InstantMessageContentType, string> textMessage = new Dictionary <InstantMessageContentType, string>();
                                textMessage.Add(InstantMessageContentType.PlainText, SUBJECT + " : " + imText);

                                imModality.BeginSendMessage(textMessage, SendMessageCallback, imModality);
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
Exemple #9
0
        /// <summary>
        /// Prevents a default instance of the <see cref="CallHandler"/> class from being created.
        /// </summary>
        private CallHandler()
        {
            this.lyncClient = LyncClient.GetClient();

            // FOR CWE WINDOW,use current hosting conversation
            this.conversation = (Conversation)Microsoft.Lync.Model.LyncClient.GetHostingConversation();
            if (this.conversation == null)
            {
                this.conversation = this.lyncClient.ConversationManager.Conversations[this.lyncClient.ConversationManager.Conversations.Count - 1];
            }

            this.audioVideoModality = (AVModality)this.conversation.Modalities[ModalityTypes.AudioVideo];
            this.audioChannel       = this.audioVideoModality.AudioChannel;

            this.conversation.StateChanged += this.Conversation_StateChangedEvent;
            this.conversation.BeginSendContextData("{553C1CE2-0C73-51B6-81C7-75F2D071FCD2}", @"plain/text", "hi", SendContextDataCallBack, null);

            this.audioVideoModality.ModalityStateChanged += new EventHandler <ModalityStateChangedEventArgs>(this.AudioVideoModality_ModalityStateChanged);

            this.instantMessageModality = (InstantMessageModality)this.conversation.Modalities[ModalityTypes.InstantMessage];

            this.remoteModality = this.conversation.Participants[1].Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;

            this.remoteModality.InstantMessageReceived += new EventHandler <MessageSentEventArgs>(this.RemoteModality_InstantMessageReceived);

            this.instantMessageModality.InstantMessageReceived += new EventHandler <MessageSentEventArgs>(this.ImModality_InstantMessageReceived);

            this.CurrentMenuLevel = 0;
        }
        public LyncConversationHandler(ITelegramBotClient bot)
        {
            _bot = bot;
            _initClient();


            string[]     targetContactUris = { "sip:[email protected]" };
            LyncClient   client            = LyncClient.GetClient();
            Conversation conv = client.ConversationManager.AddConversation();

            foreach (string target in targetContactUris)
            {
                conv.AddParticipant(client.ContactManager.GetContactByUri(target));
            }
            InstantMessageModality m = conv.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;

            m.BeginSendMessage("Test Message", null, null);


            Microsoft.Win32.SystemEvents.SessionSwitch += (s, e) =>
            {
                if (e.Reason == SessionSwitchReason.SessionLock)
                {
                    _isSessionLock = true;
                }
                else if (e.Reason == SessionSwitchReason.SessionUnlock)
                {
                    _isSessionLock = false;
                }
            };
        }
Exemple #11
0
        private static string GetLogFilePath(InstantMessageModality messageInfo)
        {
            string path = ConfigurationManager.AppSettings["LOG_PATH"];

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string username;

            if (messageInfo.Conversation.Participants.Count > 2)
            {
                username = "******";
            }
            else
            {
                Participant participant = LyncHelper.GetConversationParticipant(messageInfo.Conversation);
                username = LyncHelper.GetContactUsername(participant.Contact);
            }

            path += "/" + username;

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string conversationId = (string)messageInfo.Conversation.Properties[ConversationProperty.Id];
            string filename       = GetConversationFilename(conversationId);

            path += "/" + filename;

            return(path);
        }
Exemple #12
0
        public LyncConversation TrackConversation(Conversation conv)
        {
            var participants = new Dictionary <Participant, LyncParticipant>();

            foreach (var participant in conv.Participants)
            {
                if (participant.IsSelf)
                {
                    continue;
                }

                InstantMessageModality modality = (InstantMessageModality)participant.Modalities[ModalityTypes.InstantMessage];
                modality.InstantMessageReceived += imModality_InstantMessageReceived;

                participants.Add(participant, new LyncParticipant {
                    modality = modality, participant = participant
                });
            }

            conv.ParticipantAdded   += Conv_ParticipantAdded;
            conv.ParticipantRemoved += Conv_ParticipantRemoved;

            var lyncConv = new LyncConversation()
            {
                conversation = conv, participants = participants
            };

            lyncConv.UpdateDesc();

            return(lyncConv);
        }
        /// <summary>
        /// Receives the conversation, callback to UI and the OC root object
        /// </summary>
        public ConversationService(Conversation conversation)
        {
            //stores the conversation object
            this.conversation = conversation;

            //gets the IM modality from the self participant in the conversation
            this.myImModality = (InstantMessageModality)conversation.SelfParticipant.Modalities[ModalityTypes.InstantMessage];
        }
        /// <summary>
        /// Receives the conversation, callback to UI and the OC root object
        /// </summary>
        public ConversationService(Conversation conversation)
        {
            //stores the conversation object
            this.conversation = conversation;

            //gets the IM modality from the self participant in the conversation
            this.myImModality = (InstantMessageModality)conversation.SelfParticipant.Modalities[ModalityTypes.InstantMessage];
        }
        private void StartConversation(Conversation conversation, InstantMessageModality imModality)
        {
            conversation.ParticipantAdded += conversation_ParticipantAdded;
            conversation.StateChanged += conversation_StateChanged;
            conversation.ActionAvailabilityChanged += conversation_ActionAvailabilityChanged;

            imModality.InstantMessageReceived += imModality_InstantMessageReceived;
            imModality.IsTypingChanged += imModality_IsTypingChanged;
            imModality.ActionAvailabilityChanged += imModality_ActionAvailabilityChanged;
        }
Exemple #16
0
 //send message
 private void button2_Click(object sender, RoutedEventArgs e)
 {
     foreach (Conversation conversation in _LyncClient.ConversationManager.Conversations)
     {
         InstantMessageModality instantMessage = (InstantMessageModality)conversation.Modalities[ModalityTypes.InstantMessage];
         Dictionary <InstantMessageContentType, string> contents = new Dictionary <InstantMessageContentType, string>();
         contents.Add(InstantMessageContentType.PlainText, "http://www.google.com");
         //instantMessage.BeginSendMessage("hello sdx - success!", SendCMessageCallback, null);
         instantMessage.BeginSendMessage(contents, SendCMessageCallback, null);
     }
 }
 /// <summary>
 /// Binds the new message handler to any new messages coming from a conversation participant
 /// </summary>
 /// <param name="participant"></param>
 private void BindNewMessageHandlerToOtherParticipant(Participant participant)
 {
     // That's not me
     if (participant.Contact.Uri != _lyncClient.Self.Contact.Uri)
     {
         // When they send a message
         InstantMessageModality instantMessageModality = participant.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;
         instantMessageModality.InstantMessageReceived -= newMessageHandler;
         instantMessageModality.InstantMessageReceived += newMessageHandler;
     }
 }
Exemple #18
0
        public void SendLyncMessage(string contactMail, string message)
        {
            var contact = lyncClient.ContactManager.GetContactByUri(contactMail);
            var conv    = lyncClient.ConversationManager.AddConversation();

            conv.AddParticipant(lyncClient.ContactManager.GetContactByUri(contact.Uri));

            InstantMessageModality m = conv.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;

            m.BeginSendMessage(message, null, null);
        }
        private void SendMessageCallback(IAsyncResult ar)
        {
            try
            {
                InstantMessageModality imModality = (InstantMessageModality)ar.AsyncState;

                imModality.EndSendMessage(ar);
            }
            catch
            {
            }
        }
        /*
         * /// <summary>
         * /// Start the conversation with the specified participant using sip address
         * /// </summary>
         * /// <param name="sender"></param>
         * /// <param name="e"></param>
         * private void btnStartConv_Click(object sender, RoutedEventArgs e)
         * {
         *  TextRange tr = new TextRange(rtbParticipants.Document.ContentStart, rtbParticipants.Document.ContentEnd);
         *  if (String.IsNullOrEmpty(tr.Text.Trim()))
         *  {
         *      txtErrors.Text = "No participants specified!";
         *      return;
         *  }
         *  String[] participants = tr.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
         *
         *  KeyValuePair<AutomationModalitySettings, object>[] contextData = new KeyValuePair<AutomationModalitySettings, object>[]
         *      {
         *          new KeyValuePair<AutomationModalitySettings, object>(AutomationModalitySettings.SendFirstInstantMessageImmediately, true),
         *          new KeyValuePair<AutomationModalitySettings, object>(AutomationModalitySettings.FirstInstantMessage, "Hello World"),
         *          new KeyValuePair<AutomationModalitySettings, object>(AutomationModalitySettings.Subject, "Welcome To Lync Conversation Window"),
         *      };
         *
         *  IAsyncResult ar = automation.BeginStartConversation(AutomationModalities.InstantMessage, participants, contextData, null, null);
         *  automation.EndStartConversation(ar);
         * }
         */


        /// <summary>
        /// Async callback method invoked by InstantMessageModality instance when SendMessage completes
        /// </summary>
        /// <param name="_asyncOperation">IAsyncResult The operation result</param>
        ///
        private void SendMessageCallback(IAsyncResult ar)
        {
            InstantMessageModality imModality = (InstantMessageModality)ar.AsyncState;

            try
            {
                imModality.EndSendMessage(ar);
            }
            catch (LyncClientException lce)
            {
                MessageBox.Show("Lync Client Exception on EndSendMessage " + lce.Message);
            }
        }
Exemple #21
0
        public static void Write(InstantMessageModality messageInfo, string text)
        {
            string username = LyncHelper.GetContactUsername(messageInfo.Participant.Contact);
            string path     = GetLogFilePath(messageInfo);

            using (var writer = new StreamWriter(path, true))
            {
                if (!text.EndsWith(Environment.NewLine))
                {
                    text += Environment.NewLine;
                }

                writer.Write("[{0} {1}] {2}: {3}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), username, text);
            }
        }
Exemple #22
0
        private static void InstantMessageModality_InstantMessageReceived(object sender, MessageSentEventArgs e)
        {
            InstantMessageModality test1 = sender as InstantMessageModality;

            String txt = e.Text.Trim();

            int leng = txt.Length;

            if (txt == "!퇴근")
            {
                makeMessage(1, test1, null);
            }
            else if (txt == "!주사위")
            {
                makeMessage(2, test1, null);
            }
            else if (txt == "!아침")
            {
                makeMessage(4, test1, "AM");
            }
            else if (txt == "!점심")
            {
                makeMessage(4, test1, "NOON");
            }
            else if (txt == "!저녁")
            {
                makeMessage(4, test1, "PM");
            }
            else if (txt.StartsWith("!추가 "))
            {
                string add = "";
                try {
                    add = txt.Substring(4, leng - 4);
                }
                catch (Exception)
                {
                    add = txt.Substring(4, leng - 5);
                }
                makeMessage(3, test1, add);
            }
            else if (txt.Substring(0, 1) == "!")
            {
                makeMessage(0, test1, txt.Substring(1, leng - 1));
            }
            else
            {
            }
        }
 private void SendMessageCallback(InstantMessageModality imModality, IAsyncResult asyncResult)
 {
     try
     {
         imModality.EndSendMessage(asyncResult);
     }
     catch (Exception ex)
     {
         Trace.WriteLine("Exception during SendMessageCallback");
         Trace.WriteLine($"{ex.Message}");
         Trace.WriteLine($"{ex.StackTrace}");
     }
     finally
     {
         _sendIMEvent.Set();
     }
 }
Exemple #24
0
        protected async Task DoSendMessageAsync(Conversation conversation, string data, InstantMessageContentType type)
        {
            try
            {
                InstantMessageModality imModality = (InstantMessageModality)conversation.Modalities[ModalityTypes.InstantMessage];
                var formattedMessage = new Dictionary <InstantMessageContentType, string>();
                formattedMessage.Add(type, data);

                if (imModality.CanInvoke(ModalityAction.SendInstantMessage))
                {
                    await Task.Factory.FromAsync(imModality.BeginSendMessage, imModality.EndSendMessage, formattedMessage, imModality);
                }
            }
            catch (LyncClientException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #25
0
        void conversationManager_ConversationAdded(object sender, ConversationManagerEventArgs e)
        {
            try
            {
                ModalityState newState = e.Conversation.Modalities[ModalityTypes.InstantMessage].State;
                if (newState == ModalityState.Connected || newState == ModalityState.Notified)
                {
                    _ConversationImModality = (InstantMessageModality)e.Conversation.Modalities[ModalityTypes.InstantMessage];
                }

                e.Conversation.ParticipantAdded += new EventHandler <ParticipantCollectionChangedEventArgs>(Conversation_ParticipantAdded);
                // e.Conversation.AddParticipant(client.ContactManager.GetContactByUri(RemoteUserUri));
            }
            catch (LyncClientException lce)
            {
                System.Diagnostics.Debug.WriteLine("LYnc client exception on conversationadded " + lce.Message);
            }
        }
Exemple #26
0
        private void ImModality_InstantMessageReceived(object sender, MessageSentEventArgs e)
        {
            InstantMessageModality im = (InstantMessageModality)sender;

            if (!im.Participant.IsSelf)
            {
                var botConversation = directLineCLient.Conversations.NewConversationWithHttpMessagesAsync().Result.Body;

                var message = new Message();
                message.ConversationId = botConversation.ConversationId;
                message.Text           = e.Text;
                var result = directLineCLient.Conversations.PostMessageWithHttpMessagesAsync(botConversation.ConversationId, message).Result;

                var response = directLineCLient.Conversations.GetMessagesWithHttpMessagesAsync(botConversation.ConversationId).Result;

                im.BeginSendMessage(response.Body.Messages.LastOrDefault().Text, null, response.Body.Messages.LastOrDefault());
            }
        }
Exemple #27
0
        public void UpdateConversation(LyncConversation conv)
        {
            var activeParticipants = new List <Participant>();

            foreach (var participant in conv.conversation.Participants)
            {
                if (participant.IsSelf)
                {
                    continue;
                }

                activeParticipants.Add(participant);

                if (conv.participants.ContainsKey(participant))
                {
                    continue;
                }

                InstantMessageModality modality = (InstantMessageModality)participant.Modalities[ModalityTypes.InstantMessage];
                modality.InstantMessageReceived += imModality_InstantMessageReceived;

                conv.participants.Add(participant, new LyncParticipant {
                    modality = modality, participant = participant
                });
            }

            var deadParticipants = new List <Participant>();

            foreach (var participant in conv.participants.Keys)
            {
                if (!activeParticipants.Contains(participant))
                {
                    deadParticipants.Add(participant);
                }
            }

            foreach (var participant in deadParticipants)
            {
                conv.participants.Remove(participant);
            }

            conv.UpdateDesc();
        }
Exemple #28
0
        protected override void Execute(NativeActivityContext context)
        {
            try
            {
                string[]     arrRecepients = ReciepientList.Get(context).Split(';'); //add your recepients here
                LyncClient   lyncClient    = LyncClient.GetClient();
                Conversation conversation  = lyncClient.ConversationManager.AddConversation();

                foreach (string recepient in arrRecepients)
                {
                    conversation.AddParticipant(lyncClient.ContactManager.GetContactByUri(recepient));
                }
                InstantMessageModality imModality = conversation.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;
                string message = Message.Get(context);//use your existing notification logic here
                imModality.BeginSendMessage(message, null, null);
            }
            catch (Exception ex)
            {
            }
        }
Exemple #29
0
        private static void ChatRecived(object sender, MessageSentEventArgs e)
        {
            InstantMessageModality nananana = (InstantMessageModality)sender;
            // el user ees elPibe
            string elPibe = nananana.Endpoint.DisplayName.Substring(0, nananana.Endpoint.DisplayName.LastIndexOf("@"));
            // por ahora, luego habrá que separar los argumentos,
            //no mejor habria que derivar del comando cuantos y que arg lleva y preguntarlos y esas cosas que le gustan al Colo
            string elComando = e.Text;

            //loguear
            Console.WriteLine(DateTime.Now + ". " + elPibe + " dice: " + elComando);

            nananana.BeginSendMessage("Llegó, gracias " + elPibe, (ar) => { nananana.EndSendMessage(ar); }, null);

            //Executar comando y contar como va yendo y esa onda
            var elResul = Ejecuta(elPibe, elComando);

            Console.WriteLine(elResul);

            nananana.BeginSendMessage(elResul, (ar) => { nananana.EndSendMessage(ar); }, null);
        }
        /// <summary>
        /// Called by the Lync SDK when a new message is received.
        /// </summary>
        private void remoteImModality_InstantMessageReceived(object sender, MessageSentEventArgs args)
        {
            try
            {
                //casts the modality
                InstantMessageModality modality = (InstantMessageModality)sender;

                //gets the participant name
                string name = (string)modality.Participant.Contact.GetContactInformation(ContactInformationType.DisplayName);

                //reads the message in its plain text format (automatically converted)
                string message = args.Text;

                //notifies the UI about the new message
                MessageRecived(message, name);
            }
            catch (Exception ex)
            {
                MessageError(ex);
            }
        }
        private void BeginSearchCallback(IAsyncResult r)
        {
            object[]       asyncState = (object[])r.AsyncState;
            ContactManager cm         = (ContactManager)asyncState[0];

            try
            {
                SearchResults results = cm.EndSearch(r);
                if (results.AllResults.Count == 0)
                {
                    Console.WriteLine("No results.");
                }
                else if (results.AllResults.Count == 1)
                {
                    ContactSubscription srs     = cm.CreateSubscription();
                    Contact             contact = results.Contacts[0];
                    srs.AddContact(contact);
                    ContactInformationType[] contactInformationTypes = { ContactInformationType.Availability, ContactInformationType.ActivityId };
                    srs.Subscribe(ContactSubscriptionRefreshRate.High, contactInformationTypes);
                    _conversation = _client.ConversationManager.AddConversation();
                    _conversation.AddParticipant(contact);
                    Dictionary <InstantMessageContentType, String> messages = new Dictionary <InstantMessageContentType, String>();
                    messages.Add(InstantMessageContentType.PlainText, _message);
                    InstantMessageModality m = (InstantMessageModality)_conversation.Modalities[ModalityTypes.InstantMessage];
                    m.BeginSendMessage(messages, BeginSendMessageCallback, messages);
                }
                else
                {
                    Console.WriteLine("More than one result.");
                }
            }
            catch (SearchException se)
            {
                Console.WriteLine("Search failed: " + se.Reason.ToString());
            }
            _client.ContactManager.EndSearch(r);
        }
Exemple #32
0
        void InstantMessageModality_InstantMessageReceived(object sender, Microsoft.Lync.Model.Conversation.MessageSentEventArgs args)
        {
            InstantMessageModality imm       = (sender as InstantMessageModality);
            ConversationContainer  container = ActiveConversations[imm.Conversation];
            DateTime now     = DateTime.Now;
            String   convlog = "[" + now + "] (Conv. #" + container.m_convId + ") <" + imm.Participant.Contact.GetContactInformation(ContactInformationType.DisplayName) + ">";

            convlog += Environment.NewLine + args.Text;
            using (StreamWriter outfile = new StreamWriter(mydocpath + programFolder + @"\AllLyncIMHistory.txt", true))
            {
                outfile.WriteLine(convlog);
                outfile.Close();
            }
            foreach (Participant participant in container.Conversation.Participants)
            {
                if (participant.Contact == myself.Contact)
                {
                    continue;
                }
                String directory = mydocpath + programFolder + @"\" + participant.Contact.GetContactInformation(ContactInformationType.DisplayName);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string dateString = now.ToString("yyyy-MM-dd");
                String filename   = directory + @"\" + dateString + ".txt";
                //consoleWriteLine(filename);
                using (StreamWriter partfile = new StreamWriter(filename, true))
                {
                    partfile.WriteLine(convlog);
                    partfile.Close();
                }
            }

            consoleWriteLine(convlog);
        }
Exemple #33
0
        void _convServ_MessageRecived(string message, string participantName, InstantMessageModality instantMessageModality)
        {
            if (!cbxSendResponse.Checked)
                return;

            secondFire = !secondFire;
            if (secondFire)
                return;

            _instMsgMod = instantMessageModality;

            switch (messageIndex)
            {
                case 0:
                    Thread tMsg1 = new Thread(sndMsg1);
                    tMsg1.Start();
                    messageIndex++;
                    break;
                case 1:
                    Thread tMsg2 = new Thread(sndMsg2);
                    tMsg2.Start();
                    messageIndex++;
                    break;
                default:
                    //unsubscribe, we don't want to let them figure out its a bot
                    _convServ.MessageRecived -= _convServ_MessageRecived;
                    break;
            }
        }