Lync API: как отправить мгновенное сообщение контакту по адресу электронной почты?

У меня есть адрес электронной почты пользователя Lync, и я хочу отправить ему мгновенное сообщение.

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

Снимок экрана Проблемы LyncСсылка на большой снимок экрана: https://i.imgur.com/LMHEF.png

Как вы можете видеть на этом снимке экрана, моя программа на самом деле не работает, хотя я могу вручную найти контакт и отправить мгновенное сообщение.

Я также пытался использовать ContactManager.BeginSearch() вместо ContactManager.GetContactByUri(), но получил тот же результат (вы можете видеть на скриншоте): http://pastie.org/private/o9joyzvux4mkhzsjw1pioa


person Community    schedule 25.09.2012    source источник
comment
Я не вижу ничего, чтобы указать, почему это не работает, можете ли вы включить журналы отладки в lync (настройки на вкладке «Общие») и поместить вывод здесь   -  person Neo    schedule 26.09.2012
comment
@Neo pastie.org/private/igdb3rgsdjfmujyl2j7q   -  person    schedule 26.09.2012
comment
Тем временем я попытаюсь сравнить журнал успешной (вручную) попытки с журналом моей неудачной попытки C#.   -  person    schedule 26.09.2012
comment
Ну, там есть некоторые ошибки, которые ничего не значат для меня, но выглядят немного подозрительно, почему сообщение не отправляется, оно говорит, что не может соответствовать данным SIP или хосту (26.09.2012|20:26 :20.335 16E8:1488 ОШИБКА :: SIP_URL::InternalInitialize Не удалось найти хост при анализе URL-адреса SIP) Я бы сначала рассмотрел этот, поскольку он должен решить проблему.   -  person Neo    schedule 27.09.2012


Ответы (2)


Хорошо, теперь я заработал. Получил в рабочем состоянии, хотя мне нужно сделать серьезный рефакторинг.

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;
        }
    }
}
person Community    schedule 27.09.2012

Попробуйте ниже код, он работает нормально для меня

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);
}
person Akshay Bagi    schedule 05.07.2016