2016-05-13 6 views
1

все, что мне нужно сделать, это получить все контакты из Microsoft Exchange. Я сделал некоторые исследования, и наилучшим возможным вариантом для меня должно быть использование EWS Managed API. Я использую Visual Studio и язык программирования C#.Как получить все контакты из Microsoft Exchange с помощью управляемого API EWS?

Я думаю, что я могу подключиться к учетной записи Office365, потому что я могу отправить сообщение в программе по конкретному электронному адресу. Но я не могу получить контакты.

Если я создаю контакт непосредственно в исходном коде, контакт будет создан в приложении Office365-> People. Но я не знаю, почему! Я думал, что работаю с Exchange.

Обобщить: Есть ли возможность как получить все контакты из Office365-> адми-> Exchange-> Acceptencers->Контакты?

Вот мой код:

class Program 
{ 
    static void Main(string[] args) 
    { 
     // connecting to my Exchange account 
     ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; 
     ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1); 
     service.Credentials = new WebCredentials("[email protected]", "password123"); 

     /* 
     // debugging 
     service.TraceEnabled = true; 
     service.TraceFlags = TraceFlags.All; 
     */ 

     service.AutodiscoverUrl("[email protected]test.com", RedirectionUrlValidationCallback); 

     // send a message works good 
     EmailMessage email = new EmailMessage(service); 
     email.ToRecipients.Add("[email protected]"); 
     email.Subject = "HelloWorld"; 
     email.Body = new MessageBody("Toto je testovaci mail"); 
     email.Send(); 

     // Create the contact creates a contact in Office365 -> People application..Don't know why there and not in Office365 -> Exchange 
     /*Contact contact = new Contact(service); 

     // Specify the name and how the contact should be filed. 
     contact.GivenName = "Brian"; 
     contact.MiddleName = "David"; 
     contact.Surname = "Johnson"; 
     contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName; 

     // Specify the company name. 
     contact.CompanyName = "Contoso"; 

     // Specify the business, home, and car phone numbers. 
     contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = "425-555-0110"; 
     contact.PhoneNumbers[PhoneNumberKey.HomePhone] = "425-555-0120"; 
     contact.PhoneNumbers[PhoneNumberKey.CarPhone] = "425-555-0130"; 

     // Specify two email addresses. 
     contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress("[email protected]"); 
     contact.EmailAddresses[EmailAddressKey.EmailAddress2] = new EmailAddress("[email protected]"); 

     // Specify two IM addresses. 
     contact.ImAddresses[ImAddressKey.ImAddress1] = "[email protected]"; 
     contact.ImAddresses[ImAddressKey.ImAddress2] = " [email protected]"; 

     // Specify the home address. 
     PhysicalAddressEntry paEntry1 = new PhysicalAddressEntry(); 
     paEntry1.Street = "123 Main Street"; 
     paEntry1.City = "Seattle"; 
     paEntry1.State = "WA"; 
     paEntry1.PostalCode = "11111"; 
     paEntry1.CountryOrRegion = "United States"; 
     contact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry1; 

     // Specify the business address. 
     PhysicalAddressEntry paEntry2 = new PhysicalAddressEntry(); 
     paEntry2.Street = "456 Corp Avenue"; 
     paEntry2.City = "Seattle"; 
     paEntry2.State = "WA"; 
     paEntry2.PostalCode = "11111"; 
     paEntry2.CountryOrRegion = "United States"; 
     contact.PhysicalAddresses[PhysicalAddressKey.Business] = paEntry2; 

     // Save the contact. 
     contact.Save(); 
     */ 


     // msdn.microsoft.com/en-us/library/office/jj220498(v=exchg.80).aspx 
     // Get the number of items in the Contacts folder. 
     ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts); 
     Console.WriteLine(contactsfolder.TotalCount); 

     // Set the number of items to the number of items in the Contacts folder or 50, whichever is smaller. 
     int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50; 

     // Instantiate the item view with the number of items to retrieve from the Contacts folder. 
     ItemView view = new ItemView(numItems); 

     // To keep the request smaller, request only the display name property. 
     view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName); 

     // Retrieve the items in the Contacts folder that have the properties that you selected. 
     FindItemsResults<Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view); 

     // Display the list of contacts. 
     foreach (Item item in contactItems) 
     { 
      if (item is Contact) 
      { 
       Contact contact1 = item as Contact; 
       Console.WriteLine(contact1.DisplayName); 
      } 
     } 

     Console.ReadLine(); 
    } // end of Main() method 
    /*===========================================================================================================*/ 

    private static bool CertificateValidationCallBack(
    object sender, 
    System.Security.Cryptography.X509Certificates.X509Certificate certificate, 
    System.Security.Cryptography.X509Certificates.X509Chain chain, 
    System.Net.Security.SslPolicyErrors sslPolicyErrors) 
    { 
     // If the certificate is a valid, signed certificate, return true. 
     if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None) 
     { 
      return true; 
     } 

     // If there are errors in the certificate chain, look at each error to determine the cause. 
     if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0) 
     { 
      if (chain != null && chain.ChainStatus != null) 
      { 
       foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus) 
       { 
        if ((certificate.Subject == certificate.Issuer) && 
         (status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot)) 
        { 
         // Self-signed certificates with an untrusted root are valid. 
         continue; 
        } 
        else 
        { 
         if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError) 
         { 
          // If there are any other errors in the certificate chain, the certificate is invalid, 
          // so the method returns false. 
          return false; 
         } 
        } 
       } 
      } 

      // When processing reaches this line, the only errors in the certificate chain are 
      // untrusted root errors for self-signed certificates. These certificates are valid 
      // for default Exchange server installations, so return true. 
      return true; 
     } 
     else 
     { 
      // In all other cases, return false. 
      return false; 
     } 
    } 

    private static bool RedirectionUrlValidationCallback(string redirectionUrl) 
    { 
     // The default for the validation callback is to reject the URL. 
     bool result = false; 

     Uri redirectionUri = new Uri(redirectionUrl); 

     // Validate the contents of the redirection URL. In this simple validation 
     // callback, the redirection URL is considered valid if it is using HTTPS 
     // to encrypt the authentication credentials. 
     if (redirectionUri.Scheme == "https") 
     { 
      result = true; 
     } 
     return result; 
    } 
} 

ответ

0

кажется, что вы уже делаете хорошую работу делает метод с FindItems().

Чтобы получить все контакты, которые вам нужно добавить, это SearchFilter, в этом случае я бы рекомендовал использовать фильтр Exists(), поскольку вы можете просто сказать «Найти все контакты с идентификатором».

Смотрите мой пример ниже, если вам нужен пример применения Полный Windows, дело с контактами увидеть мою GitHub страницу github.com/rojobo

Dim oFilter As New SearchFilter.Exists(ItemSchema.Id) 
    Dim oResults As FindItemsResults(Of Item) = Nothing 
    Dim oContact As Contact 

     Dim blnMoreAvailable As Boolean = True 
     Dim intSearchOffset As Integer = 0 
     Dim oView As New ItemView(conMaxChangesReturned, intSearchOffset, OffsetBasePoint.Beginning) 
     oView.PropertySet = BasePropertySet.IdOnly 

     Do While blnMoreAvailable 
      oResults = pService.FindItems(WellKnownFolderName.Contacts, oFilter, oView) 
      blnMoreAvailable = oResults.MoreAvailable 
      If Not IsNothing(oResults) AndAlso oResults.Items.Count > 0 Then 
       For Each oExchangeItem As Item In oResults.Items 
        Dim oExchangeContactId As ItemId = oExchangeItem.Id 
        //do something else 
       Next 
       If blnMoreAvailable Then oView.Offset = oView.Offset + conMaxChangesReturned 
      End If 
     Loop 
+1

Венгерская нотация жива! Я не видел этого более десяти лет. –

0
How to retrieve all contacts from Microsoft Exchange using EWS Managed API? 

Если ваш вопрос заключается в том, чтобы извлечь контактов Exchange используя EWS, вы уже сделали это.

Office365-> Люди - это правильное приложение для управления контактами Exchange. Если вы посмотрите URL-адрес приложения People, это похоже на https://outlook.office365.com/owa/?realm=xxxxxx#exsvurl=1&ll-cc=1033&modurl=2, owa является синонимом веб-приложения Outlook.

+0

Привет, Джеки, спасибо за ваш ответ. Мне нужно получить все контакты из https://outlook.office365.com/owa/?realm=xxxxxx&exsvurl=1&ll-cc=1033&modurl=2&path=/people –

+0

конкретно из ** Office365-> Люди-> Адресная книга **

+0

Да, код, который у вас уже есть, - это просто способ сделать это. – Jackie

Смежные вопросы