예제 #1
0
        /// <summary>
        /// Возвращает результат поиска в кеше или в папке outlook объект SyncTransferData имеющий соответственный uri.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        protected override SyncTransferData GetDataItem(ItemMetadata item)
        {
            SyncTransferData retVal = null;
            string           uri    = item.GetStringField(URI_COLUMNNAME);

            foreach (SyncTransferData data in _localItems)
            {
                if (data.Uri == uri)
                {
                    retVal = data;
                    break;
                }
            }

            if (retVal == null)
            {
                OutlookAppointment appItem = FindAppointment(item);
                if (appItem == null)
                {
                    throw new System.Exception("appointment not found");
                }
                retVal = Appointment2TransferData(appItem);
            }
            return(retVal);
        }
        /// <summary>
        /// Updates an appointment in the custom calendar
        /// </summary>
        /// <param name="appointment"></param>
        /// <returns></returns>
        private bool UpdateAppointment(OutlookAppointment appointment)
        {
            if (_customCalendar == null || appointment == null)
            {
                return(false);
            }
            Outlook.AppointmentItem foundItem;

            foundItem = _customCalendar.Items.Find(String.Format("[" + ITEM_PROPERTY_SYNC_ID + "] = '{0}'", appointment.SyncID));

            if (foundItem == null)
            {
                foundItem = _customCalendar.Items.Find(String.Format("[" + ITEM_PROPERTY_GLOBAL_A_ID + "] = '{0}'", appointment.GlobalAppointmentID));
            }

            if (foundItem != null)
            {
                foundItem.Subject = appointment.Subject;
                foundItem.Body    = appointment.Body;
                foundItem.Start   = appointment.Start;
                foundItem.End     = appointment.End;
                //foundItem.ReminderSet = appointment.ReminderSet;
                //foundItem.ReminderMinutesBeforeStart = appointment.ReminderMinutesBeforeStart;
                foundItem.Location    = appointment.Location;
                foundItem.AllDayEvent = appointment.AllDayEvent;

                //if (appointment.Attachments != null)
                //foundItem.Attachments.Add(appointment.Attachments);

                foundItem.Duration = appointment.Duration;
                //foundItem.Importance = appointment.Importance;

                if (foundItem.ItemProperties[ITEM_PROPERTY_SYNC_ID] == null)
                {
                    foundItem.ItemProperties.Add(ITEM_PROPERTY_SYNC_ID, Outlook.OlUserPropertyType.olText);
                    foundItem.Save();
                }

                foundItem.ItemProperties[ITEM_PROPERTY_SYNC_ID].Value = appointment.SyncID;
                foundItem.Save();

                // updating the information, that this item was updated by the sync
                if (foundItem.ItemProperties[ITEM_PROPERTY_SYNC_UPDATE] == null)
                {
                    foundItem.ItemProperties.Add(ITEM_PROPERTY_SYNC_UPDATE, Outlook.OlUserPropertyType.olText);
                    foundItem.Save();
                }

                foundItem.ItemProperties[ITEM_PROPERTY_SYNC_UPDATE].Value = foundItem.LastModificationTime;
                foundItem.Save();

                Marshal.ReleaseComObject(foundItem);
                foundItem = null;

                return(true);
            }

            // couldn't find the appointment
            return(false);
        }
예제 #3
0
        protected override void ReadDataStore()
        {
            DebugAssistant.Log("Entering ReadDataStore()");

            _localItems.Clear();

            foreach (OutlookItem outlookItem in OutlookMapiFolder.Items)
            {
                OutlookAppointment appItem = outlookItem as OutlookAppointment;
                if (appItem != null)
                {
                    try
                    {
                        SyncTransferData transferData = Appointment2TransferData(appItem);
                        _localItems.Add(transferData);
                    }
                    catch (Exception e)
                    {
                        DebugAssistant.Log(DebugSeverity.Error | DebugSeverity.MessageBox, e.Message);
                        throw;
                    }
                }
            }

            DebugAssistant.Log("Leaving ReadDataStore(), localLastModificationTimesUtc.Count = " + _localItems.Count);
        }
 /// <summary>
 /// Deletes the appointment in the custom calendar
 /// </summary>
 /// <param name="appointment">appointment to be deleted</param>
 /// <returns>returns true if successfull</returns>
 private bool DeleteAppointment(OutlookAppointment appointment)
 {
     if (_customCalendar == null || appointment == null)
     {
         return(false);
     }
     return(DeleteAppointment(appointment.SyncID));
 }
예제 #5
0
        protected override bool DeleteDataItem(ItemChange change, ItemMetadata item, SyncTransferData data)
        {
            OutlookAppointment appItem = FindAppointment(item);

            if (appItem == null)
            {
                throw new System.Exception("Appointment for delete not found");
            }
            appItem.Delete();
            return(true);
        }
예제 #6
0
        /// <summary>
        /// Parses an Outlook appointment into XML for a CalDav request.
        /// </summary>
        /// <param name="_appointment">The OutlookAppointment to parse.</param>
        /// <returns>The XML string to use for CalDav request.</returns>
        public static String Parse(OutlookAppointment _appointment)
        {
            String querystring = "";
            String starttimestamp;
            String endtimestamp;

            if (_appointment.AllDayEvent)
            {
                starttimestamp = ";VALUE=DATE:" + _appointment.Start.ToString(@"yyyyMMdd");
                endtimestamp   = ";VALUE=DATE:" + _appointment.End.ToString(@"yyyyMMdd");
            }
            else
            {
                starttimestamp = ";VALUE=DATE-TIME:" + _appointment.Start.ToString(@"yyyyMMdd\THHmmss");
                endtimestamp   = ";VALUE=DATE-TIME:" + _appointment.End.ToString(@"yyyyMMdd\THHmmss");
            }

            String lastmodified = DateTime.Now.AddHours(CaldavConnector.LASTMODIFIED_DATE_OFFSET).ToString(@"yyyyMMdd\THHmmss");

            querystring += "BEGIN:VCALENDAR\n";
            querystring += "VERSION:2.0\n";
            querystring += "BEGIN:VEVENT\n";
            if (_appointment.SyncID != null && !_appointment.SyncID.Equals(""))
            {
                querystring += "UID:" + _appointment.SyncID + "\n";
            }
            if (_appointment.Subject != null && !_appointment.Subject.Equals(""))
            {
                querystring += "SUMMARY:" + _appointment.Subject + "\n";
            }
            if (starttimestamp != null && !starttimestamp.Equals(""))
            {
                querystring += "DTSTART" + starttimestamp + "\n";
            }
            if (endtimestamp != null && !endtimestamp.Equals(""))
            {
                querystring += "DTEND" + endtimestamp + "\n";
            }
            if (_appointment.Location != null && !_appointment.Location.Equals(""))
            {
                querystring += "LOCATION:" + _appointment.Location + "\n";
            }
            if (_appointment.Body != null && !_appointment.Body.Equals(""))
            {
                querystring += "DESCRIPTION:" + _appointment.Body + "\n";
            }
            querystring += "LAST-MODIFIED:" + lastmodified + "\n";
            querystring += "END:VEVENT\n";
            querystring += "END:VCALENDAR";

            return(querystring);
        }
예제 #7
0
        protected override void CreateDataItem(ItemChange change, ItemMetadata item, SyncTransferData data)
        {
            OutlookAppointment appItem = OutlookMapiFolder.AddItem(Outlook.OlItemType.olAppointmentItem) as OutlookAppointment;

            if (appItem == null)
            {
                throw new InvalidCastException("OutlookAppointment");
            }

            //Сохраним чтобы у appointment появился globalUID
            appItem = TransferData2AppointmentItem(data, appItem);
            item.SetCustomField(URI_COLUMNNAME, appItem.EntryID);
        }
        /// <summary>
        /// Checks the server for new, updated and deleted items and returns them.
        /// </summary>
        /// <returns>A collection with all new, updated and deleted items on serverside.</returns>
        public AppointmentSyncCollection GetUpdates()
        {
            AppointmentSyncCollection returnCollection   = new AppointmentSyncCollection();
            List <CalDavElement>      responseListCalDav = GetAllItemsFromServer();

            //Check for new and updated items
            foreach (var remoteitem in responseListCalDav)
            {
                String foundETag = _localStorage.FindEtag(remoteitem.Guid);
                if (foundETag == null)
                {
                    returnCollection.AddList.Add(CalDavElementToAppointmentItemConverter.Convert(remoteitem));
                    _localStorage.WriteEntry(remoteitem.Guid, remoteitem.ETag, remoteitem.Url);
                }
                else if (foundETag != remoteitem.ETag)
                {
                    returnCollection.UpdateList.Add(CalDavElementToAppointmentItemConverter.Convert(remoteitem));
                    _localStorage.EditETag(remoteitem.Guid, remoteitem.ETag);
                }
            }
            ;

            //Check for deleted items
            Boolean            deleted;
            OutlookAppointment deletedAppointment = new OutlookAppointment();
            List <String>      guidsToDelete      = new List <String>();

            foreach (var localitem in _localStorage.GetAll())
            {
                deleted = true;
                foreach (var remoteitem in responseListCalDav)
                {
                    if (remoteitem.Guid.Equals(localitem.Key))
                    {
                        deleted = false;
                    }
                }
                if (deleted)
                {
                    deletedAppointment.SyncID = localitem.Key;
                    returnCollection.DeleteList.Add(deletedAppointment);
                    guidsToDelete.Add(localitem.Key);
                }
            }
            foreach (var item in guidsToDelete)
            {
                _localStorage.DeleteEntry(item);
            }

            return(returnCollection);
        }
예제 #9
0
        /// <summary>
        /// Преобразует иерархию объектов SyncTranferData в Outlook Appointment
        /// </summary>
        /// <param name="transferData">The transfer data.</param>
        /// <param name="appItem">The app item.</param>
        /// <returns></returns>
        private OutlookAppointment TransferData2AppointmentItem(SyncTransferData transferData, OutlookAppointment appItem)
        {
            ITransferDataSerializable serializer = new AppointmentSerializer(appItem);

            serializer.Deserialize(transferData);
            foreach (SyncTransferData child in transferData.Childrens)
            {
                if (child.SyncDataName == RecurrencePatternTransferData.DataName)
                {
                    OutlookRecurrencePattern rPattern = appItem.GetRecurrencePattern();
                    serializer = new RecurrencePatternSerializer(rPattern);
                    if (serializer != null)
                    {
                        serializer.Deserialize(child);
                    }
                }
                else if (child.SyncDataName == RecipientTransferData.DataName)
                {
                    serializer = new RecipientSerializer();
                    string recipientName = (string)serializer.Deserialize(child);
                    if (string.IsNullOrEmpty(recipientName))
                    {
                        OutlookRecipient recipient = appItem.AddRecipient(recipientName);
                    }
                }
            }

            //Сохранем outlook appointment
            appItem.Save();
            //Переносим exception
            if (appItem.IsRecurring)
            {
                OutlookRecurrencePattern rPattern = appItem.GetRecurrencePattern();
                foreach (SyncTransferData child in transferData.Childrens)
                {
                    AppointmentTransferData exception = child as AppointmentTransferData;
                    if (exception != null)
                    {
                        OutlookAppointment appException = rPattern.GetOccurrence(exception.RecurrenceId);
                        TransferData2AppointmentItem(child, appException);
                        if (exception.DeletedException)
                        {
                            appException.Delete();
                        }
                    }
                }
            }
            return(appItem);
        }
        /// <summary>
        /// Does the convertion from CalDavElement into OutlookAppointment.
        /// </summary>
        /// <param name="_myElement">CalDavElement to convert.</param>
        /// <returns>Converted OutlookAppointment.</returns>
        public static OutlookAppointment Convert(CalDavElement _myElement)
        {
            OutlookAppointment _myAppointment = new OutlookAppointment();

            _myAppointment.SyncID               = _myElement.Guid;
            _myAppointment.Subject              = _myElement.Summary;
            _myAppointment.Body                 = _myElement.Description;
            _myAppointment.Start                = (DateTime)_myElement.Start;
            _myAppointment.End                  = (DateTime)_myElement.End;
            _myAppointment.Location             = _myElement.Location;
            _myAppointment.LastModificationTime = (DateTime)_myElement.LastModified;
            _myAppointment.AllDayEvent          = _myElement.AllDayEvent;

            return(_myAppointment);
        }
예제 #11
0
        /// <summary>
        /// Преобразует Outlook appointment  в иерархию объектов transferData
        /// </summary>
        /// <param name="appItem">The app item.</param>
        /// <returns></returns>
        private SyncTransferData Appointment2TransferData(OutlookAppointment appItem)
        {
            SyncTransferData          retVal     = null;
            ITransferDataSerializable serializer = new AppointmentSerializer(appItem);

            retVal = serializer.Serialize();
            if (appItem.IsRecurring)
            {
                OutlookRecurrencePattern rPattern = appItem.GetRecurrencePattern();
                serializer = new RecurrencePatternSerializer(rPattern);
                retVal.Childrens.Add(serializer.Serialize());
                serializer = null;
                foreach (OutlookException exception in rPattern.Exceptions)
                {
                    AppointmentTransferData transferException = new AppointmentTransferData();
                    if (!exception.Deleted)
                    {
                        OutlookAppointment appointmentException = exception.AppointmentItem;
                        serializer        = new AppointmentSerializer(appointmentException);
                        transferException = (AppointmentTransferData)serializer.Serialize();
                        //exception recipient
                        foreach (OutlookRecipient exceptionRecipient in appointmentException.Recipients)
                        {
                            serializer = new RecipientSerializer(exceptionRecipient);
                            transferException.Childrens.Add(serializer.Serialize());
                        }
                    }
                    transferException.DeletedException = exception.Deleted;
                    transferException.RecurrenceId     = exception.OriginalDate;

                    retVal.Childrens.Add(transferException);
                }
            }
            //appointment recipient
            foreach (OutlookRecipient recipient in appItem.Recipients)
            {
                serializer = new RecipientSerializer(recipient);
                retVal.Childrens.Add(serializer.Serialize());
            }

            //Инициализируем дополнительные поля (LastModified и Uri)
            retVal.LastModified = (ulong)appItem.LastModificationTime.ToUniversalTime().Ticks;
            retVal.Uri          = appItem.EntryID;

            return(retVal);
        }
예제 #12
0
        /// <summary>
        /// Finds the appointment.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns></returns>
        public OutlookAppointment FindAppointment(string uri)
        {
            OutlookAppointment retVal = null;

            foreach (OutlookItem outlookItem in OutlookMapiFolder.Items)
            {
                OutlookAppointment appItem = outlookItem as OutlookAppointment;
                if (appItem != null)
                {
                    if (appItem.EntryID == uri)
                    {
                        retVal = appItem;
                        break;
                    }
                }
            }
            return(retVal);
        }
예제 #13
0
        protected override void UpdateDataItem(ItemChange change, ItemMetadata item, SyncTransferData data)
        {
            OutlookAppointment appItem = FindAppointment(item);

            if (appItem == null)
            {
                throw new System.Exception("Appointment for update not found");
            }
            //Удаляем рекурсию
            appItem.ClearRecurrencePattern();
            //Удаляем всех участников
            while (appItem.Recipients.Count() != 0)
            {
                appItem.RemoveRecipient(1);
            }

            appItem = TransferData2AppointmentItem(data, appItem);
        }
        /// <summary>
        /// Creates a new appointment in the custom calendar
        /// </summary>
        /// <param name="appointment">new appointment</param>
        /// <returns>GlobalAppointmentID of the new appointment in Outlook</returns>
        private String CreateAppointment(OutlookAppointment appointment)
        {
            if (_customCalendar == null || appointment == null)
            {
                return(null);
            }

            Outlook.AppointmentItem newAppointment = (Outlook.AppointmentItem)_customCalendar.Items.Add(Outlook.OlItemType.olAppointmentItem);

            newAppointment.Subject     = appointment.Subject;
            newAppointment.Body        = appointment.Body;
            newAppointment.Start       = appointment.Start;
            newAppointment.End         = appointment.End;
            newAppointment.ReminderSet = false;
            //newAppointment.ReminderMinutesBeforeStart = appointment.ReminderMinutesBeforeStart;
            newAppointment.Location    = appointment.Location;
            newAppointment.AllDayEvent = appointment.AllDayEvent;

            //if (appointment.Attachments != null)
            //newAppointment.Attachments.Add(appointment.Attachments);

            newAppointment.Duration   = appointment.Duration;
            newAppointment.Importance = Outlook.OlImportance.olImportanceNormal;

            // GlobalAppointmentID must be stored as custom item property as well, because GlobalAppointmentID property cannot be searched for
            newAppointment.ItemProperties.Add(ITEM_PROPERTY_GLOBAL_A_ID, Outlook.OlUserPropertyType.olText);
            newAppointment.ItemProperties.Add(ITEM_PROPERTY_SYNC_ID, Outlook.OlUserPropertyType.olText);
            newAppointment.ItemProperties.Add(ITEM_PROPERTY_SYNC_UPDATE, Outlook.OlUserPropertyType.olText);

            newAppointment.Save();

            newAppointment.ItemProperties[ITEM_PROPERTY_GLOBAL_A_ID].Value = newAppointment.GlobalAppointmentID;
            newAppointment.ItemProperties[ITEM_PROPERTY_SYNC_ID].Value     = appointment.SyncID;
            newAppointment.ItemProperties[ITEM_PROPERTY_SYNC_UPDATE].Value = newAppointment.LastModificationTime;

            newAppointment.Save();

            return(newAppointment.GlobalAppointmentID);
        }
        /// <summary>
        /// Returns a AppointmentSyncCollection, with all updates since the specified timestamp
        /// </summary>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        private AppointmentSyncCollection GetUpdates(DateTime timestamp)
        {
            if (_customCalendar == null)
            {
                return(null);
            }
            AppointmentSyncCollection syncCollection = new AppointmentSyncCollection();

            // Debug.WriteLine("CalendarHandler: TimeStamp -> " + timestamp);

            foreach (Outlook.AppointmentItem item in _customCalendar.Items)
            {
                Boolean updatedBySync = false;

                //Debug.WriteLine("CalendarHandler: Item (" + item.Subject + ") LastModificationTime -> " + item.LastModificationTime);

                // if the date from the SYNC_UPDATE is newer or as the LastModificationTime, the item was not updated by the user
                if (item.ItemProperties[ITEM_PROPERTY_SYNC_UPDATE] != null && DateTime.Parse(item.ItemProperties[ITEM_PROPERTY_SYNC_UPDATE].Value) >= item.LastModificationTime)
                {
                    updatedBySync = true;
                }

                //Debug.WriteLine("CalendarHandler: Item (" + item.Subject + ") SyncUpdate -> " + syncUpdate);
                //Debug.WriteLine("CalendarHandler: Item (" + item.Subject + ") wasUpdatedBySync -> " + wasUpdatedBySync);

                if (item.LastModificationTime >= timestamp && !updatedBySync)
                {
                    // ADDING
                    // if SyncID does not exist, it is not yet synced and needs to be added to the other calendar
                    if (item.ItemProperties[ITEM_PROPERTY_SYNC_ID] == null)
                    {
                        syncCollection.AddList.Add(new OutlookAppointment(item));

                        if (item.ItemProperties[ITEM_PROPERTY_GLOBAL_A_ID] == null)
                        {
                            // GAI (GlobalAppointmentID) needs to be added as item property, otherwise it cannot be found later
                            Outlook.ItemProperty newProp = item.ItemProperties.Add(ITEM_PROPERTY_GLOBAL_A_ID, Outlook.OlUserPropertyType.olText);
                            item.Save();
                            newProp.Value = item.GlobalAppointmentID;
                            item.Save();
                        }
                    }

                    // UPDATING
                    // if a SyncID exist, it is already synced and needs to be updated in the other calendar
                    else
                    {
                        syncCollection.UpdateList.Add(new OutlookAppointment(item));
                    }
                }
            }

            // DELETING
            foreach (String syncID in GetAppointmentsForDeleting())
            {
                OutlookAppointment item = new OutlookAppointment();
                item.SyncID = syncID;
                syncCollection.DeleteList.Add(item);
            }

            Debug.WriteLine("CalendarHandler (GetUpdates): Added: " + syncCollection.AddList.Count + " | Updated: " + syncCollection.UpdateList.Count + " | Deleted: " + syncCollection.DeleteList.Count);

            ResetDeleteStorage();
            SetSyncTime(DateTime.Now);

            return(syncCollection);
        }
예제 #16
0
 public AppointmentSerializer(OutlookAppointment appItem)
 {
     _appItem = appItem;
 }