Exemple #1
0
        /// <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="candidateItem">The candidate item from CRM.</param>
        /// <returns>The synchronisation state of the item updated (if it was updated).</returns>
        protected override SyncState <Outlook.AppointmentItem> UpdateFromCrm(
            Outlook.MAPIFolder folder,
            string crmType,
            eEntryValue crmItem)
        {
            SyncState <Outlook.AppointmentItem> result = null;
            DateTime date_start = DateTime.ParseExact(crmItem.GetValueAsString("date_start"), "yyyy-MM-dd HH:mm:ss", null);

            date_start = date_start.Add(new DateTimeOffset(DateTime.Now).Offset); // correct for offset from UTC.
            if (date_start >= GetStartDate())
            {
                /* search for the item among the items I already know about */
                var oItem = this.ItemsSyncState.FirstOrDefault(a => a.CrmEntryId == crmItem.GetValueAsString("id") && a.CrmType == crmType);
                if (oItem == null)
                {
                    /* didn't find it, so add it to Outlook */
                    result = AddNewItemFromCrmToOutlook(folder, crmType, crmItem, date_start);
                }
                else
                {
                    /* found it, so update it from the CRM item */
                    result = UpdateExistingOutlookItemFromCrm(crmType, crmItem, date_start, oItem);
                }
            }

            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="candidateItem">The candidate item from CRM.</param>
        /// <returns>The synchronisation state of the item updated (if it was updated).</returns>
        private SyncState <Outlook.AppointmentItem> MaybeUpdateAppointmentFromCrmToOutlook(
            Outlook.MAPIFolder folder,
            string crmType,
            eEntryValue candidateItem)
        {
            SyncState <Outlook.AppointmentItem> result = null;
            dynamic  crmItem    = JsonConvert.DeserializeObject(candidateItem.name_value_object.ToString());
            DateTime date_start = DateTime.ParseExact(crmItem.date_start.value.ToString(), "yyyy-MM-dd HH:mm:ss", null);

            date_start = date_start.Add(new DateTimeOffset(DateTime.Now).Offset); // correct for offset from UTC.
            if (date_start >= GetStartDate())
            {
                /* search for the item among the items I already know about */
                var oItem = this.ItemsSyncState.FirstOrDefault(a => a.CrmEntryId == crmItem.id.value.ToString() && a.CrmType == crmType);
                if (oItem == null)
                {
                    /* didn't find it, so add it to Outlook */
                    result = AddNewItemFromCrmToOutlook(folder, crmType, crmItem, date_start);
                }
                else
                {
                    /* found it, so update it from the CRM item */
                    result = UpdateExistingOutlookItemFromCrm(crmType, crmItem, date_start, oItem);
                }
            }

            return(result);
        }
        /// <summary>
        /// Update an existing Outlook item with values taken from a corresponding CRM item. Note that
        /// this just overwrites all values in the Outlook item.
        /// </summary>
        /// <param name="crmItem">The CRM item from which values are to be taken.</param>
        /// <param name="itemSyncState">The sync state of an outlook item assumed to correspond with the CRM item.</param>
        /// <returns>An appropriate sync state.</returns>
        private SyncState <Outlook.ContactItem> UpdateExistingOutlookItemFromCrm(eEntryValue crmItem, SyncState <Outlook.ContactItem> itemSyncState)
        {
            Outlook.ContactItem  outlookItem      = itemSyncState.OutlookItem;
            Outlook.UserProperty dateModifiedProp = outlookItem.UserProperties["SOModifiedDate"];
            Outlook.UserProperty shouldSyncProp   = outlookItem.UserProperties["SShouldSync"];
            this.LogItemAction(outlookItem, "ContactSyncing.UpdateExistingOutlookItemFromCrm");

            if (CrmItemChanged(crmItem, outlookItem))
            {
                DateTime crmDate     = DateTime.Parse(crmItem.GetValueAsString("date_modified"));
                DateTime outlookDate = dateModifiedProp == null ? DateTime.MinValue : DateTime.Parse(dateModifiedProp.Value.ToString());

                if (crmDate > this.LastRunCompleted && outlookDate > this.LastRunCompleted)
                {
                    MessageBox.Show(
                        $"Contact {outlookItem.FirstName} {outlookItem.LastName} has changed both in Outlook and CRM; please check which is correct",
                        "Update problem", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (crmDate > outlookDate)
                {
                    this.SetOutlookItemPropertiesFromCrmItem(crmItem, outlookItem);
                }

                this.LogItemAction(outlookItem, $"ContactSyncing.UpdateExistingOutlookItemFromCrm, saving with {outlookItem.Sensitivity}");

                outlookItem.Save();
            }

            this.LogItemAction(outlookItem, "ContactSyncing.UpdateExistingOutlookItemFromCrm");
            itemSyncState.OModifiedDate = DateTime.ParseExact(crmItem.GetValueAsString("date_modified"), "yyyy-MM-dd HH:mm:ss", null);
            return(itemSyncState);
        }
        /// <summary>
        /// Set all those properties of this outlook item whose values are different from the
        /// equivalent values on this CRM item. Update the synchronisation properties only if some
        /// other property has actually changed.
        /// </summary>
        /// <param name="crmItem">The CRM item from which to take values.</param>
        /// <param name="outlookItem">The Outlook item into which to insert values.</param>
        /// <returns>true if anything was changed.</returns>
        private void SetOutlookItemPropertiesFromCrmItem(eEntryValue crmItem, Outlook.ContactItem outlookItem)
        {
            outlookItem.FirstName                 = crmItem.GetValueAsString("first_name");
            outlookItem.LastName                  = crmItem.GetValueAsString("last_name");
            outlookItem.Email1Address             = crmItem.GetValueAsString("email1");
            outlookItem.BusinessTelephoneNumber   = crmItem.GetValueAsString("phone_work");
            outlookItem.HomeTelephoneNumber       = crmItem.GetValueAsString("phone_home");
            outlookItem.MobileTelephoneNumber     = crmItem.GetValueAsString("phone_mobile");
            outlookItem.JobTitle                  = crmItem.GetValueAsString("title");
            outlookItem.Department                = crmItem.GetValueAsString("department");
            outlookItem.BusinessAddressCity       = crmItem.GetValueAsString("primary_address_city");
            outlookItem.BusinessAddressCountry    = crmItem.GetValueAsString("primary_address_country");
            outlookItem.BusinessAddressPostalCode = crmItem.GetValueAsString("primary_address_postalcode");
            outlookItem.BusinessAddressState      = crmItem.GetValueAsString("primary_address_state");
            outlookItem.BusinessAddressStreet     = crmItem.GetValueAsString("primary_address_street");
            outlookItem.Body = crmItem.GetValueAsString("description");
            if (crmItem.GetValue("account_name") != null)
            {
                outlookItem.Account     = crmItem.GetValueAsString("account_name");
                outlookItem.CompanyName = crmItem.GetValueAsString("account_name");
            }
            outlookItem.BusinessFaxNumber = crmItem.GetValueAsString("phone_fax");
            outlookItem.Title             = crmItem.GetValueAsString("salutation");

            EnsureSynchronisationPropertiesForOutlookItem(
                outlookItem,
                crmItem.GetValueAsString("date_modified"),
                crmItem.GetValueAsString("sync_contact"),
                crmItem.GetValueAsString("id"));
        }
Exemple #5
0
        /// <summary>
        /// Update this Outlook appointment's start and duration from this CRM object.
        /// </summary>
        /// <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>
        /// <param name="olAppointment">The outlook item assumed to correspond with the CRM item.</param>
        private void UpdateOutlookStartAndDuration(string crmType, eEntryValue crmItem, DateTime date_start, Outlook.AppointmentItem olAppointment)
        {
            olAppointment.Start = date_start;
            var minutesString = crmItem.GetValueAsString("duration_minutes");
            var hoursString   = crmItem.GetValueAsString("duration_hours");

            int minutes = string.IsNullOrWhiteSpace(minutesString) ? 0 : int.Parse(minutesString);
            int hours   = string.IsNullOrWhiteSpace(hoursString) ? 0 : int.Parse(hoursString);

            if (crmType == AppointmentSyncing.CrmModule)
            {
                olAppointment.Location = crmItem.GetValueAsString("location");
                olAppointment.End      = olAppointment.Start;
                if (hours > 0)
                {
                    olAppointment.End.AddHours(hours);
                }
                if (minutes > 0)
                {
                    olAppointment.End.AddMinutes(minutes);
                }
                Log.Info("\tSetRecepients");
                SetRecipients(olAppointment, crmItem.GetValueAsString("id"), crmType);
            }
            olAppointment.Duration = minutes + hours * 60;
        }
Exemple #6
0
        /// <summary>
        /// Update an existing Outlook item with values taken from a corresponding CRM item. Note that
        /// this just overwrites all values in the Outlook item.
        /// </summary>
        /// <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>
        /// <param name="oItem">The outlook item assumed to correspond with the CRM item.</param>
        /// <returns>An appropriate sync state.</returns>
        private SyncState <Outlook.AppointmentItem> UpdateExistingOutlookItemFromCrm(
            string crmType,
            eEntryValue crmItem,
            DateTime date_start,
            SyncState <Outlook.AppointmentItem> oItem)
        {
            LogItemAction(oItem.OutlookItem, "AppointmentSyncing.UpdateExistingOutlookItemFromCrm");
            Outlook.AppointmentItem olAppointment          = oItem.OutlookItem;
            Outlook.UserProperty    olPropertyModifiedDate = olAppointment.UserProperties["SOModifiedDate"];

            if (olPropertyModifiedDate.Value != crmItem.GetValueAsString("date_modified"))
            {
                olAppointment.Subject = crmItem.GetValueAsString("name");
                olAppointment.Body    = crmItem.GetValueAsString("description");
                if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_start")))
                {
                    UpdateOutlookStartAndDuration(crmType, crmItem, date_start, olAppointment);
                }

                EnsureSynchronisationPropertiesForOutlookItem(olAppointment, crmItem.GetValueAsString("date_modified"), crmType, crmItem.id);
                olAppointment.Save();
                LogItemAction(oItem.OutlookItem, "AppointmentSyncing.UpdateExistingOutlookItemFromCrm, item saved");
            }
            Log.Warn((string)("Not default dResult.date_modified= " + crmItem.GetValueAsString("date_modified")));
            oItem.OModifiedDate = DateTime.ParseExact(crmItem.GetValueAsString("date_modified"), "yyyy-MM-dd HH:mm:ss", null);

            return(oItem);
        }
        /// <summary>
        /// Set this outlook item's duration, but also end time and location, from this CRM item.
        /// </summary>
        /// <param name="crmType">The type of the CRM item.</param>
        /// <param name="crmItem">The CRM item.</param>
        /// <param name="olItem">The Outlook item.</param>
        private void SetOutlookItemDuration(string crmType, eEntryValue crmItem, Outlook.AppointmentItem olItem)
        {
            int minutes = 0, hours = 0;

            try
            {
                if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("duration_minutes")))
                {
                    minutes = int.Parse(crmItem.GetValueAsString("duration_minutes"));
                }
                if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("duration_hours")))
                {
                    hours = int.Parse(crmItem.GetValueAsString("duration_hours"));
                }

                int durationMinutes = minutes + hours * 60;

                if (crmType == AppointmentSyncing.CrmModule)
                {
                    olItem.Location = crmItem.GetValueAsString("location");
                    olItem.End      = olItem.Start.AddMinutes(durationMinutes);
                }

                olItem.Duration = durationMinutes;
            }
            catch (Exception any)
            {
                Log.Error("AppointmentSyncing.SetOutlookItemDuration", any);
            }
        }
Exemple #8
0
        /// <summary>
        /// A CRM item is perceived to have changed if its modified date is different from
        /// that of its Outlook representation, or if its should sync flag is.
        /// </summary>
        /// <param name="crmItem">A CRM item.</param>
        /// <param name="outlookItem">An Outlook item, assumed to represent the same entity.</param>
        /// <returns>True if either of these propertyies differ between the representations.</returns>
        private bool CrmItemChanged(eEntryValue crmItem, Outlook.ContactItem outlookItem)
        {
            Outlook.UserProperty dateModifiedProp = outlookItem.UserProperties["SOModifiedDate"];

            return(dateModifiedProp.Value != crmItem.GetValueAsString("date_modified") ||
                   ShouldSyncFlagChanged(outlookItem, crmItem));
        }
        private void MaybeAddAcceptDeclineLinks(eEntryValue crmItem, Outlook.AppointmentItem olItem, string crmType)
        {
            string description = crmItem.GetValueAsString("description") ?? string.Empty;

            if (this.DefaultCrmModule.Equals(crmType) && description.IndexOf(AcceptDeclineHeader) == -1)
            {
                olItem.Body = $"{description}\n-- \n\n{this.AcceptDeclineLinks(crmItem)}";
            }
        }
        private static string AcceptDeclineLink(eEntryValue crmItem, string acceptStatus)
        {
            StringBuilder bob = new StringBuilder();

            bob.Append($"To {acceptStatus} this invitation: {Globals.ThisAddIn.Settings.host}/index.php?entryPoint=acceptDecline&module=Meetings")
            .Append($"&user_id={clsSuiteCRMHelper.GetUserId()}")
            .Append($"&record={crmItem.id}")
            .Append($"&accept_status={acceptStatus}\n");

            return(bob.ToString());
        }
        private string AcceptDeclineLinks(eEntryValue crmItem)
        {
            StringBuilder bob = new StringBuilder(AcceptDeclineHeader);

            foreach (string acceptStatus in new string[] { "Accept", "Tentative", "Decline" })
            {
                bob.Append(AcceptDeclineLink(crmItem, acceptStatus));
            }

            return(bob.ToString());
        }
Exemple #12
0
        public static string GetValueByKey(eEntryValue entry, string key)
        {
            string str = string.Empty;

            foreach (eNameValue _value in entry.name_value_list1)
            {
                if (_value.name == key)
                {
                    str = _value.value.ToString();
                }
            }
            return(str);
        }
Exemple #13
0
        private SyncState <Outlook.TaskItem> UpdateExistingOutlookItemFromCrm(eEntryValue crmItem, DateTime?date_start, DateTime?date_due, string time_start, string time_due, SyncState <Outlook.TaskItem> syncStateForItem)
        {
            Outlook.TaskItem     outlookItem = syncStateForItem.OutlookItem;
            Outlook.UserProperty oProp       = outlookItem.UserProperties["SOModifiedDate"];

            if (oProp.Value != crmItem.GetValueAsString("date_modified"))
            {
                SetOutlookItemPropertiesFromCrmItem(crmItem, date_start, date_due, time_start, time_due, outlookItem);
                outlookItem.Save();
            }
            syncStateForItem.OModifiedDate = DateTime.ParseExact(crmItem.GetValueAsString("date_modified"), "yyyy-MM-dd HH:mm:ss", null);

            return(syncStateForItem);
        }
        /// <summary>
        /// Detect whether the should sync flag value is different between these two representations.
        /// </summary>
        /// <param name="outlookItem">An outlook item.</param>
        /// <param name="crmItem">A CRM item, presumed to represent the same entity.</param>
        /// <returns>True if the should sync flag values are different, else false.</returns>
        private bool ShouldSyncFlagChanged(Outlook.ContactItem outlookItem, eEntryValue crmItem)
        {
            bool result = false;

            Outlook.UserProperty shouldSyncProp = outlookItem.UserProperties["SShouldSync"];

            if (shouldSyncProp != null)
            {
                string crmShouldSync = ShouldSyncContact(crmItem).ToString().ToLower();
                string olShouldSync  = shouldSyncProp.Value.ToLower();

                result = crmShouldSync != olShouldSync;
            }

            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="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);
        }
Exemple #16
0
        private void SetOutlookItemPropertiesFromCrmItem(eEntryValue crmItem, DateTime?date_start, DateTime?date_due, string time_start, string time_due, Outlook.TaskItem outlookItem)
        {
            outlookItem.Subject = crmItem.GetValueAsString("name");

            if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_start")))
            {
                Log.Warn("\ttItem.StartDate= " + outlookItem.StartDate + ", date_start=" + date_start);
                outlookItem.StartDate = date_start.Value;
            }
            if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_due")))
            {
                outlookItem.DueDate = date_due.Value; // DateTime.Parse(dResult.date_due.value.ToString());
            }

            string body = crmItem.GetValueAsString("description");

            outlookItem.Body       = string.Concat(body, "#<", time_start, "#", time_due);
            outlookItem.Status     = GetStatus(crmItem.GetValueAsString("status"));
            outlookItem.Importance = GetImportance(crmItem.GetValueAsString("priority"));
            EnsureSynchronisationPropertiesForOutlookItem(outlookItem, crmItem.GetValueAsString("date_modified"), DefaultCrmModule, crmItem.id);
        }
        private void SetOutlookItemPropertiesFromCrmItem(eEntryValue crmItem, DateTime?date_start, DateTime?date_due, string time_start, string time_due, Outlook.TaskItem outlookItem)
        {
            outlookItem.Subject = crmItem.GetValueAsString("name");

            try
            {
                if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_start")))
                {
                    Log.Warn("\ttItem.StartDate= " + outlookItem.StartDate + ", date_start=" + date_start);
                    outlookItem.StartDate = date_start.Value;
                }
            }
            catch (Exception fail)
            {
                /* you (sometimes? always?) can't set the start or due dates of tasks. Investigate. */
                Log.Error($"TaskSyncing.SetOutlookItemPropertiesFromCrmItem: Failed to set start date on task because {fail.Message}", fail);
            }
            try
            {
                if (!string.IsNullOrWhiteSpace(crmItem.GetValueAsString("date_due")))
                {
                    outlookItem.DueDate = date_due.Value; // DateTime.Parse(dResult.date_due.value.ToString());
                }
            }
            catch (Exception fail)
            {
                /* you (sometimes? always?) can't set the start or due dates of tasks. Investigate. */
                Log.Error($"TaskSyncing.SetOutlookItemPropertiesFromCrmItem: Failed to set due date on task because {fail.Message}", fail);
            }

            string body = crmItem.GetValueAsString("description");

            outlookItem.Body       = string.Concat(body, "#<", time_start, "#", time_due);
            outlookItem.Status     = GetStatus(crmItem.GetValueAsString("status"));
            outlookItem.Importance = GetImportance(crmItem.GetValueAsString("priority"));
            EnsureSynchronisationPropertiesForOutlookItem(outlookItem, crmItem.GetValueAsString("date_modified"), DefaultCrmModule, crmItem.id);
        }
        /// <summary>
        /// Construct suitable label text for a tree node representing this value in this module.
        /// </summary>
        /// <param name="module">The name of the module.</param>
        /// <param name="entry">The value in the module.</param>
        /// <returns>A canonical tree node label.</returns>
        private static string ConstructNodeName(string module, eEntryValue entry)
        {
            StringBuilder nodeNameBuilder = new StringBuilder();
            string        keyValue        = string.Empty;

            nodeNameBuilder.Append(clsSuiteCRMHelper.GetValueByKey(entry, "first_name"))
            .Append(" ")
            .Append(clsSuiteCRMHelper.GetValueByKey(entry, "last_name"));

            if (String.IsNullOrWhiteSpace(nodeNameBuilder.ToString()))
            {
                nodeNameBuilder.Append(clsSuiteCRMHelper.GetValueByKey(entry, "name"));
            }

            switch (module)
            {
            case "Bugs":
                keyValue = clsSuiteCRMHelper.GetValueByKey(entry, "bug_number");
                break;

            case "Cases":
                keyValue = clsSuiteCRMHelper.GetValueByKey(entry, "case_number");
                break;

            default:
                keyValue = clsSuiteCRMHelper.GetValueByKey(entry, "account_name");
                break;
            }

            if (keyValue != string.Empty)
            {
                nodeNameBuilder.Append($" ({keyValue})");
            }

            return(nodeNameBuilder.ToString());
        }
Exemple #19
0
 /// <summary>
 /// Set up synchronisation properties for this outlook item from this CRM item, assuming my default CRM module.
 /// </summary>
 /// <param name="olItem">The Outlook item.</param>
 /// <param name="crmItem">The CRM item.</param>
 protected virtual void EnsureSynchronisationPropertiesForOutlookItem(OutlookItemType olItem, eEntryValue crmItem)
 {
     this.EnsureSynchronisationPropertiesForOutlookItem(
         olItem,
         crmItem,
         this.DefaultCrmModule);
 }
Exemple #20
0
 /// <summary>
 /// Get the existing sync state representing this item, if it exists, else null.
 /// </summary>
 /// <param name="crmItem">The item</param>
 /// <returns>the existing sync state representing this item, if it exists, else null.</returns>
 protected SyncState <OutlookItemType> GetExistingSyncState(eEntryValue crmItem)
 {
     return(crmItem == null ?
            null :
            this.GetExistingSyncState(crmItem.GetValueAsString("id")));
 }
        /// <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>
        /// Return true if this CRM contact should be synchronised with Outlook.
        /// </summary>
        /// <remarks>
        /// If the 'Sync to Outlook' field is set in CRM, we get 'true' as the value of crmItem.sync_contact.
        /// But if the field is not set, we do not (or do not reliably) get 'false'. The sync_contact
        /// property may have a value of ''.
        /// </remarks>
        /// <param name="crmContact">The CRM contact.</param>
        /// <returns>true if this CRM contact should be synchronised with Outlook.</returns>
        private bool ShouldSyncContact(eEntryValue crmContact)
        {
            object val = crmContact.GetValue("sync_contact");

            return(Boolean.TrueString.ToLower().Equals(val.ToString().ToLower()));
        }
        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);
        }
Exemple #24
0
        /// <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);
        }
Exemple #25
0
 /// <summary>
 /// Set up synchronisation properties for this outlook item from this CRM item, assuming my default CRM module.
 /// </summary>
 /// <param name="olItem">The Outlook item.</param>
 /// <param name="crmItem">The CRM item.</param>
 /// <param name="type">The value for the SType property (CRM module name).</param>
 protected virtual void EnsureSynchronisationPropertiesForOutlookItem(OutlookItemType olItem, eEntryValue crmItem, string type)
 {
     this.EnsureSynchronisationPropertiesForOutlookItem(
         olItem,
         crmItem.GetValueAsString("date_modified"),
         type,
         crmItem.GetValueAsString("id"));
 }
Exemple #26
0
        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);
        }
Exemple #27
0
        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);
        }
 public static string GetValueByKey(eEntryValue entry, string key)
 {
     string str = string.Empty;
     foreach (eNameValue _value in entry.name_value_list1)
     {
         if (_value.name == key)
         {
             str = _value.value;
         }
     }
     return str;
 }
Exemple #29
0
        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);
        }
Exemple #30
0
 /// <summary>
 /// Update a single item in the specified Outlook folder with changes from CRM. If the item
 /// does not exist, create it.
 /// </summary>
 /// <param name="folder">The folder to synchronise into.</param>
 /// <param name="crmType">The CRM type of the candidate item.</param>
 /// <param name="candidateItem">The candidate item from CRM.</param>
 /// <returns>The synchronisation state of the item updated (if it was updated).</returns>
 protected abstract SyncState <OutlookItemType> AddOrUpdateItemFromCrmToOutlook(Outlook.MAPIFolder folder, string crmType, eEntryValue candidateItem);
Exemple #31
0
        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);
            }
        }