/// <summary> /// Detects paste events in order to remove OGCS properties from pasted item. /// /// However, the clipboard is a reference to the copied item /// and the pasted object is not available yet until AFTER this function! /// We can't short-circuit the paste event by setting "Cancel = true" and performing the Copy() /// because it pastes to the same DateTime as the copied item. /// In Outlook2010 the (Explorer.View as CalendarView).SelectedStartTime exists, but not in 2007, /// so there's no way of knowing the time to paste the item in to. /// /// So the workaround is to temporarily doctor the original copied item (ie remove OGCS properties), /// which the pasted item inherits. A delayed background thread then post-processes the original item /// to revert any changes and repopulate values. /// </summary> private void beforeItemPaste(ref object ClipboardContent, MAPIFolder Target, ref bool Cancel) { log.Info("Item paste event caught."); try { Selection selection = ClipboardContent as Selection; if (selection == null) { log.Warn("Clipboard selection returned nothing."); return; } log.Debug("We've got " + selection.Count + " items selected for copy."); foreach (Object item in selection) { AppointmentItem copiedAi = null; try { if (item is AppointmentItem) { copiedAi = item as AppointmentItem; } else { throw new ApplicationException("The item is not an appointment item."); } log.Debug(OutlookOgcs.Calendar.GetEventSummary(copiedAi)); String entryID = copiedAi.EntryID; if (OutlookOgcs.CustomProperty.Exists(copiedAi, OutlookOgcs.CustomProperty.MetadataId.gEventID)) { Dictionary <String, object> propertyBackup = cleanIDs(ref copiedAi); OutlookOgcs.CustomProperty.Add(ref copiedAi, CustomProperty.MetadataId.originalStartDate, copiedAi.Start); copiedAi.Save(); System.Threading.Thread repopIDsThrd = new System.Threading.Thread(() => repopulateIDs(entryID, propertyBackup)); repopIDsThrd.Start(); } else { log.Debug("This item isn't managed by OGCS."); //But we still need to tag the pasted item as a "copied" item to avoid bad matches on Google events. OutlookOgcs.CustomProperty.Add(ref copiedAi, OutlookOgcs.CustomProperty.MetadataId.locallyCopied, true.ToString()); copiedAi.Save(); //Untag the original copied item System.Threading.Thread untagAsCopiedThrd = new System.Threading.Thread(() => untagAsCopied(entryID)); untagAsCopiedThrd.Start(); } } catch (System.ApplicationException ex) { log.Debug(ex.Message); } catch (System.Exception ex) { log.Warn("Not able to process copy and pasted event."); OGCSexception.Analyse(ex); } finally { copiedAi = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(copiedAi); } } } catch (System.Exception ex) { OGCSexception.Analyse(ex); } }
private void processOutlookExceptions(AppointmentItem ai, Event ev, Boolean forceCompare) { if (!HasExceptions(ev, checkLocalCacheOnly: true)) { return; } if (!ai.Saved) { ai.Save(); } RecurrencePattern oPattern = ai.GetRecurrencePattern(); foreach (Event gExcp in Recurrence.Instance.googleExceptions.Where(exp => exp.RecurringEventId == ev.Id)) { log.Fine("Found Google exception for " + (gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date)); DateTime oExcpDate = DateTime.Parse(gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date); AppointmentItem newAiExcp = getOutlookInstance(oPattern, oExcpDate); if (newAiExcp == null) { continue; } if (gExcp.Status != "cancelled") { int itemModified = 0; newAiExcp = OutlookCalendar.Instance.UpdateCalendarEntry(newAiExcp, gExcp, ref itemModified, forceCompare); if (itemModified > 0) { try { newAiExcp.Save(); } catch (System.Exception ex) { log.Warn(ex.Message); if (ex.Message == "Cannot save this item.") { MainForm.Instance.Logboxout("Uh oh! Outlook wasn't able to save this recurrence exception! " + "You may have two occurences on the same day, which it doesn't allow."); } } } } else { MainForm.Instance.Logboxout(OutlookCalendar.GetEventSummary(ai) + "\r\nDeleted."); newAiExcp.Delete(); } newAiExcp = (AppointmentItem)OutlookCalendar.ReleaseObject(newAiExcp); } if (!ai.Saved) { ai.Save(); } oPattern = (RecurrencePattern)OutlookCalendar.ReleaseObject(oPattern); }
private static void SyncSprintToOutlook(Sprint sprint, AppointmentItem appointment) { bool modified = false; if (appointment.Start.Date != sprint.StartDate.Date) { appointment.Start = sprint.StartDate; modified = true; } if (appointment.End.Date != sprint.EndDate.Date) { appointment.End = sprint.EndDate; modified = true; } String sprintName = getSprintAppointmentName(sprint); if (!sprintName.Equals(appointment.Subject)) { appointment.Subject = sprintName; modified = true; } if (modified) { appointment.Save(); } }
private void processOutlookExceptions(ref AppointmentItem ai, Event ev, Boolean forceCompare) { if (!HasExceptions(ev, checkLocalCacheOnly: true)) { return; } RecurrencePattern oPattern = null; try { oPattern = ai.GetRecurrencePattern(); foreach (Event gExcp in Recurrence.Instance.googleExceptions.Where(exp => exp.RecurringEventId == ev.Id)) { DateTime oExcpDate = gExcp.OriginalStartTime.DateTime ?? DateTime.Parse(gExcp.OriginalStartTime.Date); log.Fine("Found Google exception for " + oExcpDate.ToString()); AppointmentItem newAiExcp = null; try { getOutlookInstance(oPattern, oExcpDate, ref newAiExcp); if (newAiExcp == null) { continue; } if (gExcp.Status == "cancelled") { Forms.Main.Instance.Console.Update(OutlookOgcs.Calendar.GetEventSummary(newAiExcp) + "<br/>Deleted.", Console.Markup.calendar); newAiExcp.Delete(); } else if (Settings.Instance.ExcludeDeclinedInvites && gExcp.Attendees != null && gExcp.Attendees.Count(a => a.Self == true && a.ResponseStatus == "declined") == 1) { Forms.Main.Instance.Console.Update(OutlookOgcs.Calendar.GetEventSummary(newAiExcp) + "<br/>Declined.", Console.Markup.calendar); newAiExcp.Delete(); } else { int itemModified = 0; OutlookOgcs.Calendar.Instance.UpdateCalendarEntry(ref newAiExcp, gExcp, ref itemModified, forceCompare); if (itemModified > 0) { try { newAiExcp.Save(); } catch (System.Exception ex) { OGCSexception.Analyse(ex); if (ex.Message == "Cannot save this item.") { Forms.Main.Instance.Console.Update("Uh oh! Outlook wasn't able to save this recurrence exception! " + "You may have two occurences on the same day, which it doesn't allow.", Console.Markup.warning); } } } } } finally { newAiExcp = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(newAiExcp); } } } finally { oPattern = (RecurrencePattern)OutlookOgcs.Calendar.ReleaseObject(oPattern); } }
public void OnFitToBoundariesClick(Office.IRibbonControl control) { AppointmentItem selectedAppointment = GetSelectedAppointments(control).FirstOrDefault(); // Ensure selected appointment is eligible to be fitted if (selectedAppointment == null || selectedAppointment.Conflicts.Count > 0 || selectedAppointment.Start.Date != selectedAppointment.End.Date) { return; } // Determine predecessor & successor appointments (if any that day) var(predecessor, successor) = Calendar.GetSurroundingAppointmentsTheSameDay(selectedAppointment); // Set new appointment start time (if a predecessor was found that day) if (predecessor != null) { int newDuration = (int)(selectedAppointment.End - predecessor.End).TotalMinutes; selectedAppointment.Start = predecessor.End; selectedAppointment.Duration = newDuration; } // Set new appointment end time (if a sucessor was found that day) if (successor != null) { selectedAppointment.End = successor.Start; } selectedAppointment.Save(); }
/// <summary> /// Mark the item as not copied /// </summary> /// <param name="item">The appointment item</param> public static void MarkAsNotCopied(this AppointmentItem item) { var field = OutlookHelper.CreateOrGetProperty(item, Constants.FieldEntryIdCopy, OlUserPropertyType.olText); field.Value = item.EntryID; item.Save(); }
private Dictionary <OutlookOgcs.Calendar.MetadataId, object> cleanIDs(ref AppointmentItem copiedAi) { log.Info("Temporarily removing OGCS properties from copied Outlook appointment item."); Dictionary <OutlookOgcs.Calendar.MetadataId, object> propertyBackup = new Dictionary <OutlookOgcs.Calendar.MetadataId, object>(); try { object backupValue = null; foreach (OutlookOgcs.Calendar.MetadataId metaDataId in Enum.GetValues(typeof(OutlookOgcs.Calendar.MetadataId))) { log.Fine("Backing up " + metaDataId.ToString()); if (metaDataId == OutlookOgcs.Calendar.MetadataId.ogcsModified) { backupValue = OutlookOgcs.Calendar.GetOGCSlastModified(copiedAi); } else { backupValue = OutlookOgcs.Calendar.GetOGCSproperty(copiedAi, metaDataId); } propertyBackup.Add(metaDataId, backupValue); } OutlookOgcs.Calendar.RemoveOGCSproperties(ref copiedAi); OutlookOgcs.Calendar.AddOGCSproperty(ref copiedAi, OutlookOgcs.Calendar.MetadataId.locallyCopied, true.ToString()); copiedAi.Save(); } catch (System.Exception ex) { log.Warn("Failed to clean OGCS properties from copied item."); OGCSexception.Analyse(ex); } return(propertyBackup); }
private void processOutlookExceptions(AppointmentItem ai, Event ev, Boolean forceCompare) { if (!HasExceptions(ev, checkLocalCacheOnly: true)) { return; } if (!ai.Saved) { ai.Save(); } RecurrencePattern oPattern = ai.GetRecurrencePattern(); foreach (Event gExcp in Recurrence.Instance.googleExceptions.Where(exp => exp.RecurringEventId == ev.Id)) { log.Fine("Found Google exception for " + (gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date)); DateTime oExcpDate = DateTime.Parse(gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date); AppointmentItem newAiExcp = getOutlookInstance(oPattern, oExcpDate); if (newAiExcp == null) { continue; } if (gExcp.Status != "cancelled") { int itemModified = 0; newAiExcp = OutlookCalendar.Instance.UpdateCalendarEntry(newAiExcp, gExcp, ref itemModified, forceCompare); if (itemModified > 0) { newAiExcp.Save(); } } else { MainForm.Instance.Logboxout(OutlookCalendar.GetEventSummary(ai) + "\r\nDeleted."); newAiExcp.Delete(); } newAiExcp = (AppointmentItem)OutlookCalendar.ReleaseObject(newAiExcp); } if (!ai.Saved) { ai.Save(); } oPattern = (RecurrencePattern)OutlookCalendar.ReleaseObject(oPattern); }
public static void UpdateTaskCalendar(TaskItem item, DateTime dtStart, DateTime dtEnd) { try { 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; // find exists calender item. AppointmentItem oAppointment = null; string strBody = string.Format("OneNoteTaskID:\t{0}\r\nOneNoteURL:\t{1}\\{2}\\{3}" , item.TaskOneNoteId , item.NoteBookName , item.SectionName , item.PageName); //string filter = "[Start] >= '2016/6/19' and [Subject]='"+ item.TaskName + "'"; // 查找最近30分钟之内的上次同一个任务 string filter = "[Subject]='" + item.TaskName + "'" + " and " + "[End] >= '" + dtStart.AddMinutes(-30).ToString("yyyy/M/d H:mm") + "'"; oAppointment = outlookCalendarItems.Find(filter); if (oAppointment != null) { if (!oAppointment.Body.Contains(string.Format("OneNoteTaskID:\t{0}", item.TaskOneNoteId))) { oAppointment = null; } //if (dtStart > oAppointment.End.AddMinutes(30)) //{ // oAppointment = null; //} } if (oAppointment == null) { oAppointment = (AppointmentItem)outlookApp.CreateItem(OlItemType.olAppointmentItem); oAppointment.Start = dtStart; oAppointment.Body = strBody; oAppointment.Subject = item.TaskName; } oAppointment.End = dtEnd; oAppointment.ReminderSet = false; oAppointment.ReminderPlaySound = false; oAppointment.Importance = OlImportance.olImportanceNormal; oAppointment.BusyStatus = OlBusyStatus.olBusy; oAppointment.Categories = item.TaskClass.Name; //This method save the appointment to the outlook oAppointment.Save(); } catch (System.Exception e) { } }
private void updateCalendarEntry_save(AppointmentItem ai) { if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional) { log.Debug("Saving timestamp when OGCS updated appointment."); AddOGCSproperty(ref ai, Program.OGCSmodified, DateTime.Now); } ai.Save(); }
//https://www.codeproject.com/Tips/84321/Setting-up-an-MS-Outlook-Appointment-C public static void AjouterCalendrier(DeploiementModel deploiement, DateTime date) { Application outlookApp = new Application(); // creates new outlook app AppointmentItem oAppointment = (AppointmentItem)outlookApp.CreateItem(OlItemType.olAppointmentItem); // creates a new oAppointment.Subject = "Déploiement " + deploiement.Composant.Nom + ""; // set the subject oAppointment.Start = Convert.ToDateTime(date); // Set the start date oAppointment.End = Convert.ToDateTime(date.AddHours(1)); // End date oAppointment.ReminderSet = true; // Set the reminder oAppointment.ReminderMinutesBeforeStart = 15; // reminder time oAppointment.BusyStatus = OlBusyStatus.olBusy; oAppointment.Save(); }
private static void DisassociateAppointment(AppointmentItem appointment) { if (appointment.UserProperties["MJ-MRBS-ID"] != null) { appointment.UserProperties["MJ-MRBS-ID"].Delete(); if (appointment.Body.Contains("*****")) { appointment.Body = appointment.Body.Substring(0, appointment.Body.IndexOf("*****")) + appointment.Body.Substring(appointment.Body.LastIndexOf("*****") + 5); } appointment.Save(); } }
/// <summary> /// Add a new event or Update the appropriate event in the calendar. /// </summary> /// <param name="eventExists">if set to <c>true</c> the event exists.</param> /// <param name="queuePosition">The queue position.</param> /// <param name="lastSkillInQueue">if set to <c>true</c> skill is the last in queue.</param> internal override Task AddOrUpdateEventAsync(bool eventExists, int queuePosition, bool lastSkillInQueue) => TaskHelper.RunIOBoundTaskAsync(() => { AppointmentItem eventItem = eventExists ? (AppointmentItem)Events[0] : (AppointmentItem)s_mapiFolder.Items.Add(OlItemType.olAppointmentItem); eventItem.Subject = Subject; eventItem.Start = StartDate; eventItem.End = EndDate; string queuePositionText = lastSkillInQueue ? "End Of Queue" : queuePosition.ToString(CultureConstants.DefaultCulture); eventItem.Body = eventExists ? $"{eventItem.Body} {Environment.NewLine}Updated: {DateTime.Now} Queue Position: {queuePositionText}" : $"Added: {DateTime.Now} Queue Position: {queuePositionText}"; eventItem.ReminderSet = ItemReminder || AlternateReminder; eventItem.BusyStatus = OlBusyStatus.olBusy; eventItem.AllDayEvent = false; eventItem.Location = String.Empty; if (AlternateReminder) { EarlyReminder = new DateTime(StartDate.Year, StartDate.Month, StartDate.Day, EarlyReminder.Hour, EarlyReminder.Minute, EarlyReminder.Second); LateReminder = new DateTime(StartDate.Year, StartDate.Month, StartDate.Day, LateReminder.Hour, LateReminder.Minute, LateReminder.Second); DateTime dateTimeAlternateReminder = WorkOutAlternateReminders(); // Subtract the reminder time from the event time TimeSpan timeSpan = eventItem.Start.Subtract(dateTimeAlternateReminder); eventItem.ReminderMinutesBeforeStart = Math.Abs(timeSpan.Hours * 60 + timeSpan.Minutes); Minutes = eventItem.ReminderMinutesBeforeStart; } eventItem.ReminderMinutesBeforeStart = eventItem.ReminderSet ? Minutes : 0; eventItem.Save(); });
public AppointmentItem updateEntry(AppointmentItem ai, Event e, bool add_description, bool add_reminders, bool add_attendees) { ModifyEvent(ai, e, add_description, add_reminders, add_attendees); try { // save the outlook event ai.Save(); } catch (System.Exception) { // unable to save the outlook item... // should report an error, but this will get handled by the main form... } return(ai); }
/// <summary> /// Returns a syncronization id for a given appointment. If there is no syncronization id, a new one will be /// created and saved to outlook. If saving the appointment does fail because of authorization, NO exception /// will be thrown. /// </summary> /// <param name="outlookAppointment"> /// the outlook appointment to handle /// </param> /// <param name="appointmentList"> /// The appointment List to lookup duplicates. /// </param> /// <returns> /// the corresponding Guid /// </returns> private static Guid GetStandardAppointmentId( AppointmentItem outlookAppointment, IEnumerable <StdCalendarItem> appointmentList) { if (outlookAppointment == null) { throw new ArgumentNullException("outlookAppointment"); } var newId = Guid.NewGuid(); try { // try to read the contact id property - generate one if it's not there var contactIdObject = outlookAppointment.UserProperties[AppointmentIdOutlookPropertyName] ?? outlookAppointment.UserProperties.Add( ContactIdOutlookPropertyName, OlUserPropertyType.olText, true, OlFormatText.olFormatTextText); // test if the value is a valid id if (contactIdObject.Value.ToString().Length != 36) { // use the formerly generated id if the one from outlook is not valid contactIdObject.Value = newId.ToString(); outlookAppointment.Save(); } // finally read the id from the property newId = new Guid(contactIdObject.Value.ToString()); } catch (UnauthorizedAccessException) { // if we are not authorized to write back the id, we will assume a new id } var guid = newId; if (appointmentList != null && appointmentList.Where(x => x.Id == guid).Count() > 0) { newId = Guid.NewGuid(); } return(newId); }
/// <summary> /// Syncs the outlook calendar item. /// </summary> /// <param name="outlookCalendarItem">The outlook calendar item.</param> /// <param name="googleCalendarItems">The google calendar items.</param> private void SyncOutlookCalendarItem(AppointmentItem outlookCalendarItem, IEnumerable <EventEntry> googleCalendarItems) { var mergeables = googleCalendarItems.Mergeable(outlookCalendarItem).ToList(); EventEntry googleCalendarItem; if (mergeables.Any()) { googleCalendarItem = mergeables.First(); var changed = googleCalendarItem.MergeWith(outlookCalendarItem); try { if (changed) { googleCalendarItem = this.Repository.GoogleData.CalendarService.Update(googleCalendarItem); } } catch (GDataRequestException ex) { var response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode != HttpStatusCode.Conflict) { // TODO: Add functionality to resolve update conflict. throw; } } } else { googleCalendarItem = new EventEntry(); var changed = googleCalendarItem.MergeWith(outlookCalendarItem); if (changed) { googleCalendarItem = this.Repository.GoogleData.CalendarService.Insert(ApplicationData.GoogleCalendarUri, googleCalendarItem); } } var outlookChanged = outlookCalendarItem.UserProperties.SetProperty("GoogleId", googleCalendarItem.EventId); if (outlookChanged) { outlookCalendarItem.Save(); } }
private static void SyncMilestoneToOutlook(Milestone milestone, AppointmentItem appointment) { bool modified = false; if ((appointment.Start.Date != milestone.GetStartDate().Date) || (appointment.End.Date != milestone.GetEndDate().Date)) { appointment.Start = milestone.GetStartDate(); appointment.End = milestone.GetEndDate(); modified = true; } String milestoneName = getMilestoneAppointmentName(milestone); if (!milestoneName.Equals(appointment.Subject)) { appointment.Subject = milestoneName; modified = true; } MilestoneDataContainer notificationData = getMilestoneData(milestone); if (notificationData.ReminderMinutesBeforeStart == 0 && appointment.ReminderSet) { appointment.ReminderSet = false; modified = true; } if (notificationData.ReminderMinutesBeforeStart != appointment.ReminderMinutesBeforeStart) { appointment.ReminderSet = true; appointment.ReminderMinutesBeforeStart = notificationData.ReminderMinutesBeforeStart; modified = true; } if (!String.IsNullOrEmpty(notificationData.Category) && (appointment.Categories == null || !appointment.Categories.Contains(notificationData.Category))) { appointment.Categories = appointment.Categories + notificationData.Category; modified = true; } if (modified) { appointment.Save(); } }
public AppointmentItem addEntry(Event e, bool add_description, bool add_reminders, bool add_attendees) { AppointmentItem result = null; try { result = (AppointmentItem)OutlookApplication.CreateItem(OlItemType.olAppointmentItem); ModifyEvent(result, e, add_description, add_reminders, add_attendees); result.Save(); } catch (System.Exception ex) { throw ex; } return(result); }
private void repopulateIDs(String entryID, Dictionary <OutlookOgcs.Calendar.MetadataId, object> propertyValues) { //Allow time for pasted item to complete System.Threading.Thread.Sleep(2000); log.Debug("Repopulating IDs to original copied Outlook item"); AppointmentItem copiedAi = null; try { OutlookOgcs.Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out copiedAi); if (copiedAi == null) { throw new System.Exception("Could not find Outlook item with entryID " + entryID + " for post-processing."); } log.Debug(OutlookOgcs.Calendar.GetEventSummary(copiedAi)); foreach (KeyValuePair <OutlookOgcs.Calendar.MetadataId, object> property in propertyValues) { if (property.Value == null) { OutlookOgcs.Calendar.RemoveOGCSproperty(ref copiedAi, property.Key); } else { if (property.Value is DateTime) { OutlookOgcs.Calendar.AddOGCSproperty(ref copiedAi, property.Key, (DateTime)property.Value); } else { OutlookOgcs.Calendar.AddOGCSproperty(ref copiedAi, property.Key, property.Value.ToString()); } } } copiedAi.Save(); } catch (System.Exception ex) { log.Warn("Failed to repopulate OGCS properties back to copied item."); OGCSexception.Analyse(ex); } finally { copiedAi = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(copiedAi); } }
// binds the two events together public static void BindEvents(AppointmentItem oitem, Event gitem, string event_property_key) { // make sure to tag the user property of the google id UserProperty oitem_google_prop = oitem.UserProperties.Find(event_property_key); if (oitem_google_prop != null) { oitem_google_prop.Value = gitem.Id; System.Runtime.InteropServices.Marshal.ReleaseComObject(oitem_google_prop); } else { oitem.UserProperties.Add(event_property_key, OlUserPropertyType.olText).Value = gitem.Id; } try { // save the outlook event oitem.Save(); } catch (System.Exception) { // unable to save the outlook item... // should report an error, but this will get handled by the main form... } // make sure to tag the private property of the outlook id if (gitem.ExtendedProperties == null) { gitem.ExtendedProperties = new Event.ExtendedPropertiesData(); gitem.ExtendedProperties.Shared = new Dictionary <string, string>(); } else if (gitem.ExtendedProperties.Shared == null) { gitem.ExtendedProperties.Shared = new Dictionary <string, string>(); } gitem.ExtendedProperties.Shared[event_property_key] = OutlookCalendar.FormatEventID(oitem); }
/// <summary> /// Добавление Событий в календарь /// </summary> /// <param name="listItem">список событий</param> public static void AddItemCalendar(List <ItemCalendar> listItem) { SettingsContext sContext = new SettingsContext(); Application Application = null; Application = new Application(); MAPIFolder primaryCalendar = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); // if (!IsExistsWorkCalendar()) // { // CreateNewCalendar(sContext.Settings.NameCalendar); // } //var personalCalendar = primaryCalendar.Folders[sContext.Settings.NameCalendar]; //if (personalCalendar == null) return; foreach (var item in listItem) { AppointmentItem newEvent = primaryCalendar.Items.Add(OlItemType.olAppointmentItem) as AppointmentItem; if (newEvent != null) { newEvent.Start = item.StartDateTime; newEvent.End = item.EndDateTime; //newEvent.AllDayEvent = true; if (item.IsReminded) { newEvent.ReminderMinutesBeforeStart = item.ReminderMinute; newEvent.ReminderPlaySound = true; } else { newEvent.ReminderSet = false; } newEvent.Subject = item.Title; newEvent.Body = item.Body; newEvent.Save(); } } Application.ActiveExplorer().CurrentFolder.Display(); }
private Dictionary <String, object> cleanIDs(ref AppointmentItem copiedAi) { log.Info("Temporarily removing OGCS properties from copied Outlook appointment item."); Dictionary <String, object> propertyBackup = new Dictionary <String, object>(); UserProperties ups = null; try { object backupValue = null; ups = copiedAi.UserProperties; for (int p = 1; p <= ups.Count; p++) { UserProperty up = null; try { up = ups[p]; String metaDataId = up.Name; log.Fine("Backing up " + metaDataId.ToString()); backupValue = up.Value; if (backupValue == null || (backupValue is DateTime time && time == new DateTime())) { continue; } log.Fine("Property value: " + backupValue); propertyBackup.Add(metaDataId, backupValue); } finally { up = (UserProperty)OutlookOgcs.Calendar.ReleaseObject(up); } } OutlookOgcs.CustomProperty.RemoveAll(ref copiedAi); OutlookOgcs.CustomProperty.Add(ref copiedAi, OutlookOgcs.CustomProperty.MetadataId.locallyCopied, true.ToString()); copiedAi.Save(); } catch (System.Exception ex) { log.Warn("Failed to clean OGCS properties from copied item."); OGCSexception.Analyse(ex); } finally { ups = (UserProperties)OutlookOgcs.Calendar.ReleaseObject(ups); } return(propertyBackup); }
/// <summary> /// Method that checks the previous state of an appointment and tries to reset that state. /// </summary> /// <param name="item">The appointment for which to set the previous state.</param> public static void ResetPreviousState(this AppointmentItem item) { var previousState = item.GetAppointmentCustomId(Constants.FieldAppointmentPreviousState); if (!previousState.HasValue) { return; } var state = AppointmentState.AllStates.FirstOrDefault(s => s.Value == previousState.Value); if (state == null) { return; } if (state == AppointmentState.Synchronized) { Log.Warn(string.Format("Appointment state set to synchronized. #{0} Previus state: {1}", item.GetIssueId(), item.Categories)); } item.SetAppointmentState(state); item.Save(); }
public string OutLookEvent(eAppointment appointment, Boolean SendMail) { try { Application outlookapp = new Application(); AppointmentItem agendaMeeting = (AppointmentItem)outlookapp.CreateItem(OlItemType.olAppointmentItem); if (agendaMeeting != null) { agendaMeeting.MeetingStatus = appointment.MeetingStatus; agendaMeeting.Location = appointment.Location; agendaMeeting.Subject = appointment.Subject; agendaMeeting.Body = appointment.Body; agendaMeeting.Start = appointment.Start; agendaMeeting.Duration = appointment.Duration; // save the appointment agendaMeeting.Save(); if (SendMail) { Recipient recipient = null; foreach (var mails in appointment.Email) { recipient = agendaMeeting.Recipients.Add(mails); } recipient.Type = (int)OlMeetingRecipientType.olRequired; try { ((_AppointmentItem)agendaMeeting).Send(); return("Success"); } catch (System.Exception ex) { return("Fail"); } } } } catch (System.Exception ex) { } return(string.Empty); }
private static void createCalendarEntry_save(AppointmentItem ai, Event ev) { if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional) { log.Debug("Saving timestamp when OGCS updated appointment."); AddOGCSproperty(ref ai, Program.OGCSmodified, DateTime.Now); } ai.Save(); Boolean oKeyExists = false; try { oKeyExists = ev.ExtendedProperties.Private.ContainsKey(GoogleCalendar.oEntryID); } catch {} if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional || oKeyExists) { log.Debug("Storing the Outlook appointment ID in Google event."); GoogleCalendar.AddOutlookID(ref ev, ai, Environment.MachineName); GoogleCalendar.Instance.UpdateCalendarEntry_save(ev); } }
private void untagAsCopied(String entryID) { //Allow time for pasted item to complete System.Threading.Thread.Sleep(2000); log.Debug("Untagging copied Outlook item"); AppointmentItem copiedAi = null; try { OutlookOgcs.Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out copiedAi); if (copiedAi == null) { throw new System.Exception("Could not find Outlook item with entryID " + entryID + " for post-processing."); } log.Debug(OutlookOgcs.Calendar.GetEventSummary(copiedAi)); UserProperties ups = null; UserProperty prop = null; try { String propertyName = OutlookOgcs.CustomProperty.MetadataId.locallyCopied.ToString(); ups = copiedAi.UserProperties; prop = ups.Find(propertyName); if (prop != null) { prop.Delete(); log.Debug("Removed " + propertyName + " property."); } } finally { prop = (UserProperty)Calendar.ReleaseObject(prop); ups = (UserProperties)Calendar.ReleaseObject(ups); } copiedAi.Save(); } catch (System.Exception ex) { log.Warn("Failed to remove OGCS 'copied' property on copied item."); OGCSexception.Analyse(ex); } finally { copiedAi = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(copiedAi); } }
private void repopulateIDs(String entryID, Dictionary <String, object> propertyValues) { //Allow time for pasted item to complete System.Threading.Thread.Sleep(2000); log.Debug("Repopulating IDs to original copied Outlook item"); AppointmentItem copiedAi = null; try { untagAsCopied(entryID); OutlookOgcs.Calendar.Instance.IOutlook.GetAppointmentByID(entryID, out copiedAi); if (copiedAi == null) { throw new System.Exception("Could not find Outlook item with entryID " + entryID + " for post-processing."); } log.Debug(OutlookOgcs.Calendar.GetEventSummary(copiedAi)); foreach (KeyValuePair <String, object> property in propertyValues) { if (property.Value is DateTime) { addOutlookCustomProperty(ref copiedAi, property.Key, OlUserPropertyType.olDateTime, property.Value); } else { addOutlookCustomProperty(ref copiedAi, property.Key, OlUserPropertyType.olText, property.Value); } } log.Fine("Restored properties:-"); OutlookOgcs.CustomProperty.LogProperties(copiedAi, log4net.Core.Level.Debug); copiedAi.Save(); } catch (System.Exception ex) { log.Warn("Failed to repopulate OGCS properties back to copied item."); OGCSexception.Analyse(ex); } finally { copiedAi = (AppointmentItem)OutlookOgcs.Calendar.ReleaseObject(copiedAi); } }
static void addEvent(Options opts) { assertRequired("Subject", opts.Subject); assertRequired("Start date", opts.StartDate); Application outlookApp = new Application(); AppointmentItem oAppointment = (AppointmentItem)outlookApp.CreateItem(OlItemType.olAppointmentItem); oAppointment.Subject = opts.Subject; oAppointment.Body = opts.Body; oAppointment.Start = getFullTime(opts.StartDate, opts.StartTime); if (!string.IsNullOrEmpty(opts.EndTime)) { oAppointment.End = getFullTime(opts.StartDate, opts.EndTime); } else { oAppointment.AllDayEvent = true; } oAppointment.ReminderSet = true; oAppointment.ReminderMinutesBeforeStart = 15; oAppointment.Sensitivity = OlSensitivity.olPrivate; oAppointment.BusyStatus = OlBusyStatus.olFree; oAppointment.Location = opts.Location; if (opts.DryRun) { Console.WriteLine("Would create event:"); Console.WriteLine(apptToString(oAppointment)); } else { oAppointment.Save(); } }
static void Main(string[] args) { ApplicationClass application = new ApplicationClass(); NameSpace nspace = application.GetNamespace("MAPI"); nspace.Logon(Missing.Value, Missing.Value, false, false); object objappointment = application.CreateItem(OlItemType.olAppointmentItem); if (objappointment != null) { AppointmentItem appointment = (AppointmentItem)objappointment; appointment.Importance = OlImportance.olImportanceHigh; appointment.Subject = "watch tv"; appointment.Body = "Не забудь посмотреть телевизор!"; appointment.Start = DateTime.Parse("1-1-2006 11:00 am"); appointment.End = DateTime.Parse("1-1-2006 1:00 pm"); appointment.Location = "Диван"; appointment.ReminderSet = true; appointment.ReminderMinutesBeforeStart = 60; appointment.AllDayEvent = false; appointment.Save(); appointment = null; } nspace.Logoff(); nspace = null; application.Quit(); application = null; Console.ReadLine(); }
public static void AddItemCalendar(List <BirthdayItem> listItem, int hour_begin, int min_begin, int duration, int remind_min) { Application Application = null; Application = new Application(); MAPIFolder primaryCalendar = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar); foreach (var item in listItem) { //var personalCalendar = primaryCalendar.Folders["Birthday"]; //if (personalCalendar == null) return; AppointmentItem newEvent = primaryCalendar.Items.Add(OlItemType.olAppointmentItem) as AppointmentItem; //AppointmentItem newEvent = personalCalendar.Items.Add(OlItemType.olAppointmentItem) as AppointmentItem; if (newEvent != null) { var date = new DateTime(DateTime.Now.Year, item.Birthday.Month, item.Birthday.Day, hour_begin, min_begin, 0); newEvent.Start = date; //newEvent.End = item.EndDateTime; var recur = newEvent.GetRecurrencePattern(); recur.RecurrenceType = OlRecurrenceType.olRecursYearly; recur.PatternStartDate = date; recur.StartTime = date; recur.Duration = duration; recur.NoEndDate = true; //recur.EndTime = DateTime.Now.AddMinutes(10); newEvent.ReminderMinutesBeforeStart = remind_min; newEvent.Subject = $"[B] День рождения {item.Name}"; newEvent.Body = $"День рождения {item.Name}. Дата рождения {item.Birthday:d}"; newEvent.Save(); AddProcProgressBar?.Invoke(null, null); } } Application.ActiveExplorer().CurrentFolder.Display(); }
private void updateCalendarEntry_save(AppointmentItem ai) { if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional) { log.Debug("Saving timestamp when OGCS updated appointment."); setOGCSlastModified(ref ai); } ai.Save(); }
/// <summary> /// Syncs the outlook calendar item. /// </summary> /// <param name="outlookCalendarItem">The outlook calendar item.</param> /// <param name="googleCalendarItems">The google calendar items.</param> private void SyncOutlookCalendarItem(AppointmentItem outlookCalendarItem, IEnumerable<EventEntry> googleCalendarItems) { var mergeables = googleCalendarItems.Mergeable(outlookCalendarItem).ToList(); EventEntry googleCalendarItem; if (mergeables.Any()) { googleCalendarItem = mergeables.First(); var changed = googleCalendarItem.MergeWith(outlookCalendarItem); try { if (changed) googleCalendarItem = this.Repository.GoogleData.CalendarService.Update(googleCalendarItem); } catch (GDataRequestException ex) { var response = ex.Response as HttpWebResponse; if (response != null && response.StatusCode != HttpStatusCode.Conflict) { // TODO: Add functionality to resolve update conflict. throw; } } } else { googleCalendarItem = new EventEntry(); var changed = googleCalendarItem.MergeWith(outlookCalendarItem); if (changed) googleCalendarItem = this.Repository.GoogleData.CalendarService.Insert(ApplicationData.GoogleCalendarUri, googleCalendarItem); } var outlookChanged = outlookCalendarItem.UserProperties.SetProperty("GoogleId", googleCalendarItem.EventId); if (outlookChanged) outlookCalendarItem.Save(); }
private bool UpdateAppointment(bool addDescription, bool addReminder, bool addAttendees, bool attendeesToDescription, AppointmentItem appItem, Appointment calendarAppointment) { Recipients recipients = null; UserProperties userProperties = null; try { appItem.Subject = calendarAppointment.Subject; appItem.Location = calendarAppointment.Location; appItem.BusyStatus = calendarAppointment.GetOutlookBusyStatus(); if (EventCategory != null) { appItem.Categories = EventCategory.CategoryName; } if (calendarAppointment.AllDayEvent != appItem.AllDayEvent) { appItem.AllDayEvent = calendarAppointment.AllDayEvent; } appItem.Sensitivity = calendarAppointment.GetAppointmentSensitivity(); appItem.Start = calendarAppointment.StartTime.GetValueOrDefault(); appItem.End = calendarAppointment.EndTime.GetValueOrDefault(); if (addDescription) { appItem.Body = calendarAppointment.Description; } if (addAttendees && !attendeesToDescription) { recipients = appItem.Recipients; if (calendarAppointment.RequiredAttendees != null) { calendarAppointment.RequiredAttendees.ForEach(rcptName => { if (!CheckIfRecipientExists(recipients, rcptName)) { var recipient = appItem.Recipients.Add($"{rcptName.Name}<{rcptName.Email}>"); recipient.Type = (int) OlMeetingRecipientType.olRequired; recipient.Resolve(); } }); } if (calendarAppointment.OptionalAttendees != null) { calendarAppointment.OptionalAttendees.ForEach(rcptName => { if (!CheckIfRecipientExists(recipients, rcptName)) { var recipient = appItem.Recipients.Add($"{rcptName.Name}<{rcptName.Email}>"); recipient.Type = (int) OlMeetingRecipientType.olOptional; recipient.Resolve(); } }); } } if (addReminder) { if (appItem.ReminderSet != calendarAppointment.ReminderSet) { appItem.ReminderMinutesBeforeStart = calendarAppointment.ReminderMinutesBeforeStart; if (calendarAppointment.ReminderSet && appItem.ReminderMinutesBeforeStart != calendarAppointment.ReminderMinutesBeforeStart) { appItem.ReminderMinutesBeforeStart = calendarAppointment.ReminderMinutesBeforeStart; } } } userProperties = appItem.UserProperties; if (userProperties != null) { for (var i = 0; i < userProperties.Count; i++) { userProperties.Remove(i + 1); } foreach (var extendedProperty in calendarAppointment.ExtendedProperties) { var sourceProperty = userProperties.Add(extendedProperty.Key, OlUserPropertyType.olText); sourceProperty.Value = extendedProperty.Value; } } appItem.Save(); } catch (Exception exception) { Logger.Error(exception); return false; } finally { if (recipients != null) { Marshal.FinalReleaseComObject(recipients); } if (userProperties != null) { Marshal.FinalReleaseComObject(userProperties); } if (appItem != null) { Marshal.FinalReleaseComObject(appItem); } } return true; }
/// <summary> /// </summary> /// <param name="addDescription"></param> /// <param name="addReminder"></param> /// <param name="addAttendees"></param> /// <param name="attendeesToDescription"></param> /// <param name="appItem"></param> /// <param name="calendarAppointment"></param> private Appointment AddAppointment(bool addDescription, bool addReminder, bool addAttendees, bool attendeesToDescription, AppointmentItem appItem, Appointment calendarAppointment, string id) { Recipients recipients = null; UserProperties userProperties = null; Appointment createdAppointment = null; try { appItem.Subject = calendarAppointment.Subject; if (!calendarAppointment.RequiredAttendees.Any() && !calendarAppointment.OptionalAttendees.Any() && AddAsAppointments) { appItem.MeetingStatus = OlMeetingStatus.olNonMeeting; } else { appItem.MeetingStatus = OlMeetingStatus.olMeeting; } appItem.Sensitivity = calendarAppointment.GetAppointmentSensitivity(); appItem.Location = calendarAppointment.Location; appItem.BusyStatus = calendarAppointment.GetOutlookBusyStatus(); recipients = appItem.Recipients; if (EventCategory != null) { appItem.Categories = EventCategory.CategoryName; } if (calendarAppointment.AllDayEvent) { appItem.AllDayEvent = true; } appItem.Start = calendarAppointment.StartTime.GetValueOrDefault(); appItem.End = calendarAppointment.EndTime.GetValueOrDefault(); appItem.Body = calendarAppointment.GetDescriptionData(addDescription, attendeesToDescription); Recipient organizer = null; if (addAttendees && !attendeesToDescription) { calendarAppointment.RequiredAttendees?.ForEach(rcptName => { var recipient = appItem.Recipients.Add($"{rcptName.Name}<{rcptName.Email}>"); if (SetOrganizer && calendarAppointment.Organizer != null && rcptName.Name.Equals(calendarAppointment.Organizer.Name)) { recipient.Type = (int) OlMeetingRecipientType.olOrganizer; recipient.Resolve(); organizer = recipient; } else { recipient.Type = (int) OlMeetingRecipientType.olRequired; recipient.Resolve(); } }); calendarAppointment.OptionalAttendees?.ForEach(rcptName => { var recipient = appItem.Recipients.Add($"{rcptName.Name}<{rcptName.Email}>"); if (SetOrganizer && calendarAppointment.Organizer != null && rcptName.Name.Equals(calendarAppointment.Organizer.Name)) { recipient.Type = (int) OlMeetingRecipientType.olOrganizer; recipient.Resolve(); organizer = recipient; } else { recipient.Type = (int)OlMeetingRecipientType.olOptional; recipient.Resolve(); } }); } else if (SetOrganizer && calendarAppointment.Organizer != null) { var recipient = appItem.Recipients.Add( $"{calendarAppointment.Organizer.Name}<{calendarAppointment.Organizer.Email}>"); recipient.Type = (int)OlMeetingRecipientType.olOrganizer; recipient.Resolve(); organizer = recipient; } SetAppointmentOrganizer(appItem, organizer); if (addReminder) { appItem.ReminderMinutesBeforeStart = calendarAppointment.ReminderMinutesBeforeStart; appItem.ReminderSet = calendarAppointment.ReminderSet; } userProperties = appItem.UserProperties; if (userProperties != null) { var sourceProperty = userProperties.Add(calendarAppointment.GetSourceEntryKey(), OlUserPropertyType.olText); sourceProperty.Value = calendarAppointment.AppointmentId; } appItem.Save(); createdAppointment = GetAppointmentFromItem(id, appItem); } catch (Exception exception) { Logger.Error(exception); } finally { if (userProperties != null) { Marshal.FinalReleaseComObject(userProperties); } if (recipients != null) { Marshal.FinalReleaseComObject(recipients); } if (appItem != null) { Marshal.FinalReleaseComObject(appItem); } } return createdAppointment; }
private Event createCalendarEntry_save(Event ev, AppointmentItem ai) { if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional) { log.Debug("Saving timestamp when OGCS updated event."); setOGCSlastModified(ref ev); } if (Settings.Instance.APIlimit_inEffect) { addOGCSproperty(ref ev, Program.APIlimitHit, "True"); } Event createdEvent = new Event(); int backoff = 0; while (backoff < backoffLimit) { try { createdEvent = service.Events.Insert(ev, Settings.Instance.UseGoogleCalendar.Id).Fetch(); if (Settings.Instance.AddAttendees && Settings.Instance.APIlimit_inEffect) { log.Info("API limit for attendee sync lifted :-)"); Settings.Instance.APIlimit_inEffect = false; } break; } catch (Google.GoogleApiException ex) { switch (handleAPIlimits(ex, ev)) { case apiException.throwException: throw; case apiException.freeAPIexhausted: throw; case apiException.justContinue: break; case apiException.backoffThenRetry: { backoff++; if (backoff == backoffLimit) { log.Error("API limit backoff was not successful. Save failed."); throw; } else { log.Warn("API rate limit reached. Backing off " + backoff + "sec before retry."); System.Threading.Thread.Sleep(backoff * 1000); } break; } } } } Boolean gKeyExists = false; try { UserProperty up = ai.UserProperties.Find(OutlookCalendar.gEventID); gKeyExists = (up != null); } catch { } if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional || gKeyExists) { log.Debug("Storing the Google event ID in Outlook appointment."); OutlookCalendar.AddOGCSproperty(ref ai, OutlookCalendar.gEventID, createdEvent.Id); ai.Save(); } //DOS ourself by triggering API limit //for (int i = 1; i <= 30; i++) { // MainForm.Instance.Logboxout("Add #" + i, verbose:true); // Event result = service.Events.Insert(e, Settings.Instance.UseGoogleCalendar.Id).Fetch(); // System.Threading.Thread.Sleep(300); // GoogleCalendar.Instance.deleteCalendarEntry(result); // System.Threading.Thread.Sleep(300); //} return createdEvent; }
private void processOutlookExceptions(AppointmentItem ai, Event ev, Boolean forceCompare) { if (!HasExceptions(ev, checkLocalCacheOnly: true)) return; if (!ai.Saved) ai.Save(); RecurrencePattern oPattern = ai.GetRecurrencePattern(); foreach (Event gExcp in Recurrence.Instance.googleExceptions.Where(exp => exp.RecurringEventId == ev.Id)) { log.Fine("Found Google exception for " + (gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date)); DateTime oExcpDate = DateTime.Parse(gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date); AppointmentItem newAiExcp = getOutlookInstance(oPattern, oExcpDate); if (newAiExcp == null) continue; if (gExcp.Status != "cancelled") { int itemModified = 0; newAiExcp = OutlookCalendar.Instance.UpdateCalendarEntry(newAiExcp, gExcp, ref itemModified, forceCompare); if (itemModified > 0) { try { newAiExcp.Save(); } catch (System.Exception ex) { log.Warn(ex.Message); if (ex.Message == "Cannot save this item.") { MainForm.Instance.Logboxout("Uh oh! Outlook wasn't able to save this recurrence exception! " + "You may have two occurences on the same day, which it doesn't allow."); } } } } else { MainForm.Instance.Logboxout(OutlookCalendar.GetEventSummary(ai) + "\r\nDeleted."); newAiExcp.Delete(); } newAiExcp = (AppointmentItem)OutlookCalendar.ReleaseObject(newAiExcp); } if (!ai.Saved) ai.Save(); oPattern = (RecurrencePattern)OutlookCalendar.ReleaseObject(oPattern); }
private void processOutlookExceptions(AppointmentItem ai, Event ev, Boolean forceCompare) { if (!HasExceptions(ev, checkLocalCacheOnly: true)) return; if (!ai.Saved) ai.Save(); RecurrencePattern oPattern = ai.GetRecurrencePattern(); foreach (Event gExcp in Recurrence.Instance.googleExceptions.Where(exp => exp.RecurringEventId == ev.Id)) { log.Fine("Found Google exception for " + (gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date)); DateTime oExcpDate = DateTime.Parse(gExcp.OriginalStartTime.DateTime ?? gExcp.OriginalStartTime.Date); AppointmentItem newAiExcp = getOutlookInstance(oPattern, oExcpDate); if (newAiExcp == null) continue; if (gExcp.Status != "cancelled") { int itemModified = 0; newAiExcp = OutlookCalendar.Instance.UpdateCalendarEntry(newAiExcp, gExcp, ref itemModified, forceCompare); if (itemModified > 0) newAiExcp.Save(); } else { MainForm.Instance.Logboxout(OutlookCalendar.GetEventSummary(ai) +"\r\nDeleted."); newAiExcp.Delete(); } newAiExcp = (AppointmentItem)OutlookCalendar.ReleaseObject(newAiExcp); } if (!ai.Saved) ai.Save(); oPattern = (RecurrencePattern)OutlookCalendar.ReleaseObject(oPattern); }
private bool UpdateAppointment(bool addDescription, bool addReminder, bool addAttendees, bool attendeesToDescription, AppointmentItem appItem, Appointment calendarAppointment) { Recipients recipients = null; UserProperties userProperties = null; try { appItem.Subject = calendarAppointment.Subject; if (!calendarAppointment.RequiredAttendees.Any() && !calendarAppointment.OptionalAttendees.Any() && AddAsAppointments) { appItem.MeetingStatus = OlMeetingStatus.olNonMeeting; } else { appItem.MeetingStatus = OlMeetingStatus.olMeeting; } appItem.Location = calendarAppointment.Location; appItem.BusyStatus = calendarAppointment.GetOutlookBusyStatus(); recipients = appItem.Recipients; if (EventCategory != null) { appItem.Categories = EventCategory.CategoryName; } if (calendarAppointment.AllDayEvent) { appItem.AllDayEvent = true; } appItem.Start = calendarAppointment.StartTime.GetValueOrDefault(); appItem.End = calendarAppointment.EndTime.GetValueOrDefault(); appItem.Body = calendarAppointment.GetDescriptionData(addDescription, attendeesToDescription); if (addAttendees && !attendeesToDescription) { if (calendarAppointment.RequiredAttendees != null) { calendarAppointment.RequiredAttendees.ForEach(rcptName => { var recipient = appItem.Recipients.Add(string.Format("{0}<{1}>", rcptName.Name, rcptName.Email)); recipient.Type = (int) OlMeetingRecipientType.olRequired; recipient.Resolve(); }); } if (calendarAppointment.OptionalAttendees != null) { calendarAppointment.OptionalAttendees.ForEach(rcptName => { var recipient = appItem.Recipients.Add(string.Format("{0}<{1}>", rcptName.Name, rcptName.Email)); recipient.Type = (int) OlMeetingRecipientType.olOptional; recipient.Resolve(); }); } } if (addReminder) { appItem.ReminderMinutesBeforeStart = calendarAppointment.ReminderMinutesBeforeStart; appItem.ReminderSet = calendarAppointment.ReminderSet; } userProperties = appItem.UserProperties; if (userProperties != null) { for (var i = 0; i < userProperties.Count; i++) { userProperties.Remove(i + 1); } foreach (var extendedProperty in calendarAppointment.ExtendedProperties) { var sourceProperty = userProperties.Add(extendedProperty.Key, OlUserPropertyType.olText); sourceProperty.Value = extendedProperty.Value; } } appItem.Save(); } catch (Exception exception) { ApplicationLogger.Error(exception); return false; } finally { if (recipients != null) { Marshal.FinalReleaseComObject(recipients); } if (userProperties != null) { Marshal.FinalReleaseComObject(userProperties); } if (appItem != null) { Marshal.FinalReleaseComObject(appItem); } } return true; }
private static void createCalendarEntry_save(AppointmentItem ai, ref Event ev) { if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional) { log.Debug("Saving timestamp when OGCS updated appointment."); setOGCSlastModified(ref ai); } ai.Save(); Boolean oKeyExists = false; try { oKeyExists = ev.ExtendedProperties.Private.ContainsKey(GoogleCalendar.oEntryID); } catch {} if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional || oKeyExists) { log.Debug("Storing the Outlook appointment ID in Google event."); GoogleCalendar.AddOutlookID(ref ev, ai); GoogleCalendar.Instance.UpdateCalendarEntry_save(ref ev); } }
private static void createCalendarEntry_save(AppointmentItem ai, Event ev) { if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional) { log.Debug("Saving timestamp when OGCS updated appointment."); AddOGCSproperty(ref ai, Program.OGCSmodified, DateTime.Now); } ai.Save(); Boolean oKeyExists = false; try { oKeyExists = ev.ExtendedProperties.Private.ContainsKey(GoogleCalendar.oEntryID); } catch {} if (Settings.Instance.SyncDirection == SyncDirection.Bidirectional || oKeyExists) { log.Debug("Storing the Outlook appointment ID in Google event."); GoogleCalendar.AddOutlookID(ref ev, ai,Environment.MachineName); GoogleCalendar.Instance.UpdateCalendarEntry_save(ev); } }