public override void Initialise(List <MailFolder> folderList) { Status = MessageProcessorStatus.Initialising; _mainFolderList = folderList; service = ExchangeHelper.ExchangeConnect(_hostname, _username, _password); //service.TraceEnabled = true; //service.TraceFlags = TraceFlags.All; folders = new List <ExchangeFolder>(); ExchangeHelper.GetAllSubFolders(service, new ExchangeFolder { Folder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot) }, folders, false); if (_createAllFolders) { // we need to create all folders which don't exist foreach (var mailFolder in _mainFolderList) { GetCreateFolder(mailFolder.DestinationFolder); } } _lastState = new ImportState(); _queue = new PCQueue <RawMessageDescriptor, ImportState>(Name + "-exchangeTarget") { ProduceMethod = ProcessMessage, InitialiseProducer = () => _lastState, ShutdownProducer = ShutdownQueue }; _queue.Start(); Status = MessageProcessorStatus.Initialised; }
public List <ExchangeMailFolder> GetMailboxFolders(string mailServerId, string mailboxName, string mailboxPassword, string senderEmailAddress, string folderClassName) { if (string.IsNullOrEmpty(mailboxPassword)) { mailboxPassword = GetExistingMailboxPassword(senderEmailAddress, UserConnection); } var credentials = new Mail.Credentials { UserName = mailboxName, UserPassword = mailboxPassword, ServerId = Guid.Parse(mailServerId), UseOAuth = GetSettingsHasOauth(senderEmailAddress, UserConnection) }; SetServerCertificateValidation(); var exchangeUtility = new ExchangeUtilityImpl(); Exchange.ExchangeService service = exchangeUtility.CreateExchangeService(UserConnection, credentials, senderEmailAddress, true); var filterCollection = new Exchange.SearchFilter.SearchFilterCollection(Exchange.LogicalOperator.Or); var filter = new Exchange.SearchFilter.IsEqualTo(Exchange.FolderSchema.FolderClass, folderClassName); var nullfilter = new Exchange.SearchFilter.Exists(Exchange.FolderSchema.FolderClass); filterCollection.Add(filter); filterCollection.Add(new Exchange.SearchFilter.Not(nullfilter)); string[] selectedFolders = null; var idPropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly); Exchange.Folder draftFolder = null; if (folderClassName == ExchangeConsts.NoteFolderClassName) { Exchange.Folder inboxFolder = Exchange.Folder.Bind(service, Exchange.WellKnownFolderName.Inbox, idPropertySet); if (inboxFolder != null) { selectedFolders = new[] { inboxFolder.Id.UniqueId }; } draftFolder = Exchange.Folder.Bind(service, Exchange.WellKnownFolderName.Drafts, idPropertySet); } List <ExchangeMailFolder> folders = exchangeUtility.GetHierarhicalFolderList(service, Exchange.WellKnownFolderName.MsgFolderRoot, filterCollection, selectedFolders); if (folders != null && folders.Any()) { folders[0] = new ExchangeMailFolder { Id = folders[0].Id, Name = mailboxName, ParentId = string.Empty, Path = string.Empty, Selected = false }; if (draftFolder != null) { folders.Remove(folders.FirstOrDefault(e => e.Path == draftFolder.Id.UniqueId)); } } return(folders); }
/// <summary> /// In the specified directory <paramref name="folder"/>, finds all items <see cref="Exchange.Item"/>, /// that match the filter <paramref name="filter"/>, and returns them collection. In the object /// <paramref name="view"/> fixed number of read items in the catalog. /// </summary> /// <param name="folder">Exchange folder.</param> /// <param name="filter">Search filter.</param> /// <param name="view">Settings view in the directory search operation.</param> /// <returns>Items collection<see cref="Exchange.Item"/>. /// </returns> public static Exchange.FindItemsResults <Exchange.Item> ReadItems(this Exchange.Folder folder, Exchange.SearchFilter filter, Exchange.ItemView view) { Exchange.FindItemsResults <Exchange.Item> result = filter == null?folder.FindItems(view) : folder.FindItems(filter, view); view.Offset = result.NextPageOffset ?? 0; return(result); }
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)); }
public override void Initialise(List <MailFolder> folderList) { Status = MessageProcessorStatus.Initialising; service = ExchangeHelper.ExchangeConnect(_hostname, _username, _password); folders = new List <ExchangeFolder>(); // Use Exchange Helper to get all the folders for this account ExchangeHelper.GetAllSubFolders(service, new ExchangeFolder() { Folder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot) }, folders, false); if (IncludePublicFolders) { Logger.Debug("Including Public Folders"); ExchangeHelper.GetAllSubFolders(service, new ExchangeFolder() { Folder = Folder.Bind(service, WellKnownFolderName.PublicFoldersRoot), IsPublicFolder = true }, folders, false); } // Are we limited folders to a specific list? if (_limitFolderList != null) { var newFolders = new List <ExchangeFolder>(); foreach (var mailbox in _limitFolderList) { var mailboxMatch = mailbox.ToLower().Replace('/', '\\');; newFolders.AddRange(folders.Where(folder => folder.FolderPath.ToLower().Equals(mailboxMatch))); } folders = newFolders; } // Scan the folders to get message counts ExchangeHelper.GetFolderSummary(service, folders, _startDate, _endDate); folders.ForEach(folder => TotalMessages += !TestOnly ? folder.MessageCount : (folder.MessageCount > 20 ? 20 : folder.MessageCount)); Logger.Debug("Found " + folders.Count + " folders and " + TotalMessages + " messages."); // Now build the folder list that we pass on to the next folders. foreach (var exchangeFolder in folders) { var folder = new MailFolder() { SourceFolder = exchangeFolder.FolderPath, DestinationFolder = exchangeFolder.MappedDestination, MessageCount = exchangeFolder.MessageCount, }; _mainFolderList.Add(folder); } // Now initialise the next read, I am not going to start reading unless I know the pipeline is groovy NextReader.Initialise(_mainFolderList); Status = MessageProcessorStatus.Initialised; Logger.Info("ExchangeExporter Initialised"); }
/// <summary> /// <see cref="ExchangeSyncProvider.GetItemsFromFolders"/> /// </summary> protected override List <IRemoteItem> GetItemsFromFolders() { List <IRemoteItem> result = new List <IRemoteItem>(); int currentFolderIndex = 0; if (_currentFolder != null) { currentFolderIndex = _folderCollection.FindIndex(x => GetFolderId(x) == GetFolderId(_currentFolder)); } var numberSkippedFolders = Convert.ToInt32(_isCurrentFolderProcessed) + currentFolderIndex; foreach (var noteFolder in _folderCollection.Skip(numberSkippedFolders)) { _isCurrentFolderProcessed = false; _currentFolder = noteFolder; var activityFolderIds = new List <Guid>(); if (UserSettings.RootFolderId != Guid.Empty) { activityFolderIds.Add(UserSettings.RootFolderId); } var folderId = GetFolderId(noteFolder); if (UserSettings.RemoteFolderUIds.ContainsKey(folderId)) { activityFolderIds.Add(UserSettings.RemoteFolderUIds[folderId]); } Exchange.PropertySet idOnlyPropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly); var itemView = new Exchange.ItemView(PageItemCount) { PropertySet = idOnlyPropertySet, Offset = PageNumber * PageElementsCount }; Exchange.FindItemsResults <Exchange.Item> itemCollection; bool isMaxCountElements = false; bool isMoreAvailable = false; do { itemCollection = GetFolderItemsByFilter(noteFolder, _itemsFilterCollection, itemView); result.AddRange(GetEmailsFromCollection(itemCollection, activityFolderIds)); isMaxCountElements = (result.Count < PageElementsCount); isMoreAvailable = GetMoreAvailable(itemCollection); } while (isMoreAvailable && isMaxCountElements); if (!isMoreAvailable) { _isCurrentFolderProcessed = true; PageNumber = 0; } if (!isMaxCountElements) { PageNumber++; break; } } return(result); }
private void buttonEWSGetInboxCount_Click(object sender, EventArgs e) { Exchange.ExchangeService exchangeService = GetExchangeService(); string mbx = textBoxEWSMailbox.Text; if (checkBoxEWSImpersonate.Checked) { if (String.IsNullOrEmpty(mbx)) { MessageBox.Show("When impersonation is selected, you must specify the mailbox to impersonate"); return; } exchangeService.ImpersonatedUserId = new Exchange.ImpersonatedUserId(Exchange.ConnectingIdType.SmtpAddress, mbx); } if (tokenBox.Text == string.Empty) { AcquireDelegateToken(); } try { exchangeService.Credentials = new Exchange.OAuthCredentials(tokenBox.Text); } catch (Exception ex) { MessageBox.Show(String.Format("Error: {0}", ex.Message)); return; } try { Exchange.Folder inbox = null; if (!String.IsNullOrEmpty(mbx)) { // Specify the mailbox to access inbox = Exchange.Folder.Bind(exchangeService, new Exchange.FolderId(Exchange.WellKnownFolderName.Inbox, new Exchange.Mailbox(mbx))); } else { // Don't specify the mailbox inbox = Exchange.Folder.Bind(exchangeService, Exchange.WellKnownFolderName.Inbox); } MessageBox.Show(string.Format("Inbox message count = {0}", inbox.TotalCount.ToString())); } catch (Exception ex) { MessageBox.Show(String.Format("Error: {0}", ex.Message)); } }
/// <summary> /// Fills selected for synchronization folreds list. /// </summary> /// <param name="context"><see cref="SyncContext"/> instance.</param> protected void FillFoldersList(SyncContext context) { Folders = new List <Exchange.Folder>(); if (UserSettings.ImportActivitiesAll) { Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot); Folders.GetAllFoldersByClass(rootFolder, ExchangeConsts.AppointmentFolderClassName, null); } else { Folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context); } }
/// <summary> /// <see cref="ExchangeSyncProvider.EnumerateChanges"/> /// </summary> public override IEnumerable <IRemoteItem> EnumerateChanges(SyncContext context) { base.EnumerateChanges(context); var result = new List <IRemoteItem>(); if (!UserSettings.ImportActivities) { return(result); } var folders = new List <Exchange.Folder>(); Exchange.FolderId trashFolderId = Exchange.Folder.Bind( Service, Exchange.WellKnownFolderName.DeletedItems, Exchange.BasePropertySet.IdOnly).Id; if (UserSettings.ImportActivitiesAll) { Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot); folders.GetAllFoldersByFilter(rootFolder); folders.Add(rootFolder); } else { folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context); } Exchange.SearchFilter itemsFilter = GetItemsSearchFilters(); SyncItemSchema schema = FindSchemaBySyncValueName(typeof(ExchangeTask).Name); foreach (Exchange.Folder folder in folders) { if (folder.Id.Equals(trashFolderId)) { continue; } var itemView = new Exchange.ItemView(PageItemCount); Exchange.FindItemsResults <Exchange.Item> itemCollection; do { itemCollection = folder.ReadItems(itemsFilter, itemView); foreach (Exchange.Item item in itemCollection) { Exchange.Task task = ExchangeUtility.SafeBindItem <Exchange.Task>(Service, item.Id); if (task != null) { var remoteItem = new ExchangeTask(schema, task, TimeZone); result.Add(remoteItem); } } } while (itemCollection.MoreAvailable); } return(result); }
/// <summary> /// Returns all items by <paramref name="filter"/> from <paramref name="folder"/>. Recurring apointments not included. /// </summary> /// <param name="folder"><see cref=" Exchange.Folder"/> instance.</param> /// <param name="filter"><see cref=" Exchange.SearchFilter"/> instance.</param> /// <returns><see cref="Exchange.Item"/> collection.</returns> protected IEnumerable <Exchange.Item> GetCalendarItems(Exchange.Folder folder, Exchange.SearchFilter filter) { var itemView = new Exchange.ItemView(PageItemCount); Exchange.FindItemsResults <Exchange.Item> itemCollection; do { itemCollection = folder.ReadItems(filter, itemView); foreach (var item in itemCollection) { yield return(item); } } while (itemCollection.MoreAvailable); }
/// <summary> /// Binds exchange folders using <paramref name="folderRemoteIds"/>. /// </summary> /// <param name="service"><see cref="Microsoft.Exchange.WebServices.Data.ExchangeService"/> instance.</param> /// <param name="folderRemoteIds">Exchange folders unique identifiers collection.</param> /// <returns>Exchange folders collection.</returns> private List <Exchange.Folder> SafeBindFolders(Exchange.ExchangeService service, IEnumerable <string> folderRemoteIds) { List <Exchange.Folder> result = new List <Exchange.Folder>(); foreach (string uniqueId in folderRemoteIds) { if (string.IsNullOrEmpty(uniqueId)) { continue; } try { Exchange.Folder folder = Exchange.Folder.Bind(service, new Exchange.FolderId(uniqueId)); result.Add(folder); } catch (Exchange.ServiceResponseException) { } } return(result); }
/// <summary> /// <see cref="ExchangeSyncProvider.FillRemoteFoldersList"/> /// </summary> protected override void FillRemoteFoldersList(ref List <Exchange.Folder> folders, SyncContext context) { if (folders != null) { return; } folders = new List <Exchange.Folder>(); if (UserSettings.LoadAll) { Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot); folders.GetAllFoldersByFilter(rootFolder, getFolderFilters()); } else { folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context); } FilterDeprecatedFolders(ref folders); }
/// <summary> /// <see cref="ExchangeSyncProvider.FillRemoteFoldersList"/> /// </summary> protected override void FillRemoteFoldersList(ref List <Exchange.Folder> folders, SyncContext context) { if (folders != null) { return; } folders = new List <Exchange.Folder>(); if (UserSettings.LoadAll) { Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot); var filter = new Exchange.SearchFilter.IsEqualTo( Exchange.FolderSchema.FolderClass, ExchangeConsts.NoteFolderClassName); folders.GetAllFoldersByFilter(rootFolder, filter); } else { folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context); } FilterDeprecatedFolders(ref folders); }
/// <summary> /// Attempts to bind <see cref="Exchange.Folder"/> items by <paramref name="folderRemoteIds"/> collection. /// The method returns only folders which can not be obtained. /// </summary> /// <param name="service"><see cref="Exchange.ExchangeService"/> instance.</param> /// <param name="folderRemoteIds">Exchange folders remote ids collection.</param> /// <param name="context"><see cref="SyncContext"/> instance.</param> /// <returns>Folders which can not be obtained.</returns> protected virtual List <Exchange.Folder> SafeBindFolders(Exchange.ExchangeService service, IEnumerable <string> folderRemoteIds, SyncContext context) { List <Exchange.Folder> result = new List <Exchange.Folder>(); foreach (string uniqueId in folderRemoteIds) { if (string.IsNullOrEmpty(uniqueId)) { continue; } try { Exchange.Folder folder = Exchange.Folder.Bind(service, new Exchange.FolderId(uniqueId)); result.Add(folder); } catch (Exchange.ServiceResponseException exception) { LogMessage(context, SyncAction.None, SyncDirection.Upload, "Error while folder bind. Folder remoteId {0}", exception, uniqueId); } } return(result); }
/// <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); } } }
/// <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 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; }
/// <summary> /// Gets Items from <see cref="folder"/> by <see cref="filterCollection"/> /// </summary> /// <param name="folder">Exchange folder.</param> /// <param name="filterCollection">Filter collection.</param> /// <param name="itemView">Represents the view settings in a folder search operation.</param> /// <returns>Search result collection.</returns> public virtual IEnumerable <Exchange.Item> GetCalendarItemsByFilter(Exchange.Folder folder, Exchange.SearchFilter.SearchFilterCollection filterCollection, Exchange.ItemView itemView) { return(GetFolderItemsByFilter(folder, filterCollection, itemView)); }
/// <summary> /// Returns all appointments for period from <paramref name="folder"/>. Recurring apointments included. /// </summary> /// <param name="context"><see cref="SyncContext"/> instance.</param> /// <param name="folder"><see cref=" Exchange.Folder"/> instance.</param> /// <returns><see cref="Exchange.Item"/> collection.</returns> protected IEnumerable <Exchange.Item> GetAppointmentsForPeriod(SyncContext context, Exchange.Folder folder) { if (GetExchangeRecurringAppointmentsSupported(context.UserConnection)) { var type = LoadFromDateType.GetInstance(context.UserConnection); var starDate = type.GetLoadFromDate(UserSettings.ActivitySyncPeriod); var endDate = type.GetLoadFromDate(UserSettings.ActivitySyncPeriod, true); context?.LogInfo(SyncAction.None, SyncDirection.Download, "GetAppointmentsForPeriod with: starDate {0}, endDate {1}.", starDate, endDate); var currentStartDate = starDate; while (currentStartDate < endDate) { var calendarItemView = new Exchange.CalendarView(currentStartDate, currentStartDate.AddDays(1), 150); context?.LogInfo(SyncAction.None, SyncDirection.Download, "GetAppointmentsForPeriod with: currentStartDate {0}.", currentStartDate); Exchange.FindItemsResults <Exchange.Appointment> calendarItemCollection; calendarItemCollection = Service.FindAppointments(folder.Id, calendarItemView); context?.LogInfo(SyncAction.None, SyncDirection.Download, "GetAppointmentsForPeriod - Service found {0} items.", calendarItemCollection.Count()); foreach (var item in calendarItemCollection) { yield return(item); } currentStartDate = currentStartDate.AddDays(1); } context?.LogInfo(SyncAction.None, SyncDirection.Download, "GetAppointmentsForPeriod - End method."); } }
/// <summary> /// Gets Items from <see cref="folder"/> by <see cref="filterCollection"/> /// </summary> /// <param name="folder">Exchange folder.</param> /// <param name="filterCollection">Filter collection.</param> /// <param name="itemView">Represents the view settings in a folder search operation.</param> /// <returns></returns> public virtual Exchange.FindItemsResults <Exchange.Item> GetFolderItemsByFilter(Exchange.Folder folder, Exchange.SearchFilter.SearchFilterCollection filterCollection, Exchange.ItemView itemView) { return(folder.ReadItems(filterCollection, itemView)); }
/// <summary> /// Adds the specified folder. /// </summary> /// <param name="folder">The folder.</param> internal void Add(Folder folder) { this.ids.Add(new FolderWrapper(folder)); }
static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //connect to exchange //autodiscoverurl //Service service = new Service(); Program prog = new Program(); ExchangeService service = prog.getMService(); // Bind the Inbox folder to the service object. Microsoft.Exchange.WebServices.Data.Folder inbox = Microsoft.Exchange.WebServices.Data.Folder.Bind(service, WellKnownFolderName.Inbox); // The search filter to get unread email. Console.WriteLine("BEFORE"); //TIP to create search filter //first create search collection list //add any search filter like a filter that looks for a certain email or checks if email is unread or read //then if you want more searches, create a new search filter that ANDS the previous list collection //then if you want to let's say check for a domain name in the email, create new list //with that new list, add new search filter & add previous filter //then create a new search filter and AND or OR it with previous collection //idea is this starts chaining filters together //Another tip: Make sure you properly use AND and OR...e.g. can't filter two email domains // and say you want the substring to contain denali AND tmobile // so you choose OR operator to say i want to filter for either domain //SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); List <SearchFilter> searchANDFilter = new List <SearchFilter>(); //searchANDFilter.Add(sf); ExtendedPropertyDefinition PidTagSenderSmtpAddress = new ExtendedPropertyDefinition(0x5D01, MapiPropertyType.String); //searchANDFilter.Add(new SearchFilter.ContainsSubstring(PidTagSenderSmtpAddress, "@denaliai.com")); searchANDFilter.Add(new SearchFilter.ContainsSubstring(PidTagSenderSmtpAddress, "@denaliai.com")); searchANDFilter.Add(new SearchFilter.ContainsSubstring(PidTagSenderSmtpAddress, "@usc.edu")); //Console.WriteLine("the address is: " + PidTagSenderSmtpAddress.PropertySet.Value.ToString()); SearchFilter domainSF = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchANDFilter); List <SearchFilter> searchFinalFilter = new List <SearchFilter>(); searchFinalFilter.Add(new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false))); searchFinalFilter.Add(domainSF); SearchFilter finalSF = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFinalFilter); //new SearchFilter.ContainsSubstring(EmailMessageSchema.Sender, "@denaliai.com", ContainmentMode.Substring, ComparisonMode.IgnoreCase) //SearchFilter.ContainsSubstring subjectFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Sender,"@denaliai.com", ContainmentMode.Substring, ComparisonMode.IgnoreCase); Console.WriteLine("AFTER"); ItemView view = new ItemView(4); // Fire the query for the unread items. // This method call results in a FindItem call to EWS. view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.Sender); view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending); //Queue<FindItemsResults<Item>> allEmails = new Queue<FindItemsResults<Item>>(); //Queue<EmailMessage> allEmails = new Queue<EmailMessage>(); FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Inbox, finalSF, view); try { //allEmails.Enqueue(message); MailItem mail = new MailItem(); Stack <Item> allEmails = new Stack <Item>(); foreach (Item item in findResults.Items) { allEmails.Push(item); } foreach (Item item in allEmails) { mail.loadMail(findResults, item, service, prog); prog.setMailItem(mail); prog.setMProjectTitle(mail.mSubject); Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&the project title is: " + prog.getMProjectTitle()); if (mail.mIsAuthority == true) { //idea is to send project report if authority is true //EmailErrors ee = new EmailErrors(prog); //ee.sendMilestoneErrorEmail(); try { Sharepoint sp = new Sharepoint(prog); string fullReport = sp.createProjectReport(prog.getMProjectTitle()); //Create Response Email mail.sendEmail(fullReport, prog.getMProjectTitle(), service); } catch (ServerException se) { if (se.Message.Contains("does not exist at site with URL")) { EmailErrors ee = new EmailErrors(prog); ee.sendProjectDoesNotExistEmail(mail.mMailboxAddress); } } } else { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); //doc.LoadHtml(body); doc.LoadHtml(mail.mBody); String fullBodyText = ""; foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()")) { if (node.InnerText != "") { Console.WriteLine(node.InnerText); fullBodyText += "\n" + node.InnerText; } } //fullBodyText = adjustString(fullBodyText); prog.setMBody(fullBodyText); //prog.setMProjectTitle(subject); prog.setMProjectTitle(mail.mSubject); Console.WriteLine("body is: " + prog.getMBody()); prog.parseEmail(prog, service); } } } catch (Exception e) { Console.WriteLine(e); } } catch (Exception e) { Console.WriteLine(e); } }
private FolderId GetCreateFolder(string destinationFolder, bool secondAttempt = false) { lock (_folderCreationLock) { if (!folders.Any(folder => folder.FolderPath.Equals(destinationFolder))) { // folder doesn't exist // getCreate its parent var parentPath = Regex.Replace(destinationFolder, @"\\[^\\]+$", ""); FolderId parentFolderId = null; if (parentPath.Equals(destinationFolder)) { // we are at the root parentPath = ""; parentFolderId = WellKnownFolderName.MsgFolderRoot; } else { parentFolderId = GetCreateFolder(parentPath); } Logger.Debug("Folder " + destinationFolder + " doesn't exist, creating."); var destinationFolderName = Regex.Replace(destinationFolder, @"^.*\\", ""); Folder folder = new Folder(service) { DisplayName = destinationFolderName }; try { folder.Save(parentFolderId); } catch (Exception e) { // If the folder exists, we need to refresh and have another crack if (e.Message.Equals("A folder with the specified name already exists.") && !secondAttempt) { Logger.Warn("Looks like the folder " + destinationFolder + " was created under our feet, refreshing the folder list. We will only attempt this once per folder."); // Oops, the folders have been updated on the server, we need a refresh var newFolders = new List <ExchangeFolder>(); ExchangeHelper.GetAllSubFolders(service, new ExchangeFolder { Folder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot) }, newFolders, false); folders = newFolders; // lets try again return(GetCreateFolder(destinationFolder, true)); } throw e; } folders.Add(new ExchangeFolder() { Folder = folder, FolderId = folder.Id, FolderPath = String.IsNullOrEmpty(parentPath) ? destinationFolderName : parentPath + @"\" + destinationFolderName, }); return(folder.Id); } else { return(folders.First(folder => folder.FolderPath.Equals(destinationFolder)).FolderId); } } }
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 IEnumerable <IRemoteItem> EnumerateChangesOld(SyncContext context) { base.EnumerateChanges(context); var result = new List <IRemoteItem>(); var folders = new List <Exchange.Folder>(); if (UserSettings.LoadAll) { Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot); var filter = new Exchange.SearchFilter.IsEqualTo( Exchange.FolderSchema.FolderClass, ExchangeConsts.NoteFolderClassName); folders.GetAllFoldersByFilter(rootFolder, filter); } else { folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context); } var itemsFilterCollection = new Exchange.SearchFilter.SearchFilterCollection(Exchange.LogicalOperator.And); var draftFilter = new Exchange.SearchFilter.IsNotEqualTo(Exchange.ItemSchema.IsDraft, true); itemsFilterCollection.Add(draftFilter); DateTime loadEmailsFromDate = LoadEmailsFromDate != DateTime.MinValue ? LoadEmailsFromDate : UserSettings.LastSyncDate; if (loadEmailsFromDate != DateTime.MinValue) { var localLastSyncDate = GetLastSyncDate(loadEmailsFromDate); var itemsFilter = new Exchange.SearchFilter.IsGreaterThan(Exchange.ItemSchema.LastModifiedTime, localLastSyncDate); _itemsFilterCollection.Add(itemsFilter); } FilterDeprecatedFolders(ref folders); foreach (var noteFolder in folders) { var activityFolderIds = new List <Guid>(); if (UserSettings.RootFolderId != Guid.Empty) { activityFolderIds.Add(UserSettings.RootFolderId); } var folderId = GetFolderId(noteFolder); if (UserSettings.RemoteFolderUIds.ContainsKey(folderId)) { activityFolderIds.Add(UserSettings.RemoteFolderUIds[folderId]); } Exchange.PropertySet idOnlyPropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly); var itemView = new Exchange.ItemView(PageItemCount) { PropertySet = idOnlyPropertySet }; Exchange.FindItemsResults <Exchange.Item> itemCollection; do { itemCollection = GetFolderItemsByFilter(noteFolder, itemsFilterCollection, itemView); if (itemCollection == null) { break; } result.AddRange(GetEmailsFromCollection(itemCollection, activityFolderIds)); } while (itemCollection.MoreAvailable); } return(result); }
/// <summary> /// <see cref="ExchangeSyncProvider.EnumerateChanges"/> /// </summary> public override IEnumerable <IRemoteItem> EnumerateChanges(SyncContext context) { base.EnumerateChanges(context); var result = new List <IRemoteItem>(); if (!UserSettings.ImportContacts) { return(result); } var folders = new List <Exchange.Folder>(); if (UserSettings.ImportContactsAll) { Exchange.Folder rootFolder = Exchange.Folder.Bind(Service, Exchange.WellKnownFolderName.MsgFolderRoot); var filter = new Exchange.SearchFilter.IsEqualTo( Exchange.FolderSchema.FolderClass, ExchangeConsts.ContactFolderClassName); folders.GetAllFoldersByFilter(rootFolder, filter); } else { folders = SafeBindFolders(Service, UserSettings.RemoteFolderUIds.Keys, context); } Exchange.SearchFilter itemsFilter = GetExternalItemsFiltersHandler != null ? GetExternalItemsFiltersHandler() as Exchange.SearchFilter : GetContactsFilters(); SyncItemSchema schema = FindSchemaBySyncValueName(typeof(ExchangeContact).Name); var exchangeAddrDetails = new List <ExchangeAddressDetail>(); var exchangeCompanies = new List <string>(); foreach (Exchange.Folder noteFolder in folders) { var itemView = new Exchange.ItemView(PageItemCount); Exchange.FindItemsResults <Exchange.Item> itemCollection; do { itemCollection = noteFolder.ReadItems(itemsFilter, itemView); foreach (Exchange.Item item in itemCollection) { Exchange.Contact fullContact = GetFullItemHandler != null ? GetFullItemHandler(item.Id.UniqueId) as Exchange.Contact : GetFullContact(item.Id); if (fullContact == null) { continue; } var remoteItem = new ExchangeContact(schema, fullContact, TimeZone); remoteItem.InitIdProperty(context); result.Add(remoteItem); if (!string.IsNullOrEmpty(fullContact.CompanyName)) { exchangeCompanies.Add(fullContact.CompanyName); } AddAddressDetails(exchangeAddrDetails, fullContact); } } while (itemCollection.MoreAvailable); } FillAddressDetailsData(context, exchangeAddrDetails); FillAccountsMap(context, exchangeCompanies.Distinct().ToList()); return(result); }
/// <summary> /// Gets unique folder identifier. /// </summary> /// <param name="folder"><see cref="Exchange.Folder"/></param> /// <returns>Unique folder identifier</returns> protected virtual string GetFolderId(Exchange.Folder folder) { return(folder.Id.UniqueId); }