/// <summary>
        /// For each specified sahred mailbox, if the user has access to the mailbox, 
        /// items matching the search term are sought-out. Each of the specified folders in the user's personal mailbox are also searched.
        /// </summary>
        /// <param name="credentials">The user credntials to impersonate in the mail system.</param>
        /// <param name="sharedMailBoxNames">The names of the shared mailboxes to search.</param>
        /// <param name="mailFolderNames">The names of the folders in the user's personal mail box to search.</param>
        /// <param name="searchTerm">The term that results must contain. This is case insensitive.</param>
        /// <returns>Mail items that match the search term or an empty result (i.e. never null).</returns>
        public IEnumerable<MailItem> FindItems(MailBoxCredentials credentials,
            MailSearchContainerNameList sharedMailBoxNames,
            MailSearchContainerNameList mailFolderNames,
            string searchTerm)
        {
            if (credentials == null
                || String.IsNullOrEmpty(credentials.UserName))
            {
                throw new UnauthorizedAccessException("No user to impersonate specified.");
            }

            var result = new List<MailItem>();
            if (String.IsNullOrEmpty(searchTerm)
                || ((sharedMailBoxNames == null
                     || sharedMailBoxNames.Count <= 0)
                    && (mailFolderNames == null
                     || mailFolderNames.Count <= 0)))
            {
                return result;
            }

            var ewsURL = configuration.EWSURL;
            var networkDomain = configuration.EWSNetworkDomain;
            var networkUserName = configuration.EWSNetworkUserName;
            var networkPassword = configuration.EWSNetworkPassword;
            var mailDomain = configuration.MailDomain;
            var searchFilters = new Microsoft.Exchange.WebServices.Data.SearchFilter.SearchFilterCollection (LogicalOperator.Or,
                    new SearchFilter[5]{new SearchFilter.ContainsSubstring(EmailMessageSchema.Body, searchTerm),
                                        new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, searchTerm),
                                        new SearchFilter.ContainsSubstring(EmailMessageSchema.Sender, searchTerm),
                                        new SearchFilter.ContainsSubstring(EmailMessageSchema.ToRecipients, searchTerm),
                                        new SearchFilter.ContainsSubstring(EmailMessageSchema.Attachments, searchTerm)
                                        });
            var service = ConfigureMSExchangeService(networkUserName,
                                                     networkPassword,
                                                     networkDomain,
                                                     ewsURL,
                                                     credentials);
            var iv = new ItemView(VIEW_SIZE);
            iv.PropertySet = new PropertySet(BasePropertySet.IdOnly,
                                            ItemSchema.Subject,
                                            ItemSchema.DateTimeReceived);

            var shareMailBoxMatches = SearchSharedMailBoxes(service,
                                                            iv,
                                                            searchFilters,
                                                            sharedMailBoxNames,
                                                            configuration.MailDomain,
                                                            searchTerm);
            if (sharedMailBoxNames != null) result.AddRange(shareMailBoxMatches);
            var mailFolderMatches = SearchMailFolders(service,
                                                     iv,
                                                     searchFilters,
                                                     mailFolderNames,
                                                     searchTerm);
            if (mailFolderMatches != null) result.AddRange(mailFolderMatches);

            return result;
        }
 public void TestHandlesNoPersonalMailFolders()
 {
     var credentials = new MailBoxCredentials
     {
         UserName = "******",
         DomainName = "entemea.google.com"
     };
     var sharedMailBoxes = new MailSearchContainerNameList(new string[1] { "" });
     _target.FindItems(credentials, sharedMailBoxes, null, null);
 }
 public void TestHandlesNoSearchTerm()
 {
     var credentials = new MailBoxCredentials
     {
         UserName = "******",
         DomainName = "entemea.google.com"
     };
     var sharedMailBoxes = new MailSearchContainerNameList(new string[2] { "sharedmailbox", "ghdsharedtest" });
     var personalMailFolders = new MailSearchContainerNameList(new string[1] { "InBox" });
     _target.FindItems(credentials, sharedMailBoxes, personalMailFolders, null);
 }
        private List<MailItem> SearchSubFolders(ExchangeService service,
            WellKnownFolderName parentFolder,
            MailSearchContainerNameList subFolderNames,
            string mailBoxName,
            SearchFilter.SearchFilterCollection searchFilters)
        {
            var result = new List<MailItem>();
            try
            {
                var subFolders = FindSubFolders(service,
                                                parentFolder,
                                                subFolderNames);
                if (subFolders == null || subFolders.Count() <= 0) return result;
                var itemView = new ItemView(VIEW_SIZE);
                itemView.PropertySet = new PropertySet {ItemSchema.Id,
                                                        ItemSchema.HasAttachments,
                                                        ItemSchema.Subject,
                                                        ItemSchema.Body};
                foreach (var subFolder in subFolders)
                {
                    var matches = service.FindItems(subFolder.Id, searchFilters, itemView);
                    AddItems(service, matches, result,mailBoxName,subFolder.DisplayName);
                }

            }
            catch (Exception ex)
            {
                //Ignore
                Debug.WriteLine(string.Format("Error encountered searching subfolders: {0}\n {1}", ex.ToString(), ex.StackTrace.ToString()));
            }
            return result;
        }
        private List<MailItem> SearchSharedMailBoxes(ExchangeService service,                    
            ItemView view,
            SearchFilter.SearchFilterCollection searchFilters,
            MailSearchContainerNameList mailBoxNames,
            string mailDomain,
            string searchTerm)
        {
            var result = new List<MailItem>();
            if (mailBoxNames == null
                || mailBoxNames.Count <= 0 ) return result;

            foreach (var mailBoxName in mailBoxNames)
            {
                try
                {
                    var fullyQualifiedMailboxName = String.Format("{0}@{1}", mailBoxName, mailDomain);
                    Mailbox mb = new Mailbox(fullyQualifiedMailboxName);
                    FolderId fid1 = new FolderId(WellKnownFolderName.Inbox, mb);
                    var rootFolder = Folder.Bind(service, fid1);
                    var items = rootFolder.FindItems(view);
                    service.LoadPropertiesForItems(items, new PropertySet { ItemSchema.Attachments, ItemSchema.HasAttachments });
                    var matches = service.FindItems(fid1, searchFilters, view);
                    AddItems(service, matches, result, fullyQualifiedMailboxName, "InBox");
                }
                catch (ServiceResponseException)
                {
                    //Ignore this indicates the user has no access to the mail box.
                    Debug.WriteLine(String.Format("Trouble accessing mailbox {0} assuming no access.", mailBoxName));
                }
            }
            return result;
        }
        private List<MailItem> SearchMailFolders(ExchangeService service,
            ItemView view,
            SearchFilter.SearchFilterCollection searchFilters,
            MailSearchContainerNameList mailFolderNames,
            string searchTerm)
        {
            var result = new List<MailItem>();
            if (mailFolderNames == null
                || mailFolderNames.Count <= 0) return result;

            var personalFolderMatches = SearchSubFolders(service,
                                                         WellKnownFolderName.MsgFolderRoot,
                                                         mailFolderNames,
                                                         "personal mailbox",
                                                         searchFilters);
            var publicFolderMatches = SearchSubFolders(service,
                                                         WellKnownFolderName.MsgFolderRoot,
                                                         mailFolderNames,
                                                         "public folders",
                                                         searchFilters);

            if (personalFolderMatches != null) result.AddRange(personalFolderMatches);
            if (publicFolderMatches != null) result.AddRange(publicFolderMatches);

            return result;
        }
 private FindFoldersResults FindSubFolders(ExchangeService service,
     WellKnownFolderName parentFolder,
     MailSearchContainerNameList subFolderNames)
 {
     var folderView = new FolderView(VIEW_SIZE);
     folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly, new PropertySet { FolderSchema.DisplayName, FolderSchema.Id });
     Folder rootFolder = Folder.Bind(service, parentFolder);
     var searchFilters = new List<SearchFilter>();
     foreach (var subfolderName in subFolderNames)
     {
         searchFilters.Add(new SearchFilter.ContainsSubstring(FolderSchema.DisplayName,subfolderName));
     }
     var searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilters);
     return rootFolder.FindFolders(searchFilterCollection, folderView);
 }
        private MailSearchContainerNameList GetSharedMailBoxes()
        {
            var result = new MailSearchContainerNameList();
            var domain = configuration.MailDomain;

            if (configuration.SharedMailBoxes == null) return result;
            var en = configuration.SharedMailBoxes.GetEnumerator();
            while (en.MoveNext())
            {
                var mailBox = en.Current as MailBoxConfigurationElement;
                if (mailBox == null) continue;
                result.Add(String.Concat(mailBox.Name,"@", domain));
            }
            return result;
        }
 public void TestSearchesSharedMailBoxes()
 {
     var credentials = new MailBoxCredentials
     {
         UserName = "******",
         DomainName = "entemea.google.com"
     };
     var searchTerm = "test";
     var sharedMailBoxes = new MailSearchContainerNameList(new string[2] { "sharedmailbox", "ghdsharedtest" });
     _target.FindItems(credentials, sharedMailBoxes, null, searchTerm);
 }
 public void TestSearchesMailFolders()
 {
     var credentials = new MailBoxCredentials
     {
         UserName = "******",
         DomainName = "entemea.google.com"
     };
     var searchTerm = "test";
     MailSearchContainerNameList sharedMailBoxes = null;
     var mailFolderNames = new MailSearchContainerNameList(new string[1] { "Inbox" });
     _target.FindItems(credentials, sharedMailBoxes, mailFolderNames, searchTerm);
 }