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));
     }
 }
Example #2
0
        // Resolve folder name to Folder object - the folder is expected to be immediately under the mailbox root
        public static Folder FindFolderByName(string folderName, ExchangeService service)
        {
            Logger.DebugFormat("Looking for folder named '{0}'", folderName);
            // Look for the folder under the mailbox root
            var rootFolder = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot);

            // Folder name should be equal to 'folderName'
            var folderFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, folderName);

            // No need to look for more than one folder (can't have more than one folder with the exact same name)
            var findFoldersResults = rootFolder.FindFolders(folderFilter, new FolderView(1));

            if (!findFoldersResults.Any())
            {
                Logger.InfoFormat("Couldn't find folder {0}", folderName);
                return null;
            }

            Logger.DebugFormat("Found folder {0} ({1} matching folder items)", folderName, findFoldersResults.Count());

            var folder = findFoldersResults.First();
            return folder;
        }
        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);
        }
Example #4
0
        private void MainFormLoad(object sender, EventArgs e)
        {
            Form.CheckForIllegalCrossThreadCalls = false;
            Action<string> action = str => this.lbLog.Items.Add(str);
            Logger.AddAlgorithm(new ComponentLogWriteAlgorithm(action));

            this.panel1.Enabled = false;
            this.generateToolStripMenuItem.Enabled = false;
            this.saveSettingsToolStripMenuItem.Enabled = false;

            this.splitContainer4.SplitterWidth = 10;
            this.splitContainer1.SplitterWidth = 10;
            this.RearrangeCountControls();

            ToolStripButton tsbtnMove =
                new ToolStripButton(LocalizibleStrings.BtnAddSelectedToMailList)
                {
                    DisplayStyle = ToolStripItemDisplayStyle.Image,
                    Image = LocalizibleStrings.ArrowRight
                };

            tsbtnMove.Click += (o, args) =>
            {
                IEnumerable<StoredContact> storedContacts =
                    this.clTargetContacts.dgObjects.Objects.Cast<StoredContact>().ToList();

                foreach (Contact obj in
                    from Contact obj in this.clEwsContacts.dgObjects.SelectedObjects
                    let existed = storedContacts.FirstOrDefault(s => s.UniqId == obj.Id.UniqueId)
                    where existed == null
                    select obj)
                {
                    this.clTargetContacts.dgObjects.AddObject(new StoredContact(obj));
                }
            };

            this.clEwsContacts._barTools.Items.Insert(2, tsbtnMove);

            string mailTemplateFolder;
            string eventTemplateFolder;

            switch (Thread.CurrentThread.CurrentUICulture.LCID)
            {
                case LocalizationHelper.EnInt:
                    this.englishToolStripMenuItem.Checked = true;
                    this.russianToolStripMenuItem.Checked = false;
                    mailTemplateFolder = Config.EmailTemplateFolderEn;
                    eventTemplateFolder = Config.EventTemplateFolderEn;
                    break;
                case LocalizationHelper.RuInt:
                    this.russianToolStripMenuItem.Checked = true;
                    this.englishToolStripMenuItem.Checked = false;
                    mailTemplateFolder = Config.EmailTemplateFolderRu;
                    eventTemplateFolder = Config.EventTemplateFolderRu;
                    break;
                default:
                    this.englishToolStripMenuItem.Checked = true;
                    this.russianToolStripMenuItem.Checked = false;
                    mailTemplateFolder = Config.EmailTemplateFolderEn;
                    eventTemplateFolder = Config.EventTemplateFolderEn;
                    break;
            }

            this.SetEwsContactsColumns();
            this.SetMailTemplatesColumns();
            this.SetEventTemplatesColumns();
            this.SetTargetContactsColumns();

            this.clEwsContacts.tsbtnFilteredProperties.Visible = false;
            this.clEwsContacts.tsbtnCreate.Visible = false;
            this.clEwsContacts.tsbtnEdit.Visible = false;
            this.clEwsContacts.tsbtnDelete.Visible = false;
            this.clEwsContacts.tsbtnFilterSettings.Visible = false;
            this.clEwsContacts.tsbtnFilteredProperties.Visible = false;

            this.clEwsContacts.tsbtnRefresh.Text = LocalizibleStrings.BtnRefresh;
            this.clEwsContacts.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clEwsContacts.tsbtnSearch.Text = LocalizibleStrings.BtnSearch;
            this.clEwsContacts.tslbSearch.Text = LocalizibleStrings.LbSearch;
            this.clEwsContacts.tslbCount.Text = LocalizibleStrings.LbCount;

            this.clEwsContacts.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    Folder contactsFolder;
                    if (!TryGetFolder(Config.ContactFolder, out contactsFolder))
                    {
                        Logger.Message(LocalizibleStrings.TryLoadFromDefault);
                        contactsFolder = ContactsFolder.Bind(_service, WellKnownFolderName.Contacts);
                    }

                    SearchFilter sf = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, @"IPM.Contact");

                    FindItemsResults<Item> items =
                        contactsFolder.FindItems(sf, new ItemView(int.MaxValue));
                    this.clEwsContacts.dgObjects.SetObjects(items.ToList());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetContactList, exc);
                }
            };

            this.clMailTemplates.tsbtnFilteredProperties.Visible = false;
            this.clMailTemplates.tsbtnCreate.Visible = false;
            this.clMailTemplates.tsbtnEdit.Visible = false;
            this.clMailTemplates.tsbtnDelete.Visible = false;
            this.clMailTemplates.tsbtnFilterSettings.Visible = false;
            this.clMailTemplates.tsbtnFilteredProperties.Visible = false;

            this.clMailTemplates.tsbtnRefresh.Text = LocalizibleStrings.BtnRefresh;
            this.clMailTemplates.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clMailTemplates.tsbtnSearch.Text = LocalizibleStrings.BtnSearch;
            this.clMailTemplates.tslbSearch.Text = LocalizibleStrings.LbSearch;
            this.clMailTemplates.tslbCount.Text = LocalizibleStrings.LbCount;

            this.clMailTemplates.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    /*Folder templatesFolder;
                    if (!TryGetFolder(mailTemplateFolder, out templatesFolder))
                        return;

                    FindItemsResults<Item> items =
                        templatesFolder.FindItems(new ItemView(int.MaxValue));*/

                    IList<Storage.Message> items = new List<Storage.Message>();

                    // ReSharper disable once LoopCanBeConvertedToQuery
                    // под отладчиком всякая фигня происходит если linq
                    foreach (string path in
                        Directory.GetFiles(Config.GetParam(mailTemplateFolder)))
                    {
                        items.Add(new Storage.Message(path));
                    }

                    this.clMailTemplates.dgObjects.SetObjects(items.ToList());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetMailTemplateList, exc);
                }
            };

            this.clEventTemplates.tsbtnCreate.Visible = false;
            this.clEventTemplates.tsbtnEdit.Visible = false;
            this.clEventTemplates.tsbtnDelete.Visible = false;
            this.clEventTemplates.tsbtnFilterSettings.Visible = false;
            this.clEventTemplates.tsbtnFilteredProperties.Visible = false;

            this.clEventTemplates.tsbtnRefresh.Text = LocalizibleStrings.BtnRefresh;
            this.clEventTemplates.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clEventTemplates.tsbtnSearch.Text = LocalizibleStrings.BtnSearch;
            this.clEventTemplates.tslbSearch.Text = LocalizibleStrings.LbSearch;
            this.clEventTemplates.tslbCount.Text = LocalizibleStrings.LbCount;

            this.clEventTemplates.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    /*Folder templatesFolder;
                    if (!TryGetFolder(eventTemplateFolder, out templatesFolder))
                        return;

                    FindItemsResults<Item> items =
                        templatesFolder.FindItems(new ItemView(int.MaxValue));*/

                    List<Storage.Message> tasks =
                        Directory.GetFiles(Config.GetParam(eventTemplateFolder))
                            .Select(t => new Storage.Message(t))
                            .ToList();

                    this.clEventTemplates.dgObjects.SetObjects(tasks);
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetEventTemplateList, exc);
                }
            };

            this.clTargetContacts.tsbtnCreate.Text = LocalizibleStrings.BtnCreate;
            this.clTargetContacts.tsbtnDelete.Text = LocalizibleStrings.BtnDelete;
            this.clTargetContacts.tsbtnRefresh.Text = LocalizibleStrings.BtnRefresh;
            this.clTargetContacts.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clTargetContacts.tsbtnSearch.Text = LocalizibleStrings.BtnSearch;
            this.clTargetContacts.tslbSearch.Text = LocalizibleStrings.LbSearch;
            this.clTargetContacts.tslbCount.Text = LocalizibleStrings.LbCount;

            this.clTargetContacts.tsbtnCreate.Visible = true;
            this.clTargetContacts.tsbtnEdit.Visible = false;
            this.clTargetContacts.tsbtnDelete.Visible = true;
            this.clTargetContacts.tsbtnFilterSettings.Visible = false;
            this.clTargetContacts.tsbtnFilteredProperties.Visible = false;

            this.clTargetContacts.dgObjects.TriStateCheckBoxes = false;
            this.clTargetContacts.dgObjects.RenderNonEditableCheckboxesAsDisabled = false;
            this.clTargetContacts.dgObjects.UseSubItemCheckBoxes = true;

            ToolStripButton tsbtnSave =
                new ToolStripButton(LocalizibleStrings.BtnSaveAll)
                {
                    DisplayStyle = ToolStripItemDisplayStyle.Image,
                    Image = LocalizibleStrings.Save
                };

            tsbtnSave.Click +=
                (o, args) =>
                {
                    IEnumerable<StoredContact> contacts =
                        this.clTargetContacts.dgObjects.Objects.Cast<StoredContact>();
                    foreach (StoredContact contact in contacts)
                    {
                        contact.Save();
                    }
                };

            this.clTargetContacts._barTools.Items.Insert(1, tsbtnSave);

            this.clTargetContacts.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    this.clTargetContacts.dgObjects.SetObjects(StoredContact.GetAll());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetStoredContacts, exc);
                }
            };

            this.clTargetContacts.tsbtnCreate.Click +=
                (o, args) => this.clTargetContacts.dgObjects.AddObject(new StoredContact());

            this.clTargetContacts.tsbtnDelete.Click += (o, args) =>
            {
                DialogResult res = MessageBox.Show(
                    LocalizibleStrings.DeleteConfirmation,
                    LocalizibleStrings.Warning,
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2);

                if (res == DialogResult.No)
                    return;

                foreach (StoredContact cont in this.clTargetContacts.dgObjects.SelectedObjects)
                {
                    try
                    {
                        this.clTargetContacts.dgObjects.RemoveObject(cont);
                        cont.Delete();
                    }
                    catch (Exception exc)
                    {
                        Logger.Error(LocalizibleStrings.CannotDeleteContact + cont.FileName, exc);
                    }
                }
            };
        }
Example #5
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 #6
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.");
            }
        }
        public ActionResult MessageEWS(EmailAddress email)
        {
            ExchangeService service = Connection.ConnectEWS();

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

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

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

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

            //string sf = "Body:\"Compensation\"";

            //Define the new PidTagParentDisplay property to use for filtering:
            ExtendedPropertyDefinition def = new ExtendedPropertyDefinition(0x0E05, MapiPropertyType.String);
            SearchFilter searchCriteria = new SearchFilter.IsEqualTo(def, email.Address);
            FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, searchCriteria, view);

            foreach (EmailMessage it in findResults.Items)
            {
                listing.Add(it);
            }

            return View(listing.ToList<EmailMessage>());
        }
        /// <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;
        }
Example #9
0
        /**
         * Function Undo Holiday Insertion
         */
        static void UndoInsertion(ExchangeService service, List<string> mailboxes)
        {
            // Log file
            string datetimeString = DateTime.Now.ToString("MMddyyyy");
            string logfile = "../../logs/" + datetimeString + "_undo_holiday_log.txt";

            using (System.IO.StreamWriter log = new System.IO.StreamWriter(@logfile, true))
            {

                // Mailboxes that need to be rerun that errored during this process
                List<string> rrmailboxes = new List<string>();

                foreach (string mailbox in mailboxes)
                {

                    // Find the holidays
                    try
                    {
                        // Run search
                        // Impersonate that User
                        service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox);

                        // Search String
                        String category = "Holiday";
                        // Search Filter
                        SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(AppointmentSchema.Categories, category);

                        // Result Return Size, number of items
                        ItemView holidayView = new ItemView(500);
                        // Limit data to only necesary components
                        holidayView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Categories);

                        FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Calendar, filter, holidayView);

                        if (items.TotalCount > 0)
                        {
                            List<ItemId> ids = new List<ItemId>();
                            foreach (Item item in items)
                            {

                                ids.Add(item.Id);

                            }

                            service.DeleteItems(ids, DeleteMode.MoveToDeletedItems, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences);
                            Console.WriteLine("Removed " + items.TotalCount + " holidays in the Calendar folder for " + mailbox);
                            DateTime now = DateTime.Now;
                            log.WriteLine(now + " - Removed " + items.TotalCount + " holidays in the Calendar folder for " + mailbox);

                        }
                        else
                        {
                            Console.WriteLine("Could not find any holidays for mailbox: " + mailbox);
                        }
                    }
                    catch
                    {

                            log.WriteLine("Mailbox Errored: " + mailbox);
                            rrmailboxes.Add(mailbox);

                    }

                    // Clear impersonation.
                    service.ImpersonatedUserId = null;
                }

                // Rerun errored accounts.

                if (rrmailboxes.Count > 0)
                {
                    Console.WriteLine("Looping through errored mailboxes.");
                }
                while (rrmailboxes.Count > 0)
                {

                    // Run search

                    // Current mailbox
                    string mb = rrmailboxes.ElementAt(0);
                    Console.WriteLine("On Mailbox: " + mb);
                    // Take the mailbox out of the first element slot
                    Console.WriteLine("Removing mailbox " + mb + " from beginning of rrmailboxes.");
                    rrmailboxes.RemoveAt(0);
                    rrmailboxes.TrimExcess();

                    // Find the holidays
                    try
                    {

                        // Impersonate that User
                        service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mb);

                        // Search String
                        String category = "Holiday";
                        // Search Filter
                        SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(AppointmentSchema.Categories, category);

                        // Result Return Size, number of items
                        ItemView holidayView = new ItemView(100);
                        // Limit data to only necesary components
                        holidayView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Categories);

                        FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Calendar, filter, holidayView);

                        if (items.TotalCount > 0)
                        {
                            //Log number of found items
                            Console.WriteLine("Found " + items.TotalCount + " holidays in the Calendar folder for " + mb);

                            List<ItemId> ids = new List<ItemId>();
                            foreach (Item item in items)
                            {

                                ids.Add(item.Id);
                                Console.WriteLine(mb + ": Added ItemID to be removed: " + item.Id);
                            }

                            service.DeleteItems(ids, DeleteMode.MoveToDeletedItems, null, null);
                            Console.WriteLine("Removed " + items.TotalCount + " holidays in the Calendar folder for " + mb);
                            DateTime now = DateTime.Now;
                            log.WriteLine(now + " - Removed " + items.TotalCount + " holidays in the Calendar folder for " + mb);

                        }
                        else
                        {

                            Console.WriteLine("Could not find any holidays for mailbox: " + mb);
                            log.WriteLine("Could not find any holidays for mailbox: " + mb);
                        }
                    }
                    catch
                    {
                        DateTime now = DateTime.Now;
                        log.WriteLine(now + " - Fatal Mailbox Errored: " + mb + "; Will not retry");
                        Console.WriteLine("Fatal Mailbox Errored: " + mb + "; Will not retry");

                    }

                    // Clear impersonation.
                    service.ImpersonatedUserId = null;

                }
            }
        }
Example #10
0
        /**
         * Function Add the Holidays
         **/
        static void AddHolidays(ExchangeService service, List<string[]> holidays, List<string> mailboxes)
        {
            // Log file
            string datetimeString = DateTime.Now.ToString("MMddyyyy");
            string logfile = "../../logs/" + datetimeString + "_add_holiday_log.txt";

            //Initiate Error List
            List<string> mbs = new List<string>();

            using (System.IO.StreamWriter log = new System.IO.StreamWriter(@logfile, true))
            {

                // Loop through each email address in the passed in mailboxes List
                foreach (string mailbox in mailboxes)
                {

                    // Impersonate that User
                    service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox);
                    Console.WriteLine("Attempting to Add Holidays to: " + mailbox);

                    List<Appointment> uga_holidays = new List<Appointment>();

                    // Loop through all the holidays
                    foreach (string[] holiday in holidays)
                    {

                        //Create a new appointment
                        Appointment appointment = new Appointment(service);

                        // Set details
                        appointment.Subject = holiday[0];
                        appointment.Start = DateTime.Parse(holiday[1]);
                        appointment.End = appointment.Start.AddDays(1);
                        appointment.IsAllDayEvent = true;
                        StringList categories = new Microsoft.Exchange.WebServices.Data.StringList();
                        categories.Add("Holiday");
                        appointment.Categories = categories;
                        appointment.IsReminderSet = false;

                        uga_holidays.Add(appointment);

                    }

                    // Save and Send
                    try
                    {
                        service.CreateItems(uga_holidays, WellKnownFolderName.Calendar, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone);
                        Console.WriteLine("Added Holiday Successfully to: " + mailbox);

                        DateTime now = DateTime.Now;
                        log.WriteLine(now + " - Added holidays succesfully to Mailbox: " + mailbox);

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error During Initial Add - Mailbox: " + mailbox + "; Exception thrown: " + ex);
                        log.WriteLine("Error During Initial Add - Mailbox: " + mailbox + "; Exception thrown: " + ex);
                        mbs.Add(mailbox);

                    }

                    // Clear impersonation.
                    service.ImpersonatedUserId = null;

                }

                //Process Rerun List
                if (mbs.Count > 0)
                {
                    Console.WriteLine("Looping through re-run mailboxes.");

                    while (mbs.Count > 0)
                    {
                        // Current mailbox
                        string mb = mbs.ElementAt(0);
                        Console.WriteLine("On Mailbox: " + mb);

                        // Take the mailbox out of the first element slot
                        log.WriteLine("Removing mailbox " + mb + " from beginning of mbs.");
                        mbs.RemoveAt(0);
                        mbs.TrimExcess();

                        try
                        {
                            // Reruns: Removes
                            // Run search
                            // Impersonate that User
                            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mb);

                            // Search String
                            String category = "Holiday";
                            // Search Filter
                            SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(AppointmentSchema.Categories, category);

                            // Result Return Size, number of items
                            ItemView holidayView = new ItemView(100);
                            // Limit data to only necesary components
                            holidayView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Categories);

                            FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Calendar, filter, holidayView);

                            if (items.TotalCount > 0)
                            {

                                Console.WriteLine("Removing " + items.TotalCount + " holidays from " + mb);
                                log.WriteLine("Found " + items.TotalCount + " holidays in the Calendar folder for " + mb + " to be removed.");

                                List<ItemId> ids = new List<ItemId>();
                                foreach (Item item in items)
                                {

                                    ids.Add(item.Id);

                                }

                                service.DeleteItems(ids, DeleteMode.MoveToDeletedItems, null, null);

                            }
                            else
                            {
                                log.WriteLine("Found no holidays in the Calendar folder for " + mb + " to be removed.");
                            }

                            // Rerun: Adds

                            List<Appointment> holidays = new List<Appointment>();

                            // Loop through all the holidays
                            foreach (string[] holiday in holidays)
                            {

                                //Create a new appointment
                                Appointment appointment = new Appointment(service);

                                // Set details
                                appointment.Subject = holiday[0];
                                appointment.Start = DateTime.Parse(holiday[1]);
                                appointment.End = appointment.Start.AddDays(1);
                                appointment.IsAllDayEvent = true;
                                StringList categories = new Microsoft.Exchange.WebServices.Data.StringList();
                                categories.Add("Holiday");
                                appointment.Categories = categories;
                                appointment.IsReminderSet = false;

                                holidays.Add(appointment);

                            }

                            service.CreateItems(holidays, null, null, SendInvitationsMode.SendToNone);
                            Console.WriteLine("Added Holiday Successfully to" + mb);
                            DateTime now = DateTime.Now;
                            log.WriteLine(now + " - Added holidays succesfully to Mailbox: " + mb);

                        }
                        catch
                        {
                            log.WriteLine("Fatal Mailbox Errored on Re-Run Removes: " + mb + "; Will not retry.");
                            Console.WriteLine("Fatal Mailbox Errored on Re-Run Removes: " + mb + "; Will not retry.");
                        }

                        // Clear impersonation.
                        service.ImpersonatedUserId = null;

                    }
                }
            }
        }