Lync API: How to send instant message to contact by email address?
Asked Answered
D

2

5

I have the email address of a Lync user and want to send him an instant message.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;


namespace Build_Server_Lync_Notifier
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: bsln.exe <uri> <message>");
                return;
            }

            LyncClient client = Microsoft.Lync.Model.LyncClient.GetClient();
            Contact contact = client.ContactManager.GetContactByUri(args[0]);

            Conversation conversation = client.ConversationManager.AddConversation();
            conversation.AddParticipant(contact);

            Dictionary<InstantMessageContentType, String> messages = new Dictionary<InstantMessageContentType, String>();
            messages.Add(InstantMessageContentType.PlainText, args[1]);

            InstantMessageModality m = (InstantMessageModality) conversation.Modalities[ModalityTypes.InstantMessage];
            m.BeginSendMessage(messages, null, messages);

            //Console.Read();
        }
    }
}

Screenshot Lync problems Link to large screenshot: https://i.sstatic.net/zTHej.png

As you can see in this screenshot, my program doesn't really seem to work, even though I'm able to manually search up the contact and send an instant message manually.

I also tried using ContactManager.BeginSearch() instead of ContactManager.GetContactByUri(), but got the same result (you can see in the screenshot): http://pastie.org/private/o9joyzvux4mkhzsjw1pioa

Deaver answered 25/9, 2012 at 10:30 Comment(4)
I can't see anything to state why it is not working, can you enable debug logs in lync (settings under general "tab") and put the output herePerreira
@Perreira pastie.org/private/igdb3rgsdjfmujyl2j7qDeaver
I will try to compare the log from a successful (manual) attempt with the log from my C# failed attempt in the mean time.Deaver
Well there are some errors there that mean nothing to me but look a little suspicious as for why the message isn't sending, it is saying it can't match the SIP data or the host (09/26/2012|20:26:20.335 16E8:1488 ERROR :: SIP_URL::InternalInitialize Didn't find host while parsing SIP URL) I'd look into this one first as this should resolve the issue.Perreira
D
6

Ok, so I got it working now. Got it in a working state, although I need to do some serious refactoring.

Program.cs

using System;

namespace Build_Server_Lync_Notifier
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: bsln.exe <uri> <message>");
                return;
            }

            LyncManager lm = new LyncManager(args[0], args[1]);

            while (!lm.Done) 
            {
                System.Threading.Thread.Sleep(500);
            }
        }
    }
}

LyncManager.cs

using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using System;
using System.Collections.Generic;

namespace Build_Server_Lync_Notifier
{
    class LyncManager
    {
        private string _uri;
        private string _message;
        private LyncClient _client;
        private Conversation _conversation;

        private bool _done = false;
        public bool Done
        {
            get { return _done; }
        }

        public LyncManager(string arg0, string arg1)
        {
            _uri = arg0;
            _message = arg1;
            _client = Microsoft.Lync.Model.LyncClient.GetClient();
            _client.ContactManager.BeginSearch(
                _uri,
                SearchProviders.GlobalAddressList,
                SearchFields.EmailAddresses,
                SearchOptions.ContactsOnly,
                2,
                BeginSearchCallback,
                new object[] { _client.ContactManager, _uri }
            );
        }

        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);
        }

        private void BeginSendMessageCallback(IAsyncResult r)
        {
            _conversation.End();
            _done = true;
        }
    }
}
Deaver answered 27/9, 2012 at 10:17 Comment(0)
P
3

Try Below Code its working Fine For me

protected void Page_Load(object sender, EventArgs e)
{ 
   SendLyncMessage();
}
private static void SendLyncMessage()
{
  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);
}
Pectin answered 5/7, 2016 at 12:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.