public static int Main(string[] args) { try { // Create the Outlook application. Outlook.Application oApp = new Outlook.Application(); // Get the NameSpace and Logon information. // Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("mapi"); Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); //Log on by using a dialog box to choose the profile. oNS.Logon(Missing.Value, Missing.Value, true, true); //Alternate logon method that uses a specific profile. // TODO: If you use this logon method, // change the profile name to an appropriate value. //oNS.Logon("YourValidProfile", Missing.Value, false, true); // Get the Calendar folder. Outlook.MAPIFolder oCalendar = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); // Get the Items (Appointments) collection from the Calendar folder. Outlook.Items oItems = oCalendar.Items; // Get the first item. Outlook.AppointmentItem oAppt = (Outlook.AppointmentItem)oItems.GetFirst(); // Show some common properties. Console.WriteLine("Subject: " + oAppt.Subject); Console.WriteLine("Organizer: " + oAppt.Organizer); Console.WriteLine("Start: " + oAppt.Start.ToString()); Console.WriteLine("End: " + oAppt.End.ToString()); Console.WriteLine("Location: " + oAppt.Location); Console.WriteLine("Recurring: " + oAppt.IsRecurring); //Show the item to pause. oAppt.Display(true); // Done. Log off. oNS.Logoff(); // Clean up. oAppt = null; oItems = null; oCalendar = null; oNS = null; oApp = null; } //Simple error handling. catch (Exception e) { Console.WriteLine("{0} Exception caught.", e); } //Default return value return(0); }
private static bool IsDuplicateInFolder(Outlook.Folder folder, Outlook.MailItem mail) { Outlook.Items folderItems = null; Outlook.Items resultItems = null; object item = null; try { var dateFrom = mail.SentOn.AddMinutes(-SEARCH_WINDOW_MINUTES).ToString(SEARCH_DATE_FORMAT); var dateTo = mail.SentOn.AddMinutes(SEARCH_WINDOW_MINUTES).ToString(SEARCH_DATE_FORMAT); var mailId = GetMessageId(mail); var restrictCriteria = $"[SentOn] >= '{dateFrom}' And [SentOn] <= '{dateTo}'"; folderItems = folder.Items; resultItems = folderItems.Restrict(restrictCriteria); item = resultItems.GetFirst(); while (item != null) { if (item is Outlook.MailItem mailItem) { if (GetMessageId(mailItem) == mailId) { return(true); } if (mailItem.ReceivedTime == mail.ReceivedTime && mailItem.Subject == mail.Subject) { return(true); } } Marshal.ReleaseComObject(item); item = resultItems.GetNext(); } return(false); } catch (Exception) { return(false); } finally { if (item != null) { Marshal.ReleaseComObject(item); } if (folderItems != null) { Marshal.ReleaseComObject(folderItems); } if (resultItems != null) { Marshal.ReleaseComObject(resultItems); } } }
public void DoNag(Object item) { Outlook.MailItem msg = (Outlook.MailItem)item; // Blah. Creating a new mail from scratch is a problem, because if the user then replies to the AutoLottie, it doesn't // hook up. Creating a new mail using 'reply' is impossible because the one in the Lottie folder is still only a draft. // Going to try looking up the e-mail in regular sent-mail... If this works, then longer term, the approach should be // changed so that the real e-mail gets stored in the Lottie folder, introducing the requirement that mail goes to sent-mail. // Also, we can trigger the Lottie actions with a watch on sent-mail, which has a lot of other benefits. Outlook.MAPIFolder sentmail = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail); // TODO FALLS OVER WITH PUNCTUATION (like ') in the SUBJECT LINE String sFilter = "[Subject] = '" + msg.Subject + "'"; Outlook.Items sublist = sentmail.Items.Restrict(sFilter); DateTime latestSentTime = new DateTime(0); Outlook.MailItem bestFitMail = null; Outlook.MailItem messageIt = (Outlook.MailItem)sublist.GetFirst(); while (messageIt != null) { if ((((Outlook.MailItem)messageIt).ConversationID == msg.ConversationID) && (((Outlook.MailItem)messageIt).SentOn.CompareTo(latestSentTime) == 1)) { bestFitMail = (Outlook.MailItem)messageIt; latestSentTime = ((Outlook.MailItem)messageIt).SentOn; } messageIt = (Outlook.MailItem)sublist.GetNext(); } if (bestFitMail != null) { Outlook.MailItem eMail = bestFitMail.ReplyAll(); //(Outlook.MailItem)this.Application.CreateItem(Outlook.OlItemType.olMailItem); // if you change the subject, Conversation ID gets changed :-( // eMail.Subject = "[AutoLottie] " + bestFitMail.Subject; // eMail.To = msg.To; eMail.CC = bestFitMail.SenderEmailAddress; eMail.Body = "As far as my Outlook client can tell, you have not yet responded " + "to the message below. Could you do so now, please?\n\n " + "Thanks! \n\n" + "************************************************************\n\n\n" + bestFitMail.Body; eMail.Importance = Outlook.OlImportance.olImportanceNormal; Outlook.UserProperty lottieStartThreadProperty = eMail.UserProperties.Add(AutoLottieAddIn.LottieNoCancelProperty, Outlook.OlUserPropertyType.olText); lottieStartThreadProperty.Value = "True"; ((Outlook._MailItem)eMail).Send(); } // Not sure what to do here: // 1) Set the AutoLottie property so that they get nagged again in the same length of time? // 2) Remove the AutoLottie? // 3) Something random - they get nagged in double the time. I think I'll do that. :-) TimeSpan expiryTimeFromSent; TimeSpan.TryParse(msg.UserProperties[LottieDurationProperty].Value.ToString(), out expiryTimeFromSent); TimeSpan newExpiryTime = new TimeSpan(2 * expiryTimeFromSent.Days, 2 * expiryTimeFromSent.Hours, 2 * expiryTimeFromSent.Minutes, 0); UpdateTimerForMessage(msg, newExpiryTime); }
/// <summary> /// Remove synchronize keys from Outlook contact. In same delete all cache data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOutlokSync_Click(object sender, EventArgs e) { LoggerProvider.Instance.Logger.Info("User request for clear synchronize keys in Outlook. I remove all cache data for Google and Outlook."); Utils.RemoveCacheFile(false); Utils.RemoveCacheFile(true); pBar.Value = 1; pBar.Update(); pBar.Refresh(); OutlookProvider op = OutlookProvider.Instance; Outlook.Items it = op.OutlookItems(); int _ouMaxContacts = op.CountContact(); object works = null; Outlook.ContactItem oci = null; int counter = 0; for (int i = 0; i < _ouMaxContacts; i++) { pBar.Value = counter; pBar.PerformStep(); pBar.Refresh(); if (counter > pBar.Maximum) { counter = 0; } if (i == 0) { works = it.GetFirst(); } else { works = it.GetNext(); } if (works is Outlook.DistListItem) { continue; } oci = works as Outlook.ContactItem; if (works == null) { continue; } if (!string.IsNullOrEmpty(oci.User3)) { oci.User3 = string.Empty; oci.Save(); } } }
/// <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); }
/// <summary> /// Gets the first mail item /// </summary> /// <returns>first mail item</returns> public MailItem GetFirst() { return(new MailItem(_mailItems.GetFirst())); }
/// <summary> /// Step first - read all outlook contacts /// </summary> private void Step1ReadOutlook() { bool IsNeedReadAllData = true; bool IsNeedReadNewData = false; List <string> toread = new List <string>(); /// list EntryID for reading List <string> todelete = new List <string>(); /// list EntryID for delete if (SettingsProvider.Instance.IsUseOutlookCache) { LoggerProvider.Instance.Logger.Debug("Read data from cache for Outlook"); ouCacheTime = Utils.LoadCacheDate(true); ouContacts = Utils.ReadOutlookFromCache(ref ouCacheTime); if ((ouCacheTime > DateTime.MinValue) && (ouCacheTime < DateTime.Now) && (ouContacts.Count > 0)) // Data read from cache is good { //_lastStatistic.ouReadContacts = ouContacts.Count; Dictionary <string, DateTime> ouall = OutlookProvider.Instance.GetTableFilter(ouCacheTime); DateTime ouDate; foreach (string s in ouContacts.Keys) { todelete.Add(s); } foreach (string EntID in ouall.Keys) { ouDate = ouall[EntID]; if (ouContacts.ContainsKey(EntID)) /// is EntID found in current cached data { todelete.Remove(EntID); if (((OneContact)ouContacts[EntID])._ModifyDateTime < ouDate) //date from curent select is { ouContacts.Remove(EntID); toread.Add(EntID); } } else { toread.Add(EntID); } } /// in toread now only new EntryID /// in todelete now only contact deleted in outlook, this need clear from cache, because in last two steps it delete from google to foreach (string s in todelete) { ouContacts.Remove(s); } IsNeedReadNewData = toread.Count > 0; } else { LoggerProvider.Instance.Logger.Debug("Data from Outlook cache isn't valid"); } } if (IsNeedReadNewData) // need read new contact data to cache { LoggerProvider.Instance.Logger.Debug("Read only new data from Outlook"); Outlook.Items it = op.OutlookItems(); //_ouMaxContacts = op.CountContact(); syncinfo.OutlookContacts = toread.Count; syncinfo.WorkOnMax = toread.Count; Outlook.ContactItem oci = null; OneContact oc = null; object works = null; int i = 0; int read = 0; syncinfo.WorkOnNextStep(); for (; i < toread.Count; i++) { syncinfo.WorkOn = i + 1; syncinfo.WorkOnNextStep(); works = OutlookProvider.Instance.FindItemfromID(toread[i]); //if (i == 0) // works = it.GetFirst(); //else // works = it.GetNext(); if (works is Outlook.DistListItem) { continue; } oci = works as Outlook.ContactItem; if (works == null) { continue; } if (toread.Contains(oci.EntryID)) { oc = new OneContact(oci); if (SettingsProvider.Instance.IsFirstTime) { oc.ClearReference(); } ouContacts.Add(oci.EntryID, oc); } read++; } _lastStatistic.ouReadContacts += read; syncinfo.OutlookContacts = ouContacts.Count; IsNeedReadAllData = false; } if (IsNeedReadAllData) { /// because need read all data. Before this need remove all cached data ouContacts.Clear(); /// start read all data ouCacheTime = DateTime.MinValue; LoggerProvider.Instance.Logger.Debug("Read all data from Outlook"); Outlook.Items it = op.OutlookItems(); _ouMaxContacts = op.CountContact(); syncinfo.OutlookContacts = _ouMaxContacts; syncinfo.WorkOnMax = _ouMaxContacts; Outlook.ContactItem oci = null; OneContact oc = null; object works = null; int i = 0; int read = 0; syncinfo.WorkOnNextStep(); for (; i < _ouMaxContacts; i++) { syncinfo.WorkOn = i + 1; syncinfo.WorkOnNextStep(); if (i == 0) { works = it.GetFirst(); } else { works = it.GetNext(); } if (works is Outlook.DistListItem) { continue; } oci = works as Outlook.ContactItem; if (works == null) { continue; } oc = new OneContact(oci); if (SettingsProvider.Instance.IsFirstTime) { oc.ClearReference(); } ouContacts.Add(oci.EntryID, oc); read++; } _lastStatistic.ouReadContacts += read; syncinfo.OutlookContacts = ouContacts.Count; } }
private void button1_Click(object sender, EventArgs e) { // Create the Outlook application. // in-line initialization Outlook.Application oApp = new Outlook.Application(); // Get the MAPI namespace. Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); // Log on by using the default profile or existing session (no dialog box). oNS.Logon(Missing.Value, Missing.Value, false, true); // Alternate logon method that uses a specific profile name. // TODO: If you use this logon method, specify the correct profile name // and comment the previous Logon line. //oNS.Logon("profilename",Missing.Value,false,true); //Get the Inbox folder. Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Get the Items collection in the Inbox folder. Outlook.Items oItems = oInbox.Items; // Get the first message. // Because the Items folder may contain different item types, // use explicit typecasting with the assignment. Outlook.MailItem oMsg = (Outlook.MailItem)oItems.GetFirst(); //Output some common properties. textBox1.Text = (oMsg.Subject); textBox1.Text += textBox1.Text + oMsg.SenderName; textBox1.Text += textBox1.Text + oMsg.ReceivedTime; textBox1.Text += textBox1.Text + oMsg.Body; //Check for attachments. int AttachCnt = oMsg.Attachments.Count; textBox1.Text += textBox1.Text + ("Attachments: " + AttachCnt.ToString()); //TO DO: If you use the Microsoft Outlook 11.0 Object Library, uncomment the following lines. if (AttachCnt > 0) { for (int i = 1; i <= AttachCnt; i++) { textBox1.Text += textBox1.Text + (i.ToString() + "-" + oMsg.Attachments[i].DisplayName); } } //Display the message. oMsg.Display(false); //modal //Log off. oNS.Logoff(); //Explicitly release objects. oMsg = null; oItems = null; oInbox = null; oNS = null; oApp = null; }
private void DeleteTestAppointments() { Outlook.MAPIFolder mapiFolder = null; Outlook.Items items = null; if (string.IsNullOrEmpty(AppointmentsSynchronizer.SyncAppointmentsFolder)) { mapiFolder = Synchronizer.OutlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); } else { mapiFolder = Synchronizer.OutlookNameSpace.GetFolderFromID(AppointmentsSynchronizer.SyncAppointmentsFolder); } Assert.NotNull(mapiFolder); try { items = mapiFolder.Items; Assert.NotNull(items); object item = items.GetFirst(); while (item != null) { if (item is Outlook.AppointmentItem) { var ola = item as Outlook.AppointmentItem; if (ola.Subject == name) { var s = ola.Subject + " - " + ola.Start; ola.Delete(); Logger.Log("Deleted Outlook test appointment: " + s, EventType.Information); } Marshal.ReleaseComObject(ola); } Marshal.ReleaseComObject(item); item = items.GetNext(); } } finally { if (mapiFolder != null) { Marshal.ReleaseComObject(mapiFolder); } if (items != null) { Marshal.ReleaseComObject(items); } } var query = sync.appointmentsSynchronizer.EventRequest.List(AppointmentsSynchronizer.SyncAppointmentsGoogleFolder); Events feed; string pageToken = null; do { query.PageToken = pageToken; feed = query.Execute(); foreach (Event e in feed.Items) { if (!e.Status.Equals("cancelled") && e.Summary != null && e.Summary == name) { sync.appointmentsSynchronizer.EventRequest.Delete(AppointmentsSynchronizer.SyncAppointmentsGoogleFolder, e.Id).Execute(); Logger.Log("Deleted Google test appointment: " + e.Summary + " - " + AppointmentsSynchronizer.GetTime(e), EventType.Information); } } pageToken = feed.NextPageToken; }while (pageToken != null); sync.appointmentsSynchronizer.LoadAppointments(); Assert.AreEqual(0, sync.appointmentsSynchronizer.GoogleAppointments.Count); Assert.AreEqual(0, sync.appointmentsSynchronizer.OutlookAppointments.Count); }
private void FillAppointments() { DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day); string todayENCulture = today.AddDays(-1).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern); DateTime todayOneYearLater = today.AddYears(1);// new DateTime(DateTime.Now.Year + 1, DateTime.Now.Month, DateTime.Now.Day); appointments.Clear(); Outlook.MAPIFolder mAPIFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); Outlook.Items items = mAPIFolder.Items; items.Sort("[Start]", true); ApplicationConfigManagement acm = new ApplicationConfigManagement(); string dateCultureFormat = acm.ReadSetting("DateCultureFormat").ToLower(); string filterStr = ""; if (dateCultureFormat == "d") { CultureInfo culture = new CultureInfo("EN-en"); filterStr = "[Start] >= '" + today.AddYears(-1).ToString("dd/MM/yyyy", culture) + "'"; } else if (dateCultureFormat == "g") { filterStr = "[Start] >= '" + today.AddYears(-1).ToString("g") + "'"; } Outlook.Items FilteredItems = items.Restrict(filterStr); DateTime lastAppointmentDate = FilteredItems.GetFirst().Start; for (DateTime SlotDateTime = today; SlotDateTime < today.AddDays(7); SlotDateTime = SlotDateTime.AddMinutes(10)) { string startDate = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); AppointmentInitialDate = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern); cls_Appointment appointment; try { appointment = appointments.Single(m => m.StartDateTimeStr == startDate); int kk = 0; } catch (Exception) { appointment = new cls_Appointment(); appointment.StartDateTimeStr = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointment.EndDateTimeStr = SlotDateTime.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointment.StartDateTime = SlotDateTime; appointment.EndDateTime = SlotDateTime.AddMinutes(10); appointment.Subject = " "; appointment.Paid = " "; appointment.Date = new DateTime(SlotDateTime.Year, SlotDateTime.Month, SlotDateTime.Day); appointment.DateStr = appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointments.Add(appointment); } } foreach (Outlook.AppointmentItem item in FilteredItems) { try { //if (item.Start < today) // continue; CultureInfo culture1 = new CultureInfo("EN-en"); string kk = item.Start.ToString(culture1); string appointmentDate = item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); AppointmentInitialDate = item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern); TimeSpan temptsp = today - item.Start; if (temptsp.TotalSeconds > 0) { break; } cls_Appointment appointment; try { appointment = appointments.Single(m => m.StartDateTimeStr == appointmentDate); if (item.Subject != null) { appointment.Subject = item.Subject; } if (item.Location != null) { appointment.Paid = item.Location; } } catch (Exception) { appointment = new cls_Appointment(); appointment.StartDateTimeStr = item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointment.EndDateTimeStr = item.Start.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + item.Start.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointment.StartDateTime = item.Start; appointment.EndDateTime = item.Start.AddMinutes(10); appointment.Subject = " "; appointment.Paid = " "; appointment.Date = new DateTime(item.Start.Year, item.Start.Month, item.Start.Day); appointment.DateStr = appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointments.Add(appointment); } } catch (Exception) { if (item.Subject.ToLower().IndexOf("birthday") != -1) { item.Delete(); } ; } } for (DateTime SlotDateTime = today; SlotDateTime < todayOneYearLater; SlotDateTime = SlotDateTime.AddMinutes(10)) { string startDate = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); AppointmentInitialDate = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern); cls_Appointment appointment; try { appointment = appointments.Single(m => m.StartDateTimeStr == startDate); } catch (Exception) { appointment = new cls_Appointment(); appointment.StartDateTimeStr = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointment.EndDateTimeStr = SlotDateTime.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointment.StartDateTime = SlotDateTime; appointment.EndDateTime = SlotDateTime.AddMinutes(10); appointment.Subject = " "; appointment.Paid = " "; appointment.Date = new DateTime(SlotDateTime.Year, SlotDateTime.Month, SlotDateTime.Day); appointment.DateStr = appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointments.Add(appointment); } } foreach (Outlook.AppointmentItem item in FilteredItems) { try { //if (item.Start < today) // continue; CultureInfo culture1 = new CultureInfo("EN-en"); string kk = item.Start.ToString(culture1); string appointmentDate = item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); AppointmentInitialDate = item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern); cls_Appointment appointment; try { appointment = appointments.Single(m => m.StartDateTimeStr == appointmentDate); if (item.Subject != null) { appointment.Subject = item.Subject; } if (item.Location != null) { appointment.Paid = item.Location; } } catch (Exception) { appointment = new cls_Appointment(); appointment.StartDateTimeStr = item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + item.Start.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointment.EndDateTimeStr = item.Start.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + item.Start.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); appointment.StartDateTime = item.Start; appointment.EndDateTime = item.Start.AddMinutes(10); appointment.Subject = " "; appointment.Paid = " "; appointment.Date = new DateTime(item.Start.Year, item.Start.Month, item.Start.Day); appointment.DateStr = appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); if (item.Subject != null) { appointment.Subject = item.Subject; } if (item.Location != null) { appointment.Paid = item.Location; } appointments.Add(appointment); } } catch (Exception) { if (item.Subject.ToLower().IndexOf("birthday") != -1) { item.Delete(); } ; } } //for (DateTime SlotDateTime = today.AddYears(-1); SlotDateTime < today; SlotDateTime = SlotDateTime.AddMinutes(10)) //{ // string startDate = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); // AppointmentInitialDate = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern); // cls_Appointment appointment; // try // { // appointment = appointments.Single(m => m.StartDateTimeStr == startDate); // } // catch (Exception) // { // appointment = new cls_Appointment(); // appointment.StartDateTimeStr = SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); // appointment.EndDateTimeStr = SlotDateTime.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + SlotDateTime.AddMinutes(10).ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); // appointment.StartDateTime = SlotDateTime; // appointment.EndDateTime = SlotDateTime.AddMinutes(10); // appointment.Subject = " "; // appointment.Paid = " "; // appointment.Date = new DateTime(SlotDateTime.Year, SlotDateTime.Month, SlotDateTime.Day); // appointment.DateStr = appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortDatePattern) + " " + appointment.Date.ToString(CultureInfo.GetCultureInfo("en-EN").DateTimeFormat.ShortTimePattern); // appointments.Add(appointment); // } //} if (mAPIFolder != null) { Marshal.ReleaseComObject(mAPIFolder); } if (items != null) { Marshal.ReleaseComObject(items); } if (FilteredItems != null) { Marshal.ReleaseComObject(FilteredItems); } }