public static void ListTaskCalendar() { var outlookApp = new Microsoft.Office.Interop.Outlook.Application(); var mapiNamespace = outlookApp.GetNamespace("MAPI"); var CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar); var outlookCalendarItems = CalendarFolder.Items; outlookCalendarItems.IncludeRecurrences = true; foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems) { if (item.IsRecurring) { Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern(); DateTime first = new DateTime(2008, 8, 31, item.Start.Hour, item.Start.Minute, 0); DateTime last = new DateTime(2008, 10, 1); Microsoft.Office.Interop.Outlook.AppointmentItem recur = null; for (DateTime cur = first; cur <= last; cur = cur.AddDays(1)) { try { recur = rp.GetOccurrence(cur); MessageBox.Show(recur.Subject + " -> " + cur.ToLongDateString()); } catch { } } } else { MessageBox.Show(item.Subject + " -> " + item.Start.ToLongDateString()); } } }
/// <summary> /// Removes a specific event or a series of events /// </summary> /// <param name="objItems">Contains all the event items in a specific calendar/folder</param> /// <param name="subject">Subject of the event to delete</param> /// <param name="eventDate">If specified, this specific event is deleted instead of all events with subject</param> internal static void RemoveEvent(Outlook.Items objItems, string subject, string eventDate) { string methodTag = "RemoveEvent"; LogWriter.WriteInfo(TAG, methodTag, "Starting: " + methodTag + " in " + TAG); Outlook.AppointmentItem agendaMeeting = null; if (eventDate == null) { objItems.Sort("[Subject]"); objItems.IncludeRecurrences = true; LogWriter.WriteInfo(TAG, methodTag, "Attempting to find event with subject: " + subject); agendaMeeting = objItems.Find("[Subject]=" + subject); if (agendaMeeting == null) { LogWriter.WriteWarning(TAG, methodTag, "No event found with subject: " + subject); } else { LogWriter.WriteInfo(TAG, methodTag, "Removing all events with subject: " + subject); do { agendaMeeting.Delete(); agendaMeeting = objItems.FindNext(); LogWriter.WriteInfo(TAG, methodTag, "Event found and deleted, finding next"); } while (agendaMeeting != null); LogWriter.WriteInfo(TAG, methodTag, "All events with subject: " + subject + " found and deleted"); } } else { LogWriter.WriteInfo(TAG, methodTag, "Finding event with subject" + subject + " and date: " + eventDate); agendaMeeting = objItems.Find("[Subject]=" + subject); if (agendaMeeting == null) { LogWriter.WriteWarning(TAG, methodTag, "No event found with subject: " + subject); } else { Outlook.RecurrencePattern recurrPatt = agendaMeeting.GetRecurrencePattern(); agendaMeeting = recurrPatt.GetOccurrence(DateTime.Parse(eventDate)); agendaMeeting.Delete(); LogWriter.WriteInfo(TAG, methodTag, "Event found and deleted"); } } }
public void TestReplaceCalendar() { Application app = new Application(); OutlookCalendarWithSifE agent = new OutlookCalendarWithSifE(app); OutlookCalendar outlookAgent = new OutlookCalendar(app, CalendarPeriod.All); string existingEntryId = AddCalendar(); XElement x = XElement.Load(MockPath + "SifE.xml"); string entryId = agent.ReplaceItem(x.ToString(), existingEntryId); Assert.IsTrue(entryId == existingEntryId); AppointmentItem appointment = outlookAgent.GetItemByEntryId(entryId); Assert.AreEqual(appointment.Subject, x.Element("Subject").Value); Assert.AreEqual(((int)appointment.BusyStatus).ToString(), x.Element("BusyStatus").Value); Assert.AreEqual(appointment.Categories, x.Element("Categories").Value); Assert.AreEqual(appointment.Companies, x.Element("Companies").Value); Assert.AreEqual(((int)appointment.Importance).ToString(), x.Element("Importance").Value); Assert.AreEqual(appointment.AllDayEvent, x.Element("AllDayEvent").Value == "0"?false:true); // Assert.AreEqual(appointment.IsRecurring, x.Element("IsRecurring").Value=="0"?false:true);no need to check recurring events in sync. Assert.AreEqual(appointment.Location, x.Element("Location").Value); Assert.AreEqual(((int)appointment.MeetingStatus).ToString(), x.Element("MeetingStatus").Value); Assert.AreEqual(appointment.Mileage, x.Element("Mileage").Value); Assert.AreEqual(appointment.ReminderMinutesBeforeStart.ToString(), x.Element("ReminderMinutesBeforeStart").Value); Assert.AreEqual(appointment.ReminderSet, x.Element("ReminderSet").Value == "0"?false:true); Assert.AreEqual(appointment.ReminderSoundFile, x.Element("ReminderSoundFile").Value); Assert.AreEqual(DataUtility.DateTimeToIsoText(appointment.ReplyTime.ToUniversalTime()), x.Element("ReplyTime").Value); // Assert.AreEqual(((int)appointment.Sensitivity).ToString(), x.Element("Sensitivity").Value); if (appointment.IsRecurring) { Microsoft.Office.Interop.Outlook.RecurrencePattern pattern = appointment.GetRecurrencePattern(); Assert.AreEqual(pattern.Interval.ToString(), x.Element("Interval").Value); Assert.AreEqual(pattern.MonthOfYear.ToString(), x.Element("MonthOfYear").Value); Assert.AreEqual(pattern.DayOfMonth.ToString(), x.Element("DayOfMonth").Value); Assert.AreEqual(((int)pattern.DayOfWeekMask).ToString(), x.Element("DayOfWeekMask").Value); Assert.AreEqual(pattern.Instance.ToString(), x.Element("Instance").Value); Assert.AreEqual(DataUtility.DateTimeToIsoText(pattern.PatternStartDate), x.Element("PatternStartDate").Value); Assert.AreEqual(DataUtility.DateTimeToIsoText(pattern.PatternEndDate), x.Element("PatternEndDate").Value); Assert.AreEqual(pattern.NoEndDate, x.Element("NoEndDate").Value == "0" ? false : true); // Assert.AreEqual(pattern.Occurrences.ToString(), x.Element("Occurrences").Value); no need to test } else { Assert.AreEqual(appointment.Start.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"), x.Element("Start").Value); Assert.AreEqual(appointment.End.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"), x.Element("End").Value); } }
public void TestReplaceTasks() { Application app = new ApplicationClass(); OutlookTasksWithSifT agent = new OutlookTasksWithSifT(app); OutlookTasks outlookAgent = new OutlookTasks(app); TestAddTasks(); string existingEntryId = outlookAgent.GetEntryIdByDisplayName(subject); XElement x = XElement.Load(MockPath + "SifT.xml"); string entryId = agent.ReplaceItem(x.ToString(), existingEntryId); Assert.AreEqual(entryId, existingEntryId); //Compare added item with SIFT.xml TaskItem task = outlookAgent.GetItemByEntryId(entryId); Assert.AreEqual(task.Body, x.Element("Body").Value); Assert.AreEqual(task.Categories, x.Element("Categories").Value); Assert.AreEqual(task.Companies, x.Element("Companies").Value); Assert.AreEqual(((int)task.Importance).ToString(), x.Element("Importance").Value); Assert.AreEqual(task.Complete, x.Element("Complete").Value == "0" ? false : true); Assert.AreEqual(DataUtility.DateTimeToIsoText(task.DueDate), x.Element("DueDate").Value); Assert.AreEqual(task.BillingInformation, x.Element("BillingInformation").Value); Assert.AreEqual(task.ActualWork.ToString(), x.Element("ActualWork").Value); Assert.AreEqual(task.IsRecurring, x.Element("IsRecurring").Value == "0" ? false : true); Assert.AreEqual(task.Mileage, x.Element("Mileage").Value); Assert.AreEqual(task.PercentComplete.ToString(), x.Element("PercentComplete").Value); Assert.AreEqual(task.ReminderSet, x.Element("ReminderSet").Value == "0" ? false : true); Assert.AreEqual(DataUtility.DateTimeToIsoText(task.ReminderTime.ToUniversalTime()), x.Element("ReminderTime").Value); Assert.AreEqual(((int)task.Sensitivity).ToString(), x.Element("Sensitivity").Value); // Assert.AreEqual(DataUtility.DateTimeToISOText(task.StartDate), x.Element("StartDate").Value); StartDate may be altered by PatternStartDate and RecurrencePattern Assert.AreEqual(((int)task.Status).ToString(), x.Element("Status").Value); Assert.AreEqual(task.Subject, x.Element("Subject").Value); Assert.AreEqual(task.TeamTask, x.Element("TeamTask").Value == "0" ? false : true); Assert.AreEqual(task.TotalWork.ToString(), x.Element("TotalWork").Value); if (task.IsRecurring) { Microsoft.Office.Interop.Outlook.RecurrencePattern pattern = task.GetRecurrencePattern(); Assert.AreEqual(pattern.Interval.ToString(), x.Element("Interval").Value); Assert.AreEqual(pattern.MonthOfYear.ToString(), x.Element("MonthOfYear").Value); Assert.AreEqual(pattern.DayOfMonth.ToString(), x.Element("DayOfMonth").Value); Assert.AreEqual(((int)pattern.DayOfWeekMask).ToString(), x.Element("DayOfWeekMask").Value); Assert.AreEqual(pattern.Instance.ToString(), x.Element("Instance").Value); Assert.AreEqual(DataUtility.DateTimeToIsoText(pattern.PatternStartDate), x.Element("PatternStartDate").Value); Assert.AreEqual(DataUtility.DateTimeToIsoText(pattern.PatternEndDate), x.Element("PatternEndDate").Value); Assert.AreEqual(pattern.NoEndDate, x.Element("NoEndDate").Value == "0" ? false : true); // Assert.AreEqual(pattern.Occurrences.ToString(), x.Element("Occurrences").Value); no need to test } }
private void CreateRecurringTask() { Outlook.TaskItem task = Application.CreateItem( Outlook.OlItemType.olTaskItem) as Outlook.TaskItem; task.Subject = "Tax Preparation"; task.StartDate = DateTime.Parse("4/1/2007 8:00 AM"); task.DueDate = DateTime.Parse("4/15/2007 8:00 AM"); Outlook.RecurrencePattern pattern = task.GetRecurrencePattern(); pattern.RecurrenceType = Outlook.OlRecurrenceType.olRecursYearly; pattern.PatternStartDate = DateTime.Parse("4/1/2007"); pattern.NoEndDate = true; task.ReminderSet = true; task.ReminderTime = DateTime.Parse("4/1/2007 8:00 AM"); task.Save(); }
/// <summary> /// Sets recurrence exceptions in direction Google -> Outlook /// </summary> /// <param name="googleItem">Source Google event</param> /// <param name="outlookItem">Target Outlook event</param> private void SetRecurrenceExceptions(Event googleItem, object outlookItem) { //if (!this._googleExceptions.ContainsKey(googleItem.Id)) // return; ((Outlook.AppointmentItem)outlookItem).Save(); Outlook.RecurrencePattern outlookRecurrence = ((Outlook.AppointmentItem)outlookItem).GetRecurrencePattern(); try { if (this._googleExceptions.ContainsKey(googleItem.Id)) { foreach (Event googleException in this._googleExceptions[googleItem.Id]) { /// If the exception is already in Outlook event this one is omited //if (RecurrenceExceptionComparer.Contains(outlookRecurrence.Exceptions, googleException)) // continue; /// Get occurence of the recurrence and modify it. Thus new exception is created Outlook.AppointmentItem outlookExceptionItem = outlookRecurrence.GetOccurrence(googleException.OriginalStartTime.DateTime.Value); try { if (googleException.Status == "cancelled") { outlookExceptionItem.Delete(); } else { this.SetSubject(googleException, outlookExceptionItem, Target.Outlook); this.SetDescription(googleException, outlookExceptionItem, Target.Outlook); this.SetLocation(googleException, outlookExceptionItem, Target.Outlook); this.SetTime(googleException, outlookExceptionItem, Target.Outlook); outlookExceptionItem.Save(); } } finally { Marshal.ReleaseComObject(outlookExceptionItem); } } } } finally { Marshal.ReleaseComObject(outlookRecurrence); } }
// <Snippet1> private void ThisAddIn_Startup(object sender, System.EventArgs e) { Outlook.MAPIFolder calendar = Application.Session.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderCalendar); Outlook.Items calendarItems = calendar.Items; Outlook.AppointmentItem item = calendarItems["Test Appointment"] as Outlook.AppointmentItem; Outlook.RecurrencePattern pattern = item.GetRecurrencePattern(); Outlook.AppointmentItem itemDelete = pattern. GetOccurrence(new DateTime(2006, 6, 28, 8, 0, 0)); if (itemDelete != null) { itemDelete.Delete(); } }
/// <summary> /// Imports the items in Outlook calendar folder of current user /// </summary> public ServiceResult <OutlookItemImportServiceResult> ImportOutlookCalendarItems() { Outlook.Application outlookApp = null; Outlook.NameSpace mapiNamespace = null; Outlook.MAPIFolder CalendarFolder = null; Outlook.Items outlookCalendarItems = null; var messages = new List <Message>(); var countOfFailedReminderSchedules = 0; // try to initialize Outlook API and log on try { outlookApp = new Outlook.Application(); mapiNamespace = outlookApp.GetNamespace("MAPI"); CalendarFolder = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); mapiNamespace.Logon(Missing.Value, Missing.Value, true, true); } catch (Exception ex) { messages.Add(new Message() { Text = string.Format("Neparedzēta kļūda. ", ex.Message), Severity = MessageSeverity.Error }); } //build a filter from user inputs String filter = String.Format("([Start] >= '{0:g}') AND ([End] <= '{1:g}')", IntervalStart, IntervalEnd); //get the filtered Outlook items including the recurring items and sort them to expand the recurrences automatically outlookCalendarItems = CalendarFolder.Items.Restrict(filter); outlookCalendarItems.Sort("[Start]"); outlookCalendarItems.IncludeRecurrences = true; //if there are no items in the calendar folder within the specified interval, return and notify the user if (outlookCalendarItems.GetFirst() == null) { var message = "Norādītajā laika periodā Jūsu Outlook kalendārā netika atrasts neviens uzdevums"; return(new ServiceResult <OutlookItemImportServiceResult>() { Data = OutlookItemImportServiceResult.NotImported, Messages = new Message[] { new Message() { Text = message, Severity = MessageSeverity.Info } } }); } //iterate through each returned Outlook calendar item and process it foreach (Outlook.AppointmentItem item in outlookCalendarItems) { var existingWorkItem = this.dataContext.WorkItems.Where(o => o.OutlookEntryId != null && o.OutlookEntryId == item.EntryID).FirstOrDefault(); //if item is not recurring, create a new work item or update an exisiting one if (!item.IsRecurring) { if (existingWorkItem == null) { var workItem = CreateNonRecurringWorkItem(item); this.dataContext.WorkItems.Add(workItem); countOfFailedReminderSchedules += ScheduleReminder(workItem); } else { if (existingWorkItem.UpdatedAt <= item.LastModificationTime) { UpdateNonRecurringWorkItem(existingWorkItem, item); countOfFailedReminderSchedules += ScheduleReminder(existingWorkItem); } } this.dataContext.SaveChanges(); } else if (item.IsRecurring) { Outlook.RecurrencePattern recurrencePattern = item.GetRecurrencePattern(); RecurrenceType recurrenceType = 0; //Get all the exceptions in the series of this recurring item, e.g. items which belong to a series of occurrences, but whose properties have been changed List <Outlook.Exception> exceptions = new List <Outlook.Exception>(); foreach (Outlook.Exception exception in recurrencePattern.Exceptions) { exceptions.Add(exception); } int recurTypeId = (int)recurrencePattern.RecurrenceType; bool hasEndDate; if (recurrencePattern.NoEndDate == true) { hasEndDate = false; } else { hasEndDate = true; } //determine the recurrence type of the item switch (recurTypeId) { case 0: recurrenceType = RecurrenceType.Daily; break; case 1: recurrenceType = RecurrenceType.Weekly; break; case 2: recurrenceType = RecurrenceType.Monthly; break; case 3: recurrenceType = RecurrenceType.MonthNth; break; case 4: recurrenceType = RecurrenceType.Yearly; break; case 6: recurrenceType = RecurrenceType.YearNth; break; default: break; } if (existingWorkItem == null) { //Create a new work item that will act as a parent for all of its recurring items var workItem = new WorkItem(); //if recurrence pattern has end date we save it, //else we assume the end date is the end of the year to avoid large data sets if (hasEndDate == true) { workItem.EndDateTime = recurrencePattern.PatternEndDate; } else { workItem.EndDateTime = new DateTime(DateTime.Now.Year, 12, 31); } workItem.Subject = item.Parent.Subject; workItem.Location = item.Parent.Location; workItem.Body = item.Parent.Body; workItem.OutlookEntryId = item.Parent.EntryID; workItem.StartDateTime = recurrencePattern.PatternStartDate; workItem.Duration = item.Parent.Duration / 60; workItem.WorkItemType = WorkItemType.Appointment; workItem.isRecurring = true; //add the recurrence pattern workItem.RecurrencePattern = new WIRecurrencePattern { Interval = recurrencePattern.Interval, DayOfWeekMask = (DayOfWeekMask)Enum.ToObject(typeof(DayOfWeekMask), recurrencePattern.DayOfWeekMask), DayOfMonth = recurrencePattern.DayOfMonth, MonthOfYear = (MonthOfYear)Enum.ToObject(typeof(MonthOfYear), recurrencePattern.MonthOfYear), Instance = (Instance)Enum.ToObject(typeof(Instance), recurrencePattern.Instance) }; //add the recurring item workItem.RecurringItems = new List <RecurringItem>(); workItem.RecurringItems.Add(new RecurringItem { OriginalDate = item.Start, Start = item.Start, End = item.End, Duration = (item.End - item.Start).TotalHours, Origin = this.CurrentUser.BaseLocation, Subject = item.Subject, Body = item.Body, Location = item.Location, UpdatedAt = DateTime.Now }); countOfFailedReminderSchedules += ScheduleReminder(workItem, workItem.RecurringItems.FirstOrDefault()); workItem.RecurrenceType = recurrenceType; workItem.CreatedByUserId = this.CurrentUser.UserId; workItem.UpdatedByUserId = this.CurrentUser.UserId; this.dataContext.WorkItems.Add(workItem); this.dataContext.SaveChanges(); } else { //Check if recurrence pattern has not changed var existingPattern = existingWorkItem.RecurrencePattern; int mismatch = 0; if (existingPattern.Interval != recurrencePattern.Interval) { mismatch = 1; } if ((int)existingPattern.DayOfWeekMask != (int)recurrencePattern.DayOfWeekMask) { mismatch = 1; } if ((int)existingPattern.Instance != recurrencePattern.Instance) { mismatch = 1; } if (existingPattern.DayOfMonth != recurrencePattern.DayOfMonth) { mismatch = 1; } if ((int)existingPattern.MonthOfYear != recurrencePattern.MonthOfYear) { mismatch = 1; } if (mismatch == 1) { //if the pattern has changed delete all of the old recurring items, save the new pattern and asociate it with the work item foreach (var recurringItem in existingWorkItem.RecurringItems.ToList()) { this.dataContext.RecurringItems.Remove(recurringItem); var jobId = this.scheduler.GetJobId(existingWorkItem, recurringItem); scheduler.RemoveReminder(jobId); } this.dataContext.WIRecurrencePatterns.Remove(existingPattern); existingWorkItem.RecurrencePattern = new WIRecurrencePattern { Interval = recurrencePattern.Interval, DayOfWeekMask = (DayOfWeekMask)Enum.ToObject(typeof(DayOfWeekMask), recurrencePattern.MonthOfYear), DayOfMonth = recurrencePattern.DayOfMonth, MonthOfYear = (MonthOfYear)Enum.ToObject(typeof(MonthOfYear), recurrencePattern.MonthOfYear), Instance = (Instance)Enum.ToObject(typeof(Instance), recurrencePattern.MonthOfYear) }; } else { //if pattern hasn`t changed maybe the time span of the pattern has changed, if so, update the datetime values and remove unnecessary recurring items if (recurrencePattern.PatternStartDate != existingWorkItem.StartDateTime || recurrencePattern.PatternEndDate != existingWorkItem.EndDateTime) { foreach (var recurringItem in existingWorkItem.RecurringItems .Where(o => o.Start <recurrencePattern.PatternStartDate || o.End> recurrencePattern.PatternEndDate) .ToList()) { this.dataContext.RecurringItems.Remove(recurringItem); var jobId = this.scheduler.GetJobId(existingWorkItem, recurringItem); scheduler.RemoveReminder(jobId); } existingWorkItem.StartDateTime = recurrencePattern.PatternStartDate; existingWorkItem.StartDateTime = recurrencePattern.PatternEndDate; } } // we only need to look at the exceptions that are not deleted var nonDeletedException = exceptions.Where(o => o.Deleted == true).ToList(); var exception = nonDeletedException.Find(o => o.AppointmentItem.Start == item.Start); if (exception != null) { var existingRecurringItem = this.dataContext.RecurringItems.Where(o => o.OriginalDate == exception.OriginalDate).FirstOrDefault(); if (existingRecurringItem != null) { UpdateRecurringItem(existingRecurringItem, item); countOfFailedReminderSchedules += ScheduleReminder(existingRecurringItem.WorkItem, existingRecurringItem); } else { existingWorkItem.RecurringItems.Add(new RecurringItem { OriginalDate = item.Start, Exception = true, Start = item.Start, End = item.End, Subject = item.Subject, Body = item.Body, Location = item.Location, UpdatedAt = DateTime.Now }); countOfFailedReminderSchedules += ScheduleReminder(existingWorkItem, existingWorkItem.RecurringItems.FirstOrDefault()); } } else { var existingRecurringItem = existingWorkItem.RecurringItems.Where(o => o.OriginalDate == item.Start).FirstOrDefault(); if (existingRecurringItem == null) { existingWorkItem.RecurringItems.Add(new RecurringItem { OriginalDate = item.Start, Exception = false, Start = item.Start, End = item.End, Subject = item.Subject, Body = item.Body, Location = item.Location, UpdatedAt = DateTime.Now }); countOfFailedReminderSchedules += ScheduleReminder(existingWorkItem, existingWorkItem.RecurringItems.FirstOrDefault()); } else { UpdateRecurringItem(existingRecurringItem, item); countOfFailedReminderSchedules += ScheduleReminder(existingRecurringItem.WorkItem, existingRecurringItem); } } this.dataContext.SaveChanges(); } } } //Log off mapiNamespace.Logoff(); if (countOfFailedReminderSchedules > 0) { messages.Add(new Message() { Text = string.Format("{0} no importētajiem uzdevumiem netika ieplānoti atgādinājumi, jo šajā procesā rādās kļūdas", countOfFailedReminderSchedules.ToString()), Severity = MessageSeverity.Warning }); } var result = new ServiceResult <OutlookItemImportServiceResult>(); result.Messages = messages.ToArray(); if (messages.Any(m => m.Severity == MessageSeverity.Error)) { result.Data = OutlookItemImportServiceResult.Error; } else if (messages.Any(m => m.Severity == MessageSeverity.Warning)) { result.Data = OutlookItemImportServiceResult.OkWithWarnings; } else { result.Data = OutlookItemImportServiceResult.Ok; } return(result); }
public bool CalendarItemConvertRecurrences() { try { bool ConvertedAny = false; #region var DateTime checkLast_At = DateTime.Parse(sqlController.SettingRead(Settings.checkLast_At)); double checkPreSend_Hours = double.Parse(sqlController.SettingRead(Settings.checkPreSend_Hours)); double checkRetrace_Hours = double.Parse(sqlController.SettingRead(Settings.checkRetrace_Hours)); int checkEvery_Mins = int.Parse(sqlController.SettingRead(Settings.checkEvery_Mins)); bool includeBlankLocations = bool.Parse(sqlController.SettingRead(Settings.includeBlankLocations)); DateTime timeOfRun = DateTime.Now; DateTime tLimitTo = timeOfRun.AddHours(+checkPreSend_Hours); DateTime tLimitFrom = checkLast_At.AddHours(-checkRetrace_Hours); #endregion #region convert recurrences foreach (Outlook.AppointmentItem item in GetCalendarItems(tLimitTo, tLimitFrom)) { if (item.IsRecurring) //is recurring, otherwise ignore { #region location "planned"? string location = item.Location; if (location == null) { if (includeBlankLocations) { location = "planned"; } else { location = ""; } } location = location.ToLower(); #endregion if (location == "planned") #region ... { Outlook.RecurrencePattern rp = item.GetRecurrencePattern(); Outlook.AppointmentItem recur = null; DateTime startPoint = item.Start; while (startPoint.AddYears(1) <= tLimitFrom) { startPoint = startPoint.AddYears(1); } while (startPoint.AddMonths(1) <= tLimitFrom) { startPoint = startPoint.AddMonths(1); } while (startPoint.AddDays(1) <= tLimitFrom) { startPoint = startPoint.AddDays(1); } for (DateTime testPoint = startPoint; testPoint <= tLimitTo; testPoint = testPoint.AddMinutes(checkEvery_Mins)) //KEY POINT { if (testPoint >= tLimitFrom) { try { recur = rp.GetOccurrence(testPoint); try { Appointment appo_Dto = new Appointment(recur.GlobalAppointmentID, recur.Start, item.Duration, recur.Subject, recur.Location, recur.Body, t.Bool(sqlController.SettingRead(Settings.colorsRule)), false, sqlController.Lookup); appo_Dto = CreateAppointment(appo_Dto); recur.Delete(); log.LogStandard("Not Specified", recur.GlobalAppointmentID + " / " + recur.Start + " converted to non-recurence appointment"); } catch (Exception ex) { log.LogWarning("Not Specified", t.PrintException(t.GetMethodName() + " failed. The OutlookController will keep the Expection contained", ex)); } ConvertedAny = true; } catch { } } } } #endregion } } #endregion if (ConvertedAny) { log.LogStandard("Not Specified", t.GetMethodName() + " completed + converted appointment(s)"); } else { log.LogEverything("Not Specified", t.GetMethodName() + " completed"); } return(ConvertedAny); } catch (Exception ex) { throw new Exception(t.GetMethodName() + " failed", ex); } }
/// <summary> /// Sets recurrence exceptions in direction Outlook -> Google /// </summary> /// <param name="outlookItem">Source Outlook event</param> /// <param name="googleItem">Target Google event</param> private void SetRecurrenceExceptions(Outlook.AppointmentItem outlookItem, Event googleItem) { if (!outlookItem.IsRecurring) { return; } Outlook.RecurrencePattern outlookRecurrence = outlookItem.GetRecurrencePattern(); var instancesRequest = this.CalendarService.Events.Instances(this._googleCalendar.Id, googleItem.Id); instancesRequest.ShowDeleted = true; var instances = instancesRequest.Execute().Items; var exceptions = instances.Where(i => i.Status == "cancelled" || i.OriginalStartTime.DateTime != i.Start.DateTime); try { foreach (Outlook.Exception outlookException in outlookRecurrence.Exceptions) { try { /// If the exception is already in Google event this one is omited if (RecurrenceExceptionComparer.Contains(exceptions, outlookException)) { continue; } //googleItem.RecurrenceException = new Google.GData.Extensions.RecurrenceException(); Event googleException; if (outlookException.Deleted) { googleException = instances.First(e => (e.OriginalStartTime.DateTime ?? DateTime.Parse(e.OriginalStartTime.Date)).Date == outlookException.OriginalDate); googleException.Status = "cancelled"; } else { googleException = instances.First(e => (e.OriginalStartTime.DateTime ?? DateTime.Parse(e.OriginalStartTime.Date)) == outlookException.OriginalDate); googleException.Status = "confirmed"; this.SetSubject(googleException, outlookException.AppointmentItem, Target.Google); this.SetDescription(googleException, outlookException.AppointmentItem, Target.Google); this.SetLocation(googleException, outlookException.AppointmentItem, Target.Google); this.SetTime(googleException, outlookException.AppointmentItem, Target.Google); } /// Add exception to update batch this._googleBatchRequest.Queue <Event>(this.CalendarService.Events.Update( googleException, this._googleCalendar.Id, googleException.Id), BatchCallback); } catch (COMException exc) { if (exc.HResult == -1802485755) { Logger.Log(string.Format( "The exception of '{0}' with original start time {1} couldn't be read. Ignoring this exception", outlookItem.Subject, outlookException.OriginalDate), EventType.Warning); } } finally { Marshal.ReleaseComObject(outlookException); } } } finally { Marshal.ReleaseComObject(outlookRecurrence); } }
/// <summary> /// Adds the attributes to an AppointmentItem /// </summary> /// <param name="calEvent">The event of a specific calendar</param> /// <param name="subject">Title of the event</param> /// <param name="startDate">Start date of the event</param> /// <param name="recurrenceType">Recurrence type</param> /// <param name="endDate">End date for the recurrence</param> /// <param name="duration">Duration of the event</param> /// <param name="recipients">Recipients for the event</param> /// <returns>returns the filled in event so that it can be saved and sent from outlook</returns> internal static Outlook.AppointmentItem CreateEvent(Outlook.AppointmentItem calEvent, string subject, string startDate, string recurrenceType, string endDate, string duration, string[] recipients) { string methodTag = "CreateEvent"; LogWriter.WriteInfo(TAG, methodTag, "Starting: " + methodTag + " in " + TAG); Outlook.RecurrencePattern recurrPatt = null; if (calEvent != null) { calEvent.MeetingStatus = Outlook.OlMeetingStatus.olMeeting; calEvent.Sensitivity = Outlook.OlSensitivity.olNormal; if (subject != null) { calEvent.Subject = subject; LogWriter.WriteInfo(TAG, methodTag, "Subject set to: " + subject); } else { LogWriter.WriteWarning(TAG, methodTag, "Subject is null, may cause failures when searching for it"); } if (startDate != null) { calEvent.Start = DateTime.Parse(startDate); LogWriter.WriteInfo(TAG, methodTag, "Start date set to: " + startDate); } else { LogWriter.WriteInfo(TAG, methodTag, "No start date provided, using default of the next closest hour"); LogWriter.WriteWarning(TAG, methodTag, "No start date provided, may cause failures when searching for it"); } if (duration != null) { calEvent.Duration = Convert.ToInt32(duration); LogWriter.WriteInfo(TAG, methodTag, "Duration set to: " + duration); } else { LogWriter.WriteInfo(TAG, methodTag, "No duration provided, using default of 30 minutes"); } if (recurrenceType != null) { recurrPatt = calEvent.GetRecurrencePattern(); if (endDate != null) { recurrPatt.PatternEndDate = DateTime.ParseExact(endDate, "M/d/yyyy", null); LogWriter.WriteInfo(TAG, methodTag, "End date of recurrence set to: " + endDate); } else { LogWriter.WriteWarning(TAG, methodTag, "Recurrence date not set, infinite recurrence may cause problems when searching"); } if (recurrenceType == "Daily") { recurrPatt.RecurrenceType = Outlook.OlRecurrenceType.olRecursDaily; } else if (recurrenceType == "Weekly") { recurrPatt.RecurrenceType = Outlook.OlRecurrenceType.olRecursWeekly; } else if (recurrenceType == "Monthly") { recurrPatt.RecurrenceType = Outlook.OlRecurrenceType.olRecursMonthly; } else if (recurrenceType == "Yearly") { recurrPatt.RecurrenceType = Outlook.OlRecurrenceType.olRecursYearly; } LogWriter.WriteInfo(TAG, methodTag, "Recurrence type set to: " + recurrenceType); } foreach (String contact in recipients) { calEvent.Recipients.Add(contact); LogWriter.WriteInfo(TAG, methodTag, "Adding recipient: " + contact + " to meeting invite"); } } else { LogWriter.WriteWarning(TAG, methodTag, "Calendar event is null, unable to continue with creating event"); throw new NullReferenceException(); } return(calEvent); }
/// <summary> /// Updates the attributes of a specific event /// </summary> /// <param name="calEvent">Event to be updated</param> /// <param name="eventDate">Date of the specific event to be updated M/d/yyyy hh:mm:ss tt</param> /// <param name="updatedTitle">Updated title if desired</param> /// <param name="updatedStartDate">Updated start date if desired</param> /// <param name="updatedDuration">Updated duration if desired</param> /// <param name="recipients">Additonal recipients if desired</param> /// <returns></returns> internal static Outlook.AppointmentItem UpdateEvent(Outlook.AppointmentItem calEvent, string eventDate, string updatedTitle, string updatedStartDate, string updatedDuration, string[] recipients) { string methodTag = "UpdateEvent"; LogWriter.WriteInfo(TAG, methodTag, "Starting: " + methodTag + " in " + TAG); Outlook.AppointmentItem agendaMeeting = null; Outlook.RecurrencePattern recurrPatt = null; if (calEvent != null) { if (eventDate != null) { LogWriter.WriteInfo(TAG, methodTag, "Obtaining specific event on date: " + eventDate + " with title: " + calEvent.Subject); recurrPatt = calEvent.GetRecurrencePattern(); agendaMeeting = recurrPatt.GetOccurrence(DateTime.Parse(eventDate)); } else { LogWriter.WriteWarning(TAG, methodTag, "No event date specified, may cause issues finding event if it is a recurring event"); agendaMeeting = calEvent; } if (updatedTitle != null) { LogWriter.WriteInfo(TAG, methodTag, "Updating the events title to: " + updatedTitle); agendaMeeting.Subject = updatedTitle; } else { LogWriter.WriteInfo(TAG, methodTag, "No updated subject specified, keeping subject the same"); } if (updatedDuration != null) { LogWriter.WriteInfo(TAG, methodTag, "Updating the events duration to: " + updatedDuration); agendaMeeting.Duration = Convert.ToInt32(updatedDuration); } else { LogWriter.WriteInfo(TAG, methodTag, "Updated duration not specified, keepign duration the same"); } foreach (String contact in recipients) { agendaMeeting.Recipients.Add(contact); LogWriter.WriteInfo(TAG, methodTag, "Adding recipient: " + contact + " to meeting invite"); } if (updatedStartDate != null) { LogWriter.WriteInfo(TAG, methodTag, "Updating the events start date to: " + updatedStartDate); agendaMeeting.Start = DateTime.Parse(updatedStartDate); } else { LogWriter.WriteInfo(TAG, methodTag, "Updated start date not specified, keeping start date the same"); } agendaMeeting.Save(); LogWriter.WriteInfo(TAG, methodTag, "Event updated sucessfully"); } else { LogWriter.WriteWarning(TAG, methodTag, "Calendar event is null, unable to continue with update event"); throw new NullReferenceException(); } return(agendaMeeting); }
public OLCalItem(Outlook.AppointmentItem calItem) { this.calItem = calItem; if (calItem.IsRecurring) pattern = calItem.GetRecurrencePattern (); }
private List <AppointmentInfo> LoadAllData() { List <AppointmentInfo> allData = new List <AppointmentInfo>(); Log.Write($"allData cleared."); try { foreach (var folder in AllMAPIFolders) { Log.Write($"LoadAllData: {folder.Folder.FullFolderPath}"); try { SetStatus(folder.ToString(), 0); Items items = folder.Folder.Items; if (items == null) { Log.Write($"LoadAllData: Items in folder {folder.Folder.FullFolderPath} is null!"); } items.IncludeRecurrences = true; Log.Write($"LoadAllData: Total {items.Count} items"); int n = 0; int lastProgress = 0; int p = 0; foreach (var item in items) { n += 1; p = 100 * n / items.Count; if (p != lastProgress) { SetStatus(null, p); lastProgress = p; } AppointmentItem ai = item as AppointmentItem; if (ai == null) { continue; } //Log.Write($"LoadAllData: Processing item {n} - {ai.Subject}"); if (ai.Sensitivity != 0) { // Log.Write("Skipping private event"); continue; } if (ai.IsRecurring) { // Log.Write($"LoadAllData: {ai.Subject} is recurring..."); Microsoft.Office.Interop.Outlook.RecurrencePattern rp = ai.GetRecurrencePattern(); Microsoft.Office.Interop.Outlook.AppointmentItem recur = null; for (DateTime cur = monthCalendar1.SelectionStart.AddHours(ai.Start.Hour).AddMinutes(ai.Start.Minute); cur < monthCalendar2.SelectionStart.AddDays(1); cur = cur.AddDays(1)) { try { recur = rp.GetOccurrence(cur); //Log.Write($"LoadAllData: Adding occurence of recurring item {ai.Subject} for date {cur}"); allData.Add(new AppointmentInfo(recur, folder)); } catch { } } } else { if ((ai.Start >= monthCalendar1.SelectionStart) && (ai.End < monthCalendar2.SelectionStart.AddDays(1))) { //Log.Write($"LoadAllData: Adding item {ai.Subject}"); allData.Add(new AppointmentInfo(ai, folder)); } else { //Log.Write($"LoadAllData: {ai.Subject} is out of date frame, continuing..."); continue; } } } } catch (System.Exception ex) { Log.Write($"[EXCEPTION] Nastala výjimka při zpracování složky {folder.Folder.Name}:\r\n {ex.Message}"); MessageBox.Show($"Nastala výjimka při zpracování složky {folder.Folder.Name}:\r\n {ex.Message}", "Výjimka", MessageBoxButtons.OK); } finally { folder.WasProcessed = true; } } } finally { SetStatus("Načteno", -1); } return(allData); }
private static void ProcessFolder(Outlook.Folder folder, List <HeadsUpItem> returnItems) { Console.WriteLine(folder.Name); DateTime now = DateTime.Now; // Set end value DateTime lookAhead = now.AddDays(7); // Initial restriction is Jet query for date range string timeSlotFilter = "[Start] >= '" + now.ToString("g") + "' AND [Start] <= '" + lookAhead.ToString("g") + "'"; Outlook.Items items = folder.Items; items.Sort("[Start]"); items.IncludeRecurrences = true; items = items.Restrict(timeSlotFilter); foreach (object item in items) { Outlook.AppointmentItem appointment = item as Outlook.AppointmentItem; Outlook.TaskItem task = item as Outlook.TaskItem; if (appointment != null) { HeadsUpItem newItem = new HeadsUpItem(); newItem.Title = appointment.Subject; newItem.Start = appointment.Start; newItem.End = appointment.End; newItem.Location = appointment.Location; newItem.Ignorable = true; Outlook.RecurrencePattern pattern = appointment.GetRecurrencePattern(); if (appointment.RecurrenceState == Outlook.OlRecurrenceState.olApptOccurrence && pattern.RecurrenceType == Outlook.OlRecurrenceType.olRecursWeekly) { Console.WriteLine(" Ignore:" + appointment.Subject); } else { newItem.Ignorable = false; Console.WriteLine(" A: " + appointment.Subject); Console.WriteLine(" S: " + appointment.Start.ToString("g")); Console.WriteLine(" E: " + appointment.End.ToString("g")); } returnItems.Add(newItem); } else if (task != null) { Console.WriteLine(" T: " + task.Subject); } else { Console.WriteLine(" ERR: Unknown Type: " + item.GetType()); } } foreach (Outlook.Folder subFolder in folder.Folders) { ProcessFolder(subFolder, returnItems); } }