private void AddinModule_AddinInitialize(object sender, EventArgs e) { // Outlook 2010 if (this.HostMajorVersion >= 14) { adxOlExplorerCommandBar1.UseForRibbon = false; } // set the FolderName property Outlook._NameSpace ns = OutlookApp.GetNamespace("MAPI"); if (ns != null) { try { Outlook.MAPIFolder inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); if (inbox != null) { try { Outlook.MAPIFolder store = inbox.Parent as Outlook.MAPIFolder; if (store != null) { try { this.adxOlFolderPage1.FolderName = store.Name + @"\" + inbox.Name; } finally { Marshal.ReleaseComObject(store); } } } finally { Marshal.ReleaseComObject(inbox); } } } finally { Marshal.ReleaseComObject(ns); } } }
/// <summary> /// Get all items in this appointments folder. Should be called just once (per folder?) /// when the add-in starts up; initialises the SyncState list. /// </summary> /// <param name="appointmentsFolder">The folder to scan.</param> protected override void GetOutlookItems(Outlook.MAPIFolder appointmentsFolder) { try { foreach (Outlook.AppointmentItem olItem in appointmentsFolder.Items) { if (olItem.Start >= this.GetStartDate()) { Outlook.UserProperty olPropertyModified = olItem.UserProperties[ModifiedDatePropertyName]; Outlook.UserProperty olPropertyType = olItem.UserProperties[TypePropertyName]; Outlook.UserProperty olPropertyEntryId = olItem.UserProperties[CrmIdPropertyName]; if (olPropertyModified != null && olPropertyType != null && olPropertyEntryId != null) { /* The appointment probably already has the three magic properties * required for synchronisation; is that a proxy for believing that it * already exists in CRM? If so, is it reliable? */ LogItemAction(olItem, "AppointmentSyncing.GetOutlookItems: Adding known item to queue"); } else { LogItemAction(olItem, "AppointmentSyncing.GetOutlookItems: Adding unknown item to queue"); } this.AddOrGetSyncState(olItem); } } } catch (Exception ex) { Log.Error("ThisAddIn.GetOutlookCalItems", ex); } }
private void adxOutlookEvents_ExplorerFolderSwitch(object sender, object explorer) { Outlook._Explorer activeExplorer = OutlookApp.ActiveExplorer(); if (activeExplorer != null) { try { Outlook.MAPIFolder folder = activeExplorer.CurrentFolder; if (folder != null) { try { Outlook.Items items = folder.Items; if (items != null) { try { btnMessage.Enabled = (items.Count != 0); } finally { Marshal.ReleaseComObject(items); } } } finally { Marshal.ReleaseComObject(folder); } } } finally { Marshal.ReleaseComObject(activeExplorer); } } }
/// <summary> /// Synchronise items in the specified folder with the specified SuiteCRM module. /// </summary> /// <remarks> /// TODO: candidate for refactoring upwards, in concert with ContactSyncing.SyncFolder. /// </remarks> /// <param name="folder">The folder.</param> /// <param name="crmModule">The module.</param> protected override void SyncFolder(Outlook.MAPIFolder folder, string crmModule) { Log.Info(String.Format("AppointmentSyncing.SyncFolder: '{0}'", crmModule)); try { /* this.ItemsSyncState already contains items to be synced. */ var untouched = new HashSet <SyncState <Outlook.AppointmentItem> >(this.ItemsSyncState); MergeRecordsFromCrm(folder, crmModule, untouched); EntryValue[] invited = RestAPIWrapper.GetRelationships("Users", RestAPIWrapper.GetUserId(), crmModule.ToLower(), RestAPIWrapper.GetSugarFields(crmModule)); if (invited != null) { AddOrUpdateItemsFromCrmToOutlook(invited, folder, untouched, crmModule); } try { this.ResolveUnmatchedItems(untouched, crmModule); } catch (Exception ex) { Log.Error("AppointmentSyncing.SyncFolder: Exception", ex); } } catch (Exception ex) { Log.Error("AppointmentSyncing.SyncFolder: Exception", ex); } }
/// <summary> /// Update a single appointment in the specified Outlook folder with changes from CRM, but /// only if its start date is fewer than five days in the past. /// </summary> /// <param name="folder">The folder to synchronise into.</param> /// <param name="crmType">The CRM type of the candidate item.</param> /// <param name="crmItem">The candidate item from CRM.</param> /// <returns>The synchronisation state of the item updated (if it was updated).</returns> protected override SyncState <Outlook.AppointmentItem> AddOrUpdateItemFromCrmToOutlook( Outlook.MAPIFolder folder, string crmType, EntryValue crmItem) { SyncState <Outlook.AppointmentItem> result = null; DateTime dateStart = crmItem.GetValueAsDateTime("date_start"); if (dateStart >= GetStartDate()) { /* search for the item among the sync states I already know about */ var syncState = this.GetExistingSyncState(crmItem); if (syncState == null) { /* check for howlaround */ var matches = this.FindMatches(crmItem); if (matches.Count == 0) { /* didn't find it, so add it to Outlook */ result = AddNewItemFromCrmToOutlook(folder, crmType, crmItem, dateStart); } else { this.Log.Warn($"Howlaround detected? Appointment '{crmItem.GetValueAsString("name")}' offered with id {crmItem.GetValueAsString("id")}, expected {matches[0].CrmEntryId}, {matches.Count} duplicates"); } } else { /* found it, so update it from the CRM item */ result = UpdateExistingOutlookItemFromCrm(crmType, crmItem, dateStart, syncState); result?.OutlookItem.Save(); } if (crmItem?.relationships?.link_list != null) { foreach (var list in crmItem.relationships.link_list) { foreach (var record in list.records) { var data = record.data.AsDictionary(); try { this.meetingRecipientsCache[data[AddressResolutionData.EmailAddressFieldName].ToString()] = new AddressResolutionData(list.name, data); Log.Debug($"Successfully cached recipient {data[AddressResolutionData.EmailAddressFieldName]} => {list.name}, {data[AddressResolutionData.ModuleIdFieldName]}."); } catch (KeyNotFoundException kex) { Log.Error($"Key not found while caching meeting recipients.", kex); } } } } } return(result); }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { Outlook.MAPIFolder inbox = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); items = inbox.Items; items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(InboxFolderItemAdded); }
/// <summary> /// Add an item existing in CRM but not found in Outlook to Outlook. /// </summary> /// <param name="appointmentsFolder">The Outlook folder in which the item should be stored.</param> /// <param name="crmType">The CRM type of the item from which values are to be taken.</param> /// <param name="crmItem">The CRM item from which values are to be taken.</param> /// <param name="date_start">The state date/time of the item, adjusted for timezone.</param> /// <returns>A sync state object for the new item.</returns> private SyncState <Outlook.AppointmentItem> AddNewItemFromCrmToOutlook( Outlook.MAPIFolder appointmentsFolder, string crmType, EntryValue crmItem, DateTime date_start) { AppointmentSyncState newState = null; Outlook.AppointmentItem olItem = null; try { var crmId = crmItem.GetValueAsString("id"); /* * There's a nasty little bug (#223) where Outlook offers us back in a different thread * the item we're creating, before we're able to set up the sync state which marks it * as already known. By locking on the enqueueing lock here, we should prevent that. */ lock (enqueueingLock) { olItem = appointmentsFolder.Items.Add(Outlook.OlItemType.olAppointmentItem); newState = new AppointmentSyncState(crmType) { OutlookItem = olItem, OModifiedDate = DateTime.ParseExact(crmItem.GetValueAsString("date_modified"), "yyyy-MM-dd HH:mm:ss", null), CrmEntryId = crmId }; ItemsSyncState.Add(newState); olItem.Subject = crmItem.GetValueAsString("name"); olItem.Body = crmItem.GetValueAsString("description"); /* set the SEntryID property quickly, create the sync state and save the item, to reduce howlaround */ EnsureSynchronisationPropertiesForOutlookItem(olItem, crmItem, crmType); this.SaveItem(olItem); } LogItemAction(olItem, "AppointmentSyncing.AddNewItemFromCrmToOutlook"); if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_start"))) { olItem.Start = date_start; SetOutlookItemDuration(crmType, crmItem, olItem); Log.Info("\tdefault SetRecepients"); SetRecipients(olItem, crmId, crmType); } } finally { if (olItem != null) { this.SaveItem(olItem); } } return(newState); }
/// <summary> /// Gets the outlook folder from path. /// </summary> /// <param name="outlookNS">The outlook NS.</param> /// <param name="path">The path.</param> /// <returns></returns> public OutlookFolder GetOutlookFolderFromPath(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } OutlookFolder retVal = null; if (this.InvokeRequired) { Func <string, OutlookFolder> func = this.GetOutlookFolderFromPath; retVal = (OutlookFolder)this.Invoke(func, path); } else { Outlook.MAPIFolder oMapiFolder = null; Outlook.NameSpace oNs = null; try { oNs = this._addinModule.OutlookApp.GetNamespace("MAPI"); string[] folders = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (folders.Length != 0) { oMapiFolder = oNs.Folders.Item(folders[0]); for (int i = 1; i < folders.Length; i++) { Outlook.MAPIFolder oTmpMapiFolder = oMapiFolder.Folders.Item(folders[i]); if (oTmpMapiFolder != null) { Marshal.ReleaseComObject(oMapiFolder); oMapiFolder = oTmpMapiFolder; } } } } finally { if (oNs != null) { Marshal.ReleaseComObject(oNs); } } if (oMapiFolder != null) { retVal = _factory.Create <OutlookItem>(oMapiFolder) as OutlookFolder; } } return(retVal); }
private void ConnectToFolderByIndex(int index) { if (eventObject != null) { Outlook.OlDefaultFolders folderType = Outlook.OlDefaultFolders.olFolderInbox; switch (index) { case 1: folderType = Outlook.OlDefaultFolders.olFolderDeletedItems; break; case 2: folderType = Outlook.OlDefaultFolders.olFolderDrafts; break; case 3: folderType = Outlook.OlDefaultFolders.olFolderInbox; break; case 4: folderType = Outlook.OlDefaultFolders.olFolderOutbox; break; case 5: folderType = Outlook.OlDefaultFolders.olFolderSentMail; break; case 6: folderType = Outlook.OlDefaultFolders.olFolderContacts; break; case 7: folderType = Outlook.OlDefaultFolders.olFolderTasks; break; case 8: folderType = Outlook.OlDefaultFolders.olFolderCalendar; break; } Outlook._NameSpace ns = OutlookApp.GetNamespace("MAPI"); if (ns != null) { try { Outlook.MAPIFolder folder = ns.GetDefaultFolder(folderType); eventObject.ConnectTo(folder, true); } finally { Marshal.ReleaseComObject(ns); } } } }
private ArrayList RecurringItems() { // Filter all the objects we are looking for. Outlook.AppointmentItem appoinmentItem = null; Outlook.MAPIFolder folder = OutlookApplication.Session.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.MAPIFolder; // Use a Jet Query to filter the details we need initially between // the two spcified dates. string dateFilter = String.Format( CultureConstants.DefaultCulture, "[Start] >= '{0:g}' and [End] <= '{1:g}'", startDate, endDate); Outlook.Items calendarItems = folder.Items.Restrict(dateFilter); calendarItems.Sort("[Start]", Type.Missing); calendarItems.IncludeRecurrences = true; // Must use 'like' comparison for Find/FindNext string subjectFilter = String.Empty; if (String.IsNullOrEmpty(subject)) { subjectFilter = "@SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " like '%" + subject + "%'"; } else { subjectFilter = "@SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " <> '!@#'"; } // Use Find and FindNext methods to get all the items. ArrayList resultArray = new ArrayList(); appoinmentItem = calendarItems.Find(subjectFilter) as Outlook.AppointmentItem; while (appoinmentItem != null) { resultArray.Add(appoinmentItem); // Find the next appointment. appoinmentItem = calendarItems.FindNext() as Outlook.AppointmentItem; } return(resultArray); }
private void InboxFolderItemAdded(object Item) { if (Item is Outlook.MailItem) { Debug.WriteLine("I'm in!"); Outlook.MailItem mail = (Outlook.MailItem)Item; int[] answer = Predict(mail); if (answer[0] == 0) // Not spam { Outlook.MAPIFolder inboxFolder = ((Outlook.MAPIFolder) this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)); mail.Move(inboxFolder); } else if (answer[0] == 1) // Spam { Outlook.MAPIFolder junkFolder = ((Outlook.MAPIFolder) this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderJunk)); mail.Move(junkFolder); } } }
/// <summary> /// If a meeting was created in another Outlook we should NOT sync it with CRM because if we do we'll create /// duplicates. Only the Outlook which created it should sync it. /// </summary> /// <param name="folder">The folder to synchronise into.</param> /// <param name="crmType">The CRM type of the candidate item.</param> /// <param name="crmItem">The candidate item from CRM.</param> /// <returns>True if it's offered to us by CRM with its Outlook ID already populated.</returns> protected override bool ShouldAddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder folder, string crmType, EntryValue crmItem) { var outlookId = crmItem.GetValueAsString("outlook_id"); /* we're good if it's a meeting... */ bool result = crmType == this.DefaultCrmModule; /* provided it doesn't already have an Outlook id */ result &= string.IsNullOrWhiteSpace(outlookId); /* and we're also good if it's an appointment; */ result |= crmType == AppointmentSyncing.AltCrmModule; /* and we're also good if we've already got it */ result |= (this.GetExistingSyncState(crmItem) != null); if (!result) { Log.Debug($"ShouldAddOrUpdateItemFromCrmToOutlook: not syncing meeting `{crmItem.GetValueAsString("name")}` as it appears to originate from another Outlook instance."); } return(result); }
/// <summary> /// Update a single appointment in the specified Outlook folder with changes from CRM, but /// only if its start date is fewer than five days in the past. /// </summary> /// <param name="folder">The folder to synchronise into.</param> /// <param name="crmType">The CRM type of the candidate item.</param> /// <param name="crmItem">The candidate item from CRM.</param> /// <returns>The synchronisation state of the item updated (if it was updated).</returns> protected override SyncState <Outlook.AppointmentItem> AddOrUpdateItemFromCrmToOutlook( Outlook.MAPIFolder folder, string crmType, EntryValue crmItem) { SyncState <Outlook.AppointmentItem> result = null; DateTime dateStart = crmItem.GetValueAsDateTime("date_start"); if (dateStart >= GetStartDate()) { /* search for the item among the sync states I already know about */ var syncState = this.GetExistingSyncState(crmItem); if (syncState == null) { /* check for howlaround */ var matches = this.FindMatches(crmItem); if (matches.Count == 0) { /* didn't find it, so add it to Outlook */ result = AddNewItemFromCrmToOutlook(folder, crmType, crmItem, dateStart); } else { this.Log.Warn($"Howlaround detected? Appointment '{crmItem.GetValueAsString("name")}' offered with id {crmItem.GetValueAsString("id")}, expected {matches[0].CrmEntryId}, {matches.Count} duplicates"); } } else { /* found it, so update it from the CRM item */ result = UpdateExistingOutlookItemFromCrm(crmType, crmItem, dateStart, syncState); } result?.OutlookItem.Save(); // TODO TODO TODO TODO: pull and cache the recipients! } return(result); }
/// <summary> /// Adds the folder item. /// </summary> /// <param name="oFolder">The o folder.</param> /// <param name="oItemType">Type of the o item.</param> /// <returns></returns> public OutlookItem AddFolderItem(Outlook.MAPIFolder oFolder, Outlook.OlItemType oItemType) { OutlookItem retVal = null; if (oFolder == null) { throw new ArgumentNullException("oFolder"); } if (this.InvokeRequired) { Func <Outlook.MAPIFolder, Outlook.OlItemType, OutlookItem> func = AddFolderItem; retVal = this.Invoke(func, oFolder, oItemType) as OutlookItem; } else { object newItem = oFolder.Items.Add(oItemType); if (newItem != null) { retVal = _factory.Create <OutlookItem>(newItem) as OutlookItem; } } return(retVal); }
/// <summary> /// Gets the folder items. /// </summary> /// <param name="oFolder">The o folder.</param> /// <returns></returns> public List <OutlookItem> GetFolderItems(Outlook.MAPIFolder oFolder) { List <OutlookItem> retVal = new List <OutlookItem>(); if (this.InvokeRequired) { Func <Outlook.MAPIFolder, List <OutlookItem> > func = this.GetFolderItems; return((List <OutlookItem>) this.Invoke(func, oFolder)); } else { for (int i = 1; i <= oFolder.Items.Count; i++) { OutlookItem item = _factory.Create <OutlookItem>(oFolder.Items.Item(i)); if (item != null) { retVal.Add(item); } } } return(retVal); }
/// <summary> /// Picks the outlook folder path. /// </summary> /// <param name="oApp">The o app.</param> /// <param name="oItemType">Type of the o item.</param> /// <returns></returns> public static string PickOutlookFolderPath(Outlook._Application oApp, Outlook.OlItemType oItemType) { string retVal = null; bool correctFolderSelected = false; try { while (!correctFolderSelected) { Outlook.NameSpace oNameSpace = oApp.GetNamespace("MAPI"); Outlook.MAPIFolder oMapiFolder = oNameSpace.PickFolder(); if (oMapiFolder.DefaultItemType != oItemType) { DebugAssistant.Log(DebugSeverity.Error | DebugSeverity.MessageBox, Resources.ERR_OUTLOOK_BAD_FOLDER_TYPE, oItemType); continue; } correctFolderSelected = true; retVal = oMapiFolder.Name; while (oMapiFolder.Parent is Outlook.MAPIFolder) { oMapiFolder = (Outlook.MAPIFolder)oMapiFolder.Parent; retVal = string.Format("{0}/", oMapiFolder.Name) + retVal; } retVal = "//" + retVal; } } catch (Exception e) { DebugAssistant.Log(DebugSeverity.Debug, e.Message); DebugAssistant.Log(DebugSeverity.Debug | DebugSeverity.MessageBox, Resources.DBG_OUTLOOK_FOLDER_NOT_SELECTED); } return(retVal); }
public OutlookFolder(OutlookListener outlookListener, Outlook.MAPIFolder oFolder) : base(outlookListener) { _oFolder = oFolder; }
private void DoEnumContacts() { if (btnMode.State == AddinExpress.MSO.ADXMsoButtonState.adxMsoButtonDown) { securityManager1.DisableOOMWarnings = true; } try { Outlook.NameSpace namespace_ = OutlookApp.GetNamespace("MAPI"); if (namespace_ != null) { try { Outlook.MAPIFolder folder = namespace_.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts); if (folder != null) { try { ContactsForm frmContacts = new ContactsForm(); try { Outlook.Items items = folder.Items; if (items != null) { try { for (int i = 1; i <= items.Count; i++) { Outlook.ContactItem contact = items.Item(i) as Outlook.ContactItem; if (contact != null) { try { if (!string.IsNullOrEmpty(contact.Email1DisplayName)) { DataRow newRow = frmContacts.dsContacts.Tables["Contacts"].NewRow(); newRow["DisplayName"] = contact.Email1DisplayName; newRow["Address"] = contact.Email1Address; newRow["AddressType"] = contact.Email1AddressType; frmContacts.dsContacts.Tables["Contacts"].Rows.Add(newRow); } if (!string.IsNullOrEmpty(contact.Email2DisplayName)) { DataRow newRow = frmContacts.dsContacts.Tables["Contacts"].NewRow(); newRow["DisplayName"] = contact.Email2DisplayName; newRow["Address"] = contact.Email2Address; newRow["AddressType"] = contact.Email2AddressType; frmContacts.dsContacts.Tables["Contacts"].Rows.Add(newRow); } if (!string.IsNullOrEmpty(contact.Email3DisplayName)) { DataRow newRow = frmContacts.dsContacts.Tables["Contacts"].NewRow(); newRow["DisplayName"] = contact.Email3DisplayName; newRow["Address"] = contact.Email3Address; newRow["AddressType"] = contact.Email3AddressType; frmContacts.dsContacts.Tables["Contacts"].Rows.Add(newRow); } } finally { Marshal.ReleaseComObject(contact); } } } } finally { Marshal.ReleaseComObject(items); } } } catch { } frmContacts.ShowDialog(); frmContacts.Dispose(); } finally { Marshal.ReleaseComObject(folder); } } } finally { Marshal.ReleaseComObject(namespace_); } } } finally { if (btnMode.State == AddinExpress.MSO.ADXMsoButtonState.adxMsoButtonDown) { securityManager1.DisableOOMWarnings = false; } } }