/// <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);
        }
Пример #2
0
        /// <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>
        /// 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);
        }
Пример #4
0
 /// <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);
     }
 }
        /// <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);
            }
        }
Пример #6
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);
        }
 /// <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);
     }
 }
        /// <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);
        }
Пример #9
0
        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);
            }
        }
Пример #10
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="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);
            }
        }
Пример #12
0
        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);
        }
Пример #13
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);
        }
Пример #14
0
        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);
            }
        }
Пример #15
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);
            }
        }