private SyncState <Outlook.ContactItem> UpdateFromCrm(Outlook.MAPIFolder folder, eEntryValue candidateItem) { SyncState <Outlook.ContactItem> result; dynamic crmItem = JsonConvert.DeserializeObject(candidateItem.name_value_object.ToString()); String id = crmItem.id.value.ToString(); var oItem = ItemsSyncState.FirstOrDefault(a => a.CrmEntryId == crmItem.id.value.ToString()); if (ShouldSyncContact(crmItem)) { Log.Info( string.Format( "ContactSyncing.UpdateFromCrm, entry id is '{0}', sync_contact is true, syncing", id)); if (oItem == null) { result = AddNewItemFromCrmToOutlook(folder, crmItem); } else { result = UpdateExistingOutlookItemFromCrm(crmItem, oItem); } } else { Log.Info( string.Format( "ContactSyncing.UpdateFromCrm, entry id is '{0}', sync_contact is false, not syncing", id)); result = oItem; } return(result); }
/// <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="crmItem">The CRM item from which values are to be taken.</param> /// <returns>A sync state object for the new item.</returns> private SyncState <Outlook.ContactItem> AddNewItemFromCrmToOutlook(Outlook.MAPIFolder contactFolder, eEntryValue crmItem) { Log.Info( (string)string.Format( "ContactSyncing.AddNewItemFromCrmToOutlook, entry id is '{0}', creating in Outlook.", crmItem.GetValueAsString("id"))); Outlook.ContactItem olItem = contactFolder.Items.Add(Outlook.OlItemType.olContactItem); this.SetOutlookItemPropertiesFromCrmItem(crmItem, olItem); var newState = new ContactSyncState { OutlookItem = olItem, OModifiedDate = DateTime.ParseExact(crmItem.GetValueAsString("date_modified"), "yyyy-MM-dd HH:mm:ss", null), CrmEntryId = crmItem.GetValueAsString("id"), }; ItemsSyncState.Add(newState); olItem.Save(); LogItemAction(newState.OutlookItem, "AppointmentSyncing.AddNewItemFromCrmToOutlook, saved item"); return(newState); }
/// <summary> /// Constructs a new SyncState object for this Outlook item and adds it to my /// collection of sync states. /// </summary> /// <param name="oItem">The Outlook item to wrap</param> /// <returns>The sync state added.</returns> private SyncState <OutlookItemType> ConstructAndAddSyncState(OutlookItemType oItem) { SyncState <OutlookItemType> newState = ConstructSyncState(oItem); ItemsSyncState.Add(newState); return(newState); }
/// <summary> /// Deal, in CRM, with items deleted in Outlook. /// </summary> protected void RemoveDeletedItems() { if (IsCurrentView && PropagatesLocalDeletions) { // Make a copy of the list to avoid mutation error while iterating: var syncStatesCopy = new List <SyncState <OutlookItemType> >(ItemsSyncState); foreach (var oItem in syncStatesCopy) { var shouldDeleteFromCrm = oItem.IsDeletedInOutlook || !oItem.ShouldSyncWithCrm; if (shouldDeleteFromCrm) { RemoveFromCrm(oItem); } if (oItem.IsDeletedInOutlook) { ItemsSyncState.Remove(oItem); } } } else { var items = ItemsSyncState.Where(x => x.IsDeletedInOutlook).Count(); if (items > 0) { Log.Error($"Possibly bug #95: was attempting to delete {items} items from CRM"); } } }
/// <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> /// Synchronise items in the specified folder with the specified SuiteCRM module. /// </summary> /// <remarks> /// TODO: candidate for refactoring upwards, in concert with AppointmentSyncing.SyncFolder. /// </remarks> /// <param name="folder">The folder.</param> private void SyncFolder(Outlook.MAPIFolder folder) { Log.Info($"ContactSyncing.SyncFolder: '{folder}'"); try { if (HasAccess("Contacts", "export")) { var untouched = new HashSet <SyncState <Outlook.ContactItem> >(ItemsSyncState); int nextOffset = -1; // offset of the next page of entries, if any. for (int iOffset = 0; iOffset != nextOffset; iOffset = nextOffset) { eGetEntryListResult entriesPage = clsSuiteCRMHelper.GetEntryList("Contacts", "contacts.assigned_user_id = '" + clsSuiteCRMHelper.GetUserId() + "'", 0, "date_entered DESC", iOffset, false, clsSuiteCRMHelper.GetSugarFields("Contacts")); nextOffset = entriesPage.next_offset; if (iOffset != nextOffset) { UpdateItemsFromCrmToOutlook(entriesPage.entry_list, folder, untouched); } } try { // Create the lists first, because deleting items changes the value of 'ExistedInCrm'. var syncableButNotOnCrm = untouched.Where(s => s.ShouldSyncWithCrm); var toDeleteFromOutlook = syncableButNotOnCrm.Where(a => a.ExistedInCrm).ToList(); var toCreateOnCrmServer = syncableButNotOnCrm.Where(a => !a.ExistedInCrm).ToList(); foreach (var item in toDeleteFromOutlook) { LogItemAction(item.OutlookItem, "ContactSyncing.SyncFolder, deleted item"); item.OutlookItem.Delete(); ItemsSyncState.Remove(item); } foreach (var oItem in toCreateOnCrmServer) { AddOrUpdateItemFromOutlookToCrm(oItem.OutlookItem); } } catch (Exception ex) { Log.Error("ContactSyncing.SyncContacts", ex); } } else { Log.Warn("ContactSyncing.SyncContacts: CRM server denied access to export Contacts"); } } catch (Exception ex) { Log.Error("ContactSyncing.SyncContacts", ex); } }
/// <summary> /// Constructs a new SyncState object for this Outlook item and adds it to my /// collection of sync states. /// </summary> /// <param name="olItem">The Outlook item to wrap</param> /// <returns>The sync state added.</returns> private SyncState <OutlookItemType> ConstructAndAddSyncState(OutlookItemType olItem) { try { SyncState <OutlookItemType> newState = ConstructSyncState(olItem); ItemsSyncState.Add(newState); return(newState); } finally { this.SaveItem(olItem); } }
override protected void OutlookItemChanged(Outlook.TaskItem oItem) { Log.Debug("Outlook Tasks ItemChange"); string entryId = oItem.EntryID; Log.Warn("\toItem.EntryID= " + entryId); var taskitem = ItemsSyncState.FirstOrDefault(a => a.OutlookItem.EntryID == entryId); if (taskitem != null) { if ((DateTime.UtcNow - taskitem.OModifiedDate).TotalSeconds > 5) { Log.Warn("2 callitem.IsUpdate = " + taskitem.IsUpdate); taskitem.IsUpdate = 0; } Log.Warn("Before UtcNow - callitem.OModifiedDate= " + (DateTime.UtcNow - taskitem.OModifiedDate).TotalSeconds.ToString()); if ((int)(DateTime.UtcNow - taskitem.OModifiedDate).TotalSeconds > 2 && taskitem.IsUpdate == 0) { taskitem.OModifiedDate = DateTime.UtcNow; Log.Warn("1 callitem.IsUpdate = " + taskitem.IsUpdate); taskitem.IsUpdate++; } Log.Warn("callitem = " + taskitem.OutlookItem.Subject); Log.Warn("callitem.SEntryID = " + taskitem.CrmEntryId); Log.Warn("callitem mod_date= " + taskitem.OModifiedDate.ToString()); Log.Warn("UtcNow - callitem.OModifiedDate= " + (DateTime.UtcNow - taskitem.OModifiedDate).TotalSeconds.ToString()); } else { Log.Warn("not found callitem "); } if (IsCurrentView && ItemsSyncState.Exists(a => a.OutlookItem.EntryID == entryId && //// if (IsTaskView && lTaskItems.Exists(a => a.oItem.EntryID == entryId && a.OModifiedDate != "Fresh")) taskitem.IsUpdate == 1 ) ) { Outlook.UserProperty oProp1 = oItem.UserProperties["SEntryID"]; if (oProp1 != null) { Log.Warn("\tgo to AddTaskToS"); taskitem.IsUpdate++; AddOrUpdateItemFromOutlookToCrm(oItem, this.DefaultCrmModule, oProp1.Value.ToString()); } } }
protected override SyncState <Outlook.ContactItem> UpdateFromCrm(Outlook.MAPIFolder folder, string crmType, eEntryValue crmItem) { SyncState <Outlook.ContactItem> result; String id = crmItem.GetValueAsString("id"); var syncStateForItem = ItemsSyncState.FirstOrDefault(a => a.CrmEntryId == crmItem.GetValueAsString("id")); if (ShouldSyncContact(crmItem)) { Log.Info( string.Format( "ContactSyncing.UpdateFromCrm, entry id is '{0}', sync_contact is true, syncing", id)); if (syncStateForItem == null) { result = AddNewItemFromCrmToOutlook(folder, crmItem); } else { result = UpdateExistingOutlookItemFromCrm(crmItem, syncStateForItem); } } else if (syncStateForItem != null && syncStateForItem.OutlookItem != null && ShouldSyncFlagChanged(syncStateForItem.OutlookItem, crmItem)) { /* The date_modified value in CRM does not get updated when the sync_contact value * is changed. But seeing this value can only be updated at the CRM side, if it * has changed the change must have been at the CRM side. Note also that it must * have changed to 'false', because if it had changed to 'true' we would have * synced normally in the above branch. Delete from Outlook. */ Log.Warn($"ContactSyncing.UpdateFromCrm, entry id is '{id}', sync_contact has changed to {ShouldSyncContact(crmItem)}, deleting"); this.RemoveItemAndSyncState(syncStateForItem); result = syncStateForItem; } else { Log.Info( string.Format( "ContactSyncing.UpdateFromCrm, entry id is '{0}', sync_contact is false, not syncing", id)); result = syncStateForItem; } return(result); }
protected override SyncState <Outlook.TaskItem> UpdateFromCrm(Outlook.MAPIFolder tasksFolder, string crmType, eEntryValue crmItem) { SyncState <Outlook.TaskItem> result = null; if (clsSuiteCRMHelper.GetUserId() == crmItem.GetValueAsString("assigned_user_id")) { DateTime?date_start = null; DateTime?date_due = null; string time_start = "--:--", time_due = "--:--"; if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_start"))) { Log.Warn("\tSET date_start = dResult.date_start"); date_start = DateTime.ParseExact(crmItem.GetValueAsString("date_start"), "yyyy-MM-dd HH:mm:ss", null); date_start = date_start.Value.Add(new DateTimeOffset(DateTime.Now).Offset); time_start = TimeSpan.FromHours(date_start.Value.Hour) .Add(TimeSpan.FromMinutes(date_start.Value.Minute)) .ToString(@"hh\:mm"); } if (date_start != null && date_start >= GetStartDate()) { if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_due"))) { date_due = DateTime.ParseExact(crmItem.GetValueAsString("date_due"), "yyyy-MM-dd HH:mm:ss", null); date_due = date_due.Value.Add(new DateTimeOffset(DateTime.Now).Offset); time_due = TimeSpan.FromHours(date_due.Value.Hour).Add(TimeSpan.FromMinutes(date_due.Value.Minute)).ToString(@"hh\:mm"); ; } var oItem = ItemsSyncState.FirstOrDefault(a => a.CrmEntryId == crmItem.GetValueAsString("id")); if (oItem == null) { result = AddNewItemFromCrmToOutlook(tasksFolder, crmItem, date_start, date_due, time_start, time_due); } else { result = UpdateExistingOutlookItemFromCrm(crmItem, date_start, date_due, time_start, time_due, oItem); } } } return(result); }
/// <summary> /// Find the SyncState whose item is this item; if it does not already exist, construct and return it. /// </summary> /// <param name="oItem">The item to find.</param> /// <returns>the SyncState whose item is this item</returns> protected SyncState <OutlookItemType> AddOrGetSyncState(OutlookItemType oItem) { var existingState = GetExistingSyncState(oItem); if (existingState != null) { existingState.OutlookItem = oItem; return(existingState); } else { SyncState <OutlookItemType> newState = ConstructSyncState(oItem); ItemsSyncState.Add(newState); return(newState); } }
/// <summary> /// Find any existing Outlook items which appear to be identical to this CRM item. /// </summary> /// <param name="crmItem">The CRM item to match.</param> /// <returns>A list of matching Outlook items.</returns> protected List <SyncState <OutlookItemType> > FindMatches(EntryValue crmItem) { List <SyncState <OutlookItemType> > result; try { result = ItemsSyncState.Where(a => this.IsMatch(a.OutlookItem, crmItem)) .ToList <SyncState <OutlookItemType> >(); } catch (Exception any) { this.Log.Error("Exception while checking for matches", any); result = new List <SyncState <OutlookItemType> >(); } return(result); }
private SyncState <Outlook.TaskItem> AddNewItemFromCrmToOutlook(Outlook.MAPIFolder tasksFolder, eEntryValue crmItem, DateTime?date_start, DateTime?date_due, string time_start, string time_due) { Outlook.TaskItem olItem = tasksFolder.Items.Add(Outlook.OlItemType.olTaskItem); this.SetOutlookItemPropertiesFromCrmItem(crmItem, date_start, date_due, time_start, time_due, olItem); var newState = new TaskSyncState { OutlookItem = olItem, OModifiedDate = DateTime.ParseExact(crmItem.GetValueAsString("date_modified"), "yyyy-MM-dd HH:mm:ss", null), CrmEntryId = crmItem.GetValueAsString("id"), }; ItemsSyncState.Add(newState); olItem.Save(); LogItemAction(olItem, "AppointmentSyncing.AddNewItemFromCrmToOutlook"); return(newState); }
/// <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? */ ItemsSyncState.Add(new AppointmentSyncState(olPropertyType.Value.ToString()) { OutlookItem = olItem, OModifiedDate = DateTime.UtcNow, CrmEntryId = olPropertyEntryId.Value.ToString() }); LogItemAction(olItem, "AppointmentSyncing.GetOutlookItems: Adding known item to queue"); } else { ItemsSyncState.Add(new AppointmentSyncState(AppointmentSyncing.CrmModule) { OutlookItem = olItem, }); LogItemAction(olItem, "AppointmentSyncing.GetOutlookItems: Adding unknown item to queue"); } } } } catch (Exception ex) { Log.Error("ThisAddIn.GetOutlookCalItems", ex); } }
protected void RemoveDeletedItems() { if (IsCurrentView && PropagatesLocalDeletions) { // Make a copy of the list to avoid mutation error while iterating: var syncStatesCopy = new List <SyncState <OutlookItemType> >(ItemsSyncState); foreach (var oItem in syncStatesCopy) { var shouldDeleteFromCrm = oItem.IsDeletedInOutlook || !oItem.ShouldSyncWithCrm; if (shouldDeleteFromCrm) { RemoveFromCrm(oItem); } if (oItem.IsDeletedInOutlook) { ItemsSyncState.Remove(oItem); } } } }
/// <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, eEntryValue crmItem, DateTime date_start) { Outlook.AppointmentItem olItem = appointmentsFolder.Items.Add(Outlook.OlItemType.olAppointmentItem); 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); var crmId = crmItem.GetValueAsString("id"); var 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.Save(); 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); } MaybeAddAcceptDeclineLinks(crmItem, olItem, crmType); /* now modified, save again */ olItem.Save(); LogItemAction(newState.OutlookItem, "AppointmentSyncing.AddNewItemFromCrmToOutlook, saved item"); return(newState); }
private SyncState <Outlook.ContactItem> AddOrGetSyncState(Outlook.ContactItem oItem) { var entryId = oItem.EntryID; var existingState = ItemsSyncState.FirstOrDefault(a => a.OutlookItem.EntryID == entryId); if (existingState != null) { existingState.OutlookItem = oItem; return(existingState); } else { var newState = new ContactSyncState { OutlookItem = oItem, CrmEntryId = oItem.UserProperties["SEntryID"]?.Value.ToString(), OModifiedDate = ParseDateTimeFromUserProperty(oItem.UserProperties["SOModifiedDate"]?.Value.ToString()), }; ItemsSyncState.Add(newState); return(newState); } }
/// <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="crmItem">The CRM item from which values are to be taken.</param> /// <returns>A sync state object for the new item.</returns> private SyncState <Outlook.ContactItem> AddNewItemFromCrmToOutlook(Outlook.MAPIFolder contactFolder, dynamic crmItem) { Log.Info( (string)string.Format( "ContactSyncing.AddNewItemFromCrmToOutlook, entry id is '{0}', creating in Outlook.", crmItem.id.value.ToString())); Outlook.ContactItem olItem = ConstructOutlookItemFromCrmItem(contactFolder, crmItem); var newState = new ContactSyncState { OutlookItem = olItem, OModifiedDate = DateTime.ParseExact(crmItem.date_modified.value.ToString(), "yyyy-MM-dd HH:mm:ss", null), CrmEntryId = crmItem.id.value.ToString(), }; ItemsSyncState.Add(newState); olItem.Save(); LogItemAction(newState.OutlookItem, "AppointmentSyncing.AddNewItemFromCrmToOutlook, saved item"); return(newState); }
protected override void GetOutlookItems(Outlook.MAPIFolder taskFolder) { try { Outlook.Items items = taskFolder.Items; //.Restrict("[MessageClass] = 'IPM.Task'" + GetStartDateString()); foreach (Outlook.TaskItem oItem in items) { if (oItem.DueDate < DateTime.Now.AddDays(-5)) { continue; } Outlook.UserProperty oProp = oItem.UserProperties["SOModifiedDate"]; if (oProp != null) { Outlook.UserProperty oProp2 = oItem.UserProperties["SEntryID"]; ItemsSyncState.Add(new TaskSyncState { OutlookItem = oItem, //OModifiedDate = "Fresh", OModifiedDate = DateTime.UtcNow, CrmEntryId = oProp2.Value.ToString() }); } else { ItemsSyncState.Add(new TaskSyncState { OutlookItem = oItem }); } } } catch (Exception ex) { Log.Error("ThisAddIn.GetOutlookTItems", ex); } }
/// <summary> /// Get the existing sync state representing the item with this CRM id, if it exists, else null. /// </summary> /// <param name="crmItemId">The id of a CRM item</param> /// <returns>the existing sync state representing the item with this CRM id, if it exists, else null.</returns> protected SyncState <OutlookItemType> GetExistingSyncState(string crmItemId) { SyncState <OutlookItemType> result; try { /* if there are duplicate entries I want them logged */ result = ItemsSyncState.SingleOrDefault(a => a.CrmEntryId == crmItemId); } catch (InvalidOperationException notUnique) { Log.Error( String.Format( "AppointmentSyncing.AddItemFromOutlookToCrm: CRM Id {0} was not unique in this.ItemsSyncState?", crmItemId), notUnique); /* but if it isn't unique, the first will actually do for now */ result = ItemsSyncState.FirstOrDefault(a => a.CrmEntryId == crmItemId); } return(result); }
private SyncState <Outlook.TaskItem> AddNewItemFromCrmToOutlook(Outlook.MAPIFolder tasksFolder, EntryValue crmItem, DateTime?date_start, DateTime?date_due, string time_start, string time_due) { Outlook.TaskItem olItem = tasksFolder.Items.Add(Outlook.OlItemType.olTaskItem); TaskSyncState newState = null; try { this.SetOutlookItemPropertiesFromCrmItem(crmItem, date_start, date_due, time_start, time_due, olItem); newState = new TaskSyncState { OutlookItem = olItem, OModifiedDate = DateTime.ParseExact(crmItem.GetValueAsString("date_modified"), "yyyy-MM-dd HH:mm:ss", null), CrmEntryId = crmItem.GetValueAsString("id"), }; ItemsSyncState.Add(newState); } finally { this.SaveItem(olItem); } return(newState); }
private SyncState <Outlook.TaskItem> UpdateFromCrm(Outlook.MAPIFolder tasksFolder, eEntryValue oResult) { dynamic dResult = JsonConvert.DeserializeObject(oResult.name_value_object.ToString()); // if (clsSuiteCRMHelper.GetUserId() != dResult.assigned_user_id.value.ToString()) { return(null); } DateTime?date_start = null; DateTime?date_due = null; string time_start = "--:--", time_due = "--:--"; if (!string.IsNullOrWhiteSpace(dResult.date_start.value.ToString()) && !string.IsNullOrEmpty(dResult.date_start.value.ToString())) { Log.Warn("\tSET date_start = dResult.date_start"); date_start = DateTime.ParseExact(dResult.date_start.value.ToString(), "yyyy-MM-dd HH:mm:ss", null); date_start = date_start.Value.Add(new DateTimeOffset(DateTime.Now).Offset); time_start = TimeSpan.FromHours(date_start.Value.Hour) .Add(TimeSpan.FromMinutes(date_start.Value.Minute)) .ToString(@"hh\:mm"); } if (date_start != null && date_start < GetStartDate()) { Log.Warn("\tdate_start=" + date_start.ToString() + ", GetStartDate= " + GetStartDate().ToString()); return(null); } if (!string.IsNullOrWhiteSpace(dResult.date_due.value.ToString())) { date_due = DateTime.ParseExact(dResult.date_due.value.ToString(), "yyyy-MM-dd HH:mm:ss", null); date_due = date_due.Value.Add(new DateTimeOffset(DateTime.Now).Offset); time_due = TimeSpan.FromHours(date_due.Value.Hour).Add(TimeSpan.FromMinutes(date_due.Value.Minute)).ToString(@"hh\:mm"); ; } foreach (var lt in ItemsSyncState) { Log.Warn("\tTask= " + lt.CrmEntryId); } var oItem = ItemsSyncState.FirstOrDefault(a => a.CrmEntryId == dResult.id.value.ToString()); if (oItem == null) { Log.Warn("\tif default"); Outlook.TaskItem tItem = tasksFolder.Items.Add(Outlook.OlItemType.olTaskItem); tItem.Subject = dResult.name.value.ToString(); if (!string.IsNullOrWhiteSpace(dResult.date_start.value.ToString())) { tItem.StartDate = date_start.Value; } if (!string.IsNullOrWhiteSpace(dResult.date_due.value.ToString())) { tItem.DueDate = date_due.Value; // DateTime.Parse(dResult.date_due.value.ToString()); } string body = dResult.description.value.ToString(); tItem.Body = string.Concat(body, "#<", time_start, "#", time_due); tItem.Status = GetStatus(dResult.status.value.ToString()); tItem.Importance = GetImportance(dResult.priority.value.ToString()); Outlook.UserProperty oProp = tItem.UserProperties.Add("SOModifiedDate", Outlook.OlUserPropertyType.olText); oProp.Value = dResult.date_modified.value.ToString(); Outlook.UserProperty oProp2 = tItem.UserProperties.Add("SEntryID", Outlook.OlUserPropertyType.olText); oProp2.Value = dResult.id.value.ToString(); var newState = new TaskSyncState { OutlookItem = tItem, OModifiedDate = DateTime.ParseExact(dResult.date_modified.value.ToString(), "yyyy-MM-dd HH:mm:ss", null), CrmEntryId = dResult.id.value.ToString(), }; ItemsSyncState.Add(newState); Log.Warn("\tsave 0"); tItem.Save(); return(newState); } else { Log.Warn("\telse not default"); Outlook.TaskItem tItem = oItem.OutlookItem; Outlook.UserProperty oProp = tItem.UserProperties["SOModifiedDate"]; Log.Warn( (string) ("\toProp.Value= " + oProp.Value + ", dResult.date_modified=" + dResult.date_modified.value.ToString())); if (oProp.Value != dResult.date_modified.value.ToString()) { tItem.Subject = dResult.name.value.ToString(); if (!string.IsNullOrWhiteSpace(dResult.date_start.value.ToString())) { Log.Warn("\ttItem.StartDate= " + tItem.StartDate + ", date_start=" + date_start); tItem.StartDate = date_start.Value; } if (!string.IsNullOrWhiteSpace(dResult.date_due.value.ToString())) { tItem.DueDate = date_due.Value; // DateTime.Parse(dResult.date_due.value.ToString()); } string body = dResult.description.value.ToString(); tItem.Body = string.Concat(body, "#<", time_start, "#", time_due); tItem.Status = GetStatus(dResult.status.value.ToString()); tItem.Importance = GetImportance(dResult.priority.value.ToString()); if (oProp == null) { oProp = tItem.UserProperties.Add("SOModifiedDate", Outlook.OlUserPropertyType.olText); } oProp.Value = dResult.date_modified.value.ToString(); Outlook.UserProperty oProp2 = tItem.UserProperties["SEntryID"]; if (oProp2 == null) { oProp2 = tItem.UserProperties.Add("SEntryID", Outlook.OlUserPropertyType.olText); } oProp2.Value = dResult.id.value.ToString(); Log.Warn("\tsave 1"); tItem.Save(); } oItem.OModifiedDate = DateTime.ParseExact(dResult.date_modified.value.ToString(), "yyyy-MM-dd HH:mm:ss", null); return(oItem); } }
private void SyncFolder(Outlook.MAPIFolder tasksFolder) { Log.Warn("SyncTasks"); Log.Warn("My UserId= " + clsSuiteCRMHelper.GetUserId()); try { var untouched = new HashSet <SyncState <Outlook.TaskItem> >(ItemsSyncState); int iOffset = 0; while (true) { eGetEntryListResult _result2 = clsSuiteCRMHelper.GetEntryList("Tasks", String.Empty, 0, "date_start DESC", iOffset, false, clsSuiteCRMHelper.GetSugarFields("Tasks")); var nextOffset = _result2.next_offset; if (iOffset == nextOffset) { break; } foreach (var oResult in _result2.entry_list) { try { var state = UpdateFromCrm(tasksFolder, oResult); if (state != null) { untouched.Remove(state); } } catch (Exception ex) { Log.Error("ThisAddIn.SyncTasks", ex); } } iOffset = nextOffset; if (iOffset == 0) { break; } } try { var lItemToBeDeletedO = untouched.Where(a => a.ExistedInCrm); foreach (var oItem in lItemToBeDeletedO) { oItem.OutlookItem.Delete(); ItemsSyncState.Remove(oItem); } var lItemToBeAddedToS = untouched.Where(a => !a.ExistedInCrm); foreach (var oItem in lItemToBeAddedToS) { AddToCrm(oItem.OutlookItem); } } catch (Exception ex) { Log.Error("ThisAddIn.SyncTasks", ex); } } catch (Exception ex) { Log.Error("ThisAddIn.SyncTasks", ex); } }
protected override SyncState <Outlook.AppointmentItem> GetExistingSyncState(Outlook.AppointmentItem oItem) { return(ItemsSyncState.FirstOrDefault(a => !a.IsDeletedInOutlook && a.OutlookItem.EntryID == oItem.EntryID)); }
private void AddToCrm(Outlook.TaskItem oItem, string sID = "") { Log.Warn("AddTaskToS"); //if (!settings.SyncCalendar) // return; if (oItem == null) { return; } try { string _result = String.Empty; eNameValue[] data = new eNameValue[7]; string strStatus = String.Empty; string strImportance = String.Empty; switch (oItem.Status) { case Outlook.OlTaskStatus.olTaskNotStarted: strStatus = "Not Started"; break; case Outlook.OlTaskStatus.olTaskInProgress: strStatus = "In Progress"; break; case Outlook.OlTaskStatus.olTaskComplete: strStatus = "Completed"; break; case Outlook.OlTaskStatus.olTaskDeferred: strStatus = "Deferred"; break; } switch (oItem.Importance) { case Outlook.OlImportance.olImportanceLow: strImportance = "Low"; break; case Outlook.OlImportance.olImportanceNormal: strImportance = "Medium"; break; case Outlook.OlImportance.olImportanceHigh: strImportance = "High"; break; } DateTime uTCDateTime = new DateTime(); DateTime time2 = new DateTime(); uTCDateTime = oItem.StartDate.ToUniversalTime(); if (oItem.DueDate != null) { time2 = oItem.DueDate.ToUniversalTime(); } string body = String.Empty; string str, str2; str = str2 = String.Empty; if (oItem.Body != null) { body = oItem.Body.ToString(); var times = this.ParseTimesFromTaskBody(body); if (times != null) { uTCDateTime = uTCDateTime.Add(times[0]); time2 = time2.Add(times[1]); //check max date, date must has value ! if (uTCDateTime.ToUniversalTime().Year < 4000) { str = string.Format("{0:yyyy-MM-dd HH:mm:ss}", uTCDateTime.ToUniversalTime()); } if (time2.ToUniversalTime().Year < 4000) { str2 = string.Format("{0:yyyy-MM-dd HH:mm:ss}", time2.ToUniversalTime()); } } else { str = oItem.StartDate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"); str2 = oItem.DueDate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"); } } else { str = oItem.StartDate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"); str2 = oItem.DueDate.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss"); } //str = "2016-11-10 11:34:01"; //str2 = "2016-11-19 11:34:01"; string description = String.Empty; if (!string.IsNullOrEmpty(body)) { int lastIndex = body.LastIndexOf("#<"); if (lastIndex >= 0) { description = body.Remove(lastIndex); } else { description = body; } } Log.Warn("\tdescription= " + description); data[0] = clsSuiteCRMHelper.SetNameValuePair("name", oItem.Subject); data[1] = clsSuiteCRMHelper.SetNameValuePair("description", description); data[2] = clsSuiteCRMHelper.SetNameValuePair("status", strStatus); data[3] = clsSuiteCRMHelper.SetNameValuePair("date_due", str2); data[4] = clsSuiteCRMHelper.SetNameValuePair("date_start", str); data[5] = clsSuiteCRMHelper.SetNameValuePair("priority", strImportance); if (sID == String.Empty) { data[6] = clsSuiteCRMHelper.SetNameValuePair("assigned_user_id", clsSuiteCRMHelper.GetUserId()); } else { data[6] = clsSuiteCRMHelper.SetNameValuePair("id", sID); } _result = clsSuiteCRMHelper.SetEntryUnsafe(data, "Tasks"); Outlook.UserProperty oProp = oItem.UserProperties["SOModifiedDate"]; if (oProp == null) { oProp = oItem.UserProperties.Add("SOModifiedDate", Outlook.OlUserPropertyType.olText); } oProp.Value = DateTime.UtcNow; Outlook.UserProperty oProp2 = oItem.UserProperties["SEntryID"]; if (oProp2 == null) { oProp2 = oItem.UserProperties.Add("SEntryID", Outlook.OlUserPropertyType.olText); } oProp2.Value = _result; string entryId = oItem.EntryID; oItem.Save(); var sItem = ItemsSyncState.FirstOrDefault(a => a.OutlookItem.EntryID == entryId); if (sItem != null) { sItem.OutlookItem = oItem; sItem.OModifiedDate = DateTime.UtcNow; sItem.CrmEntryId = _result; } else { ItemsSyncState.Add(new TaskSyncState { CrmEntryId = _result, OModifiedDate = DateTime.UtcNow, OutlookItem = oItem }); } Log.Warn("\tdate_start= " + str + ", date_due=" + str2); } catch (Exception ex) { Log.Error("ThisAddIn.AddTaskToS", ex); } }
/// <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, eEntryValue crmItem, DateTime date_start) { Outlook.AppointmentItem olItem = appointmentsFolder.Items.Add(Outlook.OlItemType.olAppointmentItem); olItem.Subject = crmItem.GetValueAsString("name"); olItem.Body = crmItem.GetValueAsString("description"); LogItemAction(olItem, "AppointmentSyncing.AddNewItemFromCrmToOutlook"); if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_start"))) { olItem.Start = date_start; int iMin = 0, iHour = 0; if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("duration_minutes"))) { iMin = int.Parse(crmItem.GetValueAsString("duration_minutes")); } if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("duration_hours"))) { iHour = int.Parse(crmItem.GetValueAsString("duration_hours")); } if (crmType == AppointmentSyncing.CrmModule) { olItem.Location = crmItem.GetValueAsString("location"); olItem.End = olItem.Start; if (iHour > 0) { olItem.End.AddHours(iHour); } if (iMin > 0) { olItem.End.AddMinutes(iMin); } } Log.Info("\tdefault SetRecepients"); SetRecipients(olItem, crmItem.GetValueAsString("id"), crmType); try { olItem.Duration = iMin + iHour * 60; } catch (Exception) { } } string crmId = crmItem.GetValueAsString("id"); EnsureSynchronisationPropertiesForOutlookItem(olItem, crmItem.GetValueAsString("date_modified"), crmType, crmId); var 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.Save(); LogItemAction(newState.OutlookItem, "AppointmentSyncing.AddNewItemFromCrmToOutlook, saved item"); return(newState); }