如何使用 Exchange Web 服务 (EWS) 检索全局联系人?

发布于 2024-08-20 22:45:09 字数 1050 浏览 4 评论 0原文

我正在使用 EWS,希望从该公司的交易所获取全球地址列表。我知道如何检索个人联系人列表。

API 文档中的所有示例都涉及更新用户信息,但没有具体说明如何检索它们。

我什至尝试了以下方法来列出文件夹,但它没有产生正确的结果。

private static void ListFolder(ExchangeService svc, FolderId parent, int depth) {
    string s;
    foreach (var v in svc.FindFolders(parent, new FolderView(int.MaxValue))) {
        Folder f = v as Folder;
        if (f != null) {
            s = String.Format("[{0}]", f.DisplayName);
            Console.WriteLine(s.PadLeft(s.Length + (depth * 2)));
            ListFolder(svc, f.Id, depth + 1);

            try {
                foreach (Item i in f.FindItems(new ItemView(20))) {
                    Console.WriteLine(
                        i.Subject.PadLeft(i.Subject.Length + ((depth + 1) * 2)));
                }
            } catch (Exception) {
            }
        }
    }
}

虽然问题已经提出(如何获取联系人列表来自 Exchange Server?)此问题专门涉及使用 EWS 获取全局地址列表,而此问题则寻求一般级别的建议。

I am using EWS and wish to obtain the global address list from exchange for the company. I know how to retrieve the personal contact list.

All the samples in the API documentation deal with updating user information but not specifically how to retrieve them.

I've even tried the following to list the folders but it doesn't yeild the correct results.

private static void ListFolder(ExchangeService svc, FolderId parent, int depth) {
    string s;
    foreach (var v in svc.FindFolders(parent, new FolderView(int.MaxValue))) {
        Folder f = v as Folder;
        if (f != null) {
            s = String.Format("[{0}]", f.DisplayName);
            Console.WriteLine(s.PadLeft(s.Length + (depth * 2)));
            ListFolder(svc, f.Id, depth + 1);

            try {
                foreach (Item i in f.FindItems(new ItemView(20))) {
                    Console.WriteLine(
                        i.Subject.PadLeft(i.Subject.Length + ((depth + 1) * 2)));
                }
            } catch (Exception) {
            }
        }
    }
}

While the question has already been raised (How to get contact list from Exchange Server?) this question deals specifically with using EWS to get the global address list while this question asks for advice on a general level.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦纸 2024-08-27 22:45:09

您可以使用下面的代码片段在指定文件夹中获取 ItemType 对象
然后将 ItemType 对象转换为 ContactItemType (对于联系人对象)...

/// <summary>
    /// gets list of ItemType objects with maxreturncriteria specicification
    /// </summary>
    /// <param name="esb">ExchangeServiceBinding object</param>
    /// <param name="folder">FolderIdType to get items inside</param>
    /// <param name="maxEntriesReturned">the max count of items to return</param>
    public static List<ItemType> FindItems(ExchangeServiceBinding esb, FolderIdType folder, int maxEntriesReturned)
    {
        List<ItemType> returnItems = new List<ItemType>();
        // Form the FindItem request 
        FindItemType request = new FindItemType();
        request.Traversal = ItemQueryTraversalType.Shallow;
        request.ItemShape = new ItemResponseShapeType();
        request.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
        request.ParentFolderIds = new FolderIdType[] { folder };
        IndexedPageViewType indexedPageView = new IndexedPageViewType();
        indexedPageView.BasePoint = IndexBasePointType.Beginning;
        indexedPageView.Offset = 0;
        indexedPageView.MaxEntriesReturned = 100;
        indexedPageView.MaxEntriesReturnedSpecified = true;
        request.Item = indexedPageView;
        FindItemResponseType response = esb.FindItem(request);
        foreach (FindItemResponseMessageType firmtMessage in response.ResponseMessages.Items)
        {
            if (firmtMessage.ResponseClass == ResponseClassType.Success)
            {
                if (firmtMessage.RootFolder.TotalItemsInView > 0)
                    foreach (ItemType item in ((ArrayOfRealItemsType)firmtMessage.RootFolder.Item).Items)
                        returnItems.Add(item);
                        //Console.WriteLine(item.GetType().Name + ": " + item.Subject + ", " + item.DateTimeReceived.Date.ToString("dd/MM/yyyy"));
            }
            else
            {
             //handle error log  here
            }
        }
        return returnItems;
    }

you may got ItemType objects in a specifiedfolder with the code snippet below
and then cast ItemType objects to ContactItemType (for contact objects) ....

/// <summary>
    /// gets list of ItemType objects with maxreturncriteria specicification
    /// </summary>
    /// <param name="esb">ExchangeServiceBinding object</param>
    /// <param name="folder">FolderIdType to get items inside</param>
    /// <param name="maxEntriesReturned">the max count of items to return</param>
    public static List<ItemType> FindItems(ExchangeServiceBinding esb, FolderIdType folder, int maxEntriesReturned)
    {
        List<ItemType> returnItems = new List<ItemType>();
        // Form the FindItem request 
        FindItemType request = new FindItemType();
        request.Traversal = ItemQueryTraversalType.Shallow;
        request.ItemShape = new ItemResponseShapeType();
        request.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
        request.ParentFolderIds = new FolderIdType[] { folder };
        IndexedPageViewType indexedPageView = new IndexedPageViewType();
        indexedPageView.BasePoint = IndexBasePointType.Beginning;
        indexedPageView.Offset = 0;
        indexedPageView.MaxEntriesReturned = 100;
        indexedPageView.MaxEntriesReturnedSpecified = true;
        request.Item = indexedPageView;
        FindItemResponseType response = esb.FindItem(request);
        foreach (FindItemResponseMessageType firmtMessage in response.ResponseMessages.Items)
        {
            if (firmtMessage.ResponseClass == ResponseClassType.Success)
            {
                if (firmtMessage.RootFolder.TotalItemsInView > 0)
                    foreach (ItemType item in ((ArrayOfRealItemsType)firmtMessage.RootFolder.Item).Items)
                        returnItems.Add(item);
                        //Console.WriteLine(item.GetType().Name + ": " + item.Subject + ", " + item.DateTimeReceived.Date.ToString("dd/MM/yyyy"));
            }
            else
            {
             //handle error log  here
            }
        }
        return returnItems;
    }
暗地喜欢 2024-08-27 22:45:09

我刚刚做了一件类似的事情。但是,我无法通过 Exchange 获取联系人列表,因为这只获取拥有邮箱的用户,而不一定是所有用户或组。我最终通过 AD 获取了所有用户,

这里是获取 AD 中所有联系人的代码。您所需要的只是全局地址列表的folderID,可以通过在AD 服务器上使用ADSI.msc 工具并浏览到全局地址列表文件夹来获取该文件夹ID,查看属性并获取“声称的搜索”的值。在我的系统中,全局地址列表的搜索路径是“(&(objectClass=user)(objectCategory=person)(mailNickname=)(msExchHomeServerName=))”

 public List<ListItem> SearchAD(string keyword, XmlDocument valueXml)
    {           
        List<ListItem> ewsItems = new List<ListItem>();

        using (DirectoryEntry ad = Utils.GetNewDirectoryEntry("LDAP://yourdomain.com"))
        {
            Trace.Info("searcherをつくる");
            using (DirectorySearcher searcher = new DirectorySearcher(ad))
            {
                if (this.EnableSizeLimit)
                {         
                    searcher.SizeLimit = GetMaxResultCount();

                    if (Utils.maxResultsCount > 1000)
                    {
                        searcher.PageSize = 100;
                    }
                }
                else
                {
                    searcher.SizeLimit = 1000;
                    searcher.PageSize = 10;
                }

                string sisya = Utils.DecodeXml(valueXml.SelectSingleNode("Folder/SearchPath").InnerText);  //this is the folder to grab your contacts from.  In your case Global Address list

                //Container
                if(String.IsNullOrEmpty(sisya))
                {
                    return null;
                }

                keyword = Utils.EncodeLdap(keyword);

                string text = Utils.DecodeXml(valueXml.SelectSingleNode("Folder/Text").InnerText);

                searcher.Filter = this.CreateFilter(keyword, sisya);
                searcher.Sort = new SortOption("DisplayName", System.DirectoryServices.SortDirection.Ascending);

                //一つのPropertyをロードすると、全Propertyを取らないようになる
                searcher.PropertiesToLoad.Add("SAMAccountName"); //どのPropertyでもいい。


                SearchResultCollection searchResults = searcher.FindAll();



                foreach (SearchResult searchResult in searchResults)
                {
                    //ListItem contact = null;
                    using (DirectoryEntry userEntry = searchResult.GetDirectoryEntry())
                    {
                        try
                        {
                            string schemaClassName = userEntry.SchemaClassName;
                            switch (schemaClassName)
                            {
                                case "user":
                                case "contact":
                                    string fname = userEntry.Properties["GivenName"].Value == null ? "" : userEntry.Properties["GivenName"].Value.ToString();
                                    string lname = userEntry.Properties["sn"].Value == null ? "" : userEntry.Properties["sn"].Value.ToString();
                                    string dname = userEntry.Properties["DisplayName"][0] == null ? lname + " " + fname : userEntry.Properties["DisplayName"][0].ToString();

                                    //No Mail address
                                    if ((userEntry.Properties["mail"] != null) && (userEntry.Properties["mail"].Count > 0))
                                    {


                                        string sAMAccountName = "";
                                        if(userEntry.Properties["SAMAccountName"].Value != null){
                                            sAMAccountName = userEntry.Properties["SAMAccountName"].Value.ToString();
                                        }
                                        else{
                                            sAMAccountName = userEntry.Properties["cn"].Value.ToString();
                                        }
                                        string contactXml = Utils.ListViewXml(sAMAccountName, UserType.User, Utils.UserXml(fname, lname, userEntry.Properties["mail"].Value.ToString(), dname, null), ServerType.Ad);
                                        ewsItems.Add(new ListItem(dname + "<" + userEntry.Properties["mail"].Value.ToString() + ">", contactXml));
                                    }
                                    else
                                    {
                                        ListItem contact = new ListItem(dname, null);
                                        contact.Enabled = false;

                                        ewsItems.Add(contact);

                                        Trace.Info("追加できないユーザ: " + searchResult.Path);
                                    }
                                    break;
                                case "group":
                                    ewsItems.Add(new ListItem(userEntry.Properties["DisplayName"].Value.ToString(), Utils.ListViewXml(userEntry.Properties["SAMAccountName"].Value.ToString(), UserType.Group, null, ServerType.Ad)));
                                    break;
                                default:
                                   userEntry.Properties["SAMAccountName"].Value.ToString());
                                    ewsItems.Add(new ListItem(userEntry.Properties["name"].Value.ToString(), Utils.ListViewXml(userEntry.Properties["SAMAccountName"].Value.ToString(), UserType.Group, null, ServerType.Ad)));
                                    break;

                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Error("User data取得失敗", ex);
                        }
                    }
                }

                searchResults.Dispose();

            }
        }       
        return ewsItems;
    }

I just did a similiar thing. However, I was unable to get the list of contacts via Exchange since that only gets users that have mailboxes, and not necessarily all users or groups. I eventually ended up getting all the users via AD

here is code to get all the contacts in AD. All you need is the folderID of the global address list which can be gotten from using the ADSI.msc tool on your AD server and browsing to the Global address list folder, look at properties and grab the value of the "purported search". In my system the searchPath for the global address list is"(&(objectClass=user)(objectCategory=person)(mailNickname=)(msExchHomeServerName=))"

 public List<ListItem> SearchAD(string keyword, XmlDocument valueXml)
    {           
        List<ListItem> ewsItems = new List<ListItem>();

        using (DirectoryEntry ad = Utils.GetNewDirectoryEntry("LDAP://yourdomain.com"))
        {
            Trace.Info("searcherをつくる");
            using (DirectorySearcher searcher = new DirectorySearcher(ad))
            {
                if (this.EnableSizeLimit)
                {         
                    searcher.SizeLimit = GetMaxResultCount();

                    if (Utils.maxResultsCount > 1000)
                    {
                        searcher.PageSize = 100;
                    }
                }
                else
                {
                    searcher.SizeLimit = 1000;
                    searcher.PageSize = 10;
                }

                string sisya = Utils.DecodeXml(valueXml.SelectSingleNode("Folder/SearchPath").InnerText);  //this is the folder to grab your contacts from.  In your case Global Address list

                //Container
                if(String.IsNullOrEmpty(sisya))
                {
                    return null;
                }

                keyword = Utils.EncodeLdap(keyword);

                string text = Utils.DecodeXml(valueXml.SelectSingleNode("Folder/Text").InnerText);

                searcher.Filter = this.CreateFilter(keyword, sisya);
                searcher.Sort = new SortOption("DisplayName", System.DirectoryServices.SortDirection.Ascending);

                //一つのPropertyをロードすると、全Propertyを取らないようになる
                searcher.PropertiesToLoad.Add("SAMAccountName"); //どのPropertyでもいい。


                SearchResultCollection searchResults = searcher.FindAll();



                foreach (SearchResult searchResult in searchResults)
                {
                    //ListItem contact = null;
                    using (DirectoryEntry userEntry = searchResult.GetDirectoryEntry())
                    {
                        try
                        {
                            string schemaClassName = userEntry.SchemaClassName;
                            switch (schemaClassName)
                            {
                                case "user":
                                case "contact":
                                    string fname = userEntry.Properties["GivenName"].Value == null ? "" : userEntry.Properties["GivenName"].Value.ToString();
                                    string lname = userEntry.Properties["sn"].Value == null ? "" : userEntry.Properties["sn"].Value.ToString();
                                    string dname = userEntry.Properties["DisplayName"][0] == null ? lname + " " + fname : userEntry.Properties["DisplayName"][0].ToString();

                                    //No Mail address
                                    if ((userEntry.Properties["mail"] != null) && (userEntry.Properties["mail"].Count > 0))
                                    {


                                        string sAMAccountName = "";
                                        if(userEntry.Properties["SAMAccountName"].Value != null){
                                            sAMAccountName = userEntry.Properties["SAMAccountName"].Value.ToString();
                                        }
                                        else{
                                            sAMAccountName = userEntry.Properties["cn"].Value.ToString();
                                        }
                                        string contactXml = Utils.ListViewXml(sAMAccountName, UserType.User, Utils.UserXml(fname, lname, userEntry.Properties["mail"].Value.ToString(), dname, null), ServerType.Ad);
                                        ewsItems.Add(new ListItem(dname + "<" + userEntry.Properties["mail"].Value.ToString() + ">", contactXml));
                                    }
                                    else
                                    {
                                        ListItem contact = new ListItem(dname, null);
                                        contact.Enabled = false;

                                        ewsItems.Add(contact);

                                        Trace.Info("追加できないユーザ: " + searchResult.Path);
                                    }
                                    break;
                                case "group":
                                    ewsItems.Add(new ListItem(userEntry.Properties["DisplayName"].Value.ToString(), Utils.ListViewXml(userEntry.Properties["SAMAccountName"].Value.ToString(), UserType.Group, null, ServerType.Ad)));
                                    break;
                                default:
                                   userEntry.Properties["SAMAccountName"].Value.ToString());
                                    ewsItems.Add(new ListItem(userEntry.Properties["name"].Value.ToString(), Utils.ListViewXml(userEntry.Properties["SAMAccountName"].Value.ToString(), UserType.Group, null, ServerType.Ad)));
                                    break;

                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.Error("User data取得失敗", ex);
                        }
                    }
                }

                searchResults.Dispose();

            }
        }       
        return ewsItems;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文