Exemplo n.º 1
0
        public Task <bool> TryDelete(
            string entityId,
            DateTime version,
            int context,
            IEntitySynchronizationLogger logger)
        {
            var entityWithId = Get(new[] { entityId }, NullLoadEntityLogger.Instance, 0).Result.SingleOrDefault();

            if (entityWithId == null)
            {
                return(Task.FromResult(true));
            }

            using (var entity = entityWithId.Entity)
            {
                entity.Inner.Delete();
            }

            return(Task.FromResult(true));
        }
Exemplo n.º 2
0
            public JobWrapper(
                IEntitySyncStateContext <TAtypeEntityId, TAtypeEntityVersion, TAtypeEntity, TBtypeEntityId, TBtypeEntityVersion, TBtypeEntity, TContext> stateContext,
                RestoreInB <TAtypeEntityId, TAtypeEntityVersion, TAtypeEntity, TBtypeEntityId, TBtypeEntityVersion, TBtypeEntity, TContext> state,
                IEntitySynchronizationLogger <TAtypeEntityId, TAtypeEntity, TBtypeEntityId, TBtypeEntity> logger,
                TContext context)
            {
                if (state == null)
                {
                    throw new ArgumentNullException(nameof(state));
                }
                if (logger == null)
                {
                    throw new ArgumentNullException(nameof(logger));
                }

                _stateContext = stateContext;
                _state        = state;
                _logger       = logger;
                _context      = context;
            }
        public override async Task <IEntitySyncState <TAtypeEntityId, TAtypeEntityVersion, TAtypeEntity, TBtypeEntityId, TBtypeEntityVersion, TBtypeEntity> > PerformSyncActionNoThrow(
            IEntitySynchronizationLogger logger)
        {
            try
            {
                logger.SetAId(_knownData.AtypeId);
                logger.SetBId(_knownData.BtypeId);
                var newA = await _environment.ARepository.Update(
                    _knownData.AtypeId,
                    _currentAVersion,
                    _aEntity,
                    a => _environment.Mapper.Map2To1(_bEntity, a, logger));

                logger.SetAId(newA.Id);
                return(CreateDoNothing(newA.Id, newA.Version, _knownData.BtypeId, _knownData.BtypeVersion));
            }
            catch (Exception x)
            {
                logger.LogAbortedDueToError(x);
                LogException(x);
                return(CreateDoNothing());
            }
        }
Exemplo n.º 4
0
        public async Task <EntityVersion <AppointmentId, DateTime> > TryUpdate(
            AppointmentId entityId,
            DateTime entityVersion,
            IAppointmentItemWrapper entityToUpdate,
            Func <IAppointmentItemWrapper, Task <IAppointmentItemWrapper> > entityModifier,
            IEventSynchronizationContext context,
            IEntitySynchronizationLogger logger)
        {
            entityToUpdate = await entityModifier(entityToUpdate);

            entityToUpdate.Inner.Save();
            context.DuplicateEventCleaner.AnnounceAppointment(AppointmentSlim.FromAppointmentItem(entityToUpdate.Inner));

            var newAppointmentId = new AppointmentId(entityToUpdate.Inner.EntryID, entityToUpdate.Inner.GlobalAppointmentID);

            if (!entityId.Equals(newAppointmentId))
            {
                context.DuplicateEventCleaner.AnnounceAppointmentDeleted(entityId);
            }

            return(new EntityVersion <AppointmentId, DateTime> (
                       newAppointmentId,
                       entityToUpdate.Inner.LastModificationTime));
        }
Exemplo n.º 5
0
        public async Task <EntityVersion <Identifier, int> > TryUpdate(
            Identifier entityId,
            int entityVersion,
            string entityToUpdate,
            Func <string, Task <string> > entityModifier,
            int context,
            IEntitySynchronizationLogger logger)
        {
            if (IdentifierEqualityComparer.Instance.Equals(entityId, EntityWhichCausesExceptionOnUpdate))
            {
                throw new Exception("Failed!");
            }

            if (IdentifierEqualityComparer.Instance.Equals(entityId, EntityWhichCausesAbortExceptionOnUpdate))
            {
                throw new TestAbortException();
            }

            var kv = EntityVersionAndContentById[entityId];

            if (kv.Item1 != entityVersion)
            {
                throw new Exception("tried to update stale version!");
            }

            EntityVersionAndContentById.Remove(entityId);

            var newValue = await entityModifier(kv.Item2);

            var newVersion = kv.Item1 + 1;

            var newEntityId = entityId.Value + "u";

            EntityVersionAndContentById[newEntityId] = Tuple.Create(newVersion, newValue);
            return(new EntityVersion <Identifier, int>(newEntityId, newVersion));
        }
 private static void MapCertificate2To1(vCard source, ContactItem target, IEntitySynchronizationLogger logger)
 {
     if (source.Certificates.Count > 0)
     {
         object[] certWrapper = BuildCertProperty(source.Certificates[0].Data);
         using (var oPa = GenericComObjectWrapper.Create(target.PropertyAccessor))
         {
             try
             {
                 oPa.Inner.SetProperty(PR_USER_X509_CERTIFICATE, certWrapper);
             }
             catch (COMException ex)
             {
                 s_logger.Warn("Could not set property PR_USER_X509_CERTIFICATE for contact.", ex);
                 logger.LogWarning("Could not set property PR_USER_X509_CERTIFICATE for contact.", ex);
             }
             catch (System.UnauthorizedAccessException ex)
             {
                 s_logger.Warn("Could not access PR_USER_X509_CERTIFICATE for contact.", ex);
                 logger.LogWarning("Could not access PR_USER_X509_CERTIFICATE for contact.", ex);
             }
         }
     }
 }
 private void NotifyOperationFailed(Exception exception, IEntitySynchronizationLogger logger)
 {
     logger.LogAbortedDueToError(exception);
     LogException(exception);
     SetNextStateAsFailed();
 }
Exemplo n.º 8
0
 private void NotifyOperationFailed(IEntitySyncStateContext <TAtypeEntityId, TAtypeEntityVersion, TAtypeEntity, TBtypeEntityId, TBtypeEntityVersion, TBtypeEntity, TContext> stateContext, Exception exception, IEntitySynchronizationLogger <TAtypeEntityId, TAtypeEntity, TBtypeEntityId, TBtypeEntity> logger)
 {
     logger.LogAbortedDueToError(exception);
     LogException(exception);
     stateContext.SetState(CreateFailed());
 }
Exemplo n.º 9
0
 public void AddSyncronizationJob(IJobList <TAtypeEntity, TAtypeEntityId, TAtypeEntityVersion> aJobs, IJobList <TBtypeEntity, TBtypeEntityId, TBtypeEntityVersion> bJobs, IEntitySynchronizationLogger logger)
 {
 }
        public async Task <bool> TryDelete(WebResourceName entityId, string version, ICardDavRepositoryLogger context, IEntitySynchronizationLogger logger)
        {
            var result = await _inner.TryDelete(entityId, version, 0, logger);

            context.LogEntityDeleted(entityId);
            return(result);
        }
Exemplo n.º 11
0
 TBtypeEntity UpdateEntity(TBtypeEntity entity, IEntitySynchronizationLogger logger)
 {
     return(_environment.Mapper.Map1To2(_aEntity, entity, logger));
 }
        public Task <vCard> Map1To2(IContactItemWrapper source, vCard target, IEntitySynchronizationLogger logger, ICardDavRepositoryLogger context)
        {
            target.RevisionDate = source.Inner.LastModificationTime.ToUniversalTime();

            target.GivenName       = source.Inner.FirstName;
            target.FamilyName      = source.Inner.LastName;
            target.NamePrefix      = source.Inner.Title;
            target.NameSuffix      = source.Inner.Suffix;
            target.AdditionalNames = source.Inner.MiddleName;
            target.Gender          = MapGender2To1(source.Inner.Gender);

            target.Assistant = source.Inner.AssistantName;
            target.Spouse    = source.Inner.Spouse;
            target.Manager   = source.Inner.ManagerName;

            MapEmailAddresses1To2(source.Inner, target, logger);

            if (!string.IsNullOrEmpty(source.Inner.FileAs))
            {
                target.FormattedName = source.Inner.FileAs;
            }
            else if (!string.IsNullOrEmpty(source.Inner.CompanyAndFullName))
            {
                target.FormattedName = source.Inner.CompanyAndFullName;
            }
            else if (target.EmailAddresses.Count >= 1)
            {
                target.FormattedName = target.EmailAddresses[0].Address;
            }
            else
            {
                target.FormattedName = "<Empty>";
            }

            target.Nicknames.Clear();
            if (!string.IsNullOrEmpty(source.Inner.NickName))
            {
                Array.ForEach(
                    source.Inner.NickName.Split(new[] { CultureInfo.CurrentCulture.TextInfo.ListSeparator }, StringSplitOptions.RemoveEmptyEntries),
                    c => target.Nicknames.Add(c)
                    );
            }

            target.AccessClassification = CommonEntityMapper.MapPrivacy1To2(source.Inner.Sensitivity);

            target.Categories.Clear();
            if (!string.IsNullOrEmpty(source.Inner.Categories))
            {
                Array.ForEach(
                    source.Inner.Categories.Split(new[] { CultureInfo.CurrentCulture.TextInfo.ListSeparator }, StringSplitOptions.RemoveEmptyEntries),
                    c => target.Categories.Add(c.Trim())
                    );
            }

            target.IMs.Clear();
            if (!string.IsNullOrEmpty(source.Inner.IMAddress))
            {
                //IMAddress are expected to be in form of ([Protocol]: [Address]; [Protocol]: [Address])
                var imsRaw = source.Inner.IMAddress.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var imRaw in imsRaw)
                {
                    var imDetails = imRaw.Trim().Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    var im        = new vCardIMPP();
                    if (imDetails.Length == 1)
                    {
                        im.Handle = imDetails[0].Trim();
                        // Set default ServiceType to the configured DefaultImServiceType (defaults to AIM)
                        im.ServiceType = _configuration.DefaultImServicType;
                    }
                    else if (imDetails.Length > 1)
                    {
                        var serviceType = IMTypeUtils.GetIMServiceType(imDetails[0].Trim());
                        if (serviceType == null)
                        {
                            im.ServiceType = _configuration.DefaultImServicType;
                            s_logger.Warn($"Unknown IM ServiceType '{imDetails[0]}' not implemented, defaulting to '{_configuration.DefaultImServicType}'");
                            logger.LogWarning($"Unknown IM ServiceType '{imDetails[0]}' not implemented, defaulting to '{_configuration.DefaultImServicType}'");
                        }
                        else
                        {
                            im.ServiceType = serviceType.Value;
                        }

                        im.Handle = imRaw.Substring(imRaw.IndexOf(":") + 1).Trim();
                    }

                    //Only add the im Address if not empty
                    if (!string.IsNullOrEmpty(im.Handle))
                    {
                        im.IsPreferred = target.IMs.Count == 0;
                        im.ItemType    = ItemType.HOME;
                        target.IMs.Add(im);
                    }
                }
            }

            target.DeliveryAddresses.Clear();
            if (!string.IsNullOrEmpty(source.Inner.HomeAddress))
            {
                vCardDeliveryAddress homeAddress = new vCardDeliveryAddress();
                homeAddress.AddressType.Add(vCardDeliveryAddressTypes.Home);
                homeAddress.City       = source.Inner.HomeAddressCity;
                homeAddress.Country    = source.Inner.HomeAddressCountry;
                homeAddress.PostalCode = source.Inner.HomeAddressPostalCode;
                homeAddress.Region     = source.Inner.HomeAddressState;
                homeAddress.Street     = source.Inner.HomeAddressStreet;
                homeAddress.PoBox      = source.Inner.HomeAddressPostOfficeBox;
                if (source.Inner.SelectedMailingAddress == OlMailingAddress.olHome)
                {
                    homeAddress.AddressType.Add(vCardDeliveryAddressTypes.Preferred);
                }

                target.DeliveryAddresses.Add(homeAddress);
            }

            if (!string.IsNullOrEmpty(source.Inner.BusinessAddress) || !string.IsNullOrEmpty(source.Inner.OfficeLocation))
            {
                vCardDeliveryAddress businessAddress = new vCardDeliveryAddress();
                businessAddress.AddressType.Add(vCardDeliveryAddressTypes.Work);
                businessAddress.City       = source.Inner.BusinessAddressCity;
                businessAddress.Country    = source.Inner.BusinessAddressCountry;
                businessAddress.PostalCode = source.Inner.BusinessAddressPostalCode;
                businessAddress.Region     = source.Inner.BusinessAddressState;
                businessAddress.Street     = source.Inner.BusinessAddressStreet;
                businessAddress.PoBox      = source.Inner.BusinessAddressPostOfficeBox;
                if (!string.IsNullOrEmpty(source.Inner.OfficeLocation))
                {
                    businessAddress.ExtendedAddress = source.Inner.OfficeLocation;
                }

                if (source.Inner.SelectedMailingAddress == OlMailingAddress.olBusiness)
                {
                    businessAddress.AddressType.Add(vCardDeliveryAddressTypes.Preferred);
                }

                target.DeliveryAddresses.Add(businessAddress);
            }

            if (!string.IsNullOrEmpty(source.Inner.OtherAddress))
            {
                vCardDeliveryAddress otherAddress = new vCardDeliveryAddress();
                otherAddress.City       = source.Inner.OtherAddressCity;
                otherAddress.Country    = source.Inner.OtherAddressCountry;
                otherAddress.PostalCode = source.Inner.OtherAddressPostalCode;
                otherAddress.Region     = source.Inner.OtherAddressState;
                otherAddress.Street     = source.Inner.OtherAddressStreet;
                otherAddress.PoBox      = source.Inner.OtherAddressPostOfficeBox;
                if (source.Inner.SelectedMailingAddress == OlMailingAddress.olOther)
                {
                    otherAddress.AddressType.Add(vCardDeliveryAddressTypes.Preferred);
                }

                target.DeliveryAddresses.Add(otherAddress);
            }

            MapPhoneNumbers1To2(source.Inner, target);

            if (_configuration.MapAnniversary)
            {
                target.Anniversary = source.Inner.Anniversary.Equals(OutlookUtility.OUTLOOK_DATE_NONE) ? default(DateTime?) : source.Inner.Anniversary.Date;
            }

            if (_configuration.MapBirthday)
            {
                target.BirthDate = source.Inner.Birthday.Equals(OutlookUtility.OUTLOOK_DATE_NONE) ? default(DateTime?) : source.Inner.Birthday.Date;
            }

            target.Organization = source.Inner.CompanyName;
            target.Department   = source.Inner.Department;

            target.Title = source.Inner.JobTitle;
            target.Role  = source.Inner.Profession;

            target.Websites.Clear();
            if (!string.IsNullOrEmpty(source.Inner.PersonalHomePage))
            {
                target.Websites.Add(new vCardWebsite(source.Inner.PersonalHomePage, vCardWebsiteTypes.Personal));
            }

            if (!string.IsNullOrEmpty(source.Inner.BusinessHomePage))
            {
                target.Websites.Add(new vCardWebsite(source.Inner.BusinessHomePage, vCardWebsiteTypes.Work));
            }

            MapCertificate1To2(source.Inner, target, logger);

            if (_configuration.MapContactPhoto)
            {
                MapPhoto1To2(source.Inner, target, logger);
            }

            target.Notes.Clear();
            if (!string.IsNullOrEmpty(source.Inner.Body))
            {
                target.Notes.Add(new vCardNote(source.Inner.Body));
            }

            return(Task.FromResult(target));
        }
Exemplo n.º 13
0
 TAtypeEntity UpdateEntity(TAtypeEntity entity, IEntitySynchronizationLogger logger)
 {
     return(_environment.Mapper.Map2To1(_bEntity, entity, logger));
 }
 public string MapHtmlColorToCategoryOrNull(string htmlColor, IEntitySynchronizationLogger logger)
 {
     return(NullColorCategoryMapper.Instance.MapHtmlColorToCategoryOrNull(htmlColor, logger));
 }
 public Task <string> Map2To1(string source, string target, IEntitySynchronizationLogger logger, int context)
 {
     return(Task.FromResult(source));
 }
Exemplo n.º 16
0
        public async Task <EntityVersion <string, string> > TryUpdate(string entityId, string version, Task entityToUpdate, Func <Task, Task <Task> > entityModifier, int context, IEntitySynchronizationLogger logger)
        {
            entityToUpdate = await entityModifier(entityToUpdate);

            var updateRequest = _tasksService.Tasks.Update(entityToUpdate, _taskList.Id, entityId);

            updateRequest.ETagAction = Google.Apis.ETagAction.IfMatch;
            var result = await updateRequest.ExecuteAsync();

            return(EntityVersion.Create(result.Id, result.ETag));
        }
        private async Task MapPhoto2To1(vCard source, ContactItem target, IEntitySynchronizationLogger logger)
        {
            if (source.Photos.Count > 0)
            {
                if (target.HasPicture && _configuration.KeepOutlookPhoto)
                {
                    return;
                }

                vCardPhoto contactPhoto = source.Photos[0];

                string picturePath = Path.GetTempPath() + @"\Contact_" + target.EntryID + ".jpg";
                try
                {
                    if (!contactPhoto.IsLoaded && contactPhoto.Url != null)
                    {
                        using (var client = _webClientFactory())
                        {
                            await client.DownloadFileTaskAsync(contactPhoto.Url, picturePath);
                        }
                    }
                    else if (contactPhoto.IsLoaded)
                    {
                        File.WriteAllBytes(picturePath, contactPhoto.GetBytes());
                    }
                    else
                    {
                        s_logger.Warn("Could not load picture for contact.");
                        logger.LogWarning("Could not load picture for contact.");
                        return;
                    }

                    try
                    {
                        target.AddPicture(picturePath);
                    }
                    catch (COMException x)
                    {
                        s_logger.Warn("Could not add picture for contact.", x);
                        logger.LogWarning("Could not add picture for contact.", x);
                    }

                    File.Delete(picturePath);
                }
                catch (Exception ex)
                {
                    s_logger.Warn("Could not add picture for contact.", ex);
                    logger.LogWarning("Could not add picture for contact.", ex);
                }
            }
            else
            {
                if (target.HasPicture)
                {
                    try
                    {
                        target.RemovePicture();
                    }
                    catch (COMException x)
                    {
                        s_logger.Warn("Could not remove picture for contact.", x);
                        logger.LogWarning("Could not remove picture for contact.", x);
                    }
                }
            }
        }
 protected abstract IEnumerable<DistributionListMember> GetMembers(vCard source, DistributionListSychronizationContext context, IEntitySynchronizationLogger synchronizationLogger, ILog logger);
Exemplo n.º 19
0
 public override void AddSyncronizationJob(IJobList <TAtypeEntity, TAtypeEntityId, TAtypeEntityVersion> aJobs, IJobList <TBtypeEntity, TBtypeEntityId, TBtypeEntityVersion> bJobs, IEntitySynchronizationLogger logger)
 {
     logger.SetAId(_knownData.AtypeId);
     logger.SetBId(_knownData.BtypeId);
     bJobs.AddUpdateJob(new JobWrapper(this, logger));
 }
 protected abstract vCardMember CreateVCardMemberOrNull(GenericComObjectWrapper<Recipient> recipientWrapper, string nameWithoutEmail, DistributionListSychronizationContext context, IEntitySynchronizationLogger synchronizationLogger, ILog logger);
Exemplo n.º 21
0
 public abstract void AddSyncronizationJob(IJobList <TAtypeEntityId, TAtypeEntityVersion, TAtypeEntity> aJobs, IJobList <TBtypeEntityId, TBtypeEntityVersion, TBtypeEntity> bJobs, IEntitySynchronizationLogger logger, TContext context);
        public Task<IDistListItemWrapper> Map2To1(vCard source, IDistListItemWrapper target, IEntitySynchronizationLogger logger, DistributionListSychronizationContext context)
        {
            if (string.IsNullOrEmpty(source.FormattedName))
            {
                var name = new StringBuilder();
                name.Append(source.FamilyName);
                if (!string.IsNullOrEmpty(source.GivenName))
                {
                    if (name.Length > 0)
                        name.Append(",");
                    name.Append(source.GivenName);
                }

                if (!string.IsNullOrEmpty(source.AdditionalNames))
                {
                    if (name.Length > 0)
                        name.Append(",");
                    name.Append(source.AdditionalNames);
                }

                if (name.Length > 0)
                {
                    target.Inner.DLName = name.ToString();
                }
            }
            else
            {
                target.Inner.DLName = source.FormattedName;
            }

            target.Inner.Sensitivity = CommonEntityMapper.MapPrivacy2To1(source.AccessClassification);

            if (source.Categories.Count > 0)
            {
                string[] categories = new string[source.Categories.Count];
                source.Categories.CopyTo(categories, 0);
                target.Inner.Categories = string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator, categories);
            }
            else
            {
                target.Inner.Categories = string.Empty;
            }

            if (source.Notes.Count > 0)
            {
                target.Inner.Body = source.Notes[0].Text;
            }
            else
            {
                target.Inner.Body = string.Empty;
            }

            CommonEntityMapper.MapDistListMembers2To1(GetMembers(source, context, logger, s_logger), target, logger, context);

            return Task.FromResult(target);
        }
        public async Task <EntityVersion <WebResourceName, string> > TryUpdate(WebResourceName entityId, string version, vCard entityToUpdate, Func <vCard, Task <vCard> > entityModifier, ICardDavRepositoryLogger context, IEntitySynchronizationLogger logger)
        {
            var result = await _inner.TryUpdate(entityId, version, entityToUpdate, entityModifier, 0, logger);

            context.LogEntityExists(entityId, entityToUpdate);
            return(result);
        }
Exemplo n.º 24
0
        protected override vCardMember CreateVCardMemberOrNull(GenericComObjectWrapper <Recipient> recipientWrapper, string nameWithoutEmail, DistributionListSychronizationContext context, IEntitySynchronizationLogger synchronizationLogger, ILog logger)
        {
            var uid          = context.GetUidByEmailAddress(recipientWrapper.Inner.Address);
            var targetMember = new vCardMember();

            if (uid != null)
            {
                targetMember.Uid = uid;
            }
            else
            {
                targetMember.EmailAddress = recipientWrapper.Inner.Address;
                targetMember.DisplayName  = nameWithoutEmail;
            }
            return(targetMember);
        }
Exemplo n.º 25
0
 private void NotifyOperationFailed(IEntitySyncStateContext <TAtypeEntityId, TAtypeEntityVersion, TAtypeEntity, TBtypeEntityId, TBtypeEntityVersion, TBtypeEntity, TContext> stateContext, string errorMessage, IEntitySynchronizationLogger <TAtypeEntityId, TAtypeEntity, TBtypeEntityId, TBtypeEntity> logger)
 {
     logger.LogAbortedDueToError(errorMessage);
     stateContext.SetState(CreateFailed());
 }
Exemplo n.º 26
0
 protected override IEnumerable <DistributionListMember> GetMembers(vCard source, DistributionListSychronizationContext context, IEntitySynchronizationLogger synchronizationLogger, ILog logger)
 {
     foreach (var member in source.Members)
     {
         DistributionListMember distributionListMember;
         if (!string.IsNullOrEmpty(member.Uid))
         {
             (var contactWrapper, var emailAddress) = context.GetContactByUidOrNull(member.Uid, synchronizationLogger, logger);
             if (contactWrapper != null)
             {
                 using (contactWrapper)
                 {
                     distributionListMember = new DistributionListMember(emailAddress, contactWrapper.Inner.FullName);
                     yield return(distributionListMember);
                 }
             }
         }
         else
         {
             distributionListMember = new DistributionListMember(member.EmailAddress, member.DisplayName);
             yield return(distributionListMember);
         }
     }
 }
 async Task <TBtypeEntity> UpdateEntity(TBtypeEntity entity, IEntitySynchronizationLogger logger)
 {
     return(await _environment.Mapper.Map1To2(_aEntity, entity, logger));
 }
        public async Task <IContactItemWrapper> Map2To1(vCard source, IContactItemWrapper target, IEntitySynchronizationLogger logger, ICardDavRepositoryLogger context)
        {
            target.Inner.FirstName  = source.GivenName;
            target.Inner.LastName   = source.FamilyName;
            target.Inner.Title      = source.NamePrefix;
            target.Inner.Suffix     = source.NameSuffix;
            target.Inner.MiddleName = source.AdditionalNames;
            target.Inner.Gender     = MapGender1To2(source.Gender);

            target.Inner.AssistantName = source.Assistant;
            target.Inner.Spouse        = source.Spouse;
            target.Inner.ManagerName   = source.Manager;

            if (string.IsNullOrEmpty(target.Inner.FullName))
            {
                target.Inner.FullName = source.FormattedName;
            }
            if (!_configuration.KeepOutlookFileAs)
            {
                target.Inner.FileAs = source.FormattedName;
            }

            if (source.Nicknames.Count > 0)
            {
                string[] nickNames = new string[source.Nicknames.Count];
                source.Nicknames.CopyTo(nickNames, 0);
                target.Inner.NickName = string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator, nickNames);
            }
            else
            {
                target.Inner.NickName = string.Empty;
            }

            target.Inner.Sensitivity = CommonEntityMapper.MapPrivacy2To1(source.AccessClassification);

            if (source.Categories.Count > 0)
            {
                string[] categories = new string[source.Categories.Count];
                source.Categories.CopyTo(categories, 0);
                target.Inner.Categories = string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator, categories);
            }
            else
            {
                target.Inner.Categories = string.Empty;
            }

            MapIMs2To1(source, target.Inner);

            target.Inner.Email1Address     = string.Empty;
            target.Inner.Email1DisplayName = string.Empty;
            target.Inner.Email2Address     = string.Empty;
            target.Inner.Email2DisplayName = string.Empty;
            target.Inner.Email3Address     = string.Empty;
            target.Inner.Email3DisplayName = string.Empty;
            if (source.EmailAddresses.Count >= 1)
            {
                Func <vCardEmailAddress, bool> firstPredicate = e => _configuration.MapOutlookEmail1ToWork ? e.ItemType == ItemType.WORK : e.ItemType == ItemType.HOME;

                var first = source.EmailAddresses.FirstOrDefault(firstPredicate) ?? source.EmailAddresses.First();
                target.Inner.Email1Address = first.Address;

                var second = source.EmailAddresses.FirstOrDefault(e => _configuration.MapOutlookEmail1ToWork ? e.ItemType == ItemType.HOME : e.ItemType == ItemType.WORK && e != first) ??
                             source.EmailAddresses.FirstOrDefault(e => e != first);

                if (second != null)
                {
                    target.Inner.Email2Address = second.Address;

                    var other = source.EmailAddresses.FirstOrDefault(e => e != first && e != second);
                    if (other != null)
                    {
                        target.Inner.Email3Address = other.Address;
                    }
                }
            }

            MapPostalAdresses2To1(source, target.Inner);

            MapTelephoneNumber2To1(source, target.Inner);

            if (_configuration.MapAnniversary)
            {
                if (source.Anniversary.HasValue)
                {
                    if (!source.Anniversary.Value.Date.Equals(target.Inner.Anniversary))
                    {
                        try
                        {
                            target.Inner.Anniversary = source.Anniversary.Value;
                        }
                        catch (COMException ex)
                        {
                            s_logger.Warn("Could not update contact anniversary.", ex);
                            logger.LogWarning("Could not update contact anniversary.", ex);
                        }
                        catch (OverflowException ex)
                        {
                            s_logger.Warn("Contact anniversary has invalid value.", ex);
                            logger.LogWarning("Contact anniversary has invalid value.", ex);
                        }
                    }
                }
                else
                {
                    target.Inner.Anniversary = OutlookUtility.OUTLOOK_DATE_NONE;
                }
            }

            if (_configuration.MapBirthday)
            {
                if (source.BirthDate.HasValue)
                {
                    if (!source.BirthDate.Value.Date.Equals(target.Inner.Birthday))
                    {
                        try
                        {
                            target.Inner.Birthday = source.BirthDate.Value;
                        }
                        catch (COMException ex)
                        {
                            s_logger.Warn("Could not update contact birthday.", ex);
                            logger.LogWarning("Could not update contact birthday.", ex);
                        }
                        catch (OverflowException ex)
                        {
                            s_logger.Warn("Contact birthday has invalid value.", ex);
                            logger.LogWarning("Contact birthday has invalid value.", ex);
                        }
                    }
                }
                else
                {
                    target.Inner.Birthday = OutlookUtility.OUTLOOK_DATE_NONE;
                }
            }

            target.Inner.CompanyName = source.Organization;
            target.Inner.Department  = source.Department;

            target.Inner.JobTitle   = source.Title;
            target.Inner.Profession = source.Role;

            MapHomePage2To1(source, target.Inner);

            MapCertificate2To1(source, target.Inner, logger);

            if (_configuration.MapContactPhoto)
            {
                await MapPhoto2To1(source, target.Inner, logger);
            }

            if (source.Notes.Count > 0)
            {
                target.Inner.Body = source.Notes[0].Text;
            }
            else
            {
                target.Inner.Body = string.Empty;
            }

            return(target);
        }
 private void NotifyOperationFailed(string errorMessage, IEntitySynchronizationLogger logger)
 {
     logger.LogAbortedDueToError(errorMessage);
     SetNextStateAsFailed();
 }
        private void MapEmailAddresses1To2(ContactItem source, vCard target, IEntitySynchronizationLogger logger)
        {
            target.EmailAddresses.Clear();
            if (!string.IsNullOrEmpty(source.Email1Address))
            {
                string email1Address = string.Empty;

                if (source.Email1AddressType == "EX")
                {
                    try
                    {
                        email1Address = source.GetPropertySafe(PR_EMAIL1ADDRESS);
                    }
                    catch (COMException ex)
                    {
                        s_logger.Warn("Could not get property PR_EMAIL1ADDRESS for Email1Address", ex);
                        logger.LogWarning("Could not get property PR_EMAIL1ADDRESS for Email1Address", ex);
                    }
                }
                else
                {
                    email1Address = source.Email1Address;
                }

                if (!string.IsNullOrEmpty(email1Address))
                {
                    target.EmailAddresses.Add(new vCardEmailAddress(email1Address, vCardEmailAddressType.Internet, _configuration.MapOutlookEmail1ToWork ? ItemType.WORK : ItemType.HOME));
                }
            }

            if (!string.IsNullOrEmpty(source.Email2Address))
            {
                string email2Address = string.Empty;

                if (source.Email2AddressType == "EX")
                {
                    try
                    {
                        email2Address = source.GetPropertySafe(PR_EMAIL2ADDRESS);
                    }
                    catch (COMException ex)
                    {
                        s_logger.Warn("Could not get property PR_EMAIL2ADDRESS for Email2Address", ex);
                        logger.LogWarning("Could not get property PR_EMAIL2ADDRESS for Email2Address", ex);
                    }
                }
                else
                {
                    email2Address = source.Email2Address;
                }

                if (!string.IsNullOrEmpty(email2Address))
                {
                    target.EmailAddresses.Add(new vCardEmailAddress(email2Address, vCardEmailAddressType.Internet, _configuration.MapOutlookEmail1ToWork ? ItemType.HOME : ItemType.WORK));
                }
            }

            if (!string.IsNullOrEmpty(source.Email3Address))
            {
                string email3Address = string.Empty;

                if (source.Email3AddressType == "EX")
                {
                    try
                    {
                        email3Address = source.GetPropertySafe(PR_EMAIL3ADDRESS);
                    }
                    catch (COMException ex)
                    {
                        s_logger.Warn("Could not get property PR_EMAIL3ADDRESS for Email3Address", ex);
                        logger.LogWarning("Could not get property PR_EMAIL3ADDRESS for Email3Address", ex);
                    }
                }
                else
                {
                    email3Address = source.Email3Address;
                }

                if (!string.IsNullOrEmpty(email3Address))
                {
                    target.EmailAddresses.Add(new vCardEmailAddress(email3Address));
                }
            }
        }