public void PrepareForExport(Options[] profiles, Action <string> logger)
        {
            logger(Strings.Get($"Processing profiles."));

            foreach (var profile in profiles)
            {
                logger($"'{profile.Name}'");
                try
                {
                    using (var outlookFolderWrapper = GenericComObjectWrapper.Create((Folder)_session.GetFolderFromId(profile.OutlookFolderEntryId, profile.OutlookFolderStoreId)))
                    {
                        profile.OutlookFolderEntryId = outlookFolderWrapper.Inner.Name;
                    }
                }
                catch (System.Exception)
                {
                    logger(Strings.Get($"WARNING profile '{profile.Name}', references an outlook folder that doesn't exist."));
                    profile.OutlookFolderEntryId = "<ERROR>";
                }

                profile.OutlookFolderStoreId = null;
            }

            logger(Strings.Get($"Processing profiles done."));
        }
        private void SwitchCategories(ChangedOptions[] changedOptions)
        {
            foreach (var changedOption in changedOptions)
            {
                var oldCategory  = GetMappingRefPropertyOrNull <EventMappingConfiguration, string> (changedOption.Old.MappingConfiguration, o => o.EventCategory);
                var newCategory  = GetMappingRefPropertyOrNull <EventMappingConfiguration, string> (changedOption.New.MappingConfiguration, o => o.EventCategory);
                var negateFilter = GetMappingPropertyOrNull <EventMappingConfiguration, bool> (changedOption.New.MappingConfiguration, o => o.InvertEventCategoryFilter);

                if (oldCategory != newCategory && !String.IsNullOrEmpty(oldCategory) && !negateFilter.Value)
                {
                    try
                    {
                        SwitchCategories(changedOption, oldCategory, newCategory);
                    }
                    catch (Exception x)
                    {
                        s_logger.Error(null, x);
                    }
                }

                if (!String.IsNullOrEmpty(newCategory))
                {
                    var mappingConfiguration = (EventMappingConfiguration)changedOption.New.MappingConfiguration;

                    if (mappingConfiguration.UseEventCategoryColorAndMapFromCalendarColor || mappingConfiguration.CategoryShortcutKey != OlCategoryShortcutKey.olCategoryShortcutKeyNone)
                    {
                        try
                        {
                            using (var categoriesWrapper = GenericComObjectWrapper.Create(_session.Categories))
                            {
                                foreach (var existingCategory in categoriesWrapper.Inner.ToSafeEnumerable <Category>())
                                {
                                    if (existingCategory.ShortcutKey == mappingConfiguration.CategoryShortcutKey)
                                    {
                                        existingCategory.ShortcutKey = OlCategoryShortcutKey.olCategoryShortcutKeyNone;
                                    }
                                }

                                using (var categoryWrapper = GenericComObjectWrapper.Create(categoriesWrapper.Inner[newCategory]))
                                {
                                    if (categoryWrapper.Inner == null)
                                    {
                                        categoriesWrapper.Inner.Add(newCategory, mappingConfiguration.EventCategoryColor, mappingConfiguration.CategoryShortcutKey);
                                    }
                                    else
                                    {
                                        categoryWrapper.Inner.Color       = mappingConfiguration.EventCategoryColor;
                                        categoryWrapper.Inner.ShortcutKey = mappingConfiguration.CategoryShortcutKey;
                                    }
                                }
                            }
                        }
                        catch (Exception x)
                        {
                            s_logger.Error(null, x);
                        }
                    }
                }
            }
        }
        private void MapPhoto1To2(ContactItem source, GoogleContactWrapper target, IEntityMappingLogger logger)
        {
            target.PhotoOrNull = null;

            if (source.HasPicture)
            {
                foreach (var att in source.Attachments.ToSafeEnumerable <Attachment>())
                {
                    if (att.DisplayName == "ContactPicture.jpg")
                    {
                        using (var oPa = GenericComObjectWrapper.Create(att.PropertyAccessor))
                        {
                            try
                            {
                                target.PhotoOrNull = (byte[])oPa.Inner.GetProperty(PR_ATTACH_DATA_BIN);
                            }
                            catch (COMException ex)
                            {
                                s_logger.Warn("Could not get property PR_ATTACH_DATA_BIN to export picture for contact.", ex);
                                logger.LogMappingWarning("Could not get property PR_ATTACH_DATA_BIN to export picture for contact.", ex);
                            }
                            catch (System.UnauthorizedAccessException ex)
                            {
                                s_logger.Warn("Could not access PR_ATTACH_DATA_BIN to export picture for contact.", ex);
                                logger.LogMappingWarning("Could not get property PR_ATTACH_DATA_BIN to export picture for contact.", ex);
                            }
                        }
                    }
                }
            }
        }
        public Task <IReadOnlyList <EntityVersion <string, DateTime> > > GetAllVersions(IEnumerable <string> idsOfknownEntities)
        {
            var entities = new List <EntityVersion <string, DateTime> >();

            using (var tableWrapper = GenericComObjectWrapper.Create((Table)_taskFolder.GetTable(PR_MESSAGE_CLASS_DASLFILTER)))
            {
                var table = tableWrapper.Inner;
                table.Columns.RemoveAll();
                table.Columns.Add(c_entryIdColumnName);

                var storeId = _taskFolder.StoreID;

                while (!table.EndOfTable)
                {
                    var row     = table.GetNextRow();
                    var entryId = (string)row[c_entryIdColumnName];
                    try
                    {
                        using (var taskItemWrapper = GenericComObjectWrapper.Create((TaskItem)_mapiNameSpace.GetItemFromID(entryId, storeId)))
                        {
                            entities.Add(EntityVersion.Create(taskItemWrapper.Inner.EntryID, taskItemWrapper.Inner.LastModificationTime));
                        }
                    }
                    catch (COMException ex)
                    {
                        s_logger.Error("Could not fetch TaskItem, skipping.", ex);
                    }
                }
            }

            return(Task.FromResult <IReadOnlyList <EntityVersion <string, DateTime> > > (entities));
        }
        public ISynchronizer CreateSynchronizer(Options options)
        {
            OlItemType defaultItemType;
            string     folderName;

            using (var outlookFolderWrapper = GenericComObjectWrapper.Create((Folder)_outlookSession.GetFolderFromID(options.OutlookFolderEntryId, options.OutlookFolderStoreId)))
            {
                defaultItemType = outlookFolderWrapper.Inner.DefaultItemType;
                folderName      = outlookFolderWrapper.Inner.Name;
            }

            switch (defaultItemType)
            {
            case OlItemType.olAppointmentItem:
                return(CreateEventSynchronizer(options));

            case OlItemType.olTaskItem:
                return(CreateTaskSynchronizer(options));

            case OlItemType.olContactItem:
                return(CreateContactSynchronizer(options));

            default:
                throw new NotSupportedException(
                          string.Format(
                              "The folder '{0}' contains an item type ('{1}'), whis is not supported for synchronization",
                              folderName,
                              defaultItemType));
            }
        }
Ejemplo n.º 6
0
        private static void Convert(NameSpace outlookSession, Options options, Func <Options, string> cacheFileGetter, Action <Options> cacheDeleter)
        {
            OlItemType defaultItemType;

            using (var outlookFolderWrapper = GenericComObjectWrapper.Create((Folder)outlookSession.GetFolderFromID(options.OutlookFolderEntryId, options.OutlookFolderStoreId)))
            {
                defaultItemType = outlookFolderWrapper.Inner.DefaultItemType;
            }

            if (defaultItemType == OlItemType.olTaskItem)
            {
                var       fileName = cacheFileGetter(options);
                XDocument document = XDocument.Load(fileName);

                if (document.Root?.Name.LocalName == "ArrayOfOutlookEventRelationData")
                {
                    document.Root.Name = "ArrayOfTaskRelationData";
                    foreach (var node in document.Descendants().Where(n => n.Name == "OutlookEventRelationData"))
                    {
                        node.Name = "TaskRelationData";
                    }
                    document.Save(fileName);
                }
            }
        }
Ejemplo n.º 7
0
        private static void Convert(NameSpace outlookSession, Options options, Func <Options, string> cacheFileGetter, Action <Options> cacheDeleter)
        {
            OlItemType defaultItemType;

            using (var outlookFolderWrapper = GenericComObjectWrapper.Create((Folder)outlookSession.GetFolderFromID(options.OutlookFolderEntryId, options.OutlookFolderStoreId)))
            {
                defaultItemType = outlookFolderWrapper.Inner.DefaultItemType;
            }

            if (defaultItemType == OlItemType.olAppointmentItem)
            {
                var       fileName   = cacheFileGetter(options);
                XDocument document   = XDocument.Load(fileName);
                var       aTypeNodes = document.Descendants().Where(n => n.Name == "AtypeId");

                foreach (var atypeNode in aTypeNodes)
                {
                    var    entryId = atypeNode.Value;
                    string globalAppointmentId;
                    using (var appointmentWrapper = GenericComObjectWrapper.Create((AppointmentItem)outlookSession.GetItemFromID(entryId, options.OutlookFolderStoreId)))
                    {
                        globalAppointmentId = appointmentWrapper.Inner.GlobalAppointmentID;
                    }

                    atypeNode.RemoveAll();
                    atypeNode.Add(new XElement("EntryId", entryId));
                    atypeNode.Add(new XElement("GlobalAppointmentId", globalAppointmentId));
                }

                document.Save(fileName);
            }
        }
        List <EntityVersion <string, DateTime> > QueryFolder(Folder folder, string filter, IGetVersionsLogger logger)
        {
            var versions = new List <EntityVersion <string, DateTime> > ();

            using (var tableWrapper = GenericComObjectWrapper.Create(folder.GetTable(filter)))
            {
                var table = tableWrapper.Inner;
                table.Columns.RemoveAll();
                table.Columns.Add(PR_LONG_TERM_ENTRYID_FROM_TABLE);
                table.Columns.Add(LastModificationTimeColumnId);

                while (!table.EndOfTable)
                {
                    var row     = table.GetNextRow();
                    var entryId = row.BinaryToString(PR_LONG_TERM_ENTRYID_FROM_TABLE);

                    var      lastModificationTimeObject = row[LastModificationTimeColumnId];
                    DateTime lastModificationTime;
                    if (lastModificationTimeObject != null)
                    {
                        lastModificationTime = (DateTime)lastModificationTimeObject;
                    }
                    else
                    {
                        s_logger.Warn($"Column '{nameof(LastModificationTimeColumnId)}' of entity '{entryId}' is NULL.");
                        logger.LogWarning(entryId, $"Column '{nameof(LastModificationTimeColumnId)}' is NULL.");
                        lastModificationTime = OutlookUtility.OUTLOOK_DATE_NONE;
                    }

                    versions.Add(new EntityVersion <string, DateTime> (entryId, lastModificationTime));
                }
            }

            return(versions);
        }
Ejemplo n.º 9
0
        private static TItemType GetEntryOrNull <TItemType>(
            this NameSpace mapiNameSpace,
            string entryId,
            string expectedFolderId,
            string storeId,
            Func <TItemType, Folder> parentFolderGetter)
            where TItemType : class
        {
            try
            {
                var item = (TItemType)mapiNameSpace.GetItemFromID(entryId, storeId);

                using (var folderWrapper = GenericComObjectWrapper.Create(parentFolderGetter(item)))
                {
                    if (folderWrapper.Inner?.EntryID == expectedFolderId)
                    {
                        return(item);
                    }
                }

                return(null);
            }
            catch (COMException x)
            {
                const int messageNotFoundResult = -2147221233;
                if (x.HResult != messageNotFoundResult)
                {
                    s_logger.Error("Error while fetching entity.", x);
                }
                return(null);
            }
        }
        public CreateCategoryResult AddCategoryNoThrow(string name, OlCategoryColor color)
        {
            try
            {
                using (var categoriesWrapper = GenericComObjectWrapper.Create(_nameSpace.Categories))
                {
                    // Here a hashset has to be used with an case-insensitive comparer, because the indexer cannot be used to check if the
                    // category already exists, since it is case sensitive (but outlook requires case insensitive uniqueness)
                    var categoryNames = new HashSet <string>(
                        categoriesWrapper.Inner.ToSafeEnumerable <Category>().Select(c => c.Name),
                        CategoryNameComparer);

                    if (!categoryNames.Contains(name))
                    {
                        categoriesWrapper.Inner.Add(name, color);
                        return(CreateCategoryResult.Ok);
                    }
                    else
                    {
                        return(CreateCategoryResult.DidAlreadyExist);
                    }
                }
            }
            catch (System.Exception e)
            {
                s_logger.Error($"Can't create category '{name}' with color '{color}'", e);
                return(CreateCategoryResult.Error);
            }
        }
        public string GetCurrentUserEmailAddressOrNull()
        {
            try
            {
                using (var currentUser = GenericComObjectWrapper.Create(_nameSpace.CurrentUser))
                {
                    if (currentUser.Inner != null)
                    {
                        using (var addressEntry = GenericComObjectWrapper.Create(currentUser.Inner.AddressEntry))
                        {
                            if (addressEntry.Inner != null)
                            {
                                return(OutlookUtility.GetEmailAdressOrNull(addressEntry.Inner, NullEntitySynchronizationLogger.Instance, s_logger) ?? string.Empty);
                            }
                        }
                    }
                }
            }
            catch (COMException ex)
            {
                s_logger.Error("Can't access currentuser email adress.", ex);
            }

            return(null);
        }
        public EventMappingConfigurationForm(Func <ICalDavDataAccess> calDavDataAccessFactory)
        {
            InitializeComponent();
            Item.BindComboBox(_mapReminderComboBox, _availableReminderMappings);
            Item.BindComboBox(_categoryShortcutKeycomboBox, _availableShortcutKeys);

            _categoryNameComboBox.Items.Add("");
            try
            {
                using (var categoriesWrapper = GenericComObjectWrapper.Create(Globals.ThisAddIn.Application.Session.Categories))
                {
                    foreach (var category in categoriesWrapper.Inner.ToSafeEnumerable <Category>())
                    {
                        _categoryNameComboBox.Items.Add(category.Name);
                    }
                }
            }
            catch (COMException ex)
            {
                s_logger.Error("Can't access Outlook categories.", ex);
            }

            _calDavDataAccessFactory = calDavDataAccessFactory;
            _categoryColorPicker.AddCategoryColors();
        }
        public Options[] ShowWpfOptions(Guid?initialSelectedProfileId, GeneralOptions generalOptions, Options[] options)
        {
            string[] categories;
            using (var categoriesWrapper = GenericComObjectWrapper.Create(_session.Categories))
            {
                categories = categoriesWrapper.Inner.ToSafeEnumerable <Category>().Select(c => c.Name).ToArray();
            }

            var faultFinder = generalOptions.FixInvalidSettings ? new SettingsFaultFinder(EnumDisplayNameProvider.Instance) : NullSettingsFaultFinder.Instance;

            var optionTasks = new OptionTasks(_session, EnumDisplayNameProvider.Instance, faultFinder);

            var viewOptions = new ViewOptions(generalOptions.EnableAdvancedView);
            var viewModel   = new OptionsCollectionViewModel(
                generalOptions.ExpandAllSyncProfiles,
                GetProfileDataDirectory,
                _uiService,
                optionTasks,
                p => ProfileTypeRegistry.Create(p, _outlookAccountPasswordProvider, categories, optionTasks, faultFinder, generalOptions, viewOptions),
                viewOptions);

            _currentVisibleOptionsFormOrNull = viewModel;

            viewModel.SetOptionsCollection(options, initialSelectedProfileId);

            if (_uiService.ShowOptions(viewModel))
            {
                _optionsDataAccess.EnsureBackupExists("SimplifiedUi");
                return(viewModel.GetOptionsCollection());
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 14
0
        public (CreateCategoryResult Result, string ExistingColorNameForLoggingOrNull) AddCategoryNoThrow(string name, OlCategoryColor color)
        {
            try
            {
                using (var categoriesWrapper = GenericComObjectWrapper.Create(_nameSpace.Categories))
                {
                    // Here a dictionary has to be used with an case-insensitive comparer, because the indexer cannot be used to check if the
                    // category already exists, since it is case sensitive (but outlook requires case insensitive uniqueness)
                    var categoryColorByName = new Dictionary <string, OlCategoryColor>(StringComparer.InvariantCultureIgnoreCase);
                    foreach (var category in GetCategories())
                    {
                        // Use assignment via indexer to prevent exceptions if outlook retursn duplicate categories
                        categoryColorByName[category.Name] = category.Color;
                    }

                    if (!categoryColorByName.TryGetValue(name, out var existingColor))
                    {
                        categoriesWrapper.Inner.Add(name, color);
                        return(CreateCategoryResult.Ok, null);
                    }
                    else
                    {
                        return(CreateCategoryResult.DidAlreadyExist, existingColor.ToString());
                    }
                }
            }
            catch (System.Exception e)
            {
                s_logger.Error($"Can't create category '{name}' with color '{color}'", e);
                return(CreateCategoryResult.Error, null);
            }
        }
Ejemplo n.º 15
0
        public GenericComObjectWrapper <ContactItem> Map2To1(vCard source, GenericComObjectWrapper <ContactItem> target)
        {
            target.Inner.FirstName = source.GivenName;
            target.Inner.LastName  = source.FamilyName;

            return(target);
        }
        public static List <EntityVersion <string, DateTime> > QueryFolder(NameSpace session, GenericComObjectWrapper <Folder> calendarFolderWrapper, StringBuilder filterBuilder)
        {
            var events = new List <EntityVersion <string, DateTime> >();

            using (var tableWrapper = GenericComObjectWrapper.Create(
                       calendarFolderWrapper.Inner.GetTable(filterBuilder.ToString())))
            {
                var table = tableWrapper.Inner;
                table.Columns.RemoveAll();
                table.Columns.Add(c_entryIdColumnName);

                var storeId = calendarFolderWrapper.Inner.StoreID;

                while (!table.EndOfTable)
                {
                    var row     = table.GetNextRow();
                    var entryId = (string)row[c_entryIdColumnName];
                    try
                    {
                        using (var appointmentWrapper = GenericComObjectWrapper.Create((AppointmentItem)session.GetItemFromID(entryId, storeId)))
                        {
                            events.Add(new EntityVersion <string, DateTime> (appointmentWrapper.Inner.EntryID, appointmentWrapper.Inner.LastModificationTime));
                        }
                    }
                    catch (COMException ex)
                    {
                        s_logger.Error("Could not fetch AppointmentItem, skipping.", ex);
                    }
                }
            }
            return(events);
        }
Ejemplo n.º 17
0
        public vCard Map1To2(GenericComObjectWrapper <ContactItem> source, vCard target)
        {
            target.GivenName  = source.Inner.FirstName;
            target.FamilyName = source.Inner.LastName;

            return(target);
        }
 private static void MapPhoto1To2(ContactItem source, vCard target, IEntityMappingLogger logger)
 {
     if (source.HasPicture)
     {
         foreach (var att in source.Attachments.ToSafeEnumerable <Microsoft.Office.Interop.Outlook.Attachment>())
         {
             if (att.DisplayName == "ContactPicture.jpg")
             {
                 using (var oPa = GenericComObjectWrapper.Create(att.PropertyAccessor))
                 {
                     try
                     {
                         byte[] rawAttachmentData = (byte[])oPa.Inner.GetProperty(PR_ATTACH_DATA_BIN);
                         target.Photos.Add(new vCardPhoto(rawAttachmentData));
                     }
                     catch (COMException ex)
                     {
                         s_logger.Warn("Could not get property PR_ATTACH_DATA_BIN to export picture for contact.", ex);
                         logger.LogMappingWarning("Could not get property PR_ATTACH_DATA_BIN to export picture for contact.", ex);
                     }
                     catch (System.UnauthorizedAccessException ex)
                     {
                         s_logger.Warn("Could not access PR_ATTACH_DATA_BIN to export picture for contact.", ex);
                         logger.LogMappingWarning("Could not get property PR_ATTACH_DATA_BIN to export picture for contact.", ex);
                     }
                 }
             }
         }
     }
 }
        public IReadOnlyList <EntityIdWithVersion <string, DateTime> > GetVersions(DateTime fromUtc, DateTime toUtc)
        {
            var events = new List <EntityIdWithVersion <string, DateTime> >();

            string filter = String.Format("[Start] < '{0}' And [End] > '{1}'", ToOutlookDateString(toUtc), ToOutlookDateString(fromUtc));

            using (var calendarFolderWrapper = CreateFolderWrapper())
            {
                using (var tableWrapper = GenericComObjectWrapper.Create((Table)calendarFolderWrapper.Inner.GetTable(filter)))
                {
                    var table = tableWrapper.Inner;
                    table.Columns.RemoveAll();
                    table.Columns.Add(c_entryIdColumnName);

                    var storeId = calendarFolderWrapper.Inner.StoreID;

                    while (!table.EndOfTable)
                    {
                        var row     = table.GetNextRow();
                        var entryId = (string)row[c_entryIdColumnName];
                        using (var appointmentWrapper = GenericComObjectWrapper.Create((AppointmentItem)_mapiNameSpace.GetItemFromID(entryId, storeId)))
                        {
                            events.Add(new EntityIdWithVersion <string, DateTime> (appointmentWrapper.Inner.EntryID, appointmentWrapper.Inner.LastModificationTime));
                        }
                    }
                }
            }
            return(events);
        }
 public static void MapCustomProperties1To2(GenericComObjectWrapper <UserProperties> userPropertiesWrapper, ICalendarPropertyList targetProperties, bool mapAllCustomProperties, PropertyMapping[] mappings, IEntityMappingLogger logger, ILog s_logger)
 {
     if (userPropertiesWrapper.Inner != null && userPropertiesWrapper.Inner.Count > 0)
     {
         foreach (var prop in userPropertiesWrapper.Inner.ToSafeEnumerable <UserProperty>())
         {
             try
             {
                 if (prop.Value != null && !string.IsNullOrEmpty(prop.Value.ToString()) && (prop.Type == OlUserPropertyType.olText))
                 {
                     var foundMapping = mappings.FirstOrDefault(m => m.OutlookProperty == prop.Name);
                     if (foundMapping != null)
                     {
                         targetProperties.Add(new CalendarProperty(foundMapping.DavProperty, prop.Value.ToString()));
                     }
                     else if (mapAllCustomProperties)
                     {
                         targetProperties.Add(new CalendarProperty("X-CALDAVSYNCHRONIZER-" + prop.Name, prop.Value.ToString()));
                     }
                 }
             }
             catch (COMException ex)
             {
                 s_logger.Warn("Can't access UserProperty of Item!", ex);
                 logger.LogMappingWarning("Can't access UserProperty of Item!", ex);
             }
         }
     }
 }
        public Options[] ShowWpfOptions(Guid?initialSelectedProfileId, GeneralOptions generalOptions, Options[] options)
        {
            string[] categories;
            using (var categoriesWrapper = GenericComObjectWrapper.Create(_session.Categories))
            {
                categories = categoriesWrapper.Inner.ToSafeEnumerable <Category>().Select(c => c.Name).ToArray();
            }

            var viewModel = new OptionsCollectionViewModel(
                _session,
                generalOptions,
                _outlookAccountPasswordProvider,
                categories,
                GetProfileDataDirectory);

            _currentVisibleOptionsFormOrNull = viewModel;

            viewModel.SetOptionsCollection(options, initialSelectedProfileId);

            if (_uiService.ShowOptions(viewModel))
            {
                _optionsDataAccess.EnsureBackupExists("Wpf");
                return(viewModel.GetOptionsCollection());
            }
            else
            {
                return(null);
            }
        }
        public Task <IEnumerable <EntityVersion <string, DateTime> > > GetAllVersions(IEnumerable <string> idsOfknownEntities, Tcontext context, IGetVersionsLogger logger)
        {
            using (var addressbookFolderWrapper = CreateFolderWrapper())
            {
                bool isInstantSearchEnabled = false;

                try
                {
                    using (var store = GenericComObjectWrapper.Create(addressbookFolderWrapper.Inner.Store))
                    {
                        if (store.Inner != null)
                        {
                            isInstantSearchEnabled = store.Inner.IsInstantSearchEnabled;
                        }
                    }
                }
                catch (COMException)
                {
                    s_logger.Info("Can't access IsInstantSearchEnabled property of store, defaulting to false.");
                }

                var filter = _daslFilterProvider.GetContactFilter(isInstantSearchEnabled);

                return(Task.FromResult <IEnumerable <EntityVersion <string, DateTime> > >(_queryFolderStrategy.QueryContactItemFolder(_session, addressbookFolderWrapper.Inner, _folderId, filter, logger)));
            }
        }
 public static AppointmentItemWrapper CreateNewAppointment()
 {
     using (var folderWrapper = GenericComObjectWrapper.Create((Folder)s_mapiNameSpace.GetFolderFromID(s_outlookFolderEntryId, s_outlookFolderStoreId)))
     {
         return(OutlookEventRepository.CreateNewAppointmentForTesting(folderWrapper.Inner, s_mapiNameSpace));
     }
 }
Ejemplo n.º 24
0
 public static AddressEntry GetEventOrganizerOrNull(AppointmentItem source, IEntityMappingLogger logger, ILog generalLogger, int outlookMajorVersion)
 {
     try
     {
         if (outlookMajorVersion < 14)
         {
             // Microsoft recommends this way for Outlook 2007. May still work with Outlook 2010+
             using (var propertyAccessor = GenericComObjectWrapper.Create(source.PropertyAccessor))
             {
                 string organizerEntryID = propertyAccessor.Inner.BinaryToString(propertyAccessor.Inner.GetProperty(PR_SENT_REPRESENTING_ENTRYID));
                 return(Globals.ThisAddIn.Application.Session.GetAddressEntryFromID(organizerEntryID));
             }
         }
         else
         {
             // NB this works with Outlook 2010 but crashes with Outlook 2007
             return(source.GetOrganizer());
         }
     }
     catch (COMException ex)
     {
         generalLogger.Warn("Can't get organizer of appointment", ex);
         logger.LogMappingWarning("Can't get organizer of appointment", ex);
         return(null);
     }
 }
        List <AppointmentSlim> IQueryOutlookAppointmentItemFolderStrategy.QueryAppointmentFolder(IOutlookSession session, Folder calendarFolder, string filter)
        {
            var events = new List <AppointmentSlim>();

            using (var tableWrapper = GenericComObjectWrapper.Create(
                       calendarFolder.GetTable(filter)))
            {
                var table = tableWrapper.Inner;
                table.Columns.RemoveAll();
                table.Columns.Add(c_entryIdColumnName);

                var storeId = calendarFolder.StoreID;

                while (!table.EndOfTable)
                {
                    var row     = table.GetNextRow();
                    var entryId = (string)row[c_entryIdColumnName];
                    try
                    {
                        using (var appointmentWrapper = GenericComObjectWrapper.Create(session.GetAppointmentItem(entryId, storeId)))
                        {
                            events.Add(AppointmentSlim.FromAppointmentItem(appointmentWrapper.Inner));
                        }
                    }
                    catch (COMException ex)
                    {
                        s_logger.Error("Could not fetch AppointmentItem, skipping.", ex);
                    }
                }
            }
            return(events);
        }
        List <EntityVersion <string, DateTime> > IQueryOutlookContactItemFolderStrategy.QueryContactItemFolder(IOutlookSession session, Folder folder, string expectedFolderId, string filter)
        {
            var contacts = new List <EntityVersion <string, DateTime> > ();

            using (var tableWrapper = GenericComObjectWrapper.Create(folder.GetTable(filter)))
            {
                var table = tableWrapper.Inner;
                table.Columns.RemoveAll();
                table.Columns.Add(c_entryIdColumnName);

                var storeId = folder.StoreID;

                while (!table.EndOfTable)
                {
                    var row     = table.GetNextRow();
                    var entryId = (string)row[c_entryIdColumnName];

                    var contact = session.GetContactItemOrNull(entryId, expectedFolderId, storeId);
                    if (contact != null)
                    {
                        using (var contactWrapper = GenericComObjectWrapper.Create(contact))
                        {
                            contacts.Add(new EntityVersion <string, DateTime> (contactWrapper.Inner.EntryID, contactWrapper.Inner.LastModificationTime));
                        }
                    }
                }
            }

            return(contacts);
        }
        List <EntityVersion <string, DateTime> > IQueryOutlookTaskItemFolderStrategy.QueryTaskFolder(IOutlookSession session, Folder folder, string filter)
        {
            var tasks = new List <EntityVersion <string, DateTime> > ();

            using (var tableWrapper = GenericComObjectWrapper.Create(
                       folder.GetTable(filter)))
            {
                var table = tableWrapper.Inner;
                table.Columns.RemoveAll();
                table.Columns.Add(c_entryIdColumnName);

                var storeId = folder.StoreID;

                while (!table.EndOfTable)
                {
                    var row     = table.GetNextRow();
                    var entryId = (string)row[c_entryIdColumnName];
                    try
                    {
                        using (var taskWrapper = GenericComObjectWrapper.Create(session.GetTaskItem(entryId, storeId)))
                        {
                            tasks.Add(new EntityVersion <string, DateTime> (taskWrapper.Inner.EntryID, taskWrapper.Inner.LastModificationTime));
                        }
                    }
                    catch (COMException ex)
                    {
                        s_logger.Error("Could not fetch TaskItem, skipping.", ex);
                    }
                }
            }
            return(tasks);
        }
Ejemplo n.º 28
0
        public string GetFolderAccountNameOrNull(string folderStoreId)
        {
            if (ThisAddIn.IsOutlookVersionSmallerThan2010)
            {
                return(null);
            }

            try
            {
                foreach (Account account in _session.Accounts.ToSafeEnumerable <Account>())
                {
                    using (var deliveryStore = GenericComObjectWrapper.Create(account.DeliveryStore))
                    {
                        if (deliveryStore.Inner != null && deliveryStore.Inner.StoreID == folderStoreId)
                        {
                            return(account.DisplayName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                s_logger.Error("Can't access Account Name of folder.", ex);
            }

            return(null);
        }
        public Task <IReadOnlyList <EntityIdWithVersion <string, DateTime> > > GetVersions()
        {
            var entities = new List <EntityIdWithVersion <string, DateTime> >();

            using (var tableWrapper = GenericComObjectWrapper.Create((Table)_taskFolder.GetTable()))
            {
                var table = tableWrapper.Inner;
                table.Columns.RemoveAll();
                table.Columns.Add(c_entryIdColumnName);

                var storeId = _taskFolder.StoreID;

                while (!table.EndOfTable)
                {
                    var row     = table.GetNextRow();
                    var entryId = (string)row[c_entryIdColumnName];
                    using (var appointmentWrapper = GenericComObjectWrapper.Create((TaskItem)_mapiNameSpace.GetItemFromID(entryId, storeId)))
                    {
                        entities.Add(EntityIdWithVersion.Create(appointmentWrapper.Inner.EntryID, appointmentWrapper.Inner.LastModificationTime));
                    }
                }
            }

            return(Task.FromResult <IReadOnlyList <EntityIdWithVersion <string, DateTime> > > (entities));
        }
Ejemplo n.º 30
0
        private void CheckEvent(string eventData, AppointmentId appointmentId, int[] expectedSequenceNumbers)
        {
            var calendar = OutlookTestContext.DeserializeICalendar(eventData);

            Assert.That(calendar.Events.Count, Is.EqualTo(3));

            var masterEvent    = calendar.Events.Single(e => e.Summary == "Treffen");
            var exeption1Event = calendar.Events.Single(e => e.Summary == "Ex 1");
            var exeption2Event = calendar.Events.Single(e => e.Summary == "Ex 2");

            CollectionAssert.AreEquivalent(expectedSequenceNumbers, calendar.Events.Select(e => e.Sequence));
            Assert.That(exeption1Event.UID, Is.EqualTo(masterEvent.UID));
            Assert.That(exeption2Event.UID, Is.EqualTo(masterEvent.UID));

            using (var masterAppointment = OutlookTestContext.GetOutlookEvent(appointmentId))
            {
                GenericComObjectWrapper <AppointmentItem> exeption1Appointment;
                GenericComObjectWrapper <AppointmentItem> exeption2Appointment;

                using (var r = GenericComObjectWrapper.Create(masterAppointment.Inner.GetRecurrencePattern()))
                {
                    exeption1Appointment = GenericComObjectWrapper.Create(r.Inner.Exceptions[1].AppointmentItem);
                    exeption2Appointment = GenericComObjectWrapper.Create(r.Inner.Exceptions[2].AppointmentItem);
                }

                Assert.That(masterEvent.Start.Value, Is.EqualTo(masterAppointment.Inner.Start));
                Assert.That(exeption1Event.Start.Value, Is.EqualTo(exeption1Appointment.Inner.Start));
                Assert.That(exeption2Event.Start.Value, Is.EqualTo(exeption2Appointment.Inner.Start));
            }
        }
 public static void MapCustomProperties1To2 (GenericComObjectWrapper<UserProperties> userPropertiesWrapper, ICalendarPropertyList targetProperties, bool mapAllCustomProperties, PropertyMapping[] mappings, IEntityMappingLogger logger, ILog s_logger)
 {
   if (userPropertiesWrapper.Inner != null && userPropertiesWrapper.Inner.Count > 0)
   {
     foreach (var prop in userPropertiesWrapper.Inner.ToSafeEnumerable<UserProperty>())
     {
       try
       {
         if (prop.Value != null && !string.IsNullOrEmpty (prop.Value.ToString()) && (prop.Type == OlUserPropertyType.olText))
         {
           var foundMapping = mappings.FirstOrDefault (m => m.OutlookProperty == prop.Name);
           if (foundMapping != null)
           {
             targetProperties.Add (new CalendarProperty (foundMapping.DavProperty, prop.Value.ToString()));
           }
           else if (mapAllCustomProperties)
           {
             targetProperties.Add (new CalendarProperty ("X-CALDAVSYNCHRONIZER-" + prop.Name, prop.Value.ToString()));
           }
         }
       }
       catch (COMException ex)
       {
         s_logger.Warn ("Can't access UserProperty of Item!", ex);
         logger.LogMappingWarning ("Can't access UserProperty of Item!", ex);
       }
     }
   }
 }
    public static void MapCustomProperties2To1 (ICalendarPropertyList sourceList, GenericComObjectWrapper<UserProperties> userPropertiesWrapper, bool mapAllCustomProperties, PropertyMapping[] mappings, IEntityMappingLogger logger, ILog s_logger)
    {
      var alreadyMappedOutlookProperties = new HashSet<string>();

      foreach (var mapping in mappings)
      {
        var prop = sourceList.FirstOrDefault (p => p.Name == mapping.DavProperty);
        if (prop != null)
        {
          try
          {
            alreadyMappedOutlookProperties.Add(mapping.OutlookProperty);
            using (var userProperty = GenericComObjectWrapper.Create (userPropertiesWrapper.Inner.Find (mapping.OutlookProperty)))
            {
              if (userProperty.Inner != null)
              {
                userProperty.Inner.Value = prop.Value;
              }
              else
              {
                using (var newUserProperty = GenericComObjectWrapper.Create (userPropertiesWrapper.Inner.Add (mapping.OutlookProperty, OlUserPropertyType.olText, true)))
                {
                  newUserProperty.Inner.Value = prop.Value;
                }
              }
            }
          }
          catch (COMException ex)
          {
            s_logger.Warn ("Can't set UserProperty of Item!", ex);
            logger.LogMappingWarning ("Can't set UserProperty of Item!", ex);
          }
        }
      }
      if (mapAllCustomProperties)
      {
        foreach (var prop in sourceList.Where(p => p.Name.StartsWith("X-CALDAVSYNCHRONIZER-")))
        {
          var outlookProperty = prop.Name.Replace("X-CALDAVSYNCHRONIZER-", "");
          if (!alreadyMappedOutlookProperties.Contains(outlookProperty))
          {
            try
            {
              using (var userProperty = GenericComObjectWrapper.Create(userPropertiesWrapper.Inner.Find(outlookProperty)))
              {
                if (userProperty.Inner != null)
                {
                  userProperty.Inner.Value = prop.Value;
                }
                else
                {
                  using (var newUserProperty = GenericComObjectWrapper.Create(userPropertiesWrapper.Inner.Add(outlookProperty, OlUserPropertyType.olText, true)))
                  {
                    newUserProperty.Inner.Value = prop.Value;
                  }
                }
              }
            }
            catch (COMException ex)
            {
              s_logger.Warn("Can't set UserProperty of Item!", ex);
              logger.LogMappingWarning("Can't set UserProperty of Item!", ex);
            }
          }
        }
      }
    }