private static void GetAllFolders(Exchange.ExchangeService Service, string LogFilePath)
    {
        Exchange.ExtendedPropertyDefinition oIsHidden = default(Exchange.ExtendedPropertyDefinition);
        List <Exchange.Folder> oFolders = default(List <Exchange.Folder>);

        Exchange.FindFoldersResults oResults = default(Exchange.FindFoldersResults);
        bool lHasMore = false;

        Exchange.Folder     oChild = default(Exchange.Folder);
        Exchange.FolderView oView  = default(Exchange.FolderView);
        short         nPageSize    = 0;
        short         nOffSet      = 0;
        List <string> oPaths       = default(List <string>);
        List <string> oPath        = default(List <string>);

        oIsHidden = new Exchange.ExtendedPropertyDefinition(0x10f4, Exchange.MapiPropertyType.Boolean);
        nPageSize = 1000;
        oFolders  = new List <Exchange.Folder>();
        lHasMore  = true;
        nOffSet   = 0;
        while (lHasMore)
        {
            oView             = new Exchange.FolderView(nPageSize, nOffSet, Exchange.OffsetBasePoint.Beginning);
            oView.PropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);
            oView.PropertySet.Add(oIsHidden);
            oView.PropertySet.Add(Exchange.FolderSchema.ParentFolderId);
            oView.PropertySet.Add(Exchange.FolderSchema.DisplayName);
            oView.PropertySet.Add(Exchange.FolderSchema.FolderClass);
            oView.PropertySet.Add(Exchange.FolderSchema.TotalCount);
            oView.Traversal = Exchange.FolderTraversal.Deep;
            oResults        = Service.FindFolders(Exchange.WellKnownFolderName.MsgFolderRoot, oView);
            oFolders.AddRange(oResults.Folders);
            lHasMore = oResults.MoreAvailable;
            if (lHasMore)
            {
                nOffSet += nPageSize;
            }
        }
        oFolders.RemoveAll(Folder => Folder.ExtendedProperties(0).Value == true);
        oFolders.RemoveAll(Folder => Folder.FolderClass != "IPF.Note");
        oPaths = new List <string>();
        oFolders.ForEach(Folder =>
        {
            oChild = Folder;
            oPath  = new List <string>();
            do
            {
                oPath.Add(oChild.DisplayName);
                oChild = oFolders.SingleOrDefault(Parent => Parent.Id.UniqueId == oChild.ParentFolderId.UniqueId);
            } while (oChild != null);
            oPath.Reverse();
            oPaths.Add("{0}{1}{2}".ToFormat(Strings.Join(oPath.ToArray, DELIMITER), Constants.vbTab, Folder.TotalCount));
        });
        oPaths.RemoveAll(Path => Path.StartsWith("Sync Issues"));
        File.WriteAllText(LogFilePath, Strings.Join(oPaths.ToArray, Constants.vbCrLf));
    }
Example #2
0
        private CalendarFolder FindNamedCalendarFolder(string name)
        {
            Microsoft.Exchange.WebServices.Data.FolderView view = new Microsoft.Exchange.WebServices.Data.FolderView(100);
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.PropertySet.Add(FolderSchema.DisplayName);
            view.Traversal = FolderTraversal.Deep;

            SearchFilter sfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.FolderClass, "IPF.Appointment");

            FindFoldersResults findFolderResults = Service.FindFolders(WellKnownFolderName.Root, sfSearchFilter, view);

            return(findFolderResults.Where(f => f.DisplayName == name).Cast <CalendarFolder>().FirstOrDefault());
        }
        public ActionResult Index(int? page, string email, string name)
        {
            ExchangeService service = Connection.ConnectEWS();

            FolderView fv = new FolderView(50);
            SearchFilter folderSearch = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, email.ToLower());
            var findFoldersResults = service.FindFolders(WellKnownFolderName.Inbox, folderSearch, fv);
            Folder targetFolder = null;

            foreach (Folder folder in findFoldersResults)
            {
                if (folder.DisplayName.ToLower() == email.ToLower())
                {
                    targetFolder = folder;
                }
            }
            //Define ViewBag.email:
            ViewBag.email = email;
            ViewBag.emailnq = email.Split('@')[0];
            ViewBag.name = name;

            //Create empty list for all mailbox messages:
            var listing = new List<EmailMessage>();

            //Create ItemView with correct pagesize and offset:
            ItemView view = new ItemView(int.MaxValue, Connection.ExOffset, OffsetBasePoint.Beginning);

            view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties,
                EmailMessageSchema.Subject,
                EmailMessageSchema.DateTimeReceived,
                EmailMessageSchema.From
                );

            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);

            FindItemsResults<Item> findResults = service.FindItems(targetFolder.Id, view);

            //bool MoreItems = true;

            //while(MoreItems)
            //{
            foreach (EmailMessage it in findResults.Items)
            {
                listing.Add(it);
            }
            //}
            int pageSize = Connection.ExPageSize;
            int pageNumber = (page ?? 1);
            //return View(listing.ToPagedList<EmailMessage>(pageNumber, pageSize));
            return View(listing.ToList<EmailMessage>());
        }
        static void Main(string[] args)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            service.AutodiscoverUrl(UserPrincipal.Current.EmailAddress);
            Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);

            FolderView folderView = new FolderView(inbox.ChildFolderCount);
            folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName, FolderSchema.ChildFolderCount);

            foreach(Folder folder in inbox.FindFolders(folderView))
            {
                MarkAllAsRead(folder);
            }
        }
Example #5
0
        public List<Folder> GetChildFolder(Folder parentFolder)
        {
            const int pageSize = 100;
            int offset = 0;
            bool moreItems = true;
            List<Folder> result = new List<Folder>(parentFolder.ChildFolderCount);
            while (moreItems)
            {
                FolderView oView = new FolderView(pageSize, offset, OffsetBasePoint.Beginning);
                FindFoldersResults findResult = parentFolder.FindFolders(oView);
                result.AddRange(findResult.Folders);
                if (!findResult.MoreAvailable)
                    moreItems = false;

                if (moreItems)
                    offset += pageSize;
            }
            return result;
        }
Example #6
0
 /// <summary>
 /// In the specified directory <paramref name="folder"/> searches for all subdirectories
 /// that match the specified filter <paramref name="filter"/> and returns them to the collection <paramref name="list"/>.
 /// </summary>
 /// <param name="list">Filtered Exchange Server catalog collection.</param>
 /// <param name="folder">The directory from which the recursive search is performed.</param>
 /// <param name="filter">Search filter.</param>
 public static void GetAllFoldersByFilter(this List <Exchange.Folder> list, Exchange.Folder folder, Exchange.SearchFilter filter = null)
 {
     if (folder.ChildFolderCount > 0 && list != null)
     {
         Exchange.FindFoldersResults searchedFolders;
         var folderView = new Exchange.FolderView(folder.ChildFolderCount);
         if (filter != null)
         {
             searchedFolders = folder.FindFolders(filter, folderView);
         }
         else
         {
             searchedFolders = folder.FindFolders(folderView);
         }
         list.AddRange(searchedFolders);
         foreach (Exchange.Folder findFoldersResult in searchedFolders)
         {
             list.GetAllFoldersByFilter(findFoldersResult, filter);
         }
     }
 }
 static void MarkAllAsRead(Folder folder)
 {
     if (folder.ChildFolderCount == 0)
     {
         ItemView itemView = new ItemView(100);
         itemView.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.IsRead);
         SearchFilter filter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
         folder.FindItems(filter, itemView)
               .Cast<EmailMessage>()
               .ToList()
               .ForEach(item =>
         {
             item.IsRead = true;
             item.Update(ConflictResolutionMode.AutoResolve);
         });
     }
     else
     {
         FolderView folderView = new FolderView(folder.ChildFolderCount);
         folder.FindFolders(folderView).ToList().ForEach(child => MarkAllAsRead(child));
     }
 }
        /// <summary>
        /// Return the FolderID of a sub-folder within a given parent folder.
        /// </summary>
        /// <param name="WebService">Exchange Web Service instance to use</param>
        /// <param name="BaseFolderId">FolderID of the prent folder</param>
        /// <param name="FolderName">Name of the folder to find</param>
        /// <returns>FolderID of the matching folder (or null if not found)</returns>
        public static FolderId FindFolder(ExchangeService WebService, FolderId BaseFolderId, string FolderName)
        {
            // Retrieve a list of folders (paged by 10)
            FolderView folderView = new FolderView(10, 0);
            // Set base point of offset.
            folderView.OffsetBasePoint = OffsetBasePoint.Beginning;
            // Set the properties that will be loaded on returned items (display namme & folder ID)
            folderView.PropertySet = new PropertySet(FolderSchema.DisplayName, FolderSchema.Id);

            FindFoldersResults folderResults;
            do
            {
                // Get the folder at the base level.
                folderResults = WebService.FindFolders(BaseFolderId, folderView);

                // Iterate over the folders, until we find one that matches what we're looking for.
                foreach (Folder folder in folderResults)
                {
                    // Found it - return
                    if (String.Compare(folder.DisplayName, FolderName, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return folder.Id;
                    }
                }

                // If there's more folders, get them ...
                if (folderResults.NextPageOffset.HasValue)
                {
                    folderView.Offset = folderResults.NextPageOffset.Value;
                }
            }
            while (folderResults.MoreAvailable);

            // If we got here, we didn't find it, so return null.
            return null;
        }
Example #9
0
 /// <summary>
 /// In the specified directory <paramref name="folder"/> searches for all subdirectories
 /// that match the specified filter <paramref name="filter"/> with the corresponding class <paramref name="className"/>
 /// and returns them to the collection <paramref name="list"/>.
 /// </summary>
 /// <param name="list">Filtered Exchange Server catalog collection.</param>
 /// <param name="folder">The directory from which the recursive search is performed.</param>
 /// <param name="className">Class name for search.</param>
 /// <param name="filter">Search filter.</param>
 public static void GetAllFoldersByClass(this List <Exchange.Folder> list, Exchange.Folder folder, string className, Exchange.SearchFilter filter)
 {
     if (folder.ChildFolderCount > 0 && list != null)
     {
         Exchange.FindFoldersResults childFolders;
         var folderView = new Exchange.FolderView(folder.ChildFolderCount);
         if (filter == null)
         {
             childFolders = folder.FindFolders(folderView);
         }
         else
         {
             childFolders = folder.FindFolders(filter, folderView);
         }
         foreach (Exchange.Folder childFolder in childFolders)
         {
             if (childFolder.FolderClass == className)
             {
                 list.Add(childFolder);
             }
             list.GetAllFoldersByClass(childFolder, className, filter);
         }
     }
 }
        private static Folder GetSourceFolder(ExchangeService service, string email)
        {
            // Use the following search filter to get all mail in the Inbox with the word "extended" in the subject line.
            SearchFilter searchCriteria = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
                //Search for Folder DisplayName that matches mailbox email address:
                new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, email.ToLower()));
            FolderView fv = new FolderView(100);
            fv.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName, FolderSchema.TotalCount);

            // Find the search folder named "MailModder".
            FindFoldersResults findResults = service.FindFolders(
                WellKnownFolderName.Inbox,
                searchCriteria,
                fv);

            //Return root of inbox by default:
            //Folder returnFolder = Folder.Bind(service, WellKnownFolderName.Inbox);

            foreach (Folder searchFolder in findResults)
            {
                if (searchFolder.DisplayName.Contains(email.ToLower()))
                {
                    logger.Debug("Found source folder for email: " + email + ". Using folder: " + searchFolder.DisplayName + searchFolder.TotalCount);
                    return searchFolder;
                }
            }

            logger.Debug("Error getting commissioner source folder; returning global instead for: " + email);
            return GetGlobalFolder(service);
        }
Example #11
0
        public List<IFolderData> GetChildFolder(string parentFolderId)
        {
            const int pageSize = 100;
            int offset = 0;
            bool moreItems = true;
            List<IFolderData> result = new List<IFolderData>();

            var parentFolder = new FolderId(parentFolderId);
            //var parentFolderObj = Folder.Bind(CurrentExchangeService, parentFolder);
            // return GetChildFolder(parentFolderObj);
            while (moreItems)
            {
                FolderView oView = new FolderView(pageSize, offset, OffsetBasePoint.Beginning);
                oView.PropertySet = FolderPropertySet;
                FindFoldersResults findResult = _ewsOperator.FindFolders(parentFolder, oView);

                foreach(var folder in findResult.Folders)
                {
                    result.Add(DataConvert.Convert(folder, MailboxPrincipalAddress));
                }

                if (!findResult.MoreAvailable)
                    moreItems = false;

                if (moreItems)
                    offset += pageSize;
            }

            return result;
        }
Example #12
0
        /// <summary>
        /// Obtains a list of folders by searching the sub-folders of this folder. Calling this method results in a call to EWS.
        /// </summary>
        /// <param name="searchFilter">The search filter. Available search filter classes
        /// include SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
        /// SearchFilter.SearchFilterCollection</param>
        /// <param name="view">The view controlling the number of folders returned.</param>
        /// <returns>An object representing the results of the search operation.</returns>
        public FindFoldersResults FindFolders(SearchFilter searchFilter, FolderView view)
        {
            this.ThrowIfThisIsNew();

            return(this.Service.FindFolders(this.Id, searchFilter, view));
        }
Example #13
0
        /// <summary>
        /// Obtains a list of folders by searching the sub-folders of this folder. Calling this method results in a call to EWS.
        /// </summary>
        /// <param name="view">The view controlling the number of folders returned.</param>
        /// <returns>An object representing the results of the search operation.</returns>
        public FindFoldersResults FindFolders(FolderView view)
        {
            this.ThrowIfThisIsNew();

            return(this.Service.FindFolders(this.Id, view));
        }
Example #14
0
        private static bool TryGetFolder(string folderConfParam, out Folder folder)
        {
            try
            {
                FolderView view = new FolderView(int.MaxValue)
                {
                    PropertySet = new PropertySet(BasePropertySet.IdOnly) { FolderSchema.DisplayName },
                    Traversal = FolderTraversal.Deep
                };

                string folderName = Config.GetParam(folderConfParam);

                SearchFilter filter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, folderName);

                FindFoldersResults res = _service.FindFolders(WellKnownFolderName.Root, filter, view);

                if (res.TotalCount > 1)
                {
                    Logger.Error(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            LocalizibleStrings.FolderNotFound,
                            folderName,
                            folderConfParam));
                }
                else if (res.TotalCount < 1)
                {
                    Logger.Error(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            LocalizibleStrings.FolderNotFound,
                            folderName,
                            folderConfParam));
                    folder = null;
                    return false;
                }

                folder = res.Folders[0];
                return true;
            }
            catch (Exception exc)
            {
                Logger.Error(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizibleStrings.CannotGetTemplateFolder,
                        folderConfParam),
                    exc);
                folder = null;
                return false;
            }
        }
Example #15
0
        private Folder FindImHistoryFolder()
        {
            FolderView folderView = new FolderView(_pageSize, 0);
            folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            folderView.PropertySet.Add(FolderSchema.DisplayName);
            folderView.PropertySet.Add(FolderSchema.ChildFolderCount);

            folderView.Traversal = FolderTraversal.Shallow;
            Folder imHistoryFolder = null;

            FindFoldersResults findFolderResults;
            bool foundImHistoryFolder = false;
            do
            {
                findFolderResults = _exchangeService.FindFolders(WellKnownFolderName.MsgFolderRoot, folderView);
                foreach (Folder folder in findFolderResults)
                {
                    if (folder.DisplayName.ToLower() == "conversation history")
                    {
                        imHistoryFolder = folder;
                        foundImHistoryFolder = true;
                    }
                }
                folderView.Offset += _pageSize;
            } while (findFolderResults.MoreAvailable && !foundImHistoryFolder);

            if(!foundImHistoryFolder)
            {
                imHistoryFolder = new Folder(_exchangeService);
                imHistoryFolder.DisplayName = "Conversation History";
                imHistoryFolder.Save(WellKnownFolderName.MsgFolderRoot);
            }

            return imHistoryFolder;
        }
Example #16
0
        public FolderId FindFolder(IFolderDataBase folderData, FolderId parentFolderId, int findCount = 0)
        {
            FolderView view = new FolderView(1);
            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.Traversal = FolderTraversal.Shallow;
            SearchFilter filter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, folderData.DisplayName);
            FindFoldersResults results = CurrentExchangeService.FindFolders(parentFolderId, filter, view);

            if (results.TotalCount > 1)
            {
                throw new InvalidOperationException("Find more than 1 folder.");
            }
            else if (results.TotalCount == 0)
            {
                if (findCount > 3)
                {
                    return null;
                }
                Thread.Sleep(500);
                return FindFolder(folderData, parentFolderId, ++findCount);
            }
            else
            {
                foreach (var result in results)
                {
                    return result.Id;
                }
                throw new InvalidOperationException("Thread sleep time is too short.");
            }
        }
        /// <summary>
        /// This function gets the mail item by the extended property
        /// </summary>
        /// <param name="service"></param>
        /// <param name="folderId"></param>
        /// <param name="msgFolderRootId"></param>
        /// <param name="outlookMsgId"></param>
        /// <param name="isIn"></param>
        /// <returns></returns>
        public object GetMailItemByExtendedProperty(ref ExchangeService service, FolderId folderId,
            FolderId msgFolderRootId, string outlookMsgId, bool isIn)
        {
            EmailMessage message = null;
            //Folder view
            var viewFolders = new FolderView(int.MaxValue)
            {
                Traversal = FolderTraversal.Deep,
                PropertySet = new PropertySet(BasePropertySet.IdOnly)
            };
            //email view
            var viewEmails = new ItemView(int.MaxValue) { PropertySet = new PropertySet(BasePropertySet.IdOnly) };
            //email filter
            SearchFilter emailFilter =
                new SearchFilter.IsEqualTo(
                    isIn
                        ? MailboxExtendedPropertyDefinitionInbox
                        : MailboxExtendedPropertyDefinitionSent, outlookMsgId);
            //search item in default folder
            var findResults = service.FindItems(msgFolderRootId, emailFilter, viewEmails);
            //check
            if ((findResults != null) && findResults.TotalCount > 0 && findResults.FirstOrDefault() is EmailMessage)
            {
                //we found the email in default folder
                message = (EmailMessage)findResults.First();
            }
            else
            {
                //find in all folders
                var allFolders = service.FindFolders(msgFolderRootId, viewFolders);
                foreach (var folder in allFolders.Folders)
                {
                    //search
                    findResults = service.FindItems(folder.Id, emailFilter, viewEmails);

                    //check
                    if ((findResults != null) && findResults.TotalCount > 0 &&
                        findResults.FirstOrDefault() is EmailMessage)
                    {
                        //we found the email in somewhere 
                        message = (EmailMessage)findResults.First();
                        break;
                    }
                }
            }
            if (message != null)
            {
                //create property set and load necessary properties
                var propertySet = new PropertySet(EmailMessageSchema.ToRecipients, EmailMessageSchema.Sender,
                    ItemSchema.Subject, ItemSchema.Body,
                    ItemSchema.DateTimeReceived, ItemSchema.DateTimeSent, ItemSchema.HasAttachments,
                    ItemSchema.Attachments) { RequestedBodyType = BodyType.HTML };
                //load properties
                service.LoadPropertiesForItems(findResults, propertySet);
            }
            return message;
        }
        private FolderId getFolderId(string folderName)
        {
            // Create a view with a page size of 10.
            FolderView view = new FolderView(1);

            // Identify the properties to return in the results set.
            view.PropertySet = new PropertySet(FolderSchema.Id);
            view.PropertySet.Add(FolderSchema.DisplayName);

            // Return only folders that contain items.
            SearchFilter searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, folderName);

            // Unlike FindItem searches, folder searches can be deep traversals.
            view.Traversal = FolderTraversal.Deep;

            // Send the request to search the mailbox and get the results.
            FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Root, searchFilter, view);

            if (findFolderResults.TotalCount > 0)
            {
                return findFolderResults.Folders[0].Id;
            }

            return new FolderId(WellKnownFolderName.SentItems);
        }
        static void Main(string[] args)
        {
            Thread t = null;
            var reqType = new RequestType();
            try
                {
                if (args[0].Contains("poll"))
                    {
                    reqType = RequestType.Poll;
                    Console.WriteLine("\n\tTrying to connect to Exchange server.");
                    t = new Thread(ShowProgress);
                    t.Start();
                    }
                else if (args[0].Contains("send"))
                    reqType = RequestType.Send;
                else
                    {
                    Console.WriteLine("\n\tAccepted arguments are 'poll' or 'send'");
                    Environment.Exit(1);
                    }
                }
            catch
                {
                Console.WriteLine("\n\tYou have not provided any argument. Give either 'poll' or 'send' as argument.");
                Environment.Exit(1);
                }

            ExchangeService service = new ExchangeService();
            service.Credentials = new WebCredentials("<username>", "<password>", "<domain>");
            service.AutodiscoverUrl("<full email address>", RedirectionUrlValidationCallback);

            if (reqType == RequestType.Poll)
                {
                if (t != null)
                    t.Abort();
                Console.WriteLine("\n\n\tConnected. Polling for a matching email started. Hit Ctrl+C to quit.");
                while (true)
                    {
                    Thread.Sleep(10000);
                    FolderView folderView = new FolderView(int.MaxValue);
                    FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Inbox, folderView);
                    foreach (Folder folder in findFolderResults)
                        {

                        if (folder.DisplayName == "<Folder name>" && folder.UnreadCount > 0)
                            {
                            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                            ItemView view = new ItemView(1);

                            // Fire the query for the unread items.
                            // This method call results in a FindItem call to EWS.
                            FindItemsResults<Item> findResults = service.FindItems(folder.Id, sf, view);
                            var email = (EmailMessage)findResults.Items[0];

                            EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments));
                            mailFrom = message.From.Address;
                            //Console.WriteLine("Name:" + email.From.Name);
                            string subject = email.Subject;

                            Console.WriteLine("\n\tEmail received from : " + mailFrom + " with subject \"" + subject + " at " + DateTime.Now);

                            folder.MarkAllItemsAsRead(true);
                            //Perform the action you want. Example : Go to the desired URL
                            var client = new WebClient();
                            try{
                            client.OpenRead("http://google.com");
                            }
                            catch(Exception e){}
                            }
                        }
                    }
                }
            else if (reqType == RequestType.Send)
                {
                SendEmailWithReport(service, "<To email address>");
                }
        }
 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 TreeViewFolder LoadSubFolders(Folder f, TreeViewFolder subtree)
 {
     var view = new FolderView(100);
     view.Traversal = FolderTraversal.Shallow;
     var findFolderResults = f.FindFolders(view);
     foreach (var item in findFolderResults.Folders)
     {
         var childNode = new TreeViewFolder();
         childNode.Name = item.DisplayName;
         childNode.Id = item.Id.UniqueId;
         var fclass = item.FolderClass;
         if (fclass == null) fclass = "All";
         if (fclass == "IPF.Contact") fclass = "Contact";
         else if (fclass == "IPF.Appointment") fclass = "Appointment";
         else if (fclass == "IPF.Task") fclass = "Task";
         else fclass = "All";
         childNode.FolderClass = fclass;
         if (item.ChildFolderCount > 0)
         {
             subtree.ChildFolders.Add(LoadSubFolders(item, childNode));
         }
         else
         {
             subtree.ChildFolders.Add(childNode);
         }
     }
     return subtree;
 }
        public List<EWSCalendar> GetCalendarsAsync(int maxFoldersToRetrive, Dictionary<string, object> calendarSpecificData)
        {
            CheckCalendarSpecificData(calendarSpecificData);
            var serverSettings = GetBestSuitedExchangeServerData(ExchangeServerSettings.Domain,
                ExchangeServerSettings.EmailId, ExchangeServerSettings.Password,
                ExchangeServerSettings.UsingCorporateNetwork);
            var service = GetExchangeService(serverSettings);

            // Create a new folder view, and pass in the maximum number of folders to return.
            var view = new FolderView(1000);

            // Create an extended property definition for the PR_ATTR_HIDDEN property,
            // so that your results will indicate whether the folder is a hidden folder.
            var isHiddenProp = new ExtendedPropertyDefinition(0x10f4, MapiPropertyType.Boolean);

            // As a best practice, limit the properties returned to only those required.
            // In this case, return the folder ID, DisplayName, and the value of the isHiddenProp
            // extended property.
            view.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties, FolderSchema.DisplayName,
                isHiddenProp);

            // Indicate a Traversal value of Deep, so that all subfolders are retrieved.
            view.Traversal = FolderTraversal.Deep;

            // Call FindFolders to retrieve the folder hierarchy, starting with the MsgFolderRoot folder.
            // This method call results in a FindFolder call to EWS.
            var findFolderResults = service.FindFolders(WellKnownFolderName.MsgFolderRoot, view);

            var ewsCalendars = new List<EWSCalendar>();
            foreach (var searchFolder in findFolderResults.Folders)
            {
                GetCalendars(searchFolder, ewsCalendars, view);
            }
            return ewsCalendars;
        }
        private void GetCalendars(Folder searchFolder, List<EWSCalendar> ewsCalendars, FolderView view)
        {
            if (searchFolder == null)
            {
                return;
            }

            if (searchFolder.FolderClass == "IPF.Appointment")
            {
                //Add Calendar MAPIFolder to List
                ewsCalendars.Add(new EWSCalendar
                {
                    Name = searchFolder.DisplayName,
                    EntryId = searchFolder.Id.UniqueId,
                    StoreId = searchFolder.ParentFolderId.UniqueId
                });
                return;
            }

            //Walk through all subFolders in MAPIFolder
            foreach (var subFolder in searchFolder.FindFolders(view))
            {
                //Get Calendar MAPIFolders
                GetCalendars(subFolder, ewsCalendars, view);
            }
        }
        public static Folder GetGlobalFolder(ExchangeService service)
        {
            FolderView fv = new FolderView(50);
            fv.PropertySet = new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName, FolderSchema.TotalCount);
            SearchFilter folderSearch = new SearchFilter.ContainsSubstring(FolderSchema.DisplayName, Parameters.GlobalSearchFolder);
            var findFoldersResults = service.FindFolders(WellKnownFolderName.SearchFolders, folderSearch, fv);
            Folder targetFolder = new Folder(service);

            foreach (Folder folder in findFoldersResults)
            {
                if (folder.DisplayName.ToLower() == Parameters.GlobalSearchFolder.ToLower())
                {
                    targetFolder = folder;
                }
            }

            return targetFolder;
        }
        private TreeViewFolder LoadSubFolders(Folder f, TreeViewFolder subtree, bool addTopFolder)
        {
            var view = new FolderView(100);
            view.Traversal = FolderTraversal.Shallow;
            var findFolderResults = f.FindFolders(view);

            string typeClass = "Contact";

            if ((((CCFolder)Session["folderDetail"])) != null)
            {
                if ((((CCFolder)Session["folderDetail"]).Type) == 1) { typeClass = "Contact"; }
                else { typeClass = "Appointment"; }
            }

            if (addTopFolder)
            {
                var childNode = new TreeViewFolder();
                childNode.Name = f.DisplayName;
                childNode.Id = f.Id.UniqueId;
                var fclass = f.FolderClass;
                if (fclass == null) fclass = "All";
                if (fclass == "IPF.Contact") fclass = "Contact";
                else if (fclass == "IPF.Appointment") fclass = "Appointment";
                else if (fclass == "IPF.Task") fclass = "Task";
                else fclass = "All";
                childNode.FolderClass = fclass;
                subtree.ChildFolders.Add(childNode);
            }
            foreach (var item in findFolderResults.Folders)
            {
                var childNode = new TreeViewFolder();
                childNode.Name = item.DisplayName;
                childNode.Id = item.Id.UniqueId;
                var fclass = item.FolderClass;
                if (fclass == null) fclass = "All";
                if (fclass == "IPF.Contact") fclass = "Contact";
                else if (fclass == "IPF.Appointment") fclass = "Appointment";
                else if (fclass == "IPF.Task") fclass = "Task";
                else fclass = "All";
                childNode.FolderClass = fclass;
                if (item.ChildFolderCount > 0)
                {
                    if (typeClass == fclass)
                    {
                        subtree.ChildFolders.Add(LoadSubFolders(item, childNode, false));
                    }
                    else if (fclass == "All")
                    {
                        subtree.ChildFolders.Add(LoadSubFolders(item, childNode, false));
                    }
                }
                else
                {
                    if (typeClass == fclass)
                    {
                        subtree.ChildFolders.Add(childNode);
                    }
                }
            }
            return subtree;
        }
Example #26
0
        public List<Folder> GetChildFolder(string parentFolderId)
        {
            const int pageSize = 100;
            int offset = 0;
            bool moreItems = true;
            List<Folder> result = new List<Folder>();
            var parentFolder = new FolderId(parentFolderId);
            //var parentFolderObj = Folder.Bind(CurrentExchangeService, parentFolder);
            // return GetChildFolder(parentFolderObj);
            while (moreItems)
            {
                FolderView oView = new FolderView(pageSize, offset, OffsetBasePoint.Beginning);
                oView.PropertySet = FolderPropertySet;
                FindFoldersResults findResult = CurrentExchangeService.FindFolders(parentFolder, oView);
                result.AddRange(findResult.Folders);
                if (!findResult.MoreAvailable)
                    moreItems = false;

                if (moreItems)
                    offset += pageSize;
            }
            return result;
        }